diff --git a/env-llmeval/lib/python3.10/site-packages/aiohttp-3.9.4.dist-info/METADATA b/env-llmeval/lib/python3.10/site-packages/aiohttp-3.9.4.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..0ccad27c5ad3402b75ed09b0379066de26e7286e --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/aiohttp-3.9.4.dist-info/METADATA @@ -0,0 +1,245 @@ +Metadata-Version: 2.1 +Name: aiohttp +Version: 3.9.4 +Summary: Async http client/server framework (asyncio) +Home-page: https://github.com/aio-libs/aiohttp +Maintainer: aiohttp team +Maintainer-email: team@aiohttp.org +License: Apache 2 +Project-URL: Chat: Matrix, https://matrix.to/#/#aio-libs:matrix.org +Project-URL: Chat: Matrix Space, https://matrix.to/#/#aio-libs-space:matrix.org +Project-URL: CI: GitHub Actions, https://github.com/aio-libs/aiohttp/actions?query=workflow%3ACI +Project-URL: Coverage: codecov, https://codecov.io/github/aio-libs/aiohttp +Project-URL: Docs: Changelog, https://docs.aiohttp.org/en/stable/changes.html +Project-URL: Docs: RTD, https://docs.aiohttp.org +Project-URL: GitHub: issues, https://github.com/aio-libs/aiohttp/issues +Project-URL: GitHub: repo, https://github.com/aio-libs/aiohttp +Classifier: Development Status :: 5 - Production/Stable +Classifier: Framework :: AsyncIO +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Operating System :: POSIX +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Operating System :: Microsoft :: Windows +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Topic :: Internet :: WWW/HTTP +Requires-Python: >=3.8 +Description-Content-Type: text/x-rst +License-File: LICENSE.txt +Requires-Dist: aiosignal >=1.1.2 +Requires-Dist: attrs >=17.3.0 +Requires-Dist: frozenlist >=1.1.1 +Requires-Dist: multidict <7.0,>=4.5 +Requires-Dist: yarl <2.0,>=1.0 +Requires-Dist: async-timeout <5.0,>=4.0 ; python_version < "3.11" +Provides-Extra: speedups +Requires-Dist: brotlicffi ; (platform_python_implementation != "CPython") and extra == 'speedups' +Requires-Dist: Brotli ; (platform_python_implementation == "CPython") and extra == 'speedups' +Requires-Dist: aiodns ; (sys_platform == "linux" or sys_platform == "darwin") and extra == 'speedups' + +================================== +Async http client/server framework +================================== + +.. image:: https://raw.githubusercontent.com/aio-libs/aiohttp/master/docs/aiohttp-plain.svg + :height: 64px + :width: 64px + :alt: aiohttp logo + +| + +.. image:: https://github.com/aio-libs/aiohttp/workflows/CI/badge.svg + :target: https://github.com/aio-libs/aiohttp/actions?query=workflow%3ACI + :alt: GitHub Actions status for master branch + +.. image:: https://codecov.io/gh/aio-libs/aiohttp/branch/master/graph/badge.svg + :target: https://codecov.io/gh/aio-libs/aiohttp + :alt: codecov.io status for master branch + +.. image:: https://badge.fury.io/py/aiohttp.svg + :target: https://pypi.org/project/aiohttp + :alt: Latest PyPI package version + +.. image:: https://readthedocs.org/projects/aiohttp/badge/?version=latest + :target: https://docs.aiohttp.org/ + :alt: Latest Read The Docs + +.. image:: https://img.shields.io/matrix/aio-libs:matrix.org?label=Discuss%20on%20Matrix%20at%20%23aio-libs%3Amatrix.org&logo=matrix&server_fqdn=matrix.org&style=flat + :target: https://matrix.to/#/%23aio-libs:matrix.org + :alt: Matrix Room — #aio-libs:matrix.org + +.. image:: https://img.shields.io/matrix/aio-libs-space:matrix.org?label=Discuss%20on%20Matrix%20at%20%23aio-libs-space%3Amatrix.org&logo=matrix&server_fqdn=matrix.org&style=flat + :target: https://matrix.to/#/%23aio-libs-space:matrix.org + :alt: Matrix Space — #aio-libs-space:matrix.org + + +Key Features +============ + +- Supports both client and server side of HTTP protocol. +- Supports both client and server Web-Sockets out-of-the-box and avoids + Callback Hell. +- Provides Web-server with middleware and pluggable routing. + + +Getting started +=============== + +Client +------ + +To get something from the web: + +.. code-block:: python + + import aiohttp + import asyncio + + async def main(): + + async with aiohttp.ClientSession() as session: + async with session.get('http://python.org') as response: + + print("Status:", response.status) + print("Content-type:", response.headers['content-type']) + + html = await response.text() + print("Body:", html[:15], "...") + + asyncio.run(main()) + +This prints: + +.. code-block:: + + Status: 200 + Content-type: text/html; charset=utf-8 + Body: ... + +Coming from `requests `_ ? Read `why we need so many lines `_. + +Server +------ + +An example using a simple server: + +.. code-block:: python + + # examples/server_simple.py + from aiohttp import web + + async def handle(request): + name = request.match_info.get('name', "Anonymous") + text = "Hello, " + name + return web.Response(text=text) + + async def wshandle(request): + ws = web.WebSocketResponse() + await ws.prepare(request) + + async for msg in ws: + if msg.type == web.WSMsgType.text: + await ws.send_str("Hello, {}".format(msg.data)) + elif msg.type == web.WSMsgType.binary: + await ws.send_bytes(msg.data) + elif msg.type == web.WSMsgType.close: + break + + return ws + + + app = web.Application() + app.add_routes([web.get('/', handle), + web.get('/echo', wshandle), + web.get('/{name}', handle)]) + + if __name__ == '__main__': + web.run_app(app) + + +Documentation +============= + +https://aiohttp.readthedocs.io/ + + +Demos +===== + +https://github.com/aio-libs/aiohttp-demos + + +External links +============== + +* `Third party libraries + `_ +* `Built with aiohttp + `_ +* `Powered by aiohttp + `_ + +Feel free to make a Pull Request for adding your link to these pages! + + +Communication channels +====================== + +*aio-libs Discussions*: https://github.com/aio-libs/aiohttp/discussions + +*gitter chat* https://gitter.im/aio-libs/Lobby + +We support `Stack Overflow +`_. +Please add *aiohttp* tag to your question there. + +Requirements +============ + +- async-timeout_ +- attrs_ +- multidict_ +- yarl_ +- frozenlist_ + +Optionally you may install the aiodns_ library (highly recommended for sake of speed). + +.. _aiodns: https://pypi.python.org/pypi/aiodns +.. _attrs: https://github.com/python-attrs/attrs +.. _multidict: https://pypi.python.org/pypi/multidict +.. _frozenlist: https://pypi.org/project/frozenlist/ +.. _yarl: https://pypi.python.org/pypi/yarl +.. _async-timeout: https://pypi.python.org/pypi/async_timeout + +License +======= + +``aiohttp`` is offered under the Apache 2 license. + + +Keepsafe +======== + +The aiohttp community would like to thank Keepsafe +(https://www.getkeepsafe.com) for its support in the early days of +the project. + + +Source code +=========== + +The latest developer version is available in a GitHub repository: +https://github.com/aio-libs/aiohttp + +Benchmarks +========== + +If you are interested in efficiency, the AsyncIO community maintains a +list of benchmarks on the official wiki: +https://github.com/python/asyncio/wiki/Benchmarks diff --git a/env-llmeval/lib/python3.10/site-packages/aiohttp-3.9.4.dist-info/RECORD b/env-llmeval/lib/python3.10/site-packages/aiohttp-3.9.4.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..27bd079ef886162d99d4406cd50bd4558f7cf4f2 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/aiohttp-3.9.4.dist-info/RECORD @@ -0,0 +1,119 @@ +aiohttp-3.9.4.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +aiohttp-3.9.4.dist-info/LICENSE.txt,sha256=n4DQ2311WpQdtFchcsJw7L2PCCuiFd3QlZhZQu2Uqes,588 +aiohttp-3.9.4.dist-info/METADATA,sha256=64vtragOO4Zw4yBCfFzvia09h_Aqyc1LskXnwmRVedo,7459 +aiohttp-3.9.4.dist-info/RECORD,, +aiohttp-3.9.4.dist-info/WHEEL,sha256=CzQQWV-lNyM92gr3iaBk8dvO35YDHRxgzkZ-dxumUIM,152 +aiohttp-3.9.4.dist-info/top_level.txt,sha256=iv-JIaacmTl-hSho3QmphcKnbRRYx1st47yjz_178Ro,8 +aiohttp/.hash/_cparser.pxd.hash,sha256=hYa9Vje-oMs2eh_7MfCPOh2QW_1x1yCjcZuc7AmwLd0,121 +aiohttp/.hash/_find_header.pxd.hash,sha256=_mbpD6vM-CVCKq3ulUvsOAz5Wdo88wrDzfpOsMQaMNA,125 +aiohttp/.hash/_helpers.pyi.hash,sha256=Ew4BZDc2LqFwszgZZUHHrJvw5P8HBhJ700n1Ntg52hE,121 +aiohttp/.hash/_helpers.pyx.hash,sha256=5JQ6BlMBE4HnRaCGdkK9_wpL3ZSWpU1gyLYva0Wwx2c,121 +aiohttp/.hash/_http_parser.pyx.hash,sha256=4RMfISkoa9dJKvYXpa_Qe7b_32v4k7HXpaGhgXcNK4k,125 +aiohttp/.hash/_http_writer.pyx.hash,sha256=3Qg3T3D-Ud73elzPHBufK0yEu9tP5jsu6g-aPKQY9gE,125 +aiohttp/.hash/_websocket.pyx.hash,sha256=M97f-Yti-4vnE4GNTD1s_DzKs-fG_ww3jle6EUvixnE,123 +aiohttp/.hash/hdrs.py.hash,sha256=2oEszMWjYFTHoF2w4OcFCoM7osv4vY9KLLJCu9HP0xI,116 +aiohttp/__init__.py,sha256=jHB59t8RTTFUAhgySoHSKtCmKtDv7kcerMGKPavU1Wk,7762 +aiohttp/__pycache__/__init__.cpython-310.pyc,, +aiohttp/__pycache__/abc.cpython-310.pyc,, +aiohttp/__pycache__/base_protocol.cpython-310.pyc,, +aiohttp/__pycache__/client.cpython-310.pyc,, +aiohttp/__pycache__/client_exceptions.cpython-310.pyc,, +aiohttp/__pycache__/client_proto.cpython-310.pyc,, +aiohttp/__pycache__/client_reqrep.cpython-310.pyc,, +aiohttp/__pycache__/client_ws.cpython-310.pyc,, +aiohttp/__pycache__/compression_utils.cpython-310.pyc,, +aiohttp/__pycache__/connector.cpython-310.pyc,, +aiohttp/__pycache__/cookiejar.cpython-310.pyc,, +aiohttp/__pycache__/formdata.cpython-310.pyc,, +aiohttp/__pycache__/hdrs.cpython-310.pyc,, +aiohttp/__pycache__/helpers.cpython-310.pyc,, +aiohttp/__pycache__/http.cpython-310.pyc,, +aiohttp/__pycache__/http_exceptions.cpython-310.pyc,, +aiohttp/__pycache__/http_parser.cpython-310.pyc,, +aiohttp/__pycache__/http_websocket.cpython-310.pyc,, +aiohttp/__pycache__/http_writer.cpython-310.pyc,, +aiohttp/__pycache__/locks.cpython-310.pyc,, +aiohttp/__pycache__/log.cpython-310.pyc,, +aiohttp/__pycache__/multipart.cpython-310.pyc,, +aiohttp/__pycache__/payload.cpython-310.pyc,, +aiohttp/__pycache__/payload_streamer.cpython-310.pyc,, +aiohttp/__pycache__/pytest_plugin.cpython-310.pyc,, +aiohttp/__pycache__/resolver.cpython-310.pyc,, +aiohttp/__pycache__/streams.cpython-310.pyc,, +aiohttp/__pycache__/tcp_helpers.cpython-310.pyc,, +aiohttp/__pycache__/test_utils.cpython-310.pyc,, +aiohttp/__pycache__/tracing.cpython-310.pyc,, +aiohttp/__pycache__/typedefs.cpython-310.pyc,, +aiohttp/__pycache__/web.cpython-310.pyc,, +aiohttp/__pycache__/web_app.cpython-310.pyc,, +aiohttp/__pycache__/web_exceptions.cpython-310.pyc,, +aiohttp/__pycache__/web_fileresponse.cpython-310.pyc,, +aiohttp/__pycache__/web_log.cpython-310.pyc,, +aiohttp/__pycache__/web_middlewares.cpython-310.pyc,, +aiohttp/__pycache__/web_protocol.cpython-310.pyc,, +aiohttp/__pycache__/web_request.cpython-310.pyc,, +aiohttp/__pycache__/web_response.cpython-310.pyc,, +aiohttp/__pycache__/web_routedef.cpython-310.pyc,, +aiohttp/__pycache__/web_runner.cpython-310.pyc,, +aiohttp/__pycache__/web_server.cpython-310.pyc,, +aiohttp/__pycache__/web_urldispatcher.cpython-310.pyc,, +aiohttp/__pycache__/web_ws.cpython-310.pyc,, +aiohttp/__pycache__/worker.cpython-310.pyc,, +aiohttp/_cparser.pxd,sha256=8jGIg-VJ9p3llwCakUYDsPGxA4HiZe9dmK9Jmtlz-5g,4318 +aiohttp/_find_header.pxd,sha256=0GfwFCPN2zxEKTO1_MA5sYq2UfzsG8kcV3aTqvwlz3g,68 +aiohttp/_headers.pxi,sha256=n701k28dVPjwRnx5j6LpJhLTfj7dqu2vJt7f0O60Oyg,2007 +aiohttp/_helpers.cpython-310-x86_64-linux-gnu.so,sha256=KZA_we6lVYYLcxtV5fNq7f72xOwd6kqp5YzJEJT9wMI,508784 +aiohttp/_helpers.pyi,sha256=ZoKiJSS51PxELhI2cmIr5737YjjZcJt7FbIRO3ym1Ss,202 +aiohttp/_helpers.pyx,sha256=XeLbNft5X_4ifi8QB8i6TyrRuayijMSO3IDHeSA89uM,1049 +aiohttp/_http_parser.cpython-310-x86_64-linux-gnu.so,sha256=6BvwDWVHOAaETC4YAOd8I9YqEYJVq3yEjGYZtETeSm4,2586576 +aiohttp/_http_parser.pyx,sha256=q68Rq06MpW-QwLxriE3hIJmWIKc4lVFaWHU3clsHd4Y,28125 +aiohttp/_http_writer.cpython-310-x86_64-linux-gnu.so,sha256=llvQZrZI6yQIHp0lP-dgdlOWnLIIPLLWNhgEi9RsDI0,459368 +aiohttp/_http_writer.pyx,sha256=aIHAp8g4ZV5kbGRdmZce-vXjELw2M6fGKyJuOdgYQqw,4575 +aiohttp/_websocket.cpython-310-x86_64-linux-gnu.so,sha256=xO73eZVpxho_Omoz3Bh9muMnRL-7qPGEL5BTAyOTEeQ,234032 +aiohttp/_websocket.pyx,sha256=1XuOSNDCbyDrzF5uMA2isqausSs8l2jWTLDlNDLM9Io,1561 +aiohttp/abc.py,sha256=WGZ5HH0hoCH77qaISTb689ygpS9CxfKkgUCOcgjU2lo,5500 +aiohttp/base_protocol.py,sha256=HJ5SxzbzYewj-sjoKMbD6i5rDYEv9Zo7Q_cyV3Wvn6o,2876 +aiohttp/client.py,sha256=2EKZE0lcIMLjjaMZChAu_2GaSNj8TumqhhwgEEmpN6Q,47276 +aiohttp/client_exceptions.py,sha256=7lx_YWAauUQVOxg_RehW9HZE344ak3lGmVJHfCrmb-A,9411 +aiohttp/client_proto.py,sha256=kCRlCOYxiuUv83cHz-gDYF0bK4Ye_KgkhYibjqTpN_M,9910 +aiohttp/client_reqrep.py,sha256=bt5woKRdhImzsEqg39a-O0yqswY8adguODtE-ui2RxE,40075 +aiohttp/client_ws.py,sha256=nNrwu1wA0U3B0cNsVr61QfV2S60bbKfaZXHfW7klFl4,11010 +aiohttp/compression_utils.py,sha256=GCkBNJqrybMhiTQGwqqhORnaTLpRFZD_-UvRtnZ5lEQ,5015 +aiohttp/connector.py,sha256=meq8urjMWelJnG26VgkA3ibrIioaEWqujg3jjNAKG28,53796 +aiohttp/cookiejar.py,sha256=PdvsOiDasDYYUOPaaAfuuFJzR4CJyHHjut02YiZ_N8M,14015 +aiohttp/formdata.py,sha256=WjHA1mieKlWwI5O3hi3-siqN0dWz_X04oXNNZje2z7Q,6521 +aiohttp/hdrs.py,sha256=uzn5agn_jXid2h-ky6Y0ZAQ8BrPeTGLDGr-weiMctso,4613 +aiohttp/helpers.py,sha256=EAZ1V0pGfv2xRiWfhjubBqgLBI0aK-CXlUlYss3EYzo,30988 +aiohttp/http.py,sha256=8o8j8xH70OWjnfTWA9V44NR785QPxEPrUtzMXiAVpwc,1842 +aiohttp/http_exceptions.py,sha256=7LOFFUwq04fZsnZA-NP5nukd6c2i8daM8-ejj3ndbSQ,2716 +aiohttp/http_parser.py,sha256=zuG3C-WOUVjoNTqgsrdCorzCGoXbR0gHhma3G___zOA,36507 +aiohttp/http_websocket.py,sha256=9Kfp5e4TU1JJfEvJ7l1Kt6Cr2HZX3z_RIojN8BAriPI,26732 +aiohttp/http_writer.py,sha256=fxpyRj_S3WcBl9fxxF05t8YYAUA-0jW5b_PjVSluT3Y,5933 +aiohttp/locks.py,sha256=wRYFo1U82LwBBdqwU24JEPaoTAlKaaJd2FtfDKhkTb4,1136 +aiohttp/log.py,sha256=BbNKx9e3VMIm0xYjZI0IcBBoS7wjdeIeSaiJE7-qK2g,325 +aiohttp/multipart.py,sha256=UV6IYPZWgiwhK-DzDtvXd_FDdAL1yMv9xjkm52FR3R8,34561 +aiohttp/payload.py,sha256=xK04Z-TSao-qiYVMnphKG9-6yOvoqGsZBM7egUS4n9A,13542 +aiohttp/payload_streamer.py,sha256=eAS8S-UWfLkEMavRjP2Uu9amC3PnbV79wHTNDoRmYn8,2087 +aiohttp/py.typed,sha256=sow9soTwP9T_gEAQSVh7Gb8855h04Nwmhs2We-JRgZM,7 +aiohttp/pytest_plugin.py,sha256=3IwpuxtFiUVFGS_ZitWuqvECSGgXQWvCW312B2TaVLY,11605 +aiohttp/resolver.py,sha256=8peXjB482v0hg1ESn87op6f-UeLXk_fAMxQo_23Ek6M,5070 +aiohttp/streams.py,sha256=LWlr0gE44cjKzBU9I15vWwlorPW8ZAU-M2Sgz_UdjWM,21128 +aiohttp/tcp_helpers.py,sha256=BSadqVWaBpMFDRWnhaaR941N9MiDZ7bdTrxgCb0CW-M,961 +aiohttp/test_utils.py,sha256=8-McpBCAzFbA17yeEW9UYVKBypu-Hm_407ppQy76XWU,20475 +aiohttp/tracing.py,sha256=W94gFgxFtXSBWMU4ajbrOH61mJ4mElRmfyxNUw6FwIA,15132 +aiohttp/typedefs.py,sha256=f-EzBBgQAxNLiTUtkjgMAL5LQt81HloYTesxnhNM03U,1471 +aiohttp/web.py,sha256=HFTQaoYVK5pM3YmxNJtZl9fGrRIdFs_Nhloxe7_lJj0,19263 +aiohttp/web_app.py,sha256=4cXDqZV-KR0xMnUhQ471bsEACIsoI4_BkDJ3haXyG_I,18311 +aiohttp/web_exceptions.py,sha256=7nIuiwhZ39vJJ9KrWqArA5QcWbUdqkz2CLwEpJapeN8,10360 +aiohttp/web_fileresponse.py,sha256=33VS-6CQd4ZiezNBVZaVxWBCLuOUK_vPMNTU1ojiV80,11569 +aiohttp/web_log.py,sha256=DOfOxGyh2U7K5K_w6O7ILdfGcs4qOdzHxOwj2-k3c6c,7801 +aiohttp/web_middlewares.py,sha256=q6i0GGiVvUlpGtsbZmp88-zFIKQHwYtDd5SpBvKFdEY,4032 +aiohttp/web_protocol.py,sha256=8kAxmDpRYczyCFtUS4vDEIORgbD4WV0CTjVi-fZVykE,23060 +aiohttp/web_request.py,sha256=UyDR4JQwogyX12FS8PpMl-1d6ZG-TE02Bt2nPOEk0HI,28986 +aiohttp/web_response.py,sha256=3jfYnRpsNnxGRUAm-VNGu18Ekw5XyuYp7c7fzbOwbqY,27858 +aiohttp/web_routedef.py,sha256=Y5DPVa7D1uJp37HP6YXrO8Cd1BrEtDyS-fljOUdPk30,6132 +aiohttp/web_runner.py,sha256=rGI6zeIXZNDepvJajc8ZXue9hn0O2wSmh8S7CuXhkUI,11951 +aiohttp/web_server.py,sha256=5P-9uPCoPEDkK9ILbvEXmkkJWPhnTxBzdwAXwveyyDk,2587 +aiohttp/web_urldispatcher.py,sha256=e9QueGUecnOZq44CpfKJCjWi_IXHqHADUmIh_mzli18,40132 +aiohttp/web_ws.py,sha256=eiLuPZnB6HFXagcdZzU9jD9aKXP3K6YNDXDIoOpN8co,18960 +aiohttp/worker.py,sha256=bkozEd2rAzQS0qs4knnnplOmaZ4TNdYtqWXSXx9djEc,7965 diff --git a/env-llmeval/lib/python3.10/site-packages/aiohttp-3.9.4.dist-info/WHEEL b/env-llmeval/lib/python3.10/site-packages/aiohttp-3.9.4.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..9bb86cf30c63df9170e9af3dd246ce6f41270402 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/aiohttp-3.9.4.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.43.0) +Root-Is-Purelib: false +Tag: cp310-cp310-manylinux_2_17_x86_64 +Tag: cp310-cp310-manylinux2014_x86_64 + diff --git a/env-llmeval/lib/python3.10/site-packages/aiohttp-3.9.4.dist-info/top_level.txt b/env-llmeval/lib/python3.10/site-packages/aiohttp-3.9.4.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..ee4ba4f3d739e094878215c84eb41ba85c80e4a8 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/aiohttp-3.9.4.dist-info/top_level.txt @@ -0,0 +1 @@ +aiohttp diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/__init__.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..db124d36d239f7855cb7a65dbe6830a395c51191 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/__init__.py @@ -0,0 +1,884 @@ +# Copyright 2020 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# *********** +# `huggingface_hub` init has 2 modes: +# - Normal usage: +# If imported to use it, all modules and functions are lazy-loaded. This means +# they exist at top level in module but are imported only the first time they are +# used. This way, `from huggingface_hub import something` will import `something` +# quickly without the hassle of importing all the features from `huggingface_hub`. +# - Static check: +# If statically analyzed, all modules and functions are loaded normally. This way +# static typing check works properly as well as autocomplete in text editors and +# IDEs. +# +# The static model imports are done inside the `if TYPE_CHECKING:` statement at +# the bottom of this file. Since module/functions imports are duplicated, it is +# mandatory to make sure to add them twice when adding one. This is checked in the +# `make quality` command. +# +# To update the static imports, please run the following command and commit the changes. +# ``` +# # Use script +# python utils/check_static_imports.py --update-file +# +# # Or run style on codebase +# make style +# ``` +# +# *********** +# Lazy loader vendored from https://github.com/scientific-python/lazy_loader +import importlib +import os +import sys +from typing import TYPE_CHECKING + + +__version__ = "0.22.2" + +# Alphabetical order of definitions is ensured in tests +# WARNING: any comment added in this dictionary definition will be lost when +# re-generating the file ! +_SUBMOD_ATTRS = { + "_commit_scheduler": [ + "CommitScheduler", + ], + "_inference_endpoints": [ + "InferenceEndpoint", + "InferenceEndpointError", + "InferenceEndpointStatus", + "InferenceEndpointTimeoutError", + "InferenceEndpointType", + ], + "_login": [ + "interpreter_login", + "login", + "logout", + "notebook_login", + ], + "_multi_commits": [ + "MultiCommitException", + "plan_multi_commits", + ], + "_snapshot_download": [ + "snapshot_download", + ], + "_space_api": [ + "SpaceHardware", + "SpaceRuntime", + "SpaceStage", + "SpaceStorage", + "SpaceVariable", + ], + "_tensorboard_logger": [ + "HFSummaryWriter", + ], + "_webhooks_payload": [ + "WebhookPayload", + "WebhookPayloadComment", + "WebhookPayloadDiscussion", + "WebhookPayloadDiscussionChanges", + "WebhookPayloadEvent", + "WebhookPayloadMovedTo", + "WebhookPayloadRepo", + "WebhookPayloadUrl", + "WebhookPayloadWebhook", + ], + "_webhooks_server": [ + "WebhooksServer", + "webhook_endpoint", + ], + "community": [ + "Discussion", + "DiscussionComment", + "DiscussionCommit", + "DiscussionEvent", + "DiscussionStatusChange", + "DiscussionTitleChange", + "DiscussionWithDetails", + ], + "constants": [ + "CONFIG_NAME", + "FLAX_WEIGHTS_NAME", + "HUGGINGFACE_CO_URL_HOME", + "HUGGINGFACE_CO_URL_TEMPLATE", + "PYTORCH_WEIGHTS_NAME", + "REPO_TYPE_DATASET", + "REPO_TYPE_MODEL", + "REPO_TYPE_SPACE", + "TF2_WEIGHTS_NAME", + "TF_WEIGHTS_NAME", + ], + "fastai_utils": [ + "_save_pretrained_fastai", + "from_pretrained_fastai", + "push_to_hub_fastai", + ], + "file_download": [ + "HfFileMetadata", + "_CACHED_NO_EXIST", + "cached_download", + "get_hf_file_metadata", + "hf_hub_download", + "hf_hub_url", + "try_to_load_from_cache", + ], + "hf_api": [ + "Collection", + "CollectionItem", + "CommitInfo", + "CommitOperation", + "CommitOperationAdd", + "CommitOperationCopy", + "CommitOperationDelete", + "GitCommitInfo", + "GitRefInfo", + "GitRefs", + "HfApi", + "RepoUrl", + "User", + "UserLikes", + "accept_access_request", + "add_collection_item", + "add_space_secret", + "add_space_variable", + "cancel_access_request", + "change_discussion_status", + "comment_discussion", + "create_branch", + "create_collection", + "create_commit", + "create_commits_on_pr", + "create_discussion", + "create_inference_endpoint", + "create_pull_request", + "create_repo", + "create_tag", + "dataset_info", + "delete_branch", + "delete_collection", + "delete_collection_item", + "delete_file", + "delete_folder", + "delete_inference_endpoint", + "delete_repo", + "delete_space_secret", + "delete_space_storage", + "delete_space_variable", + "delete_tag", + "duplicate_space", + "edit_discussion_comment", + "file_exists", + "get_collection", + "get_dataset_tags", + "get_discussion_details", + "get_full_repo_name", + "get_inference_endpoint", + "get_model_tags", + "get_paths_info", + "get_repo_discussions", + "get_safetensors_metadata", + "get_space_runtime", + "get_space_variables", + "get_token_permission", + "grant_access", + "like", + "list_accepted_access_requests", + "list_collections", + "list_datasets", + "list_files_info", + "list_inference_endpoints", + "list_liked_repos", + "list_metrics", + "list_models", + "list_pending_access_requests", + "list_rejected_access_requests", + "list_repo_commits", + "list_repo_files", + "list_repo_likers", + "list_repo_refs", + "list_repo_tree", + "list_spaces", + "merge_pull_request", + "model_info", + "move_repo", + "parse_safetensors_file_metadata", + "pause_inference_endpoint", + "pause_space", + "preupload_lfs_files", + "reject_access_request", + "rename_discussion", + "repo_exists", + "repo_info", + "repo_type_and_id_from_hf_id", + "request_space_hardware", + "request_space_storage", + "restart_space", + "resume_inference_endpoint", + "revision_exists", + "run_as_future", + "scale_to_zero_inference_endpoint", + "set_space_sleep_time", + "space_info", + "super_squash_history", + "unlike", + "update_collection_item", + "update_collection_metadata", + "update_inference_endpoint", + "update_repo_visibility", + "upload_file", + "upload_folder", + "whoami", + ], + "hf_file_system": [ + "HfFileSystem", + "HfFileSystemFile", + "HfFileSystemResolvedPath", + "HfFileSystemStreamFile", + ], + "hub_mixin": [ + "ModelHubMixin", + "PyTorchModelHubMixin", + ], + "inference._client": [ + "InferenceClient", + "InferenceTimeoutError", + ], + "inference._generated._async_client": [ + "AsyncInferenceClient", + ], + "inference._generated.types": [ + "AudioClassificationInput", + "AudioClassificationOutputElement", + "AudioClassificationParameters", + "AudioToAudioInput", + "AudioToAudioOutputElement", + "AutomaticSpeechRecognitionGenerationParameters", + "AutomaticSpeechRecognitionInput", + "AutomaticSpeechRecognitionOutput", + "AutomaticSpeechRecognitionOutputChunk", + "AutomaticSpeechRecognitionParameters", + "ChatCompletionInput", + "ChatCompletionInputMessage", + "ChatCompletionOutput", + "ChatCompletionOutputChoice", + "ChatCompletionOutputChoiceMessage", + "ChatCompletionStreamOutput", + "ChatCompletionStreamOutputChoice", + "ChatCompletionStreamOutputDelta", + "DepthEstimationInput", + "DepthEstimationOutput", + "DocumentQuestionAnsweringInput", + "DocumentQuestionAnsweringInputData", + "DocumentQuestionAnsweringOutputElement", + "DocumentQuestionAnsweringParameters", + "FeatureExtractionInput", + "FillMaskInput", + "FillMaskOutputElement", + "FillMaskParameters", + "ImageClassificationInput", + "ImageClassificationOutputElement", + "ImageClassificationParameters", + "ImageSegmentationInput", + "ImageSegmentationOutputElement", + "ImageSegmentationParameters", + "ImageToImageInput", + "ImageToImageOutput", + "ImageToImageParameters", + "ImageToImageTargetSize", + "ImageToTextGenerationParameters", + "ImageToTextInput", + "ImageToTextOutput", + "ImageToTextParameters", + "ObjectDetectionBoundingBox", + "ObjectDetectionInput", + "ObjectDetectionOutputElement", + "ObjectDetectionParameters", + "QuestionAnsweringInput", + "QuestionAnsweringInputData", + "QuestionAnsweringOutputElement", + "QuestionAnsweringParameters", + "SentenceSimilarityInput", + "SentenceSimilarityInputData", + "SummarizationGenerationParameters", + "SummarizationInput", + "SummarizationOutput", + "TableQuestionAnsweringInput", + "TableQuestionAnsweringInputData", + "TableQuestionAnsweringOutputElement", + "Text2TextGenerationInput", + "Text2TextGenerationOutput", + "Text2TextGenerationParameters", + "TextClassificationInput", + "TextClassificationOutputElement", + "TextClassificationParameters", + "TextGenerationInput", + "TextGenerationOutput", + "TextGenerationOutputDetails", + "TextGenerationOutputSequenceDetails", + "TextGenerationOutputToken", + "TextGenerationParameters", + "TextGenerationPrefillToken", + "TextGenerationStreamDetails", + "TextGenerationStreamOutput", + "TextToAudioGenerationParameters", + "TextToAudioInput", + "TextToAudioOutput", + "TextToAudioParameters", + "TextToImageInput", + "TextToImageOutput", + "TextToImageParameters", + "TextToImageTargetSize", + "TokenClassificationInput", + "TokenClassificationOutputElement", + "TokenClassificationParameters", + "TranslationGenerationParameters", + "TranslationInput", + "TranslationOutput", + "VideoClassificationInput", + "VideoClassificationOutputElement", + "VideoClassificationParameters", + "VisualQuestionAnsweringInput", + "VisualQuestionAnsweringInputData", + "VisualQuestionAnsweringOutputElement", + "VisualQuestionAnsweringParameters", + "ZeroShotClassificationInput", + "ZeroShotClassificationInputData", + "ZeroShotClassificationOutputElement", + "ZeroShotClassificationParameters", + "ZeroShotImageClassificationInput", + "ZeroShotImageClassificationInputData", + "ZeroShotImageClassificationOutputElement", + "ZeroShotImageClassificationParameters", + "ZeroShotObjectDetectionBoundingBox", + "ZeroShotObjectDetectionInput", + "ZeroShotObjectDetectionInputData", + "ZeroShotObjectDetectionOutputElement", + ], + "inference_api": [ + "InferenceApi", + ], + "keras_mixin": [ + "KerasModelHubMixin", + "from_pretrained_keras", + "push_to_hub_keras", + "save_pretrained_keras", + ], + "repocard": [ + "DatasetCard", + "ModelCard", + "RepoCard", + "SpaceCard", + "metadata_eval_result", + "metadata_load", + "metadata_save", + "metadata_update", + ], + "repocard_data": [ + "CardData", + "DatasetCardData", + "EvalResult", + "ModelCardData", + "SpaceCardData", + ], + "repository": [ + "Repository", + ], + "serialization": [ + "StateDictSplit", + "split_numpy_state_dict_into_shards", + "split_state_dict_into_shards_factory", + "split_tf_state_dict_into_shards", + "split_torch_state_dict_into_shards", + ], + "utils": [ + "CacheNotFound", + "CachedFileInfo", + "CachedRepoInfo", + "CachedRevisionInfo", + "CorruptedCacheException", + "DeleteCacheStrategy", + "HFCacheInfo", + "HfFolder", + "cached_assets_path", + "configure_http_backend", + "dump_environment_info", + "get_session", + "get_token", + "logging", + "scan_cache_dir", + ], + "utils.endpoint_helpers": [ + "DatasetFilter", + "ModelFilter", + ], +} + + +def _attach(package_name, submodules=None, submod_attrs=None): + """Attach lazily loaded submodules, functions, or other attributes. + + Typically, modules import submodules and attributes as follows: + + ```py + import mysubmodule + import anothersubmodule + + from .foo import someattr + ``` + + The idea is to replace a package's `__getattr__`, `__dir__`, and + `__all__`, such that all imports work exactly the way they would + with normal imports, except that the import occurs upon first use. + + The typical way to call this function, replacing the above imports, is: + + ```python + __getattr__, __dir__, __all__ = lazy.attach( + __name__, + ['mysubmodule', 'anothersubmodule'], + {'foo': ['someattr']} + ) + ``` + This functionality requires Python 3.7 or higher. + + Args: + package_name (`str`): + Typically use `__name__`. + submodules (`set`): + List of submodules to attach. + submod_attrs (`dict`): + Dictionary of submodule -> list of attributes / functions. + These attributes are imported as they are used. + + Returns: + __getattr__, __dir__, __all__ + + """ + if submod_attrs is None: + submod_attrs = {} + + if submodules is None: + submodules = set() + else: + submodules = set(submodules) + + attr_to_modules = {attr: mod for mod, attrs in submod_attrs.items() for attr in attrs} + + __all__ = list(submodules | attr_to_modules.keys()) + + def __getattr__(name): + if name in submodules: + return importlib.import_module(f"{package_name}.{name}") + elif name in attr_to_modules: + submod_path = f"{package_name}.{attr_to_modules[name]}" + submod = importlib.import_module(submod_path) + attr = getattr(submod, name) + + # If the attribute lives in a file (module) with the same + # name as the attribute, ensure that the attribute and *not* + # the module is accessible on the package. + if name == attr_to_modules[name]: + pkg = sys.modules[package_name] + pkg.__dict__[name] = attr + + return attr + else: + raise AttributeError(f"No {package_name} attribute {name}") + + def __dir__(): + return __all__ + + if os.environ.get("EAGER_IMPORT", ""): + for attr in set(attr_to_modules.keys()) | submodules: + __getattr__(attr) + + return __getattr__, __dir__, list(__all__) + + +__getattr__, __dir__, __all__ = _attach(__name__, submodules=[], submod_attrs=_SUBMOD_ATTRS) + +# WARNING: any content below this statement is generated automatically. Any manual edit +# will be lost when re-generating this file ! +# +# To update the static imports, please run the following command and commit the changes. +# ``` +# # Use script +# python utils/check_static_imports.py --update-file +# +# # Or run style on codebase +# make style +# ``` +if TYPE_CHECKING: # pragma: no cover + from ._commit_scheduler import CommitScheduler # noqa: F401 + from ._inference_endpoints import ( + InferenceEndpoint, # noqa: F401 + InferenceEndpointError, # noqa: F401 + InferenceEndpointStatus, # noqa: F401 + InferenceEndpointTimeoutError, # noqa: F401 + InferenceEndpointType, # noqa: F401 + ) + from ._login import ( + interpreter_login, # noqa: F401 + login, # noqa: F401 + logout, # noqa: F401 + notebook_login, # noqa: F401 + ) + from ._multi_commits import ( + MultiCommitException, # noqa: F401 + plan_multi_commits, # noqa: F401 + ) + from ._snapshot_download import snapshot_download # noqa: F401 + from ._space_api import ( + SpaceHardware, # noqa: F401 + SpaceRuntime, # noqa: F401 + SpaceStage, # noqa: F401 + SpaceStorage, # noqa: F401 + SpaceVariable, # noqa: F401 + ) + from ._tensorboard_logger import HFSummaryWriter # noqa: F401 + from ._webhooks_payload import ( + WebhookPayload, # noqa: F401 + WebhookPayloadComment, # noqa: F401 + WebhookPayloadDiscussion, # noqa: F401 + WebhookPayloadDiscussionChanges, # noqa: F401 + WebhookPayloadEvent, # noqa: F401 + WebhookPayloadMovedTo, # noqa: F401 + WebhookPayloadRepo, # noqa: F401 + WebhookPayloadUrl, # noqa: F401 + WebhookPayloadWebhook, # noqa: F401 + ) + from ._webhooks_server import ( + WebhooksServer, # noqa: F401 + webhook_endpoint, # noqa: F401 + ) + from .community import ( + Discussion, # noqa: F401 + DiscussionComment, # noqa: F401 + DiscussionCommit, # noqa: F401 + DiscussionEvent, # noqa: F401 + DiscussionStatusChange, # noqa: F401 + DiscussionTitleChange, # noqa: F401 + DiscussionWithDetails, # noqa: F401 + ) + from .constants import ( + CONFIG_NAME, # noqa: F401 + FLAX_WEIGHTS_NAME, # noqa: F401 + HUGGINGFACE_CO_URL_HOME, # noqa: F401 + HUGGINGFACE_CO_URL_TEMPLATE, # noqa: F401 + PYTORCH_WEIGHTS_NAME, # noqa: F401 + REPO_TYPE_DATASET, # noqa: F401 + REPO_TYPE_MODEL, # noqa: F401 + REPO_TYPE_SPACE, # noqa: F401 + TF2_WEIGHTS_NAME, # noqa: F401 + TF_WEIGHTS_NAME, # noqa: F401 + ) + from .fastai_utils import ( + _save_pretrained_fastai, # noqa: F401 + from_pretrained_fastai, # noqa: F401 + push_to_hub_fastai, # noqa: F401 + ) + from .file_download import ( + _CACHED_NO_EXIST, # noqa: F401 + HfFileMetadata, # noqa: F401 + cached_download, # noqa: F401 + get_hf_file_metadata, # noqa: F401 + hf_hub_download, # noqa: F401 + hf_hub_url, # noqa: F401 + try_to_load_from_cache, # noqa: F401 + ) + from .hf_api import ( + Collection, # noqa: F401 + CollectionItem, # noqa: F401 + CommitInfo, # noqa: F401 + CommitOperation, # noqa: F401 + CommitOperationAdd, # noqa: F401 + CommitOperationCopy, # noqa: F401 + CommitOperationDelete, # noqa: F401 + GitCommitInfo, # noqa: F401 + GitRefInfo, # noqa: F401 + GitRefs, # noqa: F401 + HfApi, # noqa: F401 + RepoUrl, # noqa: F401 + User, # noqa: F401 + UserLikes, # noqa: F401 + accept_access_request, # noqa: F401 + add_collection_item, # noqa: F401 + add_space_secret, # noqa: F401 + add_space_variable, # noqa: F401 + cancel_access_request, # noqa: F401 + change_discussion_status, # noqa: F401 + comment_discussion, # noqa: F401 + create_branch, # noqa: F401 + create_collection, # noqa: F401 + create_commit, # noqa: F401 + create_commits_on_pr, # noqa: F401 + create_discussion, # noqa: F401 + create_inference_endpoint, # noqa: F401 + create_pull_request, # noqa: F401 + create_repo, # noqa: F401 + create_tag, # noqa: F401 + dataset_info, # noqa: F401 + delete_branch, # noqa: F401 + delete_collection, # noqa: F401 + delete_collection_item, # noqa: F401 + delete_file, # noqa: F401 + delete_folder, # noqa: F401 + delete_inference_endpoint, # noqa: F401 + delete_repo, # noqa: F401 + delete_space_secret, # noqa: F401 + delete_space_storage, # noqa: F401 + delete_space_variable, # noqa: F401 + delete_tag, # noqa: F401 + duplicate_space, # noqa: F401 + edit_discussion_comment, # noqa: F401 + file_exists, # noqa: F401 + get_collection, # noqa: F401 + get_dataset_tags, # noqa: F401 + get_discussion_details, # noqa: F401 + get_full_repo_name, # noqa: F401 + get_inference_endpoint, # noqa: F401 + get_model_tags, # noqa: F401 + get_paths_info, # noqa: F401 + get_repo_discussions, # noqa: F401 + get_safetensors_metadata, # noqa: F401 + get_space_runtime, # noqa: F401 + get_space_variables, # noqa: F401 + get_token_permission, # noqa: F401 + grant_access, # noqa: F401 + like, # noqa: F401 + list_accepted_access_requests, # noqa: F401 + list_collections, # noqa: F401 + list_datasets, # noqa: F401 + list_files_info, # noqa: F401 + list_inference_endpoints, # noqa: F401 + list_liked_repos, # noqa: F401 + list_metrics, # noqa: F401 + list_models, # noqa: F401 + list_pending_access_requests, # noqa: F401 + list_rejected_access_requests, # noqa: F401 + list_repo_commits, # noqa: F401 + list_repo_files, # noqa: F401 + list_repo_likers, # noqa: F401 + list_repo_refs, # noqa: F401 + list_repo_tree, # noqa: F401 + list_spaces, # noqa: F401 + merge_pull_request, # noqa: F401 + model_info, # noqa: F401 + move_repo, # noqa: F401 + parse_safetensors_file_metadata, # noqa: F401 + pause_inference_endpoint, # noqa: F401 + pause_space, # noqa: F401 + preupload_lfs_files, # noqa: F401 + reject_access_request, # noqa: F401 + rename_discussion, # noqa: F401 + repo_exists, # noqa: F401 + repo_info, # noqa: F401 + repo_type_and_id_from_hf_id, # noqa: F401 + request_space_hardware, # noqa: F401 + request_space_storage, # noqa: F401 + restart_space, # noqa: F401 + resume_inference_endpoint, # noqa: F401 + revision_exists, # noqa: F401 + run_as_future, # noqa: F401 + scale_to_zero_inference_endpoint, # noqa: F401 + set_space_sleep_time, # noqa: F401 + space_info, # noqa: F401 + super_squash_history, # noqa: F401 + unlike, # noqa: F401 + update_collection_item, # noqa: F401 + update_collection_metadata, # noqa: F401 + update_inference_endpoint, # noqa: F401 + update_repo_visibility, # noqa: F401 + upload_file, # noqa: F401 + upload_folder, # noqa: F401 + whoami, # noqa: F401 + ) + from .hf_file_system import ( + HfFileSystem, # noqa: F401 + HfFileSystemFile, # noqa: F401 + HfFileSystemResolvedPath, # noqa: F401 + HfFileSystemStreamFile, # noqa: F401 + ) + from .hub_mixin import ( + ModelHubMixin, # noqa: F401 + PyTorchModelHubMixin, # noqa: F401 + ) + from .inference._client import ( + InferenceClient, # noqa: F401 + InferenceTimeoutError, # noqa: F401 + ) + from .inference._generated._async_client import AsyncInferenceClient # noqa: F401 + from .inference._generated.types import ( + AudioClassificationInput, # noqa: F401 + AudioClassificationOutputElement, # noqa: F401 + AudioClassificationParameters, # noqa: F401 + AudioToAudioInput, # noqa: F401 + AudioToAudioOutputElement, # noqa: F401 + AutomaticSpeechRecognitionGenerationParameters, # noqa: F401 + AutomaticSpeechRecognitionInput, # noqa: F401 + AutomaticSpeechRecognitionOutput, # noqa: F401 + AutomaticSpeechRecognitionOutputChunk, # noqa: F401 + AutomaticSpeechRecognitionParameters, # noqa: F401 + ChatCompletionInput, # noqa: F401 + ChatCompletionInputMessage, # noqa: F401 + ChatCompletionOutput, # noqa: F401 + ChatCompletionOutputChoice, # noqa: F401 + ChatCompletionOutputChoiceMessage, # noqa: F401 + ChatCompletionStreamOutput, # noqa: F401 + ChatCompletionStreamOutputChoice, # noqa: F401 + ChatCompletionStreamOutputDelta, # noqa: F401 + DepthEstimationInput, # noqa: F401 + DepthEstimationOutput, # noqa: F401 + DocumentQuestionAnsweringInput, # noqa: F401 + DocumentQuestionAnsweringInputData, # noqa: F401 + DocumentQuestionAnsweringOutputElement, # noqa: F401 + DocumentQuestionAnsweringParameters, # noqa: F401 + FeatureExtractionInput, # noqa: F401 + FillMaskInput, # noqa: F401 + FillMaskOutputElement, # noqa: F401 + FillMaskParameters, # noqa: F401 + ImageClassificationInput, # noqa: F401 + ImageClassificationOutputElement, # noqa: F401 + ImageClassificationParameters, # noqa: F401 + ImageSegmentationInput, # noqa: F401 + ImageSegmentationOutputElement, # noqa: F401 + ImageSegmentationParameters, # noqa: F401 + ImageToImageInput, # noqa: F401 + ImageToImageOutput, # noqa: F401 + ImageToImageParameters, # noqa: F401 + ImageToImageTargetSize, # noqa: F401 + ImageToTextGenerationParameters, # noqa: F401 + ImageToTextInput, # noqa: F401 + ImageToTextOutput, # noqa: F401 + ImageToTextParameters, # noqa: F401 + ObjectDetectionBoundingBox, # noqa: F401 + ObjectDetectionInput, # noqa: F401 + ObjectDetectionOutputElement, # noqa: F401 + ObjectDetectionParameters, # noqa: F401 + QuestionAnsweringInput, # noqa: F401 + QuestionAnsweringInputData, # noqa: F401 + QuestionAnsweringOutputElement, # noqa: F401 + QuestionAnsweringParameters, # noqa: F401 + SentenceSimilarityInput, # noqa: F401 + SentenceSimilarityInputData, # noqa: F401 + SummarizationGenerationParameters, # noqa: F401 + SummarizationInput, # noqa: F401 + SummarizationOutput, # noqa: F401 + TableQuestionAnsweringInput, # noqa: F401 + TableQuestionAnsweringInputData, # noqa: F401 + TableQuestionAnsweringOutputElement, # noqa: F401 + Text2TextGenerationInput, # noqa: F401 + Text2TextGenerationOutput, # noqa: F401 + Text2TextGenerationParameters, # noqa: F401 + TextClassificationInput, # noqa: F401 + TextClassificationOutputElement, # noqa: F401 + TextClassificationParameters, # noqa: F401 + TextGenerationInput, # noqa: F401 + TextGenerationOutput, # noqa: F401 + TextGenerationOutputDetails, # noqa: F401 + TextGenerationOutputSequenceDetails, # noqa: F401 + TextGenerationOutputToken, # noqa: F401 + TextGenerationParameters, # noqa: F401 + TextGenerationPrefillToken, # noqa: F401 + TextGenerationStreamDetails, # noqa: F401 + TextGenerationStreamOutput, # noqa: F401 + TextToAudioGenerationParameters, # noqa: F401 + TextToAudioInput, # noqa: F401 + TextToAudioOutput, # noqa: F401 + TextToAudioParameters, # noqa: F401 + TextToImageInput, # noqa: F401 + TextToImageOutput, # noqa: F401 + TextToImageParameters, # noqa: F401 + TextToImageTargetSize, # noqa: F401 + TokenClassificationInput, # noqa: F401 + TokenClassificationOutputElement, # noqa: F401 + TokenClassificationParameters, # noqa: F401 + TranslationGenerationParameters, # noqa: F401 + TranslationInput, # noqa: F401 + TranslationOutput, # noqa: F401 + VideoClassificationInput, # noqa: F401 + VideoClassificationOutputElement, # noqa: F401 + VideoClassificationParameters, # noqa: F401 + VisualQuestionAnsweringInput, # noqa: F401 + VisualQuestionAnsweringInputData, # noqa: F401 + VisualQuestionAnsweringOutputElement, # noqa: F401 + VisualQuestionAnsweringParameters, # noqa: F401 + ZeroShotClassificationInput, # noqa: F401 + ZeroShotClassificationInputData, # noqa: F401 + ZeroShotClassificationOutputElement, # noqa: F401 + ZeroShotClassificationParameters, # noqa: F401 + ZeroShotImageClassificationInput, # noqa: F401 + ZeroShotImageClassificationInputData, # noqa: F401 + ZeroShotImageClassificationOutputElement, # noqa: F401 + ZeroShotImageClassificationParameters, # noqa: F401 + ZeroShotObjectDetectionBoundingBox, # noqa: F401 + ZeroShotObjectDetectionInput, # noqa: F401 + ZeroShotObjectDetectionInputData, # noqa: F401 + ZeroShotObjectDetectionOutputElement, # noqa: F401 + ) + from .inference_api import InferenceApi # noqa: F401 + from .keras_mixin import ( + KerasModelHubMixin, # noqa: F401 + from_pretrained_keras, # noqa: F401 + push_to_hub_keras, # noqa: F401 + save_pretrained_keras, # noqa: F401 + ) + from .repocard import ( + DatasetCard, # noqa: F401 + ModelCard, # noqa: F401 + RepoCard, # noqa: F401 + SpaceCard, # noqa: F401 + metadata_eval_result, # noqa: F401 + metadata_load, # noqa: F401 + metadata_save, # noqa: F401 + metadata_update, # noqa: F401 + ) + from .repocard_data import ( + CardData, # noqa: F401 + DatasetCardData, # noqa: F401 + EvalResult, # noqa: F401 + ModelCardData, # noqa: F401 + SpaceCardData, # noqa: F401 + ) + from .repository import Repository # noqa: F401 + from .serialization import ( + StateDictSplit, # noqa: F401 + split_numpy_state_dict_into_shards, # noqa: F401 + split_state_dict_into_shards_factory, # noqa: F401 + split_tf_state_dict_into_shards, # noqa: F401 + split_torch_state_dict_into_shards, # noqa: F401 + ) + from .utils import ( + CachedFileInfo, # noqa: F401 + CachedRepoInfo, # noqa: F401 + CachedRevisionInfo, # noqa: F401 + CacheNotFound, # noqa: F401 + CorruptedCacheException, # noqa: F401 + DeleteCacheStrategy, # noqa: F401 + HFCacheInfo, # noqa: F401 + HfFolder, # noqa: F401 + cached_assets_path, # noqa: F401 + configure_http_backend, # noqa: F401 + dump_environment_info, # noqa: F401 + get_session, # noqa: F401 + get_token, # noqa: F401 + logging, # noqa: F401 + scan_cache_dir, # noqa: F401 + ) + from .utils.endpoint_helpers import ( + DatasetFilter, # noqa: F401 + ModelFilter, # noqa: F401 + ) diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/_commit_api.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/_commit_api.py new file mode 100644 index 0000000000000000000000000000000000000000..b807106bab7c5881982502f343b5ebe111f61511 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/_commit_api.py @@ -0,0 +1,698 @@ +""" +Type definitions and utilities for the `create_commit` API +""" + +import base64 +import io +import os +import warnings +from collections import defaultdict +from contextlib import contextmanager +from dataclasses import dataclass, field +from itertools import groupby +from pathlib import Path, PurePosixPath +from typing import TYPE_CHECKING, Any, BinaryIO, Dict, Iterable, Iterator, List, Literal, Optional, Tuple, Union + +from tqdm.contrib.concurrent import thread_map + +from huggingface_hub import get_session + +from .constants import ENDPOINT, HF_HUB_ENABLE_HF_TRANSFER +from .file_download import hf_hub_url +from .lfs import UploadInfo, lfs_upload, post_lfs_batch_info +from .utils import ( + EntryNotFoundError, + chunk_iterable, + hf_raise_for_status, + logging, + tqdm_stream_file, + validate_hf_hub_args, +) +from .utils import tqdm as hf_tqdm + + +if TYPE_CHECKING: + from .hf_api import RepoFile + + +logger = logging.get_logger(__name__) + + +UploadMode = Literal["lfs", "regular"] + +# Max is 1,000 per request on the Hub for HfApi.get_paths_info +# Otherwise we get: +# HfHubHTTPError: 413 Client Error: Payload Too Large for url: https://huggingface.co/api/datasets/xxx (Request ID: xxx)\n\ntoo many parameters +# See https://github.com/huggingface/huggingface_hub/issues/1503 +FETCH_LFS_BATCH_SIZE = 500 + + +@dataclass +class CommitOperationDelete: + """ + Data structure holding necessary info to delete a file or a folder from a repository + on the Hub. + + Args: + path_in_repo (`str`): + Relative filepath in the repo, for example: `"checkpoints/1fec34a/weights.bin"` + for a file or `"checkpoints/1fec34a/"` for a folder. + is_folder (`bool` or `Literal["auto"]`, *optional*) + Whether the Delete Operation applies to a folder or not. If "auto", the path + type (file or folder) is guessed automatically by looking if path ends with + a "/" (folder) or not (file). To explicitly set the path type, you can set + `is_folder=True` or `is_folder=False`. + """ + + path_in_repo: str + is_folder: Union[bool, Literal["auto"]] = "auto" + + def __post_init__(self): + self.path_in_repo = _validate_path_in_repo(self.path_in_repo) + + if self.is_folder == "auto": + self.is_folder = self.path_in_repo.endswith("/") + if not isinstance(self.is_folder, bool): + raise ValueError( + f"Wrong value for `is_folder`. Must be one of [`True`, `False`, `'auto'`]. Got '{self.is_folder}'." + ) + + +@dataclass +class CommitOperationCopy: + """ + Data structure holding necessary info to copy a file in a repository on the Hub. + + Limitations: + - Only LFS files can be copied. To copy a regular file, you need to download it locally and re-upload it + - Cross-repository copies are not supported. + + Note: you can combine a [`CommitOperationCopy`] and a [`CommitOperationDelete`] to rename an LFS file on the Hub. + + Args: + src_path_in_repo (`str`): + Relative filepath in the repo of the file to be copied, e.g. `"checkpoints/1fec34a/weights.bin"`. + path_in_repo (`str`): + Relative filepath in the repo where to copy the file, e.g. `"checkpoints/1fec34a/weights_copy.bin"`. + src_revision (`str`, *optional*): + The git revision of the file to be copied. Can be any valid git revision. + Default to the target commit revision. + """ + + src_path_in_repo: str + path_in_repo: str + src_revision: Optional[str] = None + + def __post_init__(self): + self.src_path_in_repo = _validate_path_in_repo(self.src_path_in_repo) + self.path_in_repo = _validate_path_in_repo(self.path_in_repo) + + +@dataclass +class CommitOperationAdd: + """ + Data structure holding necessary info to upload a file to a repository on the Hub. + + Args: + path_in_repo (`str`): + Relative filepath in the repo, for example: `"checkpoints/1fec34a/weights.bin"` + path_or_fileobj (`str`, `Path`, `bytes`, or `BinaryIO`): + Either: + - a path to a local file (as `str` or `pathlib.Path`) to upload + - a buffer of bytes (`bytes`) holding the content of the file to upload + - a "file object" (subclass of `io.BufferedIOBase`), typically obtained + with `open(path, "rb")`. It must support `seek()` and `tell()` methods. + + Raises: + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If `path_or_fileobj` is not one of `str`, `Path`, `bytes` or `io.BufferedIOBase`. + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If `path_or_fileobj` is a `str` or `Path` but not a path to an existing file. + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If `path_or_fileobj` is a `io.BufferedIOBase` but it doesn't support both + `seek()` and `tell()`. + """ + + path_in_repo: str + path_or_fileobj: Union[str, Path, bytes, BinaryIO] + upload_info: UploadInfo = field(init=False, repr=False) + + # Internal attributes + + # set to "lfs" or "regular" once known + _upload_mode: Optional[UploadMode] = field(init=False, repr=False, default=None) + + # set to True if .gitignore rules prevent the file from being uploaded as LFS + # (server-side check) + _should_ignore: Optional[bool] = field(init=False, repr=False, default=None) + + # set to True once the file has been uploaded as LFS + _is_uploaded: bool = field(init=False, repr=False, default=False) + + # set to True once the file has been committed + _is_committed: bool = field(init=False, repr=False, default=False) + + def __post_init__(self) -> None: + """Validates `path_or_fileobj` and compute `upload_info`.""" + self.path_in_repo = _validate_path_in_repo(self.path_in_repo) + + # Validate `path_or_fileobj` value + if isinstance(self.path_or_fileobj, Path): + self.path_or_fileobj = str(self.path_or_fileobj) + if isinstance(self.path_or_fileobj, str): + path_or_fileobj = os.path.normpath(os.path.expanduser(self.path_or_fileobj)) + if not os.path.isfile(path_or_fileobj): + raise ValueError(f"Provided path: '{path_or_fileobj}' is not a file on the local file system") + elif not isinstance(self.path_or_fileobj, (io.BufferedIOBase, bytes)): + # ^^ Inspired from: https://stackoverflow.com/questions/44584829/how-to-determine-if-file-is-opened-in-binary-or-text-mode + raise ValueError( + "path_or_fileobj must be either an instance of str, bytes or" + " io.BufferedIOBase. If you passed a file-like object, make sure it is" + " in binary mode." + ) + if isinstance(self.path_or_fileobj, io.BufferedIOBase): + try: + self.path_or_fileobj.tell() + self.path_or_fileobj.seek(0, os.SEEK_CUR) + except (OSError, AttributeError) as exc: + raise ValueError( + "path_or_fileobj is a file-like object but does not implement seek() and tell()" + ) from exc + + # Compute "upload_info" attribute + if isinstance(self.path_or_fileobj, str): + self.upload_info = UploadInfo.from_path(self.path_or_fileobj) + elif isinstance(self.path_or_fileobj, bytes): + self.upload_info = UploadInfo.from_bytes(self.path_or_fileobj) + else: + self.upload_info = UploadInfo.from_fileobj(self.path_or_fileobj) + + @contextmanager + def as_file(self, with_tqdm: bool = False) -> Iterator[BinaryIO]: + """ + A context manager that yields a file-like object allowing to read the underlying + data behind `path_or_fileobj`. + + Args: + with_tqdm (`bool`, *optional*, defaults to `False`): + If True, iterating over the file object will display a progress bar. Only + works if the file-like object is a path to a file. Pure bytes and buffers + are not supported. + + Example: + + ```python + >>> operation = CommitOperationAdd( + ... path_in_repo="remote/dir/weights.h5", + ... path_or_fileobj="./local/weights.h5", + ... ) + CommitOperationAdd(path_in_repo='remote/dir/weights.h5', path_or_fileobj='./local/weights.h5') + + >>> with operation.as_file() as file: + ... content = file.read() + + >>> with operation.as_file(with_tqdm=True) as file: + ... while True: + ... data = file.read(1024) + ... if not data: + ... break + config.json: 100%|█████████████████████████| 8.19k/8.19k [00:02<00:00, 3.72kB/s] + + >>> with operation.as_file(with_tqdm=True) as file: + ... requests.put(..., data=file) + config.json: 100%|█████████████████████████| 8.19k/8.19k [00:02<00:00, 3.72kB/s] + ``` + """ + if isinstance(self.path_or_fileobj, str) or isinstance(self.path_or_fileobj, Path): + if with_tqdm: + with tqdm_stream_file(self.path_or_fileobj) as file: + yield file + else: + with open(self.path_or_fileobj, "rb") as file: + yield file + elif isinstance(self.path_or_fileobj, bytes): + yield io.BytesIO(self.path_or_fileobj) + elif isinstance(self.path_or_fileobj, io.BufferedIOBase): + prev_pos = self.path_or_fileobj.tell() + yield self.path_or_fileobj + self.path_or_fileobj.seek(prev_pos, io.SEEK_SET) + + def b64content(self) -> bytes: + """ + The base64-encoded content of `path_or_fileobj` + + Returns: `bytes` + """ + with self.as_file() as file: + return base64.b64encode(file.read()) + + +def _validate_path_in_repo(path_in_repo: str) -> str: + # Validate `path_in_repo` value to prevent a server-side issue + if path_in_repo.startswith("/"): + path_in_repo = path_in_repo[1:] + if path_in_repo == "." or path_in_repo == ".." or path_in_repo.startswith("../"): + raise ValueError(f"Invalid `path_in_repo` in CommitOperation: '{path_in_repo}'") + if path_in_repo.startswith("./"): + path_in_repo = path_in_repo[2:] + if any(part == ".git" for part in path_in_repo.split("/")): + raise ValueError( + "Invalid `path_in_repo` in CommitOperation: cannot update files under a '.git/' folder (path:" + f" '{path_in_repo}')." + ) + return path_in_repo + + +CommitOperation = Union[CommitOperationAdd, CommitOperationCopy, CommitOperationDelete] + + +def _warn_on_overwriting_operations(operations: List[CommitOperation]) -> None: + """ + Warn user when a list of operations is expected to overwrite itself in a single + commit. + + Rules: + - If a filepath is updated by multiple `CommitOperationAdd` operations, a warning + message is triggered. + - If a filepath is updated at least once by a `CommitOperationAdd` and then deleted + by a `CommitOperationDelete`, a warning is triggered. + - If a `CommitOperationDelete` deletes a filepath that is then updated by a + `CommitOperationAdd`, no warning is triggered. This is usually useless (no need to + delete before upload) but can happen if a user deletes an entire folder and then + add new files to it. + """ + nb_additions_per_path: Dict[str, int] = defaultdict(int) + for operation in operations: + path_in_repo = operation.path_in_repo + if isinstance(operation, CommitOperationAdd): + if nb_additions_per_path[path_in_repo] > 0: + warnings.warn( + "About to update multiple times the same file in the same commit:" + f" '{path_in_repo}'. This can cause undesired inconsistencies in" + " your repo." + ) + nb_additions_per_path[path_in_repo] += 1 + for parent in PurePosixPath(path_in_repo).parents: + # Also keep track of number of updated files per folder + # => warns if deleting a folder overwrite some contained files + nb_additions_per_path[str(parent)] += 1 + if isinstance(operation, CommitOperationDelete): + if nb_additions_per_path[str(PurePosixPath(path_in_repo))] > 0: + if operation.is_folder: + warnings.warn( + "About to delete a folder containing files that have just been" + f" updated within the same commit: '{path_in_repo}'. This can" + " cause undesired inconsistencies in your repo." + ) + else: + warnings.warn( + "About to delete a file that have just been updated within the" + f" same commit: '{path_in_repo}'. This can cause undesired" + " inconsistencies in your repo." + ) + + +@validate_hf_hub_args +def _upload_lfs_files( + *, + additions: List[CommitOperationAdd], + repo_type: str, + repo_id: str, + headers: Dict[str, str], + endpoint: Optional[str] = None, + num_threads: int = 5, + revision: Optional[str] = None, +): + """ + Uploads the content of `additions` to the Hub using the large file storage protocol. + + Relevant external documentation: + - LFS Batch API: https://github.com/git-lfs/git-lfs/blob/main/docs/api/batch.md + + Args: + additions (`List` of `CommitOperationAdd`): + The files to be uploaded + repo_type (`str`): + Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`. + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + headers (`Dict[str, str]`): + Headers to use for the request, including authorization headers and user agent. + num_threads (`int`, *optional*): + The number of concurrent threads to use when uploading. Defaults to 5. + revision (`str`, *optional*): + The git revision to upload to. + + Raises: `RuntimeError` if an upload failed for any reason + + Raises: `ValueError` if the server returns malformed responses + + Raises: `requests.HTTPError` if the LFS batch endpoint returned an HTTP + error + + """ + # Step 1: retrieve upload instructions from the LFS batch endpoint. + # Upload instructions are retrieved by chunk of 256 files to avoid reaching + # the payload limit. + batch_actions: List[Dict] = [] + for chunk in chunk_iterable(additions, chunk_size=256): + batch_actions_chunk, batch_errors_chunk = post_lfs_batch_info( + upload_infos=[op.upload_info for op in chunk], + repo_id=repo_id, + repo_type=repo_type, + revision=revision, + endpoint=endpoint, + headers=headers, + token=None, # already passed in 'headers' + ) + + # If at least 1 error, we do not retrieve information for other chunks + if batch_errors_chunk: + message = "\n".join( + [ + f'Encountered error for file with OID {err.get("oid")}: `{err.get("error", {}).get("message")}' + for err in batch_errors_chunk + ] + ) + raise ValueError(f"LFS batch endpoint returned errors:\n{message}") + + batch_actions += batch_actions_chunk + oid2addop = {add_op.upload_info.sha256.hex(): add_op for add_op in additions} + + # Step 2: ignore files that have already been uploaded + filtered_actions = [] + for action in batch_actions: + if action.get("actions") is None: + logger.debug( + f"Content of file {oid2addop[action['oid']].path_in_repo} is already" + " present upstream - skipping upload." + ) + else: + filtered_actions.append(action) + + if len(filtered_actions) == 0: + logger.debug("No LFS files to upload.") + return + + # Step 3: upload files concurrently according to these instructions + def _wrapped_lfs_upload(batch_action) -> None: + try: + operation = oid2addop[batch_action["oid"]] + lfs_upload(operation=operation, lfs_batch_action=batch_action, headers=headers, endpoint=endpoint) + except Exception as exc: + raise RuntimeError(f"Error while uploading '{operation.path_in_repo}' to the Hub.") from exc + + if HF_HUB_ENABLE_HF_TRANSFER: + logger.debug(f"Uploading {len(filtered_actions)} LFS files to the Hub using `hf_transfer`.") + for action in hf_tqdm(filtered_actions): + _wrapped_lfs_upload(action) + elif len(filtered_actions) == 1: + logger.debug("Uploading 1 LFS file to the Hub") + _wrapped_lfs_upload(filtered_actions[0]) + else: + logger.debug( + f"Uploading {len(filtered_actions)} LFS files to the Hub using up to {num_threads} threads concurrently" + ) + thread_map( + _wrapped_lfs_upload, + filtered_actions, + desc=f"Upload {len(filtered_actions)} LFS files", + max_workers=num_threads, + tqdm_class=hf_tqdm, + ) + + +def _validate_preupload_info(preupload_info: dict): + files = preupload_info.get("files") + if not isinstance(files, list): + raise ValueError("preupload_info is improperly formatted") + for file_info in files: + if not ( + isinstance(file_info, dict) + and isinstance(file_info.get("path"), str) + and isinstance(file_info.get("uploadMode"), str) + and (file_info["uploadMode"] in ("lfs", "regular")) + ): + raise ValueError("preupload_info is improperly formatted:") + return preupload_info + + +@validate_hf_hub_args +def _fetch_upload_modes( + additions: Iterable[CommitOperationAdd], + repo_type: str, + repo_id: str, + headers: Dict[str, str], + revision: str, + endpoint: Optional[str] = None, + create_pr: bool = False, + gitignore_content: Optional[str] = None, +) -> None: + """ + Requests the Hub "preupload" endpoint to determine whether each input file should be uploaded as a regular git blob + or as git LFS blob. Input `additions` are mutated in-place with the upload mode. + + Args: + additions (`Iterable` of :class:`CommitOperationAdd`): + Iterable of :class:`CommitOperationAdd` describing the files to + upload to the Hub. + repo_type (`str`): + Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`. + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + headers (`Dict[str, str]`): + Headers to use for the request, including authorization headers and user agent. + revision (`str`): + The git revision to upload the files to. Can be any valid git revision. + gitignore_content (`str`, *optional*): + The content of the `.gitignore` file to know which files should be ignored. The order of priority + is to first check if `gitignore_content` is passed, then check if the `.gitignore` file is present + in the list of files to commit and finally default to the `.gitignore` file already hosted on the Hub + (if any). + Raises: + [`~utils.HfHubHTTPError`] + If the Hub API returned an error. + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If the Hub API response is improperly formatted. + """ + endpoint = endpoint if endpoint is not None else ENDPOINT + + # Fetch upload mode (LFS or regular) chunk by chunk. + upload_modes: Dict[str, UploadMode] = {} + should_ignore_info: Dict[str, bool] = {} + + for chunk in chunk_iterable(additions, 256): + payload: Dict = { + "files": [ + { + "path": op.path_in_repo, + "sample": base64.b64encode(op.upload_info.sample).decode("ascii"), + "size": op.upload_info.size, + "sha": op.upload_info.sha256.hex(), + } + for op in chunk + ] + } + if gitignore_content is not None: + payload["gitIgnore"] = gitignore_content + + resp = get_session().post( + f"{endpoint}/api/{repo_type}s/{repo_id}/preupload/{revision}", + json=payload, + headers=headers, + params={"create_pr": "1"} if create_pr else None, + ) + hf_raise_for_status(resp) + preupload_info = _validate_preupload_info(resp.json()) + upload_modes.update(**{file["path"]: file["uploadMode"] for file in preupload_info["files"]}) + should_ignore_info.update(**{file["path"]: file["shouldIgnore"] for file in preupload_info["files"]}) + + # Set upload mode for each addition operation + for addition in additions: + addition._upload_mode = upload_modes[addition.path_in_repo] + addition._should_ignore = should_ignore_info[addition.path_in_repo] + + # Empty files cannot be uploaded as LFS (S3 would fail with a 501 Not Implemented) + # => empty files are uploaded as "regular" to still allow users to commit them. + for addition in additions: + if addition.upload_info.size == 0: + addition._upload_mode = "regular" + + +@validate_hf_hub_args +def _fetch_files_to_copy( + copies: Iterable[CommitOperationCopy], + repo_type: str, + repo_id: str, + headers: Dict[str, str], + revision: str, + endpoint: Optional[str] = None, +) -> Dict[Tuple[str, Optional[str]], Union["RepoFile", bytes]]: + """ + Fetch information about the files to copy. + + For LFS files, we only need their metadata (file size and sha256) while for regular files + we need to download the raw content from the Hub. + + Args: + copies (`Iterable` of :class:`CommitOperationCopy`): + Iterable of :class:`CommitOperationCopy` describing the files to + copy on the Hub. + repo_type (`str`): + Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`. + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + headers (`Dict[str, str]`): + Headers to use for the request, including authorization headers and user agent. + revision (`str`): + The git revision to upload the files to. Can be any valid git revision. + + Returns: `Dict[Tuple[str, Optional[str]], Union[RepoFile, bytes]]]` + Key is the file path and revision of the file to copy. + Value is the raw content as bytes (for regular files) or the file information as a RepoFile (for LFS files). + + Raises: + [`~utils.HfHubHTTPError`] + If the Hub API returned an error. + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If the Hub API response is improperly formatted. + """ + from .hf_api import HfApi, RepoFolder + + hf_api = HfApi(endpoint=endpoint, headers=headers) + files_to_copy: Dict[Tuple[str, Optional[str]], Union["RepoFile", bytes]] = {} + for src_revision, operations in groupby(copies, key=lambda op: op.src_revision): + operations = list(operations) # type: ignore + paths = [op.src_path_in_repo for op in operations] + for offset in range(0, len(paths), FETCH_LFS_BATCH_SIZE): + src_repo_files = hf_api.get_paths_info( + repo_id=repo_id, + paths=paths[offset : offset + FETCH_LFS_BATCH_SIZE], + revision=src_revision or revision, + repo_type=repo_type, + ) + for src_repo_file in src_repo_files: + if isinstance(src_repo_file, RepoFolder): + raise NotImplementedError("Copying a folder is not implemented.") + if src_repo_file.lfs: + files_to_copy[(src_repo_file.path, src_revision)] = src_repo_file + else: + # TODO: (optimization) download regular files to copy concurrently + url = hf_hub_url( + endpoint=endpoint, + repo_type=repo_type, + repo_id=repo_id, + revision=src_revision or revision, + filename=src_repo_file.path, + ) + response = get_session().get(url, headers=headers) + hf_raise_for_status(response) + files_to_copy[(src_repo_file.path, src_revision)] = response.content + for operation in operations: + if (operation.src_path_in_repo, src_revision) not in files_to_copy: + raise EntryNotFoundError( + f"Cannot copy {operation.src_path_in_repo} at revision " + f"{src_revision or revision}: file is missing on repo." + ) + return files_to_copy + + +def _prepare_commit_payload( + operations: Iterable[CommitOperation], + files_to_copy: Dict[Tuple[str, Optional[str]], Union["RepoFile", bytes]], + commit_message: str, + commit_description: Optional[str] = None, + parent_commit: Optional[str] = None, +) -> Iterable[Dict[str, Any]]: + """ + Builds the payload to POST to the `/commit` API of the Hub. + + Payload is returned as an iterator so that it can be streamed as a ndjson in the + POST request. + + For more information, see: + - https://github.com/huggingface/huggingface_hub/issues/1085#issuecomment-1265208073 + - http://ndjson.org/ + """ + commit_description = commit_description if commit_description is not None else "" + + # 1. Send a header item with the commit metadata + header_value = {"summary": commit_message, "description": commit_description} + if parent_commit is not None: + header_value["parentCommit"] = parent_commit + yield {"key": "header", "value": header_value} + + nb_ignored_files = 0 + + # 2. Send operations, one per line + for operation in operations: + # Skip ignored files + if isinstance(operation, CommitOperationAdd) and operation._should_ignore: + logger.debug(f"Skipping file '{operation.path_in_repo}' in commit (ignored by gitignore file).") + nb_ignored_files += 1 + continue + + # 2.a. Case adding a regular file + if isinstance(operation, CommitOperationAdd) and operation._upload_mode == "regular": + yield { + "key": "file", + "value": { + "content": operation.b64content().decode(), + "path": operation.path_in_repo, + "encoding": "base64", + }, + } + # 2.b. Case adding an LFS file + elif isinstance(operation, CommitOperationAdd) and operation._upload_mode == "lfs": + yield { + "key": "lfsFile", + "value": { + "path": operation.path_in_repo, + "algo": "sha256", + "oid": operation.upload_info.sha256.hex(), + "size": operation.upload_info.size, + }, + } + # 2.c. Case deleting a file or folder + elif isinstance(operation, CommitOperationDelete): + yield { + "key": "deletedFolder" if operation.is_folder else "deletedFile", + "value": {"path": operation.path_in_repo}, + } + # 2.d. Case copying a file or folder + elif isinstance(operation, CommitOperationCopy): + file_to_copy = files_to_copy[(operation.src_path_in_repo, operation.src_revision)] + if isinstance(file_to_copy, bytes): + yield { + "key": "file", + "value": { + "content": base64.b64encode(file_to_copy).decode(), + "path": operation.path_in_repo, + "encoding": "base64", + }, + } + elif file_to_copy.lfs: + yield { + "key": "lfsFile", + "value": { + "path": operation.path_in_repo, + "algo": "sha256", + "oid": file_to_copy.lfs.sha256, + }, + } + else: + raise ValueError( + "Malformed files_to_copy (should be raw file content as bytes or RepoFile objects with LFS info." + ) + # 2.e. Never expected to happen + else: + raise ValueError( + f"Unknown operation to commit. Operation: {operation}. Upload mode:" + f" {getattr(operation, '_upload_mode', None)}" + ) + + if nb_ignored_files > 0: + logger.info(f"Skipped {nb_ignored_files} file(s) in commit (ignored by gitignore file).") diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/_commit_scheduler.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/_commit_scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..80d8dac7866a4eeef888d36cfbb974aa06a9930b --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/_commit_scheduler.py @@ -0,0 +1,327 @@ +import atexit +import logging +import os +import time +from concurrent.futures import Future +from dataclasses import dataclass +from io import SEEK_END, SEEK_SET, BytesIO +from pathlib import Path +from threading import Lock, Thread +from typing import Dict, List, Optional, Union + +from .hf_api import IGNORE_GIT_FOLDER_PATTERNS, CommitInfo, CommitOperationAdd, HfApi +from .utils import filter_repo_objects + + +logger = logging.getLogger(__name__) + + +@dataclass(frozen=True) +class _FileToUpload: + """Temporary dataclass to store info about files to upload. Not meant to be used directly.""" + + local_path: Path + path_in_repo: str + size_limit: int + last_modified: float + + +class CommitScheduler: + """ + Scheduler to upload a local folder to the Hub at regular intervals (e.g. push to hub every 5 minutes). + + The scheduler is started when instantiated and run indefinitely. At the end of your script, a last commit is + triggered. Checkout the [upload guide](https://huggingface.co/docs/huggingface_hub/guides/upload#scheduled-uploads) + to learn more about how to use it. + + Args: + repo_id (`str`): + The id of the repo to commit to. + folder_path (`str` or `Path`): + Path to the local folder to upload regularly. + every (`int` or `float`, *optional*): + The number of minutes between each commit. Defaults to 5 minutes. + path_in_repo (`str`, *optional*): + Relative path of the directory in the repo, for example: `"checkpoints/"`. Defaults to the root folder + of the repository. + repo_type (`str`, *optional*): + The type of the repo to commit to. Defaults to `model`. + revision (`str`, *optional*): + The revision of the repo to commit to. Defaults to `main`. + private (`bool`, *optional*): + Whether to make the repo private. Defaults to `False`. This value is ignored if the repo already exist. + token (`str`, *optional*): + The token to use to commit to the repo. Defaults to the token saved on the machine. + allow_patterns (`List[str]` or `str`, *optional*): + If provided, only files matching at least one pattern are uploaded. + ignore_patterns (`List[str]` or `str`, *optional*): + If provided, files matching any of the patterns are not uploaded. + squash_history (`bool`, *optional*): + Whether to squash the history of the repo after each commit. Defaults to `False`. Squashing commits is + useful to avoid degraded performances on the repo when it grows too large. + hf_api (`HfApi`, *optional*): + The [`HfApi`] client to use to commit to the Hub. Can be set with custom settings (user agent, token,...). + + Example: + ```py + >>> from pathlib import Path + >>> from huggingface_hub import CommitScheduler + + # Scheduler uploads every 10 minutes + >>> csv_path = Path("watched_folder/data.csv") + >>> CommitScheduler(repo_id="test_scheduler", repo_type="dataset", folder_path=csv_path.parent, every=10) + + >>> with csv_path.open("a") as f: + ... f.write("first line") + + # Some time later (...) + >>> with csv_path.open("a") as f: + ... f.write("second line") + ``` + """ + + def __init__( + self, + *, + repo_id: str, + folder_path: Union[str, Path], + every: Union[int, float] = 5, + path_in_repo: Optional[str] = None, + repo_type: Optional[str] = None, + revision: Optional[str] = None, + private: bool = False, + token: Optional[str] = None, + allow_patterns: Optional[Union[List[str], str]] = None, + ignore_patterns: Optional[Union[List[str], str]] = None, + squash_history: bool = False, + hf_api: Optional["HfApi"] = None, + ) -> None: + self.api = hf_api or HfApi(token=token) + + # Folder + self.folder_path = Path(folder_path).expanduser().resolve() + self.path_in_repo = path_in_repo or "" + self.allow_patterns = allow_patterns + + if ignore_patterns is None: + ignore_patterns = [] + elif isinstance(ignore_patterns, str): + ignore_patterns = [ignore_patterns] + self.ignore_patterns = ignore_patterns + IGNORE_GIT_FOLDER_PATTERNS + + if self.folder_path.is_file(): + raise ValueError(f"'folder_path' must be a directory, not a file: '{self.folder_path}'.") + self.folder_path.mkdir(parents=True, exist_ok=True) + + # Repository + repo_url = self.api.create_repo(repo_id=repo_id, private=private, repo_type=repo_type, exist_ok=True) + self.repo_id = repo_url.repo_id + self.repo_type = repo_type + self.revision = revision + self.token = token + + # Keep track of already uploaded files + self.last_uploaded: Dict[Path, float] = {} # key is local path, value is timestamp + + # Scheduler + if not every > 0: + raise ValueError(f"'every' must be a positive integer, not '{every}'.") + self.lock = Lock() + self.every = every + self.squash_history = squash_history + + logger.info(f"Scheduled job to push '{self.folder_path}' to '{self.repo_id}' every {self.every} minutes.") + self._scheduler_thread = Thread(target=self._run_scheduler, daemon=True) + self._scheduler_thread.start() + atexit.register(self._push_to_hub) + + self.__stopped = False + + def stop(self) -> None: + """Stop the scheduler. + + A stopped scheduler cannot be restarted. Mostly for tests purposes. + """ + self.__stopped = True + + def _run_scheduler(self) -> None: + """Dumb thread waiting between each scheduled push to Hub.""" + while True: + self.last_future = self.trigger() + time.sleep(self.every * 60) + if self.__stopped: + break + + def trigger(self) -> Future: + """Trigger a `push_to_hub` and return a future. + + This method is automatically called every `every` minutes. You can also call it manually to trigger a commit + immediately, without waiting for the next scheduled commit. + """ + return self.api.run_as_future(self._push_to_hub) + + def _push_to_hub(self) -> Optional[CommitInfo]: + if self.__stopped: # If stopped, already scheduled commits are ignored + return None + + logger.info("(Background) scheduled commit triggered.") + try: + value = self.push_to_hub() + if self.squash_history: + logger.info("(Background) squashing repo history.") + self.api.super_squash_history(repo_id=self.repo_id, repo_type=self.repo_type, branch=self.revision) + return value + except Exception as e: + logger.error(f"Error while pushing to Hub: {e}") # Depending on the setup, error might be silenced + raise + + def push_to_hub(self) -> Optional[CommitInfo]: + """ + Push folder to the Hub and return the commit info. + + + + This method is not meant to be called directly. It is run in the background by the scheduler, respecting a + queue mechanism to avoid concurrent commits. Making a direct call to the method might lead to concurrency + issues. + + + + The default behavior of `push_to_hub` is to assume an append-only folder. It lists all files in the folder and + uploads only changed files. If no changes are found, the method returns without committing anything. If you want + to change this behavior, you can inherit from [`CommitScheduler`] and override this method. This can be useful + for example to compress data together in a single file before committing. For more details and examples, check + out our [integration guide](https://huggingface.co/docs/huggingface_hub/main/en/guides/upload#scheduled-uploads). + """ + # Check files to upload (with lock) + with self.lock: + logger.debug("Listing files to upload for scheduled commit.") + + # List files from folder (taken from `_prepare_upload_folder_additions`) + relpath_to_abspath = { + path.relative_to(self.folder_path).as_posix(): path + for path in sorted(self.folder_path.glob("**/*")) # sorted to be deterministic + if path.is_file() + } + prefix = f"{self.path_in_repo.strip('/')}/" if self.path_in_repo else "" + + # Filter with pattern + filter out unchanged files + retrieve current file size + files_to_upload: List[_FileToUpload] = [] + for relpath in filter_repo_objects( + relpath_to_abspath.keys(), allow_patterns=self.allow_patterns, ignore_patterns=self.ignore_patterns + ): + local_path = relpath_to_abspath[relpath] + stat = local_path.stat() + if self.last_uploaded.get(local_path) is None or self.last_uploaded[local_path] != stat.st_mtime: + files_to_upload.append( + _FileToUpload( + local_path=local_path, + path_in_repo=prefix + relpath, + size_limit=stat.st_size, + last_modified=stat.st_mtime, + ) + ) + + # Return if nothing to upload + if len(files_to_upload) == 0: + logger.debug("Dropping schedule commit: no changed file to upload.") + return None + + # Convert `_FileToUpload` as `CommitOperationAdd` (=> compute file shas + limit to file size) + logger.debug("Removing unchanged files since previous scheduled commit.") + add_operations = [ + CommitOperationAdd( + # Cap the file to its current size, even if the user append data to it while a scheduled commit is happening + path_or_fileobj=PartialFileIO(file_to_upload.local_path, size_limit=file_to_upload.size_limit), + path_in_repo=file_to_upload.path_in_repo, + ) + for file_to_upload in files_to_upload + ] + + # Upload files (append mode expected - no need for lock) + logger.debug("Uploading files for scheduled commit.") + commit_info = self.api.create_commit( + repo_id=self.repo_id, + repo_type=self.repo_type, + operations=add_operations, + commit_message="Scheduled Commit", + revision=self.revision, + ) + + # Successful commit: keep track of the latest "last_modified" for each file + for file in files_to_upload: + self.last_uploaded[file.local_path] = file.last_modified + return commit_info + + +class PartialFileIO(BytesIO): + """A file-like object that reads only the first part of a file. + + Useful to upload a file to the Hub when the user might still be appending data to it. Only the first part of the + file is uploaded (i.e. the part that was available when the filesystem was first scanned). + + In practice, only used internally by the CommitScheduler to regularly push a folder to the Hub with minimal + disturbance for the user. The object is passed to `CommitOperationAdd`. + + Only supports `read`, `tell` and `seek` methods. + + Args: + file_path (`str` or `Path`): + Path to the file to read. + size_limit (`int`): + The maximum number of bytes to read from the file. If the file is larger than this, only the first part + will be read (and uploaded). + """ + + def __init__(self, file_path: Union[str, Path], size_limit: int) -> None: + self._file_path = Path(file_path) + self._file = self._file_path.open("rb") + self._size_limit = min(size_limit, os.fstat(self._file.fileno()).st_size) + + def __del__(self) -> None: + self._file.close() + return super().__del__() + + def __repr__(self) -> str: + return f"" + + def __len__(self) -> int: + return self._size_limit + + def __getattribute__(self, name: str): + if name.startswith("_") or name in ("read", "tell", "seek"): # only 3 public methods supported + return super().__getattribute__(name) + raise NotImplementedError(f"PartialFileIO does not support '{name}'.") + + def tell(self) -> int: + """Return the current file position.""" + return self._file.tell() + + def seek(self, __offset: int, __whence: int = SEEK_SET) -> int: + """Change the stream position to the given offset. + + Behavior is the same as a regular file, except that the position is capped to the size limit. + """ + if __whence == SEEK_END: + # SEEK_END => set from the truncated end + __offset = len(self) + __offset + __whence = SEEK_SET + + pos = self._file.seek(__offset, __whence) + if pos > self._size_limit: + return self._file.seek(self._size_limit) + return pos + + def read(self, __size: Optional[int] = -1) -> bytes: + """Read at most `__size` bytes from the file. + + Behavior is the same as a regular file, except that it is capped to the size limit. + """ + current = self._file.tell() + if __size is None or __size < 0: + # Read until file limit + truncated_size = self._size_limit - current + else: + # Read until file limit or __size + truncated_size = min(__size, self._size_limit - current) + return self._file.read(truncated_size) diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/_inference_endpoints.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/_inference_endpoints.py new file mode 100644 index 0000000000000000000000000000000000000000..8b81a796c6379c9b6bf40e0933933ceb8ba6c739 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/_inference_endpoints.py @@ -0,0 +1,384 @@ +import time +from dataclasses import dataclass, field +from datetime import datetime +from enum import Enum +from typing import TYPE_CHECKING, Dict, Optional, Union + +from .inference._client import InferenceClient +from .inference._generated._async_client import AsyncInferenceClient +from .utils import logging, parse_datetime + + +if TYPE_CHECKING: + from .hf_api import HfApi + + +logger = logging.get_logger(__name__) + + +class InferenceEndpointError(Exception): + """Generic exception when dealing with Inference Endpoints.""" + + +class InferenceEndpointTimeoutError(InferenceEndpointError, TimeoutError): + """Exception for timeouts while waiting for Inference Endpoint.""" + + +class InferenceEndpointStatus(str, Enum): + PENDING = "pending" + INITIALIZING = "initializing" + UPDATING = "updating" + UPDATE_FAILED = "updateFailed" + RUNNING = "running" + PAUSED = "paused" + FAILED = "failed" + SCALED_TO_ZERO = "scaledToZero" + + +class InferenceEndpointType(str, Enum): + PUBlIC = "public" + PROTECTED = "protected" + PRIVATE = "private" + + +@dataclass +class InferenceEndpoint: + """ + Contains information about a deployed Inference Endpoint. + + Args: + name (`str`): + The unique name of the Inference Endpoint. + namespace (`str`): + The namespace where the Inference Endpoint is located. + repository (`str`): + The name of the model repository deployed on this Inference Endpoint. + status ([`InferenceEndpointStatus`]): + The current status of the Inference Endpoint. + url (`str`, *optional*): + The URL of the Inference Endpoint, if available. Only a deployed Inference Endpoint will have a URL. + framework (`str`): + The machine learning framework used for the model. + revision (`str`): + The specific model revision deployed on the Inference Endpoint. + task (`str`): + The task associated with the deployed model. + created_at (`datetime.datetime`): + The timestamp when the Inference Endpoint was created. + updated_at (`datetime.datetime`): + The timestamp of the last update of the Inference Endpoint. + type ([`InferenceEndpointType`]): + The type of the Inference Endpoint (public, protected, private). + raw (`Dict`): + The raw dictionary data returned from the API. + token (`str` or `bool`, *optional*): + Authentication token for the Inference Endpoint, if set when requesting the API. Will default to the + locally saved token if not provided. Pass `token=False` if you don't want to send your token to the server. + + Example: + ```python + >>> from huggingface_hub import get_inference_endpoint + >>> endpoint = get_inference_endpoint("my-text-to-image") + >>> endpoint + InferenceEndpoint(name='my-text-to-image', ...) + + # Get status + >>> endpoint.status + 'running' + >>> endpoint.url + 'https://my-text-to-image.region.vendor.endpoints.huggingface.cloud' + + # Run inference + >>> endpoint.client.text_to_image(...) + + # Pause endpoint to save $$$ + >>> endpoint.pause() + + # ... + # Resume and wait for deployment + >>> endpoint.resume() + >>> endpoint.wait() + >>> endpoint.client.text_to_image(...) + ``` + """ + + # Field in __repr__ + name: str = field(init=False) + namespace: str + repository: str = field(init=False) + status: InferenceEndpointStatus = field(init=False) + url: Optional[str] = field(init=False) + + # Other fields + framework: str = field(repr=False, init=False) + revision: str = field(repr=False, init=False) + task: str = field(repr=False, init=False) + created_at: datetime = field(repr=False, init=False) + updated_at: datetime = field(repr=False, init=False) + type: InferenceEndpointType = field(repr=False, init=False) + + # Raw dict from the API + raw: Dict = field(repr=False) + + # Internal fields + _token: Union[str, bool, None] = field(repr=False, compare=False) + _api: "HfApi" = field(repr=False, compare=False) + + @classmethod + def from_raw( + cls, raw: Dict, namespace: str, token: Union[str, bool, None] = None, api: Optional["HfApi"] = None + ) -> "InferenceEndpoint": + """Initialize object from raw dictionary.""" + if api is None: + from .hf_api import HfApi + + api = HfApi() + if token is None: + token = api.token + + # All other fields are populated in __post_init__ + return cls(raw=raw, namespace=namespace, _token=token, _api=api) + + def __post_init__(self) -> None: + """Populate fields from raw dictionary.""" + self._populate_from_raw() + + @property + def client(self) -> InferenceClient: + """Returns a client to make predictions on this Inference Endpoint. + + Returns: + [`InferenceClient`]: an inference client pointing to the deployed endpoint. + + Raises: + [`InferenceEndpointError`]: If the Inference Endpoint is not yet deployed. + """ + if self.url is None: + raise InferenceEndpointError( + "Cannot create a client for this Inference Endpoint as it is not yet deployed. " + "Please wait for the Inference Endpoint to be deployed using `endpoint.wait()` and try again." + ) + return InferenceClient(model=self.url, token=self._token) + + @property + def async_client(self) -> AsyncInferenceClient: + """Returns a client to make predictions on this Inference Endpoint. + + Returns: + [`AsyncInferenceClient`]: an asyncio-compatible inference client pointing to the deployed endpoint. + + Raises: + [`InferenceEndpointError`]: If the Inference Endpoint is not yet deployed. + """ + if self.url is None: + raise InferenceEndpointError( + "Cannot create a client for this Inference Endpoint as it is not yet deployed. " + "Please wait for the Inference Endpoint to be deployed using `endpoint.wait()` and try again." + ) + return AsyncInferenceClient(model=self.url, token=self._token) + + def wait(self, timeout: Optional[int] = None, refresh_every: int = 5) -> "InferenceEndpoint": + """Wait for the Inference Endpoint to be deployed. + + Information from the server will be fetched every 1s. If the Inference Endpoint is not deployed after `timeout` + seconds, a [`InferenceEndpointTimeoutError`] will be raised. The [`InferenceEndpoint`] will be mutated in place with the latest + data. + + Args: + timeout (`int`, *optional*): + The maximum time to wait for the Inference Endpoint to be deployed, in seconds. If `None`, will wait + indefinitely. + refresh_every (`int`, *optional*): + The time to wait between each fetch of the Inference Endpoint status, in seconds. Defaults to 5s. + + Returns: + [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data. + + Raises: + [`InferenceEndpointError`] + If the Inference Endpoint ended up in a failed state. + [`InferenceEndpointTimeoutError`] + If the Inference Endpoint is not deployed after `timeout` seconds. + """ + if self.url is not None: # Means the endpoint is deployed + logger.info("Inference Endpoint is ready to be used.") + return self + + if timeout is not None and timeout < 0: + raise ValueError("`timeout` cannot be negative.") + if refresh_every <= 0: + raise ValueError("`refresh_every` must be positive.") + + start = time.time() + while True: + self.fetch() + if self.url is not None: # Means the endpoint is deployed + logger.info("Inference Endpoint is ready to be used.") + return self + if self.status == InferenceEndpointStatus.FAILED: + raise InferenceEndpointError( + f"Inference Endpoint {self.name} failed to deploy. Please check the logs for more information." + ) + if timeout is not None: + if time.time() - start > timeout: + raise InferenceEndpointTimeoutError("Timeout while waiting for Inference Endpoint to be deployed.") + logger.info(f"Inference Endpoint is not deployed yet ({self.status}). Waiting {refresh_every}s...") + time.sleep(refresh_every) + + def fetch(self) -> "InferenceEndpoint": + """Fetch latest information about the Inference Endpoint. + + Returns: + [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data. + """ + obj = self._api.get_inference_endpoint(name=self.name, namespace=self.namespace, token=self._token) # type: ignore [arg-type] + self.raw = obj.raw + self._populate_from_raw() + return self + + def update( + self, + *, + # Compute update + accelerator: Optional[str] = None, + instance_size: Optional[str] = None, + instance_type: Optional[str] = None, + min_replica: Optional[int] = None, + max_replica: Optional[int] = None, + # Model update + repository: Optional[str] = None, + framework: Optional[str] = None, + revision: Optional[str] = None, + task: Optional[str] = None, + ) -> "InferenceEndpoint": + """Update the Inference Endpoint. + + This method allows the update of either the compute configuration, the deployed model, or both. All arguments are + optional but at least one must be provided. + + This is an alias for [`HfApi.update_inference_endpoint`]. The current object is mutated in place with the + latest data from the server. + + Args: + accelerator (`str`, *optional*): + The hardware accelerator to be used for inference (e.g. `"cpu"`). + instance_size (`str`, *optional*): + The size or type of the instance to be used for hosting the model (e.g. `"large"`). + instance_type (`str`, *optional*): + The cloud instance type where the Inference Endpoint will be deployed (e.g. `"c6i"`). + min_replica (`int`, *optional*): + The minimum number of replicas (instances) to keep running for the Inference Endpoint. + max_replica (`int`, *optional*): + The maximum number of replicas (instances) to scale to for the Inference Endpoint. + + repository (`str`, *optional*): + The name of the model repository associated with the Inference Endpoint (e.g. `"gpt2"`). + framework (`str`, *optional*): + The machine learning framework used for the model (e.g. `"custom"`). + revision (`str`, *optional*): + The specific model revision to deploy on the Inference Endpoint (e.g. `"6c0e6080953db56375760c0471a8c5f2929baf11"`). + task (`str`, *optional*): + The task on which to deploy the model (e.g. `"text-classification"`). + + Returns: + [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data. + """ + # Make API call + obj = self._api.update_inference_endpoint( + name=self.name, + namespace=self.namespace, + accelerator=accelerator, + instance_size=instance_size, + instance_type=instance_type, + min_replica=min_replica, + max_replica=max_replica, + repository=repository, + framework=framework, + revision=revision, + task=task, + token=self._token, # type: ignore [arg-type] + ) + + # Mutate current object + self.raw = obj.raw + self._populate_from_raw() + return self + + def pause(self) -> "InferenceEndpoint": + """Pause the Inference Endpoint. + + A paused Inference Endpoint will not be charged. It can be resumed at any time using [`InferenceEndpoint.resume`]. + This is different than scaling the Inference Endpoint to zero with [`InferenceEndpoint.scale_to_zero`], which + would be automatically restarted when a request is made to it. + + This is an alias for [`HfApi.pause_inference_endpoint`]. The current object is mutated in place with the + latest data from the server. + + Returns: + [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data. + """ + obj = self._api.pause_inference_endpoint(name=self.name, namespace=self.namespace, token=self._token) # type: ignore [arg-type] + self.raw = obj.raw + self._populate_from_raw() + return self + + def resume(self) -> "InferenceEndpoint": + """Resume the Inference Endpoint. + + This is an alias for [`HfApi.resume_inference_endpoint`]. The current object is mutated in place with the + latest data from the server. + + Returns: + [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data. + """ + obj = self._api.resume_inference_endpoint(name=self.name, namespace=self.namespace, token=self._token) # type: ignore [arg-type] + self.raw = obj.raw + self._populate_from_raw() + return self + + def scale_to_zero(self) -> "InferenceEndpoint": + """Scale Inference Endpoint to zero. + + An Inference Endpoint scaled to zero will not be charged. It will be resume on the next request to it, with a + cold start delay. This is different than pausing the Inference Endpoint with [`InferenceEndpoint.pause`], which + would require a manual resume with [`InferenceEndpoint.resume`]. + + This is an alias for [`HfApi.scale_to_zero_inference_endpoint`]. The current object is mutated in place with the + latest data from the server. + + Returns: + [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data. + """ + obj = self._api.scale_to_zero_inference_endpoint(name=self.name, namespace=self.namespace, token=self._token) # type: ignore [arg-type] + self.raw = obj.raw + self._populate_from_raw() + return self + + def delete(self) -> None: + """Delete the Inference Endpoint. + + This operation is not reversible. If you don't want to be charged for an Inference Endpoint, it is preferable + to pause it with [`InferenceEndpoint.pause`] or scale it to zero with [`InferenceEndpoint.scale_to_zero`]. + + This is an alias for [`HfApi.delete_inference_endpoint`]. + """ + self._api.delete_inference_endpoint(name=self.name, namespace=self.namespace, token=self._token) # type: ignore [arg-type] + + def _populate_from_raw(self) -> None: + """Populate fields from raw dictionary. + + Called in __post_init__ + each time the Inference Endpoint is updated. + """ + # Repr fields + self.name = self.raw["name"] + self.repository = self.raw["model"]["repository"] + self.status = self.raw["status"]["state"] + self.url = self.raw["status"].get("url") + + # Other fields + self.framework = self.raw["model"]["framework"] + self.revision = self.raw["model"]["revision"] + self.task = self.raw["model"]["task"] + self.created_at = parse_datetime(self.raw["status"]["createdAt"]) + self.updated_at = parse_datetime(self.raw["status"]["updatedAt"]) + self.type = self.raw["type"] diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/_multi_commits.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/_multi_commits.py new file mode 100644 index 0000000000000000000000000000000000000000..57c911bf0408081f18213db54e2ef38c819267bf --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/_multi_commits.py @@ -0,0 +1,306 @@ +# coding=utf-8 +# Copyright 2023-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contains utilities to multi-commits (i.e. push changes iteratively on a PR).""" + +import re +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Iterable, List, Optional, Set, Tuple, Union + +from ._commit_api import CommitOperationAdd, CommitOperationDelete +from .community import DiscussionWithDetails +from .utils import experimental +from .utils._cache_manager import _format_size +from .utils.insecure_hashlib import sha256 + + +if TYPE_CHECKING: + from .hf_api import HfApi + + +class MultiCommitException(Exception): + """Base exception for any exception happening while doing a multi-commit.""" + + +MULTI_COMMIT_PR_DESCRIPTION_TEMPLATE = """ +## {commit_message} + +{commit_description} + +**Multi commit ID:** {multi_commit_id} + +Scheduled commits: + +{multi_commit_strategy} + +_This is a PR opened using the `huggingface_hub` library in the context of a multi-commit. PR can be commented as a usual PR. However, please be aware that manually updating the PR description, changing the PR status, or pushing new commits, is not recommended as it might corrupt the commit process. Learn more about multi-commits [in this guide](https://huggingface.co/docs/huggingface_hub/main/guides/upload)._ +""" + +MULTI_COMMIT_PR_COMPLETION_COMMENT_TEMPLATE = """ +Multi-commit is now completed! You can ping the repo owner to review the changes. This PR can now be commented or modified without risking to corrupt it. + +_This is a comment posted using the `huggingface_hub` library in the context of a multi-commit. Learn more about multi-commits [in this guide](https://huggingface.co/docs/huggingface_hub/main/guides/upload)._ +""" + +MULTI_COMMIT_PR_CLOSING_COMMENT_TEMPLATE = """ +`create_pr=False` has been passed so PR is automatically merged. + +_This is a comment posted using the `huggingface_hub` library in the context of a multi-commit. Learn more about multi-commits [in this guide](https://huggingface.co/docs/huggingface_hub/main/guides/upload)._ +""" + +MULTI_COMMIT_PR_CLOSE_COMMENT_FAILURE_NO_CHANGES_TEMPLATE = """ +Cannot merge Pull Requests as no changes are associated. This PR will be closed automatically. + +_This is a comment posted using the `huggingface_hub` library in the context of a multi-commit. Learn more about multi-commits [in this guide](https://huggingface.co/docs/huggingface_hub/main/guides/upload)._ +""" + +MULTI_COMMIT_PR_CLOSE_COMMENT_FAILURE_BAD_REQUEST_TEMPLATE = """ +An error occurred while trying to merge the Pull Request: `{error_message}`. + +_This is a comment posted using the `huggingface_hub` library in the context of a multi-commit. Learn more about multi-commits [in this guide](https://huggingface.co/docs/huggingface_hub/main/guides/upload)._ +""" + + +STEP_ID_REGEX = re.compile(r"- \[(?P[ |x])\].*(?P[a-fA-F0-9]{64})", flags=re.MULTILINE) + + +@experimental +def plan_multi_commits( + operations: Iterable[Union[CommitOperationAdd, CommitOperationDelete]], + max_operations_per_commit: int = 50, + max_upload_size_per_commit: int = 2 * 1024 * 1024 * 1024, +) -> Tuple[List[List[CommitOperationAdd]], List[List[CommitOperationDelete]]]: + """Split a list of operations in a list of commits to perform. + + Implementation follows a sub-optimal (yet simple) algorithm: + 1. Delete operations are grouped together by commits of maximum `max_operations_per_commits` operations. + 2. All additions exceeding `max_upload_size_per_commit` are committed 1 by 1. + 3. All remaining additions are grouped together and split each time the `max_operations_per_commit` or the + `max_upload_size_per_commit` limit is reached. + + We do not try to optimize the splitting to get the lowest number of commits as this is a NP-hard problem (see + [bin packing problem](https://en.wikipedia.org/wiki/Bin_packing_problem)). For our use case, it is not problematic + to use a sub-optimal solution so we favored an easy-to-explain implementation. + + Args: + operations (`List` of [`~hf_api.CommitOperation`]): + The list of operations to split into commits. + max_operations_per_commit (`int`): + Maximum number of operations in a single commit. Defaults to 50. + max_upload_size_per_commit (`int`): + Maximum size to upload (in bytes) in a single commit. Defaults to 2GB. Files bigger than this limit are + uploaded, 1 per commit. + + Returns: + `Tuple[List[List[CommitOperationAdd]], List[List[CommitOperationDelete]]]`: a tuple. First item is a list of + lists of [`CommitOperationAdd`] representing the addition commits to push. The second item is a list of lists + of [`CommitOperationDelete`] representing the deletion commits. + + + + `plan_multi_commits` is experimental. Its API and behavior is subject to change in the future without prior notice. + + + + Example: + ```python + >>> from huggingface_hub import HfApi, plan_multi_commits + >>> addition_commits, deletion_commits = plan_multi_commits( + ... operations=[ + ... CommitOperationAdd(...), + ... CommitOperationAdd(...), + ... CommitOperationDelete(...), + ... CommitOperationDelete(...), + ... CommitOperationAdd(...), + ... ], + ... ) + >>> HfApi().create_commits_on_pr( + ... repo_id="my-cool-model", + ... addition_commits=addition_commits, + ... deletion_commits=deletion_commits, + ... (...) + ... verbose=True, + ... ) + ``` + + + + The initial order of the operations is not guaranteed! All deletions will be performed before additions. If you are + not updating multiple times the same file, you are fine. + + + """ + addition_commits: List[List[CommitOperationAdd]] = [] + deletion_commits: List[List[CommitOperationDelete]] = [] + + additions: List[CommitOperationAdd] = [] + additions_size = 0 + deletions: List[CommitOperationDelete] = [] + for op in operations: + if isinstance(op, CommitOperationDelete): + # Group delete operations together + deletions.append(op) + if len(deletions) >= max_operations_per_commit: + deletion_commits.append(deletions) + deletions = [] + + elif op.upload_info.size >= max_upload_size_per_commit: + # Upload huge files 1 by 1 + addition_commits.append([op]) + + elif additions_size + op.upload_info.size < max_upload_size_per_commit: + # Group other additions and split if size limit is reached (either max_nb_files or max_upload_size) + additions.append(op) + additions_size += op.upload_info.size + + else: + addition_commits.append(additions) + additions = [op] + additions_size = op.upload_info.size + + if len(additions) >= max_operations_per_commit: + addition_commits.append(additions) + additions = [] + additions_size = 0 + + if len(additions) > 0: + addition_commits.append(additions) + if len(deletions) > 0: + deletion_commits.append(deletions) + + return addition_commits, deletion_commits + + +@dataclass +class MultiCommitStep: + """Dataclass containing a list of CommitOperation to commit at once. + + A [`MultiCommitStep`] is one atomic part of a [`MultiCommitStrategy`]. Each step is identified by its own + deterministic ID based on the list of commit operations (hexadecimal sha256). ID is persistent between re-runs if + the list of commits is kept the same. + """ + + operations: List[Union[CommitOperationAdd, CommitOperationDelete]] + + id: str = field(init=False) + completed: bool = False + + def __post_init__(self) -> None: + if len(self.operations) == 0: + raise ValueError("A MultiCommitStep must have at least 1 commit operation, got 0.") + + # Generate commit id + sha = sha256() + for op in self.operations: + if isinstance(op, CommitOperationAdd): + sha.update(b"ADD") + sha.update(op.path_in_repo.encode()) + sha.update(op.upload_info.sha256) + elif isinstance(op, CommitOperationDelete): + sha.update(b"DELETE") + sha.update(op.path_in_repo.encode()) + sha.update(str(op.is_folder).encode()) + else: + NotImplementedError() + self.id = sha.hexdigest() + + def __str__(self) -> str: + """Format a step for PR description. + + Formatting can be changed in the future as long as it is single line, starts with `- [ ]`/`- [x]` and contains + `self.id`. Must be able to match `STEP_ID_REGEX`. + """ + additions = [op for op in self.operations if isinstance(op, CommitOperationAdd)] + file_deletions = [op for op in self.operations if isinstance(op, CommitOperationDelete) and not op.is_folder] + folder_deletions = [op for op in self.operations if isinstance(op, CommitOperationDelete) and op.is_folder] + if len(additions) > 0: + return ( + f"- [{'x' if self.completed else ' '}] Upload {len(additions)} file(s) " + f"totalling {_format_size(sum(add.upload_info.size for add in additions))}" + f" ({self.id})" + ) + else: + return ( + f"- [{'x' if self.completed else ' '}] Delete {len(file_deletions)} file(s) and" + f" {len(folder_deletions)} folder(s) ({self.id})" + ) + + +@dataclass +class MultiCommitStrategy: + """Dataclass containing a list of [`MultiCommitStep`] to commit iteratively. + + A strategy is identified by its own deterministic ID based on the list of its steps (hexadecimal sha256). ID is + persistent between re-runs if the list of commits is kept the same. + """ + + addition_commits: List[MultiCommitStep] + deletion_commits: List[MultiCommitStep] + + id: str = field(init=False) + all_steps: Set[str] = field(init=False) + + def __post_init__(self) -> None: + self.all_steps = {step.id for step in self.addition_commits + self.deletion_commits} + if len(self.all_steps) < len(self.addition_commits) + len(self.deletion_commits): + raise ValueError("Got duplicate commits in MultiCommitStrategy. All commits must be unique.") + + if len(self.all_steps) == 0: + raise ValueError("A MultiCommitStrategy must have at least 1 commit, got 0.") + + # Generate strategy id + sha = sha256() + for step in self.addition_commits + self.deletion_commits: + sha.update("new step".encode()) + sha.update(step.id.encode()) + self.id = sha.hexdigest() + + +def multi_commit_create_pull_request( + api: "HfApi", + repo_id: str, + commit_message: str, + commit_description: Optional[str], + strategy: MultiCommitStrategy, + token: Optional[str], + repo_type: Optional[str], +) -> DiscussionWithDetails: + return api.create_pull_request( + repo_id=repo_id, + title=f"[WIP] {commit_message} (multi-commit {strategy.id})", + description=multi_commit_generate_comment( + commit_message=commit_message, commit_description=commit_description, strategy=strategy + ), + token=token, + repo_type=repo_type, + ) + + +def multi_commit_generate_comment( + commit_message: str, + commit_description: Optional[str], + strategy: MultiCommitStrategy, +) -> str: + return MULTI_COMMIT_PR_DESCRIPTION_TEMPLATE.format( + commit_message=commit_message, + commit_description=commit_description or "", + multi_commit_id=strategy.id, + multi_commit_strategy="\n".join( + str(commit) for commit in strategy.deletion_commits + strategy.addition_commits + ), + ) + + +def multi_commit_parse_pr_description(description: str) -> Set[str]: + return {match[1] for match in STEP_ID_REGEX.findall(description)} diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/_snapshot_download.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/_snapshot_download.py new file mode 100644 index 0000000000000000000000000000000000000000..cbf57ea23308a3a688c6dae75a603df82f24c156 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/_snapshot_download.py @@ -0,0 +1,327 @@ +import os +from pathlib import Path +from typing import Dict, List, Literal, Optional, Union + +import requests +from tqdm.auto import tqdm as base_tqdm +from tqdm.contrib.concurrent import thread_map + +from .constants import ( + DEFAULT_ETAG_TIMEOUT, + DEFAULT_REVISION, + HF_HUB_CACHE, + HF_HUB_ENABLE_HF_TRANSFER, + REPO_TYPES, +) +from .file_download import REGEX_COMMIT_HASH, hf_hub_download, repo_folder_name +from .hf_api import DatasetInfo, HfApi, ModelInfo, SpaceInfo +from .utils import ( + GatedRepoError, + LocalEntryNotFoundError, + OfflineModeIsEnabled, + RepositoryNotFoundError, + RevisionNotFoundError, + filter_repo_objects, + logging, + validate_hf_hub_args, +) +from .utils import tqdm as hf_tqdm + + +logger = logging.get_logger(__name__) + + +@validate_hf_hub_args +def snapshot_download( + repo_id: str, + *, + repo_type: Optional[str] = None, + revision: Optional[str] = None, + cache_dir: Union[str, Path, None] = None, + local_dir: Union[str, Path, None] = None, + local_dir_use_symlinks: Union[bool, Literal["auto"]] = "auto", + library_name: Optional[str] = None, + library_version: Optional[str] = None, + user_agent: Optional[Union[Dict, str]] = None, + proxies: Optional[Dict] = None, + etag_timeout: float = DEFAULT_ETAG_TIMEOUT, + resume_download: bool = False, + force_download: bool = False, + token: Optional[Union[bool, str]] = None, + local_files_only: bool = False, + allow_patterns: Optional[Union[List[str], str]] = None, + ignore_patterns: Optional[Union[List[str], str]] = None, + max_workers: int = 8, + tqdm_class: Optional[base_tqdm] = None, + headers: Optional[Dict[str, str]] = None, + endpoint: Optional[str] = None, +) -> str: + """Download repo files. + + Download a whole snapshot of a repo's files at the specified revision. This is useful when you want all files from + a repo, because you don't know which ones you will need a priori. All files are nested inside a folder in order + to keep their actual filename relative to that folder. You can also filter which files to download using + `allow_patterns` and `ignore_patterns`. + + If `local_dir` is provided, the file structure from the repo will be replicated in this location. You can configure + how you want to move those files: + - If `local_dir_use_symlinks="auto"` (default), files are downloaded and stored in the cache directory as blob + files. Small files (<5MB) are duplicated in `local_dir` while a symlink is created for bigger files. The goal + is to be able to manually edit and save small files without corrupting the cache while saving disk space for + binary files. The 5MB threshold can be configured with the `HF_HUB_LOCAL_DIR_AUTO_SYMLINK_THRESHOLD` + environment variable. + - If `local_dir_use_symlinks=True`, files are downloaded, stored in the cache directory and symlinked in `local_dir`. + This is optimal in term of disk usage but files must not be manually edited. + - If `local_dir_use_symlinks=False` and the blob files exist in the cache directory, they are duplicated in the + local dir. This means disk usage is not optimized. + - Finally, if `local_dir_use_symlinks=False` and the blob files do not exist in the cache directory, then the + files are downloaded and directly placed under `local_dir`. This means if you need to download them again later, + they will be re-downloaded entirely. + + An alternative would be to clone the repo but this requires git and git-lfs to be installed and properly + configured. It is also not possible to filter which files to download when cloning a repository using git. + + Args: + repo_id (`str`): + A user or an organization name and a repo name separated by a `/`. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if downloading from a dataset or space, + `None` or `"model"` if downloading from a model. Default is `None`. + revision (`str`, *optional*): + An optional Git revision id which can be a branch name, a tag, or a + commit hash. + cache_dir (`str`, `Path`, *optional*): + Path to the folder where cached files are stored. + local_dir (`str` or `Path`, *optional*): + If provided, the downloaded files will be placed under this directory, either as symlinks (default) or + regular files (see description for more details). + local_dir_use_symlinks (`"auto"` or `bool`, defaults to `"auto"`): + To be used with `local_dir`. If set to "auto", the cache directory will be used and the file will be either + duplicated or symlinked to the local directory depending on its size. It set to `True`, a symlink will be + created, no matter the file size. If set to `False`, the file will either be duplicated from cache (if + already exists) or downloaded from the Hub and not cached. See description for more details. + library_name (`str`, *optional*): + The name of the library to which the object corresponds. + library_version (`str`, *optional*): + The version of the library. + user_agent (`str`, `dict`, *optional*): + The user-agent info in the form of a dictionary or a string. + proxies (`dict`, *optional*): + Dictionary mapping protocol to the URL of the proxy passed to + `requests.request`. + etag_timeout (`float`, *optional*, defaults to `10`): + When fetching ETag, how many seconds to wait for the server to send + data before giving up which is passed to `requests.request`. + resume_download (`bool`, *optional*, defaults to `False): + If `True`, resume a previously interrupted download. + force_download (`bool`, *optional*, defaults to `False`): + Whether the file should be downloaded even if it already exists in the local cache. + token (`str`, `bool`, *optional*): + A token to be used for the download. + - If `True`, the token is read from the HuggingFace config + folder. + - If a string, it's used as the authentication token. + headers (`dict`, *optional*): + Additional headers to include in the request. Those headers take precedence over the others. + local_files_only (`bool`, *optional*, defaults to `False`): + If `True`, avoid downloading the file and return the path to the + local cached file if it exists. + allow_patterns (`List[str]` or `str`, *optional*): + If provided, only files matching at least one pattern are downloaded. + ignore_patterns (`List[str]` or `str`, *optional*): + If provided, files matching any of the patterns are not downloaded. + max_workers (`int`, *optional*): + Number of concurrent threads to download files (1 thread = 1 file download). + Defaults to 8. + tqdm_class (`tqdm`, *optional*): + If provided, overwrites the default behavior for the progress bar. Passed + argument must inherit from `tqdm.auto.tqdm` or at least mimic its behavior. + Note that the `tqdm_class` is not passed to each individual download. + Defaults to the custom HF progress bar that can be disabled by setting + `HF_HUB_DISABLE_PROGRESS_BARS` environment variable. + + Returns: + Local folder path (string) of repo snapshot + + + + Raises the following errors: + + - [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError) + if `token=True` and the token cannot be found. + - [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError) if + ETag cannot be determined. + - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + if some parameter value is invalid + + + """ + if cache_dir is None: + cache_dir = HF_HUB_CACHE + if revision is None: + revision = DEFAULT_REVISION + if isinstance(cache_dir, Path): + cache_dir = str(cache_dir) + + if repo_type is None: + repo_type = "model" + if repo_type not in REPO_TYPES: + raise ValueError(f"Invalid repo type: {repo_type}. Accepted repo types are: {str(REPO_TYPES)}") + + storage_folder = os.path.join(cache_dir, repo_folder_name(repo_id=repo_id, repo_type=repo_type)) + + repo_info: Union[ModelInfo, DatasetInfo, SpaceInfo, None] = None + api_call_error: Optional[Exception] = None + if not local_files_only: + # try/except logic to handle different errors => taken from `hf_hub_download` + try: + # if we have internet connection we want to list files to download + api = HfApi( + library_name=library_name, + library_version=library_version, + user_agent=user_agent, + endpoint=endpoint, + headers=headers, + ) + repo_info = api.repo_info(repo_id=repo_id, repo_type=repo_type, revision=revision, token=token) + except (requests.exceptions.SSLError, requests.exceptions.ProxyError): + # Actually raise for those subclasses of ConnectionError + raise + except ( + requests.exceptions.ConnectionError, + requests.exceptions.Timeout, + OfflineModeIsEnabled, + ) as error: + # Internet connection is down + # => will try to use local files only + api_call_error = error + pass + except RevisionNotFoundError: + # The repo was found but the revision doesn't exist on the Hub (never existed or got deleted) + raise + except requests.HTTPError as error: + # Multiple reasons for an http error: + # - Repository is private and invalid/missing token sent + # - Repository is gated and invalid/missing token sent + # - Hub is down (error 500 or 504) + # => let's switch to 'local_files_only=True' to check if the files are already cached. + # (if it's not the case, the error will be re-raised) + api_call_error = error + pass + + # At this stage, if `repo_info` is None it means either: + # - internet connection is down + # - internet connection is deactivated (local_files_only=True or HF_HUB_OFFLINE=True) + # - repo is private/gated and invalid/missing token sent + # - Hub is down + # => let's look if we can find the appropriate folder in the cache: + # - if the specified revision is a commit hash, look inside "snapshots". + # - f the specified revision is a branch or tag, look inside "refs". + if repo_info is None: + # Try to get which commit hash corresponds to the specified revision + commit_hash = None + if REGEX_COMMIT_HASH.match(revision): + commit_hash = revision + else: + ref_path = os.path.join(storage_folder, "refs", revision) + if os.path.exists(ref_path): + # retrieve commit_hash from refs file + with open(ref_path) as f: + commit_hash = f.read() + + # Try to locate snapshot folder for this commit hash + if commit_hash is not None: + snapshot_folder = os.path.join(storage_folder, "snapshots", commit_hash) + if os.path.exists(snapshot_folder): + # Snapshot folder exists => let's return it + # (but we can't check if all the files are actually there) + return snapshot_folder + + # If we couldn't find the appropriate folder on disk, raise an error. + if local_files_only: + raise LocalEntryNotFoundError( + "Cannot find an appropriate cached snapshot folder for the specified revision on the local disk and " + "outgoing traffic has been disabled. To enable repo look-ups and downloads online, pass " + "'local_files_only=False' as input." + ) + elif isinstance(api_call_error, OfflineModeIsEnabled): + raise LocalEntryNotFoundError( + "Cannot find an appropriate cached snapshot folder for the specified revision on the local disk and " + "outgoing traffic has been disabled. To enable repo look-ups and downloads online, set " + "'HF_HUB_OFFLINE=0' as environment variable." + ) from api_call_error + elif isinstance(api_call_error, RepositoryNotFoundError) or isinstance(api_call_error, GatedRepoError): + # Repo not found => let's raise the actual error + raise api_call_error + else: + # Otherwise: most likely a connection issue or Hub downtime => let's warn the user + raise LocalEntryNotFoundError( + "An error happened while trying to locate the files on the Hub and we cannot find the appropriate" + " snapshot folder for the specified revision on the local disk. Please check your internet connection" + " and try again." + ) from api_call_error + + # At this stage, internet connection is up and running + # => let's download the files! + assert repo_info.sha is not None, "Repo info returned from server must have a revision sha." + assert repo_info.siblings is not None, "Repo info returned from server must have a siblings list." + filtered_repo_files = list( + filter_repo_objects( + items=[f.rfilename for f in repo_info.siblings], + allow_patterns=allow_patterns, + ignore_patterns=ignore_patterns, + ) + ) + commit_hash = repo_info.sha + snapshot_folder = os.path.join(storage_folder, "snapshots", commit_hash) + # if passed revision is not identical to commit_hash + # then revision has to be a branch name or tag name. + # In that case store a ref. + if revision != commit_hash: + ref_path = os.path.join(storage_folder, "refs", revision) + os.makedirs(os.path.dirname(ref_path), exist_ok=True) + with open(ref_path, "w") as f: + f.write(commit_hash) + + # we pass the commit_hash to hf_hub_download + # so no network call happens if we already + # have the file locally. + def _inner_hf_hub_download(repo_file: str): + return hf_hub_download( + repo_id, + filename=repo_file, + repo_type=repo_type, + revision=commit_hash, + endpoint=endpoint, + cache_dir=cache_dir, + local_dir=local_dir, + local_dir_use_symlinks=local_dir_use_symlinks, + library_name=library_name, + library_version=library_version, + user_agent=user_agent, + proxies=proxies, + etag_timeout=etag_timeout, + resume_download=resume_download, + force_download=force_download, + token=token, + headers=headers, + ) + + if HF_HUB_ENABLE_HF_TRANSFER: + # when using hf_transfer we don't want extra parallelism + # from the one hf_transfer provides + for file in filtered_repo_files: + _inner_hf_hub_download(file) + else: + thread_map( + _inner_hf_hub_download, + filtered_repo_files, + desc=f"Fetching {len(filtered_repo_files)} files", + max_workers=max_workers, + # User can use its own tqdm class or the default one from `huggingface_hub.utils` + tqdm_class=tqdm_class or hf_tqdm, + ) + + if local_dir is not None: + return str(os.path.realpath(local_dir)) + return snapshot_folder diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/_space_api.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/_space_api.py new file mode 100644 index 0000000000000000000000000000000000000000..da70bd05a66a96b450f04eab9171aa9b5f7420c7 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/_space_api.py @@ -0,0 +1,155 @@ +# coding=utf-8 +# Copyright 2019-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from dataclasses import dataclass +from datetime import datetime +from enum import Enum +from typing import Dict, Optional + +from huggingface_hub.utils import parse_datetime + + +class SpaceStage(str, Enum): + """ + Enumeration of possible stage of a Space on the Hub. + + Value can be compared to a string: + ```py + assert SpaceStage.BUILDING == "BUILDING" + ``` + + Taken from https://github.com/huggingface/moon-landing/blob/main/server/repo_types/SpaceInfo.ts#L61 (private url). + """ + + # Copied from moon-landing > server > repo_types > SpaceInfo.ts (private repo) + NO_APP_FILE = "NO_APP_FILE" + CONFIG_ERROR = "CONFIG_ERROR" + BUILDING = "BUILDING" + BUILD_ERROR = "BUILD_ERROR" + RUNNING = "RUNNING" + RUNNING_BUILDING = "RUNNING_BUILDING" + RUNTIME_ERROR = "RUNTIME_ERROR" + DELETING = "DELETING" + STOPPED = "STOPPED" + PAUSED = "PAUSED" + + +class SpaceHardware(str, Enum): + """ + Enumeration of hardwares available to run your Space on the Hub. + + Value can be compared to a string: + ```py + assert SpaceHardware.CPU_BASIC == "cpu-basic" + ``` + + Taken from https://github.com/huggingface/moon-landing/blob/main/server/repo_types/SpaceInfo.ts#L73 (private url). + """ + + CPU_BASIC = "cpu-basic" + CPU_UPGRADE = "cpu-upgrade" + T4_SMALL = "t4-small" + T4_MEDIUM = "t4-medium" + ZERO_A10G = "zero-a10g" + A10G_SMALL = "a10g-small" + A10G_LARGE = "a10g-large" + A10G_LARGEX2 = "a10g-largex2" + A10G_LARGEX4 = "a10g-largex4" + A100_LARGE = "a100-large" + + +class SpaceStorage(str, Enum): + """ + Enumeration of persistent storage available for your Space on the Hub. + + Value can be compared to a string: + ```py + assert SpaceStorage.SMALL == "small" + ``` + + Taken from https://github.com/huggingface/moon-landing/blob/main/server/repo_types/SpaceHardwareFlavor.ts#L24 (private url). + """ + + SMALL = "small" + MEDIUM = "medium" + LARGE = "large" + + +@dataclass +class SpaceRuntime: + """ + Contains information about the current runtime of a Space. + + Args: + stage (`str`): + Current stage of the space. Example: RUNNING. + hardware (`str` or `None`): + Current hardware of the space. Example: "cpu-basic". Can be `None` if Space + is `BUILDING` for the first time. + requested_hardware (`str` or `None`): + Requested hardware. Can be different than `hardware` especially if the request + has just been made. Example: "t4-medium". Can be `None` if no hardware has + been requested yet. + sleep_time (`int` or `None`): + Number of seconds the Space will be kept alive after the last request. By default (if value is `None`), the + Space will never go to sleep if it's running on an upgraded hardware, while it will go to sleep after 48 + hours on a free 'cpu-basic' hardware. For more details, see https://huggingface.co/docs/hub/spaces-gpus#sleep-time. + raw (`dict`): + Raw response from the server. Contains more information about the Space + runtime like number of replicas, number of cpu, memory size,... + """ + + stage: SpaceStage + hardware: Optional[SpaceHardware] + requested_hardware: Optional[SpaceHardware] + sleep_time: Optional[int] + storage: Optional[SpaceStorage] + raw: Dict + + def __init__(self, data: Dict) -> None: + self.stage = data["stage"] + self.hardware = data.get("hardware", {}).get("current") + self.requested_hardware = data.get("hardware", {}).get("requested") + self.sleep_time = data.get("gcTimeout") + self.storage = data.get("storage") + self.raw = data + + +@dataclass +class SpaceVariable: + """ + Contains information about the current variables of a Space. + + Args: + key (`str`): + Variable key. Example: `"MODEL_REPO_ID"` + value (`str`): + Variable value. Example: `"the_model_repo_id"`. + description (`str` or None): + Description of the variable. Example: `"Model Repo ID of the implemented model"`. + updatedAt (`datetime` or None): + datetime of the last update of the variable (if the variable has been updated at least once). + """ + + key: str + value: str + description: Optional[str] + updated_at: Optional[datetime] + + def __init__(self, key: str, values: Dict) -> None: + self.key = key + self.value = values["value"] + self.description = values.get("description") + updated_at = values.get("updatedAt") + self.updated_at = parse_datetime(updated_at) if updated_at is not None else None diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/_webhooks_payload.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/_webhooks_payload.py new file mode 100644 index 0000000000000000000000000000000000000000..6ea669fe09a82252cb788ad390066a894cedf0f5 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/_webhooks_payload.py @@ -0,0 +1,116 @@ +# coding=utf-8 +# Copyright 2023-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contains data structures to parse the webhooks payload.""" + +from typing import List, Literal, Optional + +from pydantic import BaseModel + + +# This is an adaptation of the ReportV3 interface implemented in moon-landing. V0, V1 and V2 have been ignored as they +# are not in used anymore. To keep in sync when format is updated in +# https://github.com/huggingface/moon-landing/blob/main/server/lib/HFWebhooks.ts (internal link). + + +WebhookEvent_T = Literal[ + "create", + "delete", + "move", + "update", +] +RepoChangeEvent_T = Literal[ + "add", + "move", + "remove", + "update", +] +RepoType_T = Literal[ + "dataset", + "model", + "space", +] +DiscussionStatus_T = Literal[ + "closed", + "draft", + "open", + "merged", +] +SupportedWebhookVersion = Literal[3] + + +class ObjectId(BaseModel): + id: str + + +class WebhookPayloadUrl(BaseModel): + web: str + api: Optional[str] = None + + +class WebhookPayloadMovedTo(BaseModel): + name: str + owner: ObjectId + + +class WebhookPayloadWebhook(ObjectId): + version: SupportedWebhookVersion + + +class WebhookPayloadEvent(BaseModel): + action: WebhookEvent_T + scope: str + + +class WebhookPayloadDiscussionChanges(BaseModel): + base: str + mergeCommitId: Optional[str] = None + + +class WebhookPayloadComment(ObjectId): + author: ObjectId + hidden: bool + content: Optional[str] = None + url: WebhookPayloadUrl + + +class WebhookPayloadDiscussion(ObjectId): + num: int + author: ObjectId + url: WebhookPayloadUrl + title: str + isPullRequest: bool + status: DiscussionStatus_T + changes: Optional[WebhookPayloadDiscussionChanges] = None + pinned: Optional[bool] = None + + +class WebhookPayloadRepo(ObjectId): + owner: ObjectId + head_sha: Optional[str] = None + name: str + private: bool + subdomain: Optional[str] = None + tags: Optional[List[str]] = None + type: Literal["dataset", "model", "space"] + url: WebhookPayloadUrl + + +class WebhookPayload(BaseModel): + event: WebhookPayloadEvent + repo: WebhookPayloadRepo + discussion: Optional[WebhookPayloadDiscussion] = None + comment: Optional[WebhookPayloadComment] = None + webhook: WebhookPayloadWebhook + movedTo: Optional[WebhookPayloadMovedTo] = None diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/community.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/community.py new file mode 100644 index 0000000000000000000000000000000000000000..387b0cc12174cafd9f4080d05cbc748e59a51b81 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/community.py @@ -0,0 +1,355 @@ +""" +Data structures to interact with Discussions and Pull Requests on the Hub. + +See [the Discussions and Pull Requests guide](https://huggingface.co/docs/hub/repositories-pull-requests-discussions) +for more information on Pull Requests, Discussions, and the community tab. +""" + +from dataclasses import dataclass +from datetime import datetime +from typing import List, Literal, Optional, Union + +from .constants import REPO_TYPE_MODEL +from .utils import parse_datetime + + +DiscussionStatus = Literal["open", "closed", "merged", "draft"] + + +@dataclass +class Discussion: + """ + A Discussion or Pull Request on the Hub. + + This dataclass is not intended to be instantiated directly. + + Attributes: + title (`str`): + The title of the Discussion / Pull Request + status (`str`): + The status of the Discussion / Pull Request. + It must be one of: + * `"open"` + * `"closed"` + * `"merged"` (only for Pull Requests ) + * `"draft"` (only for Pull Requests ) + num (`int`): + The number of the Discussion / Pull Request. + repo_id (`str`): + The id (`"{namespace}/{repo_name}"`) of the repo on which + the Discussion / Pull Request was open. + repo_type (`str`): + The type of the repo on which the Discussion / Pull Request was open. + Possible values are: `"model"`, `"dataset"`, `"space"`. + author (`str`): + The username of the Discussion / Pull Request author. + Can be `"deleted"` if the user has been deleted since. + is_pull_request (`bool`): + Whether or not this is a Pull Request. + created_at (`datetime`): + The `datetime` of creation of the Discussion / Pull Request. + endpoint (`str`): + Endpoint of the Hub. Default is https://huggingface.co. + git_reference (`str`, *optional*): + (property) Git reference to which changes can be pushed if this is a Pull Request, `None` otherwise. + url (`str`): + (property) URL of the discussion on the Hub. + """ + + title: str + status: DiscussionStatus + num: int + repo_id: str + repo_type: str + author: str + is_pull_request: bool + created_at: datetime + endpoint: str + + @property + def git_reference(self) -> Optional[str]: + """ + If this is a Pull Request , returns the git reference to which changes can be pushed. + Returns `None` otherwise. + """ + if self.is_pull_request: + return f"refs/pr/{self.num}" + return None + + @property + def url(self) -> str: + """Returns the URL of the discussion on the Hub.""" + if self.repo_type is None or self.repo_type == REPO_TYPE_MODEL: + return f"{self.endpoint}/{self.repo_id}/discussions/{self.num}" + return f"{self.endpoint}/{self.repo_type}s/{self.repo_id}/discussions/{self.num}" + + +@dataclass +class DiscussionWithDetails(Discussion): + """ + Subclass of [`Discussion`]. + + Attributes: + title (`str`): + The title of the Discussion / Pull Request + status (`str`): + The status of the Discussion / Pull Request. + It can be one of: + * `"open"` + * `"closed"` + * `"merged"` (only for Pull Requests ) + * `"draft"` (only for Pull Requests ) + num (`int`): + The number of the Discussion / Pull Request. + repo_id (`str`): + The id (`"{namespace}/{repo_name}"`) of the repo on which + the Discussion / Pull Request was open. + repo_type (`str`): + The type of the repo on which the Discussion / Pull Request was open. + Possible values are: `"model"`, `"dataset"`, `"space"`. + author (`str`): + The username of the Discussion / Pull Request author. + Can be `"deleted"` if the user has been deleted since. + is_pull_request (`bool`): + Whether or not this is a Pull Request. + created_at (`datetime`): + The `datetime` of creation of the Discussion / Pull Request. + events (`list` of [`DiscussionEvent`]) + The list of [`DiscussionEvents`] in this Discussion or Pull Request. + conflicting_files (`Union[List[str], bool, None]`, *optional*): + A list of conflicting files if this is a Pull Request. + `None` if `self.is_pull_request` is `False`. + `True` if there are conflicting files but the list can't be retrieved. + target_branch (`str`, *optional*): + The branch into which changes are to be merged if this is a + Pull Request . `None` if `self.is_pull_request` is `False`. + merge_commit_oid (`str`, *optional*): + If this is a merged Pull Request , this is set to the OID / SHA of + the merge commit, `None` otherwise. + diff (`str`, *optional*): + The git diff if this is a Pull Request , `None` otherwise. + endpoint (`str`): + Endpoint of the Hub. Default is https://huggingface.co. + git_reference (`str`, *optional*): + (property) Git reference to which changes can be pushed if this is a Pull Request, `None` otherwise. + url (`str`): + (property) URL of the discussion on the Hub. + """ + + events: List["DiscussionEvent"] + conflicting_files: Union[List[str], bool, None] + target_branch: Optional[str] + merge_commit_oid: Optional[str] + diff: Optional[str] + + +@dataclass +class DiscussionEvent: + """ + An event in a Discussion or Pull Request. + + Use concrete classes: + * [`DiscussionComment`] + * [`DiscussionStatusChange`] + * [`DiscussionCommit`] + * [`DiscussionTitleChange`] + + Attributes: + id (`str`): + The ID of the event. An hexadecimal string. + type (`str`): + The type of the event. + created_at (`datetime`): + A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime) + object holding the creation timestamp for the event. + author (`str`): + The username of the Discussion / Pull Request author. + Can be `"deleted"` if the user has been deleted since. + """ + + id: str + type: str + created_at: datetime + author: str + + _event: dict + """Stores the original event data, in case we need to access it later.""" + + +@dataclass +class DiscussionComment(DiscussionEvent): + """A comment in a Discussion / Pull Request. + + Subclass of [`DiscussionEvent`]. + + + Attributes: + id (`str`): + The ID of the event. An hexadecimal string. + type (`str`): + The type of the event. + created_at (`datetime`): + A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime) + object holding the creation timestamp for the event. + author (`str`): + The username of the Discussion / Pull Request author. + Can be `"deleted"` if the user has been deleted since. + content (`str`): + The raw markdown content of the comment. Mentions, links and images are not rendered. + edited (`bool`): + Whether or not this comment has been edited. + hidden (`bool`): + Whether or not this comment has been hidden. + """ + + content: str + edited: bool + hidden: bool + + @property + def rendered(self) -> str: + """The rendered comment, as a HTML string""" + return self._event["data"]["latest"]["html"] + + @property + def last_edited_at(self) -> datetime: + """The last edit time, as a `datetime` object.""" + return parse_datetime(self._event["data"]["latest"]["updatedAt"]) + + @property + def last_edited_by(self) -> str: + """The last edit time, as a `datetime` object.""" + return self._event["data"]["latest"].get("author", {}).get("name", "deleted") + + @property + def edit_history(self) -> List[dict]: + """The edit history of the comment""" + return self._event["data"]["history"] + + @property + def number_of_edits(self) -> int: + return len(self.edit_history) + + +@dataclass +class DiscussionStatusChange(DiscussionEvent): + """A change of status in a Discussion / Pull Request. + + Subclass of [`DiscussionEvent`]. + + Attributes: + id (`str`): + The ID of the event. An hexadecimal string. + type (`str`): + The type of the event. + created_at (`datetime`): + A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime) + object holding the creation timestamp for the event. + author (`str`): + The username of the Discussion / Pull Request author. + Can be `"deleted"` if the user has been deleted since. + new_status (`str`): + The status of the Discussion / Pull Request after the change. + It can be one of: + * `"open"` + * `"closed"` + * `"merged"` (only for Pull Requests ) + """ + + new_status: str + + +@dataclass +class DiscussionCommit(DiscussionEvent): + """A commit in a Pull Request. + + Subclass of [`DiscussionEvent`]. + + Attributes: + id (`str`): + The ID of the event. An hexadecimal string. + type (`str`): + The type of the event. + created_at (`datetime`): + A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime) + object holding the creation timestamp for the event. + author (`str`): + The username of the Discussion / Pull Request author. + Can be `"deleted"` if the user has been deleted since. + summary (`str`): + The summary of the commit. + oid (`str`): + The OID / SHA of the commit, as a hexadecimal string. + """ + + summary: str + oid: str + + +@dataclass +class DiscussionTitleChange(DiscussionEvent): + """A rename event in a Discussion / Pull Request. + + Subclass of [`DiscussionEvent`]. + + Attributes: + id (`str`): + The ID of the event. An hexadecimal string. + type (`str`): + The type of the event. + created_at (`datetime`): + A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime) + object holding the creation timestamp for the event. + author (`str`): + The username of the Discussion / Pull Request author. + Can be `"deleted"` if the user has been deleted since. + old_title (`str`): + The previous title for the Discussion / Pull Request. + new_title (`str`): + The new title. + """ + + old_title: str + new_title: str + + +def deserialize_event(event: dict) -> DiscussionEvent: + """Instantiates a [`DiscussionEvent`] from a dict""" + event_id: str = event["id"] + event_type: str = event["type"] + created_at = parse_datetime(event["createdAt"]) + + common_args = dict( + id=event_id, + type=event_type, + created_at=created_at, + author=event.get("author", {}).get("name", "deleted"), + _event=event, + ) + + if event_type == "comment": + return DiscussionComment( + **common_args, + edited=event["data"]["edited"], + hidden=event["data"]["hidden"], + content=event["data"]["latest"]["raw"], + ) + if event_type == "status-change": + return DiscussionStatusChange( + **common_args, + new_status=event["data"]["status"], + ) + if event_type == "commit": + return DiscussionCommit( + **common_args, + summary=event["data"]["subject"], + oid=event["data"]["oid"], + ) + if event_type == "title-change": + return DiscussionTitleChange( + **common_args, + old_title=event["data"]["from"], + new_title=event["data"]["to"], + ) + + return DiscussionEvent(**common_args) diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/constants.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..ddebb6258078e21aec93f9a11e062d44620db2c1 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/constants.py @@ -0,0 +1,215 @@ +import os +import re +import typing +from typing import Literal, Optional, Tuple + + +# Possible values for env variables + + +ENV_VARS_TRUE_VALUES = {"1", "ON", "YES", "TRUE"} +ENV_VARS_TRUE_AND_AUTO_VALUES = ENV_VARS_TRUE_VALUES.union({"AUTO"}) + + +def _is_true(value: Optional[str]) -> bool: + if value is None: + return False + return value.upper() in ENV_VARS_TRUE_VALUES + + +def _as_int(value: Optional[str]) -> Optional[int]: + if value is None: + return None + return int(value) + + +# Constants for file downloads + +PYTORCH_WEIGHTS_NAME = "pytorch_model.bin" +TF2_WEIGHTS_NAME = "tf_model.h5" +TF_WEIGHTS_NAME = "model.ckpt" +FLAX_WEIGHTS_NAME = "flax_model.msgpack" +CONFIG_NAME = "config.json" +REPOCARD_NAME = "README.md" +DEFAULT_ETAG_TIMEOUT = 10 +DEFAULT_DOWNLOAD_TIMEOUT = 10 +DEFAULT_REQUEST_TIMEOUT = 10 +DOWNLOAD_CHUNK_SIZE = 10 * 1024 * 1024 +HF_TRANSFER_CONCURRENCY = 100 + +# Constants for safetensors repos + +SAFETENSORS_SINGLE_FILE = "model.safetensors" +SAFETENSORS_INDEX_FILE = "model.safetensors.index.json" +SAFETENSORS_MAX_HEADER_LENGTH = 25_000_000 + +# Git-related constants + +DEFAULT_REVISION = "main" +REGEX_COMMIT_OID = re.compile(r"[A-Fa-f0-9]{5,40}") + +HUGGINGFACE_CO_URL_HOME = "https://huggingface.co/" + +_staging_mode = _is_true(os.environ.get("HUGGINGFACE_CO_STAGING")) + +_HF_DEFAULT_ENDPOINT = "https://huggingface.co" +_HF_DEFAULT_STAGING_ENDPOINT = "https://hub-ci.huggingface.co" +ENDPOINT = os.getenv("HF_ENDPOINT") or (_HF_DEFAULT_STAGING_ENDPOINT if _staging_mode else _HF_DEFAULT_ENDPOINT) + +HUGGINGFACE_CO_URL_TEMPLATE = ENDPOINT + "/{repo_id}/resolve/{revision}/{filename}" +HUGGINGFACE_HEADER_X_REPO_COMMIT = "X-Repo-Commit" +HUGGINGFACE_HEADER_X_LINKED_ETAG = "X-Linked-Etag" +HUGGINGFACE_HEADER_X_LINKED_SIZE = "X-Linked-Size" + +INFERENCE_ENDPOINT = os.environ.get("HF_INFERENCE_ENDPOINT", "https://api-inference.huggingface.co") + +# See https://huggingface.co/docs/inference-endpoints/index +INFERENCE_ENDPOINTS_ENDPOINT = "https://api.endpoints.huggingface.cloud/v2" + + +REPO_ID_SEPARATOR = "--" +# ^ this substring is not allowed in repo_ids on hf.co +# and is the canonical one we use for serialization of repo ids elsewhere. + + +REPO_TYPE_DATASET = "dataset" +REPO_TYPE_SPACE = "space" +REPO_TYPE_MODEL = "model" +REPO_TYPES = [None, REPO_TYPE_MODEL, REPO_TYPE_DATASET, REPO_TYPE_SPACE] +SPACES_SDK_TYPES = ["gradio", "streamlit", "docker", "static"] + +REPO_TYPES_URL_PREFIXES = { + REPO_TYPE_DATASET: "datasets/", + REPO_TYPE_SPACE: "spaces/", +} +REPO_TYPES_MAPPING = { + "datasets": REPO_TYPE_DATASET, + "spaces": REPO_TYPE_SPACE, + "models": REPO_TYPE_MODEL, +} + +DiscussionTypeFilter = Literal["all", "discussion", "pull_request"] +DISCUSSION_TYPES: Tuple[DiscussionTypeFilter, ...] = typing.get_args(DiscussionTypeFilter) +DiscussionStatusFilter = Literal["all", "open", "closed"] +DISCUSSION_STATUS: Tuple[DiscussionTypeFilter, ...] = typing.get_args(DiscussionStatusFilter) + +# default cache +default_home = os.path.join(os.path.expanduser("~"), ".cache") +HF_HOME = os.path.expanduser( + os.getenv( + "HF_HOME", + os.path.join(os.getenv("XDG_CACHE_HOME", default_home), "huggingface"), + ) +) +hf_cache_home = HF_HOME # for backward compatibility. TODO: remove this in 1.0.0 + +default_cache_path = os.path.join(HF_HOME, "hub") +default_assets_cache_path = os.path.join(HF_HOME, "assets") + +# Legacy env variables +HUGGINGFACE_HUB_CACHE = os.getenv("HUGGINGFACE_HUB_CACHE", default_cache_path) +HUGGINGFACE_ASSETS_CACHE = os.getenv("HUGGINGFACE_ASSETS_CACHE", default_assets_cache_path) + +# New env variables +HF_HUB_CACHE = os.getenv("HF_HUB_CACHE", HUGGINGFACE_HUB_CACHE) +HF_ASSETS_CACHE = os.getenv("HF_ASSETS_CACHE", HUGGINGFACE_ASSETS_CACHE) + +HF_HUB_OFFLINE = _is_true(os.environ.get("HF_HUB_OFFLINE") or os.environ.get("TRANSFORMERS_OFFLINE")) + +# Opt-out from telemetry requests +HF_HUB_DISABLE_TELEMETRY = ( + _is_true(os.environ.get("HF_HUB_DISABLE_TELEMETRY")) # HF-specific env variable + or _is_true(os.environ.get("DISABLE_TELEMETRY")) + or _is_true(os.environ.get("DO_NOT_TRACK")) # https://consoledonottrack.com/ +) + +# In the past, token was stored in a hardcoded location +# `_OLD_HF_TOKEN_PATH` is deprecated and will be removed "at some point". +# See https://github.com/huggingface/huggingface_hub/issues/1232 +_OLD_HF_TOKEN_PATH = os.path.expanduser("~/.huggingface/token") +HF_TOKEN_PATH = os.path.join(HF_HOME, "token") + + +if _staging_mode: + # In staging mode, we use a different cache to ensure we don't mix up production and staging data or tokens + _staging_home = os.path.join(os.path.expanduser("~"), ".cache", "huggingface_staging") + HUGGINGFACE_HUB_CACHE = os.path.join(_staging_home, "hub") + _OLD_HF_TOKEN_PATH = os.path.join(_staging_home, "_old_token") + HF_TOKEN_PATH = os.path.join(_staging_home, "token") + +# Here, `True` will disable progress bars globally without possibility of enabling it +# programmatically. `False` will enable them without possibility of disabling them. +# If environment variable is not set (None), then the user is free to enable/disable +# them programmatically. +# TL;DR: env variable has priority over code +__HF_HUB_DISABLE_PROGRESS_BARS = os.environ.get("HF_HUB_DISABLE_PROGRESS_BARS") +HF_HUB_DISABLE_PROGRESS_BARS: Optional[bool] = ( + _is_true(__HF_HUB_DISABLE_PROGRESS_BARS) if __HF_HUB_DISABLE_PROGRESS_BARS is not None else None +) + +# Disable warning on machines that do not support symlinks (e.g. Windows non-developer) +HF_HUB_DISABLE_SYMLINKS_WARNING: bool = _is_true(os.environ.get("HF_HUB_DISABLE_SYMLINKS_WARNING")) + +# Disable warning when using experimental features +HF_HUB_DISABLE_EXPERIMENTAL_WARNING: bool = _is_true(os.environ.get("HF_HUB_DISABLE_EXPERIMENTAL_WARNING")) + +# Disable sending the cached token by default is all HTTP requests to the Hub +HF_HUB_DISABLE_IMPLICIT_TOKEN: bool = _is_true(os.environ.get("HF_HUB_DISABLE_IMPLICIT_TOKEN")) + +# Enable fast-download using external dependency "hf_transfer" +# See: +# - https://pypi.org/project/hf-transfer/ +# - https://github.com/huggingface/hf_transfer (private) +HF_HUB_ENABLE_HF_TRANSFER: bool = _is_true(os.environ.get("HF_HUB_ENABLE_HF_TRANSFER")) + + +# Used if download to `local_dir` and `local_dir_use_symlinks="auto"` +# Files smaller than 5MB are copy-pasted while bigger files are symlinked. The idea is to save disk-usage by symlinking +# huge files (i.e. LFS files most of the time) while allowing small files to be manually edited in local folder. +HF_HUB_LOCAL_DIR_AUTO_SYMLINK_THRESHOLD: int = ( + _as_int(os.environ.get("HF_HUB_LOCAL_DIR_AUTO_SYMLINK_THRESHOLD")) or 5 * 1024 * 1024 +) + +# Used to override the etag timeout on a system level +HF_HUB_ETAG_TIMEOUT: int = _as_int(os.environ.get("HF_HUB_ETAG_TIMEOUT")) or DEFAULT_ETAG_TIMEOUT + +# Used to override the get request timeout on a system level +HF_HUB_DOWNLOAD_TIMEOUT: int = _as_int(os.environ.get("HF_HUB_DOWNLOAD_TIMEOUT")) or DEFAULT_DOWNLOAD_TIMEOUT + +# List frameworks that are handled by the InferenceAPI service. Useful to scan endpoints and check which models are +# deployed and running. Since 95% of the models are using the top 4 frameworks listed below, we scan only those by +# default. We still keep the full list of supported frameworks in case we want to scan all of them. +MAIN_INFERENCE_API_FRAMEWORKS = [ + "diffusers", + "sentence-transformers", + "text-generation-inference", + "transformers", +] + +ALL_INFERENCE_API_FRAMEWORKS = MAIN_INFERENCE_API_FRAMEWORKS + [ + "adapter-transformers", + "allennlp", + "asteroid", + "bertopic", + "doctr", + "espnet", + "fairseq", + "fastai", + "fasttext", + "flair", + "generic", + "k2", + "keras", + "mindspore", + "nemo", + "open_clip", + "paddlenlp", + "peft", + "pyannote-audio", + "sklearn", + "spacy", + "span-marker", + "speechbrain", + "stanza", + "timm", +] diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/errors.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..7975b39d1f9b1ef3b576c34434a62abf634299f9 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/errors.py @@ -0,0 +1,38 @@ +"""Contains all custom errors.""" + +from requests import HTTPError + + +# INFERENCE CLIENT ERRORS + + +class InferenceTimeoutError(HTTPError, TimeoutError): + """Error raised when a model is unavailable or the request times out.""" + + +# TEXT GENERATION ERRORS + + +class TextGenerationError(HTTPError): + """Generic error raised if text-generation went wrong.""" + + +# Text Generation Inference Errors +class ValidationError(TextGenerationError): + """Server-side validation error.""" + + +class GenerationError(TextGenerationError): + pass + + +class OverloadedError(TextGenerationError): + pass + + +class IncompleteGenerationError(TextGenerationError): + pass + + +class UnknownError(TextGenerationError): + pass diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/file_download.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/file_download.py new file mode 100644 index 0000000000000000000000000000000000000000..566ef3246a8877c103b4f6f16c4e5d418bd62bbc --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/file_download.py @@ -0,0 +1,1770 @@ +import copy +import errno +import fnmatch +import inspect +import io +import json +import os +import re +import shutil +import stat +import tempfile +import time +import uuid +import warnings +from contextlib import contextmanager +from dataclasses import dataclass +from functools import partial +from pathlib import Path +from typing import Any, BinaryIO, Dict, Generator, Literal, Optional, Tuple, Union +from urllib.parse import quote, urlparse + +import requests + +from huggingface_hub import constants + +from . import __version__ # noqa: F401 # for backward compatibility +from .constants import ( + DEFAULT_ETAG_TIMEOUT, + DEFAULT_REQUEST_TIMEOUT, + DEFAULT_REVISION, + DOWNLOAD_CHUNK_SIZE, + ENDPOINT, + HF_HUB_CACHE, + HF_HUB_DISABLE_SYMLINKS_WARNING, + HF_HUB_DOWNLOAD_TIMEOUT, + HF_HUB_ENABLE_HF_TRANSFER, + HF_HUB_ETAG_TIMEOUT, + HF_TRANSFER_CONCURRENCY, + HUGGINGFACE_CO_URL_TEMPLATE, + HUGGINGFACE_HEADER_X_LINKED_ETAG, + HUGGINGFACE_HEADER_X_LINKED_SIZE, + HUGGINGFACE_HEADER_X_REPO_COMMIT, + HUGGINGFACE_HUB_CACHE, # noqa: F401 # for backward compatibility + REPO_ID_SEPARATOR, + REPO_TYPES, + REPO_TYPES_URL_PREFIXES, +) +from .utils import ( + EntryNotFoundError, + FileMetadataError, + GatedRepoError, + LocalEntryNotFoundError, + OfflineModeIsEnabled, + RepositoryNotFoundError, + RevisionNotFoundError, + SoftTemporaryDirectory, + WeakFileLock, + build_hf_headers, + get_fastai_version, # noqa: F401 # for backward compatibility + get_fastcore_version, # noqa: F401 # for backward compatibility + get_graphviz_version, # noqa: F401 # for backward compatibility + get_jinja_version, # noqa: F401 # for backward compatibility + get_pydot_version, # noqa: F401 # for backward compatibility + get_session, + get_tf_version, # noqa: F401 # for backward compatibility + get_torch_version, # noqa: F401 # for backward compatibility + hf_raise_for_status, + is_fastai_available, # noqa: F401 # for backward compatibility + is_fastcore_available, # noqa: F401 # for backward compatibility + is_graphviz_available, # noqa: F401 # for backward compatibility + is_jinja_available, # noqa: F401 # for backward compatibility + is_pydot_available, # noqa: F401 # for backward compatibility + is_tf_available, # noqa: F401 # for backward compatibility + is_torch_available, # noqa: F401 # for backward compatibility + logging, + reset_sessions, + tqdm, + validate_hf_hub_args, +) +from .utils._runtime import _PY_VERSION # noqa: F401 # for backward compatibility +from .utils._typing import HTTP_METHOD_T +from .utils.insecure_hashlib import sha256 + + +logger = logging.get_logger(__name__) + +# Regex to get filename from a "Content-Disposition" header for CDN-served files +HEADER_FILENAME_PATTERN = re.compile(r'filename="(?P.*?)";') + + +_are_symlinks_supported_in_dir: Dict[str, bool] = {} + + +def are_symlinks_supported(cache_dir: Union[str, Path, None] = None) -> bool: + """Return whether the symlinks are supported on the machine. + + Since symlinks support can change depending on the mounted disk, we need to check + on the precise cache folder. By default, the default HF cache directory is checked. + + Args: + cache_dir (`str`, `Path`, *optional*): + Path to the folder where cached files are stored. + + Returns: [bool] Whether symlinks are supported in the directory. + """ + # Defaults to HF cache + if cache_dir is None: + cache_dir = HF_HUB_CACHE + cache_dir = str(Path(cache_dir).expanduser().resolve()) # make it unique + + # Check symlink compatibility only once (per cache directory) at first time use + if cache_dir not in _are_symlinks_supported_in_dir: + _are_symlinks_supported_in_dir[cache_dir] = True + + os.makedirs(cache_dir, exist_ok=True) + with SoftTemporaryDirectory(dir=cache_dir) as tmpdir: + src_path = Path(tmpdir) / "dummy_file_src" + src_path.touch() + dst_path = Path(tmpdir) / "dummy_file_dst" + + # Relative source path as in `_create_symlink`` + relative_src = os.path.relpath(src_path, start=os.path.dirname(dst_path)) + try: + os.symlink(relative_src, dst_path) + except OSError: + # Likely running on Windows + _are_symlinks_supported_in_dir[cache_dir] = False + + if not HF_HUB_DISABLE_SYMLINKS_WARNING: + message = ( + "`huggingface_hub` cache-system uses symlinks by default to" + " efficiently store duplicated files but your machine does not" + f" support them in {cache_dir}. Caching files will still work" + " but in a degraded version that might require more space on" + " your disk. This warning can be disabled by setting the" + " `HF_HUB_DISABLE_SYMLINKS_WARNING` environment variable. For" + " more details, see" + " https://huggingface.co/docs/huggingface_hub/how-to-cache#limitations." + ) + if os.name == "nt": + message += ( + "\nTo support symlinks on Windows, you either need to" + " activate Developer Mode or to run Python as an" + " administrator. In order to see activate developer mode," + " see this article:" + " https://docs.microsoft.com/en-us/windows/apps/get-started/enable-your-device-for-development" + ) + warnings.warn(message) + + return _are_symlinks_supported_in_dir[cache_dir] + + +# Return value when trying to load a file from cache but the file does not exist in the distant repo. +_CACHED_NO_EXIST = object() +_CACHED_NO_EXIST_T = Any +REGEX_COMMIT_HASH = re.compile(r"^[0-9a-f]{40}$") + + +@dataclass(frozen=True) +class HfFileMetadata: + """Data structure containing information about a file versioned on the Hub. + + Returned by [`get_hf_file_metadata`] based on a URL. + + Args: + commit_hash (`str`, *optional*): + The commit_hash related to the file. + etag (`str`, *optional*): + Etag of the file on the server. + location (`str`): + Location where to download the file. Can be a Hub url or not (CDN). + size (`size`): + Size of the file. In case of an LFS file, contains the size of the actual + LFS file, not the pointer. + """ + + commit_hash: Optional[str] + etag: Optional[str] + location: str + size: Optional[int] + + +@validate_hf_hub_args +def hf_hub_url( + repo_id: str, + filename: str, + *, + subfolder: Optional[str] = None, + repo_type: Optional[str] = None, + revision: Optional[str] = None, + endpoint: Optional[str] = None, +) -> str: + """Construct the URL of a file from the given information. + + The resolved address can either be a huggingface.co-hosted url, or a link to + Cloudfront (a Content Delivery Network, or CDN) for large files which are + more than a few MBs. + + Args: + repo_id (`str`): + A namespace (user or an organization) name and a repo name separated + by a `/`. + filename (`str`): + The name of the file in the repo. + subfolder (`str`, *optional*): + An optional value corresponding to a folder inside the repo. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if downloading from a dataset or space, + `None` or `"model"` if downloading from a model. Default is `None`. + revision (`str`, *optional*): + An optional Git revision id which can be a branch name, a tag, or a + commit hash. + + Example: + + ```python + >>> from huggingface_hub import hf_hub_url + + >>> hf_hub_url( + ... repo_id="julien-c/EsperBERTo-small", filename="pytorch_model.bin" + ... ) + 'https://huggingface.co/julien-c/EsperBERTo-small/resolve/main/pytorch_model.bin' + ``` + + + + Notes: + + Cloudfront is replicated over the globe so downloads are way faster for + the end user (and it also lowers our bandwidth costs). + + Cloudfront aggressively caches files by default (default TTL is 24 + hours), however this is not an issue here because we implement a + git-based versioning system on huggingface.co, which means that we store + the files on S3/Cloudfront in a content-addressable way (i.e., the file + name is its hash). Using content-addressable filenames means cache can't + ever be stale. + + In terms of client-side caching from this library, we base our caching + on the objects' entity tag (`ETag`), which is an identifier of a + specific version of a resource [1]_. An object's ETag is: its git-sha1 + if stored in git, or its sha256 if stored in git-lfs. + + + + References: + + - [1] https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag + """ + if subfolder == "": + subfolder = None + if subfolder is not None: + filename = f"{subfolder}/{filename}" + + if repo_type not in REPO_TYPES: + raise ValueError("Invalid repo type") + + if repo_type in REPO_TYPES_URL_PREFIXES: + repo_id = REPO_TYPES_URL_PREFIXES[repo_type] + repo_id + + if revision is None: + revision = DEFAULT_REVISION + url = HUGGINGFACE_CO_URL_TEMPLATE.format( + repo_id=repo_id, revision=quote(revision, safe=""), filename=quote(filename) + ) + # Update endpoint if provided + if endpoint is not None and url.startswith(ENDPOINT): + url = endpoint + url[len(ENDPOINT) :] + return url + + +def url_to_filename(url: str, etag: Optional[str] = None) -> str: + """Generate a local filename from a url. + + Convert `url` into a hashed filename in a reproducible way. If `etag` is + specified, append its hash to the url's, delimited by a period. If the url + ends with .h5 (Keras HDF5 weights) adds '.h5' to the name so that TF 2.0 can + identify it as a HDF5 file (see + https://github.com/tensorflow/tensorflow/blob/00fad90125b18b80fe054de1055770cfb8fe4ba3/tensorflow/python/keras/engine/network.py#L1380) + + Args: + url (`str`): + The address to the file. + etag (`str`, *optional*): + The ETag of the file. + + Returns: + The generated filename. + """ + url_bytes = url.encode("utf-8") + filename = sha256(url_bytes).hexdigest() + + if etag: + etag_bytes = etag.encode("utf-8") + filename += "." + sha256(etag_bytes).hexdigest() + + if url.endswith(".h5"): + filename += ".h5" + + return filename + + +def filename_to_url( + filename, + cache_dir: Optional[str] = None, + legacy_cache_layout: bool = False, +) -> Tuple[str, str]: + """ + Return the url and etag (which may be `None`) stored for `filename`. Raise + `EnvironmentError` if `filename` or its stored metadata do not exist. + + Args: + filename (`str`): + The name of the file + cache_dir (`str`, *optional*): + The cache directory to use instead of the default one. + legacy_cache_layout (`bool`, *optional*, defaults to `False`): + If `True`, uses the legacy file cache layout i.e. just call `hf_hub_url` + then `cached_download`. This is deprecated as the new cache layout is + more powerful. + """ + if not legacy_cache_layout: + warnings.warn( + "`filename_to_url` uses the legacy way cache file layout", + FutureWarning, + ) + + if cache_dir is None: + cache_dir = HF_HUB_CACHE + if isinstance(cache_dir, Path): + cache_dir = str(cache_dir) + + cache_path = os.path.join(cache_dir, filename) + if not os.path.exists(cache_path): + raise EnvironmentError(f"file {cache_path} not found") + + meta_path = cache_path + ".json" + if not os.path.exists(meta_path): + raise EnvironmentError(f"file {meta_path} not found") + + with open(meta_path, encoding="utf-8") as meta_file: + metadata = json.load(meta_file) + url = metadata["url"] + etag = metadata["etag"] + + return url, etag + + +def _request_wrapper( + method: HTTP_METHOD_T, url: str, *, follow_relative_redirects: bool = False, **params +) -> requests.Response: + """Wrapper around requests methods to follow relative redirects if `follow_relative_redirects=True` even when + `allow_redirection=False`. + + Args: + method (`str`): + HTTP method, such as 'GET' or 'HEAD'. + url (`str`): + The URL of the resource to fetch. + follow_relative_redirects (`bool`, *optional*, defaults to `False`) + If True, relative redirection (redirection to the same site) will be resolved even when `allow_redirection` + kwarg is set to False. Useful when we want to follow a redirection to a renamed repository without + following redirection to a CDN. + **params (`dict`, *optional*): + Params to pass to `requests.request`. + """ + # Recursively follow relative redirects + if follow_relative_redirects: + response = _request_wrapper( + method=method, + url=url, + follow_relative_redirects=False, + **params, + ) + + # If redirection, we redirect only relative paths. + # This is useful in case of a renamed repository. + if 300 <= response.status_code <= 399: + parsed_target = urlparse(response.headers["Location"]) + if parsed_target.netloc == "": + # This means it is a relative 'location' headers, as allowed by RFC 7231. + # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource') + # We want to follow this relative redirect ! + # + # Highly inspired by `resolve_redirects` from requests library. + # See https://github.com/psf/requests/blob/main/requests/sessions.py#L159 + next_url = urlparse(url)._replace(path=parsed_target.path).geturl() + return _request_wrapper(method=method, url=next_url, follow_relative_redirects=True, **params) + return response + + # Perform request and return if status_code is not in the retry list. + response = get_session().request(method=method, url=url, **params) + hf_raise_for_status(response) + return response + + +def http_get( + url: str, + temp_file: BinaryIO, + *, + proxies: Optional[Dict] = None, + resume_size: float = 0, + headers: Optional[Dict[str, str]] = None, + expected_size: Optional[int] = None, + displayed_filename: Optional[str] = None, + _nb_retries: int = 5, + _tqdm_bar: Optional[tqdm] = None, +) -> None: + """ + Download a remote file. Do not gobble up errors, and will return errors tailored to the Hugging Face Hub. + + If ConnectionError (SSLError) or ReadTimeout happen while streaming data from the server, it is most likely a + transient error (network outage?). We log a warning message and try to resume the download a few times before + giving up. The method gives up after 5 attempts if no new data has being received from the server. + + Args: + url (`str`): + The URL of the file to download. + temp_file (`BinaryIO`): + The file-like object where to save the file. + proxies (`dict`, *optional*): + Dictionary mapping protocol to the URL of the proxy passed to `requests.request`. + resume_size (`float`, *optional*): + The number of bytes already downloaded. If set to 0 (default), the whole file is download. If set to a + positive number, the download will resume at the given position. + headers (`dict`, *optional*): + Dictionary of HTTP Headers to send with the request. + expected_size (`int`, *optional*): + The expected size of the file to download. If set, the download will raise an error if the size of the + received content is different from the expected one. + displayed_filename (`str`, *optional*): + The filename of the file that is being downloaded. Value is used only to display a nice progress bar. If + not set, the filename is guessed from the URL or the `Content-Disposition` header. + """ + hf_transfer = None + if HF_HUB_ENABLE_HF_TRANSFER: + if resume_size != 0: + warnings.warn("'hf_transfer' does not support `resume_size`: falling back to regular download method") + elif proxies is not None: + warnings.warn("'hf_transfer' does not support `proxies`: falling back to regular download method") + else: + try: + import hf_transfer # type: ignore[no-redef] + except ImportError: + raise ValueError( + "Fast download using 'hf_transfer' is enabled" + " (HF_HUB_ENABLE_HF_TRANSFER=1) but 'hf_transfer' package is not" + " available in your environment. Try `pip install hf_transfer`." + ) + + initial_headers = headers + headers = copy.deepcopy(headers) or {} + if resume_size > 0: + headers["Range"] = "bytes=%d-" % (resume_size,) + + r = _request_wrapper( + method="GET", url=url, stream=True, proxies=proxies, headers=headers, timeout=HF_HUB_DOWNLOAD_TIMEOUT + ) + hf_raise_for_status(r) + content_length = r.headers.get("Content-Length") + + # NOTE: 'total' is the total number of bytes to download, not the number of bytes in the file. + # If the file is compressed, the number of bytes in the saved file will be higher than 'total'. + total = resume_size + int(content_length) if content_length is not None else None + + if displayed_filename is None: + displayed_filename = url + content_disposition = r.headers.get("Content-Disposition") + if content_disposition is not None: + match = HEADER_FILENAME_PATTERN.search(content_disposition) + if match is not None: + # Means file is on CDN + displayed_filename = match.groupdict()["filename"] + + # Truncate filename if too long to display + if len(displayed_filename) > 40: + displayed_filename = f"(…){displayed_filename[-40:]}" + + consistency_error_message = ( + f"Consistency check failed: file should be of size {expected_size} but has size" + f" {{actual_size}} ({displayed_filename}).\nWe are sorry for the inconvenience. Please retry download and" + " pass `force_download=True, resume_download=False` as argument.\nIf the issue persists, please let us" + " know by opening an issue on https://github.com/huggingface/huggingface_hub." + ) + + # Stream file to buffer + progress = _tqdm_bar + if progress is None: + progress = tqdm( + unit="B", + unit_scale=True, + total=total, + initial=resume_size, + desc=displayed_filename, + disable=True if (logger.getEffectiveLevel() == logging.NOTSET) else None, + # ^ set `disable=None` rather than `disable=False` by default to disable progress bar when no TTY attached + # see https://github.com/huggingface/huggingface_hub/pull/2000 + ) + + if hf_transfer and total is not None and total > 5 * DOWNLOAD_CHUNK_SIZE: + supports_callback = "callback" in inspect.signature(hf_transfer.download).parameters + if not supports_callback: + warnings.warn( + "You are using an outdated version of `hf_transfer`. " + "Consider upgrading to latest version to enable progress bars " + "using `pip install -U hf_transfer`." + ) + try: + hf_transfer.download( + url=url, + filename=temp_file.name, + max_files=HF_TRANSFER_CONCURRENCY, + chunk_size=DOWNLOAD_CHUNK_SIZE, + headers=headers, + parallel_failures=3, + max_retries=5, + **({"callback": progress.update} if supports_callback else {}), + ) + except Exception as e: + raise RuntimeError( + "An error occurred while downloading using `hf_transfer`. Consider" + " disabling HF_HUB_ENABLE_HF_TRANSFER for better error handling." + ) from e + if not supports_callback: + progress.update(total) + if expected_size is not None and expected_size != os.path.getsize(temp_file.name): + raise EnvironmentError( + consistency_error_message.format( + actual_size=os.path.getsize(temp_file.name), + ) + ) + return + new_resume_size = resume_size + try: + for chunk in r.iter_content(chunk_size=DOWNLOAD_CHUNK_SIZE): + if chunk: # filter out keep-alive new chunks + progress.update(len(chunk)) + temp_file.write(chunk) + new_resume_size += len(chunk) + # Some data has been downloaded from the server so we reset the number of retries. + _nb_retries = 5 + except (requests.ConnectionError, requests.ReadTimeout) as e: + # If ConnectionError (SSLError) or ReadTimeout happen while streaming data from the server, it is most likely + # a transient error (network outage?). We log a warning message and try to resume the download a few times + # before giving up. Tre retry mechanism is basic but should be enough in most cases. + if _nb_retries <= 0: + logger.warning("Error while downloading from %s: %s\nMax retries exceeded.", url, str(e)) + raise + logger.warning("Error while downloading from %s: %s\nTrying to resume download...", url, str(e)) + time.sleep(1) + reset_sessions() # In case of SSLError it's best to reset the shared requests.Session objects + return http_get( + url=url, + temp_file=temp_file, + proxies=proxies, + resume_size=new_resume_size, + headers=initial_headers, + expected_size=expected_size, + _nb_retries=_nb_retries - 1, + _tqdm_bar=_tqdm_bar, + ) + + progress.close() + + if expected_size is not None and expected_size != temp_file.tell(): + raise EnvironmentError( + consistency_error_message.format( + actual_size=temp_file.tell(), + ) + ) + + +@validate_hf_hub_args +def cached_download( + url: str, + *, + library_name: Optional[str] = None, + library_version: Optional[str] = None, + cache_dir: Union[str, Path, None] = None, + user_agent: Union[Dict, str, None] = None, + force_download: bool = False, + force_filename: Optional[str] = None, + proxies: Optional[Dict] = None, + etag_timeout: float = DEFAULT_ETAG_TIMEOUT, + resume_download: bool = False, + token: Union[bool, str, None] = None, + local_files_only: bool = False, + legacy_cache_layout: bool = False, +) -> str: + """ + Download from a given URL and cache it if it's not already present in the + local cache. + + Given a URL, this function looks for the corresponding file in the local + cache. If it's not there, download it. Then return the path to the cached + file. + + Will raise errors tailored to the Hugging Face Hub. + + Args: + url (`str`): + The path to the file to be downloaded. + library_name (`str`, *optional*): + The name of the library to which the object corresponds. + library_version (`str`, *optional*): + The version of the library. + cache_dir (`str`, `Path`, *optional*): + Path to the folder where cached files are stored. + user_agent (`dict`, `str`, *optional*): + The user-agent info in the form of a dictionary or a string. + force_download (`bool`, *optional*, defaults to `False`): + Whether the file should be downloaded even if it already exists in + the local cache. + force_filename (`str`, *optional*): + Use this name instead of a generated file name. + proxies (`dict`, *optional*): + Dictionary mapping protocol to the URL of the proxy passed to + `requests.request`. + etag_timeout (`float`, *optional* defaults to `10`): + When fetching ETag, how many seconds to wait for the server to send + data before giving up which is passed to `requests.request`. + resume_download (`bool`, *optional*, defaults to `False`): + If `True`, resume a previously interrupted download. + token (`bool`, `str`, *optional*): + A token to be used for the download. + - If `True`, the token is read from the HuggingFace config + folder. + - If a string, it's used as the authentication token. + local_files_only (`bool`, *optional*, defaults to `False`): + If `True`, avoid downloading the file and return the path to the + local cached file if it exists. + legacy_cache_layout (`bool`, *optional*, defaults to `False`): + Set this parameter to `True` to mention that you'd like to continue + the old cache layout. Putting this to `True` manually will not raise + any warning when using `cached_download`. We recommend using + `hf_hub_download` to take advantage of the new cache. + + Returns: + Local path (string) of file or if networking is off, last version of + file cached on disk. + + + + Raises the following errors: + + - [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError) + if `token=True` and the token cannot be found. + - [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError) + if ETag cannot be determined. + - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + if some parameter value is invalid + - [`~utils.RepositoryNotFoundError`] + If the repository to download from cannot be found. This may be because it doesn't exist, + or because it is set to `private` and you do not have access. + - [`~utils.RevisionNotFoundError`] + If the revision to download from cannot be found. + - [`~utils.EntryNotFoundError`] + If the file to download cannot be found. + - [`~utils.LocalEntryNotFoundError`] + If network is disabled or unavailable and file is not found in cache. + + + """ + if HF_HUB_ETAG_TIMEOUT != DEFAULT_ETAG_TIMEOUT: + # Respect environment variable above user value + etag_timeout = HF_HUB_ETAG_TIMEOUT + + if not legacy_cache_layout: + warnings.warn( + "'cached_download' is the legacy way to download files from the HF hub, please consider upgrading to" + " 'hf_hub_download'", + FutureWarning, + ) + + if cache_dir is None: + cache_dir = HF_HUB_CACHE + if isinstance(cache_dir, Path): + cache_dir = str(cache_dir) + + os.makedirs(cache_dir, exist_ok=True) + + headers = build_hf_headers( + token=token, + library_name=library_name, + library_version=library_version, + user_agent=user_agent, + ) + + url_to_download = url + etag = None + expected_size = None + if not local_files_only: + try: + # Temporary header: we want the full (decompressed) content size returned to be able to check the + # downloaded file size + headers["Accept-Encoding"] = "identity" + r = _request_wrapper( + method="HEAD", + url=url, + headers=headers, + allow_redirects=False, + follow_relative_redirects=True, + proxies=proxies, + timeout=etag_timeout, + ) + headers.pop("Accept-Encoding", None) + hf_raise_for_status(r) + etag = r.headers.get(HUGGINGFACE_HEADER_X_LINKED_ETAG) or r.headers.get("ETag") + # We favor a custom header indicating the etag of the linked resource, and + # we fallback to the regular etag header. + # If we don't have any of those, raise an error. + if etag is None: + raise FileMetadataError( + "Distant resource does not have an ETag, we won't be able to reliably ensure reproducibility." + ) + # We get the expected size of the file, to check the download went well. + expected_size = _int_or_none(r.headers.get("Content-Length")) + # In case of a redirect, save an extra redirect on the request.get call, + # and ensure we download the exact atomic version even if it changed + # between the HEAD and the GET (unlikely, but hey). + # Useful for lfs blobs that are stored on a CDN. + if 300 <= r.status_code <= 399: + url_to_download = r.headers["Location"] + headers.pop("authorization", None) + expected_size = None # redirected -> can't know the expected size + except (requests.exceptions.SSLError, requests.exceptions.ProxyError): + # Actually raise for those subclasses of ConnectionError + raise + except ( + requests.exceptions.ConnectionError, + requests.exceptions.Timeout, + OfflineModeIsEnabled, + ): + # Otherwise, our Internet connection is down. + # etag is None + pass + + filename = force_filename if force_filename is not None else url_to_filename(url, etag) + + # get cache path to put the file + cache_path = os.path.join(cache_dir, filename) + + # etag is None == we don't have a connection or we passed local_files_only. + # try to get the last downloaded one + if etag is None: + if os.path.exists(cache_path) and not force_download: + return cache_path + else: + matching_files = [ + file + for file in fnmatch.filter(os.listdir(cache_dir), filename.split(".")[0] + ".*") + if not file.endswith(".json") and not file.endswith(".lock") + ] + if len(matching_files) > 0 and not force_download and force_filename is None: + return os.path.join(cache_dir, matching_files[-1]) + else: + # If files cannot be found and local_files_only=True, + # the models might've been found if local_files_only=False + # Notify the user about that + if local_files_only: + raise LocalEntryNotFoundError( + "Cannot find the requested files in the cached path and" + " outgoing traffic has been disabled. To enable model look-ups" + " and downloads online, set 'local_files_only' to False." + ) + else: + raise LocalEntryNotFoundError( + "Connection error, and we cannot find the requested files in" + " the cached path. Please try again or make sure your Internet" + " connection is on." + ) + + # From now on, etag is not None. + if os.path.exists(cache_path) and not force_download: + return cache_path + + # Prevent parallel downloads of the same file with a lock. + lock_path = cache_path + ".lock" + + # Some Windows versions do not allow for paths longer than 255 characters. + # In this case, we must specify it is an extended path by using the "\\?\" prefix. + if os.name == "nt" and len(os.path.abspath(lock_path)) > 255: + lock_path = "\\\\?\\" + os.path.abspath(lock_path) + + if os.name == "nt" and len(os.path.abspath(cache_path)) > 255: + cache_path = "\\\\?\\" + os.path.abspath(cache_path) + + with WeakFileLock(lock_path): + # If the download just completed while the lock was activated. + if os.path.exists(cache_path) and not force_download: + # Even if returning early like here, the lock will be released. + return cache_path + + if resume_download: + incomplete_path = cache_path + ".incomplete" + + @contextmanager + def _resumable_file_manager() -> Generator[io.BufferedWriter, None, None]: + with open(incomplete_path, "ab") as f: + yield f + + temp_file_manager = _resumable_file_manager + if os.path.exists(incomplete_path): + resume_size = os.stat(incomplete_path).st_size + else: + resume_size = 0 + else: + temp_file_manager = partial( # type: ignore + tempfile.NamedTemporaryFile, mode="wb", dir=cache_dir, delete=False + ) + resume_size = 0 + + # Download to temporary file, then copy to cache dir once finished. + # Otherwise you get corrupt cache entries if the download gets interrupted. + with temp_file_manager() as temp_file: + logger.info("downloading %s to %s", url, temp_file.name) + + http_get( + url_to_download, + temp_file, + proxies=proxies, + resume_size=resume_size, + headers=headers, + expected_size=expected_size, + ) + + logger.info("storing %s in cache at %s", url, cache_path) + _chmod_and_replace(temp_file.name, cache_path) + + if force_filename is None: + logger.info("creating metadata file for %s", cache_path) + meta = {"url": url, "etag": etag} + meta_path = cache_path + ".json" + with open(meta_path, "w") as meta_file: + json.dump(meta, meta_file) + + return cache_path + + +def _normalize_etag(etag: Optional[str]) -> Optional[str]: + """Normalize ETag HTTP header, so it can be used to create nice filepaths. + + The HTTP spec allows two forms of ETag: + ETag: W/"" + ETag: "" + + For now, we only expect the second form from the server, but we want to be future-proof so we support both. For + more context, see `TestNormalizeEtag` tests and https://github.com/huggingface/huggingface_hub/pull/1428. + + Args: + etag (`str`, *optional*): HTTP header + + Returns: + `str` or `None`: string that can be used as a nice directory name. + Returns `None` if input is None. + """ + if etag is None: + return None + return etag.lstrip("W/").strip('"') + + +def _create_relative_symlink(src: str, dst: str, new_blob: bool = False) -> None: + """Alias method used in `transformers` conversion script.""" + return _create_symlink(src=src, dst=dst, new_blob=new_blob) + + +def _create_symlink(src: str, dst: str, new_blob: bool = False) -> None: + """Create a symbolic link named dst pointing to src. + + By default, it will try to create a symlink using a relative path. Relative paths have 2 advantages: + - If the cache_folder is moved (example: back-up on a shared drive), relative paths within the cache folder will + not break. + - Relative paths seems to be better handled on Windows. Issue was reported 3 times in less than a week when + changing from relative to absolute paths. See https://github.com/huggingface/huggingface_hub/issues/1398, + https://github.com/huggingface/diffusers/issues/2729 and https://github.com/huggingface/transformers/pull/22228. + NOTE: The issue with absolute paths doesn't happen on admin mode. + When creating a symlink from the cache to a local folder, it is possible that a relative path cannot be created. + This happens when paths are not on the same volume. In that case, we use absolute paths. + + + The result layout looks something like + └── [ 128] snapshots + ├── [ 128] 2439f60ef33a0d46d85da5001d52aeda5b00ce9f + │ ├── [ 52] README.md -> ../../../blobs/d7edf6bd2a681fb0175f7735299831ee1b22b812 + │ └── [ 76] pytorch_model.bin -> ../../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd + + If symlinks cannot be created on this platform (most likely to be Windows), the workaround is to avoid symlinks by + having the actual file in `dst`. If it is a new file (`new_blob=True`), we move it to `dst`. If it is not a new file + (`new_blob=False`), we don't know if the blob file is already referenced elsewhere. To avoid breaking existing + cache, the file is duplicated on the disk. + + In case symlinks are not supported, a warning message is displayed to the user once when loading `huggingface_hub`. + The warning message can be disabled with the `DISABLE_SYMLINKS_WARNING` environment variable. + """ + try: + os.remove(dst) + except OSError: + pass + + abs_src = os.path.abspath(os.path.expanduser(src)) + abs_dst = os.path.abspath(os.path.expanduser(dst)) + abs_dst_folder = os.path.dirname(abs_dst) + + # Use relative_dst in priority + try: + relative_src = os.path.relpath(abs_src, abs_dst_folder) + except ValueError: + # Raised on Windows if src and dst are not on the same volume. This is the case when creating a symlink to a + # local_dir instead of within the cache directory. + # See https://docs.python.org/3/library/os.path.html#os.path.relpath + relative_src = None + + try: + commonpath = os.path.commonpath([abs_src, abs_dst]) + _support_symlinks = are_symlinks_supported(commonpath) + except ValueError: + # Raised if src and dst are not on the same volume. Symlinks will still work on Linux/Macos. + # See https://docs.python.org/3/library/os.path.html#os.path.commonpath + _support_symlinks = os.name != "nt" + except PermissionError: + # Permission error means src and dst are not in the same volume (e.g. destination path has been provided + # by the user via `local_dir`. Let's test symlink support there) + _support_symlinks = are_symlinks_supported(abs_dst_folder) + except OSError as e: + # OS error (errno=30) means that the commonpath is readonly on Linux/MacOS. + if e.errno == errno.EROFS: + _support_symlinks = are_symlinks_supported(abs_dst_folder) + else: + raise + + # Symlinks are supported => let's create a symlink. + if _support_symlinks: + src_rel_or_abs = relative_src or abs_src + logger.debug(f"Creating pointer from {src_rel_or_abs} to {abs_dst}") + try: + os.symlink(src_rel_or_abs, abs_dst) + return + except FileExistsError: + if os.path.islink(abs_dst) and os.path.realpath(abs_dst) == os.path.realpath(abs_src): + # `abs_dst` already exists and is a symlink to the `abs_src` blob. It is most likely that the file has + # been cached twice concurrently (exactly between `os.remove` and `os.symlink`). Do nothing. + return + else: + # Very unlikely to happen. Means a file `dst` has been created exactly between `os.remove` and + # `os.symlink` and is not a symlink to the `abs_src` blob file. Raise exception. + raise + except PermissionError: + # Permission error means src and dst are not in the same volume (e.g. download to local dir) and symlink + # is supported on both volumes but not between them. Let's just make a hard copy in that case. + pass + + # Symlinks are not supported => let's move or copy the file. + if new_blob: + logger.info(f"Symlink not supported. Moving file from {abs_src} to {abs_dst}") + shutil.move(abs_src, abs_dst) + else: + logger.info(f"Symlink not supported. Copying file from {abs_src} to {abs_dst}") + shutil.copyfile(abs_src, abs_dst) + + +def _cache_commit_hash_for_specific_revision(storage_folder: str, revision: str, commit_hash: str) -> None: + """Cache reference between a revision (tag, branch or truncated commit hash) and the corresponding commit hash. + + Does nothing if `revision` is already a proper `commit_hash` or reference is already cached. + """ + if revision != commit_hash: + ref_path = Path(storage_folder) / "refs" / revision + ref_path.parent.mkdir(parents=True, exist_ok=True) + if not ref_path.exists() or commit_hash != ref_path.read_text(): + # Update ref only if has been updated. Could cause useless error in case + # repo is already cached and user doesn't have write access to cache folder. + # See https://github.com/huggingface/huggingface_hub/issues/1216. + ref_path.write_text(commit_hash) + + +@validate_hf_hub_args +def repo_folder_name(*, repo_id: str, repo_type: str) -> str: + """Return a serialized version of a hf.co repo name and type, safe for disk storage + as a single non-nested folder. + + Example: models--julien-c--EsperBERTo-small + """ + # remove all `/` occurrences to correctly convert repo to directory name + parts = [f"{repo_type}s", *repo_id.split("/")] + return REPO_ID_SEPARATOR.join(parts) + + +def _check_disk_space(expected_size: int, target_dir: Union[str, Path]) -> None: + """Check disk usage and log a warning if there is not enough disk space to download the file. + + Args: + expected_size (`int`): + The expected size of the file in bytes. + target_dir (`str`): + The directory where the file will be stored after downloading. + """ + + target_dir = Path(target_dir) # format as `Path` + for path in [target_dir] + list(target_dir.parents): # first check target_dir, then each parents one by one + try: + target_dir_free = shutil.disk_usage(path).free + if target_dir_free < expected_size: + warnings.warn( + "Not enough free disk space to download the file. " + f"The expected file size is: {expected_size / 1e6:.2f} MB. " + f"The target location {target_dir} only has {target_dir_free / 1e6:.2f} MB free disk space." + ) + return + except OSError: # raise on anything: file does not exist or space disk cannot be checked + pass + + +@validate_hf_hub_args +def hf_hub_download( + repo_id: str, + filename: str, + *, + subfolder: Optional[str] = None, + repo_type: Optional[str] = None, + revision: Optional[str] = None, + library_name: Optional[str] = None, + library_version: Optional[str] = None, + cache_dir: Union[str, Path, None] = None, + local_dir: Union[str, Path, None] = None, + local_dir_use_symlinks: Union[bool, Literal["auto"]] = "auto", + user_agent: Union[Dict, str, None] = None, + force_download: bool = False, + force_filename: Optional[str] = None, + proxies: Optional[Dict] = None, + etag_timeout: float = DEFAULT_ETAG_TIMEOUT, + resume_download: bool = False, + token: Union[bool, str, None] = None, + local_files_only: bool = False, + headers: Optional[Dict[str, str]] = None, + legacy_cache_layout: bool = False, + endpoint: Optional[str] = None, +) -> str: + """Download a given file if it's not already present in the local cache. + + The new cache file layout looks like this: + - The cache directory contains one subfolder per repo_id (namespaced by repo type) + - inside each repo folder: + - refs is a list of the latest known revision => commit_hash pairs + - blobs contains the actual file blobs (identified by their git-sha or sha256, depending on + whether they're LFS files or not) + - snapshots contains one subfolder per commit, each "commit" contains the subset of the files + that have been resolved at that particular commit. Each filename is a symlink to the blob + at that particular commit. + + If `local_dir` is provided, the file structure from the repo will be replicated in this location. You can configure + how you want to move those files: + - If `local_dir_use_symlinks="auto"` (default), files are downloaded and stored in the cache directory as blob + files. Small files (<5MB) are duplicated in `local_dir` while a symlink is created for bigger files. The goal + is to be able to manually edit and save small files without corrupting the cache while saving disk space for + binary files. The 5MB threshold can be configured with the `HF_HUB_LOCAL_DIR_AUTO_SYMLINK_THRESHOLD` + environment variable. + - If `local_dir_use_symlinks=True`, files are downloaded, stored in the cache directory and symlinked in `local_dir`. + This is optimal in term of disk usage but files must not be manually edited. + - If `local_dir_use_symlinks=False` and the blob files exist in the cache directory, they are duplicated in the + local dir. This means disk usage is not optimized. + - Finally, if `local_dir_use_symlinks=False` and the blob files do not exist in the cache directory, then the + files are downloaded and directly placed under `local_dir`. This means if you need to download them again later, + they will be re-downloaded entirely. + + ``` + [ 96] . + └── [ 160] models--julien-c--EsperBERTo-small + ├── [ 160] blobs + │ ├── [321M] 403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd + │ ├── [ 398] 7cb18dc9bafbfcf74629a4b760af1b160957a83e + │ └── [1.4K] d7edf6bd2a681fb0175f7735299831ee1b22b812 + ├── [ 96] refs + │ └── [ 40] main + └── [ 128] snapshots + ├── [ 128] 2439f60ef33a0d46d85da5001d52aeda5b00ce9f + │ ├── [ 52] README.md -> ../../blobs/d7edf6bd2a681fb0175f7735299831ee1b22b812 + │ └── [ 76] pytorch_model.bin -> ../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd + └── [ 128] bbc77c8132af1cc5cf678da3f1ddf2de43606d48 + ├── [ 52] README.md -> ../../blobs/7cb18dc9bafbfcf74629a4b760af1b160957a83e + └── [ 76] pytorch_model.bin -> ../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd + ``` + + Args: + repo_id (`str`): + A user or an organization name and a repo name separated by a `/`. + filename (`str`): + The name of the file in the repo. + subfolder (`str`, *optional*): + An optional value corresponding to a folder inside the model repo. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if downloading from a dataset or space, + `None` or `"model"` if downloading from a model. Default is `None`. + revision (`str`, *optional*): + An optional Git revision id which can be a branch name, a tag, or a + commit hash. + library_name (`str`, *optional*): + The name of the library to which the object corresponds. + library_version (`str`, *optional*): + The version of the library. + cache_dir (`str`, `Path`, *optional*): + Path to the folder where cached files are stored. + local_dir (`str` or `Path`, *optional*): + If provided, the downloaded file will be placed under this directory, either as a symlink (default) or + a regular file (see description for more details). + local_dir_use_symlinks (`"auto"` or `bool`, defaults to `"auto"`): + To be used with `local_dir`. If set to "auto", the cache directory will be used and the file will be either + duplicated or symlinked to the local directory depending on its size. It set to `True`, a symlink will be + created, no matter the file size. If set to `False`, the file will either be duplicated from cache (if + already exists) or downloaded from the Hub and not cached. See description for more details. + user_agent (`dict`, `str`, *optional*): + The user-agent info in the form of a dictionary or a string. + force_download (`bool`, *optional*, defaults to `False`): + Whether the file should be downloaded even if it already exists in + the local cache. + proxies (`dict`, *optional*): + Dictionary mapping protocol to the URL of the proxy passed to + `requests.request`. + etag_timeout (`float`, *optional*, defaults to `10`): + When fetching ETag, how many seconds to wait for the server to send + data before giving up which is passed to `requests.request`. + resume_download (`bool`, *optional*, defaults to `False`): + If `True`, resume a previously interrupted download. + token (`str`, `bool`, *optional*): + A token to be used for the download. + - If `True`, the token is read from the HuggingFace config + folder. + - If a string, it's used as the authentication token. + local_files_only (`bool`, *optional*, defaults to `False`): + If `True`, avoid downloading the file and return the path to the + local cached file if it exists. + headers (`dict`, *optional*): + Additional headers to be sent with the request. + legacy_cache_layout (`bool`, *optional*, defaults to `False`): + If `True`, uses the legacy file cache layout i.e. just call [`hf_hub_url`] + then `cached_download`. This is deprecated as the new cache layout is + more powerful. + + Returns: + Local path (string) of file or if networking is off, last version of + file cached on disk. + + + + Raises the following errors: + + - [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError) + if `token=True` and the token cannot be found. + - [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError) + if ETag cannot be determined. + - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + if some parameter value is invalid + - [`~utils.RepositoryNotFoundError`] + If the repository to download from cannot be found. This may be because it doesn't exist, + or because it is set to `private` and you do not have access. + - [`~utils.RevisionNotFoundError`] + If the revision to download from cannot be found. + - [`~utils.EntryNotFoundError`] + If the file to download cannot be found. + - [`~utils.LocalEntryNotFoundError`] + If network is disabled or unavailable and file is not found in cache. + + + """ + if HF_HUB_ETAG_TIMEOUT != DEFAULT_ETAG_TIMEOUT: + # Respect environment variable above user value + etag_timeout = HF_HUB_ETAG_TIMEOUT + + if force_filename is not None: + warnings.warn( + "The `force_filename` parameter is deprecated as a new caching system, " + "which keeps the filenames as they are on the Hub, is now in place.", + FutureWarning, + ) + legacy_cache_layout = True + + if legacy_cache_layout: + url = hf_hub_url( + repo_id, + filename, + subfolder=subfolder, + repo_type=repo_type, + revision=revision, + endpoint=endpoint, + ) + + return cached_download( + url, + library_name=library_name, + library_version=library_version, + cache_dir=cache_dir, + user_agent=user_agent, + force_download=force_download, + force_filename=force_filename, + proxies=proxies, + etag_timeout=etag_timeout, + resume_download=resume_download, + token=token, + local_files_only=local_files_only, + legacy_cache_layout=legacy_cache_layout, + ) + + if cache_dir is None: + cache_dir = HF_HUB_CACHE + if revision is None: + revision = DEFAULT_REVISION + if isinstance(cache_dir, Path): + cache_dir = str(cache_dir) + if isinstance(local_dir, Path): + local_dir = str(local_dir) + locks_dir = os.path.join(cache_dir, ".locks") + + if subfolder == "": + subfolder = None + if subfolder is not None: + # This is used to create a URL, and not a local path, hence the forward slash. + filename = f"{subfolder}/{filename}" + + if repo_type is None: + repo_type = "model" + if repo_type not in REPO_TYPES: + raise ValueError(f"Invalid repo type: {repo_type}. Accepted repo types are: {str(REPO_TYPES)}") + + storage_folder = os.path.join(cache_dir, repo_folder_name(repo_id=repo_id, repo_type=repo_type)) + + # cross platform transcription of filename, to be used as a local file path. + relative_filename = os.path.join(*filename.split("/")) + if os.name == "nt": + if relative_filename.startswith("..\\") or "\\..\\" in relative_filename: + raise ValueError( + f"Invalid filename: cannot handle filename '{relative_filename}' on Windows. Please ask the repository" + " owner to rename this file." + ) + + # if user provides a commit_hash and they already have the file on disk, + # shortcut everything. + if REGEX_COMMIT_HASH.match(revision): + pointer_path = _get_pointer_path(storage_folder, revision, relative_filename) + if os.path.exists(pointer_path): + if local_dir is not None: + return _to_local_dir(pointer_path, local_dir, relative_filename, use_symlinks=local_dir_use_symlinks) + return pointer_path + + url = hf_hub_url(repo_id, filename, repo_type=repo_type, revision=revision, endpoint=endpoint) + + headers = build_hf_headers( + token=token, + library_name=library_name, + library_version=library_version, + user_agent=user_agent, + headers=headers, + ) + + url_to_download = url + etag = None + commit_hash = None + expected_size = None + head_call_error: Optional[Exception] = None + if not local_files_only: + try: + try: + metadata = get_hf_file_metadata( + url=url, + token=token, + proxies=proxies, + timeout=etag_timeout, + library_name=library_name, + library_version=library_version, + user_agent=user_agent, + ) + except EntryNotFoundError as http_error: + # Cache the non-existence of the file and raise + commit_hash = http_error.response.headers.get(HUGGINGFACE_HEADER_X_REPO_COMMIT) + if commit_hash is not None and not legacy_cache_layout: + no_exist_file_path = Path(storage_folder) / ".no_exist" / commit_hash / relative_filename + no_exist_file_path.parent.mkdir(parents=True, exist_ok=True) + no_exist_file_path.touch() + _cache_commit_hash_for_specific_revision(storage_folder, revision, commit_hash) + raise + + # Commit hash must exist + commit_hash = metadata.commit_hash + if commit_hash is None: + raise FileMetadataError( + "Distant resource does not seem to be on huggingface.co. It is possible that a configuration issue" + " prevents you from downloading resources from https://huggingface.co. Please check your firewall" + " and proxy settings and make sure your SSL certificates are updated." + ) + + # Etag must exist + etag = metadata.etag + # We favor a custom header indicating the etag of the linked resource, and + # we fallback to the regular etag header. + # If we don't have any of those, raise an error. + if etag is None: + raise FileMetadataError( + "Distant resource does not have an ETag, we won't be able to reliably ensure reproducibility." + ) + + # Expected (uncompressed) size + expected_size = metadata.size + + # In case of a redirect, save an extra redirect on the request.get call, + # and ensure we download the exact atomic version even if it changed + # between the HEAD and the GET (unlikely, but hey). + # + # If url domain is different => we are downloading from a CDN => url is signed => don't send auth + # If url domain is the same => redirect due to repo rename AND downloading a regular file => keep auth + if metadata.location != url: + url_to_download = metadata.location + if urlparse(url).netloc != urlparse(url_to_download).netloc: + # Remove authorization header when downloading a LFS blob + headers.pop("authorization", None) + except (requests.exceptions.SSLError, requests.exceptions.ProxyError): + # Actually raise for those subclasses of ConnectionError + raise + except ( + requests.exceptions.ConnectionError, + requests.exceptions.Timeout, + OfflineModeIsEnabled, + ) as error: + # Otherwise, our Internet connection is down. + # etag is None + head_call_error = error + pass + except (RevisionNotFoundError, EntryNotFoundError): + # The repo was found but the revision or entry doesn't exist on the Hub (never existed or got deleted) + raise + except requests.HTTPError as error: + # Multiple reasons for an http error: + # - Repository is private and invalid/missing token sent + # - Repository is gated and invalid/missing token sent + # - Hub is down (error 500 or 504) + # => let's switch to 'local_files_only=True' to check if the files are already cached. + # (if it's not the case, the error will be re-raised) + head_call_error = error + pass + except FileMetadataError as error: + # Multiple reasons for a FileMetadataError: + # - Wrong network configuration (proxy, firewall, SSL certificates) + # - Inconsistency on the Hub + # => let's switch to 'local_files_only=True' to check if the files are already cached. + # (if it's not the case, the error will be re-raised) + head_call_error = error + pass + + assert ( + local_files_only or etag is not None or head_call_error is not None + ), "etag is empty due to uncovered problems" + + # etag can be None for several reasons: + # 1. we passed local_files_only. + # 2. we don't have a connection + # 3. Hub is down (HTTP 500 or 504) + # 4. repo is not found -for example private or gated- and invalid/missing token sent + # 5. Hub is blocked by a firewall or proxy is not set correctly. + # => Try to get the last downloaded one from the specified revision. + # + # If the specified revision is a commit hash, look inside "snapshots". + # If the specified revision is a branch or tag, look inside "refs". + if etag is None: + # In those cases, we cannot force download. + if force_download: + if local_files_only: + raise ValueError("Cannot pass 'force_download=True' and 'local_files_only=True' at the same time.") + elif isinstance(head_call_error, OfflineModeIsEnabled): + raise ValueError( + "Cannot pass 'force_download=True' when offline mode is enabled." + ) from head_call_error + else: + raise ValueError("Force download failed due to the above error.") from head_call_error + + # Try to get "commit_hash" from "revision" + commit_hash = None + if REGEX_COMMIT_HASH.match(revision): + commit_hash = revision + else: + ref_path = os.path.join(storage_folder, "refs", revision) + if os.path.isfile(ref_path): + with open(ref_path) as f: + commit_hash = f.read() + + # Return pointer file if exists + if commit_hash is not None: + pointer_path = _get_pointer_path(storage_folder, commit_hash, relative_filename) + if os.path.exists(pointer_path): + if local_dir is not None: + return _to_local_dir( + pointer_path, local_dir, relative_filename, use_symlinks=local_dir_use_symlinks + ) + return pointer_path + + # If we couldn't find an appropriate file on disk, raise an error. + # If files cannot be found and local_files_only=True, + # the models might've been found if local_files_only=False + # Notify the user about that + if local_files_only: + raise LocalEntryNotFoundError( + "Cannot find the requested files in the disk cache and outgoing traffic has been disabled. To enable" + " hf.co look-ups and downloads online, set 'local_files_only' to False." + ) + elif isinstance(head_call_error, RepositoryNotFoundError) or isinstance(head_call_error, GatedRepoError): + # Repo not found or gated => let's raise the actual error + raise head_call_error + else: + # Otherwise: most likely a connection issue or Hub downtime => let's warn the user + raise LocalEntryNotFoundError( + "An error happened while trying to locate the file on the Hub and we cannot find the requested files" + " in the local cache. Please check your connection and try again or make sure your Internet connection" + " is on." + ) from head_call_error + + # From now on, etag and commit_hash are not None. + assert etag is not None, "etag must have been retrieved from server" + assert commit_hash is not None, "commit_hash must have been retrieved from server" + blob_path = os.path.join(storage_folder, "blobs", etag) + pointer_path = _get_pointer_path(storage_folder, commit_hash, relative_filename) + + os.makedirs(os.path.dirname(blob_path), exist_ok=True) + os.makedirs(os.path.dirname(pointer_path), exist_ok=True) + # if passed revision is not identical to commit_hash + # then revision has to be a branch name or tag name. + # In that case store a ref. + _cache_commit_hash_for_specific_revision(storage_folder, revision, commit_hash) + + if os.path.exists(pointer_path) and not force_download: + if local_dir is not None: + return _to_local_dir(pointer_path, local_dir, relative_filename, use_symlinks=local_dir_use_symlinks) + return pointer_path + + if os.path.exists(blob_path) and not force_download: + # we have the blob already, but not the pointer + if local_dir is not None: # to local dir + return _to_local_dir(blob_path, local_dir, relative_filename, use_symlinks=local_dir_use_symlinks) + else: # or in snapshot cache + _create_symlink(blob_path, pointer_path, new_blob=False) + return pointer_path + + # Prevent parallel downloads of the same file with a lock. + # etag could be duplicated across repos, + lock_path = os.path.join(locks_dir, repo_folder_name(repo_id=repo_id, repo_type=repo_type), f"{etag}.lock") + + # Some Windows versions do not allow for paths longer than 255 characters. + # In this case, we must specify it is an extended path by using the "\\?\" prefix. + if os.name == "nt" and len(os.path.abspath(lock_path)) > 255: + lock_path = "\\\\?\\" + os.path.abspath(lock_path) + + if os.name == "nt" and len(os.path.abspath(blob_path)) > 255: + blob_path = "\\\\?\\" + os.path.abspath(blob_path) + + Path(lock_path).parent.mkdir(parents=True, exist_ok=True) + with WeakFileLock(lock_path): + # If the download just completed while the lock was activated. + if os.path.exists(pointer_path) and not force_download: + # Even if returning early like here, the lock will be released. + if local_dir is not None: + return _to_local_dir(pointer_path, local_dir, relative_filename, use_symlinks=local_dir_use_symlinks) + return pointer_path + + if resume_download: + incomplete_path = blob_path + ".incomplete" + + @contextmanager + def _resumable_file_manager() -> Generator[io.BufferedWriter, None, None]: + with open(incomplete_path, "ab") as f: + yield f + + temp_file_manager = _resumable_file_manager + if os.path.exists(incomplete_path): + resume_size = os.stat(incomplete_path).st_size + else: + resume_size = 0 + else: + temp_file_manager = partial( # type: ignore + tempfile.NamedTemporaryFile, mode="wb", dir=cache_dir, delete=False + ) + resume_size = 0 + + # Download to temporary file, then copy to cache dir once finished. + # Otherwise you get corrupt cache entries if the download gets interrupted. + with temp_file_manager() as temp_file: + logger.info("downloading %s to %s", url, temp_file.name) + + if expected_size is not None: # might be None if HTTP header not set correctly + # Check tmp path + _check_disk_space(expected_size, os.path.dirname(temp_file.name)) + + # Check destination + _check_disk_space(expected_size, os.path.dirname(blob_path)) + if local_dir is not None: + _check_disk_space(expected_size, local_dir) + + http_get( + url_to_download, + temp_file, + proxies=proxies, + resume_size=resume_size, + headers=headers, + expected_size=expected_size, + displayed_filename=filename, + ) + + if local_dir is None: + logger.debug(f"Storing {url} in cache at {blob_path}") + _chmod_and_replace(temp_file.name, blob_path) + _create_symlink(blob_path, pointer_path, new_blob=True) + else: + local_dir_filepath = os.path.join(local_dir, relative_filename) + os.makedirs(os.path.dirname(local_dir_filepath), exist_ok=True) + + # If "auto" (default) copy-paste small files to ease manual editing but symlink big files to save disk + # In both cases, blob file is cached. + is_big_file = os.stat(temp_file.name).st_size > constants.HF_HUB_LOCAL_DIR_AUTO_SYMLINK_THRESHOLD + if local_dir_use_symlinks is True or (local_dir_use_symlinks == "auto" and is_big_file): + logger.debug(f"Storing {url} in cache at {blob_path}") + _chmod_and_replace(temp_file.name, blob_path) + logger.debug("Create symlink to local dir") + _create_symlink(blob_path, local_dir_filepath, new_blob=False) + elif local_dir_use_symlinks == "auto" and not is_big_file: + logger.debug(f"Storing {url} in cache at {blob_path}") + _chmod_and_replace(temp_file.name, blob_path) + logger.debug("Duplicate in local dir (small file and use_symlink set to 'auto')") + shutil.copyfile(blob_path, local_dir_filepath) + else: + logger.debug(f"Storing {url} in local_dir at {local_dir_filepath} (not cached).") + _chmod_and_replace(temp_file.name, local_dir_filepath) + pointer_path = local_dir_filepath # for return value + + return pointer_path + + +@validate_hf_hub_args +def try_to_load_from_cache( + repo_id: str, + filename: str, + cache_dir: Union[str, Path, None] = None, + revision: Optional[str] = None, + repo_type: Optional[str] = None, +) -> Union[str, _CACHED_NO_EXIST_T, None]: + """ + Explores the cache to return the latest cached file for a given revision if found. + + This function will not raise any exception if the file in not cached. + + Args: + cache_dir (`str` or `os.PathLike`): + The folder where the cached files lie. + repo_id (`str`): + The ID of the repo on huggingface.co. + filename (`str`): + The filename to look for inside `repo_id`. + revision (`str`, *optional*): + The specific model version to use. Will default to `"main"` if it's not provided and no `commit_hash` is + provided either. + repo_type (`str`, *optional*): + The type of the repository. Will default to `"model"`. + + Returns: + `Optional[str]` or `_CACHED_NO_EXIST`: + Will return `None` if the file was not cached. Otherwise: + - The exact path to the cached file if it's found in the cache + - A special value `_CACHED_NO_EXIST` if the file does not exist at the given commit hash and this fact was + cached. + + Example: + + ```python + from huggingface_hub import try_to_load_from_cache, _CACHED_NO_EXIST + + filepath = try_to_load_from_cache() + if isinstance(filepath, str): + # file exists and is cached + ... + elif filepath is _CACHED_NO_EXIST: + # non-existence of file is cached + ... + else: + # file is not cached + ... + ``` + """ + if revision is None: + revision = "main" + if repo_type is None: + repo_type = "model" + if repo_type not in REPO_TYPES: + raise ValueError(f"Invalid repo type: {repo_type}. Accepted repo types are: {str(REPO_TYPES)}") + if cache_dir is None: + cache_dir = HF_HUB_CACHE + + object_id = repo_id.replace("/", "--") + repo_cache = os.path.join(cache_dir, f"{repo_type}s--{object_id}") + if not os.path.isdir(repo_cache): + # No cache for this model + return None + + refs_dir = os.path.join(repo_cache, "refs") + snapshots_dir = os.path.join(repo_cache, "snapshots") + no_exist_dir = os.path.join(repo_cache, ".no_exist") + + # Resolve refs (for instance to convert main to the associated commit sha) + if os.path.isdir(refs_dir): + revision_file = os.path.join(refs_dir, revision) + if os.path.isfile(revision_file): + with open(revision_file) as f: + revision = f.read() + + # Check if file is cached as "no_exist" + if os.path.isfile(os.path.join(no_exist_dir, revision, filename)): + return _CACHED_NO_EXIST + + # Check if revision folder exists + if not os.path.exists(snapshots_dir): + return None + cached_shas = os.listdir(snapshots_dir) + if revision not in cached_shas: + # No cache for this revision and we won't try to return a random revision + return None + + # Check if file exists in cache + cached_file = os.path.join(snapshots_dir, revision, filename) + return cached_file if os.path.isfile(cached_file) else None + + +@validate_hf_hub_args +def get_hf_file_metadata( + url: str, + token: Union[bool, str, None] = None, + proxies: Optional[Dict] = None, + timeout: Optional[float] = DEFAULT_REQUEST_TIMEOUT, + library_name: Optional[str] = None, + library_version: Optional[str] = None, + user_agent: Union[Dict, str, None] = None, + headers: Optional[Dict[str, str]] = None, +) -> HfFileMetadata: + """Fetch metadata of a file versioned on the Hub for a given url. + + Args: + url (`str`): + File url, for example returned by [`hf_hub_url`]. + token (`str` or `bool`, *optional*): + A token to be used for the download. + - If `True`, the token is read from the HuggingFace config + folder. + - If `False` or `None`, no token is provided. + - If a string, it's used as the authentication token. + proxies (`dict`, *optional*): + Dictionary mapping protocol to the URL of the proxy passed to + `requests.request`. + timeout (`float`, *optional*, defaults to 10): + How many seconds to wait for the server to send metadata before giving up. + library_name (`str`, *optional*): + The name of the library to which the object corresponds. + library_version (`str`, *optional*): + The version of the library. + user_agent (`dict`, `str`, *optional*): + The user-agent info in the form of a dictionary or a string. + headers (`dict`, *optional*): + Additional headers to be sent with the request. + + Returns: + A [`HfFileMetadata`] object containing metadata such as location, etag, size and + commit_hash. + """ + headers = build_hf_headers( + token=token, + library_name=library_name, + library_version=library_version, + user_agent=user_agent, + headers=headers, + ) + headers["Accept-Encoding"] = "identity" # prevent any compression => we want to know the real size of the file + + # Retrieve metadata + r = _request_wrapper( + method="HEAD", + url=url, + headers=headers, + allow_redirects=False, + follow_relative_redirects=True, + proxies=proxies, + timeout=timeout, + ) + hf_raise_for_status(r) + + # Return + return HfFileMetadata( + commit_hash=r.headers.get(HUGGINGFACE_HEADER_X_REPO_COMMIT), + # We favor a custom header indicating the etag of the linked resource, and + # we fallback to the regular etag header. + etag=_normalize_etag(r.headers.get(HUGGINGFACE_HEADER_X_LINKED_ETAG) or r.headers.get("ETag")), + # Either from response headers (if redirected) or defaults to request url + # Do not use directly `url`, as `_request_wrapper` might have followed relative + # redirects. + location=r.headers.get("Location") or r.request.url, # type: ignore + size=_int_or_none(r.headers.get(HUGGINGFACE_HEADER_X_LINKED_SIZE) or r.headers.get("Content-Length")), + ) + + +def _int_or_none(value: Optional[str]) -> Optional[int]: + try: + return int(value) # type: ignore + except (TypeError, ValueError): + return None + + +def _chmod_and_replace(src: str, dst: str) -> None: + """Set correct permission before moving a blob from tmp directory to cache dir. + + Do not take into account the `umask` from the process as there is no convenient way + to get it that is thread-safe. + + See: + - About umask: https://docs.python.org/3/library/os.html#os.umask + - Thread-safety: https://stackoverflow.com/a/70343066 + - About solution: https://github.com/huggingface/huggingface_hub/pull/1220#issuecomment-1326211591 + - Fix issue: https://github.com/huggingface/huggingface_hub/issues/1141 + - Fix issue: https://github.com/huggingface/huggingface_hub/issues/1215 + """ + # Get umask by creating a temporary file in the cached repo folder. + tmp_file = Path(dst).parent.parent / f"tmp_{uuid.uuid4()}" + try: + tmp_file.touch() + cache_dir_mode = Path(tmp_file).stat().st_mode + os.chmod(src, stat.S_IMODE(cache_dir_mode)) + finally: + tmp_file.unlink() + + shutil.move(src, dst) + + +def _get_pointer_path(storage_folder: str, revision: str, relative_filename: str) -> str: + # Using `os.path.abspath` instead of `Path.resolve()` to avoid resolving symlinks + snapshot_path = os.path.join(storage_folder, "snapshots") + pointer_path = os.path.join(snapshot_path, revision, relative_filename) + if Path(os.path.abspath(snapshot_path)) not in Path(os.path.abspath(pointer_path)).parents: + raise ValueError( + "Invalid pointer path: cannot create pointer path in snapshot folder if" + f" `storage_folder='{storage_folder}'`, `revision='{revision}'` and" + f" `relative_filename='{relative_filename}'`." + ) + return pointer_path + + +def _to_local_dir( + path: str, local_dir: str, relative_filename: str, use_symlinks: Union[bool, Literal["auto"]] +) -> str: + """Place a file in a local dir (different than cache_dir). + + Either symlink to blob file in cache or duplicate file depending on `use_symlinks` and file size. + """ + # Using `os.path.abspath` instead of `Path.resolve()` to avoid resolving symlinks + local_dir_filepath = os.path.join(local_dir, relative_filename) + if Path(os.path.abspath(local_dir)) not in Path(os.path.abspath(local_dir_filepath)).parents: + raise ValueError( + f"Cannot copy file '{relative_filename}' to local dir '{local_dir}': file would not be in the local" + " directory." + ) + + os.makedirs(os.path.dirname(local_dir_filepath), exist_ok=True) + real_blob_path = os.path.realpath(path) + + # If "auto" (default) copy-paste small files to ease manual editing but symlink big files to save disk + if use_symlinks == "auto": + use_symlinks = os.stat(real_blob_path).st_size > constants.HF_HUB_LOCAL_DIR_AUTO_SYMLINK_THRESHOLD + + if use_symlinks: + _create_symlink(real_blob_path, local_dir_filepath, new_blob=False) + else: + shutil.copyfile(real_blob_path, local_dir_filepath) + return local_dir_filepath diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/hf_api.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/hf_api.py new file mode 100644 index 0000000000000000000000000000000000000000..9e77228a8d870f77e46ed486d37240443fdfd62e --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/hf_api.py @@ -0,0 +1,8627 @@ +# coding=utf-8 +# Copyright 2019-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import inspect +import json +import re +import struct +import warnings +from concurrent.futures import Future, ThreadPoolExecutor +from dataclasses import asdict, dataclass, field +from datetime import datetime +from functools import wraps +from itertools import islice +from pathlib import Path +from typing import ( + Any, + BinaryIO, + Callable, + Dict, + Iterable, + Iterator, + List, + Literal, + Optional, + Tuple, + TypeVar, + Union, + overload, +) +from urllib.parse import quote + +import requests +from requests.exceptions import HTTPError +from tqdm.auto import tqdm as base_tqdm +from tqdm.contrib.concurrent import thread_map + +from ._commit_api import ( + CommitOperation, + CommitOperationAdd, + CommitOperationCopy, + CommitOperationDelete, + _fetch_files_to_copy, + _fetch_upload_modes, + _prepare_commit_payload, + _upload_lfs_files, + _warn_on_overwriting_operations, +) +from ._inference_endpoints import InferenceEndpoint, InferenceEndpointType +from ._multi_commits import ( + MULTI_COMMIT_PR_CLOSE_COMMENT_FAILURE_BAD_REQUEST_TEMPLATE, + MULTI_COMMIT_PR_CLOSE_COMMENT_FAILURE_NO_CHANGES_TEMPLATE, + MULTI_COMMIT_PR_CLOSING_COMMENT_TEMPLATE, + MULTI_COMMIT_PR_COMPLETION_COMMENT_TEMPLATE, + MultiCommitException, + MultiCommitStep, + MultiCommitStrategy, + multi_commit_create_pull_request, + multi_commit_generate_comment, + multi_commit_parse_pr_description, + plan_multi_commits, +) +from ._space_api import SpaceHardware, SpaceRuntime, SpaceStorage, SpaceVariable +from .community import ( + Discussion, + DiscussionComment, + DiscussionStatusChange, + DiscussionTitleChange, + DiscussionWithDetails, + deserialize_event, +) +from .constants import ( + DEFAULT_ETAG_TIMEOUT, + DEFAULT_REQUEST_TIMEOUT, + DEFAULT_REVISION, + DISCUSSION_STATUS, + DISCUSSION_TYPES, + ENDPOINT, + INFERENCE_ENDPOINTS_ENDPOINT, + REGEX_COMMIT_OID, + REPO_TYPE_MODEL, + REPO_TYPES, + REPO_TYPES_MAPPING, + REPO_TYPES_URL_PREFIXES, + SAFETENSORS_INDEX_FILE, + SAFETENSORS_MAX_HEADER_LENGTH, + SAFETENSORS_SINGLE_FILE, + SPACES_SDK_TYPES, + DiscussionStatusFilter, + DiscussionTypeFilter, +) +from .file_download import HfFileMetadata, get_hf_file_metadata, hf_hub_url +from .repocard_data import DatasetCardData, ModelCardData, SpaceCardData +from .utils import ( # noqa: F401 # imported for backward compatibility + IGNORE_GIT_FOLDER_PATTERNS, + BadRequestError, + EntryNotFoundError, + GatedRepoError, + HfFolder, + HfHubHTTPError, + LocalTokenNotFoundError, + NotASafetensorsRepoError, + RepositoryNotFoundError, + RevisionNotFoundError, + SafetensorsFileMetadata, + SafetensorsParsingError, + SafetensorsRepoMetadata, + TensorInfo, + build_hf_headers, + experimental, + filter_repo_objects, + fix_hf_endpoint_in_url, + get_session, + hf_raise_for_status, + logging, + paginate, + parse_datetime, + validate_hf_hub_args, +) +from .utils import tqdm as hf_tqdm +from .utils._deprecation import _deprecate_arguments, _deprecate_method +from .utils._typing import CallableT +from .utils.endpoint_helpers import ( + DatasetFilter, + ModelFilter, + _is_emission_within_treshold, +) + + +R = TypeVar("R") # Return type +CollectionItemType_T = Literal["model", "dataset", "space", "paper"] + +USERNAME_PLACEHOLDER = "hf_user" +_REGEX_DISCUSSION_URL = re.compile(r".*/discussions/(\d+)$") + +_CREATE_COMMIT_NO_REPO_ERROR_MESSAGE = ( + "\nNote: Creating a commit assumes that the repo already exists on the" + " Huggingface Hub. Please use `create_repo` if it's not the case." +) + +logger = logging.get_logger(__name__) + + +def repo_type_and_id_from_hf_id(hf_id: str, hub_url: Optional[str] = None) -> Tuple[Optional[str], Optional[str], str]: + """ + Returns the repo type and ID from a huggingface.co URL linking to a + repository + + Args: + hf_id (`str`): + An URL or ID of a repository on the HF hub. Accepted values are: + + - https://huggingface.co/// + - https://huggingface.co// + - hf://// + - hf:/// + - // + - / + - + hub_url (`str`, *optional*): + The URL of the HuggingFace Hub, defaults to https://huggingface.co + + Returns: + A tuple with three items: repo_type (`str` or `None`), namespace (`str` or + `None`) and repo_id (`str`). + + Raises: + - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If URL cannot be parsed. + - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If `repo_type` is unknown. + """ + input_hf_id = hf_id + + hub_url = re.sub(r"https?://", "", hub_url if hub_url is not None else ENDPOINT) + is_hf_url = hub_url in hf_id and "@" not in hf_id + + HFFS_PREFIX = "hf://" + if hf_id.startswith(HFFS_PREFIX): # Remove "hf://" prefix if exists + hf_id = hf_id[len(HFFS_PREFIX) :] + + url_segments = hf_id.split("/") + is_hf_id = len(url_segments) <= 3 + + namespace: Optional[str] + if is_hf_url: + namespace, repo_id = url_segments[-2:] + if namespace == hub_url: + namespace = None + if len(url_segments) > 2 and hub_url not in url_segments[-3]: + repo_type = url_segments[-3] + elif namespace in REPO_TYPES_MAPPING: + # Mean canonical dataset or model + repo_type = REPO_TYPES_MAPPING[namespace] + namespace = None + else: + repo_type = None + elif is_hf_id: + if len(url_segments) == 3: + # Passed // or // + repo_type, namespace, repo_id = url_segments[-3:] + elif len(url_segments) == 2: + if url_segments[0] in REPO_TYPES_MAPPING: + # Passed '' or 'datasets/' for a canonical model or dataset + repo_type = REPO_TYPES_MAPPING[url_segments[0]] + namespace = None + repo_id = hf_id.split("/")[-1] + else: + # Passed / or / + namespace, repo_id = hf_id.split("/")[-2:] + repo_type = None + else: + # Passed + repo_id = url_segments[0] + namespace, repo_type = None, None + else: + raise ValueError(f"Unable to retrieve user and repo ID from the passed HF ID: {hf_id}") + + # Check if repo type is known (mapping "spaces" => "space" + empty value => `None`) + if repo_type in REPO_TYPES_MAPPING: + repo_type = REPO_TYPES_MAPPING[repo_type] + if repo_type == "": + repo_type = None + if repo_type not in REPO_TYPES: + raise ValueError(f"Unknown `repo_type`: '{repo_type}' ('{input_hf_id}')") + + return repo_type, namespace, repo_id + + +@dataclass +class LastCommitInfo(dict): + oid: str + title: str + date: datetime + + def __post_init__(self): # hack to make LastCommitInfo backward compatible + self.update(asdict(self)) + + +@dataclass +class BlobLfsInfo(dict): + size: int + sha256: str + pointer_size: int + + def __post_init__(self): # hack to make BlobLfsInfo backward compatible + self.update(asdict(self)) + + +@dataclass +class BlobSecurityInfo(dict): + safe: bool + av_scan: Optional[Dict] + pickle_import_scan: Optional[Dict] + + def __post_init__(self): # hack to make BlogSecurityInfo backward compatible + self.update(asdict(self)) + + +@dataclass +class TransformersInfo(dict): + auto_model: str + custom_class: Optional[str] = None + # possible `pipeline_tag` values: https://github.com/huggingface/huggingface.js/blob/3ee32554b8620644a6287e786b2a83bf5caf559c/packages/tasks/src/pipelines.ts#L72 + pipeline_tag: Optional[str] = None + processor: Optional[str] = None + + def __post_init__(self): # hack to make TransformersInfo backward compatible + self.update(asdict(self)) + + +@dataclass +class SafeTensorsInfo(dict): + parameters: List[Dict[str, int]] + total: int + + def __post_init__(self): # hack to make SafeTensorsInfo backward compatible + self.update(asdict(self)) + + +@dataclass +class CommitInfo(str): + """Data structure containing information about a newly created commit. + + Returned by any method that creates a commit on the Hub: [`create_commit`], [`upload_file`], [`upload_folder`], + [`delete_file`], [`delete_folder`]. It inherits from `str` for backward compatibility but using methods specific + to `str` is deprecated. + + Attributes: + commit_url (`str`): + Url where to find the commit. + + commit_message (`str`): + The summary (first line) of the commit that has been created. + + commit_description (`str`): + Description of the commit that has been created. Can be empty. + + oid (`str`): + Commit hash id. Example: `"91c54ad1727ee830252e457677f467be0bfd8a57"`. + + pr_url (`str`, *optional*): + Url to the PR that has been created, if any. Populated when `create_pr=True` + is passed. + + pr_revision (`str`, *optional*): + Revision of the PR that has been created, if any. Populated when + `create_pr=True` is passed. Example: `"refs/pr/1"`. + + pr_num (`int`, *optional*): + Number of the PR discussion that has been created, if any. Populated when + `create_pr=True` is passed. Can be passed as `discussion_num` in + [`get_discussion_details`]. Example: `1`. + + _url (`str`, *optional*): + Legacy url for `str` compatibility. Can be the url to the uploaded file on the Hub (if returned by + [`upload_file`]), to the uploaded folder on the Hub (if returned by [`upload_folder`]) or to the commit on + the Hub (if returned by [`create_commit`]). Defaults to `commit_url`. It is deprecated to use this + attribute. Please use `commit_url` instead. + """ + + commit_url: str + commit_message: str + commit_description: str + oid: str + pr_url: Optional[str] = None + + # Computed from `pr_url` in `__post_init__` + pr_revision: Optional[str] = field(init=False) + pr_num: Optional[str] = field(init=False) + + # legacy url for `str` compatibility (ex: url to uploaded file, url to uploaded folder, url to PR, etc.) + _url: str = field(repr=False, default=None) # type: ignore # defaults to `commit_url` + + def __new__(cls, *args, commit_url: str, _url: Optional[str] = None, **kwargs): + return str.__new__(cls, _url or commit_url) + + def __post_init__(self): + """Populate pr-related fields after initialization. + + See https://docs.python.org/3.10/library/dataclasses.html#post-init-processing. + """ + if self.pr_url is not None: + self.pr_revision = _parse_revision_from_pr_url(self.pr_url) + self.pr_num = int(self.pr_revision.split("/")[-1]) + else: + self.pr_revision = None + self.pr_num = None + + +@dataclass +class AccessRequest: + """Data structure containing information about a user access request. + + Attributes: + username (`str`): + Username of the user who requested access. + fullname (`str`): + Fullname of the user who requested access. + email (`str`): + Email of the user who requested access. + timestamp (`datetime`): + Timestamp of the request. + status (`Literal["pending", "accepted", "rejected"]`): + Status of the request. Can be one of `["pending", "accepted", "rejected"]`. + fields (`Dict[str, Any]`, *optional*): + Additional fields filled by the user in the gate form. + """ + + username: str + fullname: str + email: str + timestamp: datetime + status: Literal["pending", "accepted", "rejected"] + + # Additional fields filled by the user in the gate form + fields: Optional[Dict[str, Any]] = None + + +class RepoUrl(str): + """Subclass of `str` describing a repo URL on the Hub. + + `RepoUrl` is returned by `HfApi.create_repo`. It inherits from `str` for backward + compatibility. At initialization, the URL is parsed to populate properties: + - endpoint (`str`) + - namespace (`Optional[str]`) + - repo_name (`str`) + - repo_id (`str`) + - repo_type (`Literal["model", "dataset", "space"]`) + - url (`str`) + + Args: + url (`Any`): + String value of the repo url. + endpoint (`str`, *optional*): + Endpoint of the Hub. Defaults to . + + Example: + ```py + >>> RepoUrl('https://huggingface.co/gpt2') + RepoUrl('https://huggingface.co/gpt2', endpoint='https://huggingface.co', repo_type='model', repo_id='gpt2') + + >>> RepoUrl('https://hub-ci.huggingface.co/datasets/dummy_user/dummy_dataset', endpoint='https://hub-ci.huggingface.co') + RepoUrl('https://hub-ci.huggingface.co/datasets/dummy_user/dummy_dataset', endpoint='https://hub-ci.huggingface.co', repo_type='dataset', repo_id='dummy_user/dummy_dataset') + + >>> RepoUrl('hf://datasets/my-user/my-dataset') + RepoUrl('hf://datasets/my-user/my-dataset', endpoint='https://huggingface.co', repo_type='dataset', repo_id='user/dataset') + + >>> HfApi.create_repo("dummy_model") + RepoUrl('https://huggingface.co/Wauplin/dummy_model', endpoint='https://huggingface.co', repo_type='model', repo_id='Wauplin/dummy_model') + ``` + + Raises: + - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If URL cannot be parsed. + - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If `repo_type` is unknown. + """ + + def __new__(cls, url: Any, endpoint: Optional[str] = None): + url = fix_hf_endpoint_in_url(url, endpoint=endpoint) + return super(RepoUrl, cls).__new__(cls, url) + + def __init__(self, url: Any, endpoint: Optional[str] = None) -> None: + super().__init__() + # Parse URL + self.endpoint = endpoint or ENDPOINT + repo_type, namespace, repo_name = repo_type_and_id_from_hf_id(self, hub_url=self.endpoint) + + # Populate fields + self.namespace = namespace + self.repo_name = repo_name + self.repo_id = repo_name if namespace is None else f"{namespace}/{repo_name}" + self.repo_type = repo_type or REPO_TYPE_MODEL + self.url = str(self) # just in case it's needed + + def __repr__(self) -> str: + return f"RepoUrl('{self}', endpoint='{self.endpoint}', repo_type='{self.repo_type}', repo_id='{self.repo_id}')" + + +@dataclass +class RepoSibling: + """ + Contains basic information about a repo file inside a repo on the Hub. + + + + All attributes of this class are optional except `rfilename`. This is because only the file names are returned when + listing repositories on the Hub (with [`list_models`], [`list_datasets`] or [`list_spaces`]). If you need more + information like file size, blob id or lfs details, you must request them specifically from one repo at a time + (using [`model_info`], [`dataset_info`] or [`space_info`]) as it adds more constraints on the backend server to + retrieve these. + + + + Attributes: + rfilename (str): + file name, relative to the repo root. + size (`int`, *optional*): + The file's size, in bytes. This attribute is defined when `files_metadata` argument of [`repo_info`] is set + to `True`. It's `None` otherwise. + blob_id (`str`, *optional*): + The file's git OID. This attribute is defined when `files_metadata` argument of [`repo_info`] is set to + `True`. It's `None` otherwise. + lfs (`BlobLfsInfo`, *optional*): + The file's LFS metadata. This attribute is defined when`files_metadata` argument of [`repo_info`] is set to + `True` and the file is stored with Git LFS. It's `None` otherwise. + """ + + rfilename: str + size: Optional[int] = None + blob_id: Optional[str] = None + lfs: Optional[BlobLfsInfo] = None + + +@dataclass +class RepoFile: + """ + Contains information about a file on the Hub. + + Attributes: + path (str): + file path relative to the repo root. + size (`int`): + The file's size, in bytes. + blob_id (`str`): + The file's git OID. + lfs (`BlobLfsInfo`): + The file's LFS metadata. + last_commit (`LastCommitInfo`, *optional*): + The file's last commit metadata. Only defined if [`list_files_info`], [`list_repo_tree`] and [`get_paths_info`] + are called with `expand=True`. + security (`BlobSecurityInfo`, *optional*): + The file's security scan metadata. Only defined if [`list_files_info`], [`list_repo_tree`] and [`get_paths_info`] + are called with `expand=True`. + """ + + path: str + size: int + blob_id: str + lfs: Optional[BlobLfsInfo] = None + last_commit: Optional[LastCommitInfo] = None + security: Optional[BlobSecurityInfo] = None + + def __init__(self, **kwargs): + self.path = kwargs.pop("path") + self.size = kwargs.pop("size") + self.blob_id = kwargs.pop("oid") + lfs = kwargs.pop("lfs", None) + if lfs is not None: + lfs = BlobLfsInfo(size=lfs["size"], sha256=lfs["oid"], pointer_size=lfs["pointerSize"]) + self.lfs = lfs + last_commit = kwargs.pop("lastCommit", None) or kwargs.pop("last_commit", None) + if last_commit is not None: + last_commit = LastCommitInfo( + oid=last_commit["id"], title=last_commit["title"], date=parse_datetime(last_commit["date"]) + ) + self.last_commit = last_commit + security = kwargs.pop("security", None) + if security is not None: + security = BlobSecurityInfo( + safe=security["safe"], av_scan=security["avScan"], pickle_import_scan=security["pickleImportScan"] + ) + self.security = security + + # backwards compatibility + self.rfilename = self.path + self.lastCommit = self.last_commit + + +@dataclass +class RepoFolder: + """ + Contains information about a folder on the Hub. + + Attributes: + path (str): + folder path relative to the repo root. + tree_id (`str`): + The folder's git OID. + last_commit (`LastCommitInfo`, *optional*): + The folder's last commit metadata. Only defined if [`list_repo_tree`] and [`get_paths_info`] + are called with `expand=True`. + """ + + path: str + tree_id: str + last_commit: Optional[LastCommitInfo] = None + + def __init__(self, **kwargs): + self.path = kwargs.pop("path") + self.tree_id = kwargs.pop("oid") + last_commit = kwargs.pop("lastCommit", None) or kwargs.pop("last_commit", None) + if last_commit is not None: + last_commit = LastCommitInfo( + oid=last_commit["id"], title=last_commit["title"], date=parse_datetime(last_commit["date"]) + ) + self.last_commit = last_commit + + +@dataclass +class ModelInfo: + """ + Contains information about a model on the Hub. + + + + Most attributes of this class are optional. This is because the data returned by the Hub depends on the query made. + In general, the more specific the query, the more information is returned. On the contrary, when listing models + using [`list_models`] only a subset of the attributes are returned. + + + + Attributes: + id (`str`): + ID of model. + author (`str`, *optional*): + Author of the model. + sha (`str`, *optional*): + Repo SHA at this particular revision. + created_at (`datetime`, *optional*): + Date of creation of the repo on the Hub. Note that the lowest value is `2022-03-02T23:29:04.000Z`, + corresponding to the date when we began to store creation dates. + last_modified (`datetime`, *optional*): + Date of last commit to the repo. + private (`bool`): + Is the repo private. + disabled (`bool`, *optional*): + Is the repo disabled. + gated (`Literal["auto", "manual", False]`, *optional*): + Is the repo gated. + If so, whether there is manual or automatic approval. + downloads (`int`): + Number of downloads of the model. + likes (`int`): + Number of likes of the model. + library_name (`str`, *optional*): + Library associated with the model. + tags (`List[str]`): + List of tags of the model. Compared to `card_data.tags`, contains extra tags computed by the Hub + (e.g. supported libraries, model's arXiv). + pipeline_tag (`str`, *optional*): + Pipeline tag associated with the model. + mask_token (`str`, *optional*): + Mask token used by the model. + widget_data (`Any`, *optional*): + Widget data associated with the model. + model_index (`Dict`, *optional*): + Model index for evaluation. + config (`Dict`, *optional*): + Model configuration. + transformers_info (`TransformersInfo`, *optional*): + Transformers-specific info (auto class, processor, etc.) associated with the model. + card_data (`ModelCardData`, *optional*): + Model Card Metadata as a [`huggingface_hub.repocard_data.ModelCardData`] object. + siblings (`List[RepoSibling]`): + List of [`huggingface_hub.hf_api.RepoSibling`] objects that constitute the model. + spaces (`List[str]`, *optional*): + List of spaces using the model. + safetensors (`SafeTensorsInfo`, *optional*): + Model's safetensors information. + """ + + id: str + author: Optional[str] + sha: Optional[str] + created_at: Optional[datetime] + last_modified: Optional[datetime] + private: bool + gated: Optional[Literal["auto", "manual", False]] + disabled: Optional[bool] + downloads: int + likes: int + library_name: Optional[str] + tags: List[str] + pipeline_tag: Optional[str] + mask_token: Optional[str] + card_data: Optional[ModelCardData] + widget_data: Optional[Any] + model_index: Optional[Dict] + config: Optional[Dict] + transformers_info: Optional[TransformersInfo] + siblings: Optional[List[RepoSibling]] + spaces: Optional[List[str]] + safetensors: Optional[SafeTensorsInfo] + + def __init__(self, **kwargs): + self.id = kwargs.pop("id") + self.author = kwargs.pop("author", None) + self.sha = kwargs.pop("sha", None) + last_modified = kwargs.pop("lastModified", None) or kwargs.pop("last_modified", None) + self.last_modified = parse_datetime(last_modified) if last_modified else None + created_at = kwargs.pop("createdAt", None) or kwargs.pop("created_at", None) + self.created_at = parse_datetime(created_at) if created_at else None + self.private = kwargs.pop("private") + self.gated = kwargs.pop("gated", None) + self.disabled = kwargs.pop("disabled", None) + self.downloads = kwargs.pop("downloads") + self.likes = kwargs.pop("likes") + self.library_name = kwargs.pop("library_name", None) + self.tags = kwargs.pop("tags") + self.pipeline_tag = kwargs.pop("pipeline_tag", None) + self.mask_token = kwargs.pop("mask_token", None) + card_data = kwargs.pop("cardData", None) or kwargs.pop("card_data", None) + self.card_data = ( + ModelCardData(**card_data, ignore_metadata_errors=True) if isinstance(card_data, dict) else card_data + ) + + self.widget_data = kwargs.pop("widgetData", None) + self.model_index = kwargs.pop("model-index", None) or kwargs.pop("model_index", None) + self.config = kwargs.pop("config", None) + transformers_info = kwargs.pop("transformersInfo", None) or kwargs.pop("transformers_info", None) + self.transformers_info = TransformersInfo(**transformers_info) if transformers_info else None + siblings = kwargs.pop("siblings", None) + self.siblings = ( + [ + RepoSibling( + rfilename=sibling["rfilename"], + size=sibling.get("size"), + blob_id=sibling.get("blobId"), + lfs=( + BlobLfsInfo( + size=sibling["lfs"]["size"], + sha256=sibling["lfs"]["sha256"], + pointer_size=sibling["lfs"]["pointerSize"], + ) + if sibling.get("lfs") + else None + ), + ) + for sibling in siblings + ] + if siblings + else None + ) + self.spaces = kwargs.pop("spaces", None) + safetensors = kwargs.pop("safetensors", None) + self.safetensors = SafeTensorsInfo(**safetensors) if safetensors else None + + # backwards compatibility + self.lastModified = self.last_modified + self.cardData = self.card_data + self.transformersInfo = self.transformers_info + self.__dict__.update(**kwargs) + + +@dataclass +class DatasetInfo: + """ + Contains information about a dataset on the Hub. + + + + Most attributes of this class are optional. This is because the data returned by the Hub depends on the query made. + In general, the more specific the query, the more information is returned. On the contrary, when listing datasets + using [`list_datasets`] only a subset of the attributes are returned. + + + + Attributes: + id (`str`): + ID of dataset. + author (`str`): + Author of the dataset. + sha (`str`): + Repo SHA at this particular revision. + created_at (`datetime`, *optional*): + Date of creation of the repo on the Hub. Note that the lowest value is `2022-03-02T23:29:04.000Z`, + corresponding to the date when we began to store creation dates. + last_modified (`datetime`, *optional*): + Date of last commit to the repo. + private (`bool`): + Is the repo private. + disabled (`bool`, *optional*): + Is the repo disabled. + gated (`Literal["auto", "manual", False]`, *optional*): + Is the repo gated. + If so, whether there is manual or automatic approval. + downloads (`int`): + Number of downloads of the dataset. + likes (`int`): + Number of likes of the dataset. + tags (`List[str]`): + List of tags of the dataset. + card_data (`DatasetCardData`, *optional*): + Model Card Metadata as a [`huggingface_hub.repocard_data.DatasetCardData`] object. + siblings (`List[RepoSibling]`): + List of [`huggingface_hub.hf_api.RepoSibling`] objects that constitute the dataset. + """ + + id: str + author: Optional[str] + sha: Optional[str] + created_at: Optional[datetime] + last_modified: Optional[datetime] + private: bool + gated: Optional[Literal["auto", "manual", False]] + disabled: Optional[bool] + downloads: int + likes: int + paperswithcode_id: Optional[str] + tags: List[str] + card_data: Optional[DatasetCardData] + siblings: Optional[List[RepoSibling]] + + def __init__(self, **kwargs): + self.id = kwargs.pop("id") + self.author = kwargs.pop("author", None) + self.sha = kwargs.pop("sha", None) + created_at = kwargs.pop("createdAt", None) or kwargs.pop("created_at", None) + self.created_at = parse_datetime(created_at) if created_at else None + last_modified = kwargs.pop("lastModified", None) or kwargs.pop("last_modified", None) + self.last_modified = parse_datetime(last_modified) if last_modified else None + self.private = kwargs.pop("private") + self.gated = kwargs.pop("gated", None) + self.disabled = kwargs.pop("disabled", None) + self.downloads = kwargs.pop("downloads") + self.likes = kwargs.pop("likes") + self.paperswithcode_id = kwargs.pop("paperswithcode_id", None) + self.tags = kwargs.pop("tags") + card_data = kwargs.pop("cardData", None) or kwargs.pop("card_data", None) + self.card_data = ( + DatasetCardData(**card_data, ignore_metadata_errors=True) if isinstance(card_data, dict) else card_data + ) + siblings = kwargs.pop("siblings", None) + self.siblings = ( + [ + RepoSibling( + rfilename=sibling["rfilename"], + size=sibling.get("size"), + blob_id=sibling.get("blobId"), + lfs=( + BlobLfsInfo( + size=sibling["lfs"]["size"], + sha256=sibling["lfs"]["sha256"], + pointer_size=sibling["lfs"]["pointerSize"], + ) + if sibling.get("lfs") + else None + ), + ) + for sibling in siblings + ] + if siblings + else None + ) + + # backwards compatibility + self.lastModified = self.last_modified + self.cardData = self.card_data + self.__dict__.update(**kwargs) + + +@dataclass +class SpaceInfo: + """ + Contains information about a Space on the Hub. + + + + Most attributes of this class are optional. This is because the data returned by the Hub depends on the query made. + In general, the more specific the query, the more information is returned. On the contrary, when listing spaces + using [`list_spaces`] only a subset of the attributes are returned. + + + + Attributes: + id (`str`): + ID of the Space. + author (`str`, *optional*): + Author of the Space. + sha (`str`, *optional*): + Repo SHA at this particular revision. + created_at (`datetime`, *optional*): + Date of creation of the repo on the Hub. Note that the lowest value is `2022-03-02T23:29:04.000Z`, + corresponding to the date when we began to store creation dates. + last_modified (`datetime`, *optional*): + Date of last commit to the repo. + private (`bool`): + Is the repo private. + gated (`Literal["auto", "manual", False]`, *optional*): + Is the repo gated. + If so, whether there is manual or automatic approval. + disabled (`bool`, *optional*): + Is the Space disabled. + host (`str`, *optional*): + Host URL of the Space. + subdomain (`str`, *optional*): + Subdomain of the Space. + likes (`int`): + Number of likes of the Space. + tags (`List[str]`): + List of tags of the Space. + siblings (`List[RepoSibling]`): + List of [`huggingface_hub.hf_api.RepoSibling`] objects that constitute the Space. + card_data (`SpaceCardData`, *optional*): + Space Card Metadata as a [`huggingface_hub.repocard_data.SpaceCardData`] object. + runtime (`SpaceRuntime`, *optional*): + Space runtime information as a [`huggingface_hub.hf_api.SpaceRuntime`] object. + sdk (`str`, *optional*): + SDK used by the Space. + models (`List[str]`, *optional*): + List of models used by the Space. + datasets (`List[str]`, *optional*): + List of datasets used by the Space. + """ + + id: str + author: Optional[str] + sha: Optional[str] + created_at: Optional[datetime] + last_modified: Optional[datetime] + private: bool + gated: Optional[Literal["auto", "manual", False]] + disabled: Optional[bool] + host: Optional[str] + subdomain: Optional[str] + likes: int + sdk: Optional[str] + tags: List[str] + siblings: Optional[List[RepoSibling]] + card_data: Optional[SpaceCardData] + runtime: Optional[SpaceRuntime] + models: Optional[List[str]] + datasets: Optional[List[str]] + + def __init__(self, **kwargs): + self.id = kwargs.pop("id") + self.author = kwargs.pop("author", None) + self.sha = kwargs.pop("sha", None) + created_at = kwargs.pop("createdAt", None) or kwargs.pop("created_at", None) + self.created_at = parse_datetime(created_at) if created_at else None + last_modified = kwargs.pop("lastModified", None) or kwargs.pop("last_modified", None) + self.last_modified = parse_datetime(last_modified) if last_modified else None + self.private = kwargs.pop("private") + self.gated = kwargs.pop("gated", None) + self.disabled = kwargs.pop("disabled", None) + self.host = kwargs.pop("host", None) + self.subdomain = kwargs.pop("subdomain", None) + self.likes = kwargs.pop("likes") + self.sdk = kwargs.pop("sdk", None) + self.tags = kwargs.pop("tags") + card_data = kwargs.pop("cardData", None) or kwargs.pop("card_data", None) + self.card_data = ( + SpaceCardData(**card_data, ignore_metadata_errors=True) if isinstance(card_data, dict) else card_data + ) + siblings = kwargs.pop("siblings", None) + self.siblings = ( + [ + RepoSibling( + rfilename=sibling["rfilename"], + size=sibling.get("size"), + blob_id=sibling.get("blobId"), + lfs=( + BlobLfsInfo( + size=sibling["lfs"]["size"], + sha256=sibling["lfs"]["sha256"], + pointer_size=sibling["lfs"]["pointerSize"], + ) + if sibling.get("lfs") + else None + ), + ) + for sibling in siblings + ] + if siblings + else None + ) + runtime = kwargs.pop("runtime", None) + self.runtime = SpaceRuntime(runtime) if runtime else None + self.models = kwargs.pop("models", None) + self.datasets = kwargs.pop("datasets", None) + + # backwards compatibility + self.lastModified = self.last_modified + self.cardData = self.card_data + self.__dict__.update(**kwargs) + + +@dataclass +class MetricInfo: + """ + Contains information about a metric on the Hub. + + Attributes: + id (`str`): + ID of the metric. E.g. `"accuracy"`. + space_id (`str`): + ID of the space associated with the metric. E.g. `"Accuracy"`. + description (`str`): + Description of the metric. + """ + + id: str + space_id: str + description: Optional[str] + + def __init__(self, **kwargs): + self.id = kwargs.pop("id") + self.space_id = kwargs.pop("spaceId") + self.description = kwargs.pop("description", None) + # backwards compatibility + self.spaceId = self.space_id + self.__dict__.update(**kwargs) + + +@dataclass +class CollectionItem: + """ + Contains information about an item of a Collection (model, dataset, Space or paper). + + Attributes: + item_object_id (`str`): + Unique ID of the item in the collection. + item_id (`str`): + ID of the underlying object on the Hub. Can be either a repo_id or a paper id + e.g. `"jbilcke-hf/ai-comic-factory"`, `"2307.09288"`. + item_type (`str`): + Type of the underlying object. Can be one of `"model"`, `"dataset"`, `"space"` or `"paper"`. + position (`int`): + Position of the item in the collection. + note (`str`, *optional*): + Note associated with the item, as plain text. + """ + + item_object_id: str # id in database + item_id: str # repo_id or paper id + item_type: str + position: int + note: Optional[str] = None + + def __init__( + self, _id: str, id: str, type: CollectionItemType_T, position: int, note: Optional[Dict] = None, **kwargs + ) -> None: + self.item_object_id: str = _id # id in database + self.item_id: str = id # repo_id or paper id + self.item_type: CollectionItemType_T = type + self.position: int = position + self.note: str = note["text"] if note is not None else None + + +@dataclass +class Collection: + """ + Contains information about a Collection on the Hub. + + Attributes: + slug (`str`): + Slug of the collection. E.g. `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`. + title (`str`): + Title of the collection. E.g. `"Recent models"`. + owner (`str`): + Owner of the collection. E.g. `"TheBloke"`. + items (`List[CollectionItem]`): + List of items in the collection. + last_updated (`datetime`): + Date of the last update of the collection. + position (`int`): + Position of the collection in the list of collections of the owner. + private (`bool`): + Whether the collection is private or not. + theme (`str`): + Theme of the collection. E.g. `"green"`. + upvotes (`int`): + Number of upvotes of the collection. + description (`str`, *optional*): + Description of the collection, as plain text. + url (`str`): + (property) URL of the collection on the Hub. + """ + + slug: str + title: str + owner: str + items: List[CollectionItem] + last_updated: datetime + position: int + private: bool + theme: str + upvotes: int + description: Optional[str] = None + + def __init__(self, **kwargs) -> None: + self.slug = kwargs.pop("slug") + self.title = kwargs.pop("title") + self.owner = kwargs.pop("owner") + self.items = [CollectionItem(**item) for item in kwargs.pop("items")] + self.last_updated = parse_datetime(kwargs.pop("lastUpdated")) + self.position = kwargs.pop("position") + self.private = kwargs.pop("private") + self.theme = kwargs.pop("theme") + self.upvotes = kwargs.pop("upvotes") + self.description = kwargs.pop("description", None) + endpoint = kwargs.pop("endpoint", None) + if endpoint is None: + endpoint = ENDPOINT + self._url = f"{endpoint}/collections/{self.slug}" + + @property + def url(self) -> str: + """Returns the URL of the collection on the Hub.""" + return self._url + + +@dataclass +class GitRefInfo: + """ + Contains information about a git reference for a repo on the Hub. + + Attributes: + name (`str`): + Name of the reference (e.g. tag name or branch name). + ref (`str`): + Full git ref on the Hub (e.g. `"refs/heads/main"` or `"refs/tags/v1.0"`). + target_commit (`str`): + OID of the target commit for the ref (e.g. `"e7da7f221d5bf496a48136c0cd264e630fe9fcc8"`) + """ + + name: str + ref: str + target_commit: str + + +@dataclass +class GitRefs: + """ + Contains information about all git references for a repo on the Hub. + + Object is returned by [`list_repo_refs`]. + + Attributes: + branches (`List[GitRefInfo]`): + A list of [`GitRefInfo`] containing information about branches on the repo. + converts (`List[GitRefInfo]`): + A list of [`GitRefInfo`] containing information about "convert" refs on the repo. + Converts are refs used (internally) to push preprocessed data in Dataset repos. + tags (`List[GitRefInfo]`): + A list of [`GitRefInfo`] containing information about tags on the repo. + pull_requests (`List[GitRefInfo]`, *optional*): + A list of [`GitRefInfo`] containing information about pull requests on the repo. + Only returned if `include_prs=True` is set. + """ + + branches: List[GitRefInfo] + converts: List[GitRefInfo] + tags: List[GitRefInfo] + pull_requests: Optional[List[GitRefInfo]] = None + + +@dataclass +class GitCommitInfo: + """ + Contains information about a git commit for a repo on the Hub. Check out [`list_repo_commits`] for more details. + + Attributes: + commit_id (`str`): + OID of the commit (e.g. `"e7da7f221d5bf496a48136c0cd264e630fe9fcc8"`) + authors (`List[str]`): + List of authors of the commit. + created_at (`datetime`): + Datetime when the commit was created. + title (`str`): + Title of the commit. This is a free-text value entered by the authors. + message (`str`): + Description of the commit. This is a free-text value entered by the authors. + formatted_title (`str`): + Title of the commit formatted as HTML. Only returned if `formatted=True` is set. + formatted_message (`str`): + Description of the commit formatted as HTML. Only returned if `formatted=True` is set. + """ + + commit_id: str + + authors: List[str] + created_at: datetime + title: str + message: str + + formatted_title: Optional[str] + formatted_message: Optional[str] + + +@dataclass +class UserLikes: + """ + Contains information about a user likes on the Hub. + + Attributes: + user (`str`): + Name of the user for which we fetched the likes. + total (`int`): + Total number of likes. + datasets (`List[str]`): + List of datasets liked by the user (as repo_ids). + models (`List[str]`): + List of models liked by the user (as repo_ids). + spaces (`List[str]`): + List of spaces liked by the user (as repo_ids). + """ + + # Metadata + user: str + total: int + + # User likes + datasets: List[str] + models: List[str] + spaces: List[str] + + +@dataclass +class User: + """ + Contains information about a user on the Hub. + + Attributes: + avatar_url (`str`): + URL of the user's avatar. + username (`str`): + Name of the user on the Hub (unique). + fullname (`str`): + User's full name. + """ + + # Metadata + avatar_url: str + username: str + fullname: str + + +def future_compatible(fn: CallableT) -> CallableT: + """Wrap a method of `HfApi` to handle `run_as_future=True`. + + A method flagged as "future_compatible" will be called in a thread if `run_as_future=True` and return a + `concurrent.futures.Future` instance. Otherwise, it will be called normally and return the result. + """ + sig = inspect.signature(fn) + args_params = list(sig.parameters)[1:] # remove "self" from list + + @wraps(fn) + def _inner(self, *args, **kwargs): + # Get `run_as_future` value if provided (default to False) + if "run_as_future" in kwargs: + run_as_future = kwargs["run_as_future"] + kwargs["run_as_future"] = False # avoid recursion error + else: + run_as_future = False + for param, value in zip(args_params, args): + if param == "run_as_future": + run_as_future = value + break + + # Call the function in a thread if `run_as_future=True` + if run_as_future: + return self.run_as_future(fn, self, *args, **kwargs) + + # Otherwise, call the function normally + return fn(self, *args, **kwargs) + + _inner.is_future_compatible = True # type: ignore + return _inner # type: ignore + + +class HfApi: + def __init__( + self, + endpoint: Optional[str] = None, + token: Union[str, bool, None] = None, + library_name: Optional[str] = None, + library_version: Optional[str] = None, + user_agent: Union[Dict, str, None] = None, + headers: Optional[Dict[str, str]] = None, + ) -> None: + """Create a HF client to interact with the Hub via HTTP. + + The client is initialized with some high-level settings used in all requests + made to the Hub (HF endpoint, authentication, user agents...). Using the `HfApi` + client is preferred but not mandatory as all of its public methods are exposed + directly at the root of `huggingface_hub`. + + Args: + token (`str` or `bool`, *optional*): + Hugging Face token. Will default to the locally saved token if not provided. + Pass `token=False` if you don't want to send your token to the server. + library_name (`str`, *optional*): + The name of the library that is making the HTTP request. Will be added to + the user-agent header. Example: `"transformers"`. + library_version (`str`, *optional*): + The version of the library that is making the HTTP request. Will be added + to the user-agent header. Example: `"4.24.0"`. + user_agent (`str`, `dict`, *optional*): + The user agent info in the form of a dictionary or a single string. It will + be completed with information about the installed packages. + headers (`dict`, *optional*): + Additional headers to be sent with each request. Example: `{"X-My-Header": "value"}`. + Headers passed here are taking precedence over the default headers. + """ + self.endpoint = endpoint if endpoint is not None else ENDPOINT + self.token = token + self.library_name = library_name + self.library_version = library_version + self.user_agent = user_agent + self.headers = headers + self._thread_pool: Optional[ThreadPoolExecutor] = None + + def run_as_future(self, fn: Callable[..., R], *args, **kwargs) -> Future[R]: + """ + Run a method in the background and return a Future instance. + + The main goal is to run methods without blocking the main thread (e.g. to push data during a training). + Background jobs are queued to preserve order but are not ran in parallel. If you need to speed-up your scripts + by parallelizing lots of call to the API, you must setup and use your own [ThreadPoolExecutor](https://docs.python.org/3/library/concurrent.futures.html#threadpoolexecutor). + + Note: Most-used methods like [`upload_file`], [`upload_folder`] and [`create_commit`] have a `run_as_future: bool` + argument to directly call them in the background. This is equivalent to calling `api.run_as_future(...)` on them + but less verbose. + + Args: + fn (`Callable`): + The method to run in the background. + *args, **kwargs: + Arguments with which the method will be called. + + Return: + `Future`: a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects) instance to + get the result of the task. + + Example: + ```py + >>> from huggingface_hub import HfApi + >>> api = HfApi() + >>> future = api.run_as_future(api.whoami) # instant + >>> future.done() + False + >>> future.result() # wait until complete and return result + (...) + >>> future.done() + True + ``` + """ + if self._thread_pool is None: + self._thread_pool = ThreadPoolExecutor(max_workers=1) + self._thread_pool + return self._thread_pool.submit(fn, *args, **kwargs) + + @validate_hf_hub_args + def whoami(self, token: Optional[str] = None) -> Dict: + """ + Call HF API to know "whoami". + + Args: + token (`str`, *optional*): + Hugging Face token. Will default to the locally saved token if + not provided. + """ + r = get_session().get( + f"{self.endpoint}/api/whoami-v2", + headers=self._build_hf_headers( + # If `token` is provided and not `None`, it will be used by default. + # Otherwise, the token must be retrieved from cache or env variable. + token=(token or self.token or True), + ), + ) + try: + hf_raise_for_status(r) + except HTTPError as e: + raise HTTPError( + "Invalid user token. If you didn't pass a user token, make sure you " + "are properly logged in by executing `huggingface-cli login`, and " + "if you did pass a user token, double-check it's correct.", + request=e.request, + response=e.response, + ) from e + return r.json() + + def get_token_permission(self, token: Optional[str] = None) -> Literal["read", "write", None]: + """ + Check if a given `token` is valid and return its permissions. + + For more details about tokens, please refer to https://huggingface.co/docs/hub/security-tokens#what-are-user-access-tokens. + + Args: + token (`str`, *optional*): + The token to check for validity. Defaults to the one saved locally. + + Returns: + `Literal["read", "write", None]`: Permission granted by the token ("read" or "write"). Returns `None` if no + token passed or token is invalid. + """ + try: + return self.whoami(token=token)["auth"]["accessToken"]["role"] + except (LocalTokenNotFoundError, HTTPError): + return None + + def get_model_tags(self) -> Dict: + """ + List all valid model tags as a nested namespace object + """ + path = f"{self.endpoint}/api/models-tags-by-type" + r = get_session().get(path) + hf_raise_for_status(r) + return r.json() + + def get_dataset_tags(self) -> Dict: + """ + List all valid dataset tags as a nested namespace object. + """ + path = f"{self.endpoint}/api/datasets-tags-by-type" + r = get_session().get(path) + hf_raise_for_status(r) + return r.json() + + @validate_hf_hub_args + def list_models( + self, + *, + filter: Union[ModelFilter, str, Iterable[str], None] = None, + author: Optional[str] = None, + library: Optional[Union[str, List[str]]] = None, + language: Optional[Union[str, List[str]]] = None, + model_name: Optional[str] = None, + task: Optional[Union[str, List[str]]] = None, + trained_dataset: Optional[Union[str, List[str]]] = None, + tags: Optional[Union[str, List[str]]] = None, + search: Optional[str] = None, + emissions_thresholds: Optional[Tuple[float, float]] = None, + sort: Union[Literal["last_modified"], str, None] = None, + direction: Optional[Literal[-1]] = None, + limit: Optional[int] = None, + full: Optional[bool] = None, + cardData: bool = False, + fetch_config: bool = False, + token: Optional[Union[bool, str]] = None, + pipeline_tag: Optional[str] = None, + ) -> Iterable[ModelInfo]: + """ + List models hosted on the Huggingface Hub, given some filters. + + Args: + filter ([`ModelFilter`] or `str` or `Iterable`, *optional*): + A string or [`ModelFilter`] which can be used to identify models + on the Hub. + author (`str`, *optional*): + A string which identify the author (user or organization) of the + returned models + library (`str` or `List`, *optional*): + A string or list of strings of foundational libraries models were + originally trained from, such as pytorch, tensorflow, or allennlp. + language (`str` or `List`, *optional*): + A string or list of strings of languages, both by name and country + code, such as "en" or "English" + model_name (`str`, *optional*): + A string that contain complete or partial names for models on the + Hub, such as "bert" or "bert-base-cased" + task (`str` or `List`, *optional*): + A string or list of strings of tasks models were designed for, such + as: "fill-mask" or "automatic-speech-recognition" + trained_dataset (`str` or `List`, *optional*): + A string tag or a list of string tags of the trained dataset for a + model on the Hub. + tags (`str` or `List`, *optional*): + A string tag or a list of tags to filter models on the Hub by, such + as `text-generation` or `spacy`. + search (`str`, *optional*): + A string that will be contained in the returned model ids. + emissions_thresholds (`Tuple`, *optional*): + A tuple of two ints or floats representing a minimum and maximum + carbon footprint to filter the resulting models with in grams. + sort (`Literal["last_modified"]` or `str`, *optional*): + The key with which to sort the resulting models. Possible values + are the properties of the [`huggingface_hub.hf_api.ModelInfo`] class. + direction (`Literal[-1]` or `int`, *optional*): + Direction in which to sort. The value `-1` sorts by descending + order while all other values sort by ascending order. + limit (`int`, *optional*): + The limit on the number of models fetched. Leaving this option + to `None` fetches all models. + full (`bool`, *optional*): + Whether to fetch all model data, including the `last_modified`, + the `sha`, the files and the `tags`. This is set to `True` by + default when using a filter. + cardData (`bool`, *optional*): + Whether to grab the metadata for the model as well. Can contain + useful information such as carbon emissions, metrics, and + datasets trained on. + fetch_config (`bool`, *optional*): + Whether to fetch the model configs as well. This is not included + in `full` due to its size. + token (`bool` or `str`, *optional*): + A valid authentication token (see https://huggingface.co/settings/token). + If `None` or `True` and machine is logged in (through `huggingface-cli login` + or [`~huggingface_hub.login`]), token will be retrieved from the cache. + If `False`, token is not sent in the request header. + pipeline_tag (`str`, *optional*): + A string pipeline tag to filter models on the Hub by, such as `summarization` + + + Returns: + `Iterable[ModelInfo]`: an iterable of [`huggingface_hub.hf_api.ModelInfo`] objects. + + Example usage with the `filter` argument: + + ```python + >>> from huggingface_hub import HfApi + + >>> api = HfApi() + + >>> # List all models + >>> api.list_models() + + >>> # List only the text classification models + >>> api.list_models(filter="text-classification") + + >>> # List only models from the AllenNLP library + >>> api.list_models(filter="allennlp") + ``` + + Example usage with the `search` argument: + + ```python + >>> from huggingface_hub import HfApi + + >>> api = HfApi() + + >>> # List all models with "bert" in their name + >>> api.list_models(search="bert") + + >>> # List all models with "bert" in their name made by google + >>> api.list_models(search="bert", author="google") + ``` + """ + if emissions_thresholds is not None and cardData is None: + raise ValueError("`emissions_thresholds` were passed without setting `cardData=True`.") + + path = f"{self.endpoint}/api/models" + headers = self._build_hf_headers(token=token) + params = {} + filter_list = [] + + if filter is not None: + if isinstance(filter, ModelFilter): + params = self._unpack_model_filter(filter) + else: + params.update({"filter": filter}) + + params.update({"full": True}) + + # Build the filter list + if author: + params.update({"author": author}) + if model_name: + params.update({"search": model_name}) + if library: + filter_list.extend([library] if isinstance(library, str) else library) + if task: + filter_list.extend([task] if isinstance(task, str) else task) + if trained_dataset: + if not isinstance(trained_dataset, (list, tuple)): + trained_dataset = [trained_dataset] + for dataset in trained_dataset: + if not dataset.startswith("dataset:"): + dataset = f"dataset:{dataset}" + filter_list.append(dataset) + if language: + filter_list.extend([language] if isinstance(language, str) else language) + if tags: + filter_list.extend([tags] if isinstance(tags, str) else tags) + + if search: + params.update({"search": search}) + if sort is not None: + params.update({"sort": "lastModified" if sort == "last_modified" else sort}) + if direction is not None: + params.update({"direction": direction}) + if limit is not None: + params.update({"limit": limit}) + if full is not None: + if full: + params.update({"full": True}) + elif "full" in params: + del params["full"] + if fetch_config: + params.update({"config": True}) + if cardData: + params.update({"cardData": True}) + if pipeline_tag: + params.update({"pipeline_tag": pipeline_tag}) + + filter_value = params.get("filter", []) + if filter_value: + filter_list.extend([filter_value] if isinstance(filter_value, str) else list(filter_value)) + params.update({"filter": filter_list}) + + # `items` is a generator + items = paginate(path, params=params, headers=headers) + if limit is not None: + items = islice(items, limit) # Do not iterate over all pages + for item in items: + if "siblings" not in item: + item["siblings"] = None + model_info = ModelInfo(**item) + if emissions_thresholds is None or _is_emission_within_treshold(model_info, *emissions_thresholds): + yield model_info + + def _unpack_model_filter(self, model_filter: ModelFilter): + """ + Unpacks a [`ModelFilter`] into something readable for `list_models` + """ + model_str = "" + + # Handling author + if model_filter.author: + model_str = f"{model_filter.author}/" + + # Handling model_name + if model_filter.model_name: + model_str += model_filter.model_name + + filter_list: List[str] = [] + + # Handling tasks + if model_filter.task: + filter_list.extend([model_filter.task] if isinstance(model_filter.task, str) else model_filter.task) + + # Handling dataset + if model_filter.trained_dataset: + if not isinstance(model_filter.trained_dataset, (list, tuple)): + model_filter.trained_dataset = [model_filter.trained_dataset] + for dataset in model_filter.trained_dataset: + if "dataset:" not in dataset: + dataset = f"dataset:{dataset}" + filter_list.append(dataset) + + # Handling library + if model_filter.library: + filter_list.extend( + [model_filter.library] if isinstance(model_filter.library, str) else model_filter.library + ) + + # Handling tags + if model_filter.tags: + filter_list.extend([model_filter.tags] if isinstance(model_filter.tags, str) else model_filter.tags) + + query_dict: Dict[str, Any] = {} + if model_str: + query_dict["search"] = model_str + if isinstance(model_filter.language, list): + filter_list.extend(model_filter.language) + elif isinstance(model_filter.language, str): + filter_list.append(model_filter.language) + query_dict["filter"] = tuple(filter_list) + return query_dict + + @validate_hf_hub_args + def list_datasets( + self, + *, + filter: Union[DatasetFilter, str, Iterable[str], None] = None, + author: Optional[str] = None, + benchmark: Optional[Union[str, List[str]]] = None, + dataset_name: Optional[str] = None, + language_creators: Optional[Union[str, List[str]]] = None, + language: Optional[Union[str, List[str]]] = None, + multilinguality: Optional[Union[str, List[str]]] = None, + size_categories: Optional[Union[str, List[str]]] = None, + task_categories: Optional[Union[str, List[str]]] = None, + task_ids: Optional[Union[str, List[str]]] = None, + search: Optional[str] = None, + sort: Optional[Union[Literal["last_modified"], str]] = None, + direction: Optional[Literal[-1]] = None, + limit: Optional[int] = None, + full: Optional[bool] = None, + token: Optional[str] = None, + ) -> Iterable[DatasetInfo]: + """ + List datasets hosted on the Huggingface Hub, given some filters. + + Args: + filter ([`DatasetFilter`] or `str` or `Iterable`, *optional*): + A string or [`DatasetFilter`] which can be used to identify + datasets on the hub. + author (`str`, *optional*): + A string which identify the author of the returned datasets. + benchmark (`str` or `List`, *optional*): + A string or list of strings that can be used to identify datasets on + the Hub by their official benchmark. + dataset_name (`str`, *optional*): + A string or list of strings that can be used to identify datasets on + the Hub by its name, such as `SQAC` or `wikineural` + language_creators (`str` or `List`, *optional*): + A string or list of strings that can be used to identify datasets on + the Hub with how the data was curated, such as `crowdsourced` or + `machine_generated`. + language (`str` or `List`, *optional*): + A string or list of strings representing a two-character language to + filter datasets by on the Hub. + multilinguality (`str` or `List`, *optional*): + A string or list of strings representing a filter for datasets that + contain multiple languages. + size_categories (`str` or `List`, *optional*): + A string or list of strings that can be used to identify datasets on + the Hub by the size of the dataset such as `100K>> from huggingface_hub import HfApi + + >>> api = HfApi() + + >>> # List all datasets + >>> api.list_datasets() + + + >>> # List only the text classification datasets + >>> api.list_datasets(filter="task_categories:text-classification") + + + >>> # List only the datasets in russian for language modeling + >>> api.list_datasets( + ... filter=("language:ru", "task_ids:language-modeling") + ... ) + + >>> api.list_datasets(filter=filt) + ``` + + Example usage with the `search` argument: + + ```python + >>> from huggingface_hub import HfApi + + >>> api = HfApi() + + >>> # List all datasets with "text" in their name + >>> api.list_datasets(search="text") + + >>> # List all datasets with "text" in their name made by google + >>> api.list_datasets(search="text", author="google") + ``` + """ + path = f"{self.endpoint}/api/datasets" + headers = self._build_hf_headers(token=token) + params = {} + filter_list = [] + + if filter is not None: + if isinstance(filter, DatasetFilter): + params = self._unpack_dataset_filter(filter) + else: + params.update({"filter": filter}) + + # Build the filter list + if author: + params.update({"author": author}) + if dataset_name: + params.update({"search": dataset_name}) + + for attr in ( + benchmark, + language_creators, + language, + multilinguality, + size_categories, + task_categories, + task_ids, + ): + if attr: + if not isinstance(attr, (list, tuple)): + attr = [attr] + for data in attr: + if not data.startswith(f"{attr}:"): + data = f"{attr}:{data}" + filter_list.append(data) + + if search: + params.update({"search": search}) + if sort is not None: + params.update({"sort": "lastModified" if sort == "last_modified" else sort}) + if direction is not None: + params.update({"direction": direction}) + if limit is not None: + params.update({"limit": limit}) + if full: + params.update({"full": True}) + + filter_value = params.get("filter", []) + if filter_value: + filter_list.extend([filter_value] if isinstance(filter_value, str) else list(filter_value)) + params.update({"filter": filter_list}) + + items = paginate(path, params=params, headers=headers) + if limit is not None: + items = islice(items, limit) # Do not iterate over all pages + for item in items: + if "siblings" not in item: + item["siblings"] = None + yield DatasetInfo(**item) + + def _unpack_dataset_filter(self, dataset_filter: DatasetFilter): + """ + Unpacks a [`DatasetFilter`] into something readable for `list_datasets` + """ + dataset_str = "" + + # Handling author + if dataset_filter.author: + dataset_str = f"{dataset_filter.author}/" + + # Handling dataset_name + if dataset_filter.dataset_name: + dataset_str += dataset_filter.dataset_name + + filter_list = [] + data_attributes = [ + "benchmark", + "language_creators", + "language", + "multilinguality", + "size_categories", + "task_categories", + "task_ids", + ] + + for attr in data_attributes: + curr_attr = getattr(dataset_filter, attr) + if curr_attr is not None: + if not isinstance(curr_attr, (list, tuple)): + curr_attr = [curr_attr] + for data in curr_attr: + if f"{attr}:" not in data: + data = f"{attr}:{data}" + filter_list.append(data) + + query_dict: Dict[str, Any] = {} + if dataset_str is not None: + query_dict["search"] = dataset_str + query_dict["filter"] = tuple(filter_list) + return query_dict + + def list_metrics(self) -> List[MetricInfo]: + """ + Get the public list of all the metrics on huggingface.co + + Returns: + `List[MetricInfo]`: a list of [`MetricInfo`] objects which. + """ + path = f"{self.endpoint}/api/metrics" + r = get_session().get(path) + hf_raise_for_status(r) + d = r.json() + return [MetricInfo(**x) for x in d] + + @validate_hf_hub_args + def list_spaces( + self, + *, + filter: Union[str, Iterable[str], None] = None, + author: Optional[str] = None, + search: Optional[str] = None, + sort: Union[Literal["last_modified"], str, None] = None, + direction: Optional[Literal[-1]] = None, + limit: Optional[int] = None, + datasets: Union[str, Iterable[str], None] = None, + models: Union[str, Iterable[str], None] = None, + linked: bool = False, + full: Optional[bool] = None, + token: Optional[str] = None, + ) -> Iterable[SpaceInfo]: + """ + List spaces hosted on the Huggingface Hub, given some filters. + + Args: + filter (`str` or `Iterable`, *optional*): + A string tag or list of tags that can be used to identify Spaces on the Hub. + author (`str`, *optional*): + A string which identify the author of the returned Spaces. + search (`str`, *optional*): + A string that will be contained in the returned Spaces. + sort (`Literal["last_modified"]` or `str`, *optional*): + The key with which to sort the resulting Spaces. Possible + values are the properties of the [`huggingface_hub.hf_api.SpaceInfo`]` class. + direction (`Literal[-1]` or `int`, *optional*): + Direction in which to sort. The value `-1` sorts by descending + order while all other values sort by ascending order. + limit (`int`, *optional*): + The limit on the number of Spaces fetched. Leaving this option + to `None` fetches all Spaces. + datasets (`str` or `Iterable`, *optional*): + Whether to return Spaces that make use of a dataset. + The name of a specific dataset can be passed as a string. + models (`str` or `Iterable`, *optional*): + Whether to return Spaces that make use of a model. + The name of a specific model can be passed as a string. + linked (`bool`, *optional*): + Whether to return Spaces that make use of either a model or a dataset. + full (`bool`, *optional*): + Whether to fetch all Spaces data, including the `last_modified`, `siblings` + and `card_data` fields. + token (`bool` or `str`, *optional*): + A valid authentication token (see https://huggingface.co/settings/token). + If `None` or `True` and machine is logged in (through `huggingface-cli login` + or [`~huggingface_hub.login`]), token will be retrieved from the cache. + If `False`, token is not sent in the request header. + + Returns: + `Iterable[SpaceInfo]`: an iterable of [`huggingface_hub.hf_api.SpaceInfo`] objects. + """ + path = f"{self.endpoint}/api/spaces" + headers = self._build_hf_headers(token=token) + params: Dict[str, Any] = {} + if filter is not None: + params.update({"filter": filter}) + if author is not None: + params.update({"author": author}) + if search is not None: + params.update({"search": search}) + if sort is not None: + params.update({"sort": "lastModified" if sort == "last_modified" else sort}) + if direction is not None: + params.update({"direction": direction}) + if limit is not None: + params.update({"limit": limit}) + if full: + params.update({"full": True}) + if linked: + params.update({"linked": True}) + if datasets is not None: + params.update({"datasets": datasets}) + if models is not None: + params.update({"models": models}) + + items = paginate(path, params=params, headers=headers) + if limit is not None: + items = islice(items, limit) # Do not iterate over all pages + for item in items: + if "siblings" not in item: + item["siblings"] = None + yield SpaceInfo(**item) + + @validate_hf_hub_args + def like( + self, + repo_id: str, + *, + token: Optional[str] = None, + repo_type: Optional[str] = None, + ) -> None: + """ + Like a given repo on the Hub (e.g. set as favorite). + + See also [`unlike`] and [`list_liked_repos`]. + + Args: + repo_id (`str`): + The repository to like. Example: `"user/my-cool-model"`. + + token (`str`, *optional*): + Authentication token. Will default to the stored token. + + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if liking a dataset or space, `None` or + `"model"` if liking a model. Default is `None`. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If repository is not found (error 404): wrong repo_id/repo_type, private + but not authenticated or repo does not exist. + + Example: + ```python + >>> from huggingface_hub import like, list_liked_repos, unlike + >>> like("gpt2") + >>> "gpt2" in list_liked_repos().models + True + >>> unlike("gpt2") + >>> "gpt2" in list_liked_repos().models + False + ``` + """ + if repo_type is None: + repo_type = REPO_TYPE_MODEL + response = get_session().post( + url=f"{self.endpoint}/api/{repo_type}s/{repo_id}/like", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + + @validate_hf_hub_args + def unlike( + self, + repo_id: str, + *, + token: Optional[str] = None, + repo_type: Optional[str] = None, + ) -> None: + """ + Unlike a given repo on the Hub (e.g. remove from favorite list). + + See also [`like`] and [`list_liked_repos`]. + + Args: + repo_id (`str`): + The repository to unlike. Example: `"user/my-cool-model"`. + + token (`str`, *optional*): + Authentication token. Will default to the stored token. + + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if unliking a dataset or space, `None` or + `"model"` if unliking a model. Default is `None`. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If repository is not found (error 404): wrong repo_id/repo_type, private + but not authenticated or repo does not exist. + + Example: + ```python + >>> from huggingface_hub import like, list_liked_repos, unlike + >>> like("gpt2") + >>> "gpt2" in list_liked_repos().models + True + >>> unlike("gpt2") + >>> "gpt2" in list_liked_repos().models + False + ``` + """ + if repo_type is None: + repo_type = REPO_TYPE_MODEL + response = get_session().delete( + url=f"{self.endpoint}/api/{repo_type}s/{repo_id}/like", headers=self._build_hf_headers(token=token) + ) + hf_raise_for_status(response) + + @validate_hf_hub_args + def list_liked_repos( + self, + user: Optional[str] = None, + *, + token: Optional[str] = None, + ) -> UserLikes: + """ + List all public repos liked by a user on huggingface.co. + + This list is public so token is optional. If `user` is not passed, it defaults to + the logged in user. + + See also [`like`] and [`unlike`]. + + Args: + user (`str`, *optional*): + Name of the user for which you want to fetch the likes. + token (`str`, *optional*): + A valid authentication token (see https://huggingface.co/settings/token). + Used only if `user` is not passed to implicitly determine the current + user name. + + Returns: + [`UserLikes`]: object containing the user name and 3 lists of repo ids (1 for + models, 1 for datasets and 1 for Spaces). + + Raises: + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If `user` is not passed and no token found (either from argument or from machine). + + Example: + ```python + >>> from huggingface_hub import list_liked_repos + + >>> likes = list_liked_repos("julien-c") + + >>> likes.user + "julien-c" + + >>> likes.models + ["osanseviero/streamlit_1.15", "Xhaheen/ChatGPT_HF", ...] + ``` + """ + # User is either provided explicitly or retrieved from current token. + if user is None: + me = self.whoami(token=token) + if me["type"] == "user": + user = me["name"] + else: + raise ValueError( + "Cannot list liked repos. You must provide a 'user' as input or be logged in as a user." + ) + + path = f"{self.endpoint}/api/users/{user}/likes" + headers = self._build_hf_headers(token=token) + + likes = list(paginate(path, params={}, headers=headers)) + # Looping over a list of items similar to: + # { + # 'createdAt': '2021-09-09T21:53:27.000Z', + # 'repo': { + # 'name': 'PaddlePaddle/PaddleOCR', + # 'type': 'space' + # } + # } + # Let's loop 3 times over the received list. Less efficient but more straightforward to read. + return UserLikes( + user=user, + total=len(likes), + models=[like["repo"]["name"] for like in likes if like["repo"]["type"] == "model"], + datasets=[like["repo"]["name"] for like in likes if like["repo"]["type"] == "dataset"], + spaces=[like["repo"]["name"] for like in likes if like["repo"]["type"] == "space"], + ) + + @validate_hf_hub_args + def list_repo_likers( + self, + repo_id: str, + *, + repo_type: Optional[str] = None, + token: Optional[str] = None, + ) -> List[User]: + """ + List all users who liked a given repo on the hugging Face Hub. + + See also [`like`] and [`list_liked_repos`]. + + Args: + repo_id (`str`): + The repository to retrieve . Example: `"user/my-cool-model"`. + + token (`str`, *optional*): + Authentication token. Will default to the stored token. + + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + + Returns: + `List[User]`: a list of [`User`] objects. + """ + + # Construct the API endpoint + if repo_type is None: + repo_type = REPO_TYPE_MODEL + path = f"{self.endpoint}/api/{repo_type}s/{repo_id}/likers" + headers = self._build_hf_headers(token=token) + + # Make the request + response = get_session().get(path, headers=headers) + hf_raise_for_status(response) + + # Parse the results into User objects + likers_data = response.json() + return [ + User( + username=user_data["user"], + fullname=user_data["fullname"], + avatar_url=user_data["avatarUrl"], + ) + for user_data in likers_data + ] + + @validate_hf_hub_args + def model_info( + self, + repo_id: str, + *, + revision: Optional[str] = None, + timeout: Optional[float] = None, + securityStatus: Optional[bool] = None, + files_metadata: bool = False, + token: Optional[Union[bool, str]] = None, + ) -> ModelInfo: + """ + Get info on one specific model on huggingface.co + + Model can be private if you pass an acceptable token or are logged in. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + revision (`str`, *optional*): + The revision of the model repository from which to get the + information. + timeout (`float`, *optional*): + Whether to set a timeout for the request to the Hub. + securityStatus (`bool`, *optional*): + Whether to retrieve the security status from the model + repository as well. + files_metadata (`bool`, *optional*): + Whether or not to retrieve metadata for files in the repository + (size, LFS metadata, etc). Defaults to `False`. + token (`bool` or `str`, *optional*): + A valid authentication token (see https://huggingface.co/settings/token). + If `None` or `True` and machine is logged in (through `huggingface-cli login` + or [`~huggingface_hub.login`]), token will be retrieved from the cache. + If `False`, token is not sent in the request header. + + Returns: + [`huggingface_hub.hf_api.ModelInfo`]: The model repository information. + + + + Raises the following errors: + + - [`~utils.RepositoryNotFoundError`] + If the repository to download from cannot be found. This may be because it doesn't exist, + or because it is set to `private` and you do not have access. + - [`~utils.RevisionNotFoundError`] + If the revision to download from cannot be found. + + + """ + headers = self._build_hf_headers(token=token) + path = ( + f"{self.endpoint}/api/models/{repo_id}" + if revision is None + else (f"{self.endpoint}/api/models/{repo_id}/revision/{quote(revision, safe='')}") + ) + params = {} + if securityStatus: + params["securityStatus"] = True + if files_metadata: + params["blobs"] = True + r = get_session().get(path, headers=headers, timeout=timeout, params=params) + hf_raise_for_status(r) + data = r.json() + return ModelInfo(**data) + + @validate_hf_hub_args + def dataset_info( + self, + repo_id: str, + *, + revision: Optional[str] = None, + timeout: Optional[float] = None, + files_metadata: bool = False, + token: Optional[Union[bool, str]] = None, + ) -> DatasetInfo: + """ + Get info on one specific dataset on huggingface.co. + + Dataset can be private if you pass an acceptable token. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + revision (`str`, *optional*): + The revision of the dataset repository from which to get the + information. + timeout (`float`, *optional*): + Whether to set a timeout for the request to the Hub. + files_metadata (`bool`, *optional*): + Whether or not to retrieve metadata for files in the repository + (size, LFS metadata, etc). Defaults to `False`. + token (`bool` or `str`, *optional*): + A valid authentication token (see https://huggingface.co/settings/token). + If `None` or `True` and machine is logged in (through `huggingface-cli login` + or [`~huggingface_hub.login`]), token will be retrieved from the cache. + If `False`, token is not sent in the request header. + + Returns: + [`hf_api.DatasetInfo`]: The dataset repository information. + + + + Raises the following errors: + + - [`~utils.RepositoryNotFoundError`] + If the repository to download from cannot be found. This may be because it doesn't exist, + or because it is set to `private` and you do not have access. + - [`~utils.RevisionNotFoundError`] + If the revision to download from cannot be found. + + + """ + headers = self._build_hf_headers(token=token) + path = ( + f"{self.endpoint}/api/datasets/{repo_id}" + if revision is None + else (f"{self.endpoint}/api/datasets/{repo_id}/revision/{quote(revision, safe='')}") + ) + params = {} + if files_metadata: + params["blobs"] = True + + r = get_session().get(path, headers=headers, timeout=timeout, params=params) + hf_raise_for_status(r) + data = r.json() + return DatasetInfo(**data) + + @validate_hf_hub_args + def space_info( + self, + repo_id: str, + *, + revision: Optional[str] = None, + timeout: Optional[float] = None, + files_metadata: bool = False, + token: Optional[Union[bool, str]] = None, + ) -> SpaceInfo: + """ + Get info on one specific Space on huggingface.co. + + Space can be private if you pass an acceptable token. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + revision (`str`, *optional*): + The revision of the space repository from which to get the + information. + timeout (`float`, *optional*): + Whether to set a timeout for the request to the Hub. + files_metadata (`bool`, *optional*): + Whether or not to retrieve metadata for files in the repository + (size, LFS metadata, etc). Defaults to `False`. + token (`bool` or `str`, *optional*): + A valid authentication token (see https://huggingface.co/settings/token). + If `None` or `True` and machine is logged in (through `huggingface-cli login` + or [`~huggingface_hub.login`]), token will be retrieved from the cache. + If `False`, token is not sent in the request header. + + Returns: + [`~hf_api.SpaceInfo`]: The space repository information. + + + + Raises the following errors: + + - [`~utils.RepositoryNotFoundError`] + If the repository to download from cannot be found. This may be because it doesn't exist, + or because it is set to `private` and you do not have access. + - [`~utils.RevisionNotFoundError`] + If the revision to download from cannot be found. + + + """ + headers = self._build_hf_headers(token=token) + path = ( + f"{self.endpoint}/api/spaces/{repo_id}" + if revision is None + else (f"{self.endpoint}/api/spaces/{repo_id}/revision/{quote(revision, safe='')}") + ) + params = {} + if files_metadata: + params["blobs"] = True + + r = get_session().get(path, headers=headers, timeout=timeout, params=params) + hf_raise_for_status(r) + data = r.json() + return SpaceInfo(**data) + + @validate_hf_hub_args + def repo_info( + self, + repo_id: str, + *, + revision: Optional[str] = None, + repo_type: Optional[str] = None, + timeout: Optional[float] = None, + files_metadata: bool = False, + token: Optional[Union[bool, str]] = None, + ) -> Union[ModelInfo, DatasetInfo, SpaceInfo]: + """ + Get the info object for a given repo of a given type. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + revision (`str`, *optional*): + The revision of the repository from which to get the + information. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space, + `None` or `"model"` if getting repository info from a model. Default is `None`. + timeout (`float`, *optional*): + Whether to set a timeout for the request to the Hub. + files_metadata (`bool`, *optional*): + Whether or not to retrieve metadata for files in the repository + (size, LFS metadata, etc). Defaults to `False`. + token (`bool` or `str`, *optional*): + A valid authentication token (see https://huggingface.co/settings/token). + If `None` or `True` and machine is logged in (through `huggingface-cli login` + or [`~huggingface_hub.login`]), token will be retrieved from the cache. + If `False`, token is not sent in the request header. + + Returns: + `Union[SpaceInfo, DatasetInfo, ModelInfo]`: The repository information, as a + [`huggingface_hub.hf_api.DatasetInfo`], [`huggingface_hub.hf_api.ModelInfo`] + or [`huggingface_hub.hf_api.SpaceInfo`] object. + + + + Raises the following errors: + + - [`~utils.RepositoryNotFoundError`] + If the repository to download from cannot be found. This may be because it doesn't exist, + or because it is set to `private` and you do not have access. + - [`~utils.RevisionNotFoundError`] + If the revision to download from cannot be found. + + + """ + if repo_type is None or repo_type == "model": + method = self.model_info + elif repo_type == "dataset": + method = self.dataset_info # type: ignore + elif repo_type == "space": + method = self.space_info # type: ignore + else: + raise ValueError("Unsupported repo type.") + return method( + repo_id, + revision=revision, + token=token, + timeout=timeout, + files_metadata=files_metadata, + ) + + @validate_hf_hub_args + def repo_exists( + self, + repo_id: str, + *, + repo_type: Optional[str] = None, + token: Optional[str] = None, + ) -> bool: + """ + Checks if a repository exists on the Hugging Face Hub. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space, + `None` or `"model"` if getting repository info from a model. Default is `None`. + token (`bool` or `str`, *optional*): + A valid authentication token (see https://huggingface.co/settings/token). + If `None` or `True` and machine is logged in (through `huggingface-cli login` + or [`~huggingface_hub.login`]), token will be retrieved from the cache. + If `False`, token is not sent in the request header. + + Returns: + True if the repository exists, False otherwise. + + Examples: + ```py + >>> from huggingface_hub import repo_exists + >>> repo_exists("google/gemma-7b") + True + >>> repo_exists("google/not-a-repo") + False + ``` + """ + try: + self.repo_info(repo_id=repo_id, repo_type=repo_type, token=token) + return True + except GatedRepoError: + return True # we don't have access but it exists + except RepositoryNotFoundError: + return False + + @validate_hf_hub_args + def revision_exists( + self, + repo_id: str, + revision: str, + *, + repo_type: Optional[str] = None, + token: Optional[str] = None, + ) -> bool: + """ + Checks if a specific revision exists on a repo on the Hugging Face Hub. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + revision (`str`): + The revision of the repository to check. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space, + `None` or `"model"` if getting repository info from a model. Default is `None`. + token (`bool` or `str`, *optional*): + A valid authentication token (see https://huggingface.co/settings/token). + If `None` or `True` and machine is logged in (through `huggingface-cli login` + or [`~huggingface_hub.login`]), token will be retrieved from the cache. + If `False`, token is not sent in the request header. + + Returns: + True if the repository and the revision exists, False otherwise. + + Examples: + ```py + >>> from huggingface_hub import revision_exists + >>> revision_exists("google/gemma-7b", "float16") + True + >>> revision_exists("google/gemma-7b", "not-a-revision") + False + ``` + """ + try: + self.repo_info(repo_id=repo_id, revision=revision, repo_type=repo_type, token=token) + return True + except RevisionNotFoundError: + return False + except RepositoryNotFoundError: + return False + + @validate_hf_hub_args + def file_exists( + self, + repo_id: str, + filename: str, + *, + repo_type: Optional[str] = None, + revision: Optional[str] = None, + token: Union[str, bool, None] = None, + ) -> bool: + """ + Checks if a file exists in a repository on the Hugging Face Hub. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + filename (`str`): + The name of the file to check, for example: + `"config.json"` + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space, + `None` or `"model"` if getting repository info from a model. Default is `None`. + revision (`str`, *optional*): + The revision of the repository from which to get the information. Defaults to `"main"` branch. + token (`bool` or `str`, *optional*): + A valid authentication token (see https://huggingface.co/settings/token). + If `None` or `True` and machine is logged in (through `huggingface-cli login` + or [`~huggingface_hub.login`]), token will be retrieved from the cache. + If `False`, token is not sent in the request header. + + Returns: + True if the file exists, False otherwise. + + Examples: + ```py + >>> from huggingface_hub import file_exists + >>> file_exists("bigcode/starcoder", "config.json") + True + >>> file_exists("bigcode/starcoder", "not-a-file") + False + >>> file_exists("bigcode/not-a-repo", "config.json") + False + ``` + """ + url = hf_hub_url( + repo_id=repo_id, repo_type=repo_type, revision=revision, filename=filename, endpoint=self.endpoint + ) + try: + if token is None: + token = self.token + get_hf_file_metadata(url, token=token) + return True + except GatedRepoError: # raise specifically on gated repo + raise + except (RepositoryNotFoundError, EntryNotFoundError, RevisionNotFoundError): + return False + + @validate_hf_hub_args + @_deprecate_method(version="0.23", message="Use `list_repo_tree` and `get_paths_info` instead.") + def list_files_info( + self, + repo_id: str, + paths: Union[List[str], str, None] = None, + *, + expand: bool = False, + revision: Optional[str] = None, + repo_type: Optional[str] = None, + token: Optional[Union[bool, str]] = None, + ) -> Iterable[RepoFile]: + """ + List files on a repo and get information about them. + + Takes as input a list of paths. Those paths can be either files or folders. Two server endpoints are called: + 1. POST "/paths-info" to get information about the provided paths. Called once. + 2. GET "/tree?recursive=True" to paginate over the input folders. Called only if a folder path is provided as + input. Will be called multiple times to follow pagination. + If no path is provided as input, step 1. is ignored and all files from the repo are listed. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated by a `/`. + paths (`Union[List[str], str, None]`, *optional*): + The paths to get information about. Paths to files are directly resolved. Paths to folders are resolved + recursively which means that information is returned about all files in the folder and its subfolders. + If `None`, all files are returned (the default). If a path do not exist, it is ignored without raising + an exception. + expand (`bool`, *optional*, defaults to `False`): + Whether to fetch more information about the files (e.g. last commit and security scan results). This + operation is more expensive for the server so only 50 results are returned per page (instead of 1000). + As pagination is implemented in `huggingface_hub`, this is transparent for you except for the time it + takes to get the results. + revision (`str`, *optional*): + The revision of the repository from which to get the information. Defaults to `"main"` branch. + repo_type (`str`, *optional*): + The type of the repository from which to get the information (`"model"`, `"dataset"` or `"space"`. + Defaults to `"model"`. + token (`bool` or `str`, *optional*): + A valid authentication token (see https://huggingface.co/settings/token). If `None` or `True` and + machine is logged in (through `huggingface-cli login` or [`~huggingface_hub.login`]), token will be + retrieved from the cache. If `False`, token is not sent in the request header. + + Returns: + `Iterable[RepoFile]`: + The information about the files, as an iterable of [`RepoFile`] objects. The order of the files is + not guaranteed. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo + does not exist. + [`~utils.RevisionNotFoundError`]: + If revision is not found (error 404) on the repo. + + Examples: + + Get information about files on a repo. + ```py + >>> from huggingface_hub import list_files_info + >>> files_info = list_files_info("lysandre/arxiv-nlp", ["README.md", "config.json"]) + >>> files_info + + >>> list(files_info) + [ + RepoFile(path='README.md', size=391, blob_id='43bd404b159de6fba7c2f4d3264347668d43af25', lfs=None, last_commit=None, security=None), + RepoFile(path='config.json', size=554, blob_id='2f9618c3a19b9a61add74f70bfb121335aeef666', lfs=None, last_commit=None, security=None) + ] + ``` + + Get even more information about files on a repo (last commit and security scan results) + ```py + >>> from huggingface_hub import list_files_info + >>> files_info = list_files_info("prompthero/openjourney-v4", expand=True) + >>> list(files_info) + [ + RepoFile( + path='safety_checker/pytorch_model.bin', + size=1216064769, + blob_id='c8835557a0d3af583cb06c7c154b7e54a069c41d', + lfs={ + 'size': 1216064769, + 'sha256': '16d28f2b37109f222cdc33620fdd262102ac32112be0352a7f77e9614b35a394', + 'pointer_size': 135 + }, + last_commit={ + 'oid': '47b62b20b20e06b9de610e840282b7e6c3d51190', + 'title': 'Upload diffusers weights (#48)', + 'date': datetime.datetime(2023, 3, 21, 10, 5, 27, tzinfo=datetime.timezone.utc) + }, + security={ + 'safe': True, + 'av_scan': { + 'virusFound': False, + 'virusNames': None + }, + 'pickle_import_scan': { + 'highestSafetyLevel': 'innocuous', + 'imports': [ + {'module': 'torch', 'name': 'FloatStorage', 'safety': 'innocuous'}, + {'module': 'collections', 'name': 'OrderedDict', 'safety': 'innocuous'}, + {'module': 'torch', 'name': 'LongStorage', 'safety': 'innocuous'}, + {'module': 'torch._utils', 'name': '_rebuild_tensor_v2', 'safety': 'innocuous'} + ] + } + } + ), + RepoFile( + path='scheduler/scheduler_config.json', + size=465, + blob_id='70d55e3e9679f41cbc66222831b38d5abce683dd', + lfs=None, + last_commit={ + 'oid': '47b62b20b20e06b9de610e840282b7e6c3d51190', + 'title': 'Upload diffusers weights (#48)', + 'date': datetime.datetime(2023, 3, 21, 10, 5, 27, tzinfo=datetime.timezone.utc)}, + security={ + 'safe': True, + 'av_scan': { + 'virusFound': False, + 'virusNames': None + }, + 'pickle_import_scan': None + } + ), + ... + ] + ``` + + List LFS files from the "vae/" folder in "stabilityai/stable-diffusion-2" repository. + + ```py + >>> from huggingface_hub import list_files_info + >>> [info.path for info in list_files_info("stabilityai/stable-diffusion-2", "vae") if info.lfs is not None] + ['vae/diffusion_pytorch_model.bin', 'vae/diffusion_pytorch_model.safetensors'] + ``` + + List all files on a repo. + ```py + >>> from huggingface_hub import list_files_info + >>> [info.path for info in list_files_info("glue", repo_type="dataset")] + ['.gitattributes', 'README.md', 'dataset_infos.json', 'glue.py'] + ``` + """ + repo_type = repo_type or REPO_TYPE_MODEL + revision = quote(revision, safe="") if revision is not None else DEFAULT_REVISION + headers = self._build_hf_headers(token=token) + + folder_paths = [] + if paths is None: + # `paths` is not provided => list all files from the repo + folder_paths.append("") + elif paths == []: + # corner case: server would return a 400 error if `paths` is an empty list. Let's return early. + return + else: + # `paths` is provided => get info about those + response = get_session().post( + f"{self.endpoint}/api/{repo_type}s/{repo_id}/paths-info/{revision}", + data={ + "paths": paths if isinstance(paths, list) else [paths], + "expand": expand, + }, + headers=headers, + ) + hf_raise_for_status(response) + paths_info = response.json() + + # List top-level files first + for path_info in paths_info: + if path_info["type"] == "file": + yield RepoFile(**path_info) + else: + folder_paths.append(path_info["path"]) + + # List files in subdirectories + for path in folder_paths: + encoded_path = "/" + quote(path, safe="") if path else "" + tree_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/tree/{revision}{encoded_path}" + for subpath_info in paginate(path=tree_url, headers=headers, params={"recursive": True, "expand": expand}): + if subpath_info["type"] == "file": + yield RepoFile(**subpath_info) + + @validate_hf_hub_args + def list_repo_files( + self, + repo_id: str, + *, + revision: Optional[str] = None, + repo_type: Optional[str] = None, + token: Optional[Union[bool, str]] = None, + ) -> List[str]: + """ + Get the list of files in a given repo. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated by a `/`. + revision (`str`, *optional*): + The revision of the model repository from which to get the information. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or space, `None` or `"model"` if uploading to + a model. Default is `None`. + token (`bool` or `str`, *optional*): + A valid authentication token (see https://huggingface.co/settings/token). If `None` or `True` and + machine is logged in (through `huggingface-cli login` or [`~huggingface_hub.login`]), token will be + retrieved from the cache. If `False`, token is not sent in the request header. + + Returns: + `List[str]`: the list of files in a given repository. + """ + return [ + f.rfilename + for f in self.list_repo_tree( + repo_id=repo_id, recursive=True, revision=revision, repo_type=repo_type, token=token + ) + if isinstance(f, RepoFile) + ] + + @validate_hf_hub_args + def list_repo_tree( + self, + repo_id: str, + path_in_repo: Optional[str] = None, + *, + recursive: bool = False, + expand: bool = False, + revision: Optional[str] = None, + repo_type: Optional[str] = None, + token: Optional[Union[bool, str]] = None, + ) -> Iterable[Union[RepoFile, RepoFolder]]: + """ + List a repo tree's files and folders and get information about them. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated by a `/`. + path_in_repo (`str`, *optional*): + Relative path of the tree (folder) in the repo, for example: + `"checkpoints/1fec34a/results"`. Will default to the root tree (folder) of the repository. + recursive (`bool`, *optional*, defaults to `False`): + Whether to list tree's files and folders recursively. + expand (`bool`, *optional*, defaults to `False`): + Whether to fetch more information about the tree's files and folders (e.g. last commit and files' security scan results). This + operation is more expensive for the server so only 50 results are returned per page (instead of 1000). + As pagination is implemented in `huggingface_hub`, this is transparent for you except for the time it + takes to get the results. + revision (`str`, *optional*): + The revision of the repository from which to get the tree. Defaults to `"main"` branch. + repo_type (`str`, *optional*): + The type of the repository from which to get the tree (`"model"`, `"dataset"` or `"space"`. + Defaults to `"model"`. + token (`bool` or `str`, *optional*): + A valid authentication token (see https://huggingface.co/settings/token). If `None` or `True` and + machine is logged in (through `huggingface-cli login` or [`~huggingface_hub.login`]), token will be + retrieved from the cache. If `False`, token is not sent in the request header. + + Returns: + `Iterable[Union[RepoFile, RepoFolder]]`: + The information about the tree's files and folders, as an iterable of [`RepoFile`] and [`RepoFolder`] objects. The order of the files and folders is + not guaranteed. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo + does not exist. + [`~utils.RevisionNotFoundError`]: + If revision is not found (error 404) on the repo. + [`~utils.EntryNotFoundError`]: + If the tree (folder) does not exist (error 404) on the repo. + + Examples: + + Get information about a repo's tree. + ```py + >>> from huggingface_hub import list_repo_tree + >>> repo_tree = list_repo_tree("lysandre/arxiv-nlp") + >>> repo_tree + + >>> list(repo_tree) + [ + RepoFile(path='.gitattributes', size=391, blob_id='ae8c63daedbd4206d7d40126955d4e6ab1c80f8f', lfs=None, last_commit=None, security=None), + RepoFile(path='README.md', size=391, blob_id='43bd404b159de6fba7c2f4d3264347668d43af25', lfs=None, last_commit=None, security=None), + RepoFile(path='config.json', size=554, blob_id='2f9618c3a19b9a61add74f70bfb121335aeef666', lfs=None, last_commit=None, security=None), + RepoFile( + path='flax_model.msgpack', size=497764107, blob_id='8095a62ccb4d806da7666fcda07467e2d150218e', + lfs={'size': 497764107, 'sha256': 'd88b0d6a6ff9c3f8151f9d3228f57092aaea997f09af009eefd7373a77b5abb9', 'pointer_size': 134}, last_commit=None, security=None + ), + RepoFile(path='merges.txt', size=456318, blob_id='226b0752cac7789c48f0cb3ec53eda48b7be36cc', lfs=None, last_commit=None, security=None), + RepoFile( + path='pytorch_model.bin', size=548123560, blob_id='64eaa9c526867e404b68f2c5d66fd78e27026523', + lfs={'size': 548123560, 'sha256': '9be78edb5b928eba33aa88f431551348f7466ba9f5ef3daf1d552398722a5436', 'pointer_size': 134}, last_commit=None, security=None + ), + RepoFile(path='vocab.json', size=898669, blob_id='b00361fece0387ca34b4b8b8539ed830d644dbeb', lfs=None, last_commit=None, security=None)] + ] + ``` + + Get even more information about a repo's tree (last commit and files' security scan results) + ```py + >>> from huggingface_hub import list_repo_tree + >>> repo_tree = list_repo_tree("prompthero/openjourney-v4", expand=True) + >>> list(repo_tree) + [ + RepoFolder( + path='feature_extractor', + tree_id='aa536c4ea18073388b5b0bc791057a7296a00398', + last_commit={ + 'oid': '47b62b20b20e06b9de610e840282b7e6c3d51190', + 'title': 'Upload diffusers weights (#48)', + 'date': datetime.datetime(2023, 3, 21, 9, 5, 27, tzinfo=datetime.timezone.utc) + } + ), + RepoFolder( + path='safety_checker', + tree_id='65aef9d787e5557373fdf714d6c34d4fcdd70440', + last_commit={ + 'oid': '47b62b20b20e06b9de610e840282b7e6c3d51190', + 'title': 'Upload diffusers weights (#48)', + 'date': datetime.datetime(2023, 3, 21, 9, 5, 27, tzinfo=datetime.timezone.utc) + } + ), + RepoFile( + path='model_index.json', + size=582, + blob_id='d3d7c1e8c3e78eeb1640b8e2041ee256e24c9ee1', + lfs=None, + last_commit={ + 'oid': 'b195ed2d503f3eb29637050a886d77bd81d35f0e', + 'title': 'Fix deprecation warning by changing `CLIPFeatureExtractor` to `CLIPImageProcessor`. (#54)', + 'date': datetime.datetime(2023, 5, 15, 21, 41, 59, tzinfo=datetime.timezone.utc) + }, + security={ + 'safe': True, + 'av_scan': {'virusFound': False, 'virusNames': None}, + 'pickle_import_scan': None + } + ) + ... + ] + ``` + """ + repo_type = repo_type or REPO_TYPE_MODEL + revision = quote(revision, safe="") if revision is not None else DEFAULT_REVISION + headers = self._build_hf_headers(token=token) + + encoded_path_in_repo = "/" + quote(path_in_repo, safe="") if path_in_repo else "" + tree_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/tree/{revision}{encoded_path_in_repo}" + for path_info in paginate(path=tree_url, headers=headers, params={"recursive": recursive, "expand": expand}): + yield (RepoFile(**path_info) if path_info["type"] == "file" else RepoFolder(**path_info)) + + @validate_hf_hub_args + def list_repo_refs( + self, + repo_id: str, + *, + repo_type: Optional[str] = None, + include_pull_requests: bool = False, + token: Optional[Union[bool, str]] = None, + ) -> GitRefs: + """ + Get the list of refs of a given repo (both tags and branches). + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if listing refs from a dataset or a Space, + `None` or `"model"` if listing from a model. Default is `None`. + include_pull_requests (`bool`, *optional*): + Whether to include refs from pull requests in the list. Defaults to `False`. + token (`bool` or `str`, *optional*): + A valid authentication token (see https://huggingface.co/settings/token). + If `None` or `True` and machine is logged in (through `huggingface-cli login` + or [`~huggingface_hub.login`]), token will be retrieved from the cache. + If `False`, token is not sent in the request header. + + Example: + ```py + >>> from huggingface_hub import HfApi + >>> api = HfApi() + >>> api.list_repo_refs("gpt2") + GitRefs(branches=[GitRefInfo(name='main', ref='refs/heads/main', target_commit='e7da7f221d5bf496a48136c0cd264e630fe9fcc8')], converts=[], tags=[]) + + >>> api.list_repo_refs("bigcode/the-stack", repo_type='dataset') + GitRefs( + branches=[ + GitRefInfo(name='main', ref='refs/heads/main', target_commit='18edc1591d9ce72aa82f56c4431b3c969b210ae3'), + GitRefInfo(name='v1.1.a1', ref='refs/heads/v1.1.a1', target_commit='f9826b862d1567f3822d3d25649b0d6d22ace714') + ], + converts=[], + tags=[ + GitRefInfo(name='v1.0', ref='refs/tags/v1.0', target_commit='c37a8cd1e382064d8aced5e05543c5f7753834da') + ] + ) + ``` + + Returns: + [`GitRefs`]: object containing all information about branches and tags for a + repo on the Hub. + """ + repo_type = repo_type or REPO_TYPE_MODEL + response = get_session().get( + f"{self.endpoint}/api/{repo_type}s/{repo_id}/refs", + headers=self._build_hf_headers(token=token), + params={"include_prs": 1} if include_pull_requests else {}, + ) + hf_raise_for_status(response) + data = response.json() + + def _format_as_git_ref_info(item: Dict) -> GitRefInfo: + return GitRefInfo(name=item["name"], ref=item["ref"], target_commit=item["targetCommit"]) + + return GitRefs( + branches=[_format_as_git_ref_info(item) for item in data["branches"]], + converts=[_format_as_git_ref_info(item) for item in data["converts"]], + tags=[_format_as_git_ref_info(item) for item in data["tags"]], + pull_requests=[_format_as_git_ref_info(item) for item in data["pullRequests"]] + if include_pull_requests + else None, + ) + + @validate_hf_hub_args + def list_repo_commits( + self, + repo_id: str, + *, + repo_type: Optional[str] = None, + token: Optional[Union[bool, str]] = None, + revision: Optional[str] = None, + formatted: bool = False, + ) -> List[GitCommitInfo]: + """ + Get the list of commits of a given revision for a repo on the Hub. + + Commits are sorted by date (last commit first). + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated by a `/`. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if listing commits from a dataset or a Space, `None` or `"model"` if + listing from a model. Default is `None`. + token (`bool` or `str`, *optional*): + A valid authentication token (see https://huggingface.co/settings/token). + If `None` or `True` and machine is logged in (through `huggingface-cli login` + or [`~huggingface_hub.login`]), token will be retrieved from the cache. + If `False`, token is not sent in the request header. + revision (`str`, *optional*): + The git revision to commit from. Defaults to the head of the `"main"` branch. + formatted (`bool`): + Whether to return the HTML-formatted title and description of the commits. Defaults to False. + + Example: + ```py + >>> from huggingface_hub import HfApi + >>> api = HfApi() + + # Commits are sorted by date (last commit first) + >>> initial_commit = api.list_repo_commits("gpt2")[-1] + + # Initial commit is always a system commit containing the `.gitattributes` file. + >>> initial_commit + GitCommitInfo( + commit_id='9b865efde13a30c13e0a33e536cf3e4a5a9d71d8', + authors=['system'], + created_at=datetime.datetime(2019, 2, 18, 10, 36, 15, tzinfo=datetime.timezone.utc), + title='initial commit', + message='', + formatted_title=None, + formatted_message=None + ) + + # Create an empty branch by deriving from initial commit + >>> api.create_branch("gpt2", "new_empty_branch", revision=initial_commit.commit_id) + ``` + + Returns: + List[[`GitCommitInfo`]]: list of objects containing information about the commits for a repo on the Hub. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo + does not exist. + [`~utils.RevisionNotFoundError`]: + If revision is not found (error 404) on the repo. + """ + repo_type = repo_type or REPO_TYPE_MODEL + revision = quote(revision, safe="") if revision is not None else DEFAULT_REVISION + + # Paginate over results and return the list of commits. + return [ + GitCommitInfo( + commit_id=item["id"], + authors=[author["user"] for author in item["authors"]], + created_at=parse_datetime(item["date"]), + title=item["title"], + message=item["message"], + formatted_title=item.get("formatted", {}).get("title"), + formatted_message=item.get("formatted", {}).get("message"), + ) + for item in paginate( + f"{self.endpoint}/api/{repo_type}s/{repo_id}/commits/{revision}", + headers=self._build_hf_headers(token=token), + params={"expand[]": "formatted"} if formatted else {}, + ) + ] + + @validate_hf_hub_args + def get_paths_info( + self, + repo_id: str, + paths: Union[List[str], str], + *, + expand: bool = False, + revision: Optional[str] = None, + repo_type: Optional[str] = None, + token: Optional[Union[bool, str]] = None, + ) -> List[Union[RepoFile, RepoFolder]]: + """ + Get information about a repo's paths. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated by a `/`. + paths (`Union[List[str], str]`, *optional*): + The paths to get information about. If a path do not exist, it is ignored without raising + an exception. + expand (`bool`, *optional*, defaults to `False`): + Whether to fetch more information about the paths (e.g. last commit and files' security scan results). This + operation is more expensive for the server so only 50 results are returned per page (instead of 1000). + As pagination is implemented in `huggingface_hub`, this is transparent for you except for the time it + takes to get the results. + revision (`str`, *optional*): + The revision of the repository from which to get the information. Defaults to `"main"` branch. + repo_type (`str`, *optional*): + The type of the repository from which to get the information (`"model"`, `"dataset"` or `"space"`. + Defaults to `"model"`. + token (`bool` or `str`, *optional*): + A valid authentication token (see https://huggingface.co/settings/token). If `None` or `True` and + machine is logged in (through `huggingface-cli login` or [`~huggingface_hub.login`]), token will be + retrieved from the cache. If `False`, token is not sent in the request header. + + Returns: + `List[Union[RepoFile, RepoFolder]]`: + The information about the paths, as a list of [`RepoFile`] and [`RepoFolder`] objects. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo + does not exist. + [`~utils.RevisionNotFoundError`]: + If revision is not found (error 404) on the repo. + + Example: + ```py + >>> from huggingface_hub import get_paths_info + >>> paths_info = get_paths_info("allenai/c4", ["README.md", "en"], repo_type="dataset") + >>> paths_info + [ + RepoFile(path='README.md', size=2379, blob_id='f84cb4c97182890fc1dbdeaf1a6a468fd27b4fff', lfs=None, last_commit=None, security=None), + RepoFolder(path='en', tree_id='dc943c4c40f53d02b31ced1defa7e5f438d5862e', last_commit=None) + ] + ``` + """ + repo_type = repo_type or REPO_TYPE_MODEL + revision = quote(revision, safe="") if revision is not None else DEFAULT_REVISION + headers = self._build_hf_headers(token=token) + + response = get_session().post( + f"{self.endpoint}/api/{repo_type}s/{repo_id}/paths-info/{revision}", + data={ + "paths": paths if isinstance(paths, list) else [paths], + "expand": expand, + }, + headers=headers, + ) + hf_raise_for_status(response) + paths_info = response.json() + return [ + RepoFile(**path_info) if path_info["type"] == "file" else RepoFolder(**path_info) + for path_info in paths_info + ] + + @validate_hf_hub_args + def super_squash_history( + self, + repo_id: str, + *, + branch: Optional[str] = None, + commit_message: Optional[str] = None, + repo_type: Optional[str] = None, + token: Optional[str] = None, + ) -> None: + """Squash commit history on a branch for a repo on the Hub. + + Squashing the repo history is useful when you know you'll make hundreds of commits and you don't want to + clutter the history. Squashing commits can only be performed from the head of a branch. + + + + Once squashed, the commit history cannot be retrieved. This is a non-revertible operation. + + + + + + Once the history of a branch has been squashed, it is not possible to merge it back into another branch since + their history will have diverged. + + + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated by a `/`. + branch (`str`, *optional*): + The branch to squash. Defaults to the head of the `"main"` branch. + commit_message (`str`, *optional*): + The commit message to use for the squashed commit. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if listing commits from a dataset or a Space, `None` or `"model"` if + listing from a model. Default is `None`. + token (`str`, *optional*): + A valid authentication token (see https://huggingface.co/settings/token). If the machine is logged in + (through `huggingface-cli login` or [`~huggingface_hub.login`]), token can be automatically retrieved + from the cache. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo + does not exist. + [`~utils.RevisionNotFoundError`]: + If the branch to squash cannot be found. + [`~utils.BadRequestError`]: + If invalid reference for a branch. You cannot squash history on tags. + + Example: + ```py + >>> from huggingface_hub import HfApi + >>> api = HfApi() + + # Create repo + >>> repo_id = api.create_repo("test-squash").repo_id + + # Make a lot of commits. + >>> api.upload_file(repo_id=repo_id, path_in_repo="file.txt", path_or_fileobj=b"content") + >>> api.upload_file(repo_id=repo_id, path_in_repo="lfs.bin", path_or_fileobj=b"content") + >>> api.upload_file(repo_id=repo_id, path_in_repo="file.txt", path_or_fileobj=b"another_content") + + # Squash history + >>> api.super_squash_history(repo_id=repo_id) + ``` + """ + if repo_type is None: + repo_type = REPO_TYPE_MODEL + if repo_type not in REPO_TYPES: + raise ValueError("Invalid repo type") + if branch is None: + branch = DEFAULT_REVISION + + # Prepare request + url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/super-squash/{branch}" + headers = self._build_hf_headers(token=token) + commit_message = commit_message or f"Super-squash branch '{branch}' using huggingface_hub" + + # Super-squash + response = get_session().post(url=url, headers=headers, json={"message": commit_message}) + hf_raise_for_status(response) + + @validate_hf_hub_args + def create_repo( + self, + repo_id: str, + *, + token: Optional[str] = None, + private: bool = False, + repo_type: Optional[str] = None, + exist_ok: bool = False, + space_sdk: Optional[str] = None, + space_hardware: Optional[SpaceHardware] = None, + space_storage: Optional[SpaceStorage] = None, + space_sleep_time: Optional[int] = None, + space_secrets: Optional[List[Dict[str, str]]] = None, + space_variables: Optional[List[Dict[str, str]]] = None, + ) -> RepoUrl: + """Create an empty repo on the HuggingFace Hub. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + token (`str`, *optional*): + An authentication token (See https://huggingface.co/settings/token) + private (`bool`, *optional*, defaults to `False`): + Whether the model repo should be private. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + exist_ok (`bool`, *optional*, defaults to `False`): + If `True`, do not raise an error if repo already exists. + space_sdk (`str`, *optional*): + Choice of SDK to use if repo_type is "space". Can be "streamlit", "gradio", "docker", or "static". + space_hardware (`SpaceHardware` or `str`, *optional*): + Choice of Hardware if repo_type is "space". See [`SpaceHardware`] for a complete list. + space_storage (`SpaceStorage` or `str`, *optional*): + Choice of persistent storage tier. Example: `"small"`. See [`SpaceStorage`] for a complete list. + space_sleep_time (`int`, *optional*): + Number of seconds of inactivity to wait before a Space is put to sleep. Set to `-1` if you don't want + your Space to sleep (default behavior for upgraded hardware). For free hardware, you can't configure + the sleep time (value is fixed to 48 hours of inactivity). + See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details. + space_secrets (`List[Dict[str, str]]`, *optional*): + A list of secret keys to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional. + For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets. + space_variables (`List[Dict[str, str]]`, *optional*): + A list of public environment variables to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional. + For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables. + + Returns: + [`RepoUrl`]: URL to the newly created repo. Value is a subclass of `str` containing + attributes like `endpoint`, `repo_type` and `repo_id`. + """ + organization, name = repo_id.split("/") if "/" in repo_id else (None, repo_id) + + path = f"{self.endpoint}/api/repos/create" + + if repo_type not in REPO_TYPES: + raise ValueError("Invalid repo type") + + json: Dict[str, Any] = {"name": name, "organization": organization, "private": private} + if repo_type is not None: + json["type"] = repo_type + if repo_type == "space": + if space_sdk is None: + raise ValueError( + "No space_sdk provided. `create_repo` expects space_sdk to be one" + f" of {SPACES_SDK_TYPES} when repo_type is 'space'`" + ) + if space_sdk not in SPACES_SDK_TYPES: + raise ValueError(f"Invalid space_sdk. Please choose one of {SPACES_SDK_TYPES}.") + json["sdk"] = space_sdk + + if space_sdk is not None and repo_type != "space": + warnings.warn("Ignoring provided space_sdk because repo_type is not 'space'.") + + function_args = [ + "space_hardware", + "space_storage", + "space_sleep_time", + "space_secrets", + "space_variables", + ] + json_keys = ["hardware", "storageTier", "sleepTimeSeconds", "secrets", "variables"] + values = [space_hardware, space_storage, space_sleep_time, space_secrets, space_variables] + + if repo_type == "space": + json.update({k: v for k, v in zip(json_keys, values) if v is not None}) + else: + provided_space_args = [key for key, value in zip(function_args, values) if value is not None] + + if provided_space_args: + warnings.warn(f"Ignoring provided {', '.join(provided_space_args)} because repo_type is not 'space'.") + + if getattr(self, "_lfsmultipartthresh", None): + # Testing purposes only. + # See https://github.com/huggingface/huggingface_hub/pull/733/files#r820604472 + json["lfsmultipartthresh"] = self._lfsmultipartthresh # type: ignore + headers = self._build_hf_headers(token=token) + + while True: + r = get_session().post(path, headers=headers, json=json) + if r.status_code == 409 and "Cannot create repo: another conflicting operation is in progress" in r.text: + # Since https://github.com/huggingface/moon-landing/pull/7272 (private repo), it is not possible to + # concurrently create repos on the Hub for a same user. This is rarely an issue, except when running + # tests. To avoid any inconvenience, we retry to create the repo for this specific error. + # NOTE: This could have being fixed directly in the tests but adding it here should fixed CIs for all + # dependent libraries. + # NOTE: If a fix is implemented server-side, we should be able to remove this retry mechanism. + logger.debug("Create repo failed due to a concurrency issue. Retrying...") + continue + break + + try: + hf_raise_for_status(r) + except HTTPError as err: + if exist_ok and err.response.status_code == 409: + # Repo already exists and `exist_ok=True` + pass + elif exist_ok and err.response.status_code == 403: + # No write permission on the namespace but repo might already exist + try: + self.repo_info(repo_id=repo_id, repo_type=repo_type, token=token) + if repo_type is None or repo_type == REPO_TYPE_MODEL: + return RepoUrl(f"{self.endpoint}/{repo_id}") + return RepoUrl(f"{self.endpoint}/{repo_type}/{repo_id}") + except HfHubHTTPError: + raise + else: + raise + + d = r.json() + return RepoUrl(d["url"], endpoint=self.endpoint) + + @validate_hf_hub_args + def delete_repo( + self, + repo_id: str, + *, + token: Optional[str] = None, + repo_type: Optional[str] = None, + missing_ok: bool = False, + ) -> None: + """ + Delete a repo from the HuggingFace Hub. CAUTION: this is irreversible. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + token (`str`, *optional*): + An authentication token (See https://huggingface.co/settings/token) + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. + missing_ok (`bool`, *optional*, defaults to `False`): + If `True`, do not raise an error if repo does not exist. + + Raises: + - [`~utils.RepositoryNotFoundError`] + If the repository to delete from cannot be found and `missing_ok` is set to False (default). + """ + organization, name = repo_id.split("/") if "/" in repo_id else (None, repo_id) + + path = f"{self.endpoint}/api/repos/delete" + + if repo_type not in REPO_TYPES: + raise ValueError("Invalid repo type") + + json = {"name": name, "organization": organization} + if repo_type is not None: + json["type"] = repo_type + + headers = self._build_hf_headers(token=token) + r = get_session().delete(path, headers=headers, json=json) + try: + hf_raise_for_status(r) + except RepositoryNotFoundError: + if not missing_ok: + raise + + @validate_hf_hub_args + @_deprecate_arguments( + version="0.24.0", deprecated_args=("organization", "name"), custom_message="Use `repo_id` instead." + ) + def update_repo_visibility( + self, + repo_id: str, + private: bool = False, + *, + token: Optional[str] = None, + organization: Optional[str] = None, + repo_type: Optional[str] = None, + name: Optional[str] = None, + ) -> Dict[str, bool]: + """Update the visibility setting of a repository. + + Args: + repo_id (`str`, *optional*): + A namespace (user or an organization) and a repo name separated + by a `/`. + private (`bool`, *optional*, defaults to `False`): + Whether the model repo should be private. + token (`str`, *optional*): + An authentication token (See https://huggingface.co/settings/token) + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + + Returns: + The HTTP response in json. + + + + Raises the following errors: + + - [`~utils.RepositoryNotFoundError`] + If the repository to download from cannot be found. This may be because it doesn't exist, + or because it is set to `private` and you do not have access. + + + """ + if repo_type not in REPO_TYPES: + raise ValueError("Invalid repo type") + + organization, name = repo_id.split("/") if "/" in repo_id else (None, repo_id) + + if organization is None: + namespace = self.whoami(token)["name"] + else: + namespace = organization + + if repo_type is None: + repo_type = REPO_TYPE_MODEL # default repo type + + r = get_session().put( + url=f"{self.endpoint}/api/{repo_type}s/{namespace}/{name}/settings", + headers=self._build_hf_headers(token=token), + json={"private": private}, + ) + hf_raise_for_status(r) + return r.json() + + def move_repo( + self, + from_id: str, + to_id: str, + *, + repo_type: Optional[str] = None, + token: Optional[str] = None, + ): + """ + Moving a repository from namespace1/repo_name1 to namespace2/repo_name2 + + Note there are certain limitations. For more information about moving + repositories, please see + https://hf.co/docs/hub/repositories-settings#renaming-or-transferring-a-repo. + + Args: + from_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. Original repository identifier. + to_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. Final repository identifier. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + token (`str`, *optional*): + An authentication token (See https://huggingface.co/settings/token) + + + + Raises the following errors: + + - [`~utils.RepositoryNotFoundError`] + If the repository to download from cannot be found. This may be because it doesn't exist, + or because it is set to `private` and you do not have access. + + + """ + if len(from_id.split("/")) != 2: + raise ValueError(f"Invalid repo_id: {from_id}. It should have a namespace (:namespace:/:repo_name:)") + + if len(to_id.split("/")) != 2: + raise ValueError(f"Invalid repo_id: {to_id}. It should have a namespace (:namespace:/:repo_name:)") + + if repo_type is None: + repo_type = REPO_TYPE_MODEL # Hub won't accept `None`. + + json = {"fromRepo": from_id, "toRepo": to_id, "type": repo_type} + + path = f"{self.endpoint}/api/repos/move" + headers = self._build_hf_headers(token=token) + r = get_session().post(path, headers=headers, json=json) + try: + hf_raise_for_status(r) + except HfHubHTTPError as e: + e.append_to_message( + "\nFor additional documentation please see" + " https://hf.co/docs/hub/repositories-settings#renaming-or-transferring-a-repo." + ) + raise + + @overload + def create_commit( # type: ignore + self, + repo_id: str, + operations: Iterable[CommitOperation], + *, + commit_message: str, + commit_description: Optional[str] = None, + token: Optional[str] = None, + repo_type: Optional[str] = None, + revision: Optional[str] = None, + create_pr: Optional[bool] = None, + num_threads: int = 5, + parent_commit: Optional[str] = None, + run_as_future: Literal[False] = ..., + ) -> CommitInfo: ... + + @overload + def create_commit( + self, + repo_id: str, + operations: Iterable[CommitOperation], + *, + commit_message: str, + commit_description: Optional[str] = None, + token: Optional[str] = None, + repo_type: Optional[str] = None, + revision: Optional[str] = None, + create_pr: Optional[bool] = None, + num_threads: int = 5, + parent_commit: Optional[str] = None, + run_as_future: Literal[True] = ..., + ) -> Future[CommitInfo]: ... + + @validate_hf_hub_args + @future_compatible + def create_commit( + self, + repo_id: str, + operations: Iterable[CommitOperation], + *, + commit_message: str, + commit_description: Optional[str] = None, + token: Optional[str] = None, + repo_type: Optional[str] = None, + revision: Optional[str] = None, + create_pr: Optional[bool] = None, + num_threads: int = 5, + parent_commit: Optional[str] = None, + run_as_future: bool = False, + ) -> Union[CommitInfo, Future[CommitInfo]]: + """ + Creates a commit in the given repo, deleting & uploading files as needed. + + + + The input list of `CommitOperation` will be mutated during the commit process. Do not reuse the same objects + for multiple commits. + + + + + + `create_commit` assumes that the repo already exists on the Hub. If you get a + Client error 404, please make sure you are authenticated and that `repo_id` and + `repo_type` are set correctly. If repo does not exist, create it first using + [`~hf_api.create_repo`]. + + + + + + `create_commit` is limited to 25k LFS files and a 1GB payload for regular files. + + + + Args: + repo_id (`str`): + The repository in which the commit will be created, for example: + `"username/custom_transformers"` + + operations (`Iterable` of [`~hf_api.CommitOperation`]): + An iterable of operations to include in the commit, either: + + - [`~hf_api.CommitOperationAdd`] to upload a file + - [`~hf_api.CommitOperationDelete`] to delete a file + - [`~hf_api.CommitOperationCopy`] to copy a file + + Operation objects will be mutated to include information relative to the upload. Do not reuse the + same objects for multiple commits. + + commit_message (`str`): + The summary (first line) of the commit that will be created. + + commit_description (`str`, *optional*): + The description of the commit that will be created + + token (`str`, *optional*): + Authentication token, obtained with `HfApi.login` method. Will + default to the stored token. + + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + + revision (`str`, *optional*): + The git revision to commit from. Defaults to the head of the `"main"` branch. + + create_pr (`boolean`, *optional*): + Whether or not to create a Pull Request with that commit. Defaults to `False`. + If `revision` is not set, PR is opened against the `"main"` branch. If + `revision` is set and is a branch, PR is opened against this branch. If + `revision` is set and is not a branch name (example: a commit oid), an + `RevisionNotFoundError` is returned by the server. + + num_threads (`int`, *optional*): + Number of concurrent threads for uploading files. Defaults to 5. + Setting it to 2 means at most 2 files will be uploaded concurrently. + + parent_commit (`str`, *optional*): + The OID / SHA of the parent commit, as a hexadecimal string. + Shorthands (7 first characters) are also supported. If specified and `create_pr` is `False`, + the commit will fail if `revision` does not point to `parent_commit`. If specified and `create_pr` + is `True`, the pull request will be created from `parent_commit`. Specifying `parent_commit` + ensures the repo has not changed before committing the changes, and can be especially useful + if the repo is updated / committed to concurrently. + run_as_future (`bool`, *optional*): + Whether or not to run this method in the background. Background jobs are run sequentially without + blocking the main thread. Passing `run_as_future=True` will return a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects) + object. Defaults to `False`. + + Returns: + [`CommitInfo`] or `Future`: + Instance of [`CommitInfo`] containing information about the newly created commit (commit hash, commit + url, pr url, commit message,...). If `run_as_future=True` is passed, returns a Future object which will + contain the result when executed. + + Raises: + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If commit message is empty. + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If parent commit is not a valid commit OID. + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If a README.md file with an invalid metadata section is committed. In this case, the commit will fail + early, before trying to upload any file. + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If `create_pr` is `True` and revision is neither `None` nor `"main"`. + [`~utils.RepositoryNotFoundError`]: + If repository is not found (error 404): wrong repo_id/repo_type, private + but not authenticated or repo does not exist. + """ + if parent_commit is not None and not REGEX_COMMIT_OID.fullmatch(parent_commit): + raise ValueError( + f"`parent_commit` is not a valid commit OID. It must match the following regex: {REGEX_COMMIT_OID}" + ) + + if commit_message is None or len(commit_message) == 0: + raise ValueError("`commit_message` can't be empty, please pass a value.") + + commit_description = commit_description if commit_description is not None else "" + repo_type = repo_type if repo_type is not None else REPO_TYPE_MODEL + if repo_type not in REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {REPO_TYPES}") + unquoted_revision = revision or DEFAULT_REVISION + revision = quote(unquoted_revision, safe="") + create_pr = create_pr if create_pr is not None else False + + headers = self._build_hf_headers(token=token) + + operations = list(operations) + additions = [op for op in operations if isinstance(op, CommitOperationAdd)] + copies = [op for op in operations if isinstance(op, CommitOperationCopy)] + nb_additions = len(additions) + nb_copies = len(copies) + nb_deletions = len(operations) - nb_additions - nb_copies + + for addition in additions: + if addition._is_committed: + raise ValueError( + f"CommitOperationAdd {addition} has already being committed and cannot be reused. Please create a" + " new CommitOperationAdd object if you want to create a new commit." + ) + + logger.debug( + f"About to commit to the hub: {len(additions)} addition(s), {len(copies)} copie(s) and" + f" {nb_deletions} deletion(s)." + ) + + # If updating a README.md file, make sure the metadata format is valid + # It's better to fail early than to fail after all the files have been uploaded. + for addition in additions: + if addition.path_in_repo == "README.md": + with addition.as_file() as file: + response = get_session().post( + f"{ENDPOINT}/api/validate-yaml", + json={"content": file.read().decode(), "repoType": repo_type}, + headers=headers, + ) + # Handle warnings (example: empty metadata) + response_content = response.json() + message = "\n".join( + [f"- {warning.get('message')}" for warning in response_content.get("warnings", [])] + ) + if message: + warnings.warn(f"Warnings while validating metadata in README.md:\n{message}") + + # Raise on errors + try: + hf_raise_for_status(response) + except BadRequestError as e: + errors = response_content.get("errors", []) + message = "\n".join([f"- {error.get('message')}" for error in errors]) + raise ValueError(f"Invalid metadata in README.md.\n{message}") from e + + # If updating twice the same file or update then delete a file in a single commit + _warn_on_overwriting_operations(operations) + + self.preupload_lfs_files( + repo_id=repo_id, + additions=additions, + token=token, + repo_type=repo_type, + revision=unquoted_revision, # first-class methods take unquoted revision + create_pr=create_pr, + num_threads=num_threads, + free_memory=False, # do not remove `CommitOperationAdd.path_or_fileobj` on LFS files for "normal" users + ) + files_to_copy = _fetch_files_to_copy( + copies=copies, + repo_type=repo_type, + repo_id=repo_id, + headers=headers, + revision=revision, + endpoint=self.endpoint, + ) + commit_payload = _prepare_commit_payload( + operations=operations, + files_to_copy=files_to_copy, + commit_message=commit_message, + commit_description=commit_description, + parent_commit=parent_commit, + ) + commit_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/commit/{revision}" + + def _payload_as_ndjson() -> Iterable[bytes]: + for item in commit_payload: + yield json.dumps(item).encode() + yield b"\n" + + headers = { + # See https://github.com/huggingface/huggingface_hub/issues/1085#issuecomment-1265208073 + "Content-Type": "application/x-ndjson", + **headers, + } + data = b"".join(_payload_as_ndjson()) + params = {"create_pr": "1"} if create_pr else None + + try: + commit_resp = get_session().post(url=commit_url, headers=headers, data=data, params=params) + hf_raise_for_status(commit_resp, endpoint_name="commit") + except RepositoryNotFoundError as e: + e.append_to_message(_CREATE_COMMIT_NO_REPO_ERROR_MESSAGE) + raise + except EntryNotFoundError as e: + if nb_deletions > 0 and "A file with this name doesn't exist" in str(e): + e.append_to_message( + "\nMake sure to differentiate file and folder paths in delete" + " operations with a trailing '/' or using `is_folder=True/False`." + ) + raise + + # Mark additions as committed (cannot be reused in another commit) + for addition in additions: + addition._is_committed = True + + commit_data = commit_resp.json() + return CommitInfo( + commit_url=commit_data["commitUrl"], + commit_message=commit_message, + commit_description=commit_description, + oid=commit_data["commitOid"], + pr_url=commit_data["pullRequestUrl"] if create_pr else None, + ) + + @experimental + @validate_hf_hub_args + def create_commits_on_pr( + self, + *, + repo_id: str, + addition_commits: List[List[CommitOperationAdd]], + deletion_commits: List[List[CommitOperationDelete]], + commit_message: str, + commit_description: Optional[str] = None, + token: Optional[str] = None, + repo_type: Optional[str] = None, + merge_pr: bool = True, + num_threads: int = 5, # TODO: use to multithread uploads + verbose: bool = False, + ) -> str: + """Push changes to the Hub in multiple commits. + + Commits are pushed to a draft PR branch. If the upload fails or gets interrupted, it can be resumed. Progress + is tracked in the PR description. At the end of the process, the PR is set as open and the title is updated to + match the initial commit message. If `merge_pr=True` is passed, the PR is merged automatically. + + All deletion commits are pushed first, followed by the addition commits. The order of the commits is not + guaranteed as we might implement parallel commits in the future. Be sure that your are not updating several + times the same file. + + + + `create_commits_on_pr` is experimental. Its API and behavior is subject to change in the future without prior notice. + + + + + + `create_commits_on_pr` assumes that the repo already exists on the Hub. If you get a Client error 404, please + make sure you are authenticated and that `repo_id` and `repo_type` are set correctly. If repo does not exist, + create it first using [`~hf_api.create_repo`]. + + + + Args: + repo_id (`str`): + The repository in which the commits will be pushed. Example: `"username/my-cool-model"`. + + addition_commits (`List` of `List` of [`~hf_api.CommitOperationAdd`]): + A list containing lists of [`~hf_api.CommitOperationAdd`]. Each sublist will result in a commit on the + PR. + + deletion_commits + A list containing lists of [`~hf_api.CommitOperationDelete`]. Each sublist will result in a commit on + the PR. Deletion commits are pushed before addition commits. + + commit_message (`str`): + The summary (first line) of the commit that will be created. Will also be the title of the PR. + + commit_description (`str`, *optional*): + The description of the commit that will be created. The description will be added to the PR. + + token (`str`, *optional*): + Authentication token, obtained with `HfApi.login` method. Will default to the stored token. + + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or space, `None` or `"model"` if uploading to + a model. Default is `None`. + + merge_pr (`bool`): + If set to `True`, the Pull Request is merged at the end of the process. Defaults to `True`. + + num_threads (`int`, *optional*): + Number of concurrent threads for uploading files. Defaults to 5. + + verbose (`bool`): + If set to `True`, process will run on verbose mode i.e. print information about the ongoing tasks. + Defaults to `False`. + + Returns: + `str`: URL to the created PR. + + Example: + ```python + >>> from huggingface_hub import HfApi, plan_multi_commits + >>> addition_commits, deletion_commits = plan_multi_commits( + ... operations=[ + ... CommitOperationAdd(...), + ... CommitOperationAdd(...), + ... CommitOperationDelete(...), + ... CommitOperationDelete(...), + ... CommitOperationAdd(...), + ... ], + ... ) + >>> HfApi().create_commits_on_pr( + ... repo_id="my-cool-model", + ... addition_commits=addition_commits, + ... deletion_commits=deletion_commits, + ... (...) + ... verbose=True, + ... ) + ``` + + Raises: + [`MultiCommitException`]: + If an unexpected issue occur in the process: empty commits, unexpected commits in a PR, unexpected PR + description, etc. + """ + logger = logging.get_logger(__name__ + ".create_commits_on_pr") + if verbose: + logger.setLevel("INFO") + + # 1. Get strategy ID + logger.info( + f"Will create {len(deletion_commits)} deletion commit(s) and {len(addition_commits)} addition commit(s)," + f" totalling {sum(len(ops) for ops in addition_commits+deletion_commits)} atomic operations." + ) + strategy = MultiCommitStrategy( + addition_commits=[MultiCommitStep(operations=operations) for operations in addition_commits], # type: ignore + deletion_commits=[MultiCommitStep(operations=operations) for operations in deletion_commits], # type: ignore + ) + logger.info(f"Multi-commits strategy with ID {strategy.id}.") + + # 2. Get or create a PR with this strategy ID + for discussion in self.get_repo_discussions(repo_id=repo_id, repo_type=repo_type, token=token): + # search for a draft PR with strategy ID + if discussion.is_pull_request and discussion.status == "draft" and strategy.id in discussion.title: + pr = self.get_discussion_details( + repo_id=repo_id, discussion_num=discussion.num, repo_type=repo_type, token=token + ) + logger.info(f"PR already exists: {pr.url}. Will resume process where it stopped.") + break + else: + # did not find a PR matching the strategy ID + pr = multi_commit_create_pull_request( + self, + repo_id=repo_id, + commit_message=commit_message, + commit_description=commit_description, + strategy=strategy, + token=token, + repo_type=repo_type, + ) + logger.info(f"New PR created: {pr.url}") + + # 3. Parse PR description to check consistency with strategy (e.g. same commits are scheduled) + for event in pr.events: + if isinstance(event, DiscussionComment): + pr_comment = event + break + else: + raise MultiCommitException(f"PR #{pr.num} must have at least 1 comment") + + description_commits = multi_commit_parse_pr_description(pr_comment.content) + if len(description_commits) != len(strategy.all_steps): + raise MultiCommitException( + f"Corrupted multi-commit PR #{pr.num}: got {len(description_commits)} steps in" + f" description but {len(strategy.all_steps)} in strategy." + ) + for step_id in strategy.all_steps: + if step_id not in description_commits: + raise MultiCommitException( + f"Corrupted multi-commit PR #{pr.num}: expected step {step_id} but didn't find" + f" it (have {', '.join(description_commits)})." + ) + + # 4. Retrieve commit history (and check consistency) + commits_on_main_branch = { + commit.commit_id + for commit in self.list_repo_commits( + repo_id=repo_id, repo_type=repo_type, token=token, revision=DEFAULT_REVISION + ) + } + pr_commits = [ + commit + for commit in self.list_repo_commits( + repo_id=repo_id, repo_type=repo_type, token=token, revision=pr.git_reference + ) + if commit.commit_id not in commits_on_main_branch + ] + if len(pr_commits) > 0: + logger.info(f"Found {len(pr_commits)} existing commits on the PR.") + + # At this point `pr_commits` is a list of commits pushed to the PR. We expect all of these commits (if any) to have + # a step_id as title. We raise exception if an unexpected commit has been pushed. + if len(pr_commits) > len(strategy.all_steps): + raise MultiCommitException( + f"Corrupted multi-commit PR #{pr.num}: scheduled {len(strategy.all_steps)} steps but" + f" {len(pr_commits)} commits have already been pushed to the PR." + ) + + # Check which steps are already completed + remaining_additions = {step.id: step for step in strategy.addition_commits} + remaining_deletions = {step.id: step for step in strategy.deletion_commits} + for commit in pr_commits: + if commit.title in remaining_additions: + step = remaining_additions.pop(commit.title) + step.completed = True + elif commit.title in remaining_deletions: + step = remaining_deletions.pop(commit.title) + step.completed = True + + if len(remaining_deletions) > 0 and len(remaining_additions) < len(strategy.addition_commits): + raise MultiCommitException( + f"Corrupted multi-commit PR #{pr.num}: some addition commits have already been pushed to the PR but" + " deletion commits are not all completed yet." + ) + nb_remaining = len(remaining_deletions) + len(remaining_additions) + if len(pr_commits) > 0: + logger.info( + f"{nb_remaining} commits remaining ({len(remaining_deletions)} deletion commits and" + f" {len(remaining_additions)} addition commits)" + ) + + # 5. Push remaining commits to the PR + update description + # TODO: multi-thread this + for step in list(remaining_deletions.values()) + list(remaining_additions.values()): + # Push new commit + self.create_commit( + repo_id=repo_id, + repo_type=repo_type, + token=token, + commit_message=step.id, + revision=pr.git_reference, + num_threads=num_threads, + operations=step.operations, + create_pr=False, + ) + step.completed = True + nb_remaining -= 1 + logger.info(f" step {step.id} completed (still {nb_remaining} to go).") + + # Update PR description + self.edit_discussion_comment( + repo_id=repo_id, + repo_type=repo_type, + token=token, + discussion_num=pr.num, + comment_id=pr_comment.id, + new_content=multi_commit_generate_comment( + commit_message=commit_message, commit_description=commit_description, strategy=strategy + ), + ) + logger.info("All commits have been pushed.") + + # 6. Update PR (and merge) + self.rename_discussion( + repo_id=repo_id, + repo_type=repo_type, + token=token, + discussion_num=pr.num, + new_title=commit_message, + ) + self.change_discussion_status( + repo_id=repo_id, + repo_type=repo_type, + token=token, + discussion_num=pr.num, + new_status="open", + comment=MULTI_COMMIT_PR_COMPLETION_COMMENT_TEMPLATE, + ) + logger.info("PR is now open for reviews.") + + if merge_pr: # User don't want a PR => merge it + try: + self.merge_pull_request( + repo_id=repo_id, + repo_type=repo_type, + token=token, + discussion_num=pr.num, + comment=MULTI_COMMIT_PR_CLOSING_COMMENT_TEMPLATE, + ) + logger.info("PR has been automatically merged (`merge_pr=True` was passed).") + except BadRequestError as error: + if error.server_message is not None and "no associated changes" in error.server_message: + # PR cannot be merged as no changes are associated. We close the PR without merging with a comment to + # explain. + self.change_discussion_status( + repo_id=repo_id, + repo_type=repo_type, + token=token, + discussion_num=pr.num, + comment=MULTI_COMMIT_PR_CLOSE_COMMENT_FAILURE_NO_CHANGES_TEMPLATE, + new_status="closed", + ) + logger.warning("Couldn't merge the PR: no associated changes.") + else: + # PR cannot be merged for another reason (conflicting files for example). We comment the PR to explain + # and re-raise the exception. + self.comment_discussion( + repo_id=repo_id, + repo_type=repo_type, + token=token, + discussion_num=pr.num, + comment=MULTI_COMMIT_PR_CLOSE_COMMENT_FAILURE_BAD_REQUEST_TEMPLATE.format( + error_message=error.server_message + ), + ) + raise MultiCommitException( + f"Couldn't merge Pull Request in multi-commit: {error.server_message}" + ) from error + + return pr.url + + def preupload_lfs_files( + self, + repo_id: str, + additions: Iterable[CommitOperationAdd], + *, + token: Optional[str] = None, + repo_type: Optional[str] = None, + revision: Optional[str] = None, + create_pr: Optional[bool] = None, + num_threads: int = 5, + free_memory: bool = True, + gitignore_content: Optional[str] = None, + ): + """Pre-upload LFS files to S3 in preparation on a future commit. + + This method is useful if you are generating the files to upload on-the-fly and you don't want to store them + in memory before uploading them all at once. + + + + This is a power-user method. You shouldn't need to call it directly to make a normal commit. + Use [`create_commit`] directly instead. + + + + + + Commit operations will be mutated during the process. In particular, the attached `path_or_fileobj` will be + removed after the upload to save memory (and replaced by an empty `bytes` object). Do not reuse the same + objects except to pass them to [`create_commit`]. If you don't want to remove the attached content from the + commit operation object, pass `free_memory=False`. + + + + Args: + repo_id (`str`): + The repository in which you will commit the files, for example: `"username/custom_transformers"`. + + operations (`Iterable` of [`CommitOperationAdd`]): + The list of files to upload. Warning: the objects in this list will be mutated to include information + relative to the upload. Do not reuse the same objects for multiple commits. + + token (`str`, *optional*): + Authentication token. Will default to the stored token. + + repo_type (`str`, *optional*): + The type of repository to upload to (e.g. `"model"` -default-, `"dataset"` or `"space"`). + + revision (`str`, *optional*): + The git revision to commit from. Defaults to the head of the `"main"` branch. + + create_pr (`boolean`, *optional*): + Whether or not you plan to create a Pull Request with that commit. Defaults to `False`. + + num_threads (`int`, *optional*): + Number of concurrent threads for uploading files. Defaults to 5. + Setting it to 2 means at most 2 files will be uploaded concurrently. + + gitignore_content (`str`, *optional*): + The content of the `.gitignore` file to know which files should be ignored. The order of priority + is to first check if `gitignore_content` is passed, then check if the `.gitignore` file is present + in the list of files to commit and finally default to the `.gitignore` file already hosted on the Hub + (if any). + + Example: + ```py + >>> from huggingface_hub import CommitOperationAdd, preupload_lfs_files, create_commit, create_repo + + >>> repo_id = create_repo("test_preupload").repo_id + + # Generate and preupload LFS files one by one + >>> operations = [] # List of all `CommitOperationAdd` objects that will be generated + >>> for i in range(5): + ... content = ... # generate binary content + ... addition = CommitOperationAdd(path_in_repo=f"shard_{i}_of_5.bin", path_or_fileobj=content) + ... preupload_lfs_files(repo_id, additions=[addition]) # upload + free memory + ... operations.append(addition) + + # Create commit + >>> create_commit(repo_id, operations=operations, commit_message="Commit all shards") + ``` + """ + repo_type = repo_type if repo_type is not None else REPO_TYPE_MODEL + if repo_type not in REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {REPO_TYPES}") + revision = quote(revision, safe="") if revision is not None else DEFAULT_REVISION + create_pr = create_pr if create_pr is not None else False + headers = self._build_hf_headers(token=token) + + # Check if a `gitignore` file is being committed to the Hub. + additions = list(additions) + if gitignore_content is None: + for addition in additions: + if addition.path_in_repo == ".gitignore": + with addition.as_file() as f: + gitignore_content = f.read().decode() + break + + # Filter out already uploaded files + new_additions = [addition for addition in additions if not addition._is_uploaded] + + # Check which new files are LFS + try: + _fetch_upload_modes( + additions=new_additions, + repo_type=repo_type, + repo_id=repo_id, + headers=headers, + revision=revision, + endpoint=self.endpoint, + create_pr=create_pr or False, + gitignore_content=gitignore_content, + ) + except RepositoryNotFoundError as e: + e.append_to_message(_CREATE_COMMIT_NO_REPO_ERROR_MESSAGE) + raise + + # Filter out regular files + new_lfs_additions = [addition for addition in new_additions if addition._upload_mode == "lfs"] + + # Filter out files listed in .gitignore + new_lfs_additions_to_upload = [] + for addition in new_lfs_additions: + if addition._should_ignore: + logger.debug(f"Skipping upload for LFS file '{addition.path_in_repo}' (ignored by gitignore file).") + else: + new_lfs_additions_to_upload.append(addition) + if len(new_lfs_additions) != len(new_lfs_additions_to_upload): + logger.info( + f"Skipped upload for {len(new_lfs_additions) - len(new_lfs_additions_to_upload)} LFS file(s) " + "(ignored by gitignore file)." + ) + + # Upload new LFS files + _upload_lfs_files( + additions=new_lfs_additions_to_upload, + repo_type=repo_type, + repo_id=repo_id, + headers=headers, + endpoint=self.endpoint, + num_threads=num_threads, + # If `create_pr`, we don't want to check user permission on the revision as users with read permission + # should still be able to create PRs even if they don't have write permission on the target branch of the + # PR (i.e. `revision`). + revision=revision if not create_pr else None, + ) + for addition in new_lfs_additions_to_upload: + addition._is_uploaded = True + if free_memory: + addition.path_or_fileobj = b"" + + @overload + def upload_file( # type: ignore + self, + *, + path_or_fileobj: Union[str, Path, bytes, BinaryIO], + path_in_repo: str, + repo_id: str, + token: Optional[str] = None, + repo_type: Optional[str] = None, + revision: Optional[str] = None, + commit_message: Optional[str] = None, + commit_description: Optional[str] = None, + create_pr: Optional[bool] = None, + parent_commit: Optional[str] = None, + run_as_future: Literal[False] = ..., + ) -> CommitInfo: ... + + @overload + def upload_file( + self, + *, + path_or_fileobj: Union[str, Path, bytes, BinaryIO], + path_in_repo: str, + repo_id: str, + token: Optional[str] = None, + repo_type: Optional[str] = None, + revision: Optional[str] = None, + commit_message: Optional[str] = None, + commit_description: Optional[str] = None, + create_pr: Optional[bool] = None, + parent_commit: Optional[str] = None, + run_as_future: Literal[True] = ..., + ) -> Future[CommitInfo]: ... + + @validate_hf_hub_args + @future_compatible + def upload_file( + self, + *, + path_or_fileobj: Union[str, Path, bytes, BinaryIO], + path_in_repo: str, + repo_id: str, + token: Optional[str] = None, + repo_type: Optional[str] = None, + revision: Optional[str] = None, + commit_message: Optional[str] = None, + commit_description: Optional[str] = None, + create_pr: Optional[bool] = None, + parent_commit: Optional[str] = None, + run_as_future: bool = False, + ) -> Union[CommitInfo, Future[CommitInfo]]: + """ + Upload a local file (up to 50 GB) to the given repo. The upload is done + through a HTTP post request, and doesn't require git or git-lfs to be + installed. + + Args: + path_or_fileobj (`str`, `Path`, `bytes`, or `IO`): + Path to a file on the local machine or binary data stream / + fileobj / buffer. + path_in_repo (`str`): + Relative filepath in the repo, for example: + `"checkpoints/1fec34a/weights.bin"` + repo_id (`str`): + The repository to which the file will be uploaded, for example: + `"username/custom_transformers"` + token (`str`, *optional*): + Authentication token, obtained with `HfApi.login` method. Will + default to the stored token. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + revision (`str`, *optional*): + The git revision to commit from. Defaults to the head of the `"main"` branch. + commit_message (`str`, *optional*): + The summary / title / first line of the generated commit + commit_description (`str` *optional*) + The description of the generated commit + create_pr (`boolean`, *optional*): + Whether or not to create a Pull Request with that commit. Defaults to `False`. + If `revision` is not set, PR is opened against the `"main"` branch. If + `revision` is set and is a branch, PR is opened against this branch. If + `revision` is set and is not a branch name (example: a commit oid), an + `RevisionNotFoundError` is returned by the server. + parent_commit (`str`, *optional*): + The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported. + If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`. + If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`. + Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be + especially useful if the repo is updated / committed to concurrently. + run_as_future (`bool`, *optional*): + Whether or not to run this method in the background. Background jobs are run sequentially without + blocking the main thread. Passing `run_as_future=True` will return a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects) + object. Defaults to `False`. + + + Returns: + [`CommitInfo`] or `Future`: + Instance of [`CommitInfo`] containing information about the newly created commit (commit hash, commit + url, pr url, commit message,...). If `run_as_future=True` is passed, returns a Future object which will + contain the result when executed. + + + Raises the following errors: + + - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + if the HuggingFace API returned an error + - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + if some parameter value is invalid + - [`~utils.RepositoryNotFoundError`] + If the repository to download from cannot be found. This may be because it doesn't exist, + or because it is set to `private` and you do not have access. + - [`~utils.RevisionNotFoundError`] + If the revision to download from cannot be found. + + + + + + `upload_file` assumes that the repo already exists on the Hub. If you get a + Client error 404, please make sure you are authenticated and that `repo_id` and + `repo_type` are set correctly. If repo does not exist, create it first using + [`~hf_api.create_repo`]. + + + + Example: + + ```python + >>> from huggingface_hub import upload_file + + >>> with open("./local/filepath", "rb") as fobj: + ... upload_file( + ... path_or_fileobj=fileobj, + ... path_in_repo="remote/file/path.h5", + ... repo_id="username/my-dataset", + ... repo_type="dataset", + ... token="my_token", + ... ) + "https://huggingface.co/datasets/username/my-dataset/blob/main/remote/file/path.h5" + + >>> upload_file( + ... path_or_fileobj=".\\\\local\\\\file\\\\path", + ... path_in_repo="remote/file/path.h5", + ... repo_id="username/my-model", + ... token="my_token", + ... ) + "https://huggingface.co/username/my-model/blob/main/remote/file/path.h5" + + >>> upload_file( + ... path_or_fileobj=".\\\\local\\\\file\\\\path", + ... path_in_repo="remote/file/path.h5", + ... repo_id="username/my-model", + ... token="my_token", + ... create_pr=True, + ... ) + "https://huggingface.co/username/my-model/blob/refs%2Fpr%2F1/remote/file/path.h5" + ``` + """ + if repo_type not in REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {REPO_TYPES}") + + commit_message = ( + commit_message if commit_message is not None else f"Upload {path_in_repo} with huggingface_hub" + ) + operation = CommitOperationAdd( + path_or_fileobj=path_or_fileobj, + path_in_repo=path_in_repo, + ) + + commit_info = self.create_commit( + repo_id=repo_id, + repo_type=repo_type, + operations=[operation], + commit_message=commit_message, + commit_description=commit_description, + token=token, + revision=revision, + create_pr=create_pr, + parent_commit=parent_commit, + ) + + if commit_info.pr_url is not None: + revision = quote(_parse_revision_from_pr_url(commit_info.pr_url), safe="") + if repo_type in REPO_TYPES_URL_PREFIXES: + repo_id = REPO_TYPES_URL_PREFIXES[repo_type] + repo_id + revision = revision if revision is not None else DEFAULT_REVISION + + return CommitInfo( + commit_url=commit_info.commit_url, + commit_message=commit_info.commit_message, + commit_description=commit_info.commit_description, + oid=commit_info.oid, + pr_url=commit_info.pr_url, + # Similar to `hf_hub_url` but it's "blob" instead of "resolve" + # TODO: remove this in v1.0 + _url=f"{self.endpoint}/{repo_id}/blob/{revision}/{path_in_repo}", + ) + + @overload + def upload_folder( # type: ignore + self, + *, + repo_id: str, + folder_path: Union[str, Path], + path_in_repo: Optional[str] = None, + commit_message: Optional[str] = None, + commit_description: Optional[str] = None, + token: Optional[str] = None, + repo_type: Optional[str] = None, + revision: Optional[str] = None, + create_pr: Optional[bool] = None, + parent_commit: Optional[str] = None, + allow_patterns: Optional[Union[List[str], str]] = None, + ignore_patterns: Optional[Union[List[str], str]] = None, + delete_patterns: Optional[Union[List[str], str]] = None, + multi_commits: Literal[False] = ..., + multi_commits_verbose: bool = False, + run_as_future: Literal[False] = ..., + ) -> CommitInfo: ... + + @overload + def upload_folder( # type: ignore + self, + *, + repo_id: str, + folder_path: Union[str, Path], + path_in_repo: Optional[str] = None, + commit_message: Optional[str] = None, + commit_description: Optional[str] = None, + token: Optional[str] = None, + repo_type: Optional[str] = None, + revision: Optional[str] = None, + create_pr: Optional[bool] = None, + parent_commit: Optional[str] = None, + allow_patterns: Optional[Union[List[str], str]] = None, + ignore_patterns: Optional[Union[List[str], str]] = None, + delete_patterns: Optional[Union[List[str], str]] = None, + multi_commits: Literal[True] = ..., + multi_commits_verbose: bool = False, + run_as_future: Literal[False] = ..., + ) -> str: # Only the PR url in multi-commits mode + ... + + @overload + def upload_folder( # type: ignore + self, + *, + repo_id: str, + folder_path: Union[str, Path], + path_in_repo: Optional[str] = None, + commit_message: Optional[str] = None, + commit_description: Optional[str] = None, + token: Optional[str] = None, + repo_type: Optional[str] = None, + revision: Optional[str] = None, + create_pr: Optional[bool] = None, + parent_commit: Optional[str] = None, + allow_patterns: Optional[Union[List[str], str]] = None, + ignore_patterns: Optional[Union[List[str], str]] = None, + delete_patterns: Optional[Union[List[str], str]] = None, + multi_commits: Literal[False] = ..., + multi_commits_verbose: bool = False, + run_as_future: Literal[True] = ..., + ) -> Future[CommitInfo]: ... + + @overload + def upload_folder( + self, + *, + repo_id: str, + folder_path: Union[str, Path], + path_in_repo: Optional[str] = None, + commit_message: Optional[str] = None, + commit_description: Optional[str] = None, + token: Optional[str] = None, + repo_type: Optional[str] = None, + revision: Optional[str] = None, + create_pr: Optional[bool] = None, + parent_commit: Optional[str] = None, + allow_patterns: Optional[Union[List[str], str]] = None, + ignore_patterns: Optional[Union[List[str], str]] = None, + delete_patterns: Optional[Union[List[str], str]] = None, + multi_commits: Literal[True] = ..., + multi_commits_verbose: bool = False, + run_as_future: Literal[True] = ..., + ) -> Future[str]: # Only the PR url in multi-commits mode + ... + + @validate_hf_hub_args + @future_compatible + def upload_folder( + self, + *, + repo_id: str, + folder_path: Union[str, Path], + path_in_repo: Optional[str] = None, + commit_message: Optional[str] = None, + commit_description: Optional[str] = None, + token: Optional[str] = None, + repo_type: Optional[str] = None, + revision: Optional[str] = None, + create_pr: Optional[bool] = None, + parent_commit: Optional[str] = None, + allow_patterns: Optional[Union[List[str], str]] = None, + ignore_patterns: Optional[Union[List[str], str]] = None, + delete_patterns: Optional[Union[List[str], str]] = None, + multi_commits: bool = False, + multi_commits_verbose: bool = False, + run_as_future: bool = False, + ) -> Union[CommitInfo, str, Future[CommitInfo], Future[str]]: + """ + Upload a local folder to the given repo. The upload is done through a HTTP requests, and doesn't require git or + git-lfs to be installed. + + The structure of the folder will be preserved. Files with the same name already present in the repository will + be overwritten. Others will be left untouched. + + Use the `allow_patterns` and `ignore_patterns` arguments to specify which files to upload. These parameters + accept either a single pattern or a list of patterns. Patterns are Standard Wildcards (globbing patterns) as + documented [here](https://tldp.org/LDP/GNU-Linux-Tools-Summary/html/x11655.htm). If both `allow_patterns` and + `ignore_patterns` are provided, both constraints apply. By default, all files from the folder are uploaded. + + Use the `delete_patterns` argument to specify remote files you want to delete. Input type is the same as for + `allow_patterns` (see above). If `path_in_repo` is also provided, the patterns are matched against paths + relative to this folder. For example, `upload_folder(..., path_in_repo="experiment", delete_patterns="logs/*")` + will delete any remote file under `./experiment/logs/`. Note that the `.gitattributes` file will not be deleted + even if it matches the patterns. + + Any `.git/` folder present in any subdirectory will be ignored. However, please be aware that the `.gitignore` + file is not taken into account. + + Uses `HfApi.create_commit` under the hood. + + Args: + repo_id (`str`): + The repository to which the file will be uploaded, for example: + `"username/custom_transformers"` + folder_path (`str` or `Path`): + Path to the folder to upload on the local file system + path_in_repo (`str`, *optional*): + Relative path of the directory in the repo, for example: + `"checkpoints/1fec34a/results"`. Will default to the root folder of the repository. + token (`str`, *optional*): + Authentication token, obtained with `HfApi.login` method. Will + default to the stored token. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + revision (`str`, *optional*): + The git revision to commit from. Defaults to the head of the `"main"` branch. + commit_message (`str`, *optional*): + The summary / title / first line of the generated commit. Defaults to: + `f"Upload {path_in_repo} with huggingface_hub"` + commit_description (`str` *optional*): + The description of the generated commit + create_pr (`boolean`, *optional*): + Whether or not to create a Pull Request with that commit. Defaults to `False`. If `revision` is not + set, PR is opened against the `"main"` branch. If `revision` is set and is a branch, PR is opened + against this branch. If `revision` is set and is not a branch name (example: a commit oid), an + `RevisionNotFoundError` is returned by the server. If both `multi_commits` and `create_pr` are True, + the PR created in the multi-commit process is kept opened. + parent_commit (`str`, *optional*): + The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported. + If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`. + If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`. + Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be + especially useful if the repo is updated / committed to concurrently. + allow_patterns (`List[str]` or `str`, *optional*): + If provided, only files matching at least one pattern are uploaded. + ignore_patterns (`List[str]` or `str`, *optional*): + If provided, files matching any of the patterns are not uploaded. + delete_patterns (`List[str]` or `str`, *optional*): + If provided, remote files matching any of the patterns will be deleted from the repo while committing + new files. This is useful if you don't know which files have already been uploaded. + Note: to avoid discrepancies the `.gitattributes` file is not deleted even if it matches the pattern. + multi_commits (`bool`): + If True, changes are pushed to a PR using a multi-commit process. Defaults to `False`. + multi_commits_verbose (`bool`): + If True and `multi_commits` is used, more information will be displayed to the user. + run_as_future (`bool`, *optional*): + Whether or not to run this method in the background. Background jobs are run sequentially without + blocking the main thread. Passing `run_as_future=True` will return a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects) + object. Defaults to `False`. + + Returns: + [`CommitInfo`] or `Future`: + Instance of [`CommitInfo`] containing information about the newly created commit (commit hash, commit + url, pr url, commit message,...). If `run_as_future=True` is passed, returns a Future object which will + contain the result when executed. + [`str`] or `Future`: + If `multi_commits=True`, returns the url of the PR created to push the changes. If `run_as_future=True` + is passed, returns a Future object which will contain the result when executed. + + + + Raises the following errors: + + - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + if the HuggingFace API returned an error + - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + if some parameter value is invalid + + + + + + `upload_folder` assumes that the repo already exists on the Hub. If you get a Client error 404, please make + sure you are authenticated and that `repo_id` and `repo_type` are set correctly. If repo does not exist, create + it first using [`~hf_api.create_repo`]. + + + + + + `multi_commits` is experimental. Its API and behavior is subject to change in the future without prior notice. + + + + Example: + + ```python + # Upload checkpoints folder except the log files + >>> upload_folder( + ... folder_path="local/checkpoints", + ... path_in_repo="remote/experiment/checkpoints", + ... repo_id="username/my-dataset", + ... repo_type="datasets", + ... token="my_token", + ... ignore_patterns="**/logs/*.txt", + ... ) + # "https://huggingface.co/datasets/username/my-dataset/tree/main/remote/experiment/checkpoints" + + # Upload checkpoints folder including logs while deleting existing logs from the repo + # Useful if you don't know exactly which log files have already being pushed + >>> upload_folder( + ... folder_path="local/checkpoints", + ... path_in_repo="remote/experiment/checkpoints", + ... repo_id="username/my-dataset", + ... repo_type="datasets", + ... token="my_token", + ... delete_patterns="**/logs/*.txt", + ... ) + "https://huggingface.co/datasets/username/my-dataset/tree/main/remote/experiment/checkpoints" + + # Upload checkpoints folder while creating a PR + >>> upload_folder( + ... folder_path="local/checkpoints", + ... path_in_repo="remote/experiment/checkpoints", + ... repo_id="username/my-dataset", + ... repo_type="datasets", + ... token="my_token", + ... create_pr=True, + ... ) + "https://huggingface.co/datasets/username/my-dataset/tree/refs%2Fpr%2F1/remote/experiment/checkpoints" + + ``` + """ + if repo_type not in REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {REPO_TYPES}") + + if multi_commits: + if revision is not None and revision != DEFAULT_REVISION: + raise ValueError("Cannot use `multi_commit` to commit changes other than the main branch.") + + # By default, upload folder to the root directory in repo. + if path_in_repo is None: + path_in_repo = "" + + # Do not upload .git folder + if ignore_patterns is None: + ignore_patterns = [] + elif isinstance(ignore_patterns, str): + ignore_patterns = [ignore_patterns] + ignore_patterns += IGNORE_GIT_FOLDER_PATTERNS + + delete_operations = self._prepare_upload_folder_deletions( + repo_id=repo_id, + repo_type=repo_type, + revision=DEFAULT_REVISION if create_pr else revision, + token=token, + path_in_repo=path_in_repo, + delete_patterns=delete_patterns, + ) + add_operations = _prepare_upload_folder_additions( + folder_path, + path_in_repo, + allow_patterns=allow_patterns, + ignore_patterns=ignore_patterns, + ) + + # Optimize operations: if some files will be overwritten, we don't need to delete them first + if len(add_operations) > 0: + added_paths = set(op.path_in_repo for op in add_operations) + delete_operations = [ + delete_op for delete_op in delete_operations if delete_op.path_in_repo not in added_paths + ] + commit_operations = delete_operations + add_operations + + commit_message = commit_message or "Upload folder using huggingface_hub" + if multi_commits: + addition_commits, deletion_commits = plan_multi_commits(operations=commit_operations) + pr_url = self.create_commits_on_pr( + repo_id=repo_id, + repo_type=repo_type, + addition_commits=addition_commits, + deletion_commits=deletion_commits, + commit_message=commit_message, + commit_description=commit_description, + token=token, + merge_pr=not create_pr, + verbose=multi_commits_verbose, + ) + # Defining a CommitInfo object is not really relevant in this case + # Let's return early with pr_url only (as string). + return pr_url + + commit_info = self.create_commit( + repo_type=repo_type, + repo_id=repo_id, + operations=commit_operations, + commit_message=commit_message, + commit_description=commit_description, + token=token, + revision=revision, + create_pr=create_pr, + parent_commit=parent_commit, + ) + + # Create url to uploaded folder (for legacy return value) + if create_pr and commit_info.pr_url is not None: + revision = quote(_parse_revision_from_pr_url(commit_info.pr_url), safe="") + if repo_type in REPO_TYPES_URL_PREFIXES: + repo_id = REPO_TYPES_URL_PREFIXES[repo_type] + repo_id + revision = revision if revision is not None else DEFAULT_REVISION + + return CommitInfo( + commit_url=commit_info.commit_url, + commit_message=commit_info.commit_message, + commit_description=commit_info.commit_description, + oid=commit_info.oid, + pr_url=commit_info.pr_url, + # Similar to `hf_hub_url` but it's "tree" instead of "resolve" + # TODO: remove this in v1.0 + _url=f"{self.endpoint}/{repo_id}/tree/{revision}/{path_in_repo}", + ) + + @validate_hf_hub_args + def delete_file( + self, + path_in_repo: str, + repo_id: str, + *, + token: Optional[str] = None, + repo_type: Optional[str] = None, + revision: Optional[str] = None, + commit_message: Optional[str] = None, + commit_description: Optional[str] = None, + create_pr: Optional[bool] = None, + parent_commit: Optional[str] = None, + ) -> CommitInfo: + """ + Deletes a file in the given repo. + + Args: + path_in_repo (`str`): + Relative filepath in the repo, for example: + `"checkpoints/1fec34a/weights.bin"` + repo_id (`str`): + The repository from which the file will be deleted, for example: + `"username/custom_transformers"` + token (`str`, *optional*): + Authentication token, obtained with `HfApi.login` method. Will + default to the stored token. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if the file is in a dataset or + space, `None` or `"model"` if in a model. Default is `None`. + revision (`str`, *optional*): + The git revision to commit from. Defaults to the head of the `"main"` branch. + commit_message (`str`, *optional*): + The summary / title / first line of the generated commit. Defaults to + `f"Delete {path_in_repo} with huggingface_hub"`. + commit_description (`str` *optional*) + The description of the generated commit + create_pr (`boolean`, *optional*): + Whether or not to create a Pull Request with that commit. Defaults to `False`. + If `revision` is not set, PR is opened against the `"main"` branch. If + `revision` is set and is a branch, PR is opened against this branch. If + `revision` is set and is not a branch name (example: a commit oid), an + `RevisionNotFoundError` is returned by the server. + parent_commit (`str`, *optional*): + The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported. + If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`. + If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`. + Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be + especially useful if the repo is updated / committed to concurrently. + + + + + Raises the following errors: + + - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + if the HuggingFace API returned an error + - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + if some parameter value is invalid + - [`~utils.RepositoryNotFoundError`] + If the repository to download from cannot be found. This may be because it doesn't exist, + or because it is set to `private` and you do not have access. + - [`~utils.RevisionNotFoundError`] + If the revision to download from cannot be found. + - [`~utils.EntryNotFoundError`] + If the file to download cannot be found. + + + + """ + commit_message = ( + commit_message if commit_message is not None else f"Delete {path_in_repo} with huggingface_hub" + ) + + operations = [CommitOperationDelete(path_in_repo=path_in_repo)] + + return self.create_commit( + repo_id=repo_id, + repo_type=repo_type, + token=token, + operations=operations, + revision=revision, + commit_message=commit_message, + commit_description=commit_description, + create_pr=create_pr, + parent_commit=parent_commit, + ) + + @validate_hf_hub_args + def delete_folder( + self, + path_in_repo: str, + repo_id: str, + *, + token: Optional[str] = None, + repo_type: Optional[str] = None, + revision: Optional[str] = None, + commit_message: Optional[str] = None, + commit_description: Optional[str] = None, + create_pr: Optional[bool] = None, + parent_commit: Optional[str] = None, + ) -> CommitInfo: + """ + Deletes a folder in the given repo. + + Simple wrapper around [`create_commit`] method. + + Args: + path_in_repo (`str`): + Relative folder path in the repo, for example: `"checkpoints/1fec34a"`. + repo_id (`str`): + The repository from which the folder will be deleted, for example: + `"username/custom_transformers"` + token (`str`, *optional*): + Authentication token, obtained with `HfApi.login` method. Will default + to the stored token. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if the folder is in a dataset or + space, `None` or `"model"` if in a model. Default is `None`. + revision (`str`, *optional*): + The git revision to commit from. Defaults to the head of the `"main"` branch. + commit_message (`str`, *optional*): + The summary / title / first line of the generated commit. Defaults to + `f"Delete folder {path_in_repo} with huggingface_hub"`. + commit_description (`str` *optional*) + The description of the generated commit. + create_pr (`boolean`, *optional*): + Whether or not to create a Pull Request with that commit. Defaults to `False`. + If `revision` is not set, PR is opened against the `"main"` branch. If + `revision` is set and is a branch, PR is opened against this branch. If + `revision` is set and is not a branch name (example: a commit oid), an + `RevisionNotFoundError` is returned by the server. + parent_commit (`str`, *optional*): + The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported. + If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`. + If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`. + Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be + especially useful if the repo is updated / committed to concurrently. + """ + return self.create_commit( + repo_id=repo_id, + repo_type=repo_type, + token=token, + operations=[CommitOperationDelete(path_in_repo=path_in_repo, is_folder=True)], + revision=revision, + commit_message=( + commit_message if commit_message is not None else f"Delete folder {path_in_repo} with huggingface_hub" + ), + commit_description=commit_description, + create_pr=create_pr, + parent_commit=parent_commit, + ) + + @validate_hf_hub_args + def get_hf_file_metadata( + self, + *, + url: str, + token: Union[bool, str, None] = None, + proxies: Optional[Dict] = None, + timeout: Optional[float] = DEFAULT_REQUEST_TIMEOUT, + ) -> HfFileMetadata: + """Fetch metadata of a file versioned on the Hub for a given url. + + Args: + url (`str`): + File url, for example returned by [`hf_hub_url`]. + token (`str` or `bool`, *optional*): + A token to be used for the download. + - If `True`, the token is read from the HuggingFace config + folder. + - If `False` or `None`, no token is provided. + - If a string, it's used as the authentication token. + proxies (`dict`, *optional*): + Dictionary mapping protocol to the URL of the proxy passed to `requests.request`. + timeout (`float`, *optional*, defaults to 10): + How many seconds to wait for the server to send metadata before giving up. + + Returns: + A [`HfFileMetadata`] object containing metadata such as location, etag, size and commit_hash. + """ + if token is None: + # Cannot do `token = token or self.token` as token can be `False`. + token = self.token + + return get_hf_file_metadata( + url=url, + token=token, + proxies=proxies, + timeout=timeout, + library_name=self.library_name, + library_version=self.library_version, + user_agent=self.user_agent, + ) + + @validate_hf_hub_args + def hf_hub_download( + self, + repo_id: str, + filename: str, + *, + subfolder: Optional[str] = None, + repo_type: Optional[str] = None, + revision: Optional[str] = None, + cache_dir: Union[str, Path, None] = None, + local_dir: Union[str, Path, None] = None, + local_dir_use_symlinks: Union[bool, Literal["auto"]] = "auto", + force_download: bool = False, + force_filename: Optional[str] = None, + proxies: Optional[Dict] = None, + etag_timeout: float = DEFAULT_ETAG_TIMEOUT, + resume_download: bool = False, + token: Optional[Union[str, bool]] = None, + local_files_only: bool = False, + legacy_cache_layout: bool = False, + ) -> str: + """Download a given file if it's not already present in the local cache. + + The new cache file layout looks like this: + - The cache directory contains one subfolder per repo_id (namespaced by repo type) + - inside each repo folder: + - refs is a list of the latest known revision => commit_hash pairs + - blobs contains the actual file blobs (identified by their git-sha or sha256, depending on + whether they're LFS files or not) + - snapshots contains one subfolder per commit, each "commit" contains the subset of the files + that have been resolved at that particular commit. Each filename is a symlink to the blob + at that particular commit. + + If `local_dir` is provided, the file structure from the repo will be replicated in this location. You can configure + how you want to move those files: + - If `local_dir_use_symlinks="auto"` (default), files are downloaded and stored in the cache directory as blob + files. Small files (<5MB) are duplicated in `local_dir` while a symlink is created for bigger files. The goal + is to be able to manually edit and save small files without corrupting the cache while saving disk space for + binary files. The 5MB threshold can be configured with the `HF_HUB_LOCAL_DIR_AUTO_SYMLINK_THRESHOLD` + environment variable. + - If `local_dir_use_symlinks=True`, files are downloaded, stored in the cache directory and symlinked in `local_dir`. + This is optimal in term of disk usage but files must not be manually edited. + - If `local_dir_use_symlinks=False` and the blob files exist in the cache directory, they are duplicated in the + local dir. This means disk usage is not optimized. + - Finally, if `local_dir_use_symlinks=False` and the blob files do not exist in the cache directory, then the + files are downloaded and directly placed under `local_dir`. This means if you need to download them again later, + they will be re-downloaded entirely. + + ``` + [ 96] . + └── [ 160] models--julien-c--EsperBERTo-small + ├── [ 160] blobs + │ ├── [321M] 403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd + │ ├── [ 398] 7cb18dc9bafbfcf74629a4b760af1b160957a83e + │ └── [1.4K] d7edf6bd2a681fb0175f7735299831ee1b22b812 + ├── [ 96] refs + │ └── [ 40] main + └── [ 128] snapshots + ├── [ 128] 2439f60ef33a0d46d85da5001d52aeda5b00ce9f + │ ├── [ 52] README.md -> ../../blobs/d7edf6bd2a681fb0175f7735299831ee1b22b812 + │ └── [ 76] pytorch_model.bin -> ../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd + └── [ 128] bbc77c8132af1cc5cf678da3f1ddf2de43606d48 + ├── [ 52] README.md -> ../../blobs/7cb18dc9bafbfcf74629a4b760af1b160957a83e + └── [ 76] pytorch_model.bin -> ../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd + ``` + + Args: + repo_id (`str`): + A user or an organization name and a repo name separated by a `/`. + filename (`str`): + The name of the file in the repo. + subfolder (`str`, *optional*): + An optional value corresponding to a folder inside the model repo. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if downloading from a dataset or space, + `None` or `"model"` if downloading from a model. Default is `None`. + revision (`str`, *optional*): + An optional Git revision id which can be a branch name, a tag, or a + commit hash. + cache_dir (`str`, `Path`, *optional*): + Path to the folder where cached files are stored. + local_dir (`str` or `Path`, *optional*): + If provided, the downloaded file will be placed under this directory, either as a symlink (default) or + a regular file (see description for more details). + local_dir_use_symlinks (`"auto"` or `bool`, defaults to `"auto"`): + To be used with `local_dir`. If set to "auto", the cache directory will be used and the file will be either + duplicated or symlinked to the local directory depending on its size. It set to `True`, a symlink will be + created, no matter the file size. If set to `False`, the file will either be duplicated from cache (if + already exists) or downloaded from the Hub and not cached. See description for more details. + force_download (`bool`, *optional*, defaults to `False`): + Whether the file should be downloaded even if it already exists in + the local cache. + proxies (`dict`, *optional*): + Dictionary mapping protocol to the URL of the proxy passed to + `requests.request`. + etag_timeout (`float`, *optional*, defaults to `10`): + When fetching ETag, how many seconds to wait for the server to send + data before giving up which is passed to `requests.request`. + resume_download (`bool`, *optional*, defaults to `False`): + If `True`, resume a previously interrupted download. + token (`bool` or `str`, *optional*): + A valid authentication token (see https://huggingface.co/settings/token). + If `None` or `True` and machine is logged in (through `huggingface-cli login` + or [`~huggingface_hub.login`]), token will be retrieved from the cache. + If `False`, token is not sent in the request header. + local_files_only (`bool`, *optional*, defaults to `False`): + If `True`, avoid downloading the file and return the path to the + local cached file if it exists. + legacy_cache_layout (`bool`, *optional*, defaults to `False`): + If `True`, uses the legacy file cache layout i.e. just call [`hf_hub_url`] + then `cached_download`. This is deprecated as the new cache layout is + more powerful. + + Returns: + Local path (string) of file or if networking is off, last version of + file cached on disk. + + + + Raises the following errors: + + - [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError) + if `token=True` and the token cannot be found. + - [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError) + if ETag cannot be determined. + - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + if some parameter value is invalid + - [`~utils.RepositoryNotFoundError`] + If the repository to download from cannot be found. This may be because it doesn't exist, + or because it is set to `private` and you do not have access. + - [`~utils.RevisionNotFoundError`] + If the revision to download from cannot be found. + - [`~utils.EntryNotFoundError`] + If the file to download cannot be found. + - [`~utils.LocalEntryNotFoundError`] + If network is disabled or unavailable and file is not found in cache. + + + """ + from .file_download import hf_hub_download + + if token is None: + # Cannot do `token = token or self.token` as token can be `False`. + token = self.token + + return hf_hub_download( + repo_id=repo_id, + filename=filename, + subfolder=subfolder, + repo_type=repo_type, + revision=revision, + endpoint=self.endpoint, + library_name=self.library_name, + library_version=self.library_version, + cache_dir=cache_dir, + local_dir=local_dir, + local_dir_use_symlinks=local_dir_use_symlinks, + user_agent=self.user_agent, + force_download=force_download, + force_filename=force_filename, + proxies=proxies, + etag_timeout=etag_timeout, + resume_download=resume_download, + token=token, + headers=self.headers, + local_files_only=local_files_only, + legacy_cache_layout=legacy_cache_layout, + ) + + @validate_hf_hub_args + def snapshot_download( + self, + repo_id: str, + *, + repo_type: Optional[str] = None, + revision: Optional[str] = None, + cache_dir: Union[str, Path, None] = None, + local_dir: Union[str, Path, None] = None, + local_dir_use_symlinks: Union[bool, Literal["auto"]] = "auto", + proxies: Optional[Dict] = None, + etag_timeout: float = DEFAULT_ETAG_TIMEOUT, + resume_download: bool = False, + force_download: bool = False, + token: Optional[Union[str, bool]] = None, + local_files_only: bool = False, + allow_patterns: Optional[Union[List[str], str]] = None, + ignore_patterns: Optional[Union[List[str], str]] = None, + max_workers: int = 8, + tqdm_class: Optional[base_tqdm] = None, + ) -> str: + """Download repo files. + + Download a whole snapshot of a repo's files at the specified revision. This is useful when you want all files from + a repo, because you don't know which ones you will need a priori. All files are nested inside a folder in order + to keep their actual filename relative to that folder. You can also filter which files to download using + `allow_patterns` and `ignore_patterns`. + + If `local_dir` is provided, the file structure from the repo will be replicated in this location. You can configure + how you want to move those files: + - If `local_dir_use_symlinks="auto"` (default), files are downloaded and stored in the cache directory as blob + files. Small files (<5MB) are duplicated in `local_dir` while a symlink is created for bigger files. The goal + is to be able to manually edit and save small files without corrupting the cache while saving disk space for + binary files. The 5MB threshold can be configured with the `HF_HUB_LOCAL_DIR_AUTO_SYMLINK_THRESHOLD` + environment variable. + - If `local_dir_use_symlinks=True`, files are downloaded, stored in the cache directory and symlinked in `local_dir`. + This is optimal in term of disk usage but files must not be manually edited. + - If `local_dir_use_symlinks=False` and the blob files exist in the cache directory, they are duplicated in the + local dir. This means disk usage is not optimized. + - Finally, if `local_dir_use_symlinks=False` and the blob files do not exist in the cache directory, then the + files are downloaded and directly placed under `local_dir`. This means if you need to download them again later, + they will be re-downloaded entirely. + + An alternative would be to clone the repo but this requires git and git-lfs to be installed and properly + configured. It is also not possible to filter which files to download when cloning a repository using git. + + Args: + repo_id (`str`): + A user or an organization name and a repo name separated by a `/`. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if downloading from a dataset or space, + `None` or `"model"` if downloading from a model. Default is `None`. + revision (`str`, *optional*): + An optional Git revision id which can be a branch name, a tag, or a + commit hash. + cache_dir (`str`, `Path`, *optional*): + Path to the folder where cached files are stored. + local_dir (`str` or `Path`, *optional*): + If provided, the downloaded files will be placed under this directory, either as symlinks (default) or + regular files (see description for more details). + local_dir_use_symlinks (`"auto"` or `bool`, defaults to `"auto"`): + To be used with `local_dir`. If set to "auto", the cache directory will be used and the file will be either + duplicated or symlinked to the local directory depending on its size. It set to `True`, a symlink will be + created, no matter the file size. If set to `False`, the file will either be duplicated from cache (if + already exists) or downloaded from the Hub and not cached. See description for more details. + proxies (`dict`, *optional*): + Dictionary mapping protocol to the URL of the proxy passed to + `requests.request`. + etag_timeout (`float`, *optional*, defaults to `10`): + When fetching ETag, how many seconds to wait for the server to send + data before giving up which is passed to `requests.request`. + resume_download (`bool`, *optional*, defaults to `False): + If `True`, resume a previously interrupted download. + force_download (`bool`, *optional*, defaults to `False`): + Whether the file should be downloaded even if it already exists in the local cache. + token (`bool` or `str`, *optional*): + A valid authentication token (see https://huggingface.co/settings/token). + If `None` or `True` and machine is logged in (through `huggingface-cli login` + or [`~huggingface_hub.login`]), token will be retrieved from the cache. + If `False`, token is not sent in the request header. + local_files_only (`bool`, *optional*, defaults to `False`): + If `True`, avoid downloading the file and return the path to the + local cached file if it exists. + allow_patterns (`List[str]` or `str`, *optional*): + If provided, only files matching at least one pattern are downloaded. + ignore_patterns (`List[str]` or `str`, *optional*): + If provided, files matching any of the patterns are not downloaded. + max_workers (`int`, *optional*): + Number of concurrent threads to download files (1 thread = 1 file download). + Defaults to 8. + tqdm_class (`tqdm`, *optional*): + If provided, overwrites the default behavior for the progress bar. Passed + argument must inherit from `tqdm.auto.tqdm` or at least mimic its behavior. + Note that the `tqdm_class` is not passed to each individual download. + Defaults to the custom HF progress bar that can be disabled by setting + `HF_HUB_DISABLE_PROGRESS_BARS` environment variable. + + Returns: + Local folder path (string) of repo snapshot + + + + Raises the following errors: + + - [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError) + if `token=True` and the token cannot be found. + - [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError) if + ETag cannot be determined. + - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + if some parameter value is invalid + + + """ + from ._snapshot_download import snapshot_download + + if token is None: + # Cannot do `token = token or self.token` as token can be `False`. + token = self.token + + return snapshot_download( + repo_id=repo_id, + repo_type=repo_type, + revision=revision, + endpoint=self.endpoint, + cache_dir=cache_dir, + local_dir=local_dir, + local_dir_use_symlinks=local_dir_use_symlinks, + library_name=self.library_name, + library_version=self.library_version, + user_agent=self.user_agent, + proxies=proxies, + etag_timeout=etag_timeout, + resume_download=resume_download, + force_download=force_download, + token=token, + local_files_only=local_files_only, + allow_patterns=allow_patterns, + ignore_patterns=ignore_patterns, + max_workers=max_workers, + tqdm_class=tqdm_class, + ) + + def get_safetensors_metadata( + self, + repo_id: str, + *, + repo_type: Optional[str] = None, + revision: Optional[str] = None, + token: Optional[str] = None, + ) -> SafetensorsRepoMetadata: + """ + Parse metadata for a safetensors repo on the Hub. + + We first check if the repo has a single safetensors file or a sharded safetensors repo. If it's a single + safetensors file, we parse the metadata from this file. If it's a sharded safetensors repo, we parse the + metadata from the index file and then parse the metadata from each shard. + + To parse metadata from a single safetensors file, use [`parse_safetensors_file_metadata`]. + + For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format. + + Args: + repo_id (`str`): + A user or an organization name and a repo name separated by a `/`. + filename (`str`): + The name of the file in the repo. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if the file is in a dataset or space, `None` or `"model"` if in a + model. Default is `None`. + revision (`str`, *optional*): + The git revision to fetch the file from. Can be a branch name, a tag, or a commit hash. Defaults to the + head of the `"main"` branch. + token (`bool` or `str`, *optional*): + A valid authentication token (see https://huggingface.co/settings/token). If `None` or `True` and + machine is logged in (through `huggingface-cli login` or [`~huggingface_hub.login`]), token will be + retrieved from the cache. If `False`, token is not sent in the request header. + + Returns: + [`SafetensorsRepoMetadata`]: information related to safetensors repo. + + Raises: + - [`NotASafetensorsRepoError`]: if the repo is not a safetensors repo i.e. doesn't have either a + `model.safetensors` or a `model.safetensors.index.json` file. + - [`SafetensorsParsingError`]: if a safetensors file header couldn't be parsed correctly. + + Example: + ```py + # Parse repo with single weights file + >>> metadata = get_safetensors_metadata("bigscience/bloomz-560m") + >>> metadata + SafetensorsRepoMetadata( + metadata=None, + sharded=False, + weight_map={'h.0.input_layernorm.bias': 'model.safetensors', ...}, + files_metadata={'model.safetensors': SafetensorsFileMetadata(...)} + ) + >>> metadata.files_metadata["model.safetensors"].metadata + {'format': 'pt'} + + # Parse repo with sharded model + >>> metadata = get_safetensors_metadata("bigscience/bloom") + Parse safetensors files: 100%|██████████████████████████████████████████| 72/72 [00:12<00:00, 5.78it/s] + >>> metadata + SafetensorsRepoMetadata(metadata={'total_size': 352494542848}, sharded=True, weight_map={...}, files_metadata={...}) + >>> len(metadata.files_metadata) + 72 # All safetensors files have been fetched + + # Parse repo with sharded model + >>> get_safetensors_metadata("runwayml/stable-diffusion-v1-5") + NotASafetensorsRepoError: 'runwayml/stable-diffusion-v1-5' is not a safetensors repo. Couldn't find 'model.safetensors.index.json' or 'model.safetensors' files. + ``` + """ + if self.file_exists( # Single safetensors file => non-sharded model + repo_id=repo_id, filename=SAFETENSORS_SINGLE_FILE, repo_type=repo_type, revision=revision, token=token + ): + file_metadata = self.parse_safetensors_file_metadata( + repo_id=repo_id, filename=SAFETENSORS_SINGLE_FILE, repo_type=repo_type, revision=revision, token=token + ) + return SafetensorsRepoMetadata( + metadata=None, + sharded=False, + weight_map={tensor_name: SAFETENSORS_SINGLE_FILE for tensor_name in file_metadata.tensors.keys()}, + files_metadata={SAFETENSORS_SINGLE_FILE: file_metadata}, + ) + elif self.file_exists( # Multiple safetensors files => sharded with index + repo_id=repo_id, filename=SAFETENSORS_INDEX_FILE, repo_type=repo_type, revision=revision, token=token + ): + # Fetch index + index_file = self.hf_hub_download( + repo_id=repo_id, filename=SAFETENSORS_INDEX_FILE, repo_type=repo_type, revision=revision, token=token + ) + with open(index_file) as f: + index = json.load(f) + + weight_map = index.get("weight_map", {}) + + # Fetch metadata per shard + files_metadata = {} + + def _parse(filename: str) -> None: + files_metadata[filename] = self.parse_safetensors_file_metadata( + repo_id=repo_id, filename=filename, repo_type=repo_type, revision=revision, token=token + ) + + thread_map( + _parse, + set(weight_map.values()), + desc="Parse safetensors files", + tqdm_class=hf_tqdm, + ) + + return SafetensorsRepoMetadata( + metadata=index.get("metadata", None), + sharded=True, + weight_map=weight_map, + files_metadata=files_metadata, + ) + else: + # Not a safetensors repo + raise NotASafetensorsRepoError( + f"'{repo_id}' is not a safetensors repo. Couldn't find '{SAFETENSORS_INDEX_FILE}' or '{SAFETENSORS_SINGLE_FILE}' files." + ) + + def parse_safetensors_file_metadata( + self, + repo_id: str, + filename: str, + *, + repo_type: Optional[str] = None, + revision: Optional[str] = None, + token: Optional[str] = None, + ) -> SafetensorsFileMetadata: + """ + Parse metadata from a safetensors file on the Hub. + + To parse metadata from all safetensors files in a repo at once, use [`get_safetensors_metadata`]. + + For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format. + + Args: + repo_id (`str`): + A user or an organization name and a repo name separated by a `/`. + filename (`str`): + The name of the file in the repo. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if the file is in a dataset or space, `None` or `"model"` if in a + model. Default is `None`. + revision (`str`, *optional*): + The git revision to fetch the file from. Can be a branch name, a tag, or a commit hash. Defaults to the + head of the `"main"` branch. + token (`bool` or `str`, *optional*): + A valid authentication token (see https://huggingface.co/settings/token). If `None` or `True` and + machine is logged in (through `huggingface-cli login` or [`~huggingface_hub.login`]), token will be + retrieved from the cache. If `False`, token is not sent in the request header. + + Returns: + [`SafetensorsFileMetadata`]: information related to a safetensors file. + + Raises: + - [`NotASafetensorsRepoError`]: if the repo is not a safetensors repo i.e. doesn't have either a + `model.safetensors` or a `model.safetensors.index.json` file. + - [`SafetensorsParsingError`]: if a safetensors file header couldn't be parsed correctly. + """ + url = hf_hub_url( + repo_id=repo_id, filename=filename, repo_type=repo_type, revision=revision, endpoint=self.endpoint + ) + _headers = self._build_hf_headers(token=token) + + # 1. Fetch first 100kb + # Empirically, 97% of safetensors files have a metadata size < 100kb (over the top 1000 models on the Hub). + # We assume fetching 100kb is faster than making 2 GET requests. Therefore we always fetch the first 100kb to + # avoid the 2nd GET in most cases. + # See https://github.com/huggingface/huggingface_hub/pull/1855#discussion_r1404286419. + response = get_session().get(url, headers={**_headers, "range": "bytes=0-100000"}) + hf_raise_for_status(response) + + # 2. Parse metadata size + metadata_size = struct.unpack(" SAFETENSORS_MAX_HEADER_LENGTH: + raise SafetensorsParsingError( + f"Failed to parse safetensors header for '{filename}' (repo '{repo_id}', revision " + f"'{revision or DEFAULT_REVISION}'): safetensors header is too big. Maximum supported size is " + f"{SAFETENSORS_MAX_HEADER_LENGTH} bytes (got {metadata_size})." + ) + + # 3.a. Get metadata from payload + if metadata_size <= 100000: + metadata_as_bytes = response.content[8 : 8 + metadata_size] + else: # 3.b. Request full metadata + response = get_session().get(url, headers={**_headers, "range": f"bytes=8-{metadata_size+7}"}) + hf_raise_for_status(response) + metadata_as_bytes = response.content + + # 4. Parse json header + try: + metadata_as_dict = json.loads(metadata_as_bytes.decode(errors="ignore")) + except json.JSONDecodeError as e: + raise SafetensorsParsingError( + f"Failed to parse safetensors header for '{filename}' (repo '{repo_id}', revision " + f"'{revision or DEFAULT_REVISION}'): header is not json-encoded string. Please make sure this is a " + "correctly formatted safetensors file." + ) from e + + try: + return SafetensorsFileMetadata( + metadata=metadata_as_dict.get("__metadata__", {}), + tensors={ + key: TensorInfo( + dtype=tensor["dtype"], + shape=tensor["shape"], + data_offsets=tuple(tensor["data_offsets"]), # type: ignore + ) + for key, tensor in metadata_as_dict.items() + if key != "__metadata__" + }, + ) + except (KeyError, IndexError) as e: + raise SafetensorsParsingError( + f"Failed to parse safetensors header for '{filename}' (repo '{repo_id}', revision " + f"'{revision or DEFAULT_REVISION}'): header format not recognized. Please make sure this is a correctly" + " formatted safetensors file." + ) from e + + @validate_hf_hub_args + def create_branch( + self, + repo_id: str, + *, + branch: str, + revision: Optional[str] = None, + token: Optional[str] = None, + repo_type: Optional[str] = None, + exist_ok: bool = False, + ) -> None: + """ + Create a new branch for a repo on the Hub, starting from the specified revision (defaults to `main`). + To find a revision suiting your needs, you can use [`list_repo_refs`] or [`list_repo_commits`]. + + Args: + repo_id (`str`): + The repository in which the branch will be created. + Example: `"user/my-cool-model"`. + + branch (`str`): + The name of the branch to create. + + revision (`str`, *optional*): + The git revision to create the branch from. It can be a branch name or + the OID/SHA of a commit, as a hexadecimal string. Defaults to the head + of the `"main"` branch. + + token (`str`, *optional*): + Authentication token. Will default to the stored token. + + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if creating a branch on a dataset or + space, `None` or `"model"` if tagging a model. Default is `None`. + + exist_ok (`bool`, *optional*, defaults to `False`): + If `True`, do not raise an error if branch already exists. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If repository is not found (error 404): wrong repo_id/repo_type, private + but not authenticated or repo does not exist. + [`~utils.BadRequestError`]: + If invalid reference for a branch. Ex: `refs/pr/5` or 'refs/foo/bar'. + [`~utils.HfHubHTTPError`]: + If the branch already exists on the repo (error 409) and `exist_ok` is + set to `False`. + """ + if repo_type is None: + repo_type = REPO_TYPE_MODEL + branch = quote(branch, safe="") + + # Prepare request + branch_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/branch/{branch}" + headers = self._build_hf_headers(token=token) + payload = {} + if revision is not None: + payload["startingPoint"] = revision + + # Create branch + response = get_session().post(url=branch_url, headers=headers, json=payload) + try: + hf_raise_for_status(response) + except HfHubHTTPError as e: + if not (e.response.status_code == 409 and exist_ok): + raise + + @validate_hf_hub_args + def delete_branch( + self, + repo_id: str, + *, + branch: str, + token: Optional[str] = None, + repo_type: Optional[str] = None, + ) -> None: + """ + Delete a branch from a repo on the Hub. + + Args: + repo_id (`str`): + The repository in which a branch will be deleted. + Example: `"user/my-cool-model"`. + + branch (`str`): + The name of the branch to delete. + + token (`str`, *optional*): + Authentication token. Will default to the stored token. + + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if creating a branch on a dataset or + space, `None` or `"model"` if tagging a model. Default is `None`. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If repository is not found (error 404): wrong repo_id/repo_type, private + but not authenticated or repo does not exist. + [`~utils.HfHubHTTPError`]: + If trying to delete a protected branch. Ex: `main` cannot be deleted. + [`~utils.HfHubHTTPError`]: + If trying to delete a branch that does not exist. + + """ + if repo_type is None: + repo_type = REPO_TYPE_MODEL + branch = quote(branch, safe="") + + # Prepare request + branch_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/branch/{branch}" + headers = self._build_hf_headers(token=token) + + # Delete branch + response = get_session().delete(url=branch_url, headers=headers) + hf_raise_for_status(response) + + @validate_hf_hub_args + def create_tag( + self, + repo_id: str, + *, + tag: str, + tag_message: Optional[str] = None, + revision: Optional[str] = None, + token: Optional[str] = None, + repo_type: Optional[str] = None, + exist_ok: bool = False, + ) -> None: + """ + Tag a given commit of a repo on the Hub. + + Args: + repo_id (`str`): + The repository in which a commit will be tagged. + Example: `"user/my-cool-model"`. + + tag (`str`): + The name of the tag to create. + + tag_message (`str`, *optional*): + The description of the tag to create. + + revision (`str`, *optional*): + The git revision to tag. It can be a branch name or the OID/SHA of a + commit, as a hexadecimal string. Shorthands (7 first characters) are + also supported. Defaults to the head of the `"main"` branch. + + token (`str`, *optional*): + Authentication token. Will default to the stored token. + + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if tagging a dataset or + space, `None` or `"model"` if tagging a model. Default is + `None`. + + exist_ok (`bool`, *optional*, defaults to `False`): + If `True`, do not raise an error if tag already exists. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If repository is not found (error 404): wrong repo_id/repo_type, private + but not authenticated or repo does not exist. + [`~utils.RevisionNotFoundError`]: + If revision is not found (error 404) on the repo. + [`~utils.HfHubHTTPError`]: + If the branch already exists on the repo (error 409) and `exist_ok` is + set to `False`. + """ + if repo_type is None: + repo_type = REPO_TYPE_MODEL + revision = quote(revision, safe="") if revision is not None else DEFAULT_REVISION + + # Prepare request + tag_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/tag/{revision}" + headers = self._build_hf_headers(token=token) + payload = {"tag": tag} + if tag_message is not None: + payload["message"] = tag_message + + # Tag + response = get_session().post(url=tag_url, headers=headers, json=payload) + try: + hf_raise_for_status(response) + except HfHubHTTPError as e: + if not (e.response.status_code == 409 and exist_ok): + raise + + @validate_hf_hub_args + def delete_tag( + self, + repo_id: str, + *, + tag: str, + token: Optional[str] = None, + repo_type: Optional[str] = None, + ) -> None: + """ + Delete a tag from a repo on the Hub. + + Args: + repo_id (`str`): + The repository in which a tag will be deleted. + Example: `"user/my-cool-model"`. + + tag (`str`): + The name of the tag to delete. + + token (`str`, *optional*): + Authentication token. Will default to the stored token. + + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if tagging a dataset or space, `None` or + `"model"` if tagging a model. Default is `None`. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If repository is not found (error 404): wrong repo_id/repo_type, private + but not authenticated or repo does not exist. + [`~utils.RevisionNotFoundError`]: + If tag is not found. + """ + if repo_type is None: + repo_type = REPO_TYPE_MODEL + tag = quote(tag, safe="") + + # Prepare request + tag_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/tag/{tag}" + headers = self._build_hf_headers(token=token) + + # Un-tag + response = get_session().delete(url=tag_url, headers=headers) + hf_raise_for_status(response) + + @validate_hf_hub_args + def get_full_repo_name( + self, + model_id: str, + *, + organization: Optional[str] = None, + token: Optional[Union[bool, str]] = None, + ): + """ + Returns the repository name for a given model ID and optional + organization. + + Args: + model_id (`str`): + The name of the model. + organization (`str`, *optional*): + If passed, the repository name will be in the organization + namespace instead of the user namespace. + token (`bool` or `str`, *optional*): + A valid authentication token (see https://huggingface.co/settings/token). + If `None` or `True` and machine is logged in (through `huggingface-cli login` + or [`~huggingface_hub.login`]), token will be retrieved from the cache. + If `False`, token is not sent in the request header. + + Returns: + `str`: The repository name in the user's namespace + ({username}/{model_id}) if no organization is passed, and under the + organization namespace ({organization}/{model_id}) otherwise. + """ + if organization is None: + if "/" in model_id: + username = model_id.split("/")[0] + else: + username = self.whoami(token=token)["name"] # type: ignore + return f"{username}/{model_id}" + else: + return f"{organization}/{model_id}" + + @validate_hf_hub_args + def get_repo_discussions( + self, + repo_id: str, + *, + author: Optional[str] = None, + discussion_type: Optional[DiscussionTypeFilter] = None, + discussion_status: Optional[DiscussionStatusFilter] = None, + repo_type: Optional[str] = None, + token: Optional[str] = None, + ) -> Iterator[Discussion]: + """ + Fetches Discussions and Pull Requests for the given repo. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + author (`str`, *optional*): + Pass a value to filter by discussion author. `None` means no filter. + Default is `None`. + discussion_type (`str`, *optional*): + Set to `"pull_request"` to fetch only pull requests, `"discussion"` + to fetch only discussions. Set to `"all"` or `None` to fetch both. + Default is `None`. + discussion_status (`str`, *optional*): + Set to `"open"` (respectively `"closed"`) to fetch only open + (respectively closed) discussions. Set to `"all"` or `None` + to fetch both. + Default is `None`. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if fetching from a dataset or + space, `None` or `"model"` if fetching from a model. Default is + `None`. + token (`str`, *optional*): + An authentication token (See https://huggingface.co/settings/token). + + Returns: + `Iterator[Discussion]`: An iterator of [`Discussion`] objects. + + Example: + Collecting all discussions of a repo in a list: + + ```python + >>> from huggingface_hub import get_repo_discussions + >>> discussions_list = list(get_repo_discussions(repo_id="bert-base-uncased")) + ``` + + Iterating over discussions of a repo: + + ```python + >>> from huggingface_hub import get_repo_discussions + >>> for discussion in get_repo_discussions(repo_id="bert-base-uncased"): + ... print(discussion.num, discussion.title) + ``` + """ + if repo_type not in REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {REPO_TYPES}") + if repo_type is None: + repo_type = REPO_TYPE_MODEL + if discussion_type is not None and discussion_type not in DISCUSSION_TYPES: + raise ValueError(f"Invalid discussion_type, must be one of {DISCUSSION_TYPES}") + if discussion_status is not None and discussion_status not in DISCUSSION_STATUS: + raise ValueError(f"Invalid discussion_status, must be one of {DISCUSSION_STATUS}") + + headers = self._build_hf_headers(token=token) + path = f"{self.endpoint}/api/{repo_type}s/{repo_id}/discussions" + + params: Dict[str, Union[str, int]] = {} + if discussion_type is not None: + params["type"] = discussion_type + if discussion_status is not None: + params["status"] = discussion_status + if author is not None: + params["author"] = author + + def _fetch_discussion_page(page_index: int): + params["p"] = page_index + resp = get_session().get(path, headers=headers, params=params) + hf_raise_for_status(resp) + paginated_discussions = resp.json() + total = paginated_discussions["count"] + start = paginated_discussions["start"] + discussions = paginated_discussions["discussions"] + has_next = (start + len(discussions)) < total + return discussions, has_next + + has_next, page_index = True, 0 + + while has_next: + discussions, has_next = _fetch_discussion_page(page_index=page_index) + for discussion in discussions: + yield Discussion( + title=discussion["title"], + num=discussion["num"], + author=discussion.get("author", {}).get("name", "deleted"), + created_at=parse_datetime(discussion["createdAt"]), + status=discussion["status"], + repo_id=discussion["repo"]["name"], + repo_type=discussion["repo"]["type"], + is_pull_request=discussion["isPullRequest"], + endpoint=self.endpoint, + ) + page_index = page_index + 1 + + @validate_hf_hub_args + def get_discussion_details( + self, + repo_id: str, + discussion_num: int, + *, + repo_type: Optional[str] = None, + token: Optional[str] = None, + ) -> DiscussionWithDetails: + """Fetches a Discussion's / Pull Request 's details from the Hub. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + discussion_num (`int`): + The number of the Discussion or Pull Request . Must be a strictly positive integer. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + token (`str`, *optional*): + An authentication token (See https://huggingface.co/settings/token) + + Returns: [`DiscussionWithDetails`] + + + + Raises the following errors: + + - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + if the HuggingFace API returned an error + - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + if some parameter value is invalid + - [`~utils.RepositoryNotFoundError`] + If the repository to download from cannot be found. This may be because it doesn't exist, + or because it is set to `private` and you do not have access. + + + """ + if not isinstance(discussion_num, int) or discussion_num <= 0: + raise ValueError("Invalid discussion_num, must be a positive integer") + if repo_type not in REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {REPO_TYPES}") + if repo_type is None: + repo_type = REPO_TYPE_MODEL + + path = f"{self.endpoint}/api/{repo_type}s/{repo_id}/discussions/{discussion_num}" + headers = self._build_hf_headers(token=token) + resp = get_session().get(path, params={"diff": "1"}, headers=headers) + hf_raise_for_status(resp) + + discussion_details = resp.json() + is_pull_request = discussion_details["isPullRequest"] + + target_branch = discussion_details["changes"]["base"] if is_pull_request else None + conflicting_files = discussion_details["filesWithConflicts"] if is_pull_request else None + merge_commit_oid = discussion_details["changes"].get("mergeCommitId", None) if is_pull_request else None + + return DiscussionWithDetails( + title=discussion_details["title"], + num=discussion_details["num"], + author=discussion_details.get("author", {}).get("name", "deleted"), + created_at=parse_datetime(discussion_details["createdAt"]), + status=discussion_details["status"], + repo_id=discussion_details["repo"]["name"], + repo_type=discussion_details["repo"]["type"], + is_pull_request=discussion_details["isPullRequest"], + events=[deserialize_event(evt) for evt in discussion_details["events"]], + conflicting_files=conflicting_files, + target_branch=target_branch, + merge_commit_oid=merge_commit_oid, + diff=discussion_details.get("diff"), + endpoint=self.endpoint, + ) + + @validate_hf_hub_args + def create_discussion( + self, + repo_id: str, + title: str, + *, + token: Optional[str] = None, + description: Optional[str] = None, + repo_type: Optional[str] = None, + pull_request: bool = False, + ) -> DiscussionWithDetails: + """Creates a Discussion or Pull Request. + + Pull Requests created programmatically will be in `"draft"` status. + + Creating a Pull Request with changes can also be done at once with [`HfApi.create_commit`]. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + title (`str`): + The title of the discussion. It can be up to 200 characters long, + and must be at least 3 characters long. Leading and trailing whitespaces + will be stripped. + token (`str`, *optional*): + An authentication token (See https://huggingface.co/settings/token) + description (`str`, *optional*): + An optional description for the Pull Request. + Defaults to `"Discussion opened with the huggingface_hub Python library"` + pull_request (`bool`, *optional*): + Whether to create a Pull Request or discussion. If `True`, creates a Pull Request. + If `False`, creates a discussion. Defaults to `False`. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + + Returns: [`DiscussionWithDetails`] + + + + Raises the following errors: + + - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + if the HuggingFace API returned an error + - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + if some parameter value is invalid + - [`~utils.RepositoryNotFoundError`] + If the repository to download from cannot be found. This may be because it doesn't exist, + or because it is set to `private` and you do not have access. + + """ + if repo_type not in REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {REPO_TYPES}") + if repo_type is None: + repo_type = REPO_TYPE_MODEL + + if description is not None: + description = description.strip() + description = ( + description + if description + else ( + f"{'Pull Request' if pull_request else 'Discussion'} opened with the" + " [huggingface_hub Python" + " library](https://huggingface.co/docs/huggingface_hub)" + ) + ) + + headers = self._build_hf_headers(token=token) + resp = get_session().post( + f"{self.endpoint}/api/{repo_type}s/{repo_id}/discussions", + json={ + "title": title.strip(), + "description": description, + "pullRequest": pull_request, + }, + headers=headers, + ) + hf_raise_for_status(resp) + num = resp.json()["num"] + return self.get_discussion_details( + repo_id=repo_id, + repo_type=repo_type, + discussion_num=num, + token=token, + ) + + @validate_hf_hub_args + def create_pull_request( + self, + repo_id: str, + title: str, + *, + token: Optional[str] = None, + description: Optional[str] = None, + repo_type: Optional[str] = None, + ) -> DiscussionWithDetails: + """Creates a Pull Request . Pull Requests created programmatically will be in `"draft"` status. + + Creating a Pull Request with changes can also be done at once with [`HfApi.create_commit`]; + + This is a wrapper around [`HfApi.create_discussion`]. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + title (`str`): + The title of the discussion. It can be up to 200 characters long, + and must be at least 3 characters long. Leading and trailing whitespaces + will be stripped. + token (`str`, *optional*): + An authentication token (See https://huggingface.co/settings/token) + description (`str`, *optional*): + An optional description for the Pull Request. + Defaults to `"Discussion opened with the huggingface_hub Python library"` + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + + Returns: [`DiscussionWithDetails`] + + + + Raises the following errors: + + - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + if the HuggingFace API returned an error + - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + if some parameter value is invalid + - [`~utils.RepositoryNotFoundError`] + If the repository to download from cannot be found. This may be because it doesn't exist, + or because it is set to `private` and you do not have access. + + """ + return self.create_discussion( + repo_id=repo_id, + title=title, + token=token, + description=description, + repo_type=repo_type, + pull_request=True, + ) + + def _post_discussion_changes( + self, + *, + repo_id: str, + discussion_num: int, + resource: str, + body: Optional[dict] = None, + token: Optional[str] = None, + repo_type: Optional[str] = None, + ) -> requests.Response: + """Internal utility to POST changes to a Discussion or Pull Request""" + if not isinstance(discussion_num, int) or discussion_num <= 0: + raise ValueError("Invalid discussion_num, must be a positive integer") + if repo_type not in REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {REPO_TYPES}") + if repo_type is None: + repo_type = REPO_TYPE_MODEL + repo_id = f"{repo_type}s/{repo_id}" + + path = f"{self.endpoint}/api/{repo_id}/discussions/{discussion_num}/{resource}" + + headers = self._build_hf_headers(token=token) + resp = requests.post(path, headers=headers, json=body) + hf_raise_for_status(resp) + return resp + + @validate_hf_hub_args + def comment_discussion( + self, + repo_id: str, + discussion_num: int, + comment: str, + *, + token: Optional[str] = None, + repo_type: Optional[str] = None, + ) -> DiscussionComment: + """Creates a new comment on the given Discussion. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + discussion_num (`int`): + The number of the Discussion or Pull Request . Must be a strictly positive integer. + comment (`str`): + The content of the comment to create. Comments support markdown formatting. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + token (`str`, *optional*): + An authentication token (See https://huggingface.co/settings/token) + + Returns: + [`DiscussionComment`]: the newly created comment + + + Examples: + ```python + + >>> comment = \"\"\" + ... Hello @otheruser! + ... + ... # This is a title + ... + ... **This is bold**, *this is italic* and ~this is strikethrough~ + ... And [this](http://url) is a link + ... \"\"\" + + >>> HfApi().comment_discussion( + ... repo_id="username/repo_name", + ... discussion_num=34 + ... comment=comment + ... ) + # DiscussionComment(id='deadbeef0000000', type='comment', ...) + + ``` + + + + Raises the following errors: + + - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + if the HuggingFace API returned an error + - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + if some parameter value is invalid + - [`~utils.RepositoryNotFoundError`] + If the repository to download from cannot be found. This may be because it doesn't exist, + or because it is set to `private` and you do not have access. + + + """ + resp = self._post_discussion_changes( + repo_id=repo_id, + repo_type=repo_type, + discussion_num=discussion_num, + token=token, + resource="comment", + body={"comment": comment}, + ) + return deserialize_event(resp.json()["newMessage"]) # type: ignore + + @validate_hf_hub_args + def rename_discussion( + self, + repo_id: str, + discussion_num: int, + new_title: str, + *, + token: Optional[str] = None, + repo_type: Optional[str] = None, + ) -> DiscussionTitleChange: + """Renames a Discussion. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + discussion_num (`int`): + The number of the Discussion or Pull Request . Must be a strictly positive integer. + new_title (`str`): + The new title for the discussion + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + token (`str`, *optional*): + An authentication token (See https://huggingface.co/settings/token) + + Returns: + [`DiscussionTitleChange`]: the title change event + + + Examples: + ```python + >>> new_title = "New title, fixing a typo" + >>> HfApi().rename_discussion( + ... repo_id="username/repo_name", + ... discussion_num=34 + ... new_title=new_title + ... ) + # DiscussionTitleChange(id='deadbeef0000000', type='title-change', ...) + + ``` + + + + Raises the following errors: + + - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + if the HuggingFace API returned an error + - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + if some parameter value is invalid + - [`~utils.RepositoryNotFoundError`] + If the repository to download from cannot be found. This may be because it doesn't exist, + or because it is set to `private` and you do not have access. + + + """ + resp = self._post_discussion_changes( + repo_id=repo_id, + repo_type=repo_type, + discussion_num=discussion_num, + token=token, + resource="title", + body={"title": new_title}, + ) + return deserialize_event(resp.json()["newTitle"]) # type: ignore + + @validate_hf_hub_args + def change_discussion_status( + self, + repo_id: str, + discussion_num: int, + new_status: Literal["open", "closed"], + *, + token: Optional[str] = None, + comment: Optional[str] = None, + repo_type: Optional[str] = None, + ) -> DiscussionStatusChange: + """Closes or re-opens a Discussion or Pull Request. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + discussion_num (`int`): + The number of the Discussion or Pull Request . Must be a strictly positive integer. + new_status (`str`): + The new status for the discussion, either `"open"` or `"closed"`. + comment (`str`, *optional*): + An optional comment to post with the status change. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + token (`str`, *optional*): + An authentication token (See https://huggingface.co/settings/token) + + Returns: + [`DiscussionStatusChange`]: the status change event + + + Examples: + ```python + >>> new_title = "New title, fixing a typo" + >>> HfApi().rename_discussion( + ... repo_id="username/repo_name", + ... discussion_num=34 + ... new_title=new_title + ... ) + # DiscussionStatusChange(id='deadbeef0000000', type='status-change', ...) + + ``` + + + + Raises the following errors: + + - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + if the HuggingFace API returned an error + - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + if some parameter value is invalid + - [`~utils.RepositoryNotFoundError`] + If the repository to download from cannot be found. This may be because it doesn't exist, + or because it is set to `private` and you do not have access. + + + """ + if new_status not in ["open", "closed"]: + raise ValueError("Invalid status, valid statuses are: 'open' and 'closed'") + body: Dict[str, str] = {"status": new_status} + if comment and comment.strip(): + body["comment"] = comment.strip() + resp = self._post_discussion_changes( + repo_id=repo_id, + repo_type=repo_type, + discussion_num=discussion_num, + token=token, + resource="status", + body=body, + ) + return deserialize_event(resp.json()["newStatus"]) # type: ignore + + @validate_hf_hub_args + def merge_pull_request( + self, + repo_id: str, + discussion_num: int, + *, + token: Optional[str] = None, + comment: Optional[str] = None, + repo_type: Optional[str] = None, + ): + """Merges a Pull Request. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + discussion_num (`int`): + The number of the Discussion or Pull Request . Must be a strictly positive integer. + comment (`str`, *optional*): + An optional comment to post with the status change. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + token (`str`, *optional*): + An authentication token (See https://huggingface.co/settings/token) + + Returns: + [`DiscussionStatusChange`]: the status change event + + + + Raises the following errors: + + - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + if the HuggingFace API returned an error + - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + if some parameter value is invalid + - [`~utils.RepositoryNotFoundError`] + If the repository to download from cannot be found. This may be because it doesn't exist, + or because it is set to `private` and you do not have access. + + + """ + self._post_discussion_changes( + repo_id=repo_id, + repo_type=repo_type, + discussion_num=discussion_num, + token=token, + resource="merge", + body={"comment": comment.strip()} if comment and comment.strip() else None, + ) + + @validate_hf_hub_args + def edit_discussion_comment( + self, + repo_id: str, + discussion_num: int, + comment_id: str, + new_content: str, + *, + token: Optional[str] = None, + repo_type: Optional[str] = None, + ) -> DiscussionComment: + """Edits a comment on a Discussion / Pull Request. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + discussion_num (`int`): + The number of the Discussion or Pull Request . Must be a strictly positive integer. + comment_id (`str`): + The ID of the comment to edit. + new_content (`str`): + The new content of the comment. Comments support markdown formatting. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + token (`str`, *optional*): + An authentication token (See https://huggingface.co/settings/token) + + Returns: + [`DiscussionComment`]: the edited comment + + + + Raises the following errors: + + - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + if the HuggingFace API returned an error + - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + if some parameter value is invalid + - [`~utils.RepositoryNotFoundError`] + If the repository to download from cannot be found. This may be because it doesn't exist, + or because it is set to `private` and you do not have access. + + + """ + resp = self._post_discussion_changes( + repo_id=repo_id, + repo_type=repo_type, + discussion_num=discussion_num, + token=token, + resource=f"comment/{comment_id.lower()}/edit", + body={"content": new_content}, + ) + return deserialize_event(resp.json()["updatedComment"]) # type: ignore + + @validate_hf_hub_args + def hide_discussion_comment( + self, + repo_id: str, + discussion_num: int, + comment_id: str, + *, + token: Optional[str] = None, + repo_type: Optional[str] = None, + ) -> DiscussionComment: + """Hides a comment on a Discussion / Pull Request. + + + Hidden comments' content cannot be retrieved anymore. Hiding a comment is irreversible. + + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + discussion_num (`int`): + The number of the Discussion or Pull Request . Must be a strictly positive integer. + comment_id (`str`): + The ID of the comment to edit. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + token (`str`, *optional*): + An authentication token (See https://huggingface.co/settings/token) + + Returns: + [`DiscussionComment`]: the hidden comment + + + + Raises the following errors: + + - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + if the HuggingFace API returned an error + - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + if some parameter value is invalid + - [`~utils.RepositoryNotFoundError`] + If the repository to download from cannot be found. This may be because it doesn't exist, + or because it is set to `private` and you do not have access. + + + """ + warnings.warn( + "Hidden comments' content cannot be retrieved anymore. Hiding a comment is irreversible.", + UserWarning, + ) + resp = self._post_discussion_changes( + repo_id=repo_id, + repo_type=repo_type, + discussion_num=discussion_num, + token=token, + resource=f"comment/{comment_id.lower()}/hide", + ) + return deserialize_event(resp.json()["updatedComment"]) # type: ignore + + @validate_hf_hub_args + def add_space_secret( + self, repo_id: str, key: str, value: str, *, description: Optional[str] = None, token: Optional[str] = None + ) -> None: + """Adds or updates a secret in a Space. + + Secrets allow to set secret keys or tokens to a Space without hardcoding them. + For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets. + + Args: + repo_id (`str`): + ID of the repo to update. Example: `"bigcode/in-the-stack"`. + key (`str`): + Secret key. Example: `"GITHUB_API_KEY"` + value (`str`): + Secret value. Example: `"your_github_api_key"`. + description (`str`, *optional*): + Secret description. Example: `"Github API key to access the Github API"`. + token (`str`, *optional*): + Hugging Face token. Will default to the locally saved token if not provided. + """ + payload = {"key": key, "value": value} + if description is not None: + payload["description"] = description + r = get_session().post( + f"{self.endpoint}/api/spaces/{repo_id}/secrets", + headers=self._build_hf_headers(token=token), + json=payload, + ) + hf_raise_for_status(r) + + @validate_hf_hub_args + def delete_space_secret(self, repo_id: str, key: str, *, token: Optional[str] = None) -> None: + """Deletes a secret from a Space. + + Secrets allow to set secret keys or tokens to a Space without hardcoding them. + For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets. + + Args: + repo_id (`str`): + ID of the repo to update. Example: `"bigcode/in-the-stack"`. + key (`str`): + Secret key. Example: `"GITHUB_API_KEY"`. + token (`str`, *optional*): + Hugging Face token. Will default to the locally saved token if not provided. + """ + r = get_session().delete( + f"{self.endpoint}/api/spaces/{repo_id}/secrets", + headers=self._build_hf_headers(token=token), + json={"key": key}, + ) + hf_raise_for_status(r) + + @validate_hf_hub_args + def get_space_variables(self, repo_id: str, *, token: Optional[str] = None) -> Dict[str, SpaceVariable]: + """Gets all variables from a Space. + + Variables allow to set environment variables to a Space without hardcoding them. + For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables + + Args: + repo_id (`str`): + ID of the repo to query. Example: `"bigcode/in-the-stack"`. + token (`str`, *optional*): + Hugging Face token. Will default to the locally saved token if not provided. + """ + r = get_session().get( + f"{self.endpoint}/api/spaces/{repo_id}/variables", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(r) + return {k: SpaceVariable(k, v) for k, v in r.json().items()} + + @validate_hf_hub_args + def add_space_variable( + self, repo_id: str, key: str, value: str, *, description: Optional[str] = None, token: Optional[str] = None + ) -> Dict[str, SpaceVariable]: + """Adds or updates a variable in a Space. + + Variables allow to set environment variables to a Space without hardcoding them. + For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables + + Args: + repo_id (`str`): + ID of the repo to update. Example: `"bigcode/in-the-stack"`. + key (`str`): + Variable key. Example: `"MODEL_REPO_ID"` + value (`str`): + Variable value. Example: `"the_model_repo_id"`. + description (`str`): + Description of the variable. Example: `"Model Repo ID of the implemented model"`. + token (`str`, *optional*): + Hugging Face token. Will default to the locally saved token if not provided. + """ + payload = {"key": key, "value": value} + if description is not None: + payload["description"] = description + r = get_session().post( + f"{self.endpoint}/api/spaces/{repo_id}/variables", + headers=self._build_hf_headers(token=token), + json=payload, + ) + hf_raise_for_status(r) + return {k: SpaceVariable(k, v) for k, v in r.json().items()} + + @validate_hf_hub_args + def delete_space_variable( + self, repo_id: str, key: str, *, token: Optional[str] = None + ) -> Dict[str, SpaceVariable]: + """Deletes a variable from a Space. + + Variables allow to set environment variables to a Space without hardcoding them. + For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables + + Args: + repo_id (`str`): + ID of the repo to update. Example: `"bigcode/in-the-stack"`. + key (`str`): + Variable key. Example: `"MODEL_REPO_ID"` + token (`str`, *optional*): + Hugging Face token. Will default to the locally saved token if not provided. + """ + r = get_session().delete( + f"{self.endpoint}/api/spaces/{repo_id}/variables", + headers=self._build_hf_headers(token=token), + json={"key": key}, + ) + hf_raise_for_status(r) + return {k: SpaceVariable(k, v) for k, v in r.json().items()} + + @validate_hf_hub_args + def get_space_runtime(self, repo_id: str, *, token: Optional[str] = None) -> SpaceRuntime: + """Gets runtime information about a Space. + + Args: + repo_id (`str`): + ID of the repo to update. Example: `"bigcode/in-the-stack"`. + token (`str`, *optional*): + Hugging Face token. Will default to the locally saved token if + not provided. + Returns: + [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware. + """ + r = get_session().get( + f"{self.endpoint}/api/spaces/{repo_id}/runtime", headers=self._build_hf_headers(token=token) + ) + hf_raise_for_status(r) + return SpaceRuntime(r.json()) + + @validate_hf_hub_args + def request_space_hardware( + self, + repo_id: str, + hardware: SpaceHardware, + *, + token: Optional[str] = None, + sleep_time: Optional[int] = None, + ) -> SpaceRuntime: + """Request new hardware for a Space. + + Args: + repo_id (`str`): + ID of the repo to update. Example: `"bigcode/in-the-stack"`. + hardware (`str` or [`SpaceHardware`]): + Hardware on which to run the Space. Example: `"t4-medium"`. + token (`str`, *optional*): + Hugging Face token. Will default to the locally saved token if not provided. + sleep_time (`int`, *optional*): + Number of seconds of inactivity to wait before a Space is put to sleep. Set to `-1` if you don't want + your Space to sleep (default behavior for upgraded hardware). For free hardware, you can't configure + the sleep time (value is fixed to 48 hours of inactivity). + See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details. + Returns: + [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware. + + + + It is also possible to request hardware directly when creating the Space repo! See [`create_repo`] for details. + + + """ + if sleep_time is not None and hardware == SpaceHardware.CPU_BASIC: + warnings.warn( + "If your Space runs on the default 'cpu-basic' hardware, it will go to sleep if inactive for more" + " than 48 hours. This value is not configurable. If you don't want your Space to deactivate or if" + " you want to set a custom sleep time, you need to upgrade to a paid Hardware.", + UserWarning, + ) + payload: Dict[str, Any] = {"flavor": hardware} + if sleep_time is not None: + payload["sleepTimeSeconds"] = sleep_time + r = get_session().post( + f"{self.endpoint}/api/spaces/{repo_id}/hardware", + headers=self._build_hf_headers(token=token), + json=payload, + ) + hf_raise_for_status(r) + return SpaceRuntime(r.json()) + + @validate_hf_hub_args + def set_space_sleep_time(self, repo_id: str, sleep_time: int, *, token: Optional[str] = None) -> SpaceRuntime: + """Set a custom sleep time for a Space running on upgraded hardware.. + + Your Space will go to sleep after X seconds of inactivity. You are not billed when your Space is in "sleep" + mode. If a new visitor lands on your Space, it will "wake it up". Only upgraded hardware can have a + configurable sleep time. To know more about the sleep stage, please refer to + https://huggingface.co/docs/hub/spaces-gpus#sleep-time. + + Args: + repo_id (`str`): + ID of the repo to update. Example: `"bigcode/in-the-stack"`. + sleep_time (`int`, *optional*): + Number of seconds of inactivity to wait before a Space is put to sleep. Set to `-1` if you don't want + your Space to pause (default behavior for upgraded hardware). For free hardware, you can't configure + the sleep time (value is fixed to 48 hours of inactivity). + See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details. + token (`str`, *optional*): + Hugging Face token. Will default to the locally saved token if not provided. + Returns: + [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware. + + + + It is also possible to set a custom sleep time when requesting hardware with [`request_space_hardware`]. + + + """ + r = get_session().post( + f"{self.endpoint}/api/spaces/{repo_id}/sleeptime", + headers=self._build_hf_headers(token=token), + json={"seconds": sleep_time}, + ) + hf_raise_for_status(r) + runtime = SpaceRuntime(r.json()) + + hardware = runtime.requested_hardware or runtime.hardware + if hardware == SpaceHardware.CPU_BASIC: + warnings.warn( + "If your Space runs on the default 'cpu-basic' hardware, it will go to sleep if inactive for more" + " than 48 hours. This value is not configurable. If you don't want your Space to deactivate or if" + " you want to set a custom sleep time, you need to upgrade to a paid Hardware.", + UserWarning, + ) + return runtime + + @validate_hf_hub_args + def pause_space(self, repo_id: str, *, token: Optional[str] = None) -> SpaceRuntime: + """Pause your Space. + + A paused Space stops executing until manually restarted by its owner. This is different from the sleeping + state in which free Spaces go after 48h of inactivity. Paused time is not billed to your account, no matter the + hardware you've selected. To restart your Space, use [`restart_space`] and go to your Space settings page. + + For more details, please visit [the docs](https://huggingface.co/docs/hub/spaces-gpus#pause). + + Args: + repo_id (`str`): + ID of the Space to pause. Example: `"Salesforce/BLIP2"`. + token (`str`, *optional*): + Hugging Face token. Will default to the locally saved token if not provided. + + Returns: + [`SpaceRuntime`]: Runtime information about your Space including `stage=PAUSED` and requested hardware. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If your Space is not found (error 404). Most probably wrong repo_id or your space is private but you + are not authenticated. + [`~utils.HfHubHTTPError`]: + 403 Forbidden: only the owner of a Space can pause it. If you want to manage a Space that you don't + own, either ask the owner by opening a Discussion or duplicate the Space. + [`~utils.BadRequestError`]: + If your Space is a static Space. Static Spaces are always running and never billed. If you want to hide + a static Space, you can set it to private. + """ + r = get_session().post( + f"{self.endpoint}/api/spaces/{repo_id}/pause", headers=self._build_hf_headers(token=token) + ) + hf_raise_for_status(r) + return SpaceRuntime(r.json()) + + @validate_hf_hub_args + def restart_space( + self, repo_id: str, *, token: Optional[str] = None, factory_reboot: bool = False + ) -> SpaceRuntime: + """Restart your Space. + + This is the only way to programmatically restart a Space if you've put it on Pause (see [`pause_space`]). You + must be the owner of the Space to restart it. If you are using an upgraded hardware, your account will be + billed as soon as the Space is restarted. You can trigger a restart no matter the current state of a Space. + + For more details, please visit [the docs](https://huggingface.co/docs/hub/spaces-gpus#pause). + + Args: + repo_id (`str`): + ID of the Space to restart. Example: `"Salesforce/BLIP2"`. + token (`str`, *optional*): + Hugging Face token. Will default to the locally saved token if not provided. + factory_reboot (`bool`, *optional*): + If `True`, the Space will be rebuilt from scratch without caching any requirements. + + Returns: + [`SpaceRuntime`]: Runtime information about your Space. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If your Space is not found (error 404). Most probably wrong repo_id or your space is private but you + are not authenticated. + [`~utils.HfHubHTTPError`]: + 403 Forbidden: only the owner of a Space can restart it. If you want to restart a Space that you don't + own, either ask the owner by opening a Discussion or duplicate the Space. + [`~utils.BadRequestError`]: + If your Space is a static Space. Static Spaces are always running and never billed. If you want to hide + a static Space, you can set it to private. + """ + params = {} + if factory_reboot: + params["factory"] = "true" + r = get_session().post( + f"{self.endpoint}/api/spaces/{repo_id}/restart", headers=self._build_hf_headers(token=token), params=params + ) + hf_raise_for_status(r) + return SpaceRuntime(r.json()) + + @validate_hf_hub_args + def duplicate_space( + self, + from_id: str, + to_id: Optional[str] = None, + *, + private: Optional[bool] = None, + token: Optional[str] = None, + exist_ok: bool = False, + hardware: Optional[SpaceHardware] = None, + storage: Optional[SpaceStorage] = None, + sleep_time: Optional[int] = None, + secrets: Optional[List[Dict[str, str]]] = None, + variables: Optional[List[Dict[str, str]]] = None, + ) -> RepoUrl: + """Duplicate a Space. + + Programmatically duplicate a Space. The new Space will be created in your account and will be in the same state + as the original Space (running or paused). You can duplicate a Space no matter the current state of a Space. + + Args: + from_id (`str`): + ID of the Space to duplicate. Example: `"pharma/CLIP-Interrogator"`. + to_id (`str`, *optional*): + ID of the new Space. Example: `"dog/CLIP-Interrogator"`. If not provided, the new Space will have the same + name as the original Space, but in your account. + private (`bool`, *optional*): + Whether the new Space should be private or not. Defaults to the same privacy as the original Space. + token (`str`, *optional*): + Hugging Face token. Will default to the locally saved token if not provided. + exist_ok (`bool`, *optional*, defaults to `False`): + If `True`, do not raise an error if repo already exists. + hardware (`SpaceHardware` or `str`, *optional*): + Choice of Hardware. Example: `"t4-medium"`. See [`SpaceHardware`] for a complete list. + storage (`SpaceStorage` or `str`, *optional*): + Choice of persistent storage tier. Example: `"small"`. See [`SpaceStorage`] for a complete list. + sleep_time (`int`, *optional*): + Number of seconds of inactivity to wait before a Space is put to sleep. Set to `-1` if you don't want + your Space to sleep (default behavior for upgraded hardware). For free hardware, you can't configure + the sleep time (value is fixed to 48 hours of inactivity). + See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details. + secrets (`List[Dict[str, str]]`, *optional*): + A list of secret keys to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional. + For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets. + variables (`List[Dict[str, str]]`, *optional*): + A list of public environment variables to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional. + For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables. + + Returns: + [`RepoUrl`]: URL to the newly created repo. Value is a subclass of `str` containing + attributes like `endpoint`, `repo_type` and `repo_id`. + + Raises: + - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + if the HuggingFace API returned an error + - [`~utils.RepositoryNotFoundError`] + If one of `from_id` or `to_id` cannot be found. This may be because it doesn't exist, + or because it is set to `private` and you do not have access. + + Example: + ```python + >>> from huggingface_hub import duplicate_space + + # Duplicate a Space to your account + >>> duplicate_space("multimodalart/dreambooth-training") + RepoUrl('https://huggingface.co/spaces/nateraw/dreambooth-training',...) + + # Can set custom destination id and visibility flag. + >>> duplicate_space("multimodalart/dreambooth-training", to_id="my-dreambooth", private=True) + RepoUrl('https://huggingface.co/spaces/nateraw/my-dreambooth',...) + ``` + """ + # Parse to_id if provided + parsed_to_id = RepoUrl(to_id) if to_id is not None else None + + # Infer target repo_id + to_namespace = ( # set namespace manually or default to username + parsed_to_id.namespace + if parsed_to_id is not None and parsed_to_id.namespace is not None + else self.whoami(token)["name"] + ) + to_repo_name = parsed_to_id.repo_name if to_id is not None else RepoUrl(from_id).repo_name # type: ignore + + # repository must be a valid repo_id (namespace/repo_name). + payload: Dict[str, Any] = {"repository": f"{to_namespace}/{to_repo_name}"} + + keys = ["private", "hardware", "storageTier", "sleepTimeSeconds", "secrets", "variables"] + values = [private, hardware, storage, sleep_time, secrets, variables] + payload.update({k: v for k, v in zip(keys, values) if v is not None}) + + if sleep_time is not None and hardware == SpaceHardware.CPU_BASIC: + warnings.warn( + "If your Space runs on the default 'cpu-basic' hardware, it will go to sleep if inactive for more" + " than 48 hours. This value is not configurable. If you don't want your Space to deactivate or if" + " you want to set a custom sleep time, you need to upgrade to a paid Hardware.", + UserWarning, + ) + + r = get_session().post( + f"{self.endpoint}/api/spaces/{from_id}/duplicate", + headers=self._build_hf_headers(token=token), + json=payload, + ) + + try: + hf_raise_for_status(r) + except HTTPError as err: + if exist_ok and err.response.status_code == 409: + # Repo already exists and `exist_ok=True` + pass + else: + raise + + return RepoUrl(r.json()["url"], endpoint=self.endpoint) + + @validate_hf_hub_args + def request_space_storage( + self, + repo_id: str, + storage: SpaceStorage, + *, + token: Optional[str] = None, + ) -> SpaceRuntime: + """Request persistent storage for a Space. + + Args: + repo_id (`str`): + ID of the Space to update. Example: `"HuggingFaceH4/open_llm_leaderboard"`. + storage (`str` or [`SpaceStorage`]): + Storage tier. Either 'small', 'medium', or 'large'. + token (`str`, *optional*): + Hugging Face token. Will default to the locally saved token if not provided. + Returns: + [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware. + + + + It is not possible to decrease persistent storage after its granted. To do so, you must delete it + via [`delete_space_storage`]. + + + """ + payload: Dict[str, SpaceStorage] = {"tier": storage} + r = get_session().post( + f"{self.endpoint}/api/spaces/{repo_id}/storage", + headers=self._build_hf_headers(token=token), + json=payload, + ) + hf_raise_for_status(r) + return SpaceRuntime(r.json()) + + @validate_hf_hub_args + def delete_space_storage( + self, + repo_id: str, + *, + token: Optional[str] = None, + ) -> SpaceRuntime: + """Delete persistent storage for a Space. + + Args: + repo_id (`str`): + ID of the Space to update. Example: `"HuggingFaceH4/open_llm_leaderboard"`. + token (`str`, *optional*): + Hugging Face token. Will default to the locally saved token if not provided. + Returns: + [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware. + Raises: + [`BadRequestError`] + If space has no persistent storage. + + """ + r = get_session().delete( + f"{self.endpoint}/api/spaces/{repo_id}/storage", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(r) + return SpaceRuntime(r.json()) + + ####################### + # Inference Endpoints # + ####################### + + def list_inference_endpoints( + self, namespace: Optional[str] = None, *, token: Optional[str] = None + ) -> List[InferenceEndpoint]: + """Lists all inference endpoints for the given namespace. + + Args: + namespace (`str`, *optional*): + The namespace to list endpoints for. Defaults to the current user. Set to `"*"` to list all endpoints + from all namespaces (i.e. personal namespace and all orgs the user belongs to). + token (`str`, *optional*): + An authentication token (See https://huggingface.co/settings/token). + + Returns: + List[`InferenceEndpoint`]: A list of all inference endpoints for the given namespace. + + Example: + ```python + >>> from huggingface_hub import HfApi + >>> api = HfApi() + >>> api.list_inference_endpoints() + [InferenceEndpoint(name='my-endpoint', ...), ...] + ``` + """ + # Special case: list all endpoints for all namespaces the user has access to + if namespace == "*": + user = self.whoami(token=token) + + # List personal endpoints first + endpoints: List[InferenceEndpoint] = list_inference_endpoints(namespace=self._get_namespace(token=token)) + + # Then list endpoints for all orgs the user belongs to and ignore 401 errors (no billing or no access) + for org in user.get("orgs", []): + try: + endpoints += list_inference_endpoints(namespace=org["name"], token=token) + except HfHubHTTPError as error: + if error.response.status_code == 401: # Either no billing or user don't have access) + logger.debug("Cannot list Inference Endpoints for org '%s': %s", org["name"], error) + pass + + return endpoints + + # Normal case: list endpoints for a specific namespace + namespace = namespace or self._get_namespace(token=token) + + response = get_session().get( + f"{INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + + return [ + InferenceEndpoint.from_raw(endpoint, namespace=namespace, token=token) + for endpoint in response.json()["items"] + ] + + def create_inference_endpoint( + self, + name: str, + *, + repository: str, + framework: str, + accelerator: str, + instance_size: str, + instance_type: str, + region: str, + vendor: str, + account_id: Optional[str] = None, + min_replica: int = 0, + max_replica: int = 1, + revision: Optional[str] = None, + task: Optional[str] = None, + custom_image: Optional[Dict] = None, + type: InferenceEndpointType = InferenceEndpointType.PROTECTED, + namespace: Optional[str] = None, + token: Optional[str] = None, + ) -> InferenceEndpoint: + """Create a new Inference Endpoint. + + Args: + name (`str`): + The unique name for the new Inference Endpoint. + repository (`str`): + The name of the model repository associated with the Inference Endpoint (e.g. `"gpt2"`). + framework (`str`): + The machine learning framework used for the model (e.g. `"custom"`). + accelerator (`str`): + The hardware accelerator to be used for inference (e.g. `"cpu"`). + instance_size (`str`): + The size or type of the instance to be used for hosting the model (e.g. `"large"`). + instance_type (`str`): + The cloud instance type where the Inference Endpoint will be deployed (e.g. `"c6i"`). + region (`str`): + The cloud region in which the Inference Endpoint will be created (e.g. `"us-east-1"`). + vendor (`str`): + The cloud provider or vendor where the Inference Endpoint will be hosted (e.g. `"aws"`). + account_id (`str`, *optional*): + The account ID used to link a VPC to a private Inference Endpoint (if applicable). + min_replica (`int`, *optional*): + The minimum number of replicas (instances) to keep running for the Inference Endpoint. Defaults to 0. + max_replica (`int`, *optional*): + The maximum number of replicas (instances) to scale to for the Inference Endpoint. Defaults to 1. + revision (`str`, *optional*): + The specific model revision to deploy on the Inference Endpoint (e.g. `"6c0e6080953db56375760c0471a8c5f2929baf11"`). + task (`str`, *optional*): + The task on which to deploy the model (e.g. `"text-classification"`). + custom_image (`Dict`, *optional*): + A custom Docker image to use for the Inference Endpoint. This is useful if you want to deploy an + Inference Endpoint running on the `text-generation-inference` (TGI) framework (see examples). + type ([`InferenceEndpointType]`, *optional*): + The type of the Inference Endpoint, which can be `"protected"` (default), `"public"` or `"private"`. + namespace (`str`, *optional*): + The namespace where the Inference Endpoint will be created. Defaults to the current user's namespace. + token (`str`, *optional*): + An authentication token (See https://huggingface.co/settings/token). + + Returns: + [`InferenceEndpoint`]: information about the updated Inference Endpoint. + + Example: + ```python + >>> from huggingface_hub import HfApi + >>> api = HfApi() + >>> create_inference_endpoint( + ... "my-endpoint-name", + ... repository="gpt2", + ... framework="pytorch", + ... task="text-generation", + ... accelerator="cpu", + ... vendor="aws", + ... region="us-east-1", + ... type="protected", + ... instance_size="medium", + ... instance_type="c6i", + ... ) + >>> endpoint + InferenceEndpoint(name='my-endpoint-name', status="pending",...) + + # Run inference on the endpoint + >>> endpoint.client.text_generation(...) + "..." + ``` + + ```python + # Start an Inference Endpoint running Zephyr-7b-beta on TGI + >>> from huggingface_hub import HfApi + >>> api = HfApi() + >>> create_inference_endpoint( + ... "aws-zephyr-7b-beta-0486", + ... repository="HuggingFaceH4/zephyr-7b-beta", + ... framework="pytorch", + ... task="text-generation", + ... accelerator="gpu", + ... vendor="aws", + ... region="us-east-1", + ... type="protected", + ... instance_size="medium", + ... instance_type="g5.2xlarge", + ... custom_image={ + ... "health_route": "/health", + ... "env": { + ... "MAX_BATCH_PREFILL_TOKENS": "2048", + ... "MAX_INPUT_LENGTH": "1024", + ... "MAX_TOTAL_TOKENS": "1512", + ... "MODEL_ID": "/repository" + ... }, + ... "url": "ghcr.io/huggingface/text-generation-inference:1.1.0", + ... }, + ... ) + + ``` + """ + namespace = namespace or self._get_namespace(token=token) + + image = {"custom": custom_image} if custom_image is not None else {"huggingface": {}} + payload: Dict = { + "accountId": account_id, + "compute": { + "accelerator": accelerator, + "instanceSize": instance_size, + "instanceType": instance_type, + "scaling": { + "maxReplica": max_replica, + "minReplica": min_replica, + }, + }, + "model": { + "framework": framework, + "repository": repository, + "revision": revision, + "task": task, + "image": image, + }, + "name": name, + "provider": { + "region": region, + "vendor": vendor, + }, + "type": type, + } + + response = get_session().post( + f"{INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}", + headers=self._build_hf_headers(token=token), + json=payload, + ) + hf_raise_for_status(response) + + return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token) + + def get_inference_endpoint( + self, name: str, *, namespace: Optional[str] = None, token: Optional[str] = None + ) -> InferenceEndpoint: + """Get information about an Inference Endpoint. + + Args: + name (`str`): + The name of the Inference Endpoint to retrieve information about. + namespace (`str`, *optional*): + The namespace in which the Inference Endpoint is located. Defaults to the current user. + token (`str`, *optional*): + An authentication token (See https://huggingface.co/settings/token). + + Returns: + [`InferenceEndpoint`]: information about the requested Inference Endpoint. + + Example: + ```python + >>> from huggingface_hub import HfApi + >>> api = HfApi() + >>> endpoint = api.get_inference_endpoint("my-text-to-image") + >>> endpoint + InferenceEndpoint(name='my-text-to-image', ...) + + # Get status + >>> endpoint.status + 'running' + >>> endpoint.url + 'https://my-text-to-image.region.vendor.endpoints.huggingface.cloud' + + # Run inference + >>> endpoint.client.text_to_image(...) + ``` + """ + namespace = namespace or self._get_namespace(token=token) + + response = get_session().get( + f"{INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + + return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token) + + def update_inference_endpoint( + self, + name: str, + *, + # Compute update + accelerator: Optional[str] = None, + instance_size: Optional[str] = None, + instance_type: Optional[str] = None, + min_replica: Optional[int] = None, + max_replica: Optional[int] = None, + # Model update + repository: Optional[str] = None, + framework: Optional[str] = None, + revision: Optional[str] = None, + task: Optional[str] = None, + # Other + namespace: Optional[str] = None, + token: Optional[str] = None, + ) -> InferenceEndpoint: + """Update an Inference Endpoint. + + This method allows the update of either the compute configuration, the deployed model, or both. All arguments are + optional but at least one must be provided. + + For convenience, you can also update an Inference Endpoint using [`InferenceEndpoint.update`]. + + Args: + name (`str`): + The name of the Inference Endpoint to update. + + accelerator (`str`, *optional*): + The hardware accelerator to be used for inference (e.g. `"cpu"`). + instance_size (`str`, *optional*): + The size or type of the instance to be used for hosting the model (e.g. `"large"`). + instance_type (`str`, *optional*): + The cloud instance type where the Inference Endpoint will be deployed (e.g. `"c6i"`). + min_replica (`int`, *optional*): + The minimum number of replicas (instances) to keep running for the Inference Endpoint. + max_replica (`int`, *optional*): + The maximum number of replicas (instances) to scale to for the Inference Endpoint. + + repository (`str`, *optional*): + The name of the model repository associated with the Inference Endpoint (e.g. `"gpt2"`). + framework (`str`, *optional*): + The machine learning framework used for the model (e.g. `"custom"`). + revision (`str`, *optional*): + The specific model revision to deploy on the Inference Endpoint (e.g. `"6c0e6080953db56375760c0471a8c5f2929baf11"`). + task (`str`, *optional*): + The task on which to deploy the model (e.g. `"text-classification"`). + + namespace (`str`, *optional*): + The namespace where the Inference Endpoint will be updated. Defaults to the current user's namespace. + token (`str`, *optional*): + An authentication token (See https://huggingface.co/settings/token). + + Returns: + [`InferenceEndpoint`]: information about the updated Inference Endpoint. + """ + namespace = namespace or self._get_namespace(token=token) + + payload: Dict = {} + if any(value is not None for value in (accelerator, instance_size, instance_type, min_replica, max_replica)): + payload["compute"] = { + "accelerator": accelerator, + "instanceSize": instance_size, + "instanceType": instance_type, + "scaling": { + "maxReplica": max_replica, + "minReplica": min_replica, + }, + } + if any(value is not None for value in (repository, framework, revision, task)): + payload["model"] = { + "framework": framework, + "repository": repository, + "revision": revision, + "task": task, + "image": {"huggingface": {}}, + } + + response = get_session().put( + f"{INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}", + headers=self._build_hf_headers(token=token), + json=payload, + ) + hf_raise_for_status(response) + + return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token) + + def delete_inference_endpoint( + self, name: str, *, namespace: Optional[str] = None, token: Optional[str] = None + ) -> None: + """Delete an Inference Endpoint. + + This operation is not reversible. If you don't want to be charged for an Inference Endpoint, it is preferable + to pause it with [`pause_inference_endpoint`] or scale it to zero with [`scale_to_zero_inference_endpoint`]. + + For convenience, you can also delete an Inference Endpoint using [`InferenceEndpoint.delete`]. + + Args: + name (`str`): + The name of the Inference Endpoint to delete. + namespace (`str`, *optional*): + The namespace in which the Inference Endpoint is located. Defaults to the current user. + token (`str`, *optional*): + An authentication token (See https://huggingface.co/settings/token). + """ + namespace = namespace or self._get_namespace(token=token) + response = get_session().delete( + f"{INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + + def pause_inference_endpoint( + self, name: str, *, namespace: Optional[str] = None, token: Optional[str] = None + ) -> InferenceEndpoint: + """Pause an Inference Endpoint. + + A paused Inference Endpoint will not be charged. It can be resumed at any time using [`resume_inference_endpoint`]. + This is different than scaling the Inference Endpoint to zero with [`scale_to_zero_inference_endpoint`], which + would be automatically restarted when a request is made to it. + + For convenience, you can also pause an Inference Endpoint using [`pause_inference_endpoint`]. + + Args: + name (`str`): + The name of the Inference Endpoint to pause. + namespace (`str`, *optional*): + The namespace in which the Inference Endpoint is located. Defaults to the current user. + token (`str`, *optional*): + An authentication token (See https://huggingface.co/settings/token). + + Returns: + [`InferenceEndpoint`]: information about the paused Inference Endpoint. + """ + namespace = namespace or self._get_namespace(token=token) + + response = get_session().post( + f"{INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}/pause", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + + return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token) + + def resume_inference_endpoint( + self, name: str, *, namespace: Optional[str] = None, token: Optional[str] = None + ) -> InferenceEndpoint: + """Resume an Inference Endpoint. + + For convenience, you can also resume an Inference Endpoint using [`InferenceEndpoint.resume`]. + + Args: + name (`str`): + The name of the Inference Endpoint to resume. + namespace (`str`, *optional*): + The namespace in which the Inference Endpoint is located. Defaults to the current user. + token (`str`, *optional*): + An authentication token (See https://huggingface.co/settings/token). + + Returns: + [`InferenceEndpoint`]: information about the resumed Inference Endpoint. + """ + namespace = namespace or self._get_namespace(token=token) + + response = get_session().post( + f"{INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}/resume", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + + return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token) + + def scale_to_zero_inference_endpoint( + self, name: str, *, namespace: Optional[str] = None, token: Optional[str] = None + ) -> InferenceEndpoint: + """Scale Inference Endpoint to zero. + + An Inference Endpoint scaled to zero will not be charged. It will be resume on the next request to it, with a + cold start delay. This is different than pausing the Inference Endpoint with [`pause_inference_endpoint`], which + would require a manual resume with [`resume_inference_endpoint`]. + + For convenience, you can also scale an Inference Endpoint to zero using [`InferenceEndpoint.scale_to_zero`]. + + Args: + name (`str`): + The name of the Inference Endpoint to scale to zero. + namespace (`str`, *optional*): + The namespace in which the Inference Endpoint is located. Defaults to the current user. + token (`str`, *optional*): + An authentication token (See https://huggingface.co/settings/token). + + Returns: + [`InferenceEndpoint`]: information about the scaled-to-zero Inference Endpoint. + """ + namespace = namespace or self._get_namespace(token=token) + + response = get_session().post( + f"{INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}/scale-to-zero", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + + return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token) + + def _get_namespace(self, token: Optional[str] = None) -> str: + """Get the default namespace for the current user.""" + me = self.whoami(token=token) + if me["type"] == "user": + return me["name"] + else: + raise ValueError( + "Cannot determine default namespace. You must provide a 'namespace' as input or be logged in as a" + " user." + ) + + ######################## + # Collection Endpoints # + ######################## + @validate_hf_hub_args + def list_collections( + self, + *, + owner: Union[List[str], str, None] = None, + item: Union[List[str], str, None] = None, + sort: Optional[Literal["lastModified", "trending", "upvotes"]] = None, + limit: Optional[int] = None, + token: Optional[Union[bool, str]] = None, + ) -> Iterable[Collection]: + """List collections on the Huggingface Hub, given some filters. + + + + When listing collections, the item list per collection is truncated to 4 items maximum. To retrieve all items + from a collection, you must use [`get_collection`]. + + + + Args: + owner (`List[str]` or `str`, *optional*): + Filter by owner's username. + item (`List[str]` or `str`, *optional*): + Filter collections containing a particular items. Example: `"models/teknium/OpenHermes-2.5-Mistral-7B"`, `"datasets/squad"` or `"papers/2311.12983"`. + sort (`Literal["lastModified", "trending", "upvotes"]`, *optional*): + Sort collections by last modified, trending or upvotes. + limit (`int`, *optional*): + Maximum number of collections to be returned. + token (`bool` or `str`, *optional*): + An authentication token (see https://huggingface.co/settings/token). + + Returns: + `Iterable[Collection]`: an iterable of [`Collection`] objects. + """ + # Construct the API endpoint + path = f"{self.endpoint}/api/collections" + headers = self._build_hf_headers(token=token) + params: Dict = {} + if owner is not None: + params.update({"owner": owner}) + if item is not None: + params.update({"item": item}) + if sort is not None: + params.update({"sort": sort}) + if limit is not None: + params.update({"limit": limit}) + + # Paginate over the results until limit is reached + items = paginate(path, headers=headers, params=params) + if limit is not None: + items = islice(items, limit) # Do not iterate over all pages + + # Parse as Collection and return + for position, collection_data in enumerate(items): + yield Collection(position=position, **collection_data) + + def get_collection(self, collection_slug: str, *, token: Optional[str] = None) -> Collection: + """Gets information about a Collection on the Hub. + + Args: + collection_slug (`str`): + Slug of the collection of the Hub. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`. + token (`str`, *optional*): + Hugging Face token. Will default to the locally saved token if not provided. + + Returns: [`Collection`] + + Example: + + ```py + >>> from huggingface_hub import get_collection + >>> collection = get_collection("TheBloke/recent-models-64f9a55bb3115b4f513ec026") + >>> collection.title + 'Recent models' + >>> len(collection.items) + 37 + >>> collection.items[0] + CollectionItem( + item_object_id='651446103cd773a050bf64c2', + item_id='TheBloke/U-Amethyst-20B-AWQ', + item_type='model', + position=88, + note=None + ) + ``` + """ + r = get_session().get( + f"{self.endpoint}/api/collections/{collection_slug}", headers=self._build_hf_headers(token=token) + ) + hf_raise_for_status(r) + return Collection(**{**r.json(), "endpoint": self.endpoint}) + + def create_collection( + self, + title: str, + *, + namespace: Optional[str] = None, + description: Optional[str] = None, + private: bool = False, + exists_ok: bool = False, + token: Optional[str] = None, + ) -> Collection: + """Create a new Collection on the Hub. + + Args: + title (`str`): + Title of the collection to create. Example: `"Recent models"`. + namespace (`str`, *optional*): + Namespace of the collection to create (username or org). Will default to the owner name. + description (`str`, *optional*): + Description of the collection to create. + private (`bool`, *optional*): + Whether the collection should be private or not. Defaults to `False` (i.e. public collection). + exists_ok (`bool`, *optional*): + If `True`, do not raise an error if collection already exists. + token (`str`, *optional*): + Hugging Face token. Will default to the locally saved token if not provided. + + Returns: [`Collection`] + + Example: + + ```py + >>> from huggingface_hub import create_collection + >>> collection = create_collection( + ... title="ICCV 2023", + ... description="Portfolio of models, papers and demos I presented at ICCV 2023", + ... ) + >>> collection.slug + "username/iccv-2023-64f9a55bb3115b4f513ec026" + ``` + """ + if namespace is None: + namespace = self.whoami(token)["name"] + + payload = { + "title": title, + "namespace": namespace, + "private": private, + } + if description is not None: + payload["description"] = description + + r = get_session().post( + f"{self.endpoint}/api/collections", headers=self._build_hf_headers(token=token), json=payload + ) + try: + hf_raise_for_status(r) + except HTTPError as err: + if exists_ok and err.response.status_code == 409: + # Collection already exists and `exists_ok=True` + slug = r.json()["slug"] + return self.get_collection(slug, token=token) + else: + raise + return Collection(**{**r.json(), "endpoint": self.endpoint}) + + def update_collection_metadata( + self, + collection_slug: str, + *, + title: Optional[str] = None, + description: Optional[str] = None, + position: Optional[int] = None, + private: Optional[bool] = None, + theme: Optional[str] = None, + token: Optional[str] = None, + ) -> Collection: + """Update metadata of a collection on the Hub. + + All arguments are optional. Only provided metadata will be updated. + + Args: + collection_slug (`str`): + Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`. + title (`str`): + Title of the collection to update. + description (`str`, *optional*): + Description of the collection to update. + position (`int`, *optional*): + New position of the collection in the list of collections of the user. + private (`bool`, *optional*): + Whether the collection should be private or not. + theme (`str`, *optional*): + Theme of the collection on the Hub. + token (`str`, *optional*): + Hugging Face token. Will default to the locally saved token if not provided. + + Returns: [`Collection`] + + Example: + + ```py + >>> from huggingface_hub import update_collection_metadata + >>> collection = update_collection_metadata( + ... collection_slug="username/iccv-2023-64f9a55bb3115b4f513ec026", + ... title="ICCV Oct. 2023" + ... description="Portfolio of models, datasets, papers and demos I presented at ICCV Oct. 2023", + ... private=False, + ... theme="pink", + ... ) + >>> collection.slug + "username/iccv-oct-2023-64f9a55bb3115b4f513ec026" + # ^collection slug got updated but not the trailing ID + ``` + """ + payload = { + "position": position, + "private": private, + "theme": theme, + "title": title, + "description": description, + } + r = get_session().patch( + f"{self.endpoint}/api/collections/{collection_slug}", + headers=self._build_hf_headers(token=token), + # Only send not-none values to the API + json={key: value for key, value in payload.items() if value is not None}, + ) + hf_raise_for_status(r) + return Collection(**{**r.json()["data"], "endpoint": self.endpoint}) + + def delete_collection( + self, collection_slug: str, *, missing_ok: bool = False, token: Optional[str] = None + ) -> None: + """Delete a collection on the Hub. + + Args: + collection_slug (`str`): + Slug of the collection to delete. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`. + missing_ok (`bool`, *optional*): + If `True`, do not raise an error if collection doesn't exists. + token (`str`, *optional*): + Hugging Face token. Will default to the locally saved token if not provided. + + Example: + + ```py + >>> from huggingface_hub import delete_collection + >>> collection = delete_collection("username/useless-collection-64f9a55bb3115b4f513ec026", missing_ok=True) + ``` + + + + This is a non-revertible action. A deleted collection cannot be restored. + + + """ + r = get_session().delete( + f"{self.endpoint}/api/collections/{collection_slug}", headers=self._build_hf_headers(token=token) + ) + try: + hf_raise_for_status(r) + except HTTPError as err: + if missing_ok and err.response.status_code == 404: + # Collection doesn't exists and `missing_ok=True` + return + else: + raise + + def add_collection_item( + self, + collection_slug: str, + item_id: str, + item_type: CollectionItemType_T, + *, + note: Optional[str] = None, + exists_ok: bool = False, + token: Optional[str] = None, + ) -> Collection: + """Add an item to a collection on the Hub. + + Args: + collection_slug (`str`): + Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`. + item_id (`str`): + ID of the item to add to the collection. It can be the ID of a repo on the Hub (e.g. `"facebook/bart-large-mnli"`) + or a paper id (e.g. `"2307.09288"`). + item_type (`str`): + Type of the item to add. Can be one of `"model"`, `"dataset"`, `"space"` or `"paper"`. + note (`str`, *optional*): + A note to attach to the item in the collection. The maximum size for a note is 500 characters. + exists_ok (`bool`, *optional*): + If `True`, do not raise an error if item already exists. + token (`str`, *optional*): + Hugging Face token. Will default to the locally saved token if not provided. + + Returns: [`Collection`] + + Raises: + `HTTPError`: + HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write` + or `admin` role in the organization the repo belongs to or if you passed a `read` token. + `HTTPError`: + HTTP 404 if the item you try to add to the collection does not exist on the Hub. + `HTTPError`: + HTTP 409 if the item you try to add to the collection is already in the collection (and exists_ok=False) + + Example: + + ```py + >>> from huggingface_hub import add_collection_item + >>> collection = add_collection_item( + ... collection_slug="davanstrien/climate-64f99dc2a5067f6b65531bab", + ... item_id="pierre-loic/climate-news-articles", + ... item_type="dataset" + ... ) + >>> collection.items[-1].item_id + "pierre-loic/climate-news-articles" + # ^item got added to the collection on last position + + # Add item with a note + >>> add_collection_item( + ... collection_slug="davanstrien/climate-64f99dc2a5067f6b65531bab", + ... item_id="datasets/climate_fever", + ... item_type="dataset" + ... note="This dataset adopts the FEVER methodology that consists of 1,535 real-world claims regarding climate-change collected on the internet." + ... ) + (...) + ``` + """ + payload: Dict[str, Any] = {"item": {"id": item_id, "type": item_type}} + if note is not None: + payload["note"] = note + r = get_session().post( + f"{self.endpoint}/api/collections/{collection_slug}/items", + headers=self._build_hf_headers(token=token), + json=payload, + ) + try: + hf_raise_for_status(r) + except HTTPError as err: + if exists_ok and err.response.status_code == 409: + # Item already exists and `exists_ok=True` + return self.get_collection(collection_slug, token=token) + else: + raise + return Collection(**{**r.json(), "endpoint": self.endpoint}) + + def update_collection_item( + self, + collection_slug: str, + item_object_id: str, + *, + note: Optional[str] = None, + position: Optional[int] = None, + token: Optional[str] = None, + ) -> None: + """Update an item in a collection. + + Args: + collection_slug (`str`): + Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`. + item_object_id (`str`): + ID of the item in the collection. This is not the id of the item on the Hub (repo_id or paper id). + It must be retrieved from a [`CollectionItem`] object. Example: `collection.items[0].item_object_id`. + note (`str`, *optional*): + A note to attach to the item in the collection. The maximum size for a note is 500 characters. + position (`int`, *optional*): + New position of the item in the collection. + token (`str`, *optional*): + Hugging Face token. Will default to the locally saved token if not provided. + + Example: + + ```py + >>> from huggingface_hub import get_collection, update_collection_item + + # Get collection first + >>> collection = get_collection("TheBloke/recent-models-64f9a55bb3115b4f513ec026") + + # Update item based on its ID (add note + update position) + >>> update_collection_item( + ... collection_slug="TheBloke/recent-models-64f9a55bb3115b4f513ec026", + ... item_object_id=collection.items[-1].item_object_id, + ... note="Newly updated model!" + ... position=0, + ... ) + ``` + """ + payload = {"position": position, "note": note} + r = get_session().patch( + f"{self.endpoint}/api/collections/{collection_slug}/items/{item_object_id}", + headers=self._build_hf_headers(token=token), + # Only send not-none values to the API + json={key: value for key, value in payload.items() if value is not None}, + ) + hf_raise_for_status(r) + + def delete_collection_item( + self, + collection_slug: str, + item_object_id: str, + *, + missing_ok: bool = False, + token: Optional[str] = None, + ) -> None: + """Delete an item from a collection. + + Args: + collection_slug (`str`): + Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`. + item_object_id (`str`): + ID of the item in the collection. This is not the id of the item on the Hub (repo_id or paper id). + It must be retrieved from a [`CollectionItem`] object. Example: `collection.items[0]._id`. + missing_ok (`bool`, *optional*): + If `True`, do not raise an error if item doesn't exists. + token (`str`, *optional*): + Hugging Face token. Will default to the locally saved token if not provided. + + Example: + + ```py + >>> from huggingface_hub import get_collection, delete_collection_item + + # Get collection first + >>> collection = get_collection("TheBloke/recent-models-64f9a55bb3115b4f513ec026") + + # Delete item based on its ID + >>> delete_collection_item( + ... collection_slug="TheBloke/recent-models-64f9a55bb3115b4f513ec026", + ... item_object_id=collection.items[-1].item_object_id, + ... ) + ``` + """ + r = get_session().delete( + f"{self.endpoint}/api/collections/{collection_slug}/items/{item_object_id}", + headers=self._build_hf_headers(token=token), + ) + try: + hf_raise_for_status(r) + except HTTPError as err: + if missing_ok and err.response.status_code == 404: + # Item already deleted and `missing_ok=True` + return + else: + raise + + ########################## + # Manage access requests # + ########################## + + @validate_hf_hub_args + def list_pending_access_requests( + self, repo_id: str, *, repo_type: Optional[str] = None, token: Optional[str] = None + ) -> List[AccessRequest]: + """ + Get pending access requests for a given gated repo. + + A pending request means the user has requested access to the repo but the request has not been processed yet. + If the approval mode is automatic, this list should be empty. Pending requests can be accepted or rejected + using [`accept_access_request`] and [`reject_access_request`]. + + For more info about gated repos, see https://huggingface.co/docs/hub/models-gated. + + Args: + repo_id (`str`): + The id of the repo to get access requests for. + repo_type (`str`, *optional*): + The type of the repo to get access requests for. Must be one of `model`, `dataset` or `space`. + Defaults to `model`. + token (`str`, *optional*): + A valid authentication token (see https://huggingface.co/settings/token). + + Returns: + `List[AccessRequest]`: A list of [`AccessRequest`] objects. Each time contains a `username`, `email`, + `status` and `timestamp` attribute. If the gated repo has a custom form, the `fields` attribute will + be populated with user's answers. + + Raises: + `HTTPError`: + HTTP 400 if the repo is not gated. + `HTTPError`: + HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write` + or `admin` role in the organization the repo belongs to or if you passed a `read` token. + + Example: + ```py + >>> from huggingface_hub import list_pending_access_requests, accept_access_request + + # List pending requests + >>> requests = list_pending_access_requests("meta-llama/Llama-2-7b") + >>> len(requests) + 411 + >>> requests[0] + [ + AccessRequest( + username='clem', + fullname='Clem 🤗', + email='***', + timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc), + status='pending', + fields=None, + ), + ... + ] + + # Accept Clem's request + >>> accept_access_request("meta-llama/Llama-2-7b", "clem") + ``` + """ + return self._list_access_requests(repo_id, "pending", repo_type=repo_type, token=token) + + @validate_hf_hub_args + def list_accepted_access_requests( + self, repo_id: str, *, repo_type: Optional[str] = None, token: Optional[str] = None + ) -> List[AccessRequest]: + """ + Get accepted access requests for a given gated repo. + + An accepted request means the user has requested access to the repo and the request has been accepted. The user + can download any file of the repo. If the approval mode is automatic, this list should contains by default all + requests. Accepted requests can be cancelled or rejected at any time using [`cancel_access_request`] and + [`reject_access_request`]. A cancelled request will go back to the pending list while a rejected request will + go to the rejected list. In both cases, the user will lose access to the repo. + + For more info about gated repos, see https://huggingface.co/docs/hub/models-gated. + + Args: + repo_id (`str`): + The id of the repo to get access requests for. + repo_type (`str`, *optional*): + The type of the repo to get access requests for. Must be one of `model`, `dataset` or `space`. + Defaults to `model`. + token (`str`, *optional*): + A valid authentication token (see https://huggingface.co/settings/token). + + Returns: + `List[AccessRequest]`: A list of [`AccessRequest`] objects. Each time contains a `username`, `email`, + `status` and `timestamp` attribute. If the gated repo has a custom form, the `fields` attribute will + be populated with user's answers. + + Raises: + `HTTPError`: + HTTP 400 if the repo is not gated. + `HTTPError`: + HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write` + or `admin` role in the organization the repo belongs to or if you passed a `read` token. + + Example: + ```py + >>> from huggingface_hub import list_accepted_access_requests + + >>> requests = list_accepted_access_requests("meta-llama/Llama-2-7b") + >>> len(requests) + 411 + >>> requests[0] + [ + AccessRequest( + username='clem', + fullname='Clem 🤗', + email='***', + timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc), + status='accepted', + fields=None, + ), + ... + ] + ``` + """ + return self._list_access_requests(repo_id, "accepted", repo_type=repo_type, token=token) + + @validate_hf_hub_args + def list_rejected_access_requests( + self, repo_id: str, *, repo_type: Optional[str] = None, token: Optional[str] = None + ) -> List[AccessRequest]: + """ + Get rejected access requests for a given gated repo. + + A rejected request means the user has requested access to the repo and the request has been explicitly rejected + by a repo owner (either you or another user from your organization). The user cannot download any file of the + repo. Rejected requests can be accepted or cancelled at any time using [`accept_access_request`] and + [`cancel_access_request`]. A cancelled request will go back to the pending list while an accepted request will + go to the accepted list. + + For more info about gated repos, see https://huggingface.co/docs/hub/models-gated. + + Args: + repo_id (`str`): + The id of the repo to get access requests for. + repo_type (`str`, *optional*): + The type of the repo to get access requests for. Must be one of `model`, `dataset` or `space`. + Defaults to `model`. + token (`str`, *optional*): + A valid authentication token (see https://huggingface.co/settings/token). + + Returns: + `List[AccessRequest]`: A list of [`AccessRequest`] objects. Each time contains a `username`, `email`, + `status` and `timestamp` attribute. If the gated repo has a custom form, the `fields` attribute will + be populated with user's answers. + + Raises: + `HTTPError`: + HTTP 400 if the repo is not gated. + `HTTPError`: + HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write` + or `admin` role in the organization the repo belongs to or if you passed a `read` token. + + Example: + ```py + >>> from huggingface_hub import list_rejected_access_requests + + >>> requests = list_rejected_access_requests("meta-llama/Llama-2-7b") + >>> len(requests) + 411 + >>> requests[0] + [ + AccessRequest( + username='clem', + fullname='Clem 🤗', + email='***', + timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc), + status='rejected', + fields=None, + ), + ... + ] + ``` + """ + return self._list_access_requests(repo_id, "rejected", repo_type=repo_type, token=token) + + def _list_access_requests( + self, + repo_id: str, + status: Literal["accepted", "rejected", "pending"], + repo_type: Optional[str] = None, + token: Optional[str] = None, + ) -> List[AccessRequest]: + if repo_type not in REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {REPO_TYPES}") + if repo_type is None: + repo_type = REPO_TYPE_MODEL + + response = get_session().get( + f"{ENDPOINT}/api/{repo_type}s/{repo_id}/user-access-request/{status}", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + return [ + AccessRequest( + username=request["user"]["user"], + fullname=request["user"]["fullname"], + email=request["user"]["email"], + status=request["status"], + timestamp=parse_datetime(request["timestamp"]), + fields=request.get("fields"), # only if custom fields in form + ) + for request in response.json() + ] + + @validate_hf_hub_args + def cancel_access_request( + self, repo_id: str, user: str, *, repo_type: Optional[str] = None, token: Optional[str] = None + ) -> None: + """ + Cancel an access request from a user for a given gated repo. + + A cancelled request will go back to the pending list and the user will lose access to the repo. + + For more info about gated repos, see https://huggingface.co/docs/hub/models-gated. + + Args: + repo_id (`str`): + The id of the repo to cancel access request for. + user (`str`): + The username of the user which access request should be cancelled. + repo_type (`str`, *optional*): + The type of the repo to cancel access request for. Must be one of `model`, `dataset` or `space`. + Defaults to `model`. + token (`str`, *optional*): + A valid authentication token (see https://huggingface.co/settings/token). + + Raises: + `HTTPError`: + HTTP 400 if the repo is not gated. + `HTTPError`: + HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write` + or `admin` role in the organization the repo belongs to or if you passed a `read` token. + `HTTPError`: + HTTP 404 if the user does not exist on the Hub. + `HTTPError`: + HTTP 404 if the user access request cannot be found. + `HTTPError`: + HTTP 404 if the user access request is already in the pending list. + """ + self._handle_access_request(repo_id, user, "pending", repo_type=repo_type, token=token) + + @validate_hf_hub_args + def accept_access_request( + self, repo_id: str, user: str, *, repo_type: Optional[str] = None, token: Optional[str] = None + ) -> None: + """ + Accept an access request from a user for a given gated repo. + + Once the request is accepted, the user will be able to download any file of the repo and access the community + tab. If the approval mode is automatic, you don't have to accept requests manually. An accepted request can be + cancelled or rejected at any time using [`cancel_access_request`] and [`reject_access_request`]. + + For more info about gated repos, see https://huggingface.co/docs/hub/models-gated. + + Args: + repo_id (`str`): + The id of the repo to accept access request for. + user (`str`): + The username of the user which access request should be accepted. + repo_type (`str`, *optional*): + The type of the repo to accept access request for. Must be one of `model`, `dataset` or `space`. + Defaults to `model`. + token (`str`, *optional*): + A valid authentication token (see https://huggingface.co/settings/token). + + Raises: + `HTTPError`: + HTTP 400 if the repo is not gated. + `HTTPError`: + HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write` + or `admin` role in the organization the repo belongs to or if you passed a `read` token. + `HTTPError`: + HTTP 404 if the user does not exist on the Hub. + `HTTPError`: + HTTP 404 if the user access request cannot be found. + `HTTPError`: + HTTP 404 if the user access request is already in the accepted list. + """ + self._handle_access_request(repo_id, user, "accepted", repo_type=repo_type, token=token) + + @validate_hf_hub_args + def reject_access_request( + self, repo_id: str, user: str, *, repo_type: Optional[str] = None, token: Optional[str] = None + ) -> None: + """ + Reject an access request from a user for a given gated repo. + + A rejected request will go to the rejected list. The user cannot download any file of the repo. Rejected + requests can be accepted or cancelled at any time using [`accept_access_request`] and [`cancel_access_request`]. + A cancelled request will go back to the pending list while an accepted request will go to the accepted list. + + For more info about gated repos, see https://huggingface.co/docs/hub/models-gated. + + Args: + repo_id (`str`): + The id of the repo to reject access request for. + user (`str`): + The username of the user which access request should be rejected. + repo_type (`str`, *optional*): + The type of the repo to reject access request for. Must be one of `model`, `dataset` or `space`. + Defaults to `model`. + token (`str`, *optional*): + A valid authentication token (see https://huggingface.co/settings/token). + + Raises: + `HTTPError`: + HTTP 400 if the repo is not gated. + `HTTPError`: + HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write` + or `admin` role in the organization the repo belongs to or if you passed a `read` token. + `HTTPError`: + HTTP 404 if the user does not exist on the Hub. + `HTTPError`: + HTTP 404 if the user access request cannot be found. + `HTTPError`: + HTTP 404 if the user access request is already in the rejected list. + """ + self._handle_access_request(repo_id, user, "rejected", repo_type=repo_type, token=token) + + @validate_hf_hub_args + def _handle_access_request( + self, + repo_id: str, + user: str, + status: Literal["accepted", "rejected", "pending"], + repo_type: Optional[str] = None, + token: Optional[str] = None, + ) -> None: + if repo_type not in REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {REPO_TYPES}") + if repo_type is None: + repo_type = REPO_TYPE_MODEL + + response = get_session().post( + f"{ENDPOINT}/api/{repo_type}s/{repo_id}/user-access-request/handle", + headers=self._build_hf_headers(token=token), + json={"user": user, "status": status}, + ) + hf_raise_for_status(response) + + @validate_hf_hub_args + def grant_access( + self, repo_id: str, user: str, *, repo_type: Optional[str] = None, token: Optional[str] = None + ) -> None: + """ + Grant access to a user for a given gated repo. + + Granting access don't require for the user to send an access request by themselves. The user is automatically + added to the accepted list meaning they can download the files You can revoke the granted access at any time + using [`cancel_access_request`] or [`reject_access_request`]. + + For more info about gated repos, see https://huggingface.co/docs/hub/models-gated. + + Args: + repo_id (`str`): + The id of the repo to grant access to. + user (`str`): + The username of the user to grant access. + repo_type (`str`, *optional*): + The type of the repo to grant access to. Must be one of `model`, `dataset` or `space`. + Defaults to `model`. + token (`str`, *optional*): + A valid authentication token (see https://huggingface.co/settings/token). + + Raises: + `HTTPError`: + HTTP 400 if the repo is not gated. + `HTTPError`: + HTTP 400 if the user already has access to the repo. + `HTTPError`: + HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write` + or `admin` role in the organization the repo belongs to or if you passed a `read` token. + `HTTPError`: + HTTP 404 if the user does not exist on the Hub. + """ + if repo_type not in REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {REPO_TYPES}") + if repo_type is None: + repo_type = REPO_TYPE_MODEL + + response = get_session().post( + f"{ENDPOINT}/api/models/{repo_id}/user-access-request/grant", + headers=self._build_hf_headers(token=token), + json={"user": user}, + ) + hf_raise_for_status(response) + return response.json() + + ############# + # Internals # + ############# + + def _build_hf_headers( + self, + token: Optional[Union[bool, str]] = None, + is_write_action: bool = False, + library_name: Optional[str] = None, + library_version: Optional[str] = None, + user_agent: Union[Dict, str, None] = None, + ) -> Dict[str, str]: + """ + Alias for [`build_hf_headers`] that uses the token from [`HfApi`] client + when `token` is not provided. + """ + if token is None: + # Cannot do `token = token or self.token` as token can be `False`. + token = self.token + return build_hf_headers( + token=token, + is_write_action=is_write_action, + library_name=library_name or self.library_name, + library_version=library_version or self.library_version, + user_agent=user_agent or self.user_agent, + headers=self.headers, + ) + + def _prepare_upload_folder_deletions( + self, + repo_id: str, + repo_type: Optional[str], + revision: Optional[str], + token: Optional[str], + path_in_repo: str, + delete_patterns: Optional[Union[List[str], str]], + ) -> List[CommitOperationDelete]: + """Generate the list of Delete operations for a commit to delete files from a repo. + + List remote files and match them against the `delete_patterns` constraints. Returns a list of [`CommitOperationDelete`] + with the matching items. + + Note: `.gitattributes` file is essential to make a repo work properly on the Hub. This file will always be + kept even if it matches the `delete_patterns` constraints. + """ + if delete_patterns is None: + # If no delete patterns, no need to list and filter remote files + return [] + + # List remote files + filenames = self.list_repo_files(repo_id=repo_id, revision=revision, repo_type=repo_type, token=token) + + # Compute relative path in repo + if path_in_repo and path_in_repo not in (".", "./"): + path_in_repo = path_in_repo.strip("/") + "/" # harmonize + relpath_to_abspath = { + file[len(path_in_repo) :]: file for file in filenames if file.startswith(path_in_repo) + } + else: + relpath_to_abspath = {file: file for file in filenames} + + # Apply filter on relative paths and return + return [ + CommitOperationDelete(path_in_repo=relpath_to_abspath[relpath], is_folder=False) + for relpath in filter_repo_objects(relpath_to_abspath.keys(), allow_patterns=delete_patterns) + if relpath_to_abspath[relpath] != ".gitattributes" + ] + + +def _prepare_upload_folder_additions( + folder_path: Union[str, Path], + path_in_repo: str, + allow_patterns: Optional[Union[List[str], str]] = None, + ignore_patterns: Optional[Union[List[str], str]] = None, +) -> List[CommitOperationAdd]: + """Generate the list of Add operations for a commit to upload a folder. + + Files not matching the `allow_patterns` (allowlist) and `ignore_patterns` (denylist) + constraints are discarded. + """ + folder_path = Path(folder_path).expanduser().resolve() + if not folder_path.is_dir(): + raise ValueError(f"Provided path: '{folder_path}' is not a directory") + + # List files from folder + relpath_to_abspath = { + path.relative_to(folder_path).as_posix(): path + for path in sorted(folder_path.glob("**/*")) # sorted to be deterministic + if path.is_file() + } + + # Filter files and return + # Patterns are applied on the path relative to `folder_path`. `path_in_repo` is prefixed after the filtering. + prefix = f"{path_in_repo.strip('/')}/" if path_in_repo else "" + return [ + CommitOperationAdd( + path_or_fileobj=relpath_to_abspath[relpath], # absolute path on disk + path_in_repo=prefix + relpath, # "absolute" path in repo + ) + for relpath in filter_repo_objects( + relpath_to_abspath.keys(), allow_patterns=allow_patterns, ignore_patterns=ignore_patterns + ) + ] + + +def _parse_revision_from_pr_url(pr_url: str) -> str: + """Safely parse revision number from a PR url. + + Example: + ```py + >>> _parse_revision_from_pr_url("https://huggingface.co/bigscience/bloom/discussions/2") + "refs/pr/2" + ``` + """ + re_match = re.match(_REGEX_DISCUSSION_URL, pr_url) + if re_match is None: + raise RuntimeError(f"Unexpected response from the hub, expected a Pull Request URL but got: '{pr_url}'") + return f"refs/pr/{re_match[1]}" + + +api = HfApi() + +whoami = api.whoami +get_token_permission = api.get_token_permission + +list_models = api.list_models +model_info = api.model_info + +list_datasets = api.list_datasets +dataset_info = api.dataset_info + +list_spaces = api.list_spaces +space_info = api.space_info + +repo_exists = api.repo_exists +revision_exists = api.revision_exists +file_exists = api.file_exists +repo_info = api.repo_info +list_repo_files = api.list_repo_files +list_repo_refs = api.list_repo_refs +list_repo_commits = api.list_repo_commits +list_files_info = api.list_files_info +list_repo_tree = api.list_repo_tree +get_paths_info = api.get_paths_info + +list_metrics = api.list_metrics + +get_model_tags = api.get_model_tags +get_dataset_tags = api.get_dataset_tags + +create_commit = api.create_commit +create_repo = api.create_repo +delete_repo = api.delete_repo +update_repo_visibility = api.update_repo_visibility +super_squash_history = api.super_squash_history +move_repo = api.move_repo +upload_file = api.upload_file +upload_folder = api.upload_folder +delete_file = api.delete_file +delete_folder = api.delete_folder +create_commits_on_pr = api.create_commits_on_pr +preupload_lfs_files = api.preupload_lfs_files +create_branch = api.create_branch +delete_branch = api.delete_branch +create_tag = api.create_tag +delete_tag = api.delete_tag +get_full_repo_name = api.get_full_repo_name + +# Safetensors helpers +get_safetensors_metadata = api.get_safetensors_metadata +parse_safetensors_file_metadata = api.parse_safetensors_file_metadata + +# Background jobs +run_as_future = api.run_as_future + +# Activity API +list_liked_repos = api.list_liked_repos +list_repo_likers = api.list_repo_likers +like = api.like +unlike = api.unlike + +# Community API +get_discussion_details = api.get_discussion_details +get_repo_discussions = api.get_repo_discussions +create_discussion = api.create_discussion +create_pull_request = api.create_pull_request +change_discussion_status = api.change_discussion_status +comment_discussion = api.comment_discussion +edit_discussion_comment = api.edit_discussion_comment +rename_discussion = api.rename_discussion +merge_pull_request = api.merge_pull_request + +# Space API +add_space_secret = api.add_space_secret +delete_space_secret = api.delete_space_secret +get_space_variables = api.get_space_variables +add_space_variable = api.add_space_variable +delete_space_variable = api.delete_space_variable +get_space_runtime = api.get_space_runtime +request_space_hardware = api.request_space_hardware +set_space_sleep_time = api.set_space_sleep_time +pause_space = api.pause_space +restart_space = api.restart_space +duplicate_space = api.duplicate_space +request_space_storage = api.request_space_storage +delete_space_storage = api.delete_space_storage + +# Inference Endpoint API +list_inference_endpoints = api.list_inference_endpoints +create_inference_endpoint = api.create_inference_endpoint +get_inference_endpoint = api.get_inference_endpoint +update_inference_endpoint = api.update_inference_endpoint +delete_inference_endpoint = api.delete_inference_endpoint +pause_inference_endpoint = api.pause_inference_endpoint +resume_inference_endpoint = api.resume_inference_endpoint +scale_to_zero_inference_endpoint = api.scale_to_zero_inference_endpoint + +# Collections API +get_collection = api.get_collection +list_collections = api.list_collections +create_collection = api.create_collection +update_collection_metadata = api.update_collection_metadata +delete_collection = api.delete_collection +add_collection_item = api.add_collection_item +update_collection_item = api.update_collection_item +delete_collection_item = api.delete_collection_item +delete_collection_item = api.delete_collection_item + +# Access requests API +list_pending_access_requests = api.list_pending_access_requests +list_accepted_access_requests = api.list_accepted_access_requests +list_rejected_access_requests = api.list_rejected_access_requests +cancel_access_request = api.cancel_access_request +accept_access_request = api.accept_access_request +reject_access_request = api.reject_access_request +grant_access = api.grant_access diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/hf_file_system.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/hf_file_system.py new file mode 100644 index 0000000000000000000000000000000000000000..e6843b7074d946d7675d4414a91c19519e178227 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/hf_file_system.py @@ -0,0 +1,867 @@ +import copy +import os +import re +import tempfile +from collections import deque +from dataclasses import dataclass, field +from datetime import datetime +from itertools import chain +from pathlib import Path +from typing import Any, Dict, List, NoReturn, Optional, Tuple, Union +from urllib.parse import quote, unquote + +import fsspec +from fsspec.callbacks import _DEFAULT_CALLBACK, NoOpCallback, TqdmCallback +from fsspec.utils import isfilelike +from requests import Response + +from ._commit_api import CommitOperationCopy, CommitOperationDelete +from .constants import ( + DEFAULT_REVISION, + ENDPOINT, + REPO_TYPE_MODEL, + REPO_TYPES_MAPPING, + REPO_TYPES_URL_PREFIXES, +) +from .file_download import hf_hub_url, http_get +from .hf_api import HfApi, LastCommitInfo, RepoFile +from .utils import ( + EntryNotFoundError, + HFValidationError, + RepositoryNotFoundError, + RevisionNotFoundError, + hf_raise_for_status, + http_backoff, +) + + +# Regex used to match special revisions with "/" in them (see #1710) +SPECIAL_REFS_REVISION_REGEX = re.compile( + r""" + (^refs\/convert\/\w+) # `refs/convert/parquet` revisions + | + (^refs\/pr\/\d+) # PR revisions + """, + re.VERBOSE, +) + + +@dataclass +class HfFileSystemResolvedPath: + """Data structure containing information about a resolved Hugging Face file system path.""" + + repo_type: str + repo_id: str + revision: str + path_in_repo: str + # The part placed after '@' in the initial path. It can be a quoted or unquoted refs revision. + # Used to reconstruct the unresolved path to return to the user. + _raw_revision: Optional[str] = field(default=None, repr=False) + + def unresolve(self) -> str: + repo_path = REPO_TYPES_URL_PREFIXES.get(self.repo_type, "") + self.repo_id + if self._raw_revision: + return f"{repo_path}@{self._raw_revision}/{self.path_in_repo}".rstrip("/") + elif self.revision != DEFAULT_REVISION: + return f"{repo_path}@{safe_revision(self.revision)}/{self.path_in_repo}".rstrip("/") + else: + return f"{repo_path}/{self.path_in_repo}".rstrip("/") + + +class HfFileSystem(fsspec.AbstractFileSystem): + """ + Access a remote Hugging Face Hub repository as if were a local file system. + + Args: + token (`str`, *optional*): + Authentication token, obtained with [`HfApi.login`] method. Will default to the stored token. + + Usage: + + ```python + >>> from huggingface_hub import HfFileSystem + + >>> fs = HfFileSystem() + + >>> # List files + >>> fs.glob("my-username/my-model/*.bin") + ['my-username/my-model/pytorch_model.bin'] + >>> fs.ls("datasets/my-username/my-dataset", detail=False) + ['datasets/my-username/my-dataset/.gitattributes', 'datasets/my-username/my-dataset/README.md', 'datasets/my-username/my-dataset/data.json'] + + >>> # Read/write files + >>> with fs.open("my-username/my-model/pytorch_model.bin") as f: + ... data = f.read() + >>> with fs.open("my-username/my-model/pytorch_model.bin", "wb") as f: + ... f.write(data) + ``` + """ + + root_marker = "" + protocol = "hf" + + def __init__( + self, + *args, + endpoint: Optional[str] = None, + token: Optional[str] = None, + **storage_options, + ): + super().__init__(*args, **storage_options) + self.endpoint = endpoint or ENDPOINT + self.token = token + self._api = HfApi(endpoint=endpoint, token=token) + # Maps (repo_type, repo_id, revision) to a 2-tuple with: + # * the 1st element indicating whether the repositoy and the revision exist + # * the 2nd element being the exception raised if the repository or revision doesn't exist + self._repo_and_revision_exists_cache: Dict[ + Tuple[str, str, Optional[str]], Tuple[bool, Optional[Exception]] + ] = {} + + def _repo_and_revision_exist( + self, repo_type: str, repo_id: str, revision: Optional[str] + ) -> Tuple[bool, Optional[Exception]]: + if (repo_type, repo_id, revision) not in self._repo_and_revision_exists_cache: + try: + self._api.repo_info(repo_id, revision=revision, repo_type=repo_type) + except (RepositoryNotFoundError, HFValidationError) as e: + self._repo_and_revision_exists_cache[(repo_type, repo_id, revision)] = False, e + self._repo_and_revision_exists_cache[(repo_type, repo_id, None)] = False, e + except RevisionNotFoundError as e: + self._repo_and_revision_exists_cache[(repo_type, repo_id, revision)] = False, e + self._repo_and_revision_exists_cache[(repo_type, repo_id, None)] = True, None + else: + self._repo_and_revision_exists_cache[(repo_type, repo_id, revision)] = True, None + self._repo_and_revision_exists_cache[(repo_type, repo_id, None)] = True, None + return self._repo_and_revision_exists_cache[(repo_type, repo_id, revision)] + + def resolve_path(self, path: str, revision: Optional[str] = None) -> HfFileSystemResolvedPath: + def _align_revision_in_path_with_revision( + revision_in_path: Optional[str], revision: Optional[str] + ) -> Optional[str]: + if revision is not None: + if revision_in_path is not None and revision_in_path != revision: + raise ValueError( + f'Revision specified in path ("{revision_in_path}") and in `revision` argument ("{revision}")' + " are not the same." + ) + else: + revision = revision_in_path + return revision + + path = self._strip_protocol(path) + if not path: + # can't list repositories at root + raise NotImplementedError("Access to repositories lists is not implemented.") + elif path.split("/")[0] + "/" in REPO_TYPES_URL_PREFIXES.values(): + if "/" not in path: + # can't list repositories at the repository type level + raise NotImplementedError("Access to repositories lists is not implemented.") + repo_type, path = path.split("/", 1) + repo_type = REPO_TYPES_MAPPING[repo_type] + else: + repo_type = REPO_TYPE_MODEL + if path.count("/") > 0: + if "@" in path: + repo_id, revision_in_path = path.split("@", 1) + if "/" in revision_in_path: + match = SPECIAL_REFS_REVISION_REGEX.search(revision_in_path) + if match is not None and revision in (None, match.group()): + # Handle `refs/convert/parquet` and PR revisions separately + path_in_repo = SPECIAL_REFS_REVISION_REGEX.sub("", revision_in_path).lstrip("/") + revision_in_path = match.group() + else: + revision_in_path, path_in_repo = revision_in_path.split("/", 1) + else: + path_in_repo = "" + revision = _align_revision_in_path_with_revision(unquote(revision_in_path), revision) + repo_and_revision_exist, err = self._repo_and_revision_exist(repo_type, repo_id, revision) + if not repo_and_revision_exist: + _raise_file_not_found(path, err) + else: + revision_in_path = None + repo_id_with_namespace = "/".join(path.split("/")[:2]) + path_in_repo_with_namespace = "/".join(path.split("/")[2:]) + repo_id_without_namespace = path.split("/")[0] + path_in_repo_without_namespace = "/".join(path.split("/")[1:]) + repo_id = repo_id_with_namespace + path_in_repo = path_in_repo_with_namespace + repo_and_revision_exist, err = self._repo_and_revision_exist(repo_type, repo_id, revision) + if not repo_and_revision_exist: + if isinstance(err, (RepositoryNotFoundError, HFValidationError)): + repo_id = repo_id_without_namespace + path_in_repo = path_in_repo_without_namespace + repo_and_revision_exist, _ = self._repo_and_revision_exist(repo_type, repo_id, revision) + if not repo_and_revision_exist: + _raise_file_not_found(path, err) + else: + _raise_file_not_found(path, err) + else: + repo_id = path + path_in_repo = "" + if "@" in path: + repo_id, revision_in_path = path.split("@", 1) + revision = _align_revision_in_path_with_revision(unquote(revision_in_path), revision) + else: + revision_in_path = None + repo_and_revision_exist, _ = self._repo_and_revision_exist(repo_type, repo_id, revision) + if not repo_and_revision_exist: + raise NotImplementedError("Access to repositories lists is not implemented.") + + revision = revision if revision is not None else DEFAULT_REVISION + return HfFileSystemResolvedPath(repo_type, repo_id, revision, path_in_repo, _raw_revision=revision_in_path) + + def invalidate_cache(self, path: Optional[str] = None) -> None: + if not path: + self.dircache.clear() + self._repo_and_revision_exists_cache.clear() + else: + path = self.resolve_path(path).unresolve() + while path: + self.dircache.pop(path, None) + path = self._parent(path) + + def _open( + self, + path: str, + mode: str = "rb", + revision: Optional[str] = None, + block_size: Optional[int] = None, + **kwargs, + ) -> "HfFileSystemFile": + if "a" in mode: + raise NotImplementedError("Appending to remote files is not yet supported.") + if block_size == 0: + return HfFileSystemStreamFile(self, path, mode=mode, revision=revision, block_size=block_size, **kwargs) + else: + return HfFileSystemFile(self, path, mode=mode, revision=revision, block_size=block_size, **kwargs) + + def _rm(self, path: str, revision: Optional[str] = None, **kwargs) -> None: + resolved_path = self.resolve_path(path, revision=revision) + self._api.delete_file( + path_in_repo=resolved_path.path_in_repo, + repo_id=resolved_path.repo_id, + token=self.token, + repo_type=resolved_path.repo_type, + revision=resolved_path.revision, + commit_message=kwargs.get("commit_message"), + commit_description=kwargs.get("commit_description"), + ) + self.invalidate_cache(path=resolved_path.unresolve()) + + def rm( + self, + path: str, + recursive: bool = False, + maxdepth: Optional[int] = None, + revision: Optional[str] = None, + **kwargs, + ) -> None: + resolved_path = self.resolve_path(path, revision=revision) + paths = self.expand_path(path, recursive=recursive, maxdepth=maxdepth, revision=revision) + paths_in_repo = [self.resolve_path(path).path_in_repo for path in paths if not self.isdir(path)] + operations = [CommitOperationDelete(path_in_repo=path_in_repo) for path_in_repo in paths_in_repo] + commit_message = f"Delete {path} " + commit_message += "recursively " if recursive else "" + commit_message += f"up to depth {maxdepth} " if maxdepth is not None else "" + # TODO: use `commit_description` to list all the deleted paths? + self._api.create_commit( + repo_id=resolved_path.repo_id, + repo_type=resolved_path.repo_type, + token=self.token, + operations=operations, + revision=resolved_path.revision, + commit_message=kwargs.get("commit_message", commit_message), + commit_description=kwargs.get("commit_description"), + ) + self.invalidate_cache(path=resolved_path.unresolve()) + + def ls( + self, path: str, detail: bool = True, refresh: bool = False, revision: Optional[str] = None, **kwargs + ) -> List[Union[str, Dict[str, Any]]]: + """List the contents of a directory.""" + resolved_path = self.resolve_path(path, revision=revision) + path = resolved_path.unresolve() + kwargs = {"expand_info": detail, **kwargs} + try: + out = self._ls_tree(path, refresh=refresh, revision=revision, **kwargs) + except EntryNotFoundError: + # Path could be a file + if not resolved_path.path_in_repo: + _raise_file_not_found(path, None) + out = self._ls_tree(self._parent(path), refresh=refresh, revision=revision, **kwargs) + out = [o for o in out if o["name"] == path] + if len(out) == 0: + _raise_file_not_found(path, None) + return out if detail else [o["name"] for o in out] + + def _ls_tree( + self, + path: str, + recursive: bool = False, + refresh: bool = False, + revision: Optional[str] = None, + expand_info: bool = True, + ): + resolved_path = self.resolve_path(path, revision=revision) + path = resolved_path.unresolve() + root_path = HfFileSystemResolvedPath( + resolved_path.repo_type, + resolved_path.repo_id, + resolved_path.revision, + path_in_repo="", + _raw_revision=resolved_path._raw_revision, + ).unresolve() + + out = [] + if path in self.dircache and not refresh: + cached_path_infos = self.dircache[path] + out.extend(cached_path_infos) + dirs_not_in_dircache = [] + if recursive: + # Use BFS to traverse the cache and build the "recursive "output + # (The Hub uses a so-called "tree first" strategy for the tree endpoint but we sort the output to follow the spec so the result is (eventually) the same) + dirs_to_visit = deque( + [path_info for path_info in cached_path_infos if path_info["type"] == "directory"] + ) + while dirs_to_visit: + dir_info = dirs_to_visit.popleft() + if dir_info["name"] not in self.dircache: + dirs_not_in_dircache.append(dir_info["name"]) + else: + cached_path_infos = self.dircache[dir_info["name"]] + out.extend(cached_path_infos) + dirs_to_visit.extend( + [path_info for path_info in cached_path_infos if path_info["type"] == "directory"] + ) + + dirs_not_expanded = [] + if expand_info: + # Check if there are directories with non-expanded entries + dirs_not_expanded = [self._parent(o["name"]) for o in out if o["last_commit"] is None] + + if (recursive and dirs_not_in_dircache) or (expand_info and dirs_not_expanded): + # If the dircache is incomplete, find the common path of the missing and non-expanded entries + # and extend the output with the result of `_ls_tree(common_path, recursive=True)` + common_prefix = os.path.commonprefix(dirs_not_in_dircache + dirs_not_expanded) + # Get the parent directory if the common prefix itself is not a directory + common_path = ( + common_prefix.rstrip("/") + if common_prefix.endswith("/") + or common_prefix == root_path + or common_prefix in chain(dirs_not_in_dircache, dirs_not_expanded) + else self._parent(common_prefix) + ) + out = [o for o in out if not o["name"].startswith(common_path + "/")] + for cached_path in self.dircache: + if cached_path.startswith(common_path + "/"): + self.dircache.pop(cached_path, None) + self.dircache.pop(common_path, None) + out.extend( + self._ls_tree( + common_path, + recursive=recursive, + refresh=True, + revision=revision, + expand_info=expand_info, + ) + ) + else: + tree = self._api.list_repo_tree( + resolved_path.repo_id, + resolved_path.path_in_repo, + recursive=recursive, + expand=expand_info, + revision=resolved_path.revision, + repo_type=resolved_path.repo_type, + ) + for path_info in tree: + if isinstance(path_info, RepoFile): + cache_path_info = { + "name": root_path + "/" + path_info.path, + "size": path_info.size, + "type": "file", + "blob_id": path_info.blob_id, + "lfs": path_info.lfs, + "last_commit": path_info.last_commit, + "security": path_info.security, + } + else: + cache_path_info = { + "name": root_path + "/" + path_info.path, + "size": 0, + "type": "directory", + "tree_id": path_info.tree_id, + "last_commit": path_info.last_commit, + } + parent_path = self._parent(cache_path_info["name"]) + self.dircache.setdefault(parent_path, []).append(cache_path_info) + out.append(cache_path_info) + return copy.deepcopy(out) # copy to not let users modify the dircache + + def glob(self, path, **kwargs): + # Set expand_info=False by default to get a x10 speed boost + kwargs = {"expand_info": kwargs.get("detail", False), **kwargs} + path = self.resolve_path(path, revision=kwargs.get("revision")).unresolve() + return super().glob(path, **kwargs) + + def find( + self, + path: str, + maxdepth: Optional[int] = None, + withdirs: bool = False, + detail: bool = False, + refresh: bool = False, + revision: Optional[str] = None, + **kwargs, + ) -> Union[List[str], Dict[str, Dict[str, Any]]]: + if maxdepth: + return super().find( + path, maxdepth=maxdepth, withdirs=withdirs, detail=detail, refresh=refresh, revision=revision, **kwargs + ) + resolved_path = self.resolve_path(path, revision=revision) + path = resolved_path.unresolve() + kwargs = {"expand_info": detail, **kwargs} + try: + out = self._ls_tree(path, recursive=True, refresh=refresh, revision=resolved_path.revision, **kwargs) + except EntryNotFoundError: + # Path could be a file + if self.info(path, revision=revision, **kwargs)["type"] == "file": + out = {path: {}} + else: + out = {} + else: + if not withdirs: + out = [o for o in out if o["type"] != "directory"] + else: + # If `withdirs=True`, include the directory itself to be consistent with the spec + path_info = self.info(path, revision=resolved_path.revision, **kwargs) + out = [path_info] + out if path_info["type"] == "directory" else out + out = {o["name"]: o for o in out} + names = sorted(out) + if not detail: + return names + else: + return {name: out[name] for name in names} + + def cp_file(self, path1: str, path2: str, revision: Optional[str] = None, **kwargs) -> None: + resolved_path1 = self.resolve_path(path1, revision=revision) + resolved_path2 = self.resolve_path(path2, revision=revision) + + same_repo = ( + resolved_path1.repo_type == resolved_path2.repo_type and resolved_path1.repo_id == resolved_path2.repo_id + ) + + if same_repo: + commit_message = f"Copy {path1} to {path2}" + self._api.create_commit( + repo_id=resolved_path1.repo_id, + repo_type=resolved_path1.repo_type, + revision=resolved_path2.revision, + commit_message=kwargs.get("commit_message", commit_message), + commit_description=kwargs.get("commit_description", ""), + operations=[ + CommitOperationCopy( + src_path_in_repo=resolved_path1.path_in_repo, + path_in_repo=resolved_path2.path_in_repo, + src_revision=resolved_path1.revision, + ) + ], + ) + else: + with self.open(path1, "rb", revision=resolved_path1.revision) as f: + content = f.read() + commit_message = f"Copy {path1} to {path2}" + self._api.upload_file( + path_or_fileobj=content, + path_in_repo=resolved_path2.path_in_repo, + repo_id=resolved_path2.repo_id, + token=self.token, + repo_type=resolved_path2.repo_type, + revision=resolved_path2.revision, + commit_message=kwargs.get("commit_message", commit_message), + commit_description=kwargs.get("commit_description"), + ) + self.invalidate_cache(path=resolved_path1.unresolve()) + self.invalidate_cache(path=resolved_path2.unresolve()) + + def modified(self, path: str, **kwargs) -> datetime: + info = self.info(path, **kwargs) + return info["last_commit"]["date"] + + def info(self, path: str, refresh: bool = False, revision: Optional[str] = None, **kwargs) -> Dict[str, Any]: + resolved_path = self.resolve_path(path, revision=revision) + path = resolved_path.unresolve() + expand_info = kwargs.get( + "expand_info", True + ) # don't expose it as a parameter in the public API to follow the spec + if not resolved_path.path_in_repo: + # Path is the root directory + out = { + "name": path, + "size": 0, + "type": "directory", + } + if expand_info: + last_commit = self._api.list_repo_commits( + resolved_path.repo_id, repo_type=resolved_path.repo_type, revision=resolved_path.revision + )[-1] + out = { + **out, + "tree_id": None, # TODO: tree_id of the root directory? + "last_commit": LastCommitInfo( + oid=last_commit.commit_id, title=last_commit.title, date=last_commit.created_at + ), + } + else: + out = None + parent_path = self._parent(path) + if parent_path in self.dircache: + # Check if the path is in the cache + out1 = [o for o in self.dircache[parent_path] if o["name"] == path] + if not out1: + _raise_file_not_found(path, None) + out = out1[0] + if refresh or out is None or (expand_info and out and out["last_commit"] is None): + paths_info = self._api.get_paths_info( + resolved_path.repo_id, + resolved_path.path_in_repo, + expand=expand_info, + revision=resolved_path.revision, + repo_type=resolved_path.repo_type, + ) + if not paths_info: + _raise_file_not_found(path, None) + path_info = paths_info[0] + root_path = HfFileSystemResolvedPath( + resolved_path.repo_type, + resolved_path.repo_id, + resolved_path.revision, + path_in_repo="", + _raw_revision=resolved_path._raw_revision, + ).unresolve() + if isinstance(path_info, RepoFile): + out = { + "name": root_path + "/" + path_info.path, + "size": path_info.size, + "type": "file", + "blob_id": path_info.blob_id, + "lfs": path_info.lfs, + "last_commit": path_info.last_commit, + "security": path_info.security, + } + else: + out = { + "name": root_path + "/" + path_info.path, + "size": 0, + "type": "directory", + "tree_id": path_info.tree_id, + "last_commit": path_info.last_commit, + } + if not expand_info: + out = {k: out[k] for k in ["name", "size", "type"]} + assert out is not None + return copy.deepcopy(out) # copy to not let users modify the dircache + + def exists(self, path, **kwargs): + """Is there a file at the given path""" + try: + self.info(path, **{**kwargs, "expand_info": False}) + return True + except: # noqa: E722 + # any exception allowed bar FileNotFoundError? + return False + + def isdir(self, path): + """Is this entry directory-like?""" + try: + return self.info(path, expand_info=False)["type"] == "directory" + except OSError: + return False + + def isfile(self, path): + """Is this entry file-like?""" + try: + return self.info(path, expand_info=False)["type"] == "file" + except: # noqa: E722 + return False + + def url(self, path: str) -> str: + """Get the HTTP URL of the given path""" + resolved_path = self.resolve_path(path) + url = hf_hub_url( + resolved_path.repo_id, + resolved_path.path_in_repo, + repo_type=resolved_path.repo_type, + revision=resolved_path.revision, + endpoint=self.endpoint, + ) + if self.isdir(path): + url = url.replace("/resolve/", "/tree/", 1) + return url + + def get_file(self, rpath, lpath, callback=_DEFAULT_CALLBACK, outfile=None, **kwargs) -> None: + """Copy single remote file to local.""" + revision = kwargs.get("revision") + unhandled_kwargs = set(kwargs.keys()) - {"revision"} + if not isinstance(callback, (NoOpCallback, TqdmCallback)) or len(unhandled_kwargs) > 0: + # for now, let's not handle custom callbacks + # and let's not handle custom kwargs + return super().get_file(rpath, lpath, callback=callback, outfile=outfile, **kwargs) + + # Taken from https://github.com/fsspec/filesystem_spec/blob/47b445ae4c284a82dd15e0287b1ffc410e8fc470/fsspec/spec.py#L883 + if isfilelike(lpath): + outfile = lpath + elif self.isdir(rpath): + os.makedirs(lpath, exist_ok=True) + return None + + if isinstance(lpath, (str, Path)): # otherwise, let's assume it's a file-like object + os.makedirs(os.path.dirname(lpath), exist_ok=True) + + # Open file if not already open + close_file = False + if outfile is None: + outfile = open(lpath, "wb") + close_file = True + initial_pos = outfile.tell() + + # Custom implementation of `get_file` to use `http_get`. + resolve_remote_path = self.resolve_path(rpath, revision=revision) + expected_size = self.info(rpath, revision=revision)["size"] + callback.set_size(expected_size) + try: + http_get( + url=hf_hub_url( + repo_id=resolve_remote_path.repo_id, + revision=resolve_remote_path.revision, + filename=resolve_remote_path.path_in_repo, + repo_type=resolve_remote_path.repo_type, + endpoint=self.endpoint, + ), + temp_file=outfile, + displayed_filename=rpath, + expected_size=expected_size, + resume_size=0, + headers=self._api._build_hf_headers(), + _tqdm_bar=callback.tqdm if isinstance(callback, TqdmCallback) else None, + ) + outfile.seek(initial_pos) + finally: + # Close file only if we opened it ourselves + if close_file: + outfile.close() + + @property + def transaction(self): + """A context within which files are committed together upon exit + + Requires the file class to implement `.commit()` and `.discard()` + for the normal and exception cases. + """ + # Taken from https://github.com/fsspec/filesystem_spec/blob/3fbb6fee33b46cccb015607630843dea049d3243/fsspec/spec.py#L231 + # See https://github.com/huggingface/huggingface_hub/issues/1733 + raise NotImplementedError("Transactional commits are not supported.") + + def start_transaction(self): + """Begin write transaction for deferring files, non-context version""" + # Taken from https://github.com/fsspec/filesystem_spec/blob/3fbb6fee33b46cccb015607630843dea049d3243/fsspec/spec.py#L241 + # See https://github.com/huggingface/huggingface_hub/issues/1733 + raise NotImplementedError("Transactional commits are not supported.") + + +class HfFileSystemFile(fsspec.spec.AbstractBufferedFile): + def __init__(self, fs: HfFileSystem, path: str, revision: Optional[str] = None, **kwargs): + try: + self.resolved_path = fs.resolve_path(path, revision=revision) + except FileNotFoundError as e: + if "w" in kwargs.get("mode", ""): + raise FileNotFoundError( + f"{e}.\nMake sure the repository and revision exist before writing data." + ) from e + raise + super().__init__(fs, self.resolved_path.unresolve(), **kwargs) + self.fs: HfFileSystem + + def __del__(self): + if not hasattr(self, "resolved_path"): + # Means that the constructor failed. Nothing to do. + return + return super().__del__() + + def _fetch_range(self, start: int, end: int) -> bytes: + headers = { + "range": f"bytes={start}-{end - 1}", + **self.fs._api._build_hf_headers(), + } + url = hf_hub_url( + repo_id=self.resolved_path.repo_id, + revision=self.resolved_path.revision, + filename=self.resolved_path.path_in_repo, + repo_type=self.resolved_path.repo_type, + endpoint=self.fs.endpoint, + ) + r = http_backoff("GET", url, headers=headers, retry_on_status_codes=(502, 503, 504)) + hf_raise_for_status(r) + return r.content + + def _initiate_upload(self) -> None: + self.temp_file = tempfile.NamedTemporaryFile(prefix="hffs-", delete=False) + + def _upload_chunk(self, final: bool = False) -> None: + self.buffer.seek(0) + block = self.buffer.read() + self.temp_file.write(block) + if final: + self.temp_file.close() + self.fs._api.upload_file( + path_or_fileobj=self.temp_file.name, + path_in_repo=self.resolved_path.path_in_repo, + repo_id=self.resolved_path.repo_id, + token=self.fs.token, + repo_type=self.resolved_path.repo_type, + revision=self.resolved_path.revision, + commit_message=self.kwargs.get("commit_message"), + commit_description=self.kwargs.get("commit_description"), + ) + os.remove(self.temp_file.name) + self.fs.invalidate_cache( + path=self.resolved_path.unresolve(), + ) + + def read(self, length=-1): + """Read remote file. + + If `length` is not provided or is -1, the entire file is downloaded and read. On POSIX systems and if + `hf_transfer` is not enabled, the file is loaded in memory directly. Otherwise, the file is downloaded to a + temporary file and read from there. + """ + if self.mode == "rb" and (length is None or length == -1) and self.loc == 0: + with self.fs.open(self.path, "rb", block_size=0) as f: # block_size=0 enables fast streaming + return f.read() + return super().read(length) + + def url(self) -> str: + return self.fs.url(self.path) + + +class HfFileSystemStreamFile(fsspec.spec.AbstractBufferedFile): + def __init__( + self, + fs: HfFileSystem, + path: str, + mode: str = "rb", + revision: Optional[str] = None, + block_size: int = 0, + cache_type: str = "none", + **kwargs, + ): + if block_size != 0: + raise ValueError(f"HfFileSystemStreamFile only supports block_size=0 but got {block_size}") + if cache_type != "none": + raise ValueError(f"HfFileSystemStreamFile only supports cache_type='none' but got {cache_type}") + if "w" in mode: + raise ValueError(f"HfFileSystemStreamFile only supports reading but got mode='{mode}'") + try: + self.resolved_path = fs.resolve_path(path, revision=revision) + except FileNotFoundError as e: + if "w" in kwargs.get("mode", ""): + raise FileNotFoundError( + f"{e}.\nMake sure the repository and revision exist before writing data." + ) from e + # avoid an unnecessary .info() call to instantiate .details + self.details = {"name": self.resolved_path.unresolve(), "size": None} + super().__init__( + fs, self.resolved_path.unresolve(), mode=mode, block_size=block_size, cache_type=cache_type, **kwargs + ) + self.response: Optional[Response] = None + self.fs: HfFileSystem + + def seek(self, loc: int, whence: int = 0): + if loc == 0 and whence == 1: + return + if loc == self.loc and whence == 0: + return + raise ValueError("Cannot seek streaming HF file") + + def read(self, length: int = -1): + read_args = (length,) if length >= 0 else () + if self.response is None or self.response.raw.isclosed(): + url = hf_hub_url( + repo_id=self.resolved_path.repo_id, + revision=self.resolved_path.revision, + filename=self.resolved_path.path_in_repo, + repo_type=self.resolved_path.repo_type, + endpoint=self.fs.endpoint, + ) + self.response = http_backoff( + "GET", + url, + headers=self.fs._api._build_hf_headers(), + retry_on_status_codes=(502, 503, 504), + stream=True, + ) + hf_raise_for_status(self.response) + try: + out = self.response.raw.read(*read_args) + except Exception: + self.response.close() + + # Retry by recreating the connection + url = hf_hub_url( + repo_id=self.resolved_path.repo_id, + revision=self.resolved_path.revision, + filename=self.resolved_path.path_in_repo, + repo_type=self.resolved_path.repo_type, + endpoint=self.fs.endpoint, + ) + self.response = http_backoff( + "GET", + url, + headers={"Range": "bytes=%d-" % self.loc, **self.fs._api._build_hf_headers()}, + retry_on_status_codes=(502, 503, 504), + stream=True, + ) + hf_raise_for_status(self.response) + try: + out = self.response.raw.read(*read_args) + except Exception: + self.response.close() + raise + self.loc += len(out) + return out + + def url(self) -> str: + return self.fs.url(self.path) + + def __del__(self): + if not hasattr(self, "resolved_path"): + # Means that the constructor failed. Nothing to do. + return + return super().__del__() + + def __reduce__(self): + return reopen, (self.fs, self.path, self.mode, self.blocksize, self.cache.name) + + +def safe_revision(revision: str) -> str: + return revision if SPECIAL_REFS_REVISION_REGEX.match(revision) else safe_quote(revision) + + +def safe_quote(s: str) -> str: + return quote(s, safe="") + + +def _raise_file_not_found(path: str, err: Optional[Exception]) -> NoReturn: + msg = path + if isinstance(err, RepositoryNotFoundError): + msg = f"{path} (repository not found)" + elif isinstance(err, RevisionNotFoundError): + msg = f"{path} (revision not found)" + elif isinstance(err, HFValidationError): + msg = f"{path} (invalid repository id)" + raise FileNotFoundError(msg) from err + + +def reopen(fs: HfFileSystem, path: str, mode: str, block_size: int, cache_type: str): + return fs.open(path, mode=mode, block_size=block_size, cache_type=cache_type) diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference_api.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference_api.py new file mode 100644 index 0000000000000000000000000000000000000000..c889a6d8720a5242f50f81955916df3cb33357e1 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference_api.py @@ -0,0 +1,217 @@ +import io +from typing import Any, Dict, List, Optional, Union + +from .constants import INFERENCE_ENDPOINT +from .hf_api import HfApi +from .utils import build_hf_headers, get_session, is_pillow_available, logging, validate_hf_hub_args +from .utils._deprecation import _deprecate_method + + +logger = logging.get_logger(__name__) + + +ALL_TASKS = [ + # NLP + "text-classification", + "token-classification", + "table-question-answering", + "question-answering", + "zero-shot-classification", + "translation", + "summarization", + "conversational", + "feature-extraction", + "text-generation", + "text2text-generation", + "fill-mask", + "sentence-similarity", + # Audio + "text-to-speech", + "automatic-speech-recognition", + "audio-to-audio", + "audio-classification", + "voice-activity-detection", + # Computer vision + "image-classification", + "object-detection", + "image-segmentation", + "text-to-image", + "image-to-image", + # Others + "tabular-classification", + "tabular-regression", +] + + +class InferenceApi: + """Client to configure requests and make calls to the HuggingFace Inference API. + + Example: + + ```python + >>> from huggingface_hub.inference_api import InferenceApi + + >>> # Mask-fill example + >>> inference = InferenceApi("bert-base-uncased") + >>> inference(inputs="The goal of life is [MASK].") + [{'sequence': 'the goal of life is life.', 'score': 0.10933292657136917, 'token': 2166, 'token_str': 'life'}] + + >>> # Question Answering example + >>> inference = InferenceApi("deepset/roberta-base-squad2") + >>> inputs = { + ... "question": "What's my name?", + ... "context": "My name is Clara and I live in Berkeley.", + ... } + >>> inference(inputs) + {'score': 0.9326569437980652, 'start': 11, 'end': 16, 'answer': 'Clara'} + + >>> # Zero-shot example + >>> inference = InferenceApi("typeform/distilbert-base-uncased-mnli") + >>> inputs = "Hi, I recently bought a device from your company but it is not working as advertised and I would like to get reimbursed!" + >>> params = {"candidate_labels": ["refund", "legal", "faq"]} + >>> inference(inputs, params) + {'sequence': 'Hi, I recently bought a device from your company but it is not working as advertised and I would like to get reimbursed!', 'labels': ['refund', 'faq', 'legal'], 'scores': [0.9378499388694763, 0.04914155602455139, 0.013008488342165947]} + + >>> # Overriding configured task + >>> inference = InferenceApi("bert-base-uncased", task="feature-extraction") + + >>> # Text-to-image + >>> inference = InferenceApi("stabilityai/stable-diffusion-2-1") + >>> inference("cat") + + + >>> # Return as raw response to parse the output yourself + >>> inference = InferenceApi("mio/amadeus") + >>> response = inference("hello world", raw_response=True) + >>> response.headers + {"Content-Type": "audio/flac", ...} + >>> response.content # raw bytes from server + b'(...)' + ``` + """ + + @validate_hf_hub_args + @_deprecate_method( + version="1.0", + message=( + "`InferenceApi` client is deprecated in favor of the more feature-complete `InferenceClient`. Check out" + " this guide to learn how to convert your script to use it:" + " https://huggingface.co/docs/huggingface_hub/guides/inference#legacy-inferenceapi-client." + ), + ) + def __init__( + self, + repo_id: str, + task: Optional[str] = None, + token: Optional[str] = None, + gpu: bool = False, + ): + """Inits headers and API call information. + + Args: + repo_id (``str``): + Id of repository (e.g. `user/bert-base-uncased`). + task (``str``, `optional`, defaults ``None``): + Whether to force a task instead of using task specified in the + repository. + token (`str`, `optional`): + The API token to use as HTTP bearer authorization. This is not + the authentication token. You can find the token in + https://huggingface.co/settings/token. Alternatively, you can + find both your organizations and personal API tokens using + `HfApi().whoami(token)`. + gpu (`bool`, `optional`, defaults `False`): + Whether to use GPU instead of CPU for inference(requires Startup + plan at least). + """ + self.options = {"wait_for_model": True, "use_gpu": gpu} + self.headers = build_hf_headers(token=token) + + # Configure task + model_info = HfApi(token=token).model_info(repo_id=repo_id) + if not model_info.pipeline_tag and not task: + raise ValueError( + "Task not specified in the repository. Please add it to the model card" + " using pipeline_tag" + " (https://huggingface.co/docs#how-is-a-models-type-of-inference-api-and-widget-determined)" + ) + + if task and task != model_info.pipeline_tag: + if task not in ALL_TASKS: + raise ValueError(f"Invalid task {task}. Make sure it's valid.") + + logger.warning( + "You're using a different task than the one specified in the" + " repository. Be sure to know what you're doing :)" + ) + self.task = task + else: + assert model_info.pipeline_tag is not None, "Pipeline tag cannot be None" + self.task = model_info.pipeline_tag + + self.api_url = f"{INFERENCE_ENDPOINT}/pipeline/{self.task}/{repo_id}" + + def __repr__(self): + # Do not add headers to repr to avoid leaking token. + return f"InferenceAPI(api_url='{self.api_url}', task='{self.task}', options={self.options})" + + def __call__( + self, + inputs: Optional[Union[str, Dict, List[str], List[List[str]]]] = None, + params: Optional[Dict] = None, + data: Optional[bytes] = None, + raw_response: bool = False, + ) -> Any: + """Make a call to the Inference API. + + Args: + inputs (`str` or `Dict` or `List[str]` or `List[List[str]]`, *optional*): + Inputs for the prediction. + params (`Dict`, *optional*): + Additional parameters for the models. Will be sent as `parameters` in the + payload. + data (`bytes`, *optional*): + Bytes content of the request. In this case, leave `inputs` and `params` empty. + raw_response (`bool`, defaults to `False`): + If `True`, the raw `Response` object is returned. You can parse its content + as preferred. By default, the content is parsed into a more practical format + (json dictionary or PIL Image for example). + """ + # Build payload + payload: Dict[str, Any] = { + "options": self.options, + } + if inputs: + payload["inputs"] = inputs + if params: + payload["parameters"] = params + + # Make API call + response = get_session().post(self.api_url, headers=self.headers, json=payload, data=data) + + # Let the user handle the response + if raw_response: + return response + + # By default, parse the response for the user. + content_type = response.headers.get("Content-Type") or "" + if content_type.startswith("image"): + if not is_pillow_available(): + raise ImportError( + f"Task '{self.task}' returned as image but Pillow is not installed." + " Please install it (`pip install Pillow`) or pass" + " `raw_response=True` to get the raw `Response` object and parse" + " the image by yourself." + ) + + from PIL import Image + + return Image.open(io.BytesIO(response.content)) + elif content_type == "application/json": + return response.json() + else: + raise NotImplementedError( + f"{content_type} output type is not implemented yet. You can pass" + " `raw_response=True` to get the raw `Response` object and parse the" + " output by yourself." + ) diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/lfs.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/lfs.py new file mode 100644 index 0000000000000000000000000000000000000000..d6fb9e210b522ab6f6730a3ab52c90d0e692e9d5 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/lfs.py @@ -0,0 +1,541 @@ +# coding=utf-8 +# Copyright 2019-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Git LFS related type definitions and utilities""" + +import inspect +import io +import os +import re +import warnings +from contextlib import AbstractContextManager +from dataclasses import dataclass +from math import ceil +from os.path import getsize +from pathlib import Path +from typing import TYPE_CHECKING, BinaryIO, Dict, Iterable, List, Optional, Tuple, TypedDict +from urllib.parse import unquote + +from huggingface_hub.constants import ENDPOINT, HF_HUB_ENABLE_HF_TRANSFER, REPO_TYPES_URL_PREFIXES + +from .utils import ( + build_hf_headers, + fix_hf_endpoint_in_url, + get_session, + hf_raise_for_status, + http_backoff, + logging, + tqdm, + validate_hf_hub_args, +) +from .utils.sha import sha256, sha_fileobj + + +if TYPE_CHECKING: + from ._commit_api import CommitOperationAdd + +logger = logging.get_logger(__name__) + +OID_REGEX = re.compile(r"^[0-9a-f]{40}$") + +LFS_MULTIPART_UPLOAD_COMMAND = "lfs-multipart-upload" + +LFS_HEADERS = { + "Accept": "application/vnd.git-lfs+json", + "Content-Type": "application/vnd.git-lfs+json", +} + + +@dataclass +class UploadInfo: + """ + Dataclass holding required information to determine whether a blob + should be uploaded to the hub using the LFS protocol or the regular protocol + + Args: + sha256 (`bytes`): + SHA256 hash of the blob + size (`int`): + Size in bytes of the blob + sample (`bytes`): + First 512 bytes of the blob + """ + + sha256: bytes + size: int + sample: bytes + + @classmethod + def from_path(cls, path: str): + size = getsize(path) + with io.open(path, "rb") as file: + sample = file.peek(512)[:512] + sha = sha_fileobj(file) + return cls(size=size, sha256=sha, sample=sample) + + @classmethod + def from_bytes(cls, data: bytes): + sha = sha256(data).digest() + return cls(size=len(data), sample=data[:512], sha256=sha) + + @classmethod + def from_fileobj(cls, fileobj: BinaryIO): + sample = fileobj.read(512) + fileobj.seek(0, io.SEEK_SET) + sha = sha_fileobj(fileobj) + size = fileobj.tell() + fileobj.seek(0, io.SEEK_SET) + return cls(size=size, sha256=sha, sample=sample) + + +@validate_hf_hub_args +def post_lfs_batch_info( + upload_infos: Iterable[UploadInfo], + token: Optional[str], + repo_type: str, + repo_id: str, + revision: Optional[str] = None, + endpoint: Optional[str] = None, + headers: Optional[Dict[str, str]] = None, +) -> Tuple[List[dict], List[dict]]: + """ + Requests the LFS batch endpoint to retrieve upload instructions + + Learn more: https://github.com/git-lfs/git-lfs/blob/main/docs/api/batch.md + + Args: + upload_infos (`Iterable` of `UploadInfo`): + `UploadInfo` for the files that are being uploaded, typically obtained + from `CommitOperationAdd.upload_info` + repo_type (`str`): + Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`. + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + revision (`str`, *optional*): + The git revision to upload to. + headers (`dict`, *optional*): + Additional headers to include in the request + + Returns: + `LfsBatchInfo`: 2-tuple: + - First element is the list of upload instructions from the server + - Second element is an list of errors, if any + + Raises: + `ValueError`: If an argument is invalid or the server response is malformed + + `HTTPError`: If the server returned an error + """ + endpoint = endpoint if endpoint is not None else ENDPOINT + url_prefix = "" + if repo_type in REPO_TYPES_URL_PREFIXES: + url_prefix = REPO_TYPES_URL_PREFIXES[repo_type] + batch_url = f"{endpoint}/{url_prefix}{repo_id}.git/info/lfs/objects/batch" + payload: Dict = { + "operation": "upload", + "transfers": ["basic", "multipart"], + "objects": [ + { + "oid": upload.sha256.hex(), + "size": upload.size, + } + for upload in upload_infos + ], + "hash_algo": "sha256", + } + if revision is not None: + payload["ref"] = {"name": unquote(revision)} # revision has been previously 'quoted' + + headers = { + **LFS_HEADERS, + **build_hf_headers(token=token), + **(headers or {}), + } + resp = get_session().post(batch_url, headers=headers, json=payload) + hf_raise_for_status(resp) + batch_info = resp.json() + + objects = batch_info.get("objects", None) + if not isinstance(objects, list): + raise ValueError("Malformed response from server") + + return ( + [_validate_batch_actions(obj) for obj in objects if "error" not in obj], + [_validate_batch_error(obj) for obj in objects if "error" in obj], + ) + + +class PayloadPartT(TypedDict): + partNumber: int + etag: str + + +class CompletionPayloadT(TypedDict): + """Payload that will be sent to the Hub when uploading multi-part.""" + + oid: str + parts: List[PayloadPartT] + + +def lfs_upload( + operation: "CommitOperationAdd", + lfs_batch_action: Dict, + token: Optional[str] = None, + headers: Optional[Dict[str, str]] = None, + endpoint: Optional[str] = None, +) -> None: + """ + Handles uploading a given object to the Hub with the LFS protocol. + + Can be a No-op if the content of the file is already present on the hub large file storage. + + Args: + operation (`CommitOperationAdd`): + The add operation triggering this upload. + lfs_batch_action (`dict`): + Upload instructions from the LFS batch endpoint for this object. See [`~utils.lfs.post_lfs_batch_info`] for + more details. + headers (`dict`, *optional*): + Headers to include in the request, including authentication and user agent headers. + + Raises: + - `ValueError` if `lfs_batch_action` is improperly formatted + - `HTTPError` if the upload resulted in an error + """ + # 0. If LFS file is already present, skip upload + _validate_batch_actions(lfs_batch_action) + actions = lfs_batch_action.get("actions") + if actions is None: + # The file was already uploaded + logger.debug(f"Content of file {operation.path_in_repo} is already present upstream - skipping upload") + return + + # 1. Validate server response (check required keys in dict) + upload_action = lfs_batch_action["actions"]["upload"] + _validate_lfs_action(upload_action) + verify_action = lfs_batch_action["actions"].get("verify") + if verify_action is not None: + _validate_lfs_action(verify_action) + + # 2. Upload file (either single part or multi-part) + header = upload_action.get("header", {}) + chunk_size = header.get("chunk_size") + upload_url = fix_hf_endpoint_in_url(upload_action["href"], endpoint=endpoint) + if chunk_size is not None: + try: + chunk_size = int(chunk_size) + except (ValueError, TypeError): + raise ValueError( + f"Malformed response from LFS batch endpoint: `chunk_size` should be an integer. Got '{chunk_size}'." + ) + _upload_multi_part(operation=operation, header=header, chunk_size=chunk_size, upload_url=upload_url) + else: + _upload_single_part(operation=operation, upload_url=upload_url) + + # 3. Verify upload went well + if verify_action is not None: + _validate_lfs_action(verify_action) + verify_url = fix_hf_endpoint_in_url(verify_action["href"], endpoint) + verify_resp = get_session().post( + verify_url, + headers=build_hf_headers(token=token, headers=headers), + json={"oid": operation.upload_info.sha256.hex(), "size": operation.upload_info.size}, + ) + hf_raise_for_status(verify_resp) + logger.debug(f"{operation.path_in_repo}: Upload successful") + + +def _validate_lfs_action(lfs_action: dict): + """validates response from the LFS batch endpoint""" + if not ( + isinstance(lfs_action.get("href"), str) + and (lfs_action.get("header") is None or isinstance(lfs_action.get("header"), dict)) + ): + raise ValueError("lfs_action is improperly formatted") + return lfs_action + + +def _validate_batch_actions(lfs_batch_actions: dict): + """validates response from the LFS batch endpoint""" + if not (isinstance(lfs_batch_actions.get("oid"), str) and isinstance(lfs_batch_actions.get("size"), int)): + raise ValueError("lfs_batch_actions is improperly formatted") + + upload_action = lfs_batch_actions.get("actions", {}).get("upload") + verify_action = lfs_batch_actions.get("actions", {}).get("verify") + if upload_action is not None: + _validate_lfs_action(upload_action) + if verify_action is not None: + _validate_lfs_action(verify_action) + return lfs_batch_actions + + +def _validate_batch_error(lfs_batch_error: dict): + """validates response from the LFS batch endpoint""" + if not (isinstance(lfs_batch_error.get("oid"), str) and isinstance(lfs_batch_error.get("size"), int)): + raise ValueError("lfs_batch_error is improperly formatted") + error_info = lfs_batch_error.get("error") + if not ( + isinstance(error_info, dict) + and isinstance(error_info.get("message"), str) + and isinstance(error_info.get("code"), int) + ): + raise ValueError("lfs_batch_error is improperly formatted") + return lfs_batch_error + + +def _upload_single_part(operation: "CommitOperationAdd", upload_url: str) -> None: + """ + Uploads `fileobj` as a single PUT HTTP request (basic LFS transfer protocol) + + Args: + upload_url (`str`): + The URL to PUT the file to. + fileobj: + The file-like object holding the data to upload. + + Returns: `requests.Response` + + Raises: `requests.HTTPError` if the upload resulted in an error + """ + with operation.as_file(with_tqdm=True) as fileobj: + # S3 might raise a transient 500 error -> let's retry if that happens + response = http_backoff("PUT", upload_url, data=fileobj, retry_on_status_codes=(500, 502, 503, 504)) + hf_raise_for_status(response) + + +def _upload_multi_part(operation: "CommitOperationAdd", header: Dict, chunk_size: int, upload_url: str) -> None: + """ + Uploads file using HF multipart LFS transfer protocol. + """ + # 1. Get upload URLs for each part + sorted_parts_urls = _get_sorted_parts_urls(header=header, upload_info=operation.upload_info, chunk_size=chunk_size) + + # 2. Upload parts (either with hf_transfer or in pure Python) + use_hf_transfer = HF_HUB_ENABLE_HF_TRANSFER + if ( + HF_HUB_ENABLE_HF_TRANSFER + and not isinstance(operation.path_or_fileobj, str) + and not isinstance(operation.path_or_fileobj, Path) + ): + warnings.warn( + "hf_transfer is enabled but does not support uploading from bytes or BinaryIO, falling back to regular" + " upload" + ) + use_hf_transfer = False + + response_headers = ( + _upload_parts_hf_transfer(operation=operation, sorted_parts_urls=sorted_parts_urls, chunk_size=chunk_size) + if use_hf_transfer + else _upload_parts_iteratively(operation=operation, sorted_parts_urls=sorted_parts_urls, chunk_size=chunk_size) + ) + + # 3. Send completion request + completion_res = get_session().post( + upload_url, + json=_get_completion_payload(response_headers, operation.upload_info.sha256.hex()), + headers=LFS_HEADERS, + ) + hf_raise_for_status(completion_res) + + +def _get_sorted_parts_urls(header: Dict, upload_info: UploadInfo, chunk_size: int) -> List[str]: + sorted_part_upload_urls = [ + upload_url + for _, upload_url in sorted( + [ + (int(part_num, 10), upload_url) + for part_num, upload_url in header.items() + if part_num.isdigit() and len(part_num) > 0 + ], + key=lambda t: t[0], + ) + ] + num_parts = len(sorted_part_upload_urls) + if num_parts != ceil(upload_info.size / chunk_size): + raise ValueError("Invalid server response to upload large LFS file") + return sorted_part_upload_urls + + +def _get_completion_payload(response_headers: List[Dict], oid: str) -> CompletionPayloadT: + parts: List[PayloadPartT] = [] + for part_number, header in enumerate(response_headers): + etag = header.get("etag") + if etag is None or etag == "": + raise ValueError(f"Invalid etag (`{etag}`) returned for part {part_number + 1}") + parts.append( + { + "partNumber": part_number + 1, + "etag": etag, + } + ) + return {"oid": oid, "parts": parts} + + +def _upload_parts_iteratively( + operation: "CommitOperationAdd", sorted_parts_urls: List[str], chunk_size: int +) -> List[Dict]: + headers = [] + with operation.as_file(with_tqdm=True) as fileobj: + for part_idx, part_upload_url in enumerate(sorted_parts_urls): + with SliceFileObj( + fileobj, + seek_from=chunk_size * part_idx, + read_limit=chunk_size, + ) as fileobj_slice: + # S3 might raise a transient 500 error -> let's retry if that happens + part_upload_res = http_backoff( + "PUT", part_upload_url, data=fileobj_slice, retry_on_status_codes=(500, 502, 503, 504) + ) + hf_raise_for_status(part_upload_res) + headers.append(part_upload_res.headers) + return headers # type: ignore + + +def _upload_parts_hf_transfer( + operation: "CommitOperationAdd", sorted_parts_urls: List[str], chunk_size: int +) -> List[Dict]: + # Upload file using an external Rust-based package. Upload is faster but support less features (no progress bars). + try: + from hf_transfer import multipart_upload + except ImportError: + raise ValueError( + "Fast uploading using 'hf_transfer' is enabled (HF_HUB_ENABLE_HF_TRANSFER=1) but 'hf_transfer' package is" + " not available in your environment. Try `pip install hf_transfer`." + ) + + supports_callback = "callback" in inspect.signature(multipart_upload).parameters + if not supports_callback: + warnings.warn( + "You are using an outdated version of `hf_transfer`. Consider upgrading to latest version to enable progress bars using `pip install -U hf_transfer`." + ) + + total = operation.upload_info.size + desc = operation.path_in_repo + if len(desc) > 40: + desc = f"(…){desc[-40:]}" + + # set `disable=None` rather than `disable=False` by default to disable progress bar when no TTY attached + # see https://github.com/huggingface/huggingface_hub/pull/2000 + disable = True if (logger.getEffectiveLevel() == logging.NOTSET) else None + + with tqdm(unit="B", unit_scale=True, total=total, initial=0, desc=desc, disable=disable) as progress: + try: + output = multipart_upload( + file_path=operation.path_or_fileobj, + parts_urls=sorted_parts_urls, + chunk_size=chunk_size, + max_files=128, + parallel_failures=127, # could be removed + max_retries=5, + **({"callback": progress.update} if supports_callback else {}), + ) + except Exception as e: + raise RuntimeError( + "An error occurred while uploading using `hf_transfer`. Consider disabling HF_HUB_ENABLE_HF_TRANSFER for" + " better error handling." + ) from e + if not supports_callback: + progress.update(total) + return output + + +class SliceFileObj(AbstractContextManager): + """ + Utility context manager to read a *slice* of a seekable file-like object as a seekable, file-like object. + + This is NOT thread safe + + Inspired by stackoverflow.com/a/29838711/593036 + + Credits to @julien-c + + Args: + fileobj (`BinaryIO`): + A file-like object to slice. MUST implement `tell()` and `seek()` (and `read()` of course). + `fileobj` will be reset to its original position when exiting the context manager. + seek_from (`int`): + The start of the slice (offset from position 0 in bytes). + read_limit (`int`): + The maximum number of bytes to read from the slice. + + Attributes: + previous_position (`int`): + The previous position + + Examples: + + Reading 200 bytes with an offset of 128 bytes from a file (ie bytes 128 to 327): + ```python + >>> with open("path/to/file", "rb") as file: + ... with SliceFileObj(file, seek_from=128, read_limit=200) as fslice: + ... fslice.read(...) + ``` + + Reading a file in chunks of 512 bytes + ```python + >>> import os + >>> chunk_size = 512 + >>> file_size = os.getsize("path/to/file") + >>> with open("path/to/file", "rb") as file: + ... for chunk_idx in range(ceil(file_size / chunk_size)): + ... with SliceFileObj(file, seek_from=chunk_idx * chunk_size, read_limit=chunk_size) as fslice: + ... chunk = fslice.read(...) + + ``` + """ + + def __init__(self, fileobj: BinaryIO, seek_from: int, read_limit: int): + self.fileobj = fileobj + self.seek_from = seek_from + self.read_limit = read_limit + + def __enter__(self): + self._previous_position = self.fileobj.tell() + end_of_stream = self.fileobj.seek(0, os.SEEK_END) + self._len = min(self.read_limit, end_of_stream - self.seek_from) + # ^^ The actual number of bytes that can be read from the slice + self.fileobj.seek(self.seek_from, io.SEEK_SET) + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.fileobj.seek(self._previous_position, io.SEEK_SET) + + def read(self, n: int = -1): + pos = self.tell() + if pos >= self._len: + return b"" + remaining_amount = self._len - pos + data = self.fileobj.read(remaining_amount if n < 0 else min(n, remaining_amount)) + return data + + def tell(self) -> int: + return self.fileobj.tell() - self.seek_from + + def seek(self, offset: int, whence: int = os.SEEK_SET) -> int: + start = self.seek_from + end = start + self._len + if whence in (os.SEEK_SET, os.SEEK_END): + offset = start + offset if whence == os.SEEK_SET else end + offset + offset = max(start, min(offset, end)) + whence = os.SEEK_SET + elif whence == os.SEEK_CUR: + cur_pos = self.fileobj.tell() + offset = max(start - cur_pos, min(offset, end - cur_pos)) + else: + raise ValueError(f"whence value {whence} is not supported") + return self.fileobj.seek(offset, whence) - self.seek_from + + def __iter__(self): + yield self.read(n=4 * 1024 * 1024) diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/repocard.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/repocard.py new file mode 100644 index 0000000000000000000000000000000000000000..2ea7fc136cef1e9d78d3c4f44b1516a1ebe64158 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/repocard.py @@ -0,0 +1,828 @@ +import os +import re +from pathlib import Path +from typing import Any, Dict, Literal, Optional, Type, Union + +import requests +import yaml + +from huggingface_hub.file_download import hf_hub_download +from huggingface_hub.hf_api import upload_file +from huggingface_hub.repocard_data import ( + CardData, + DatasetCardData, + EvalResult, + ModelCardData, + SpaceCardData, + eval_results_to_model_index, + model_index_to_eval_results, +) +from huggingface_hub.utils import get_session, is_jinja_available, yaml_dump + +from .constants import REPOCARD_NAME +from .utils import EntryNotFoundError, SoftTemporaryDirectory, logging, validate_hf_hub_args + + +logger = logging.get_logger(__name__) + + +TEMPLATE_MODELCARD_PATH = Path(__file__).parent / "templates" / "modelcard_template.md" +TEMPLATE_DATASETCARD_PATH = Path(__file__).parent / "templates" / "datasetcard_template.md" + +# exact same regex as in the Hub server. Please keep in sync. +# See https://github.com/huggingface/moon-landing/blob/main/server/lib/ViewMarkdown.ts#L18 +REGEX_YAML_BLOCK = re.compile(r"^(\s*---[\r\n]+)([\S\s]*?)([\r\n]+---(\r\n|\n|$))") + + +class RepoCard: + card_data_class = CardData + default_template_path = TEMPLATE_MODELCARD_PATH + repo_type = "model" + + def __init__(self, content: str, ignore_metadata_errors: bool = False): + """Initialize a RepoCard from string content. The content should be a + Markdown file with a YAML block at the beginning and a Markdown body. + + Args: + content (`str`): The content of the Markdown file. + + Example: + ```python + >>> from huggingface_hub.repocard import RepoCard + >>> text = ''' + ... --- + ... language: en + ... license: mit + ... --- + ... + ... # My repo + ... ''' + >>> card = RepoCard(text) + >>> card.data.to_dict() + {'language': 'en', 'license': 'mit'} + >>> card.text + '\\n# My repo\\n' + + ``` + + Raises the following error: + + - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + when the content of the repo card metadata is not a dictionary. + + + """ + + # Set the content of the RepoCard, as well as underlying .data and .text attributes. + # See the `content` property setter for more details. + self.ignore_metadata_errors = ignore_metadata_errors + self.content = content + + @property + def content(self): + """The content of the RepoCard, including the YAML block and the Markdown body.""" + line_break = _detect_line_ending(self._content) or "\n" + return f"---{line_break}{self.data.to_yaml(line_break=line_break)}{line_break}---{line_break}{self.text}" + + @content.setter + def content(self, content: str): + """Set the content of the RepoCard.""" + self._content = content + + match = REGEX_YAML_BLOCK.search(content) + if match: + # Metadata found in the YAML block + yaml_block = match.group(2) + self.text = content[match.end() :] + data_dict = yaml.safe_load(yaml_block) + + if data_dict is None: + data_dict = {} + + # The YAML block's data should be a dictionary + if not isinstance(data_dict, dict): + raise ValueError("repo card metadata block should be a dict") + else: + # Model card without metadata... create empty metadata + logger.warning("Repo card metadata block was not found. Setting CardData to empty.") + data_dict = {} + self.text = content + + self.data = self.card_data_class(**data_dict, ignore_metadata_errors=self.ignore_metadata_errors) + + def __str__(self): + return self.content + + def save(self, filepath: Union[Path, str]): + r"""Save a RepoCard to a file. + + Args: + filepath (`Union[Path, str]`): Filepath to the markdown file to save. + + Example: + ```python + >>> from huggingface_hub.repocard import RepoCard + >>> card = RepoCard("---\nlanguage: en\n---\n# This is a test repo card") + >>> card.save("/tmp/test.md") + + ``` + """ + filepath = Path(filepath) + filepath.parent.mkdir(parents=True, exist_ok=True) + # Preserve newlines as in the existing file. + with open(filepath, mode="w", newline="", encoding="utf-8") as f: + f.write(str(self)) + + @classmethod + def load( + cls, + repo_id_or_path: Union[str, Path], + repo_type: Optional[str] = None, + token: Optional[str] = None, + ignore_metadata_errors: bool = False, + ): + """Initialize a RepoCard from a Hugging Face Hub repo's README.md or a local filepath. + + Args: + repo_id_or_path (`Union[str, Path]`): + The repo ID associated with a Hugging Face Hub repo or a local filepath. + repo_type (`str`, *optional*): + The type of Hugging Face repo to push to. Defaults to None, which will use use "model". Other options + are "dataset" and "space". Not used when loading from a local filepath. If this is called from a child + class, the default value will be the child class's `repo_type`. + token (`str`, *optional*): + Authentication token, obtained with `huggingface_hub.HfApi.login` method. Will default to the stored token. + ignore_metadata_errors (`str`): + If True, errors while parsing the metadata section will be ignored. Some information might be lost during + the process. Use it at your own risk. + + Returns: + [`huggingface_hub.repocard.RepoCard`]: The RepoCard (or subclass) initialized from the repo's + README.md file or filepath. + + Example: + ```python + >>> from huggingface_hub.repocard import RepoCard + >>> card = RepoCard.load("nateraw/food") + >>> assert card.data.tags == ["generated_from_trainer", "image-classification", "pytorch"] + + ``` + """ + + if Path(repo_id_or_path).exists(): + card_path = Path(repo_id_or_path) + elif isinstance(repo_id_or_path, str): + card_path = Path( + hf_hub_download( + repo_id_or_path, + REPOCARD_NAME, + repo_type=repo_type or cls.repo_type, + token=token, + ) + ) + else: + raise ValueError(f"Cannot load RepoCard: path not found on disk ({repo_id_or_path}).") + + # Preserve newlines in the existing file. + with card_path.open(mode="r", newline="", encoding="utf-8") as f: + return cls(f.read(), ignore_metadata_errors=ignore_metadata_errors) + + def validate(self, repo_type: Optional[str] = None): + """Validates card against Hugging Face Hub's card validation logic. + Using this function requires access to the internet, so it is only called + internally by [`huggingface_hub.repocard.RepoCard.push_to_hub`]. + + Args: + repo_type (`str`, *optional*, defaults to "model"): + The type of Hugging Face repo to push to. Options are "model", "dataset", and "space". + If this function is called from a child class, the default will be the child class's `repo_type`. + + + Raises the following errors: + + - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + if the card fails validation checks. + - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + if the request to the Hub API fails for any other reason. + + + """ + + # If repo type is provided, otherwise, use the repo type of the card. + repo_type = repo_type or self.repo_type + + body = { + "repoType": repo_type, + "content": str(self), + } + headers = {"Accept": "text/plain"} + + try: + r = get_session().post("https://huggingface.co/api/validate-yaml", body, headers=headers) + r.raise_for_status() + except requests.exceptions.HTTPError as exc: + if r.status_code == 400: + raise ValueError(r.text) + else: + raise exc + + def push_to_hub( + self, + repo_id: str, + token: Optional[str] = None, + repo_type: Optional[str] = None, + commit_message: Optional[str] = None, + commit_description: Optional[str] = None, + revision: Optional[str] = None, + create_pr: Optional[bool] = None, + parent_commit: Optional[str] = None, + ): + """Push a RepoCard to a Hugging Face Hub repo. + + Args: + repo_id (`str`): + The repo ID of the Hugging Face Hub repo to push to. Example: "nateraw/food". + token (`str`, *optional*): + Authentication token, obtained with `huggingface_hub.HfApi.login` method. Will default to + the stored token. + repo_type (`str`, *optional*, defaults to "model"): + The type of Hugging Face repo to push to. Options are "model", "dataset", and "space". If this + function is called by a child class, it will default to the child class's `repo_type`. + commit_message (`str`, *optional*): + The summary / title / first line of the generated commit. + commit_description (`str`, *optional*) + The description of the generated commit. + revision (`str`, *optional*): + The git revision to commit from. Defaults to the head of the `"main"` branch. + create_pr (`bool`, *optional*): + Whether or not to create a Pull Request with this commit. Defaults to `False`. + parent_commit (`str`, *optional*): + The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported. + If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`. + If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`. + Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be + especially useful if the repo is updated / committed to concurrently. + Returns: + `str`: URL of the commit which updated the card metadata. + """ + + # If repo type is provided, otherwise, use the repo type of the card. + repo_type = repo_type or self.repo_type + + # Validate card before pushing to hub + self.validate(repo_type=repo_type) + + with SoftTemporaryDirectory() as tmpdir: + tmp_path = Path(tmpdir) / REPOCARD_NAME + tmp_path.write_text(str(self)) + url = upload_file( + path_or_fileobj=str(tmp_path), + path_in_repo=REPOCARD_NAME, + repo_id=repo_id, + token=token, + repo_type=repo_type, + commit_message=commit_message, + commit_description=commit_description, + create_pr=create_pr, + revision=revision, + parent_commit=parent_commit, + ) + return url + + @classmethod + def from_template( + cls, + card_data: CardData, + template_path: Optional[str] = None, + template_str: Optional[str] = None, + **template_kwargs, + ): + """Initialize a RepoCard from a template. By default, it uses the default template. + + Templates are Jinja2 templates that can be customized by passing keyword arguments. + + Args: + card_data (`huggingface_hub.CardData`): + A huggingface_hub.CardData instance containing the metadata you want to include in the YAML + header of the repo card on the Hugging Face Hub. + template_path (`str`, *optional*): + A path to a markdown file with optional Jinja template variables that can be filled + in with `template_kwargs`. Defaults to the default template. + + Returns: + [`huggingface_hub.repocard.RepoCard`]: A RepoCard instance with the specified card data and content from the + template. + """ + if is_jinja_available(): + import jinja2 + else: + raise ImportError( + "Using RepoCard.from_template requires Jinja2 to be installed. Please" + " install it with `pip install Jinja2`." + ) + + kwargs = card_data.to_dict().copy() + kwargs.update(template_kwargs) # Template_kwargs have priority + + if template_path is not None: + template_str = Path(template_path).read_text() + if template_str is None: + template_str = Path(cls.default_template_path).read_text() + template = jinja2.Template(template_str) + content = template.render(card_data=card_data.to_yaml(), **kwargs) + return cls(content) + + +class ModelCard(RepoCard): + card_data_class = ModelCardData + default_template_path = TEMPLATE_MODELCARD_PATH + repo_type = "model" + + @classmethod + def from_template( # type: ignore # violates Liskov property but easier to use + cls, + card_data: ModelCardData, + template_path: Optional[str] = None, + template_str: Optional[str] = None, + **template_kwargs, + ): + """Initialize a ModelCard from a template. By default, it uses the default template, which can be found here: + https://github.com/huggingface/huggingface_hub/blob/main/src/huggingface_hub/templates/modelcard_template.md + + Templates are Jinja2 templates that can be customized by passing keyword arguments. + + Args: + card_data (`huggingface_hub.ModelCardData`): + A huggingface_hub.ModelCardData instance containing the metadata you want to include in the YAML + header of the model card on the Hugging Face Hub. + template_path (`str`, *optional*): + A path to a markdown file with optional Jinja template variables that can be filled + in with `template_kwargs`. Defaults to the default template. + + Returns: + [`huggingface_hub.ModelCard`]: A ModelCard instance with the specified card data and content from the + template. + + Example: + ```python + >>> from huggingface_hub import ModelCard, ModelCardData, EvalResult + + >>> # Using the Default Template + >>> card_data = ModelCardData( + ... language='en', + ... license='mit', + ... library_name='timm', + ... tags=['image-classification', 'resnet'], + ... datasets=['beans'], + ... metrics=['accuracy'], + ... ) + >>> card = ModelCard.from_template( + ... card_data, + ... model_description='This model does x + y...' + ... ) + + >>> # Including Evaluation Results + >>> card_data = ModelCardData( + ... language='en', + ... tags=['image-classification', 'resnet'], + ... eval_results=[ + ... EvalResult( + ... task_type='image-classification', + ... dataset_type='beans', + ... dataset_name='Beans', + ... metric_type='accuracy', + ... metric_value=0.9, + ... ), + ... ], + ... model_name='my-cool-model', + ... ) + >>> card = ModelCard.from_template(card_data) + + >>> # Using a Custom Template + >>> card_data = ModelCardData( + ... language='en', + ... tags=['image-classification', 'resnet'] + ... ) + >>> card = ModelCard.from_template( + ... card_data=card_data, + ... template_path='./src/huggingface_hub/templates/modelcard_template.md', + ... custom_template_var='custom value', # will be replaced in template if it exists + ... ) + + ``` + """ + return super().from_template(card_data, template_path, template_str, **template_kwargs) + + +class DatasetCard(RepoCard): + card_data_class = DatasetCardData + default_template_path = TEMPLATE_DATASETCARD_PATH + repo_type = "dataset" + + @classmethod + def from_template( # type: ignore # violates Liskov property but easier to use + cls, + card_data: DatasetCardData, + template_path: Optional[str] = None, + template_str: Optional[str] = None, + **template_kwargs, + ): + """Initialize a DatasetCard from a template. By default, it uses the default template, which can be found here: + https://github.com/huggingface/huggingface_hub/blob/main/src/huggingface_hub/templates/datasetcard_template.md + + Templates are Jinja2 templates that can be customized by passing keyword arguments. + + Args: + card_data (`huggingface_hub.DatasetCardData`): + A huggingface_hub.DatasetCardData instance containing the metadata you want to include in the YAML + header of the dataset card on the Hugging Face Hub. + template_path (`str`, *optional*): + A path to a markdown file with optional Jinja template variables that can be filled + in with `template_kwargs`. Defaults to the default template. + + Returns: + [`huggingface_hub.DatasetCard`]: A DatasetCard instance with the specified card data and content from the + template. + + Example: + ```python + >>> from huggingface_hub import DatasetCard, DatasetCardData + + >>> # Using the Default Template + >>> card_data = DatasetCardData( + ... language='en', + ... license='mit', + ... annotations_creators='crowdsourced', + ... task_categories=['text-classification'], + ... task_ids=['sentiment-classification', 'text-scoring'], + ... multilinguality='monolingual', + ... pretty_name='My Text Classification Dataset', + ... ) + >>> card = DatasetCard.from_template( + ... card_data, + ... pretty_name=card_data.pretty_name, + ... ) + + >>> # Using a Custom Template + >>> card_data = DatasetCardData( + ... language='en', + ... license='mit', + ... ) + >>> card = DatasetCard.from_template( + ... card_data=card_data, + ... template_path='./src/huggingface_hub/templates/datasetcard_template.md', + ... custom_template_var='custom value', # will be replaced in template if it exists + ... ) + + ``` + """ + return super().from_template(card_data, template_path, template_str, **template_kwargs) + + +class SpaceCard(RepoCard): + card_data_class = SpaceCardData + default_template_path = TEMPLATE_MODELCARD_PATH + repo_type = "space" + + +def _detect_line_ending(content: str) -> Literal["\r", "\n", "\r\n", None]: # noqa: F722 + """Detect the line ending of a string. Used by RepoCard to avoid making huge diff on newlines. + + Uses same implementation as in Hub server, keep it in sync. + + Returns: + str: The detected line ending of the string. + """ + cr = content.count("\r") + lf = content.count("\n") + crlf = content.count("\r\n") + if cr + lf == 0: + return None + if crlf == cr and crlf == lf: + return "\r\n" + if cr > lf: + return "\r" + else: + return "\n" + + +def metadata_load(local_path: Union[str, Path]) -> Optional[Dict]: + content = Path(local_path).read_text() + match = REGEX_YAML_BLOCK.search(content) + if match: + yaml_block = match.group(2) + data = yaml.safe_load(yaml_block) + if data is None or isinstance(data, dict): + return data + raise ValueError("repo card metadata block should be a dict") + else: + return None + + +def metadata_save(local_path: Union[str, Path], data: Dict) -> None: + """ + Save the metadata dict in the upper YAML part Trying to preserve newlines as + in the existing file. Docs about open() with newline="" parameter: + https://docs.python.org/3/library/functions.html?highlight=open#open Does + not work with "^M" linebreaks, which are replaced by \n + """ + line_break = "\n" + content = "" + # try to detect existing newline character + if os.path.exists(local_path): + with open(local_path, "r", newline="", encoding="utf8") as readme: + content = readme.read() + if isinstance(readme.newlines, tuple): + line_break = readme.newlines[0] + elif isinstance(readme.newlines, str): + line_break = readme.newlines + + # creates a new file if it not + with open(local_path, "w", newline="", encoding="utf8") as readme: + data_yaml = yaml_dump(data, sort_keys=False, line_break=line_break) + # sort_keys: keep dict order + match = REGEX_YAML_BLOCK.search(content) + if match: + output = content[: match.start()] + f"---{line_break}{data_yaml}---{line_break}" + content[match.end() :] + else: + output = f"---{line_break}{data_yaml}---{line_break}{content}" + + readme.write(output) + readme.close() + + +def metadata_eval_result( + *, + model_pretty_name: str, + task_pretty_name: str, + task_id: str, + metrics_pretty_name: str, + metrics_id: str, + metrics_value: Any, + dataset_pretty_name: str, + dataset_id: str, + metrics_config: Optional[str] = None, + metrics_verified: bool = False, + dataset_config: Optional[str] = None, + dataset_split: Optional[str] = None, + dataset_revision: Optional[str] = None, + metrics_verification_token: Optional[str] = None, +) -> Dict: + """ + Creates a metadata dict with the result from a model evaluated on a dataset. + + Args: + model_pretty_name (`str`): + The name of the model in natural language. + task_pretty_name (`str`): + The name of a task in natural language. + task_id (`str`): + Example: automatic-speech-recognition. A task id. + metrics_pretty_name (`str`): + A name for the metric in natural language. Example: Test WER. + metrics_id (`str`): + Example: wer. A metric id from https://hf.co/metrics. + metrics_value (`Any`): + The value from the metric. Example: 20.0 or "20.0 ± 1.2". + dataset_pretty_name (`str`): + The name of the dataset in natural language. + dataset_id (`str`): + Example: common_voice. A dataset id from https://hf.co/datasets. + metrics_config (`str`, *optional*): + The name of the metric configuration used in `load_metric()`. + Example: bleurt-large-512 in `load_metric("bleurt", "bleurt-large-512")`. + metrics_verified (`bool`, *optional*, defaults to `False`): + Indicates whether the metrics originate from Hugging Face's [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator) or not. Automatically computed by Hugging Face, do not set. + dataset_config (`str`, *optional*): + Example: fr. The name of the dataset configuration used in `load_dataset()`. + dataset_split (`str`, *optional*): + Example: test. The name of the dataset split used in `load_dataset()`. + dataset_revision (`str`, *optional*): + Example: 5503434ddd753f426f4b38109466949a1217c2bb. The name of the dataset dataset revision + used in `load_dataset()`. + metrics_verification_token (`bool`, *optional*): + A JSON Web Token that is used to verify whether the metrics originate from Hugging Face's [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator) or not. + + Returns: + `dict`: a metadata dict with the result from a model evaluated on a dataset. + + Example: + ```python + >>> from huggingface_hub import metadata_eval_result + >>> results = metadata_eval_result( + ... model_pretty_name="RoBERTa fine-tuned on ReactionGIF", + ... task_pretty_name="Text Classification", + ... task_id="text-classification", + ... metrics_pretty_name="Accuracy", + ... metrics_id="accuracy", + ... metrics_value=0.2662102282047272, + ... dataset_pretty_name="ReactionJPEG", + ... dataset_id="julien-c/reactionjpeg", + ... dataset_config="default", + ... dataset_split="test", + ... ) + >>> results == { + ... 'model-index': [ + ... { + ... 'name': 'RoBERTa fine-tuned on ReactionGIF', + ... 'results': [ + ... { + ... 'task': { + ... 'type': 'text-classification', + ... 'name': 'Text Classification' + ... }, + ... 'dataset': { + ... 'name': 'ReactionJPEG', + ... 'type': 'julien-c/reactionjpeg', + ... 'config': 'default', + ... 'split': 'test' + ... }, + ... 'metrics': [ + ... { + ... 'type': 'accuracy', + ... 'value': 0.2662102282047272, + ... 'name': 'Accuracy', + ... 'verified': False + ... } + ... ] + ... } + ... ] + ... } + ... ] + ... } + True + + ``` + """ + + return { + "model-index": eval_results_to_model_index( + model_name=model_pretty_name, + eval_results=[ + EvalResult( + task_name=task_pretty_name, + task_type=task_id, + metric_name=metrics_pretty_name, + metric_type=metrics_id, + metric_value=metrics_value, + dataset_name=dataset_pretty_name, + dataset_type=dataset_id, + metric_config=metrics_config, + verified=metrics_verified, + verify_token=metrics_verification_token, + dataset_config=dataset_config, + dataset_split=dataset_split, + dataset_revision=dataset_revision, + ) + ], + ) + } + + +@validate_hf_hub_args +def metadata_update( + repo_id: str, + metadata: Dict, + *, + repo_type: Optional[str] = None, + overwrite: bool = False, + token: Optional[str] = None, + commit_message: Optional[str] = None, + commit_description: Optional[str] = None, + revision: Optional[str] = None, + create_pr: bool = False, + parent_commit: Optional[str] = None, +) -> str: + """ + Updates the metadata in the README.md of a repository on the Hugging Face Hub. + If the README.md file doesn't exist yet, a new one is created with metadata and an + the default ModelCard or DatasetCard template. For `space` repo, an error is thrown + as a Space cannot exist without a `README.md` file. + + Args: + repo_id (`str`): + The name of the repository. + metadata (`dict`): + A dictionary containing the metadata to be updated. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if updating to a dataset or space, + `None` or `"model"` if updating to a model. Default is `None`. + overwrite (`bool`, *optional*, defaults to `False`): + If set to `True` an existing field can be overwritten, otherwise + attempting to overwrite an existing field will cause an error. + token (`str`, *optional*): + The Hugging Face authentication token. + commit_message (`str`, *optional*): + The summary / title / first line of the generated commit. Defaults to + `f"Update metadata with huggingface_hub"` + commit_description (`str` *optional*) + The description of the generated commit + revision (`str`, *optional*): + The git revision to commit from. Defaults to the head of the + `"main"` branch. + create_pr (`boolean`, *optional*): + Whether or not to create a Pull Request from `revision` with that commit. + Defaults to `False`. + parent_commit (`str`, *optional*): + The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported. + If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`. + If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`. + Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be + especially useful if the repo is updated / committed to concurrently. + Returns: + `str`: URL of the commit which updated the card metadata. + + Example: + ```python + >>> from huggingface_hub import metadata_update + >>> metadata = {'model-index': [{'name': 'RoBERTa fine-tuned on ReactionGIF', + ... 'results': [{'dataset': {'name': 'ReactionGIF', + ... 'type': 'julien-c/reactiongif'}, + ... 'metrics': [{'name': 'Recall', + ... 'type': 'recall', + ... 'value': 0.7762102282047272}], + ... 'task': {'name': 'Text Classification', + ... 'type': 'text-classification'}}]}]} + >>> url = metadata_update("hf-internal-testing/reactiongif-roberta-card", metadata) + + ``` + """ + commit_message = commit_message if commit_message is not None else "Update metadata with huggingface_hub" + + # Card class given repo_type + card_class: Type[RepoCard] + if repo_type is None or repo_type == "model": + card_class = ModelCard + elif repo_type == "dataset": + card_class = DatasetCard + elif repo_type == "space": + card_class = RepoCard + else: + raise ValueError(f"Unknown repo_type: {repo_type}") + + # Either load repo_card from the Hub or create an empty one. + # NOTE: Will not create the repo if it doesn't exist. + try: + card = card_class.load(repo_id, token=token, repo_type=repo_type) + except EntryNotFoundError: + if repo_type == "space": + raise ValueError("Cannot update metadata on a Space that doesn't contain a `README.md` file.") + + # Initialize a ModelCard or DatasetCard from default template and no data. + card = card_class.from_template(CardData()) + + for key, value in metadata.items(): + if key == "model-index": + # if the new metadata doesn't include a name, either use existing one or repo name + if "name" not in value[0]: + value[0]["name"] = getattr(card, "model_name", repo_id) + model_name, new_results = model_index_to_eval_results(value) + if card.data.eval_results is None: + card.data.eval_results = new_results + card.data.model_name = model_name + else: + existing_results = card.data.eval_results + + # Iterate over new results + # Iterate over existing results + # If both results describe the same metric but value is different: + # If overwrite=True: overwrite the metric value + # Else: raise ValueError + # Else: append new result to existing ones. + for new_result in new_results: + result_found = False + for existing_result in existing_results: + if new_result.is_equal_except_value(existing_result): + if new_result != existing_result and not overwrite: + raise ValueError( + "You passed a new value for the existing metric" + f" 'name: {new_result.metric_name}, type: " + f"{new_result.metric_type}'. Set `overwrite=True`" + " to overwrite existing metrics." + ) + result_found = True + existing_result.metric_value = new_result.metric_value + if existing_result.verified is True: + existing_result.verify_token = new_result.verify_token + if not result_found: + card.data.eval_results.append(new_result) + else: + # Any metadata that is not a result metric + if card.data.get(key) is not None and not overwrite and card.data.get(key) != value: + raise ValueError( + f"You passed a new value for the existing meta data field '{key}'." + " Set `overwrite=True` to overwrite existing metadata." + ) + else: + card.data[key] = value + + return card.push_to_hub( + repo_id, + token=token, + repo_type=repo_type, + commit_message=commit_message, + commit_description=commit_description, + create_pr=create_pr, + revision=revision, + parent_commit=parent_commit, + ) diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/repository.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/repository.py new file mode 100644 index 0000000000000000000000000000000000000000..d7aff2eb66318803ee8c2fa4e3cccb29e0036801 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/repository.py @@ -0,0 +1,1476 @@ +import atexit +import os +import re +import subprocess +import threading +import time +from contextlib import contextmanager +from pathlib import Path +from typing import Callable, Dict, Iterator, List, Optional, Tuple, TypedDict, Union +from urllib.parse import urlparse + +from huggingface_hub.constants import REPO_TYPES_URL_PREFIXES, REPOCARD_NAME +from huggingface_hub.repocard import metadata_load, metadata_save + +from .hf_api import HfApi, repo_type_and_id_from_hf_id +from .lfs import LFS_MULTIPART_UPLOAD_COMMAND +from .utils import ( + SoftTemporaryDirectory, + get_token, + logging, + run_subprocess, + tqdm, + validate_hf_hub_args, +) +from .utils._deprecation import _deprecate_method + + +logger = logging.get_logger(__name__) + + +class CommandInProgress: + """ + Utility to follow commands launched asynchronously. + """ + + def __init__( + self, + title: str, + is_done_method: Callable, + status_method: Callable, + process: subprocess.Popen, + post_method: Optional[Callable] = None, + ): + self.title = title + self._is_done = is_done_method + self._status = status_method + self._process = process + self._stderr = "" + self._stdout = "" + self._post_method = post_method + + @property + def is_done(self) -> bool: + """ + Whether the process is done. + """ + result = self._is_done() + + if result and self._post_method is not None: + self._post_method() + self._post_method = None + + return result + + @property + def status(self) -> int: + """ + The exit code/status of the current action. Will return `0` if the + command has completed successfully, and a number between 1 and 255 if + the process errored-out. + + Will return -1 if the command is still ongoing. + """ + return self._status() + + @property + def failed(self) -> bool: + """ + Whether the process errored-out. + """ + return self.status > 0 + + @property + def stderr(self) -> str: + """ + The current output message on the standard error. + """ + if self._process.stderr is not None: + self._stderr += self._process.stderr.read() + return self._stderr + + @property + def stdout(self) -> str: + """ + The current output message on the standard output. + """ + if self._process.stdout is not None: + self._stdout += self._process.stdout.read() + return self._stdout + + def __repr__(self): + status = self.status + + if status == -1: + status = "running" + + return ( + f"[{self.title} command, status code: {status}," + f" {'in progress.' if not self.is_done else 'finished.'} PID:" + f" {self._process.pid}]" + ) + + +def is_git_repo(folder: Union[str, Path]) -> bool: + """ + Check if the folder is the root or part of a git repository + + Args: + folder (`str`): + The folder in which to run the command. + + Returns: + `bool`: `True` if the repository is part of a repository, `False` + otherwise. + """ + folder_exists = os.path.exists(os.path.join(folder, ".git")) + git_branch = subprocess.run("git branch".split(), cwd=folder, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + return folder_exists and git_branch.returncode == 0 + + +def is_local_clone(folder: Union[str, Path], remote_url: str) -> bool: + """ + Check if the folder is a local clone of the remote_url + + Args: + folder (`str` or `Path`): + The folder in which to run the command. + remote_url (`str`): + The url of a git repository. + + Returns: + `bool`: `True` if the repository is a local clone of the remote + repository specified, `False` otherwise. + """ + if not is_git_repo(folder): + return False + + remotes = run_subprocess("git remote -v", folder).stdout + + # Remove token for the test with remotes. + remote_url = re.sub(r"https://.*@", "https://", remote_url) + remotes = [re.sub(r"https://.*@", "https://", remote) for remote in remotes.split()] + return remote_url in remotes + + +def is_tracked_with_lfs(filename: Union[str, Path]) -> bool: + """ + Check if the file passed is tracked with git-lfs. + + Args: + filename (`str` or `Path`): + The filename to check. + + Returns: + `bool`: `True` if the file passed is tracked with git-lfs, `False` + otherwise. + """ + folder = Path(filename).parent + filename = Path(filename).name + + try: + p = run_subprocess("git check-attr -a".split() + [filename], folder) + attributes = p.stdout.strip() + except subprocess.CalledProcessError as exc: + if not is_git_repo(folder): + return False + else: + raise OSError(exc.stderr) + + if len(attributes) == 0: + return False + + found_lfs_tag = {"diff": False, "merge": False, "filter": False} + + for attribute in attributes.split("\n"): + for tag in found_lfs_tag.keys(): + if tag in attribute and "lfs" in attribute: + found_lfs_tag[tag] = True + + return all(found_lfs_tag.values()) + + +def is_git_ignored(filename: Union[str, Path]) -> bool: + """ + Check if file is git-ignored. Supports nested .gitignore files. + + Args: + filename (`str` or `Path`): + The filename to check. + + Returns: + `bool`: `True` if the file passed is ignored by `git`, `False` + otherwise. + """ + folder = Path(filename).parent + filename = Path(filename).name + + try: + p = run_subprocess("git check-ignore".split() + [filename], folder, check=False) + # Will return exit code 1 if not gitignored + is_ignored = not bool(p.returncode) + except subprocess.CalledProcessError as exc: + raise OSError(exc.stderr) + + return is_ignored + + +def is_binary_file(filename: Union[str, Path]) -> bool: + """ + Check if file is a binary file. + + Args: + filename (`str` or `Path`): + The filename to check. + + Returns: + `bool`: `True` if the file passed is a binary file, `False` otherwise. + """ + try: + with open(filename, "rb") as f: + content = f.read(10 * (1024**2)) # Read a maximum of 10MB + + # Code sample taken from the following stack overflow thread + # https://stackoverflow.com/questions/898669/how-can-i-detect-if-a-file-is-binary-non-text-in-python/7392391#7392391 + text_chars = bytearray({7, 8, 9, 10, 12, 13, 27} | set(range(0x20, 0x100)) - {0x7F}) + return bool(content.translate(None, text_chars)) + except UnicodeDecodeError: + return True + + +def files_to_be_staged(pattern: str = ".", folder: Union[str, Path, None] = None) -> List[str]: + """ + Returns a list of filenames that are to be staged. + + Args: + pattern (`str` or `Path`): + The pattern of filenames to check. Put `.` to get all files. + folder (`str` or `Path`): + The folder in which to run the command. + + Returns: + `List[str]`: List of files that are to be staged. + """ + try: + p = run_subprocess("git ls-files --exclude-standard -mo".split() + [pattern], folder) + if len(p.stdout.strip()): + files = p.stdout.strip().split("\n") + else: + files = [] + except subprocess.CalledProcessError as exc: + raise EnvironmentError(exc.stderr) + + return files + + +def is_tracked_upstream(folder: Union[str, Path]) -> bool: + """ + Check if the current checked-out branch is tracked upstream. + + Args: + folder (`str` or `Path`): + The folder in which to run the command. + + Returns: + `bool`: `True` if the current checked-out branch is tracked upstream, + `False` otherwise. + """ + try: + run_subprocess("git rev-parse --symbolic-full-name --abbrev-ref @{u}", folder) + return True + except subprocess.CalledProcessError as exc: + if "HEAD" in exc.stderr: + raise OSError("No branch checked out") + + return False + + +def commits_to_push(folder: Union[str, Path], upstream: Optional[str] = None) -> int: + """ + Check the number of commits that would be pushed upstream + + Args: + folder (`str` or `Path`): + The folder in which to run the command. + upstream (`str`, *optional*): + The name of the upstream repository with which the comparison should be + made. + + Returns: + `int`: Number of commits that would be pushed upstream were a `git + push` to proceed. + """ + try: + result = run_subprocess(f"git cherry -v {upstream or ''}", folder) + return len(result.stdout.split("\n")) - 1 + except subprocess.CalledProcessError as exc: + raise EnvironmentError(exc.stderr) + + +class PbarT(TypedDict): + # Used to store an opened progress bar in `_lfs_log_progress` + bar: tqdm + past_bytes: int + + +@contextmanager +def _lfs_log_progress(): + """ + This is a context manager that will log the Git LFS progress of cleaning, + smudging, pulling and pushing. + """ + + if logger.getEffectiveLevel() >= logging.ERROR: + try: + yield + except Exception: + pass + return + + def output_progress(stopping_event: threading.Event): + """ + To be launched as a separate thread with an event meaning it should stop + the tail. + """ + # Key is tuple(state, filename), value is a dict(tqdm bar and a previous value) + pbars: Dict[Tuple[str, str], PbarT] = {} + + def close_pbars(): + for pbar in pbars.values(): + pbar["bar"].update(pbar["bar"].total - pbar["past_bytes"]) + pbar["bar"].refresh() + pbar["bar"].close() + + def tail_file(filename) -> Iterator[str]: + """ + Creates a generator to be iterated through, which will return each + line one by one. Will stop tailing the file if the stopping_event is + set. + """ + with open(filename, "r") as file: + current_line = "" + while True: + if stopping_event.is_set(): + close_pbars() + break + + line_bit = file.readline() + if line_bit is not None and not len(line_bit.strip()) == 0: + current_line += line_bit + if current_line.endswith("\n"): + yield current_line + current_line = "" + else: + time.sleep(1) + + # If the file isn't created yet, wait for a few seconds before trying again. + # Can be interrupted with the stopping_event. + while not os.path.exists(os.environ["GIT_LFS_PROGRESS"]): + if stopping_event.is_set(): + close_pbars() + return + + time.sleep(2) + + for line in tail_file(os.environ["GIT_LFS_PROGRESS"]): + try: + state, file_progress, byte_progress, filename = line.split() + except ValueError as error: + # Try/except to ease debugging. See https://github.com/huggingface/huggingface_hub/issues/1373. + raise ValueError(f"Cannot unpack LFS progress line:\n{line}") from error + description = f"{state.capitalize()} file {filename}" + + current_bytes, total_bytes = byte_progress.split("/") + current_bytes_int = int(current_bytes) + total_bytes_int = int(total_bytes) + + pbar = pbars.get((state, filename)) + if pbar is None: + # Initialize progress bar + pbars[(state, filename)] = { + "bar": tqdm( + desc=description, + initial=current_bytes_int, + total=total_bytes_int, + unit="B", + unit_scale=True, + unit_divisor=1024, + ), + "past_bytes": int(current_bytes), + } + else: + # Update progress bar + pbar["bar"].update(current_bytes_int - pbar["past_bytes"]) + pbar["past_bytes"] = current_bytes_int + + current_lfs_progress_value = os.environ.get("GIT_LFS_PROGRESS", "") + + with SoftTemporaryDirectory() as tmpdir: + os.environ["GIT_LFS_PROGRESS"] = os.path.join(tmpdir, "lfs_progress") + logger.debug(f"Following progress in {os.environ['GIT_LFS_PROGRESS']}") + + exit_event = threading.Event() + x = threading.Thread(target=output_progress, args=(exit_event,), daemon=True) + x.start() + + try: + yield + finally: + exit_event.set() + x.join() + + os.environ["GIT_LFS_PROGRESS"] = current_lfs_progress_value + + +class Repository: + """ + Helper class to wrap the git and git-lfs commands. + + The aim is to facilitate interacting with huggingface.co hosted model or + dataset repos, though not a lot here (if any) is actually specific to + huggingface.co. + + + + [`Repository`] is deprecated in favor of the http-based alternatives implemented in + [`HfApi`]. Given its large adoption in legacy code, the complete removal of + [`Repository`] will only happen in release `v1.0`. For more details, please read + https://huggingface.co/docs/huggingface_hub/concepts/git_vs_http. + + + """ + + command_queue: List[CommandInProgress] + + @validate_hf_hub_args + @_deprecate_method( + version="1.0", + message=( + "Please prefer the http-based alternatives instead. Given its large adoption in legacy code, the complete" + " removal is only planned on next major release.\nFor more details, please read" + " https://huggingface.co/docs/huggingface_hub/concepts/git_vs_http." + ), + ) + def __init__( + self, + local_dir: Union[str, Path], + clone_from: Optional[str] = None, + repo_type: Optional[str] = None, + token: Union[bool, str] = True, + git_user: Optional[str] = None, + git_email: Optional[str] = None, + revision: Optional[str] = None, + skip_lfs_files: bool = False, + client: Optional[HfApi] = None, + ): + """ + Instantiate a local clone of a git repo. + + If `clone_from` is set, the repo will be cloned from an existing remote repository. + If the remote repo does not exist, a `EnvironmentError` exception will be thrown. + Please create the remote repo first using [`create_repo`]. + + `Repository` uses the local git credentials by default. If explicitly set, the `token` + or the `git_user`/`git_email` pair will be used instead. + + Args: + local_dir (`str` or `Path`): + path (e.g. `'my_trained_model/'`) to the local directory, where + the `Repository` will be initialized. + clone_from (`str`, *optional*): + Either a repository url or `repo_id`. + Example: + - `"https://huggingface.co/philschmid/playground-tests"` + - `"philschmid/playground-tests"` + repo_type (`str`, *optional*): + To set when cloning a repo from a repo_id. Default is model. + token (`bool` or `str`, *optional*): + A valid authentication token (see https://huggingface.co/settings/token). + If `None` or `True` and machine is logged in (through `huggingface-cli login` + or [`~huggingface_hub.login`]), token will be retrieved from the cache. + If `False`, token is not sent in the request header. + git_user (`str`, *optional*): + will override the `git config user.name` for committing and + pushing files to the hub. + git_email (`str`, *optional*): + will override the `git config user.email` for committing and + pushing files to the hub. + revision (`str`, *optional*): + Revision to checkout after initializing the repository. If the + revision doesn't exist, a branch will be created with that + revision name from the default branch's current HEAD. + skip_lfs_files (`bool`, *optional*, defaults to `False`): + whether to skip git-LFS files or not. + client (`HfApi`, *optional*): + Instance of [`HfApi`] to use when calling the HF Hub API. A new + instance will be created if this is left to `None`. + + Raises: + - [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError) + if the remote repository set in `clone_from` does not exist. + """ + if isinstance(local_dir, Path): + local_dir = str(local_dir) + os.makedirs(local_dir, exist_ok=True) + self.local_dir = os.path.join(os.getcwd(), local_dir) + self._repo_type = repo_type + self.command_queue = [] + self.skip_lfs_files = skip_lfs_files + self.client = client if client is not None else HfApi() + + self.check_git_versions() + + if isinstance(token, str): + self.huggingface_token: Optional[str] = token + elif token is False: + self.huggingface_token = None + else: + # if `True` -> explicit use of the cached token + # if `None` -> implicit use of the cached token + self.huggingface_token = get_token() + + if clone_from is not None: + self.clone_from(repo_url=clone_from) + else: + if is_git_repo(self.local_dir): + logger.debug("[Repository] is a valid git repo") + else: + raise ValueError("If not specifying `clone_from`, you need to pass Repository a valid git clone.") + + if self.huggingface_token is not None and (git_email is None or git_user is None): + user = self.client.whoami(self.huggingface_token) + + if git_email is None: + git_email = user["email"] + + if git_user is None: + git_user = user["fullname"] + + if git_user is not None or git_email is not None: + self.git_config_username_and_email(git_user, git_email) + + self.lfs_enable_largefiles() + self.git_credential_helper_store() + + if revision is not None: + self.git_checkout(revision, create_branch_ok=True) + + # This ensures that all commands exit before exiting the Python runtime. + # This will ensure all pushes register on the hub, even if other errors happen in subsequent operations. + atexit.register(self.wait_for_commands) + + @property + def current_branch(self) -> str: + """ + Returns the current checked out branch. + + Returns: + `str`: Current checked out branch. + """ + try: + result = run_subprocess("git rev-parse --abbrev-ref HEAD", self.local_dir).stdout.strip() + except subprocess.CalledProcessError as exc: + raise EnvironmentError(exc.stderr) + + return result + + def check_git_versions(self): + """ + Checks that `git` and `git-lfs` can be run. + + Raises: + - [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError) + if `git` or `git-lfs` are not installed. + """ + try: + git_version = run_subprocess("git --version", self.local_dir).stdout.strip() + except FileNotFoundError: + raise EnvironmentError("Looks like you do not have git installed, please install.") + + try: + lfs_version = run_subprocess("git-lfs --version", self.local_dir).stdout.strip() + except FileNotFoundError: + raise EnvironmentError( + "Looks like you do not have git-lfs installed, please install." + " You can install from https://git-lfs.github.com/." + " Then run `git lfs install` (you only have to do this once)." + ) + logger.info(git_version + "\n" + lfs_version) + + @validate_hf_hub_args + def clone_from(self, repo_url: str, token: Union[bool, str, None] = None): + """ + Clone from a remote. If the folder already exists, will try to clone the + repository within it. + + If this folder is a git repository with linked history, will try to + update the repository. + + Args: + repo_url (`str`): + The URL from which to clone the repository + token (`Union[str, bool]`, *optional*): + Whether to use the authentication token. It can be: + - a string which is the token itself + - `False`, which would not use the authentication token + - `True`, which would fetch the authentication token from the + local folder and use it (you should be logged in for this to + work). + - `None`, which would retrieve the value of + `self.huggingface_token`. + + + + Raises the following error: + + - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + if an organization token (starts with "api_org") is passed. Use must use + your own personal access token (see https://hf.co/settings/tokens). + + - [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError) + if you are trying to clone the repository in a non-empty folder, or if the + `git` operations raise errors. + + + """ + token = ( + token # str -> use it + if isinstance(token, str) + else ( + None # `False` -> explicit no token + if token is False + else self.huggingface_token # `None` or `True` -> use default + ) + ) + if token is not None and token.startswith("api_org"): + raise ValueError( + "You must use your personal access token, not an Organization token" + " (see https://hf.co/settings/tokens)." + ) + + hub_url = self.client.endpoint + if hub_url in repo_url or ("http" not in repo_url and len(repo_url.split("/")) <= 2): + repo_type, namespace, repo_name = repo_type_and_id_from_hf_id(repo_url, hub_url=hub_url) + repo_id = f"{namespace}/{repo_name}" if namespace is not None else repo_name + + if repo_type is not None: + self._repo_type = repo_type + + repo_url = hub_url + "/" + + if self._repo_type in REPO_TYPES_URL_PREFIXES: + repo_url += REPO_TYPES_URL_PREFIXES[self._repo_type] + + if token is not None: + # Add token in git url when provided + scheme = urlparse(repo_url).scheme + repo_url = repo_url.replace(f"{scheme}://", f"{scheme}://user:{token}@") + + repo_url += repo_id + + # For error messages, it's cleaner to show the repo url without the token. + clean_repo_url = re.sub(r"(https?)://.*@", r"\1://", repo_url) + try: + run_subprocess("git lfs install", self.local_dir) + + # checks if repository is initialized in a empty repository or in one with files + if len(os.listdir(self.local_dir)) == 0: + logger.warning(f"Cloning {clean_repo_url} into local empty directory.") + + with _lfs_log_progress(): + env = os.environ.copy() + + if self.skip_lfs_files: + env.update({"GIT_LFS_SKIP_SMUDGE": "1"}) + + run_subprocess( + # 'git lfs clone' is deprecated (will display a warning in the terminal) + # but we still use it as it provides a nicer UX when downloading large + # files (shows progress). + f"{'git clone' if self.skip_lfs_files else 'git lfs clone'} {repo_url} .", + self.local_dir, + env=env, + ) + else: + # Check if the folder is the root of a git repository + if not is_git_repo(self.local_dir): + raise EnvironmentError( + "Tried to clone a repository in a non-empty folder that isn't" + f" a git repository ('{self.local_dir}'). If you really want to" + f" do this, do it manually:\n cd {self.local_dir} && git init" + " && git remote add origin && git pull origin main\n or clone" + " repo to a new folder and move your existing files there" + " afterwards." + ) + + if is_local_clone(self.local_dir, repo_url): + logger.warning( + f"{self.local_dir} is already a clone of {clean_repo_url}." + " Make sure you pull the latest changes with" + " `repo.git_pull()`." + ) + else: + output = run_subprocess("git remote get-url origin", self.local_dir, check=False) + + error_msg = ( + f"Tried to clone {clean_repo_url} in an unrelated git" + " repository.\nIf you believe this is an error, please add" + f" a remote with the following URL: {clean_repo_url}." + ) + if output.returncode == 0: + clean_local_remote_url = re.sub(r"https://.*@", "https://", output.stdout) + error_msg += f"\nLocal path has its origin defined as: {clean_local_remote_url}" + raise EnvironmentError(error_msg) + + except subprocess.CalledProcessError as exc: + raise EnvironmentError(exc.stderr) + + def git_config_username_and_email(self, git_user: Optional[str] = None, git_email: Optional[str] = None): + """ + Sets git username and email (only in the current repo). + + Args: + git_user (`str`, *optional*): + The username to register through `git`. + git_email (`str`, *optional*): + The email to register through `git`. + """ + try: + if git_user is not None: + run_subprocess("git config user.name".split() + [git_user], self.local_dir) + + if git_email is not None: + run_subprocess(f"git config user.email {git_email}".split(), self.local_dir) + except subprocess.CalledProcessError as exc: + raise EnvironmentError(exc.stderr) + + def git_credential_helper_store(self): + """ + Sets the git credential helper to `store` + """ + try: + run_subprocess("git config credential.helper store", self.local_dir) + except subprocess.CalledProcessError as exc: + raise EnvironmentError(exc.stderr) + + def git_head_hash(self) -> str: + """ + Get commit sha on top of HEAD. + + Returns: + `str`: The current checked out commit SHA. + """ + try: + p = run_subprocess("git rev-parse HEAD", self.local_dir) + return p.stdout.strip() + except subprocess.CalledProcessError as exc: + raise EnvironmentError(exc.stderr) + + def git_remote_url(self) -> str: + """ + Get URL to origin remote. + + Returns: + `str`: The URL of the `origin` remote. + """ + try: + p = run_subprocess("git config --get remote.origin.url", self.local_dir) + url = p.stdout.strip() + # Strip basic auth info. + return re.sub(r"https://.*@", "https://", url) + except subprocess.CalledProcessError as exc: + raise EnvironmentError(exc.stderr) + + def git_head_commit_url(self) -> str: + """ + Get URL to last commit on HEAD. We assume it's been pushed, and the url + scheme is the same one as for GitHub or HuggingFace. + + Returns: + `str`: The URL to the current checked-out commit. + """ + sha = self.git_head_hash() + url = self.git_remote_url() + if url.endswith("/"): + url = url[:-1] + return f"{url}/commit/{sha}" + + def list_deleted_files(self) -> List[str]: + """ + Returns a list of the files that are deleted in the working directory or + index. + + Returns: + `List[str]`: A list of files that have been deleted in the working + directory or index. + """ + try: + git_status = run_subprocess("git status -s", self.local_dir).stdout.strip() + except subprocess.CalledProcessError as exc: + raise EnvironmentError(exc.stderr) + + if len(git_status) == 0: + return [] + + # Receives a status like the following + # D .gitignore + # D new_file.json + # AD new_file1.json + # ?? new_file2.json + # ?? new_file4.json + + # Strip each line of whitespaces + modified_files_statuses = [status.strip() for status in git_status.split("\n")] + + # Only keep files that are deleted using the D prefix + deleted_files_statuses = [status for status in modified_files_statuses if "D" in status.split()[0]] + + # Remove the D prefix and strip to keep only the relevant filename + deleted_files = [status.split()[-1].strip() for status in deleted_files_statuses] + + return deleted_files + + def lfs_track(self, patterns: Union[str, List[str]], filename: bool = False): + """ + Tell git-lfs to track files according to a pattern. + + Setting the `filename` argument to `True` will treat the arguments as + literal filenames, not as patterns. Any special glob characters in the + filename will be escaped when writing to the `.gitattributes` file. + + Args: + patterns (`Union[str, List[str]]`): + The pattern, or list of patterns, to track with git-lfs. + filename (`bool`, *optional*, defaults to `False`): + Whether to use the patterns as literal filenames. + """ + if isinstance(patterns, str): + patterns = [patterns] + try: + for pattern in patterns: + run_subprocess( + f"git lfs track {'--filename' if filename else ''} {pattern}", + self.local_dir, + ) + except subprocess.CalledProcessError as exc: + raise EnvironmentError(exc.stderr) + + def lfs_untrack(self, patterns: Union[str, List[str]]): + """ + Tell git-lfs to untrack those files. + + Args: + patterns (`Union[str, List[str]]`): + The pattern, or list of patterns, to untrack with git-lfs. + """ + if isinstance(patterns, str): + patterns = [patterns] + try: + for pattern in patterns: + run_subprocess("git lfs untrack".split() + [pattern], self.local_dir) + except subprocess.CalledProcessError as exc: + raise EnvironmentError(exc.stderr) + + def lfs_enable_largefiles(self): + """ + HF-specific. This enables upload support of files >5GB. + """ + try: + lfs_config = "git config lfs.customtransfer.multipart" + run_subprocess(f"{lfs_config}.path huggingface-cli", self.local_dir) + run_subprocess( + f"{lfs_config}.args {LFS_MULTIPART_UPLOAD_COMMAND}", + self.local_dir, + ) + except subprocess.CalledProcessError as exc: + raise EnvironmentError(exc.stderr) + + def auto_track_binary_files(self, pattern: str = ".") -> List[str]: + """ + Automatically track binary files with git-lfs. + + Args: + pattern (`str`, *optional*, defaults to "."): + The pattern with which to track files that are binary. + + Returns: + `List[str]`: List of filenames that are now tracked due to being + binary files + """ + files_to_be_tracked_with_lfs = [] + + deleted_files = self.list_deleted_files() + + for filename in files_to_be_staged(pattern, folder=self.local_dir): + if filename in deleted_files: + continue + + path_to_file = os.path.join(os.getcwd(), self.local_dir, filename) + + if not (is_tracked_with_lfs(path_to_file) or is_git_ignored(path_to_file)): + size_in_mb = os.path.getsize(path_to_file) / (1024 * 1024) + + if size_in_mb >= 10: + logger.warning( + "Parsing a large file to check if binary or not. Tracking large" + " files using `repository.auto_track_large_files` is" + " recommended so as to not load the full file in memory." + ) + + is_binary = is_binary_file(path_to_file) + + if is_binary: + self.lfs_track(filename) + files_to_be_tracked_with_lfs.append(filename) + + # Cleanup the .gitattributes if files were deleted + self.lfs_untrack(deleted_files) + + return files_to_be_tracked_with_lfs + + def auto_track_large_files(self, pattern: str = ".") -> List[str]: + """ + Automatically track large files (files that weigh more than 10MBs) with + git-lfs. + + Args: + pattern (`str`, *optional*, defaults to "."): + The pattern with which to track files that are above 10MBs. + + Returns: + `List[str]`: List of filenames that are now tracked due to their + size. + """ + files_to_be_tracked_with_lfs = [] + + deleted_files = self.list_deleted_files() + + for filename in files_to_be_staged(pattern, folder=self.local_dir): + if filename in deleted_files: + continue + + path_to_file = os.path.join(os.getcwd(), self.local_dir, filename) + size_in_mb = os.path.getsize(path_to_file) / (1024 * 1024) + + if size_in_mb >= 10 and not is_tracked_with_lfs(path_to_file) and not is_git_ignored(path_to_file): + self.lfs_track(filename) + files_to_be_tracked_with_lfs.append(filename) + + # Cleanup the .gitattributes if files were deleted + self.lfs_untrack(deleted_files) + + return files_to_be_tracked_with_lfs + + def lfs_prune(self, recent=False): + """ + git lfs prune + + Args: + recent (`bool`, *optional*, defaults to `False`): + Whether to prune files even if they were referenced by recent + commits. See the following + [link](https://github.com/git-lfs/git-lfs/blob/f3d43f0428a84fc4f1e5405b76b5a73ec2437e65/docs/man/git-lfs-prune.1.ronn#recent-files) + for more information. + """ + try: + with _lfs_log_progress(): + result = run_subprocess(f"git lfs prune {'--recent' if recent else ''}", self.local_dir) + logger.info(result.stdout) + except subprocess.CalledProcessError as exc: + raise EnvironmentError(exc.stderr) + + def git_pull(self, rebase: bool = False, lfs: bool = False): + """ + git pull + + Args: + rebase (`bool`, *optional*, defaults to `False`): + Whether to rebase the current branch on top of the upstream + branch after fetching. + lfs (`bool`, *optional*, defaults to `False`): + Whether to fetch the LFS files too. This option only changes the + behavior when a repository was cloned without fetching the LFS + files; calling `repo.git_pull(lfs=True)` will then fetch the LFS + file from the remote repository. + """ + command = "git pull" if not lfs else "git lfs pull" + if rebase: + command += " --rebase" + try: + with _lfs_log_progress(): + result = run_subprocess(command, self.local_dir) + logger.info(result.stdout) + except subprocess.CalledProcessError as exc: + raise EnvironmentError(exc.stderr) + + def git_add(self, pattern: str = ".", auto_lfs_track: bool = False): + """ + git add + + Setting the `auto_lfs_track` parameter to `True` will automatically + track files that are larger than 10MB with `git-lfs`. + + Args: + pattern (`str`, *optional*, defaults to "."): + The pattern with which to add files to staging. + auto_lfs_track (`bool`, *optional*, defaults to `False`): + Whether to automatically track large and binary files with + git-lfs. Any file over 10MB in size, or in binary format, will + be automatically tracked. + """ + if auto_lfs_track: + # Track files according to their size (>=10MB) + tracked_files = self.auto_track_large_files(pattern) + + # Read the remaining files and track them if they're binary + tracked_files.extend(self.auto_track_binary_files(pattern)) + + if tracked_files: + logger.warning( + f"Adding files tracked by Git LFS: {tracked_files}. This may take a" + " bit of time if the files are large." + ) + + try: + result = run_subprocess("git add -v".split() + [pattern], self.local_dir) + logger.info(f"Adding to index:\n{result.stdout}\n") + except subprocess.CalledProcessError as exc: + raise EnvironmentError(exc.stderr) + + def git_commit(self, commit_message: str = "commit files to HF hub"): + """ + git commit + + Args: + commit_message (`str`, *optional*, defaults to "commit files to HF hub"): + The message attributed to the commit. + """ + try: + result = run_subprocess("git commit -v -m".split() + [commit_message], self.local_dir) + logger.info(f"Committed:\n{result.stdout}\n") + except subprocess.CalledProcessError as exc: + if len(exc.stderr) > 0: + raise EnvironmentError(exc.stderr) + else: + raise EnvironmentError(exc.stdout) + + def git_push( + self, + upstream: Optional[str] = None, + blocking: bool = True, + auto_lfs_prune: bool = False, + ) -> Union[str, Tuple[str, CommandInProgress]]: + """ + git push + + If used without setting `blocking`, will return url to commit on remote + repo. If used with `blocking=True`, will return a tuple containing the + url to commit and the command object to follow for information about the + process. + + Args: + upstream (`str`, *optional*): + Upstream to which this should push. If not specified, will push + to the lastly defined upstream or to the default one (`origin + main`). + blocking (`bool`, *optional*, defaults to `True`): + Whether the function should return only when the push has + finished. Setting this to `False` will return an + `CommandInProgress` object which has an `is_done` property. This + property will be set to `True` when the push is finished. + auto_lfs_prune (`bool`, *optional*, defaults to `False`): + Whether to automatically prune files once they have been pushed + to the remote. + """ + command = "git push" + + if upstream: + command += f" --set-upstream {upstream}" + + number_of_commits = commits_to_push(self.local_dir, upstream) + + if number_of_commits > 1: + logger.warning(f"Several commits ({number_of_commits}) will be pushed upstream.") + if blocking: + logger.warning("The progress bars may be unreliable.") + + try: + with _lfs_log_progress(): + process = subprocess.Popen( + command.split(), + stderr=subprocess.PIPE, + stdout=subprocess.PIPE, + encoding="utf-8", + cwd=self.local_dir, + ) + + if blocking: + stdout, stderr = process.communicate() + return_code = process.poll() + process.kill() + + if len(stderr): + logger.warning(stderr) + + if return_code: + raise subprocess.CalledProcessError(return_code, process.args, output=stdout, stderr=stderr) + + except subprocess.CalledProcessError as exc: + raise EnvironmentError(exc.stderr) + + if not blocking: + + def status_method(): + status = process.poll() + if status is None: + return -1 + else: + return status + + command_in_progress = CommandInProgress( + "push", + is_done_method=lambda: process.poll() is not None, + status_method=status_method, + process=process, + post_method=self.lfs_prune if auto_lfs_prune else None, + ) + + self.command_queue.append(command_in_progress) + + return self.git_head_commit_url(), command_in_progress + + if auto_lfs_prune: + self.lfs_prune() + + return self.git_head_commit_url() + + def git_checkout(self, revision: str, create_branch_ok: bool = False): + """ + git checkout a given revision + + Specifying `create_branch_ok` to `True` will create the branch to the + given revision if that revision doesn't exist. + + Args: + revision (`str`): + The revision to checkout. + create_branch_ok (`str`, *optional*, defaults to `False`): + Whether creating a branch named with the `revision` passed at + the current checked-out reference if `revision` isn't an + existing revision is allowed. + """ + try: + result = run_subprocess(f"git checkout {revision}", self.local_dir) + logger.warning(f"Checked out {revision} from {self.current_branch}.") + logger.warning(result.stdout) + except subprocess.CalledProcessError as exc: + if not create_branch_ok: + raise EnvironmentError(exc.stderr) + else: + try: + result = run_subprocess(f"git checkout -b {revision}", self.local_dir) + logger.warning( + f"Revision `{revision}` does not exist. Created and checked out branch `{revision}`." + ) + logger.warning(result.stdout) + except subprocess.CalledProcessError as exc: + raise EnvironmentError(exc.stderr) + + def tag_exists(self, tag_name: str, remote: Optional[str] = None) -> bool: + """ + Check if a tag exists or not. + + Args: + tag_name (`str`): + The name of the tag to check. + remote (`str`, *optional*): + Whether to check if the tag exists on a remote. This parameter + should be the identifier of the remote. + + Returns: + `bool`: Whether the tag exists. + """ + if remote: + try: + result = run_subprocess(f"git ls-remote origin refs/tags/{tag_name}", self.local_dir).stdout.strip() + except subprocess.CalledProcessError as exc: + raise EnvironmentError(exc.stderr) + + return len(result) != 0 + else: + try: + git_tags = run_subprocess("git tag", self.local_dir).stdout.strip() + except subprocess.CalledProcessError as exc: + raise EnvironmentError(exc.stderr) + + git_tags = git_tags.split("\n") + return tag_name in git_tags + + def delete_tag(self, tag_name: str, remote: Optional[str] = None) -> bool: + """ + Delete a tag, both local and remote, if it exists + + Args: + tag_name (`str`): + The tag name to delete. + remote (`str`, *optional*): + The remote on which to delete the tag. + + Returns: + `bool`: `True` if deleted, `False` if the tag didn't exist. + If remote is not passed, will just be updated locally + """ + delete_locally = True + delete_remotely = True + + if not self.tag_exists(tag_name): + delete_locally = False + + if not self.tag_exists(tag_name, remote=remote): + delete_remotely = False + + if delete_locally: + try: + run_subprocess(["git", "tag", "-d", tag_name], self.local_dir).stdout.strip() + except subprocess.CalledProcessError as exc: + raise EnvironmentError(exc.stderr) + + if remote and delete_remotely: + try: + run_subprocess(f"git push {remote} --delete {tag_name}", self.local_dir).stdout.strip() + except subprocess.CalledProcessError as exc: + raise EnvironmentError(exc.stderr) + + return True + + def add_tag(self, tag_name: str, message: Optional[str] = None, remote: Optional[str] = None): + """ + Add a tag at the current head and push it + + If remote is None, will just be updated locally + + If no message is provided, the tag will be lightweight. if a message is + provided, the tag will be annotated. + + Args: + tag_name (`str`): + The name of the tag to be added. + message (`str`, *optional*): + The message that accompanies the tag. The tag will turn into an + annotated tag if a message is passed. + remote (`str`, *optional*): + The remote on which to add the tag. + """ + if message: + tag_args = ["git", "tag", "-a", tag_name, "-m", message] + else: + tag_args = ["git", "tag", tag_name] + + try: + run_subprocess(tag_args, self.local_dir).stdout.strip() + except subprocess.CalledProcessError as exc: + raise EnvironmentError(exc.stderr) + + if remote: + try: + run_subprocess(f"git push {remote} {tag_name}", self.local_dir).stdout.strip() + except subprocess.CalledProcessError as exc: + raise EnvironmentError(exc.stderr) + + def is_repo_clean(self) -> bool: + """ + Return whether or not the git status is clean or not + + Returns: + `bool`: `True` if the git status is clean, `False` otherwise. + """ + try: + git_status = run_subprocess("git status --porcelain", self.local_dir).stdout.strip() + except subprocess.CalledProcessError as exc: + raise EnvironmentError(exc.stderr) + + return len(git_status) == 0 + + def push_to_hub( + self, + commit_message: str = "commit files to HF hub", + blocking: bool = True, + clean_ok: bool = True, + auto_lfs_prune: bool = False, + ) -> Union[None, str, Tuple[str, CommandInProgress]]: + """ + Helper to add, commit, and push files to remote repository on the + HuggingFace Hub. Will automatically track large files (>10MB). + + Args: + commit_message (`str`): + Message to use for the commit. + blocking (`bool`, *optional*, defaults to `True`): + Whether the function should return only when the `git push` has + finished. + clean_ok (`bool`, *optional*, defaults to `True`): + If True, this function will return None if the repo is + untouched. Default behavior is to fail because the git command + fails. + auto_lfs_prune (`bool`, *optional*, defaults to `False`): + Whether to automatically prune files once they have been pushed + to the remote. + """ + if clean_ok and self.is_repo_clean(): + logger.info("Repo currently clean. Ignoring push_to_hub") + return None + self.git_add(auto_lfs_track=True) + self.git_commit(commit_message) + return self.git_push( + upstream=f"origin {self.current_branch}", + blocking=blocking, + auto_lfs_prune=auto_lfs_prune, + ) + + @contextmanager + def commit( + self, + commit_message: str, + branch: Optional[str] = None, + track_large_files: bool = True, + blocking: bool = True, + auto_lfs_prune: bool = False, + ): + """ + Context manager utility to handle committing to a repository. This + automatically tracks large files (>10Mb) with git-lfs. Set the + `track_large_files` argument to `False` if you wish to ignore that + behavior. + + Args: + commit_message (`str`): + Message to use for the commit. + branch (`str`, *optional*): + The branch on which the commit will appear. This branch will be + checked-out before any operation. + track_large_files (`bool`, *optional*, defaults to `True`): + Whether to automatically track large files or not. Will do so by + default. + blocking (`bool`, *optional*, defaults to `True`): + Whether the function should return only when the `git push` has + finished. + auto_lfs_prune (`bool`, defaults to `True`): + Whether to automatically prune files once they have been pushed + to the remote. + + Examples: + + ```python + >>> with Repository( + ... "text-files", + ... clone_from="/text-files", + ... token=True, + >>> ).commit("My first file :)"): + ... with open("file.txt", "w+") as f: + ... f.write(json.dumps({"hey": 8})) + + >>> import torch + + >>> model = torch.nn.Transformer() + >>> with Repository( + ... "torch-model", + ... clone_from="/torch-model", + ... token=True, + >>> ).commit("My cool model :)"): + ... torch.save(model.state_dict(), "model.pt") + ``` + + """ + + files_to_stage = files_to_be_staged(".", folder=self.local_dir) + + if len(files_to_stage): + files_in_msg = str(files_to_stage[:5])[:-1] + ", ...]" if len(files_to_stage) > 5 else str(files_to_stage) + logger.error( + "There exists some updated files in the local repository that are not" + f" committed: {files_in_msg}. This may lead to errors if checking out" + " a branch. These files and their modifications will be added to the" + " current commit." + ) + + if branch is not None: + self.git_checkout(branch, create_branch_ok=True) + + if is_tracked_upstream(self.local_dir): + logger.warning("Pulling changes ...") + self.git_pull(rebase=True) + else: + logger.warning(f"The current branch has no upstream branch. Will push to 'origin {self.current_branch}'") + + current_working_directory = os.getcwd() + os.chdir(os.path.join(current_working_directory, self.local_dir)) + + try: + yield self + finally: + self.git_add(auto_lfs_track=track_large_files) + + try: + self.git_commit(commit_message) + except OSError as e: + # If no changes are detected, there is nothing to commit. + if "nothing to commit" not in str(e): + raise e + + try: + self.git_push( + upstream=f"origin {self.current_branch}", + blocking=blocking, + auto_lfs_prune=auto_lfs_prune, + ) + except OSError as e: + # If no changes are detected, there is nothing to commit. + if "could not read Username" in str(e): + raise OSError("Couldn't authenticate user for push. Did you set `token` to `True`?") from e + else: + raise e + + os.chdir(current_working_directory) + + def repocard_metadata_load(self) -> Optional[Dict]: + filepath = os.path.join(self.local_dir, REPOCARD_NAME) + if os.path.isfile(filepath): + return metadata_load(filepath) + return None + + def repocard_metadata_save(self, data: Dict) -> None: + return metadata_save(os.path.join(self.local_dir, REPOCARD_NAME), data) + + @property + def commands_failed(self): + """ + Returns the asynchronous commands that failed. + """ + return [c for c in self.command_queue if c.status > 0] + + @property + def commands_in_progress(self): + """ + Returns the asynchronous commands that are currently in progress. + """ + return [c for c in self.command_queue if not c.is_done] + + def wait_for_commands(self): + """ + Blocking method: blocks all subsequent execution until all commands have + been processed. + """ + index = 0 + for command_failed in self.commands_failed: + logger.error(f"The {command_failed.title} command with PID {command_failed._process.pid} failed.") + logger.error(command_failed.stderr) + + while self.commands_in_progress: + if index % 10 == 0: + logger.warning( + f"Waiting for the following commands to finish before shutting down: {self.commands_in_progress}." + ) + + index += 1 + + time.sleep(1) diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/templates/datasetcard_template.md b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/templates/datasetcard_template.md new file mode 100644 index 0000000000000000000000000000000000000000..9af29ebbed93653ec74a8952e314e7554323ef15 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/templates/datasetcard_template.md @@ -0,0 +1,143 @@ +--- +# For reference on dataset card metadata, see the spec: https://github.com/huggingface/hub-docs/blob/main/datasetcard.md?plain=1 +# Doc / guide: https://huggingface.co/docs/hub/datasets-cards +{{ card_data }} +--- + +# Dataset Card for {{ pretty_name | default("Dataset Name", true) }} + + + +{{ dataset_summary | default("", true) }} + +## Dataset Details + +### Dataset Description + + + +{{ dataset_description | default("", true) }} + +- **Curated by:** {{ curators | default("[More Information Needed]", true)}} +- **Funded by [optional]:** {{ funded_by | default("[More Information Needed]", true)}} +- **Shared by [optional]:** {{ shared_by | default("[More Information Needed]", true)}} +- **Language(s) (NLP):** {{ language | default("[More Information Needed]", true)}} +- **License:** {{ license | default("[More Information Needed]", true)}} + +### Dataset Sources [optional] + + + +- **Repository:** {{ repo | default("[More Information Needed]", true)}} +- **Paper [optional]:** {{ paper | default("[More Information Needed]", true)}} +- **Demo [optional]:** {{ demo | default("[More Information Needed]", true)}} + +## Uses + + + +### Direct Use + + + +{{ direct_use | default("[More Information Needed]", true)}} + +### Out-of-Scope Use + + + +{{ out_of_scope_use | default("[More Information Needed]", true)}} + +## Dataset Structure + + + +{{ dataset_structure | default("[More Information Needed]", true)}} + +## Dataset Creation + +### Curation Rationale + + + +{{ curation_rationale_section | default("[More Information Needed]", true)}} + +### Source Data + + + +#### Data Collection and Processing + + + +{{ data_collection_and_processing_section | default("[More Information Needed]", true)}} + +#### Who are the source data producers? + + + +{{ source_data_producers_section | default("[More Information Needed]", true)}} + +### Annotations [optional] + + + +#### Annotation process + + + +{{ annotation_process_section | default("[More Information Needed]", true)}} + +#### Who are the annotators? + + + +{{ who_are_annotators_section | default("[More Information Needed]", true)}} + +#### Personal and Sensitive Information + + + +{{ personal_and_sensitive_information | default("[More Information Needed]", true)}} + +## Bias, Risks, and Limitations + + + +{{ bias_risks_limitations | default("[More Information Needed]", true)}} + +### Recommendations + + + +{{ bias_recommendations | default("Users should be made aware of the risks, biases and limitations of the dataset. More information needed for further recommendations.", true)}} + +## Citation [optional] + + + +**BibTeX:** + +{{ citation_bibtex | default("[More Information Needed]", true)}} + +**APA:** + +{{ citation_apa | default("[More Information Needed]", true)}} + +## Glossary [optional] + + + +{{ glossary | default("[More Information Needed]", true)}} + +## More Information [optional] + +{{ more_information | default("[More Information Needed]", true)}} + +## Dataset Card Authors [optional] + +{{ dataset_card_authors | default("[More Information Needed]", true)}} + +## Dataset Card Contact + +{{ dataset_card_contact | default("[More Information Needed]", true)}} diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/templates/modelcard_template.md b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/templates/modelcard_template.md new file mode 100644 index 0000000000000000000000000000000000000000..79ca15e4547debac763b390ef8e4b715e6f6403f --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/templates/modelcard_template.md @@ -0,0 +1,200 @@ +--- +# For reference on model card metadata, see the spec: https://github.com/huggingface/hub-docs/blob/main/modelcard.md?plain=1 +# Doc / guide: https://huggingface.co/docs/hub/model-cards +{{ card_data }} +--- + +# Model Card for {{ model_id | default("Model ID", true) }} + + + +{{ model_summary | default("", true) }} + +## Model Details + +### Model Description + + + +{{ model_description | default("", true) }} + +- **Developed by:** {{ developers | default("[More Information Needed]", true)}} +- **Funded by [optional]:** {{ funded_by | default("[More Information Needed]", true)}} +- **Shared by [optional]:** {{ shared_by | default("[More Information Needed]", true)}} +- **Model type:** {{ model_type | default("[More Information Needed]", true)}} +- **Language(s) (NLP):** {{ language | default("[More Information Needed]", true)}} +- **License:** {{ license | default("[More Information Needed]", true)}} +- **Finetuned from model [optional]:** {{ base_model | default("[More Information Needed]", true)}} + +### Model Sources [optional] + + + +- **Repository:** {{ repo | default("[More Information Needed]", true)}} +- **Paper [optional]:** {{ paper | default("[More Information Needed]", true)}} +- **Demo [optional]:** {{ demo | default("[More Information Needed]", true)}} + +## Uses + + + +### Direct Use + + + +{{ direct_use | default("[More Information Needed]", true)}} + +### Downstream Use [optional] + + + +{{ downstream_use | default("[More Information Needed]", true)}} + +### Out-of-Scope Use + + + +{{ out_of_scope_use | default("[More Information Needed]", true)}} + +## Bias, Risks, and Limitations + + + +{{ bias_risks_limitations | default("[More Information Needed]", true)}} + +### Recommendations + + + +{{ bias_recommendations | default("Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.", true)}} + +## How to Get Started with the Model + +Use the code below to get started with the model. + +{{ get_started_code | default("[More Information Needed]", true)}} + +## Training Details + +### Training Data + + + +{{ training_data | default("[More Information Needed]", true)}} + +### Training Procedure + + + +#### Preprocessing [optional] + +{{ preprocessing | default("[More Information Needed]", true)}} + + +#### Training Hyperparameters + +- **Training regime:** {{ training_regime | default("[More Information Needed]", true)}} + +#### Speeds, Sizes, Times [optional] + + + +{{ speeds_sizes_times | default("[More Information Needed]", true)}} + +## Evaluation + + + +### Testing Data, Factors & Metrics + +#### Testing Data + + + +{{ testing_data | default("[More Information Needed]", true)}} + +#### Factors + + + +{{ testing_factors | default("[More Information Needed]", true)}} + +#### Metrics + + + +{{ testing_metrics | default("[More Information Needed]", true)}} + +### Results + +{{ results | default("[More Information Needed]", true)}} + +#### Summary + +{{ results_summary | default("", true) }} + +## Model Examination [optional] + + + +{{ model_examination | default("[More Information Needed]", true)}} + +## Environmental Impact + + + +Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700). + +- **Hardware Type:** {{ hardware_type | default("[More Information Needed]", true)}} +- **Hours used:** {{ hours_used | default("[More Information Needed]", true)}} +- **Cloud Provider:** {{ cloud_provider | default("[More Information Needed]", true)}} +- **Compute Region:** {{ cloud_region | default("[More Information Needed]", true)}} +- **Carbon Emitted:** {{ co2_emitted | default("[More Information Needed]", true)}} + +## Technical Specifications [optional] + +### Model Architecture and Objective + +{{ model_specs | default("[More Information Needed]", true)}} + +### Compute Infrastructure + +{{ compute_infrastructure | default("[More Information Needed]", true)}} + +#### Hardware + +{{ hardware_requirements | default("[More Information Needed]", true)}} + +#### Software + +{{ software | default("[More Information Needed]", true)}} + +## Citation [optional] + + + +**BibTeX:** + +{{ citation_bibtex | default("[More Information Needed]", true)}} + +**APA:** + +{{ citation_apa | default("[More Information Needed]", true)}} + +## Glossary [optional] + + + +{{ glossary | default("[More Information Needed]", true)}} + +## More Information [optional] + +{{ more_information | default("[More Information Needed]", true)}} + +## Model Card Authors [optional] + +{{ model_card_authors | default("[More Information Needed]", true)}} + +## Model Card Contact + +{{ model_card_contact | default("[More Information Needed]", true)}} diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/__init__.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..97c236ecec3233c863facf2207a0038cb173bcea --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/__init__.py @@ -0,0 +1,122 @@ +#!/usr/bin/env python +# coding=utf-8 +# Copyright 2021 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License + +# ruff: noqa: F401 + +from . import tqdm as _tqdm # _tqdm is the module +from ._cache_assets import cached_assets_path +from ._cache_manager import ( + CachedFileInfo, + CachedRepoInfo, + CachedRevisionInfo, + CacheNotFound, + CorruptedCacheException, + DeleteCacheStrategy, + HFCacheInfo, + scan_cache_dir, +) +from ._chunk_utils import chunk_iterable +from ._datetime import parse_datetime +from ._errors import ( + BadRequestError, + DisabledRepoError, + EntryNotFoundError, + FileMetadataError, + GatedRepoError, + HfHubHTTPError, + LocalEntryNotFoundError, + RepositoryNotFoundError, + RevisionNotFoundError, + hf_raise_for_status, +) +from ._experimental import experimental +from ._fixes import SoftTemporaryDirectory, WeakFileLock, yaml_dump +from ._git_credential import list_credential_helpers, set_git_credential, unset_git_credential +from ._headers import LocalTokenNotFoundError, build_hf_headers, get_token_to_send +from ._hf_folder import HfFolder +from ._http import ( + OfflineModeIsEnabled, + configure_http_backend, + fix_hf_endpoint_in_url, + get_session, + http_backoff, + reset_sessions, +) +from ._pagination import paginate +from ._paths import IGNORE_GIT_FOLDER_PATTERNS, filter_repo_objects +from ._runtime import ( + dump_environment_info, + get_aiohttp_version, + get_fastai_version, + get_fastcore_version, + get_gradio_version, + get_graphviz_version, + get_hf_hub_version, + get_hf_transfer_version, + get_jinja_version, + get_minijinja_version, + get_numpy_version, + get_pillow_version, + get_pydantic_version, + get_pydot_version, + get_python_version, + get_tensorboard_version, + get_tf_version, + get_torch_version, + is_aiohttp_available, + is_fastai_available, + is_fastcore_available, + is_google_colab, + is_gradio_available, + is_graphviz_available, + is_hf_transfer_available, + is_jinja_available, + is_minijinja_available, + is_notebook, + is_numpy_available, + is_package_available, + is_pillow_available, + is_pydantic_available, + is_pydot_available, + is_safetensors_available, + is_tensorboard_available, + is_tf_available, + is_torch_available, +) +from ._safetensors import ( + NotASafetensorsRepoError, + SafetensorsFileMetadata, + SafetensorsParsingError, + SafetensorsRepoMetadata, + TensorInfo, +) +from ._subprocess import capture_output, run_interactive_subprocess, run_subprocess +from ._telemetry import send_telemetry +from ._token import get_token +from ._typing import is_jsonable +from ._validators import ( + HFValidationError, + smoothly_deprecate_use_auth_token, + validate_hf_hub_args, + validate_repo_id, +) +from .tqdm import ( + are_progress_bars_disabled, + disable_progress_bars, + enable_progress_bars, + tqdm, + tqdm_stream_file, +) diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_fixes.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_fixes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..219a6866504cb6598789a75357352af8d85afbf5 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_fixes.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_token.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_token.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1d8c0d93c322ac26d5ce651991a6fd05542e052 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_token.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/logging.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/logging.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78b8160a615bb356b6926bb97c5a8c061a36f0d8 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/logging.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_cache_assets.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_cache_assets.py new file mode 100644 index 0000000000000000000000000000000000000000..e5d435df9b0bb0c67c0bcb5ef65711e9aef367f6 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_cache_assets.py @@ -0,0 +1,135 @@ +# coding=utf-8 +# Copyright 2019-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from pathlib import Path +from typing import Union + +from ..constants import HF_ASSETS_CACHE + + +def cached_assets_path( + library_name: str, + namespace: str = "default", + subfolder: str = "default", + *, + assets_dir: Union[str, Path, None] = None, +): + """Return a folder path to cache arbitrary files. + + `huggingface_hub` provides a canonical folder path to store assets. This is the + recommended way to integrate cache in a downstream library as it will benefit from + the builtins tools to scan and delete the cache properly. + + The distinction is made between files cached from the Hub and assets. Files from the + Hub are cached in a git-aware manner and entirely managed by `huggingface_hub`. See + [related documentation](https://huggingface.co/docs/huggingface_hub/how-to-cache). + All other files that a downstream library caches are considered to be "assets" + (files downloaded from external sources, extracted from a .tar archive, preprocessed + for training,...). + + Once the folder path is generated, it is guaranteed to exist and to be a directory. + The path is based on 3 levels of depth: the library name, a namespace and a + subfolder. Those 3 levels grants flexibility while allowing `huggingface_hub` to + expect folders when scanning/deleting parts of the assets cache. Within a library, + it is expected that all namespaces share the same subset of subfolder names but this + is not a mandatory rule. The downstream library has then full control on which file + structure to adopt within its cache. Namespace and subfolder are optional (would + default to a `"default/"` subfolder) but library name is mandatory as we want every + downstream library to manage its own cache. + + Expected tree: + ```text + assets/ + └── datasets/ + │ ├── SQuAD/ + │ │ ├── downloaded/ + │ │ ├── extracted/ + │ │ └── processed/ + │ ├── Helsinki-NLP--tatoeba_mt/ + │ ├── downloaded/ + │ ├── extracted/ + │ └── processed/ + └── transformers/ + ├── default/ + │ ├── something/ + ├── bert-base-cased/ + │ ├── default/ + │ └── training/ + hub/ + └── models--julien-c--EsperBERTo-small/ + ├── blobs/ + │ ├── (...) + │ ├── (...) + ├── refs/ + │ └── (...) + └── [ 128] snapshots/ + ├── 2439f60ef33a0d46d85da5001d52aeda5b00ce9f/ + │ ├── (...) + └── bbc77c8132af1cc5cf678da3f1ddf2de43606d48/ + └── (...) + ``` + + + Args: + library_name (`str`): + Name of the library that will manage the cache folder. Example: `"dataset"`. + namespace (`str`, *optional*, defaults to "default"): + Namespace to which the data belongs. Example: `"SQuAD"`. + subfolder (`str`, *optional*, defaults to "default"): + Subfolder in which the data will be stored. Example: `extracted`. + assets_dir (`str`, `Path`, *optional*): + Path to the folder where assets are cached. This must not be the same folder + where Hub files are cached. Defaults to `HF_HOME / "assets"` if not provided. + Can also be set with `HF_ASSETS_CACHE` environment variable. + + Returns: + Path to the cache folder (`Path`). + + Example: + ```py + >>> from huggingface_hub import cached_assets_path + + >>> cached_assets_path(library_name="datasets", namespace="SQuAD", subfolder="download") + PosixPath('/home/wauplin/.cache/huggingface/extra/datasets/SQuAD/download') + + >>> cached_assets_path(library_name="datasets", namespace="SQuAD", subfolder="extracted") + PosixPath('/home/wauplin/.cache/huggingface/extra/datasets/SQuAD/extracted') + + >>> cached_assets_path(library_name="datasets", namespace="Helsinki-NLP/tatoeba_mt") + PosixPath('/home/wauplin/.cache/huggingface/extra/datasets/Helsinki-NLP--tatoeba_mt/default') + + >>> cached_assets_path(library_name="datasets", assets_dir="/tmp/tmp123456") + PosixPath('/tmp/tmp123456/datasets/default/default') + ``` + """ + # Resolve assets_dir + if assets_dir is None: + assets_dir = HF_ASSETS_CACHE + assets_dir = Path(assets_dir).expanduser().resolve() + + # Avoid names that could create path issues + for part in (" ", "/", "\\"): + library_name = library_name.replace(part, "--") + namespace = namespace.replace(part, "--") + subfolder = subfolder.replace(part, "--") + + # Path to subfolder is created + path = assets_dir / library_name / namespace / subfolder + try: + path.mkdir(exist_ok=True, parents=True) + except (FileExistsError, NotADirectoryError): + raise ValueError(f"Corrupted assets folder: cannot create directory because of an existing file ({path}).") + + # Return + return path diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_cache_manager.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_cache_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..78ce8fdadc58ac3112324be25c02cbb56637f86e --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_cache_manager.py @@ -0,0 +1,813 @@ +# coding=utf-8 +# Copyright 2022-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contains utilities to manage the HF cache directory.""" + +import os +import shutil +import time +from collections import defaultdict +from dataclasses import dataclass +from pathlib import Path +from typing import Dict, FrozenSet, List, Literal, Optional, Set, Union + +from ..constants import HF_HUB_CACHE +from . import logging + + +logger = logging.get_logger(__name__) + +REPO_TYPE_T = Literal["model", "dataset", "space"] + +# List of OS-created helper files that need to be ignored +FILES_TO_IGNORE = [".DS_Store"] + + +class CacheNotFound(Exception): + """Exception thrown when the Huggingface cache is not found.""" + + cache_dir: Union[str, Path] + + def __init__(self, msg: str, cache_dir: Union[str, Path], *args, **kwargs): + super().__init__(msg, *args, **kwargs) + self.cache_dir = cache_dir + + +class CorruptedCacheException(Exception): + """Exception for any unexpected structure in the Huggingface cache-system.""" + + +@dataclass(frozen=True) +class CachedFileInfo: + """Frozen data structure holding information about a single cached file. + + Args: + file_name (`str`): + Name of the file. Example: `config.json`. + file_path (`Path`): + Path of the file in the `snapshots` directory. The file path is a symlink + referring to a blob in the `blobs` folder. + blob_path (`Path`): + Path of the blob file. This is equivalent to `file_path.resolve()`. + size_on_disk (`int`): + Size of the blob file in bytes. + blob_last_accessed (`float`): + Timestamp of the last time the blob file has been accessed (from any + revision). + blob_last_modified (`float`): + Timestamp of the last time the blob file has been modified/created. + + + + `blob_last_accessed` and `blob_last_modified` reliability can depend on the OS you + are using. See [python documentation](https://docs.python.org/3/library/os.html#os.stat_result) + for more details. + + + """ + + file_name: str + file_path: Path + blob_path: Path + size_on_disk: int + + blob_last_accessed: float + blob_last_modified: float + + @property + def blob_last_accessed_str(self) -> str: + """ + (property) Timestamp of the last time the blob file has been accessed (from any + revision), returned as a human-readable string. + + Example: "2 weeks ago". + """ + return _format_timesince(self.blob_last_accessed) + + @property + def blob_last_modified_str(self) -> str: + """ + (property) Timestamp of the last time the blob file has been modified, returned + as a human-readable string. + + Example: "2 weeks ago". + """ + return _format_timesince(self.blob_last_modified) + + @property + def size_on_disk_str(self) -> str: + """ + (property) Size of the blob file as a human-readable string. + + Example: "42.2K". + """ + return _format_size(self.size_on_disk) + + +@dataclass(frozen=True) +class CachedRevisionInfo: + """Frozen data structure holding information about a revision. + + A revision correspond to a folder in the `snapshots` folder and is populated with + the exact tree structure as the repo on the Hub but contains only symlinks. A + revision can be either referenced by 1 or more `refs` or be "detached" (no refs). + + Args: + commit_hash (`str`): + Hash of the revision (unique). + Example: `"9338f7b671827df886678df2bdd7cc7b4f36dffd"`. + snapshot_path (`Path`): + Path to the revision directory in the `snapshots` folder. It contains the + exact tree structure as the repo on the Hub. + files: (`FrozenSet[CachedFileInfo]`): + Set of [`~CachedFileInfo`] describing all files contained in the snapshot. + refs (`FrozenSet[str]`): + Set of `refs` pointing to this revision. If the revision has no `refs`, it + is considered detached. + Example: `{"main", "2.4.0"}` or `{"refs/pr/1"}`. + size_on_disk (`int`): + Sum of the blob file sizes that are symlink-ed by the revision. + last_modified (`float`): + Timestamp of the last time the revision has been created/modified. + + + + `last_accessed` cannot be determined correctly on a single revision as blob files + are shared across revisions. + + + + + + `size_on_disk` is not necessarily the sum of all file sizes because of possible + duplicated files. Besides, only blobs are taken into account, not the (negligible) + size of folders and symlinks. + + + """ + + commit_hash: str + snapshot_path: Path + size_on_disk: int + files: FrozenSet[CachedFileInfo] + refs: FrozenSet[str] + + last_modified: float + + @property + def last_modified_str(self) -> str: + """ + (property) Timestamp of the last time the revision has been modified, returned + as a human-readable string. + + Example: "2 weeks ago". + """ + return _format_timesince(self.last_modified) + + @property + def size_on_disk_str(self) -> str: + """ + (property) Sum of the blob file sizes as a human-readable string. + + Example: "42.2K". + """ + return _format_size(self.size_on_disk) + + @property + def nb_files(self) -> int: + """ + (property) Total number of files in the revision. + """ + return len(self.files) + + +@dataclass(frozen=True) +class CachedRepoInfo: + """Frozen data structure holding information about a cached repository. + + Args: + repo_id (`str`): + Repo id of the repo on the Hub. Example: `"google/fleurs"`. + repo_type (`Literal["dataset", "model", "space"]`): + Type of the cached repo. + repo_path (`Path`): + Local path to the cached repo. + size_on_disk (`int`): + Sum of the blob file sizes in the cached repo. + nb_files (`int`): + Total number of blob files in the cached repo. + revisions (`FrozenSet[CachedRevisionInfo]`): + Set of [`~CachedRevisionInfo`] describing all revisions cached in the repo. + last_accessed (`float`): + Timestamp of the last time a blob file of the repo has been accessed. + last_modified (`float`): + Timestamp of the last time a blob file of the repo has been modified/created. + + + + `size_on_disk` is not necessarily the sum of all revisions sizes because of + duplicated files. Besides, only blobs are taken into account, not the (negligible) + size of folders and symlinks. + + + + + + `last_accessed` and `last_modified` reliability can depend on the OS you are using. + See [python documentation](https://docs.python.org/3/library/os.html#os.stat_result) + for more details. + + + """ + + repo_id: str + repo_type: REPO_TYPE_T + repo_path: Path + size_on_disk: int + nb_files: int + revisions: FrozenSet[CachedRevisionInfo] + + last_accessed: float + last_modified: float + + @property + def last_accessed_str(self) -> str: + """ + (property) Last time a blob file of the repo has been accessed, returned as a + human-readable string. + + Example: "2 weeks ago". + """ + return _format_timesince(self.last_accessed) + + @property + def last_modified_str(self) -> str: + """ + (property) Last time a blob file of the repo has been modified, returned as a + human-readable string. + + Example: "2 weeks ago". + """ + return _format_timesince(self.last_modified) + + @property + def size_on_disk_str(self) -> str: + """ + (property) Sum of the blob file sizes as a human-readable string. + + Example: "42.2K". + """ + return _format_size(self.size_on_disk) + + @property + def refs(self) -> Dict[str, CachedRevisionInfo]: + """ + (property) Mapping between `refs` and revision data structures. + """ + return {ref: revision for revision in self.revisions for ref in revision.refs} + + +@dataclass(frozen=True) +class DeleteCacheStrategy: + """Frozen data structure holding the strategy to delete cached revisions. + + This object is not meant to be instantiated programmatically but to be returned by + [`~utils.HFCacheInfo.delete_revisions`]. See documentation for usage example. + + Args: + expected_freed_size (`float`): + Expected freed size once strategy is executed. + blobs (`FrozenSet[Path]`): + Set of blob file paths to be deleted. + refs (`FrozenSet[Path]`): + Set of reference file paths to be deleted. + repos (`FrozenSet[Path]`): + Set of entire repo paths to be deleted. + snapshots (`FrozenSet[Path]`): + Set of snapshots to be deleted (directory of symlinks). + """ + + expected_freed_size: int + blobs: FrozenSet[Path] + refs: FrozenSet[Path] + repos: FrozenSet[Path] + snapshots: FrozenSet[Path] + + @property + def expected_freed_size_str(self) -> str: + """ + (property) Expected size that will be freed as a human-readable string. + + Example: "42.2K". + """ + return _format_size(self.expected_freed_size) + + def execute(self) -> None: + """Execute the defined strategy. + + + + If this method is interrupted, the cache might get corrupted. Deletion order is + implemented so that references and symlinks are deleted before the actual blob + files. + + + + + + This method is irreversible. If executed, cached files are erased and must be + downloaded again. + + + """ + # Deletion order matters. Blobs are deleted in last so that the user can't end + # up in a state where a `ref`` refers to a missing snapshot or a snapshot + # symlink refers to a deleted blob. + + # Delete entire repos + for path in self.repos: + _try_delete_path(path, path_type="repo") + + # Delete snapshot directories + for path in self.snapshots: + _try_delete_path(path, path_type="snapshot") + + # Delete refs files + for path in self.refs: + _try_delete_path(path, path_type="ref") + + # Delete blob files + for path in self.blobs: + _try_delete_path(path, path_type="blob") + + logger.info(f"Cache deletion done. Saved {self.expected_freed_size_str}.") + + +@dataclass(frozen=True) +class HFCacheInfo: + """Frozen data structure holding information about the entire cache-system. + + This data structure is returned by [`scan_cache_dir`] and is immutable. + + Args: + size_on_disk (`int`): + Sum of all valid repo sizes in the cache-system. + repos (`FrozenSet[CachedRepoInfo]`): + Set of [`~CachedRepoInfo`] describing all valid cached repos found on the + cache-system while scanning. + warnings (`List[CorruptedCacheException]`): + List of [`~CorruptedCacheException`] that occurred while scanning the cache. + Those exceptions are captured so that the scan can continue. Corrupted repos + are skipped from the scan. + + + + Here `size_on_disk` is equal to the sum of all repo sizes (only blobs). However if + some cached repos are corrupted, their sizes are not taken into account. + + + """ + + size_on_disk: int + repos: FrozenSet[CachedRepoInfo] + warnings: List[CorruptedCacheException] + + @property + def size_on_disk_str(self) -> str: + """ + (property) Sum of all valid repo sizes in the cache-system as a human-readable + string. + + Example: "42.2K". + """ + return _format_size(self.size_on_disk) + + def delete_revisions(self, *revisions: str) -> DeleteCacheStrategy: + """Prepare the strategy to delete one or more revisions cached locally. + + Input revisions can be any revision hash. If a revision hash is not found in the + local cache, a warning is thrown but no error is raised. Revisions can be from + different cached repos since hashes are unique across repos, + + Examples: + ```py + >>> from huggingface_hub import scan_cache_dir + >>> cache_info = scan_cache_dir() + >>> delete_strategy = cache_info.delete_revisions( + ... "81fd1d6e7847c99f5862c9fb81387956d99ec7aa" + ... ) + >>> print(f"Will free {delete_strategy.expected_freed_size_str}.") + Will free 7.9K. + >>> delete_strategy.execute() + Cache deletion done. Saved 7.9K. + ``` + + ```py + >>> from huggingface_hub import scan_cache_dir + >>> scan_cache_dir().delete_revisions( + ... "81fd1d6e7847c99f5862c9fb81387956d99ec7aa", + ... "e2983b237dccf3ab4937c97fa717319a9ca1a96d", + ... "6c0e6080953db56375760c0471a8c5f2929baf11", + ... ).execute() + Cache deletion done. Saved 8.6G. + ``` + + + + `delete_revisions` returns a [`~utils.DeleteCacheStrategy`] object that needs to + be executed. The [`~utils.DeleteCacheStrategy`] is not meant to be modified but + allows having a dry run before actually executing the deletion. + + + """ + hashes_to_delete: Set[str] = set(revisions) + + repos_with_revisions: Dict[CachedRepoInfo, Set[CachedRevisionInfo]] = defaultdict(set) + + for repo in self.repos: + for revision in repo.revisions: + if revision.commit_hash in hashes_to_delete: + repos_with_revisions[repo].add(revision) + hashes_to_delete.remove(revision.commit_hash) + + if len(hashes_to_delete) > 0: + logger.warning(f"Revision(s) not found - cannot delete them: {', '.join(hashes_to_delete)}") + + delete_strategy_blobs: Set[Path] = set() + delete_strategy_refs: Set[Path] = set() + delete_strategy_repos: Set[Path] = set() + delete_strategy_snapshots: Set[Path] = set() + delete_strategy_expected_freed_size = 0 + + for affected_repo, revisions_to_delete in repos_with_revisions.items(): + other_revisions = affected_repo.revisions - revisions_to_delete + + # If no other revisions, it means all revisions are deleted + # -> delete the entire cached repo + if len(other_revisions) == 0: + delete_strategy_repos.add(affected_repo.repo_path) + delete_strategy_expected_freed_size += affected_repo.size_on_disk + continue + + # Some revisions of the repo will be deleted but not all. We need to filter + # which blob files will not be linked anymore. + for revision_to_delete in revisions_to_delete: + # Snapshot dir + delete_strategy_snapshots.add(revision_to_delete.snapshot_path) + + # Refs dir + for ref in revision_to_delete.refs: + delete_strategy_refs.add(affected_repo.repo_path / "refs" / ref) + + # Blobs dir + for file in revision_to_delete.files: + if file.blob_path not in delete_strategy_blobs: + is_file_alone = True + for revision in other_revisions: + for rev_file in revision.files: + if file.blob_path == rev_file.blob_path: + is_file_alone = False + break + if not is_file_alone: + break + + # Blob file not referenced by remaining revisions -> delete + if is_file_alone: + delete_strategy_blobs.add(file.blob_path) + delete_strategy_expected_freed_size += file.size_on_disk + + # Return the strategy instead of executing it. + return DeleteCacheStrategy( + blobs=frozenset(delete_strategy_blobs), + refs=frozenset(delete_strategy_refs), + repos=frozenset(delete_strategy_repos), + snapshots=frozenset(delete_strategy_snapshots), + expected_freed_size=delete_strategy_expected_freed_size, + ) + + +def scan_cache_dir(cache_dir: Optional[Union[str, Path]] = None) -> HFCacheInfo: + """Scan the entire HF cache-system and return a [`~HFCacheInfo`] structure. + + Use `scan_cache_dir` in order to programmatically scan your cache-system. The cache + will be scanned repo by repo. If a repo is corrupted, a [`~CorruptedCacheException`] + will be thrown internally but captured and returned in the [`~HFCacheInfo`] + structure. Only valid repos get a proper report. + + ```py + >>> from huggingface_hub import scan_cache_dir + + >>> hf_cache_info = scan_cache_dir() + HFCacheInfo( + size_on_disk=3398085269, + repos=frozenset({ + CachedRepoInfo( + repo_id='t5-small', + repo_type='model', + repo_path=PosixPath(...), + size_on_disk=970726914, + nb_files=11, + revisions=frozenset({ + CachedRevisionInfo( + commit_hash='d78aea13fa7ecd06c29e3e46195d6341255065d5', + size_on_disk=970726339, + snapshot_path=PosixPath(...), + files=frozenset({ + CachedFileInfo( + file_name='config.json', + size_on_disk=1197 + file_path=PosixPath(...), + blob_path=PosixPath(...), + ), + CachedFileInfo(...), + ... + }), + ), + CachedRevisionInfo(...), + ... + }), + ), + CachedRepoInfo(...), + ... + }), + warnings=[ + CorruptedCacheException("Snapshots dir doesn't exist in cached repo: ..."), + CorruptedCacheException(...), + ... + ], + ) + ``` + + You can also print a detailed report directly from the `huggingface-cli` using: + ```text + > huggingface-cli scan-cache + REPO ID REPO TYPE SIZE ON DISK NB FILES REFS LOCAL PATH + --------------------------- --------- ------------ -------- ------------------- ------------------------------------------------------------------------- + glue dataset 116.3K 15 1.17.0, main, 2.4.0 /Users/lucain/.cache/huggingface/hub/datasets--glue + google/fleurs dataset 64.9M 6 main, refs/pr/1 /Users/lucain/.cache/huggingface/hub/datasets--google--fleurs + Jean-Baptiste/camembert-ner model 441.0M 7 main /Users/lucain/.cache/huggingface/hub/models--Jean-Baptiste--camembert-ner + bert-base-cased model 1.9G 13 main /Users/lucain/.cache/huggingface/hub/models--bert-base-cased + t5-base model 10.1K 3 main /Users/lucain/.cache/huggingface/hub/models--t5-base + t5-small model 970.7M 11 refs/pr/1, main /Users/lucain/.cache/huggingface/hub/models--t5-small + + Done in 0.0s. Scanned 6 repo(s) for a total of 3.4G. + Got 1 warning(s) while scanning. Use -vvv to print details. + ``` + + Args: + cache_dir (`str` or `Path`, `optional`): + Cache directory to cache. Defaults to the default HF cache directory. + + + + Raises: + + `CacheNotFound` + If the cache directory does not exist. + + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If the cache directory is a file, instead of a directory. + + + + Returns: a [`~HFCacheInfo`] object. + """ + if cache_dir is None: + cache_dir = HF_HUB_CACHE + + cache_dir = Path(cache_dir).expanduser().resolve() + if not cache_dir.exists(): + raise CacheNotFound( + f"Cache directory not found: {cache_dir}. Please use `cache_dir` argument or set `HF_HUB_CACHE` environment variable.", + cache_dir=cache_dir, + ) + + if cache_dir.is_file(): + raise ValueError( + f"Scan cache expects a directory but found a file: {cache_dir}. Please use `cache_dir` argument or set `HF_HUB_CACHE` environment variable." + ) + + repos: Set[CachedRepoInfo] = set() + warnings: List[CorruptedCacheException] = [] + for repo_path in cache_dir.iterdir(): + if repo_path.name == ".locks": # skip './.locks/' folder + continue + try: + repos.add(_scan_cached_repo(repo_path)) + except CorruptedCacheException as e: + warnings.append(e) + + return HFCacheInfo( + repos=frozenset(repos), + size_on_disk=sum(repo.size_on_disk for repo in repos), + warnings=warnings, + ) + + +def _scan_cached_repo(repo_path: Path) -> CachedRepoInfo: + """Scan a single cache repo and return information about it. + + Any unexpected behavior will raise a [`~CorruptedCacheException`]. + """ + if not repo_path.is_dir(): + raise CorruptedCacheException(f"Repo path is not a directory: {repo_path}") + + if "--" not in repo_path.name: + raise CorruptedCacheException(f"Repo path is not a valid HuggingFace cache directory: {repo_path}") + + repo_type, repo_id = repo_path.name.split("--", maxsplit=1) + repo_type = repo_type[:-1] # "models" -> "model" + repo_id = repo_id.replace("--", "/") # google/fleurs -> "google/fleurs" + + if repo_type not in {"dataset", "model", "space"}: + raise CorruptedCacheException( + f"Repo type must be `dataset`, `model` or `space`, found `{repo_type}` ({repo_path})." + ) + + blob_stats: Dict[Path, os.stat_result] = {} # Key is blob_path, value is blob stats + + snapshots_path = repo_path / "snapshots" + refs_path = repo_path / "refs" + + if not snapshots_path.exists() or not snapshots_path.is_dir(): + raise CorruptedCacheException(f"Snapshots dir doesn't exist in cached repo: {snapshots_path}") + + # Scan over `refs` directory + + # key is revision hash, value is set of refs + refs_by_hash: Dict[str, Set[str]] = defaultdict(set) + if refs_path.exists(): + # Example of `refs` directory + # ── refs + # ├── main + # └── refs + # └── pr + # └── 1 + if refs_path.is_file(): + raise CorruptedCacheException(f"Refs directory cannot be a file: {refs_path}") + + for ref_path in refs_path.glob("**/*"): + # glob("**/*") iterates over all files and directories -> skip directories + if ref_path.is_dir(): + continue + + ref_name = str(ref_path.relative_to(refs_path)) + with ref_path.open() as f: + commit_hash = f.read() + + refs_by_hash[commit_hash].add(ref_name) + + # Scan snapshots directory + cached_revisions: Set[CachedRevisionInfo] = set() + for revision_path in snapshots_path.iterdir(): + # Ignore OS-created helper files + if revision_path.name in FILES_TO_IGNORE: + continue + if revision_path.is_file(): + raise CorruptedCacheException(f"Snapshots folder corrupted. Found a file: {revision_path}") + + cached_files = set() + for file_path in revision_path.glob("**/*"): + # glob("**/*") iterates over all files and directories -> skip directories + if file_path.is_dir(): + continue + + blob_path = Path(file_path).resolve() + if not blob_path.exists(): + raise CorruptedCacheException(f"Blob missing (broken symlink): {blob_path}") + + if blob_path not in blob_stats: + blob_stats[blob_path] = blob_path.stat() + + cached_files.add( + CachedFileInfo( + file_name=file_path.name, + file_path=file_path, + size_on_disk=blob_stats[blob_path].st_size, + blob_path=blob_path, + blob_last_accessed=blob_stats[blob_path].st_atime, + blob_last_modified=blob_stats[blob_path].st_mtime, + ) + ) + + # Last modified is either the last modified blob file or the revision folder + # itself if it is empty + if len(cached_files) > 0: + revision_last_modified = max(blob_stats[file.blob_path].st_mtime for file in cached_files) + else: + revision_last_modified = revision_path.stat().st_mtime + + cached_revisions.add( + CachedRevisionInfo( + commit_hash=revision_path.name, + files=frozenset(cached_files), + refs=frozenset(refs_by_hash.pop(revision_path.name, set())), + size_on_disk=sum( + blob_stats[blob_path].st_size for blob_path in set(file.blob_path for file in cached_files) + ), + snapshot_path=revision_path, + last_modified=revision_last_modified, + ) + ) + + # Check that all refs referred to an existing revision + if len(refs_by_hash) > 0: + raise CorruptedCacheException( + f"Reference(s) refer to missing commit hashes: {dict(refs_by_hash)} ({repo_path})." + ) + + # Last modified is either the last modified blob file or the repo folder itself if + # no blob files has been found. Same for last accessed. + if len(blob_stats) > 0: + repo_last_accessed = max(stat.st_atime for stat in blob_stats.values()) + repo_last_modified = max(stat.st_mtime for stat in blob_stats.values()) + else: + repo_stats = repo_path.stat() + repo_last_accessed = repo_stats.st_atime + repo_last_modified = repo_stats.st_mtime + + # Build and return frozen structure + return CachedRepoInfo( + nb_files=len(blob_stats), + repo_id=repo_id, + repo_path=repo_path, + repo_type=repo_type, # type: ignore + revisions=frozenset(cached_revisions), + size_on_disk=sum(stat.st_size for stat in blob_stats.values()), + last_accessed=repo_last_accessed, + last_modified=repo_last_modified, + ) + + +def _format_size(num: int) -> str: + """Format size in bytes into a human-readable string. + + Taken from https://stackoverflow.com/a/1094933 + """ + num_f = float(num) + for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]: + if abs(num_f) < 1000.0: + return f"{num_f:3.1f}{unit}" + num_f /= 1000.0 + return f"{num_f:.1f}Y" + + +_TIMESINCE_CHUNKS = ( + # Label, divider, max value + ("second", 1, 60), + ("minute", 60, 60), + ("hour", 60 * 60, 24), + ("day", 60 * 60 * 24, 6), + ("week", 60 * 60 * 24 * 7, 6), + ("month", 60 * 60 * 24 * 30, 11), + ("year", 60 * 60 * 24 * 365, None), +) + + +def _format_timesince(ts: float) -> str: + """Format timestamp in seconds into a human-readable string, relative to now. + + Vaguely inspired by Django's `timesince` formatter. + """ + delta = time.time() - ts + if delta < 20: + return "a few seconds ago" + for label, divider, max_value in _TIMESINCE_CHUNKS: # noqa: B007 + value = round(delta / divider) + if max_value is not None and value <= max_value: + break + return f"{value} {label}{'s' if value > 1 else ''} ago" + + +def _try_delete_path(path: Path, path_type: str) -> None: + """Try to delete a local file or folder. + + If the path does not exists, error is logged as a warning and then ignored. + + Args: + path (`Path`) + Path to delete. Can be a file or a folder. + path_type (`str`) + What path are we deleting ? Only for logging purposes. Example: "snapshot". + """ + logger.info(f"Delete {path_type}: {path}") + try: + if path.is_file(): + os.remove(path) + else: + shutil.rmtree(path) + except FileNotFoundError: + logger.warning(f"Couldn't delete {path_type}: file not found ({path})", exc_info=True) + except PermissionError: + logger.warning(f"Couldn't delete {path_type}: permission denied ({path})", exc_info=True) diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_chunk_utils.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_chunk_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b0af032ae6a68f03676ad7fdb8e483248d9853f8 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_chunk_utils.py @@ -0,0 +1,65 @@ +# coding=utf-8 +# Copyright 2022-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contains a utility to iterate by chunks over an iterator.""" + +import itertools +from typing import Iterable, TypeVar + + +T = TypeVar("T") + + +def chunk_iterable(iterable: Iterable[T], chunk_size: int) -> Iterable[Iterable[T]]: + """Iterates over an iterator chunk by chunk. + + Taken from https://stackoverflow.com/a/8998040. + See also https://github.com/huggingface/huggingface_hub/pull/920#discussion_r938793088. + + Args: + iterable (`Iterable`): + The iterable on which we want to iterate. + chunk_size (`int`): + Size of the chunks. Must be a strictly positive integer (e.g. >0). + + Example: + + ```python + >>> from huggingface_hub.utils import chunk_iterable + + >>> for items in chunk_iterable(range(17), chunk_size=8): + ... print(items) + # [0, 1, 2, 3, 4, 5, 6, 7] + # [8, 9, 10, 11, 12, 13, 14, 15] + # [16] # smaller last chunk + ``` + + Raises: + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If `chunk_size` <= 0. + + + The last chunk can be smaller than `chunk_size`. + + """ + if not isinstance(chunk_size, int) or chunk_size <= 0: + raise ValueError("`chunk_size` must be a strictly positive integer (>0).") + + iterator = iter(iterable) + while True: + try: + next_item = next(iterator) + except StopIteration: + return + yield itertools.chain((next_item,), itertools.islice(iterator, chunk_size - 1)) diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_datetime.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_datetime.py new file mode 100644 index 0000000000000000000000000000000000000000..e544884b8793d8d409303cafd34586523fc3fb1c --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_datetime.py @@ -0,0 +1,62 @@ +# coding=utf-8 +# Copyright 2022-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contains utilities to handle datetimes in Huggingface Hub.""" + +from datetime import datetime, timezone + + +def parse_datetime(date_string: str) -> datetime: + """ + Parses a date_string returned from the server to a datetime object. + + This parser is a weak-parser is the sense that it handles only a single format of + date_string. It is expected that the server format will never change. The + implementation depends only on the standard lib to avoid an external dependency + (python-dateutil). See full discussion about this decision on PR: + https://github.com/huggingface/huggingface_hub/pull/999. + + Example: + ```py + > parse_datetime('2022-08-19T07:19:38.123Z') + datetime.datetime(2022, 8, 19, 7, 19, 38, 123000, tzinfo=timezone.utc) + ``` + + Args: + date_string (`str`): + A string representing a datetime returned by the Hub server. + String is expected to follow '%Y-%m-%dT%H:%M:%S.%fZ' pattern. + + Returns: + A python datetime object. + + Raises: + :class:`ValueError`: + If `date_string` cannot be parsed. + """ + try: + # Datetime ending with a Z means "UTC". We parse the date and then explicitly + # set the timezone to UTC. + # See https://en.wikipedia.org/wiki/ISO_8601#Coordinated_Universal_Time_(UTC) + # Taken from https://stackoverflow.com/a/3168394. + if len(date_string) == 30: + # Means timezoned-timestamp with nanoseconds precision. We need to truncate the last 3 digits. + date_string = date_string[:-4] + "Z" + dt = datetime.strptime(date_string, "%Y-%m-%dT%H:%M:%S.%fZ") + return dt.replace(tzinfo=timezone.utc) # Set explicit timezone + except ValueError as e: + raise ValueError( + f"Cannot parse '{date_string}' as a datetime. Date string is expected to" + " follow '%Y-%m-%dT%H:%M:%S.%fZ' pattern." + ) from e diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_deprecation.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_deprecation.py new file mode 100644 index 0000000000000000000000000000000000000000..4cb8d6e418c76accd1ecd61158b4bdd265e12f71 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_deprecation.py @@ -0,0 +1,136 @@ +import warnings +from functools import wraps +from inspect import Parameter, signature +from typing import Iterable, Optional + + +def _deprecate_positional_args(*, version: str): + """Decorator for methods that issues warnings for positional arguments. + Using the keyword-only argument syntax in pep 3102, arguments after the + * will issue a warning when passed as a positional argument. + + Args: + version (`str`): + The version when positional arguments will result in error. + """ + + def _inner_deprecate_positional_args(f): + sig = signature(f) + kwonly_args = [] + all_args = [] + for name, param in sig.parameters.items(): + if param.kind == Parameter.POSITIONAL_OR_KEYWORD: + all_args.append(name) + elif param.kind == Parameter.KEYWORD_ONLY: + kwonly_args.append(name) + + @wraps(f) + def inner_f(*args, **kwargs): + extra_args = len(args) - len(all_args) + if extra_args <= 0: + return f(*args, **kwargs) + # extra_args > 0 + args_msg = [ + f"{name}='{arg}'" if isinstance(arg, str) else f"{name}={arg}" + for name, arg in zip(kwonly_args[:extra_args], args[-extra_args:]) + ] + args_msg = ", ".join(args_msg) + warnings.warn( + f"Deprecated positional argument(s) used in '{f.__name__}': pass" + f" {args_msg} as keyword args. From version {version} passing these" + " as positional arguments will result in an error,", + FutureWarning, + ) + kwargs.update(zip(sig.parameters, args)) + return f(**kwargs) + + return inner_f + + return _inner_deprecate_positional_args + + +def _deprecate_arguments( + *, + version: str, + deprecated_args: Iterable[str], + custom_message: Optional[str] = None, +): + """Decorator to issue warnings when using deprecated arguments. + + TODO: could be useful to be able to set a custom error message. + + Args: + version (`str`): + The version when deprecated arguments will result in error. + deprecated_args (`List[str]`): + List of the arguments to be deprecated. + custom_message (`str`, *optional*): + Warning message that is raised. If not passed, a default warning message + will be created. + """ + + def _inner_deprecate_positional_args(f): + sig = signature(f) + + @wraps(f) + def inner_f(*args, **kwargs): + # Check for used deprecated arguments + used_deprecated_args = [] + for _, parameter in zip(args, sig.parameters.values()): + if parameter.name in deprecated_args: + used_deprecated_args.append(parameter.name) + for kwarg_name, kwarg_value in kwargs.items(): + if ( + # If argument is deprecated but still used + kwarg_name in deprecated_args + # And then the value is not the default value + and kwarg_value != sig.parameters[kwarg_name].default + ): + used_deprecated_args.append(kwarg_name) + + # Warn and proceed + if len(used_deprecated_args) > 0: + message = ( + f"Deprecated argument(s) used in '{f.__name__}':" + f" {', '.join(used_deprecated_args)}. Will not be supported from" + f" version '{version}'." + ) + if custom_message is not None: + message += "\n\n" + custom_message + warnings.warn(message, FutureWarning) + return f(*args, **kwargs) + + return inner_f + + return _inner_deprecate_positional_args + + +def _deprecate_method(*, version: str, message: Optional[str] = None): + """Decorator to issue warnings when using a deprecated method. + + Args: + version (`str`): + The version when deprecated arguments will result in error. + message (`str`, *optional*): + Warning message that is raised. If not passed, a default warning message + will be created. + """ + + def _inner_deprecate_method(f): + name = f.__name__ + if name == "__init__": + name = f.__qualname__.split(".")[0] # class name instead of method name + + @wraps(f) + def inner_f(*args, **kwargs): + warning_message = ( + f"'{name}' (from '{f.__module__}') is deprecated and will be removed from version '{version}'." + ) + if message is not None: + warning_message += " " + message + warnings.warn(warning_message, FutureWarning) + return f(*args, **kwargs) + + return inner_f + + return _inner_deprecate_method diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_errors.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_errors.py new file mode 100644 index 0000000000000000000000000000000000000000..70e97f0c24101243bce003f0ca55d852c02a48cd --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_errors.py @@ -0,0 +1,397 @@ +import re +from typing import Optional + +from requests import HTTPError, Response + +from ._fixes import JSONDecodeError + + +REPO_API_REGEX = re.compile( + r""" + # staging or production endpoint + ^https://[^/]+ + ( + # on /api/repo_type/repo_id + /api/(models|datasets|spaces)/(.+) + | + # or /repo_id/resolve/revision/... + /(.+)/resolve/(.+) + ) + """, + flags=re.VERBOSE, +) + + +class FileMetadataError(OSError): + """Error triggered when the metadata of a file on the Hub cannot be retrieved (missing ETag or commit_hash). + + Inherits from `OSError` for backward compatibility. + """ + + +class HfHubHTTPError(HTTPError): + """ + HTTPError to inherit from for any custom HTTP Error raised in HF Hub. + + Any HTTPError is converted at least into a `HfHubHTTPError`. If some information is + sent back by the server, it will be added to the error message. + + Added details: + - Request id from "X-Request-Id" header if exists. + - Server error message from the header "X-Error-Message". + - Server error message if we can found one in the response body. + + Example: + ```py + import requests + from huggingface_hub.utils import get_session, hf_raise_for_status, HfHubHTTPError + + response = get_session().post(...) + try: + hf_raise_for_status(response) + except HfHubHTTPError as e: + print(str(e)) # formatted message + e.request_id, e.server_message # details returned by server + + # Complete the error message with additional information once it's raised + e.append_to_message("\n`create_commit` expects the repository to exist.") + raise + ``` + """ + + request_id: Optional[str] = None + server_message: Optional[str] = None + + def __init__(self, message: str, response: Optional[Response] = None): + # Parse server information if any. + if response is not None: + self.request_id = response.headers.get("X-Request-Id") + try: + server_data = response.json() + except JSONDecodeError: + server_data = {} + + # Retrieve server error message from multiple sources + server_message_from_headers = response.headers.get("X-Error-Message") + server_message_from_body = server_data.get("error") + server_multiple_messages_from_body = "\n".join( + error["message"] for error in server_data.get("errors", []) if "message" in error + ) + + # Concatenate error messages + _server_message = "" + if server_message_from_headers is not None: # from headers + _server_message += server_message_from_headers + "\n" + if server_message_from_body is not None: # from body "error" + if isinstance(server_message_from_body, list): + server_message_from_body = "\n".join(server_message_from_body) + if server_message_from_body not in _server_message: + _server_message += server_message_from_body + "\n" + if server_multiple_messages_from_body is not None: # from body "errors" + if server_multiple_messages_from_body not in _server_message: + _server_message += server_multiple_messages_from_body + "\n" + _server_message = _server_message.strip() + + # Set message to `HfHubHTTPError` (if any) + if _server_message != "": + self.server_message = _server_message + + super().__init__( + _format_error_message( + message, + request_id=self.request_id, + server_message=self.server_message, + ), + response=response, # type: ignore + request=response.request if response is not None else None, # type: ignore + ) + + def append_to_message(self, additional_message: str) -> None: + """Append additional information to the `HfHubHTTPError` initial message.""" + self.args = (self.args[0] + additional_message,) + self.args[1:] + + +class RepositoryNotFoundError(HfHubHTTPError): + """ + Raised when trying to access a hf.co URL with an invalid repository name, or + with a private repo name the user does not have access to. + + Example: + + ```py + >>> from huggingface_hub import model_info + >>> model_info("") + (...) + huggingface_hub.utils._errors.RepositoryNotFoundError: 401 Client Error. (Request ID: PvMw_VjBMjVdMz53WKIzP) + + Repository Not Found for url: https://huggingface.co/api/models/%3Cnon_existent_repository%3E. + Please make sure you specified the correct `repo_id` and `repo_type`. + If the repo is private, make sure you are authenticated. + Invalid username or password. + ``` + """ + + +class GatedRepoError(RepositoryNotFoundError): + """ + Raised when trying to access a gated repository for which the user is not on the + authorized list. + + Note: derives from `RepositoryNotFoundError` to ensure backward compatibility. + + Example: + + ```py + >>> from huggingface_hub import model_info + >>> model_info("") + (...) + huggingface_hub.utils._errors.GatedRepoError: 403 Client Error. (Request ID: ViT1Bf7O_026LGSQuVqfa) + + Cannot access gated repo for url https://huggingface.co/api/models/ardent-figment/gated-model. + Access to model ardent-figment/gated-model is restricted and you are not in the authorized list. + Visit https://huggingface.co/ardent-figment/gated-model to ask for access. + ``` + """ + + +class DisabledRepoError(HfHubHTTPError): + """ + Raised when trying to access a repository that has been disabled by its author. + + Example: + + ```py + >>> from huggingface_hub import dataset_info + >>> dataset_info("laion/laion-art") + (...) + huggingface_hub.utils._errors.DisabledRepoError: 403 Client Error. (Request ID: Root=1-659fc3fa-3031673e0f92c71a2260dbe2;bc6f4dfb-b30a-4862-af0a-5cfe827610d8) + + Cannot access repository for url https://huggingface.co/api/datasets/laion/laion-art. + Access to this resource is disabled. + ``` + """ + + +class RevisionNotFoundError(HfHubHTTPError): + """ + Raised when trying to access a hf.co URL with a valid repository but an invalid + revision. + + Example: + + ```py + >>> from huggingface_hub import hf_hub_download + >>> hf_hub_download('bert-base-cased', 'config.json', revision='') + (...) + huggingface_hub.utils._errors.RevisionNotFoundError: 404 Client Error. (Request ID: Mwhe_c3Kt650GcdKEFomX) + + Revision Not Found for url: https://huggingface.co/bert-base-cased/resolve/%3Cnon-existent-revision%3E/config.json. + ``` + """ + + +class EntryNotFoundError(HfHubHTTPError): + """ + Raised when trying to access a hf.co URL with a valid repository and revision + but an invalid filename. + + Example: + + ```py + >>> from huggingface_hub import hf_hub_download + >>> hf_hub_download('bert-base-cased', '') + (...) + huggingface_hub.utils._errors.EntryNotFoundError: 404 Client Error. (Request ID: 53pNl6M0MxsnG5Sw8JA6x) + + Entry Not Found for url: https://huggingface.co/bert-base-cased/resolve/main/%3Cnon-existent-file%3E. + ``` + """ + + +class LocalEntryNotFoundError(EntryNotFoundError, FileNotFoundError, ValueError): + """ + Raised when trying to access a file or snapshot that is not on the disk when network is + disabled or unavailable (connection issue). The entry may exist on the Hub. + + Note: `ValueError` type is to ensure backward compatibility. + Note: `LocalEntryNotFoundError` derives from `HTTPError` because of `EntryNotFoundError` + even when it is not a network issue. + + Example: + + ```py + >>> from huggingface_hub import hf_hub_download + >>> hf_hub_download('bert-base-cased', '', local_files_only=True) + (...) + huggingface_hub.utils._errors.LocalEntryNotFoundError: Cannot find the requested files in the disk cache and outgoing traffic has been disabled. To enable hf.co look-ups and downloads online, set 'local_files_only' to False. + ``` + """ + + def __init__(self, message: str): + super().__init__(message, response=None) + + +class BadRequestError(HfHubHTTPError, ValueError): + """ + Raised by `hf_raise_for_status` when the server returns a HTTP 400 error. + + Example: + + ```py + >>> resp = requests.post("hf.co/api/check", ...) + >>> hf_raise_for_status(resp, endpoint_name="check") + huggingface_hub.utils._errors.BadRequestError: Bad request for check endpoint: {details} (Request ID: XXX) + ``` + """ + + +def hf_raise_for_status(response: Response, endpoint_name: Optional[str] = None) -> None: + """ + Internal version of `response.raise_for_status()` that will refine a + potential HTTPError. Raised exception will be an instance of `HfHubHTTPError`. + + This helper is meant to be the unique method to raise_for_status when making a call + to the Hugging Face Hub. + + Example: + ```py + import requests + from huggingface_hub.utils import get_session, hf_raise_for_status, HfHubHTTPError + + response = get_session().post(...) + try: + hf_raise_for_status(response) + except HfHubHTTPError as e: + print(str(e)) # formatted message + e.request_id, e.server_message # details returned by server + + # Complete the error message with additional information once it's raised + e.append_to_message("\n`create_commit` expects the repository to exist.") + raise + ``` + + Args: + response (`Response`): + Response from the server. + endpoint_name (`str`, *optional*): + Name of the endpoint that has been called. If provided, the error message + will be more complete. + + + + Raises when the request has failed: + + - [`~utils.RepositoryNotFoundError`] + If the repository to download from cannot be found. This may be because it + doesn't exist, because `repo_type` is not set correctly, or because the repo + is `private` and you do not have access. + - [`~utils.GatedRepoError`] + If the repository exists but is gated and the user is not on the authorized + list. + - [`~utils.RevisionNotFoundError`] + If the repository exists but the revision couldn't be find. + - [`~utils.EntryNotFoundError`] + If the repository exists but the entry (e.g. the requested file) couldn't be + find. + - [`~utils.BadRequestError`] + If request failed with a HTTP 400 BadRequest error. + - [`~utils.HfHubHTTPError`] + If request failed for a reason not listed above. + + + """ + try: + response.raise_for_status() + except HTTPError as e: + error_code = response.headers.get("X-Error-Code") + error_message = response.headers.get("X-Error-Message") + + if error_code == "RevisionNotFound": + message = f"{response.status_code} Client Error." + "\n\n" + f"Revision Not Found for url: {response.url}." + raise RevisionNotFoundError(message, response) from e + + elif error_code == "EntryNotFound": + message = f"{response.status_code} Client Error." + "\n\n" + f"Entry Not Found for url: {response.url}." + raise EntryNotFoundError(message, response) from e + + elif error_code == "GatedRepo": + message = ( + f"{response.status_code} Client Error." + "\n\n" + f"Cannot access gated repo for url {response.url}." + ) + raise GatedRepoError(message, response) from e + + elif error_message == "Access to this resource is disabled.": + message = ( + f"{response.status_code} Client Error." + + "\n\n" + + f"Cannot access repository for url {response.url}." + + "\n" + + "Access to this resource is disabled." + ) + raise DisabledRepoError(message, response) from e + + elif error_code == "RepoNotFound" or ( + response.status_code == 401 + and response.request is not None + and response.request.url is not None + and REPO_API_REGEX.search(response.request.url) is not None + ): + # 401 is misleading as it is returned for: + # - private and gated repos if user is not authenticated + # - missing repos + # => for now, we process them as `RepoNotFound` anyway. + # See https://gist.github.com/Wauplin/46c27ad266b15998ce56a6603796f0b9 + message = ( + f"{response.status_code} Client Error." + + "\n\n" + + f"Repository Not Found for url: {response.url}." + + "\nPlease make sure you specified the correct `repo_id` and" + " `repo_type`.\nIf you are trying to access a private or gated repo," + " make sure you are authenticated." + ) + raise RepositoryNotFoundError(message, response) from e + + elif response.status_code == 400: + message = ( + f"\n\nBad request for {endpoint_name} endpoint:" if endpoint_name is not None else "\n\nBad request:" + ) + raise BadRequestError(message, response=response) from e + + elif response.status_code == 403: + message = ( + f"\n\n{response.status_code} Forbidden: {error_message}." + + f"\nCannot access content at: {response.url}." + + "\nIf you are trying to create or update content," + + "make sure you have a token with the `write` role." + ) + raise HfHubHTTPError(message, response=response) from e + + # Convert `HTTPError` into a `HfHubHTTPError` to display request information + # as well (request id and/or server error message) + raise HfHubHTTPError(str(e), response=response) from e + + +def _format_error_message(message: str, request_id: Optional[str], server_message: Optional[str]) -> str: + """ + Format the `HfHubHTTPError` error message based on initial message and information + returned by the server. + + Used when initializing `HfHubHTTPError`. + """ + # Add message from response body + if server_message is not None and len(server_message) > 0 and server_message.lower() not in message.lower(): + if "\n\n" in message: + message += "\n" + server_message + else: + message += "\n\n" + server_message + + # Add Request ID + if request_id is not None and str(request_id).lower() not in message.lower(): + request_id_message = f" (Request ID: {request_id})" + if "\n" in message: + newline_index = message.index("\n") + message = message[:newline_index] + request_id_message + message[newline_index:] + else: + message += request_id_message + + return message diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_experimental.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_experimental.py new file mode 100644 index 0000000000000000000000000000000000000000..34141eba09123c06fbca55c929a19a0264e5788e --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_experimental.py @@ -0,0 +1,66 @@ +# coding=utf-8 +# Copyright 2023-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contains utilities to flag a feature as "experimental" in Huggingface Hub.""" + +import warnings +from functools import wraps +from typing import Callable + +from .. import constants + + +def experimental(fn: Callable) -> Callable: + """Decorator to flag a feature as experimental. + + An experimental feature trigger a warning when used as it might be subject to breaking changes in the future. + Warnings can be disabled by setting the environment variable `HF_EXPERIMENTAL_WARNING` to `0`. + + Args: + fn (`Callable`): + The function to flag as experimental. + + Returns: + `Callable`: The decorated function. + + Example: + + ```python + >>> from huggingface_hub.utils import experimental + + >>> @experimental + ... def my_function(): + ... print("Hello world!") + + >>> my_function() + UserWarning: 'my_function' is experimental and might be subject to breaking changes in the future. You can disable + this warning by setting `HF_HUB_DISABLE_EXPERIMENTAL_WARNING=1` as environment variable. + Hello world! + ``` + """ + # For classes, put the "experimental" around the "__new__" method => __new__ will be removed in warning message + name = fn.__qualname__[: -len(".__new__")] if fn.__qualname__.endswith(".__new__") else fn.__qualname__ + + @wraps(fn) + def _inner_fn(*args, **kwargs): + if not constants.HF_HUB_DISABLE_EXPERIMENTAL_WARNING: + warnings.warn( + f"'{name}' is experimental and might be subject to breaking changes in the future." + " You can disable this warning by setting `HF_HUB_DISABLE_EXPERIMENTAL_WARNING=1` as environment" + " variable.", + UserWarning, + ) + return fn(*args, **kwargs) + + return _inner_fn diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_fixes.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_fixes.py new file mode 100644 index 0000000000000000000000000000000000000000..1edcbc1eeedc8d89a8c9b9ff8a4cbe4371ce2576 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_fixes.py @@ -0,0 +1,93 @@ +# JSONDecodeError was introduced in requests=2.27 released in 2022. +# This allows us to support older requests for users +# More information: https://github.com/psf/requests/pull/5856 +try: + from requests import JSONDecodeError # type: ignore # noqa: F401 +except ImportError: + try: + from simplejson import JSONDecodeError # type: ignore # noqa: F401 + except ImportError: + from json import JSONDecodeError # type: ignore # noqa: F401 +import contextlib +import os +import shutil +import stat +import tempfile +from functools import partial +from pathlib import Path +from typing import Callable, Generator, Optional, Union + +import yaml +from filelock import BaseFileLock, FileLock + + +# Wrap `yaml.dump` to set `allow_unicode=True` by default. +# +# Example: +# ```py +# >>> yaml.dump({"emoji": "👀", "some unicode": "日本か"}) +# 'emoji: "\\U0001F440"\nsome unicode: "\\u65E5\\u672C\\u304B"\n' +# +# >>> yaml_dump({"emoji": "👀", "some unicode": "日本か"}) +# 'emoji: "👀"\nsome unicode: "日本か"\n' +# ``` +yaml_dump: Callable[..., str] = partial(yaml.dump, stream=None, allow_unicode=True) # type: ignore + + +@contextlib.contextmanager +def SoftTemporaryDirectory( + suffix: Optional[str] = None, + prefix: Optional[str] = None, + dir: Optional[Union[Path, str]] = None, + **kwargs, +) -> Generator[Path, None, None]: + """ + Context manager to create a temporary directory and safely delete it. + + If tmp directory cannot be deleted normally, we set the WRITE permission and retry. + If cleanup still fails, we give up but don't raise an exception. This is equivalent + to `tempfile.TemporaryDirectory(..., ignore_cleanup_errors=True)` introduced in + Python 3.10. + + See https://www.scivision.dev/python-tempfile-permission-error-windows/. + """ + tmpdir = tempfile.TemporaryDirectory(prefix=prefix, suffix=suffix, dir=dir, **kwargs) + yield Path(tmpdir.name).resolve() + + try: + # First once with normal cleanup + shutil.rmtree(tmpdir.name) + except Exception: + # If failed, try to set write permission and retry + try: + shutil.rmtree(tmpdir.name, onerror=_set_write_permission_and_retry) + except Exception: + pass + + # And finally, cleanup the tmpdir. + # If it fails again, give up but do not throw error + try: + tmpdir.cleanup() + except Exception: + pass + + +def _set_write_permission_and_retry(func, path, excinfo): + os.chmod(path, stat.S_IWRITE) + func(path) + + +@contextlib.contextmanager +def WeakFileLock(lock_file: Union[str, Path]) -> Generator[BaseFileLock, None, None]: + lock = FileLock(lock_file) + lock.acquire() + + yield lock + + try: + return lock.release() + except OSError: + try: + Path(lock_file).unlink() + except OSError: + pass diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_git_credential.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_git_credential.py new file mode 100644 index 0000000000000000000000000000000000000000..a8ed77f4e49ca88ff4fa9aba48cbf00195036013 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_git_credential.py @@ -0,0 +1,121 @@ +# coding=utf-8 +# Copyright 2022-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contains utilities to manage Git credentials.""" + +import re +import subprocess +from typing import List, Optional + +from ..constants import ENDPOINT +from ._subprocess import run_interactive_subprocess, run_subprocess + + +GIT_CREDENTIAL_REGEX = re.compile( + r""" + ^\s* # start of line + credential\.helper # credential.helper value + \s*=\s* # separator + (\w+) # the helper name (group 1) + (\s|$) # whitespace or end of line + """, + flags=re.MULTILINE | re.IGNORECASE | re.VERBOSE, +) + + +def list_credential_helpers(folder: Optional[str] = None) -> List[str]: + """Return the list of git credential helpers configured. + + See https://git-scm.com/docs/gitcredentials. + + Credentials are saved in all configured helpers (store, cache, macOS keychain,...). + Calls "`git credential approve`" internally. See https://git-scm.com/docs/git-credential. + + Args: + folder (`str`, *optional*): + The folder in which to check the configured helpers. + """ + try: + output = run_subprocess("git config --list", folder=folder).stdout + parsed = _parse_credential_output(output) + return parsed + except subprocess.CalledProcessError as exc: + raise EnvironmentError(exc.stderr) + + +def set_git_credential(token: str, username: str = "hf_user", folder: Optional[str] = None) -> None: + """Save a username/token pair in git credential for HF Hub registry. + + Credentials are saved in all configured helpers (store, cache, macOS keychain,...). + Calls "`git credential approve`" internally. See https://git-scm.com/docs/git-credential. + + Args: + username (`str`, defaults to `"hf_user"`): + A git username. Defaults to `"hf_user"`, the default user used in the Hub. + token (`str`, defaults to `"hf_user"`): + A git password. In practice, the User Access Token for the Hub. + See https://huggingface.co/settings/tokens. + folder (`str`, *optional*): + The folder in which to check the configured helpers. + """ + with run_interactive_subprocess("git credential approve", folder=folder) as ( + stdin, + _, + ): + stdin.write(f"url={ENDPOINT}\nusername={username.lower()}\npassword={token}\n\n") + stdin.flush() + + +def unset_git_credential(username: str = "hf_user", folder: Optional[str] = None) -> None: + """Erase credentials from git credential for HF Hub registry. + + Credentials are erased from the configured helpers (store, cache, macOS + keychain,...), if any. If `username` is not provided, any credential configured for + HF Hub endpoint is erased. + Calls "`git credential erase`" internally. See https://git-scm.com/docs/git-credential. + + Args: + username (`str`, defaults to `"hf_user"`): + A git username. Defaults to `"hf_user"`, the default user used in the Hub. + folder (`str`, *optional*): + The folder in which to check the configured helpers. + """ + with run_interactive_subprocess("git credential reject", folder=folder) as ( + stdin, + _, + ): + standard_input = f"url={ENDPOINT}\n" + if username is not None: + standard_input += f"username={username.lower()}\n" + standard_input += "\n" + + stdin.write(standard_input) + stdin.flush() + + +def _parse_credential_output(output: str) -> List[str]: + """Parse the output of `git credential fill` to extract the password. + + Args: + output (`str`): + The output of `git credential fill`. + """ + # NOTE: If user has set an helper for a custom URL, it will not we caught here. + # Example: `credential.https://huggingface.co.helper=store` + # See: https://github.com/huggingface/huggingface_hub/pull/1138#discussion_r1013324508 + return sorted( # Sort for nice printing + set( # Might have some duplicates + match[0] for match in GIT_CREDENTIAL_REGEX.findall(output) + ) + ) diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_headers.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_headers.py new file mode 100644 index 0000000000000000000000000000000000000000..fdcaf06e9d19de202a6e84b8bde212d4482d1b07 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_headers.py @@ -0,0 +1,241 @@ +# coding=utf-8 +# Copyright 2022-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contains utilities to handle headers to send in calls to Huggingface Hub.""" + +from typing import Dict, Optional, Union + +from .. import constants +from ._runtime import ( + get_fastai_version, + get_fastcore_version, + get_hf_hub_version, + get_python_version, + get_tf_version, + get_torch_version, + is_fastai_available, + is_fastcore_available, + is_tf_available, + is_torch_available, +) +from ._token import get_token +from ._validators import validate_hf_hub_args + + +class LocalTokenNotFoundError(EnvironmentError): + """Raised if local token is required but not found.""" + + +@validate_hf_hub_args +def build_hf_headers( + *, + token: Optional[Union[bool, str]] = None, + is_write_action: bool = False, + library_name: Optional[str] = None, + library_version: Optional[str] = None, + user_agent: Union[Dict, str, None] = None, + headers: Optional[Dict[str, str]] = None, +) -> Dict[str, str]: + """ + Build headers dictionary to send in a HF Hub call. + + By default, authorization token is always provided either from argument (explicit + use) or retrieved from the cache (implicit use). To explicitly avoid sending the + token to the Hub, set `token=False` or set the `HF_HUB_DISABLE_IMPLICIT_TOKEN` + environment variable. + + In case of an API call that requires write access, an error is thrown if token is + `None` or token is an organization token (starting with `"api_org***"`). + + In addition to the auth header, a user-agent is added to provide information about + the installed packages (versions of python, huggingface_hub, torch, tensorflow, + fastai and fastcore). + + Args: + token (`str`, `bool`, *optional*): + The token to be sent in authorization header for the Hub call: + - if a string, it is used as the Hugging Face token + - if `True`, the token is read from the machine (cache or env variable) + - if `False`, authorization header is not set + - if `None`, the token is read from the machine only except if + `HF_HUB_DISABLE_IMPLICIT_TOKEN` env variable is set. + is_write_action (`bool`, default to `False`): + Set to True if the API call requires a write access. If `True`, the token + will be validated (cannot be `None`, cannot start by `"api_org***"`). + library_name (`str`, *optional*): + The name of the library that is making the HTTP request. Will be added to + the user-agent header. + library_version (`str`, *optional*): + The version of the library that is making the HTTP request. Will be added + to the user-agent header. + user_agent (`str`, `dict`, *optional*): + The user agent info in the form of a dictionary or a single string. It will + be completed with information about the installed packages. + headers (`dict`, *optional*): + Additional headers to include in the request. Those headers take precedence + over the ones generated by this function. + + Returns: + A `Dict` of headers to pass in your API call. + + Example: + ```py + >>> build_hf_headers(token="hf_***") # explicit token + {"authorization": "Bearer hf_***", "user-agent": ""} + + >>> build_hf_headers(token=True) # explicitly use cached token + {"authorization": "Bearer hf_***",...} + + >>> build_hf_headers(token=False) # explicitly don't use cached token + {"user-agent": ...} + + >>> build_hf_headers() # implicit use of the cached token + {"authorization": "Bearer hf_***",...} + + # HF_HUB_DISABLE_IMPLICIT_TOKEN=True # to set as env variable + >>> build_hf_headers() # token is not sent + {"user-agent": ...} + + >>> build_hf_headers(token="api_org_***", is_write_action=True) + ValueError: You must use your personal account token for write-access methods. + + >>> build_hf_headers(library_name="transformers", library_version="1.2.3") + {"authorization": ..., "user-agent": "transformers/1.2.3; hf_hub/0.10.2; python/3.10.4; tensorflow/1.55"} + ``` + + Raises: + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If organization token is passed and "write" access is required. + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If "write" access is required but token is not passed and not saved locally. + [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError) + If `token=True` but token is not saved locally. + """ + # Get auth token to send + token_to_send = get_token_to_send(token) + _validate_token_to_send(token_to_send, is_write_action=is_write_action) + + # Combine headers + hf_headers = { + "user-agent": _http_user_agent( + library_name=library_name, + library_version=library_version, + user_agent=user_agent, + ) + } + if token_to_send is not None: + hf_headers["authorization"] = f"Bearer {token_to_send}" + if headers is not None: + hf_headers.update(headers) + return hf_headers + + +def get_token_to_send(token: Optional[Union[bool, str]]) -> Optional[str]: + """Select the token to send from either `token` or the cache.""" + # Case token is explicitly provided + if isinstance(token, str): + return token + + # Case token is explicitly forbidden + if token is False: + return None + + # Token is not provided: we get it from local cache + cached_token = get_token() + + # Case token is explicitly required + if token is True: + if cached_token is None: + raise LocalTokenNotFoundError( + "Token is required (`token=True`), but no token found. You" + " need to provide a token or be logged in to Hugging Face with" + " `huggingface-cli login` or `huggingface_hub.login`. See" + " https://huggingface.co/settings/tokens." + ) + return cached_token + + # Case implicit use of the token is forbidden by env variable + if constants.HF_HUB_DISABLE_IMPLICIT_TOKEN: + return None + + # Otherwise: we use the cached token as the user has not explicitly forbidden it + return cached_token + + +def _validate_token_to_send(token: Optional[str], is_write_action: bool) -> None: + if is_write_action: + if token is None: + raise ValueError( + "Token is required (write-access action) but no token found. You need" + " to provide a token or be logged in to Hugging Face with" + " `huggingface-cli login` or `huggingface_hub.login`. See" + " https://huggingface.co/settings/tokens." + ) + if token.startswith("api_org"): + raise ValueError( + "You must use your personal account token for write-access methods. To" + " generate a write-access token, go to" + " https://huggingface.co/settings/tokens" + ) + + +def _http_user_agent( + *, + library_name: Optional[str] = None, + library_version: Optional[str] = None, + user_agent: Union[Dict, str, None] = None, +) -> str: + """Format a user-agent string containing information about the installed packages. + + Args: + library_name (`str`, *optional*): + The name of the library that is making the HTTP request. + library_version (`str`, *optional*): + The version of the library that is making the HTTP request. + user_agent (`str`, `dict`, *optional*): + The user agent info in the form of a dictionary or a single string. + + Returns: + The formatted user-agent string. + """ + if library_name is not None: + ua = f"{library_name}/{library_version}" + else: + ua = "unknown/None" + ua += f"; hf_hub/{get_hf_hub_version()}" + ua += f"; python/{get_python_version()}" + + if not constants.HF_HUB_DISABLE_TELEMETRY: + if is_torch_available(): + ua += f"; torch/{get_torch_version()}" + if is_tf_available(): + ua += f"; tensorflow/{get_tf_version()}" + if is_fastai_available(): + ua += f"; fastai/{get_fastai_version()}" + if is_fastcore_available(): + ua += f"; fastcore/{get_fastcore_version()}" + + if isinstance(user_agent, dict): + ua += "; " + "; ".join(f"{k}/{v}" for k, v in user_agent.items()) + elif isinstance(user_agent, str): + ua += "; " + user_agent + + return _deduplicate_user_agent(ua) + + +def _deduplicate_user_agent(user_agent: str) -> str: + """Deduplicate redundant information in the generated user-agent.""" + # Split around ";" > Strip whitespaces > Store as dict keys (ensure unicity) > format back as string + # Order is implicitly preserved by dictionary structure (see https://stackoverflow.com/a/53657523). + return "; ".join({key.strip(): None for key in user_agent.split(";")}.keys()) diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_hf_folder.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_hf_folder.py new file mode 100644 index 0000000000000000000000000000000000000000..502b22658b44d2221b535cbd943348bb93213245 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_hf_folder.py @@ -0,0 +1,96 @@ +# coding=utf-8 +# Copyright 2022-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contain helper class to retrieve/store token from/to local cache.""" + +import warnings +from pathlib import Path +from typing import Optional + +from .. import constants +from ._token import get_token + + +class HfFolder: + path_token = Path(constants.HF_TOKEN_PATH) + # Private attribute. Will be removed in v0.15 + _old_path_token = Path(constants._OLD_HF_TOKEN_PATH) + + # TODO: deprecate when adapted in transformers/datasets/gradio + # @_deprecate_method(version="1.0", message="Use `huggingface_hub.login` instead.") + @classmethod + def save_token(cls, token: str) -> None: + """ + Save token, creating folder as needed. + + Token is saved in the huggingface home folder. You can configure it by setting + the `HF_HOME` environment variable. + + Args: + token (`str`): + The token to save to the [`HfFolder`] + """ + cls.path_token.parent.mkdir(parents=True, exist_ok=True) + cls.path_token.write_text(token) + + # TODO: deprecate when adapted in transformers/datasets/gradio + # @_deprecate_method(version="1.0", message="Use `huggingface_hub.get_token` instead.") + @classmethod + def get_token(cls) -> Optional[str]: + """ + Get token or None if not existent. + + This method is deprecated in favor of [`huggingface_hub.get_token`] but is kept for backward compatibility. + Its behavior is the same as [`huggingface_hub.get_token`]. + + Returns: + `str` or `None`: The token, `None` if it doesn't exist. + """ + # 0. Check if token exist in old path but not new location + try: + cls._copy_to_new_path_and_warn() + except Exception: # if not possible (e.g. PermissionError), do not raise + pass + + return get_token() + + # TODO: deprecate when adapted in transformers/datasets/gradio + # @_deprecate_method(version="1.0", message="Use `huggingface_hub.logout` instead.") + @classmethod + def delete_token(cls) -> None: + """ + Deletes the token from storage. Does not fail if token does not exist. + """ + try: + cls.path_token.unlink() + except FileNotFoundError: + pass + + try: + cls._old_path_token.unlink() + except FileNotFoundError: + pass + + @classmethod + def _copy_to_new_path_and_warn(cls): + if cls._old_path_token.exists() and not cls.path_token.exists(): + cls.save_token(cls._old_path_token.read_text()) + warnings.warn( + f"A token has been found in `{cls._old_path_token}`. This is the old" + " path where tokens were stored. The new location is" + f" `{cls.path_token}` which is configurable using `HF_HOME` environment" + " variable. Your token has been copied to this new location. You can" + " now safely delete the old token file manually or use" + " `huggingface-cli logout`." + ) diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_http.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_http.py new file mode 100644 index 0000000000000000000000000000000000000000..081d84a4f455e5b47c2f0f6483550dc1c8ac7a36 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_http.py @@ -0,0 +1,321 @@ +# coding=utf-8 +# Copyright 2022-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contains utilities to handle HTTP requests in Huggingface Hub.""" + +import io +import os +import threading +import time +import uuid +from functools import lru_cache +from http import HTTPStatus +from typing import Callable, Optional, Tuple, Type, Union + +import requests +from requests import Response +from requests.adapters import HTTPAdapter +from requests.models import PreparedRequest + +from .. import constants +from . import logging +from ._typing import HTTP_METHOD_T + + +logger = logging.get_logger(__name__) + +# Both headers are used by the Hub to debug failed requests. +# `X_AMZN_TRACE_ID` is better as it also works to debug on Cloudfront and ALB. +# If `X_AMZN_TRACE_ID` is set, the Hub will use it as well. +X_AMZN_TRACE_ID = "X-Amzn-Trace-Id" +X_REQUEST_ID = "x-request-id" + + +class OfflineModeIsEnabled(ConnectionError): + """Raised when a request is made but `HF_HUB_OFFLINE=1` is set as environment variable.""" + + +class UniqueRequestIdAdapter(HTTPAdapter): + X_AMZN_TRACE_ID = "X-Amzn-Trace-Id" + + def add_headers(self, request, **kwargs): + super().add_headers(request, **kwargs) + + # Add random request ID => easier for server-side debug + if X_AMZN_TRACE_ID not in request.headers: + request.headers[X_AMZN_TRACE_ID] = request.headers.get(X_REQUEST_ID) or str(uuid.uuid4()) + + # Add debug log + has_token = str(request.headers.get("authorization", "")).startswith("Bearer hf_") + logger.debug( + f"Request {request.headers[X_AMZN_TRACE_ID]}: {request.method} {request.url} (authenticated: {has_token})" + ) + + def send(self, request: PreparedRequest, *args, **kwargs) -> Response: + """Catch any RequestException to append request id to the error message for debugging.""" + try: + return super().send(request, *args, **kwargs) + except requests.RequestException as e: + request_id = request.headers.get(X_AMZN_TRACE_ID) + if request_id is not None: + # Taken from https://stackoverflow.com/a/58270258 + e.args = (*e.args, f"(Request ID: {request_id})") + raise + + +class OfflineAdapter(HTTPAdapter): + def send(self, request: PreparedRequest, *args, **kwargs) -> Response: + raise OfflineModeIsEnabled( + f"Cannot reach {request.url}: offline mode is enabled. To disable it, please unset the `HF_HUB_OFFLINE` environment variable." + ) + + +def _default_backend_factory() -> requests.Session: + session = requests.Session() + if constants.HF_HUB_OFFLINE: + session.mount("http://", OfflineAdapter()) + session.mount("https://", OfflineAdapter()) + else: + session.mount("http://", UniqueRequestIdAdapter()) + session.mount("https://", UniqueRequestIdAdapter()) + return session + + +BACKEND_FACTORY_T = Callable[[], requests.Session] +_GLOBAL_BACKEND_FACTORY: BACKEND_FACTORY_T = _default_backend_factory + + +def configure_http_backend(backend_factory: BACKEND_FACTORY_T = _default_backend_factory) -> None: + """ + Configure the HTTP backend by providing a `backend_factory`. Any HTTP calls made by `huggingface_hub` will use a + Session object instantiated by this factory. This can be useful if you are running your scripts in a specific + environment requiring custom configuration (e.g. custom proxy or certifications). + + Use [`get_session`] to get a configured Session. Since `requests.Session` is not guaranteed to be thread-safe, + `huggingface_hub` creates 1 Session instance per thread. They are all instantiated using the same `backend_factory` + set in [`configure_http_backend`]. A LRU cache is used to cache the created sessions (and connections) between + calls. Max size is 128 to avoid memory leaks if thousands of threads are spawned. + + See [this issue](https://github.com/psf/requests/issues/2766) to know more about thread-safety in `requests`. + + Example: + ```py + import requests + from huggingface_hub import configure_http_backend, get_session + + # Create a factory function that returns a Session with configured proxies + def backend_factory() -> requests.Session: + session = requests.Session() + session.proxies = {"http": "http://10.10.1.10:3128", "https": "https://10.10.1.11:1080"} + return session + + # Set it as the default session factory + configure_http_backend(backend_factory=backend_factory) + + # In practice, this is mostly done internally in `huggingface_hub` + session = get_session() + ``` + """ + global _GLOBAL_BACKEND_FACTORY + _GLOBAL_BACKEND_FACTORY = backend_factory + reset_sessions() + + +def get_session() -> requests.Session: + """ + Get a `requests.Session` object, using the session factory from the user. + + Use [`get_session`] to get a configured Session. Since `requests.Session` is not guaranteed to be thread-safe, + `huggingface_hub` creates 1 Session instance per thread. They are all instantiated using the same `backend_factory` + set in [`configure_http_backend`]. A LRU cache is used to cache the created sessions (and connections) between + calls. Max size is 128 to avoid memory leaks if thousands of threads are spawned. + + See [this issue](https://github.com/psf/requests/issues/2766) to know more about thread-safety in `requests`. + + Example: + ```py + import requests + from huggingface_hub import configure_http_backend, get_session + + # Create a factory function that returns a Session with configured proxies + def backend_factory() -> requests.Session: + session = requests.Session() + session.proxies = {"http": "http://10.10.1.10:3128", "https": "https://10.10.1.11:1080"} + return session + + # Set it as the default session factory + configure_http_backend(backend_factory=backend_factory) + + # In practice, this is mostly done internally in `huggingface_hub` + session = get_session() + ``` + """ + return _get_session_from_cache(process_id=os.getpid(), thread_id=threading.get_ident()) + + +def reset_sessions() -> None: + """Reset the cache of sessions. + + Mostly used internally when sessions are reconfigured or an SSLError is raised. + See [`configure_http_backend`] for more details. + """ + _get_session_from_cache.cache_clear() + + +@lru_cache +def _get_session_from_cache(process_id: int, thread_id: int) -> requests.Session: + """ + Create a new session per thread using global factory. Using LRU cache (maxsize 128) to avoid memory leaks when + using thousands of threads. Cache is cleared when `configure_http_backend` is called. + """ + return _GLOBAL_BACKEND_FACTORY() + + +def http_backoff( + method: HTTP_METHOD_T, + url: str, + *, + max_retries: int = 5, + base_wait_time: float = 1, + max_wait_time: float = 8, + retry_on_exceptions: Union[Type[Exception], Tuple[Type[Exception], ...]] = ( + requests.Timeout, + requests.ConnectionError, + ), + retry_on_status_codes: Union[int, Tuple[int, ...]] = HTTPStatus.SERVICE_UNAVAILABLE, + **kwargs, +) -> Response: + """Wrapper around requests to retry calls on an endpoint, with exponential backoff. + + Endpoint call is retried on exceptions (ex: connection timeout, proxy error,...) + and/or on specific status codes (ex: service unavailable). If the call failed more + than `max_retries`, the exception is thrown or `raise_for_status` is called on the + response object. + + Re-implement mechanisms from the `backoff` library to avoid adding an external + dependencies to `hugging_face_hub`. See https://github.com/litl/backoff. + + Args: + method (`Literal["GET", "OPTIONS", "HEAD", "POST", "PUT", "PATCH", "DELETE"]`): + HTTP method to perform. + url (`str`): + The URL of the resource to fetch. + max_retries (`int`, *optional*, defaults to `5`): + Maximum number of retries, defaults to 5 (no retries). + base_wait_time (`float`, *optional*, defaults to `1`): + Duration (in seconds) to wait before retrying the first time. + Wait time between retries then grows exponentially, capped by + `max_wait_time`. + max_wait_time (`float`, *optional*, defaults to `8`): + Maximum duration (in seconds) to wait before retrying. + retry_on_exceptions (`Type[Exception]` or `Tuple[Type[Exception]]`, *optional*): + Define which exceptions must be caught to retry the request. Can be a single type or a tuple of types. + By default, retry on `requests.Timeout` and `requests.ConnectionError`. + retry_on_status_codes (`int` or `Tuple[int]`, *optional*, defaults to `503`): + Define on which status codes the request must be retried. By default, only + HTTP 503 Service Unavailable is retried. + **kwargs (`dict`, *optional*): + kwargs to pass to `requests.request`. + + Example: + ``` + >>> from huggingface_hub.utils import http_backoff + + # Same usage as "requests.request". + >>> response = http_backoff("GET", "https://www.google.com") + >>> response.raise_for_status() + + # If you expect a Gateway Timeout from time to time + >>> http_backoff("PUT", upload_url, data=data, retry_on_status_codes=504) + >>> response.raise_for_status() + ``` + + + + When using `requests` it is possible to stream data by passing an iterator to the + `data` argument. On http backoff this is a problem as the iterator is not reset + after a failed call. This issue is mitigated for file objects or any IO streams + by saving the initial position of the cursor (with `data.tell()`) and resetting the + cursor between each call (with `data.seek()`). For arbitrary iterators, http backoff + will fail. If this is a hard constraint for you, please let us know by opening an + issue on [Github](https://github.com/huggingface/huggingface_hub). + + + """ + if isinstance(retry_on_exceptions, type): # Tuple from single exception type + retry_on_exceptions = (retry_on_exceptions,) + + if isinstance(retry_on_status_codes, int): # Tuple from single status code + retry_on_status_codes = (retry_on_status_codes,) + + nb_tries = 0 + sleep_time = base_wait_time + + # If `data` is used and is a file object (or any IO), it will be consumed on the + # first HTTP request. We need to save the initial position so that the full content + # of the file is re-sent on http backoff. See warning tip in docstring. + io_obj_initial_pos = None + if "data" in kwargs and isinstance(kwargs["data"], io.IOBase): + io_obj_initial_pos = kwargs["data"].tell() + + session = get_session() + while True: + nb_tries += 1 + try: + # If `data` is used and is a file object (or any IO), set back cursor to + # initial position. + if io_obj_initial_pos is not None: + kwargs["data"].seek(io_obj_initial_pos) + + # Perform request and return if status_code is not in the retry list. + response = session.request(method=method, url=url, **kwargs) + if response.status_code not in retry_on_status_codes: + return response + + # Wrong status code returned (HTTP 503 for instance) + logger.warning(f"HTTP Error {response.status_code} thrown while requesting {method} {url}") + if nb_tries > max_retries: + response.raise_for_status() # Will raise uncaught exception + # We return response to avoid infinite loop in the corner case where the + # user ask for retry on a status code that doesn't raise_for_status. + return response + + except retry_on_exceptions as err: + logger.warning(f"'{err}' thrown while requesting {method} {url}") + + if isinstance(err, requests.ConnectionError): + reset_sessions() # In case of SSLError it's best to reset the shared requests.Session objects + + if nb_tries > max_retries: + raise err + + # Sleep for X seconds + logger.warning(f"Retrying in {sleep_time}s [Retry {nb_tries}/{max_retries}].") + time.sleep(sleep_time) + + # Update sleep time for next retry + sleep_time = min(max_wait_time, sleep_time * 2) # Exponential backoff + + +def fix_hf_endpoint_in_url(url: str, endpoint: Optional[str]) -> str: + """Replace the default endpoint in a URL by a custom one. + + This is useful when using a proxy and the Hugging Face Hub returns a URL with the default endpoint. + """ + endpoint = endpoint or constants.ENDPOINT + # check if a proxy has been set => if yes, update the returned URL to use the proxy + if endpoint not in (None, constants._HF_DEFAULT_ENDPOINT, constants._HF_DEFAULT_STAGING_ENDPOINT): + url = url.replace(constants._HF_DEFAULT_ENDPOINT, endpoint) + url = url.replace(constants._HF_DEFAULT_STAGING_ENDPOINT, endpoint) + return url diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_pagination.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_pagination.py new file mode 100644 index 0000000000000000000000000000000000000000..f7ab4fe7cba9bd13f01d9c81854a00fd30b7f0d9 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_pagination.py @@ -0,0 +1,52 @@ +# coding=utf-8 +# Copyright 2022-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contains utilities to handle pagination on Huggingface Hub.""" + +from typing import Dict, Iterable, Optional + +import requests + +from . import get_session, hf_raise_for_status, logging + + +logger = logging.get_logger(__name__) + + +def paginate(path: str, params: Dict, headers: Dict) -> Iterable: + """Fetch a list of models/datasets/spaces and paginate through results. + + This is using the same "Link" header format as GitHub. + See: + - https://requests.readthedocs.io/en/latest/api/#requests.Response.links + - https://docs.github.com/en/rest/guides/traversing-with-pagination#link-header + """ + session = get_session() + r = session.get(path, params=params, headers=headers) + hf_raise_for_status(r) + yield from r.json() + + # Follow pages + # Next link already contains query params + next_page = _get_next_page(r) + while next_page is not None: + logger.debug(f"Pagination detected. Requesting next page: {next_page}") + r = session.get(next_page, headers=headers) + hf_raise_for_status(r) + yield from r.json() + next_page = _get_next_page(r) + + +def _get_next_page(response: requests.Response) -> Optional[str]: + return response.links.get("next", {}).get("url") diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_paths.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_paths.py new file mode 100644 index 0000000000000000000000000000000000000000..411d7d52bb3edc2be948d85267e21ce2be91d460 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_paths.py @@ -0,0 +1,118 @@ +# coding=utf-8 +# Copyright 2022-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contains utilities to handle paths in Huggingface Hub.""" + +from fnmatch import fnmatch +from pathlib import Path +from typing import Callable, Generator, Iterable, List, Optional, TypeVar, Union + + +T = TypeVar("T") + +IGNORE_GIT_FOLDER_PATTERNS = [".git", ".git/*", "*/.git", "**/.git/**"] + + +def filter_repo_objects( + items: Iterable[T], + *, + allow_patterns: Optional[Union[List[str], str]] = None, + ignore_patterns: Optional[Union[List[str], str]] = None, + key: Optional[Callable[[T], str]] = None, +) -> Generator[T, None, None]: + """Filter repo objects based on an allowlist and a denylist. + + Input must be a list of paths (`str` or `Path`) or a list of arbitrary objects. + In the later case, `key` must be provided and specifies a function of one argument + that is used to extract a path from each element in iterable. + + Patterns are Unix shell-style wildcards which are NOT regular expressions. See + https://docs.python.org/3/library/fnmatch.html for more details. + + Args: + items (`Iterable`): + List of items to filter. + allow_patterns (`str` or `List[str]`, *optional*): + Patterns constituting the allowlist. If provided, item paths must match at + least one pattern from the allowlist. + ignore_patterns (`str` or `List[str]`, *optional*): + Patterns constituting the denylist. If provided, item paths must not match + any patterns from the denylist. + key (`Callable[[T], str]`, *optional*): + Single-argument function to extract a path from each item. If not provided, + the `items` must already be `str` or `Path`. + + Returns: + Filtered list of objects, as a generator. + + Raises: + :class:`ValueError`: + If `key` is not provided and items are not `str` or `Path`. + + Example usage with paths: + ```python + >>> # Filter only PDFs that are not hidden. + >>> list(filter_repo_objects( + ... ["aaa.PDF", "bbb.jpg", ".ccc.pdf", ".ddd.png"], + ... allow_patterns=["*.pdf"], + ... ignore_patterns=[".*"], + ... )) + ["aaa.pdf"] + ``` + + Example usage with objects: + ```python + >>> list(filter_repo_objects( + ... [ + ... CommitOperationAdd(path_or_fileobj="/tmp/aaa.pdf", path_in_repo="aaa.pdf") + ... CommitOperationAdd(path_or_fileobj="/tmp/bbb.jpg", path_in_repo="bbb.jpg") + ... CommitOperationAdd(path_or_fileobj="/tmp/.ccc.pdf", path_in_repo=".ccc.pdf") + ... CommitOperationAdd(path_or_fileobj="/tmp/.ddd.png", path_in_repo=".ddd.png") + ... ], + ... allow_patterns=["*.pdf"], + ... ignore_patterns=[".*"], + ... key=lambda x: x.repo_in_path + ... )) + [CommitOperationAdd(path_or_fileobj="/tmp/aaa.pdf", path_in_repo="aaa.pdf")] + ``` + """ + if isinstance(allow_patterns, str): + allow_patterns = [allow_patterns] + + if isinstance(ignore_patterns, str): + ignore_patterns = [ignore_patterns] + + if key is None: + + def _identity(item: T) -> str: + if isinstance(item, str): + return item + if isinstance(item, Path): + return str(item) + raise ValueError(f"Please provide `key` argument in `filter_repo_objects`: `{item}` is not a string.") + + key = _identity # Items must be `str` or `Path`, otherwise raise ValueError + + for item in items: + path = key(item) + + # Skip if there's an allowlist and path doesn't match any + if allow_patterns is not None and not any(fnmatch(path, r) for r in allow_patterns): + continue + + # Skip if there's a denylist and path matches any + if ignore_patterns is not None and any(fnmatch(path, r) for r in ignore_patterns): + continue + + yield item diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_runtime.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..21f852736c841be1caa747f8dc6c8657c0e3d8f2 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_runtime.py @@ -0,0 +1,372 @@ +# coding=utf-8 +# Copyright 2022-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Check presence of installed packages at runtime.""" + +import importlib.metadata +import platform +import sys +import warnings +from typing import Any, Dict + +from .. import __version__, constants + + +_PY_VERSION: str = sys.version.split()[0].rstrip("+") + +_package_versions = {} + +_CANDIDATES = { + "aiohttp": {"aiohttp"}, + "fastai": {"fastai"}, + "fastcore": {"fastcore"}, + "gradio": {"gradio"}, + "graphviz": {"graphviz"}, + "hf_transfer": {"hf_transfer"}, + "jinja": {"Jinja2"}, + "keras": {"keras"}, + "minijinja": {"minijinja"}, + "numpy": {"numpy"}, + "pillow": {"Pillow"}, + "pydantic": {"pydantic"}, + "pydot": {"pydot"}, + "safetensors": {"safetensors"}, + "tensorboard": {"tensorboardX"}, + "tensorflow": ( + "tensorflow", + "tensorflow-cpu", + "tensorflow-gpu", + "tf-nightly", + "tf-nightly-cpu", + "tf-nightly-gpu", + "intel-tensorflow", + "intel-tensorflow-avx512", + "tensorflow-rocm", + "tensorflow-macos", + ), + "torch": {"torch"}, +} + +# Check once at runtime +for candidate_name, package_names in _CANDIDATES.items(): + _package_versions[candidate_name] = "N/A" + for name in package_names: + try: + _package_versions[candidate_name] = importlib.metadata.version(name) + break + except importlib.metadata.PackageNotFoundError: + pass + + +def _get_version(package_name: str) -> str: + return _package_versions.get(package_name, "N/A") + + +def is_package_available(package_name: str) -> bool: + return _get_version(package_name) != "N/A" + + +# Python +def get_python_version() -> str: + return _PY_VERSION + + +# Huggingface Hub +def get_hf_hub_version() -> str: + return __version__ + + +# aiohttp +def is_aiohttp_available() -> bool: + return is_package_available("aiohttp") + + +def get_aiohttp_version() -> str: + return _get_version("aiohttp") + + +# FastAI +def is_fastai_available() -> bool: + return is_package_available("fastai") + + +def get_fastai_version() -> str: + return _get_version("fastai") + + +# Fastcore +def is_fastcore_available() -> bool: + return is_package_available("fastcore") + + +def get_fastcore_version() -> str: + return _get_version("fastcore") + + +# FastAI +def is_gradio_available() -> bool: + return is_package_available("gradio") + + +def get_gradio_version() -> str: + return _get_version("gradio") + + +# Graphviz +def is_graphviz_available() -> bool: + return is_package_available("graphviz") + + +def get_graphviz_version() -> str: + return _get_version("graphviz") + + +# hf_transfer +def is_hf_transfer_available() -> bool: + return is_package_available("hf_transfer") + + +def get_hf_transfer_version() -> str: + return _get_version("hf_transfer") + + +# keras +def is_keras_available() -> bool: + return is_package_available("keras") + + +def get_keras_version() -> str: + return _get_version("keras") + + +# Minijinja +def is_minijinja_available() -> bool: + return is_package_available("minijinja") + + +def get_minijinja_version() -> str: + return _get_version("minijinja") + + +# Numpy +def is_numpy_available() -> bool: + return is_package_available("numpy") + + +def get_numpy_version() -> str: + return _get_version("numpy") + + +# Jinja +def is_jinja_available() -> bool: + return is_package_available("jinja") + + +def get_jinja_version() -> str: + return _get_version("jinja") + + +# Pillow +def is_pillow_available() -> bool: + return is_package_available("pillow") + + +def get_pillow_version() -> str: + return _get_version("pillow") + + +# Pydantic +def is_pydantic_available() -> bool: + if not is_package_available("pydantic"): + return False + # For Pydantic, we add an extra check to test whether it is correctly installed or not. If both pydantic 2.x and + # typing_extensions<=4.5.0 are installed, then pydantic will fail at import time. This should not happen when + # it is installed with `pip install huggingface_hub[inference]` but it can happen when it is installed manually + # by the user in an environment that we don't control. + # + # Usually we won't need to do this kind of check on optional dependencies. However, pydantic is a special case + # as it is automatically imported when doing `from huggingface_hub import ...` even if the user doesn't use it. + # + # See https://github.com/huggingface/huggingface_hub/pull/1829 for more details. + try: + from pydantic import validator # noqa: F401 + except ImportError: + # Example: "ImportError: cannot import name 'TypeAliasType' from 'typing_extensions'" + warnings.warn( + "Pydantic is installed but cannot be imported. Please check your installation. `huggingface_hub` will " + "default to not using Pydantic. Error message: '{e}'" + ) + return False + return True + + +def get_pydantic_version() -> str: + return _get_version("pydantic") + + +# Pydot +def is_pydot_available() -> bool: + return is_package_available("pydot") + + +def get_pydot_version() -> str: + return _get_version("pydot") + + +# Tensorboard +def is_tensorboard_available() -> bool: + return is_package_available("tensorboard") + + +def get_tensorboard_version() -> str: + return _get_version("tensorboard") + + +# Tensorflow +def is_tf_available() -> bool: + return is_package_available("tensorflow") + + +def get_tf_version() -> str: + return _get_version("tensorflow") + + +# Torch +def is_torch_available() -> bool: + return is_package_available("torch") + + +def get_torch_version() -> str: + return _get_version("torch") + + +# Safetensors +def is_safetensors_available() -> bool: + return is_package_available("safetensors") + + +# Shell-related helpers +try: + # Set to `True` if script is running in a Google Colab notebook. + # If running in Google Colab, git credential store is set globally which makes the + # warning disappear. See https://github.com/huggingface/huggingface_hub/issues/1043 + # + # Taken from https://stackoverflow.com/a/63519730. + _is_google_colab = "google.colab" in str(get_ipython()) # type: ignore # noqa: F821 +except NameError: + _is_google_colab = False + + +def is_notebook() -> bool: + """Return `True` if code is executed in a notebook (Jupyter, Colab, QTconsole). + + Taken from https://stackoverflow.com/a/39662359. + Adapted to make it work with Google colab as well. + """ + try: + shell_class = get_ipython().__class__ # type: ignore # noqa: F821 + for parent_class in shell_class.__mro__: # e.g. "is subclass of" + if parent_class.__name__ == "ZMQInteractiveShell": + return True # Jupyter notebook, Google colab or qtconsole + return False + except NameError: + return False # Probably standard Python interpreter + + +def is_google_colab() -> bool: + """Return `True` if code is executed in a Google colab. + + Taken from https://stackoverflow.com/a/63519730. + """ + return _is_google_colab + + +def dump_environment_info() -> Dict[str, Any]: + """Dump information about the machine to help debugging issues. + + Similar helper exist in: + - `datasets` (https://github.com/huggingface/datasets/blob/main/src/datasets/commands/env.py) + - `diffusers` (https://github.com/huggingface/diffusers/blob/main/src/diffusers/commands/env.py) + - `transformers` (https://github.com/huggingface/transformers/blob/main/src/transformers/commands/env.py) + """ + from huggingface_hub import get_token, whoami + from huggingface_hub.utils import list_credential_helpers + + token = get_token() + + # Generic machine info + info: Dict[str, Any] = { + "huggingface_hub version": get_hf_hub_version(), + "Platform": platform.platform(), + "Python version": get_python_version(), + } + + # Interpreter info + try: + shell_class = get_ipython().__class__ # type: ignore # noqa: F821 + info["Running in iPython ?"] = "Yes" + info["iPython shell"] = shell_class.__name__ + except NameError: + info["Running in iPython ?"] = "No" + info["Running in notebook ?"] = "Yes" if is_notebook() else "No" + info["Running in Google Colab ?"] = "Yes" if is_google_colab() else "No" + + # Login info + info["Token path ?"] = constants.HF_TOKEN_PATH + info["Has saved token ?"] = token is not None + if token is not None: + try: + info["Who am I ?"] = whoami()["name"] + except Exception: + pass + + try: + info["Configured git credential helpers"] = ", ".join(list_credential_helpers()) + except Exception: + pass + + # Installed dependencies + info["FastAI"] = get_fastai_version() + info["Tensorflow"] = get_tf_version() + info["Torch"] = get_torch_version() + info["Jinja2"] = get_jinja_version() + info["Graphviz"] = get_graphviz_version() + info["keras"] = get_keras_version() + info["Pydot"] = get_pydot_version() + info["Pillow"] = get_pillow_version() + info["hf_transfer"] = get_hf_transfer_version() + info["gradio"] = get_gradio_version() + info["tensorboard"] = get_tensorboard_version() + info["numpy"] = get_numpy_version() + info["pydantic"] = get_pydantic_version() + info["aiohttp"] = get_aiohttp_version() + + # Environment variables + info["ENDPOINT"] = constants.ENDPOINT + info["HF_HUB_CACHE"] = constants.HF_HUB_CACHE + info["HF_ASSETS_CACHE"] = constants.HF_ASSETS_CACHE + info["HF_TOKEN_PATH"] = constants.HF_TOKEN_PATH + info["HF_HUB_OFFLINE"] = constants.HF_HUB_OFFLINE + info["HF_HUB_DISABLE_TELEMETRY"] = constants.HF_HUB_DISABLE_TELEMETRY + info["HF_HUB_DISABLE_PROGRESS_BARS"] = constants.HF_HUB_DISABLE_PROGRESS_BARS + info["HF_HUB_DISABLE_SYMLINKS_WARNING"] = constants.HF_HUB_DISABLE_SYMLINKS_WARNING + info["HF_HUB_DISABLE_EXPERIMENTAL_WARNING"] = constants.HF_HUB_DISABLE_EXPERIMENTAL_WARNING + info["HF_HUB_DISABLE_IMPLICIT_TOKEN"] = constants.HF_HUB_DISABLE_IMPLICIT_TOKEN + info["HF_HUB_ENABLE_HF_TRANSFER"] = constants.HF_HUB_ENABLE_HF_TRANSFER + info["HF_HUB_ETAG_TIMEOUT"] = constants.HF_HUB_ETAG_TIMEOUT + info["HF_HUB_DOWNLOAD_TIMEOUT"] = constants.HF_HUB_DOWNLOAD_TIMEOUT + + print("\nCopy-and-paste the text below in your GitHub issue.\n") + print("\n".join([f"- {prop}: {val}" for prop, val in info.items()]) + "\n") + return info diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_safetensors.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_safetensors.py new file mode 100644 index 0000000000000000000000000000000000000000..d37e8f76fee25976d48ad591fe8afb277ae6ef38 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_safetensors.py @@ -0,0 +1,124 @@ +import functools +import operator +from collections import defaultdict +from dataclasses import dataclass, field +from typing import Dict, List, Literal, Optional, Tuple + + +FILENAME_T = str +TENSOR_NAME_T = str +DTYPE_T = Literal["F64", "F32", "F16", "BF16", "I64", "I32", "I16", "I8", "U8", "BOOL"] + + +class SafetensorsParsingError(Exception): + """Raised when failing to parse a safetensors file metadata. + + This can be the case if the file is not a safetensors file or does not respect the specification. + """ + + +class NotASafetensorsRepoError(Exception): + """Raised when a repo is not a Safetensors repo i.e. doesn't have either a `model.safetensors` or a + `model.safetensors.index.json` file. + """ + + +@dataclass +class TensorInfo: + """Information about a tensor. + + For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format. + + Attributes: + dtype (`str`): + The data type of the tensor ("F64", "F32", "F16", "BF16", "I64", "I32", "I16", "I8", "U8", "BOOL"). + shape (`List[int]`): + The shape of the tensor. + data_offsets (`Tuple[int, int]`): + The offsets of the data in the file as a tuple `[BEGIN, END]`. + parameter_count (`int`): + The number of parameters in the tensor. + """ + + dtype: DTYPE_T + shape: List[int] + data_offsets: Tuple[int, int] + parameter_count: int = field(init=False) + + def __post_init__(self) -> None: + # Taken from https://stackoverflow.com/a/13840436 + try: + self.parameter_count = functools.reduce(operator.mul, self.shape) + except TypeError: + self.parameter_count = 1 # scalar value has no shape + + +@dataclass +class SafetensorsFileMetadata: + """Metadata for a Safetensors file hosted on the Hub. + + This class is returned by [`parse_safetensors_file_metadata`]. + + For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format. + + Attributes: + metadata (`Dict`): + The metadata contained in the file. + tensors (`Dict[str, TensorInfo]`): + A map of all tensors. Keys are tensor names and values are information about the corresponding tensor, as a + [`TensorInfo`] object. + parameter_count (`Dict[str, int]`): + A map of the number of parameters per data type. Keys are data types and values are the number of parameters + of that data type. + """ + + metadata: Dict[str, str] + tensors: Dict[TENSOR_NAME_T, TensorInfo] + parameter_count: Dict[DTYPE_T, int] = field(init=False) + + def __post_init__(self) -> None: + parameter_count: Dict[DTYPE_T, int] = defaultdict(int) + for tensor in self.tensors.values(): + parameter_count[tensor.dtype] += tensor.parameter_count + self.parameter_count = dict(parameter_count) + + +@dataclass +class SafetensorsRepoMetadata: + """Metadata for a Safetensors repo. + + A repo is considered to be a Safetensors repo if it contains either a 'model.safetensors' weight file (non-shared + model) or a 'model.safetensors.index.json' index file (sharded model) at its root. + + This class is returned by [`get_safetensors_metadata`]. + + For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format. + + Attributes: + metadata (`Dict`, *optional*): + The metadata contained in the 'model.safetensors.index.json' file, if it exists. Only populated for sharded + models. + sharded (`bool`): + Whether the repo contains a sharded model or not. + weight_map (`Dict[str, str]`): + A map of all weights. Keys are tensor names and values are filenames of the files containing the tensors. + files_metadata (`Dict[str, SafetensorsFileMetadata]`): + A map of all files metadata. Keys are filenames and values are the metadata of the corresponding file, as + a [`SafetensorsFileMetadata`] object. + parameter_count (`Dict[str, int]`): + A map of the number of parameters per data type. Keys are data types and values are the number of parameters + of that data type. + """ + + metadata: Optional[Dict] + sharded: bool + weight_map: Dict[TENSOR_NAME_T, FILENAME_T] # tensor name -> filename + files_metadata: Dict[FILENAME_T, SafetensorsFileMetadata] # filename -> metadata + parameter_count: Dict[DTYPE_T, int] = field(init=False) + + def __post_init__(self) -> None: + parameter_count: Dict[DTYPE_T, int] = defaultdict(int) + for file_metadata in self.files_metadata.values(): + for dtype, nb_parameters_ in file_metadata.parameter_count.items(): + parameter_count[dtype] += nb_parameters_ + self.parameter_count = dict(parameter_count) diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_subprocess.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_subprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..a09e0d58868ecd699ea3a3e503a8a702d25c8ea5 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_subprocess.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python +# coding=utf-8 +# Copyright 2021 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License +"""Contains utilities to easily handle subprocesses in `huggingface_hub`.""" + +import os +import subprocess +import sys +from contextlib import contextmanager +from io import StringIO +from pathlib import Path +from typing import IO, Generator, List, Optional, Tuple, Union + +from .logging import get_logger + + +logger = get_logger(__name__) + + +@contextmanager +def capture_output() -> Generator[StringIO, None, None]: + """Capture output that is printed to terminal. + + Taken from https://stackoverflow.com/a/34738440 + + Example: + ```py + >>> with capture_output() as output: + ... print("hello world") + >>> assert output.getvalue() == "hello world\n" + ``` + """ + output = StringIO() + previous_output = sys.stdout + sys.stdout = output + yield output + sys.stdout = previous_output + + +def run_subprocess( + command: Union[str, List[str]], + folder: Optional[Union[str, Path]] = None, + check=True, + **kwargs, +) -> subprocess.CompletedProcess: + """ + Method to run subprocesses. Calling this will capture the `stderr` and `stdout`, + please call `subprocess.run` manually in case you would like for them not to + be captured. + + Args: + command (`str` or `List[str]`): + The command to execute as a string or list of strings. + folder (`str`, *optional*): + The folder in which to run the command. Defaults to current working + directory (from `os.getcwd()`). + check (`bool`, *optional*, defaults to `True`): + Setting `check` to `True` will raise a `subprocess.CalledProcessError` + when the subprocess has a non-zero exit code. + kwargs (`Dict[str]`): + Keyword arguments to be passed to the `subprocess.run` underlying command. + + Returns: + `subprocess.CompletedProcess`: The completed process. + """ + if isinstance(command, str): + command = command.split() + + if isinstance(folder, Path): + folder = str(folder) + + return subprocess.run( + command, + stderr=subprocess.PIPE, + stdout=subprocess.PIPE, + check=check, + encoding="utf-8", + errors="replace", # if not utf-8, replace char by � + cwd=folder or os.getcwd(), + **kwargs, + ) + + +@contextmanager +def run_interactive_subprocess( + command: Union[str, List[str]], + folder: Optional[Union[str, Path]] = None, + **kwargs, +) -> Generator[Tuple[IO[str], IO[str]], None, None]: + """Run a subprocess in an interactive mode in a context manager. + + Args: + command (`str` or `List[str]`): + The command to execute as a string or list of strings. + folder (`str`, *optional*): + The folder in which to run the command. Defaults to current working + directory (from `os.getcwd()`). + kwargs (`Dict[str]`): + Keyword arguments to be passed to the `subprocess.run` underlying command. + + Returns: + `Tuple[IO[str], IO[str]]`: A tuple with `stdin` and `stdout` to interact + with the process (input and output are utf-8 encoded). + + Example: + ```python + with _interactive_subprocess("git credential-store get") as (stdin, stdout): + # Write to stdin + stdin.write("url=hf.co\nusername=obama\n".encode("utf-8")) + stdin.flush() + + # Read from stdout + output = stdout.read().decode("utf-8") + ``` + """ + if isinstance(command, str): + command = command.split() + + with subprocess.Popen( + command, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + encoding="utf-8", + errors="replace", # if not utf-8, replace char by � + cwd=folder or os.getcwd(), + **kwargs, + ) as process: + assert process.stdin is not None, "subprocess is opened as subprocess.PIPE" + assert process.stdout is not None, "subprocess is opened as subprocess.PIPE" + yield process.stdin, process.stdout diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_telemetry.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_telemetry.py new file mode 100644 index 0000000000000000000000000000000000000000..5de988e2795188324f69232d1beb68191591715d --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_telemetry.py @@ -0,0 +1,118 @@ +from queue import Queue +from threading import Lock, Thread +from typing import Dict, Optional, Union +from urllib.parse import quote + +from .. import constants, logging +from . import build_hf_headers, get_session, hf_raise_for_status + + +logger = logging.get_logger(__name__) + +# Telemetry is sent by a separate thread to avoid blocking the main thread. +# A daemon thread is started once and consume tasks from the _TELEMETRY_QUEUE. +# If the thread stops for some reason -shouldn't happen-, we restart a new one. +_TELEMETRY_THREAD: Optional[Thread] = None +_TELEMETRY_THREAD_LOCK = Lock() # Lock to avoid starting multiple threads in parallel +_TELEMETRY_QUEUE: Queue = Queue() + + +def send_telemetry( + topic: str, + *, + library_name: Optional[str] = None, + library_version: Optional[str] = None, + user_agent: Union[Dict, str, None] = None, +) -> None: + """ + Sends telemetry that helps tracking usage of different HF libraries. + + This usage data helps us debug issues and prioritize new features. However, we understand that not everyone wants + to share additional information, and we respect your privacy. You can disable telemetry collection by setting the + `HF_HUB_DISABLE_TELEMETRY=1` as environment variable. Telemetry is also disabled in offline mode (i.e. when setting + `HF_HUB_OFFLINE=1`). + + Telemetry collection is run in a separate thread to minimize impact for the user. + + Args: + topic (`str`): + Name of the topic that is monitored. The topic is directly used to build the URL. If you want to monitor + subtopics, just use "/" separation. Examples: "gradio", "transformers/examples",... + library_name (`str`, *optional*): + The name of the library that is making the HTTP request. Will be added to the user-agent header. + library_version (`str`, *optional*): + The version of the library that is making the HTTP request. Will be added to the user-agent header. + user_agent (`str`, `dict`, *optional*): + The user agent info in the form of a dictionary or a single string. It will be completed with information about the installed packages. + + Example: + ```py + >>> from huggingface_hub.utils import send_telemetry + + # Send telemetry without library information + >>> send_telemetry("ping") + + # Send telemetry to subtopic with library information + >>> send_telemetry("gradio/local_link", library_name="gradio", library_version="3.22.1") + + # Send telemetry with additional data + >>> send_telemetry( + ... topic="examples", + ... library_name="transformers", + ... library_version="4.26.0", + ... user_agent={"pipeline": "text_classification", "framework": "flax"}, + ... ) + ``` + """ + if constants.HF_HUB_OFFLINE or constants.HF_HUB_DISABLE_TELEMETRY: + return + + _start_telemetry_thread() # starts thread only if doesn't exist yet + _TELEMETRY_QUEUE.put( + {"topic": topic, "library_name": library_name, "library_version": library_version, "user_agent": user_agent} + ) + + +def _start_telemetry_thread(): + """Start a daemon thread to consume tasks from the telemetry queue. + + If the thread is interrupted, start a new one. + """ + with _TELEMETRY_THREAD_LOCK: # avoid to start multiple threads if called concurrently + global _TELEMETRY_THREAD + if _TELEMETRY_THREAD is None or not _TELEMETRY_THREAD.is_alive(): + _TELEMETRY_THREAD = Thread(target=_telemetry_worker, daemon=True) + _TELEMETRY_THREAD.start() + + +def _telemetry_worker(): + """Wait for a task and consume it.""" + while True: + kwargs = _TELEMETRY_QUEUE.get() + _send_telemetry_in_thread(**kwargs) + _TELEMETRY_QUEUE.task_done() + + +def _send_telemetry_in_thread( + topic: str, + *, + library_name: Optional[str] = None, + library_version: Optional[str] = None, + user_agent: Union[Dict, str, None] = None, +) -> None: + """Contains the actual data sending data to the Hub.""" + path = "/".join(quote(part) for part in topic.split("/") if len(part) > 0) + try: + r = get_session().head( + f"{constants.ENDPOINT}/api/telemetry/{path}", + headers=build_hf_headers( + token=False, # no need to send a token for telemetry + library_name=library_name, + library_version=library_version, + user_agent=user_agent, + ), + ) + hf_raise_for_status(r) + except Exception as e: + # We don't want to error in case of connection errors of any kind. + logger.debug(f"Error while sending telemetry: {e}") diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_token.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_token.py new file mode 100644 index 0000000000000000000000000000000000000000..3218bb45c0737f67912c9c257734c463f5871255 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_token.py @@ -0,0 +1,130 @@ +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contains an helper to get the token from machine (env variable, secret or config file).""" + +import os +import warnings +from pathlib import Path +from threading import Lock +from typing import Optional + +from .. import constants +from ._runtime import is_google_colab + + +_IS_GOOGLE_COLAB_CHECKED = False +_GOOGLE_COLAB_SECRET_LOCK = Lock() +_GOOGLE_COLAB_SECRET: Optional[str] = None + + +def get_token() -> Optional[str]: + """ + Get token if user is logged in. + + Note: in most cases, you should use [`huggingface_hub.utils.build_hf_headers`] instead. This method is only useful + if you want to retrieve the token for other purposes than sending an HTTP request. + + Token is retrieved in priority from the `HF_TOKEN` environment variable. Otherwise, we read the token file located + in the Hugging Face home folder. Returns None if user is not logged in. To log in, use [`login`] or + `huggingface-cli login`. + + Returns: + `str` or `None`: The token, `None` if it doesn't exist. + """ + return _get_token_from_google_colab() or _get_token_from_environment() or _get_token_from_file() + + +def _get_token_from_google_colab() -> Optional[str]: + """Get token from Google Colab secrets vault using `google.colab.userdata.get(...)`. + + Token is read from the vault only once per session and then stored in a global variable to avoid re-requesting + access to the vault. + """ + if not is_google_colab(): + return None + + # `google.colab.userdata` is not thread-safe + # This can lead to a deadlock if multiple threads try to access it at the same time + # (typically when using `snapshot_download`) + # => use a lock + # See https://github.com/huggingface/huggingface_hub/issues/1952 for more details. + with _GOOGLE_COLAB_SECRET_LOCK: + global _GOOGLE_COLAB_SECRET + global _IS_GOOGLE_COLAB_CHECKED + + if _IS_GOOGLE_COLAB_CHECKED: # request access only once + return _GOOGLE_COLAB_SECRET + + try: + from google.colab import userdata + from google.colab.errors import Error as ColabError + except ImportError: + return None + + try: + token = userdata.get("HF_TOKEN") + _GOOGLE_COLAB_SECRET = _clean_token(token) + except userdata.NotebookAccessError: + # Means the user has a secret call `HF_TOKEN` and got a popup "please grand access to HF_TOKEN" and refused it + # => warn user but ignore error => do not re-request access to user + warnings.warn( + "\nAccess to the secret `HF_TOKEN` has not been granted on this notebook." + "\nYou will not be requested again." + "\nPlease restart the session if you want to be prompted again." + ) + _GOOGLE_COLAB_SECRET = None + except userdata.SecretNotFoundError: + # Means the user did not define a `HF_TOKEN` secret => warn + warnings.warn( + "\nThe secret `HF_TOKEN` does not exist in your Colab secrets." + "\nTo authenticate with the Hugging Face Hub, create a token in your settings tab " + "(https://huggingface.co/settings/tokens), set it as secret in your Google Colab and restart your session." + "\nYou will be able to reuse this secret in all of your notebooks." + "\nPlease note that authentication is recommended but still optional to access public models or datasets." + ) + _GOOGLE_COLAB_SECRET = None + except ColabError as e: + # Something happen but we don't know what => recommend to open a GitHub issue + warnings.warn( + f"\nError while fetching `HF_TOKEN` secret value from your vault: '{str(e)}'." + "\nYou are not authenticated with the Hugging Face Hub in this notebook." + "\nIf the error persists, please let us know by opening an issue on GitHub " + "(https://github.com/huggingface/huggingface_hub/issues/new)." + ) + _GOOGLE_COLAB_SECRET = None + + _IS_GOOGLE_COLAB_CHECKED = True + return _GOOGLE_COLAB_SECRET + + +def _get_token_from_environment() -> Optional[str]: + # `HF_TOKEN` has priority (keep `HUGGING_FACE_HUB_TOKEN` for backward compatibility) + return _clean_token(os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")) + + +def _get_token_from_file() -> Optional[str]: + try: + return _clean_token(Path(constants.HF_TOKEN_PATH).read_text()) + except FileNotFoundError: + return None + + +def _clean_token(token: Optional[str]) -> Optional[str]: + """Clean token by removing trailing and leading spaces and newlines. + + If token is an empty string, return None. + """ + if token is None: + return None + return token.replace("\r", "").replace("\n", "").strip() or None diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_typing.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_typing.py new file mode 100644 index 0000000000000000000000000000000000000000..ae502b825bcb900ea076ffe1b0fe1078569821c5 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_typing.py @@ -0,0 +1,50 @@ +# coding=utf-8 +# Copyright 2022-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Handle typing imports based on system compatibility.""" + +from typing import Any, Callable, Literal, TypeVar + + +HTTP_METHOD_T = Literal["GET", "OPTIONS", "HEAD", "POST", "PUT", "PATCH", "DELETE"] + +# type hint meaning "function signature not changed by decorator" +CallableT = TypeVar("CallableT", bound=Callable) + +_JSON_SERIALIZABLE_TYPES = (int, float, str, bool, type(None)) + + +def is_jsonable(obj: Any) -> bool: + """Check if an object is JSON serializable. + + This is a weak check, as it does not check for the actual JSON serialization, but only for the types of the object. + It works correctly for basic use cases but do not guarantee an exhaustive check. + + Object is considered to be recursively json serializable if: + - it is an instance of int, float, str, bool, or NoneType + - it is a list or tuple and all its items are json serializable + - it is a dict and all its keys are strings and all its values are json serializable + """ + try: + if isinstance(obj, _JSON_SERIALIZABLE_TYPES): + return True + if isinstance(obj, (list, tuple)): + return all(is_jsonable(item) for item in obj) + if isinstance(obj, dict): + return all(isinstance(key, str) and is_jsonable(value) for key, value in obj.items()) + if hasattr(obj, "__json__"): + return True + return False + except RecursionError: + return False diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_validators.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_validators.py new file mode 100644 index 0000000000000000000000000000000000000000..f58d38919791127b871b5d1accb9b38b064e1075 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_validators.py @@ -0,0 +1,231 @@ +# coding=utf-8 +# Copyright 2022-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contains utilities to validate argument values in `huggingface_hub`.""" + +import inspect +import re +import warnings +from functools import wraps +from itertools import chain +from typing import Any, Dict + +from ._typing import CallableT + + +REPO_ID_REGEX = re.compile( + r""" + ^ + (\b[\w\-.]+\b/)? # optional namespace (username or organization) + \b # starts with a word boundary + [\w\-.]{1,96} # repo_name: alphanumeric + . _ - + \b # ends with a word boundary + $ + """, + flags=re.VERBOSE, +) + + +class HFValidationError(ValueError): + """Generic exception thrown by `huggingface_hub` validators. + + Inherits from [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError). + """ + + +def validate_hf_hub_args(fn: CallableT) -> CallableT: + """Validate values received as argument for any public method of `huggingface_hub`. + + The goal of this decorator is to harmonize validation of arguments reused + everywhere. By default, all defined validators are tested. + + Validators: + - [`~utils.validate_repo_id`]: `repo_id` must be `"repo_name"` + or `"namespace/repo_name"`. Namespace is a username or an organization. + - [`~utils.smoothly_deprecate_use_auth_token`]: Use `token` instead of + `use_auth_token` (only if `use_auth_token` is not expected by the decorated + function - in practice, always the case in `huggingface_hub`). + + Example: + ```py + >>> from huggingface_hub.utils import validate_hf_hub_args + + >>> @validate_hf_hub_args + ... def my_cool_method(repo_id: str): + ... print(repo_id) + + >>> my_cool_method(repo_id="valid_repo_id") + valid_repo_id + + >>> my_cool_method("other..repo..id") + huggingface_hub.utils._validators.HFValidationError: Cannot have -- or .. in repo_id: 'other..repo..id'. + + >>> my_cool_method(repo_id="other..repo..id") + huggingface_hub.utils._validators.HFValidationError: Cannot have -- or .. in repo_id: 'other..repo..id'. + + >>> @validate_hf_hub_args + ... def my_cool_auth_method(token: str): + ... print(token) + + >>> my_cool_auth_method(token="a token") + "a token" + + >>> my_cool_auth_method(use_auth_token="a use_auth_token") + "a use_auth_token" + + >>> my_cool_auth_method(token="a token", use_auth_token="a use_auth_token") + UserWarning: Both `token` and `use_auth_token` are passed (...) + "a token" + ``` + + Raises: + [`~utils.HFValidationError`]: + If an input is not valid. + """ + # TODO: add an argument to opt-out validation for specific argument? + signature = inspect.signature(fn) + + # Should the validator switch `use_auth_token` values to `token`? In practice, always + # True in `huggingface_hub`. Might not be the case in a downstream library. + check_use_auth_token = "use_auth_token" not in signature.parameters and "token" in signature.parameters + + @wraps(fn) + def _inner_fn(*args, **kwargs): + has_token = False + for arg_name, arg_value in chain( + zip(signature.parameters, args), # Args values + kwargs.items(), # Kwargs values + ): + if arg_name in ["repo_id", "from_id", "to_id"]: + validate_repo_id(arg_value) + + elif arg_name == "token" and arg_value is not None: + has_token = True + + if check_use_auth_token: + kwargs = smoothly_deprecate_use_auth_token(fn_name=fn.__name__, has_token=has_token, kwargs=kwargs) + + return fn(*args, **kwargs) + + return _inner_fn # type: ignore + + +def validate_repo_id(repo_id: str) -> None: + """Validate `repo_id` is valid. + + This is not meant to replace the proper validation made on the Hub but rather to + avoid local inconsistencies whenever possible (example: passing `repo_type` in the + `repo_id` is forbidden). + + Rules: + - Between 1 and 96 characters. + - Either "repo_name" or "namespace/repo_name" + - [a-zA-Z0-9] or "-", "_", "." + - "--" and ".." are forbidden + + Valid: `"foo"`, `"foo/bar"`, `"123"`, `"Foo-BAR_foo.bar123"` + + Not valid: `"datasets/foo/bar"`, `".repo_id"`, `"foo--bar"`, `"foo.git"` + + Example: + ```py + >>> from huggingface_hub.utils import validate_repo_id + >>> validate_repo_id(repo_id="valid_repo_id") + >>> validate_repo_id(repo_id="other..repo..id") + huggingface_hub.utils._validators.HFValidationError: Cannot have -- or .. in repo_id: 'other..repo..id'. + ``` + + Discussed in https://github.com/huggingface/huggingface_hub/issues/1008. + In moon-landing (internal repository): + - https://github.com/huggingface/moon-landing/blob/main/server/lib/Names.ts#L27 + - https://github.com/huggingface/moon-landing/blob/main/server/views/components/NewRepoForm/NewRepoForm.svelte#L138 + """ + if not isinstance(repo_id, str): + # Typically, a Path is not a repo_id + raise HFValidationError(f"Repo id must be a string, not {type(repo_id)}: '{repo_id}'.") + + if repo_id.count("/") > 1: + raise HFValidationError( + "Repo id must be in the form 'repo_name' or 'namespace/repo_name':" + f" '{repo_id}'. Use `repo_type` argument if needed." + ) + + if not REPO_ID_REGEX.match(repo_id): + raise HFValidationError( + "Repo id must use alphanumeric chars or '-', '_', '.', '--' and '..' are" + " forbidden, '-' and '.' cannot start or end the name, max length is 96:" + f" '{repo_id}'." + ) + + if "--" in repo_id or ".." in repo_id: + raise HFValidationError(f"Cannot have -- or .. in repo_id: '{repo_id}'.") + + if repo_id.endswith(".git"): + raise HFValidationError(f"Repo_id cannot end by '.git': '{repo_id}'.") + + +def smoothly_deprecate_use_auth_token(fn_name: str, has_token: bool, kwargs: Dict[str, Any]) -> Dict[str, Any]: + """Smoothly deprecate `use_auth_token` in the `huggingface_hub` codebase. + + The long-term goal is to remove any mention of `use_auth_token` in the codebase in + favor of a unique and less verbose `token` argument. This will be done a few steps: + + 0. Step 0: methods that require a read-access to the Hub use the `use_auth_token` + argument (`str`, `bool` or `None`). Methods requiring write-access have a `token` + argument (`str`, `None`). This implicit rule exists to be able to not send the + token when not necessary (`use_auth_token=False`) even if logged in. + + 1. Step 1: we want to harmonize everything and use `token` everywhere (supporting + `token=False` for read-only methods). In order not to break existing code, if + `use_auth_token` is passed to a function, the `use_auth_token` value is passed + as `token` instead, without any warning. + a. Corner case: if both `use_auth_token` and `token` values are passed, a warning + is thrown and the `use_auth_token` value is ignored. + + 2. Step 2: Once it is release, we should push downstream libraries to switch from + `use_auth_token` to `token` as much as possible, but without throwing a warning + (e.g. manually create issues on the corresponding repos). + + 3. Step 3: After a transitional period (6 months e.g. until April 2023?), we update + `huggingface_hub` to throw a warning on `use_auth_token`. Hopefully, very few + users will be impacted as it would have already been fixed. + In addition, unit tests in `huggingface_hub` must be adapted to expect warnings + to be thrown (but still use `use_auth_token` as before). + + 4. Step 4: After a normal deprecation cycle (3 releases ?), remove this validator. + `use_auth_token` will definitely not be supported. + In addition, we update unit tests in `huggingface_hub` to use `token` everywhere. + + This has been discussed in: + - https://github.com/huggingface/huggingface_hub/issues/1094. + - https://github.com/huggingface/huggingface_hub/pull/928 + - (related) https://github.com/huggingface/huggingface_hub/pull/1064 + """ + new_kwargs = kwargs.copy() # do not mutate input ! + + use_auth_token = new_kwargs.pop("use_auth_token", None) # remove from kwargs + if use_auth_token is not None: + if has_token: + warnings.warn( + "Both `token` and `use_auth_token` are passed to" + f" `{fn_name}` with non-None values. `token` is now the" + " preferred argument to pass a User Access Token." + " `use_auth_token` value will be ignored." + ) + else: + # `token` argument is not passed and a non-None value is passed in + # `use_auth_token` => use `use_auth_token` value as `token` kwarg. + new_kwargs["token"] = use_auth_token + + return new_kwargs diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/endpoint_helpers.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/endpoint_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..ac52ce85a0f45932aeefc702eb44828ad2e17871 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/endpoint_helpers.py @@ -0,0 +1,250 @@ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Helpful utility functions and classes in relation to exploring API endpoints +with the aim for a user-friendly interface. +""" + +import math +import re +import warnings +from dataclasses import dataclass +from typing import TYPE_CHECKING, List, Optional, Union + +from ..repocard_data import ModelCardData + + +if TYPE_CHECKING: + from ..hf_api import ModelInfo + + +def _is_emission_within_treshold(model_info: "ModelInfo", minimum_threshold: float, maximum_threshold: float) -> bool: + """Checks if a model's emission is within a given threshold. + + Args: + model_info (`ModelInfo`): + A model info object containing the model's emission information. + minimum_threshold (`float`): + A minimum carbon threshold to filter by, such as 1. + maximum_threshold (`float`): + A maximum carbon threshold to filter by, such as 10. + + Returns: + `bool`: Whether the model's emission is within the given threshold. + """ + if minimum_threshold is None and maximum_threshold is None: + raise ValueError("Both `minimum_threshold` and `maximum_threshold` cannot both be `None`") + if minimum_threshold is None: + minimum_threshold = -1 + if maximum_threshold is None: + maximum_threshold = math.inf + + card_data = getattr(model_info, "card_data", None) + if card_data is None or not isinstance(card_data, (dict, ModelCardData)): + return False + + # Get CO2 emission metadata + emission = card_data.get("co2_eq_emissions", None) + if isinstance(emission, dict): + emission = emission["emissions"] + if not emission: + return False + + # Filter out if value is missing or out of range + matched = re.search(r"\d+\.\d+|\d+", str(emission)) + if matched is None: + return False + + emission_value = float(matched.group(0)) + return minimum_threshold <= emission_value <= maximum_threshold + + +@dataclass +class DatasetFilter: + """ + A class that converts human-readable dataset search parameters into ones + compatible with the REST API. For all parameters capitalization does not + matter. + + + + The `DatasetFilter` class is deprecated and will be removed in huggingface_hub>=0.24. Please pass the filter parameters as keyword arguments directly to [`list_datasets`]. + + + + Args: + author (`str`, *optional*): + A string that can be used to identify datasets on + the Hub by the original uploader (author or organization), such as + `facebook` or `huggingface`. + benchmark (`str` or `List`, *optional*): + A string or list of strings that can be used to identify datasets on + the Hub by their official benchmark. + dataset_name (`str`, *optional*): + A string or list of strings that can be used to identify datasets on + the Hub by its name, such as `SQAC` or `wikineural` + language_creators (`str` or `List`, *optional*): + A string or list of strings that can be used to identify datasets on + the Hub with how the data was curated, such as `crowdsourced` or + `machine_generated`. + language (`str` or `List`, *optional*): + A string or list of strings representing a two-character language to + filter datasets by on the Hub. + multilinguality (`str` or `List`, *optional*): + A string or list of strings representing a filter for datasets that + contain multiple languages. + size_categories (`str` or `List`, *optional*): + A string or list of strings that can be used to identify datasets on + the Hub by the size of the dataset such as `100K>> from huggingface_hub import DatasetFilter + + >>> # Using author + >>> new_filter = DatasetFilter(author="facebook") + + >>> # Using benchmark + >>> new_filter = DatasetFilter(benchmark="raft") + + >>> # Using dataset_name + >>> new_filter = DatasetFilter(dataset_name="wikineural") + + >>> # Using language_creator + >>> new_filter = DatasetFilter(language_creator="crowdsourced") + + >>> # Using language + >>> new_filter = DatasetFilter(language="en") + + >>> # Using multilinguality + >>> new_filter = DatasetFilter(multilinguality="multilingual") + + >>> # Using size_categories + >>> new_filter = DatasetFilter(size_categories="100K>> # Using task_categories + >>> new_filter = DatasetFilter(task_categories="audio_classification") + + >>> # Using task_ids + >>> new_filter = DatasetFilter(task_ids="paraphrase") + ``` + """ + + author: Optional[str] = None + benchmark: Optional[Union[str, List[str]]] = None + dataset_name: Optional[str] = None + language_creators: Optional[Union[str, List[str]]] = None + language: Optional[Union[str, List[str]]] = None + multilinguality: Optional[Union[str, List[str]]] = None + size_categories: Optional[Union[str, List[str]]] = None + task_categories: Optional[Union[str, List[str]]] = None + task_ids: Optional[Union[str, List[str]]] = None + + def __post_init__(self): + warnings.warn( + "'DatasetFilter' is deprecated and will be removed in huggingface_hub>=0.24. Please pass the filter parameters as keyword arguments directly to the `list_datasets` method.", + category=FutureWarning, + ) + + +@dataclass +class ModelFilter: + """ + A class that converts human-readable model search parameters into ones + compatible with the REST API. For all parameters capitalization does not + matter. + + + + The `ModelFilter` class is deprecated and will be removed in huggingface_hub>=0.24. Please pass the filter parameters as keyword arguments directly to [`list_models`]. + + + + Args: + author (`str`, *optional*): + A string that can be used to identify models on the Hub by the + original uploader (author or organization), such as `facebook` or + `huggingface`. + library (`str` or `List`, *optional*): + A string or list of strings of foundational libraries models were + originally trained from, such as pytorch, tensorflow, or allennlp. + language (`str` or `List`, *optional*): + A string or list of strings of languages, both by name and country + code, such as "en" or "English" + model_name (`str`, *optional*): + A string that contain complete or partial names for models on the + Hub, such as "bert" or "bert-base-cased" + task (`str` or `List`, *optional*): + A string or list of strings of tasks models were designed for, such + as: "fill-mask" or "automatic-speech-recognition" + tags (`str` or `List`, *optional*): + A string tag or a list of tags to filter models on the Hub by, such + as `text-generation` or `spacy`. + trained_dataset (`str` or `List`, *optional*): + A string tag or a list of string tags of the trained dataset for a + model on the Hub. + + Examples: + + ```python + >>> from huggingface_hub import ModelFilter + + >>> # For the author_or_organization + >>> new_filter = ModelFilter(author_or_organization="facebook") + + >>> # For the library + >>> new_filter = ModelFilter(library="pytorch") + + >>> # For the language + >>> new_filter = ModelFilter(language="french") + + >>> # For the model_name + >>> new_filter = ModelFilter(model_name="bert") + + >>> # For the task + >>> new_filter = ModelFilter(task="text-classification") + + >>> from huggingface_hub import HfApi + + >>> api = HfApi() + # To list model tags + + >>> new_filter = ModelFilter(tags="benchmark:raft") + + >>> # Related to the dataset + >>> new_filter = ModelFilter(trained_dataset="common_voice") + ``` + """ + + author: Optional[str] = None + library: Optional[Union[str, List[str]]] = None + language: Optional[Union[str, List[str]]] = None + model_name: Optional[str] = None + task: Optional[Union[str, List[str]]] = None + trained_dataset: Optional[Union[str, List[str]]] = None + tags: Optional[Union[str, List[str]]] = None + + def __post_init__(self): + warnings.warn( + "'ModelFilter' is deprecated and will be removed in huggingface_hub>=0.24. Please pass the filter parameters as keyword arguments directly to the `list_models` method.", + FutureWarning, + ) diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/insecure_hashlib.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/insecure_hashlib.py new file mode 100644 index 0000000000000000000000000000000000000000..f232ee0adcfc52dcc18b5ea4d9c913b206521f71 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/insecure_hashlib.py @@ -0,0 +1,34 @@ +# Taken from https://github.com/mlflow/mlflow/pull/10119 +# +# DO NOT use this function for security purposes (e.g., password hashing). +# +# In Python >= 3.9, insecure hashing algorithms such as MD5 fail in FIPS-compliant +# environments unless `usedforsecurity=False` is explicitly passed. +# +# References: +# - https://github.com/mlflow/mlflow/issues/9905 +# - https://github.com/mlflow/mlflow/pull/10119 +# - https://docs.python.org/3/library/hashlib.html +# - https://github.com/huggingface/transformers/pull/27038 +# +# Usage: +# ```python +# # Use +# from huggingface_hub.utils.insecure_hashlib import sha256 +# # instead of +# from hashlib import sha256 +# +# # Use +# from huggingface_hub.utils import insecure_hashlib +# # instead of +# import hashlib +# ``` +import functools +import hashlib +import sys + + +_kwargs = {"usedforsecurity": False} if sys.version_info >= (3, 9) else {} +md5 = functools.partial(hashlib.md5, **_kwargs) +sha1 = functools.partial(hashlib.sha1, **_kwargs) +sha256 = functools.partial(hashlib.sha256, **_kwargs) diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/logging.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/logging.py new file mode 100644 index 0000000000000000000000000000000000000000..3aafdf148135397556b4bb762862377eafdafd14 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/logging.py @@ -0,0 +1,182 @@ +# coding=utf-8 +# Copyright 2020 Optuna, Hugging Face +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Logging utilities.""" + +import logging +import os +from logging import ( + CRITICAL, # NOQA + DEBUG, # NOQA + ERROR, # NOQA + FATAL, # NOQA + INFO, # NOQA + NOTSET, # NOQA + WARN, # NOQA + WARNING, # NOQA +) +from typing import Optional + + +log_levels = { + "debug": logging.DEBUG, + "info": logging.INFO, + "warning": logging.WARNING, + "error": logging.ERROR, + "critical": logging.CRITICAL, +} + +_default_log_level = logging.WARNING + + +def _get_library_name() -> str: + return __name__.split(".")[0] + + +def _get_library_root_logger() -> logging.Logger: + return logging.getLogger(_get_library_name()) + + +def _get_default_logging_level(): + """ + If `HF_HUB_VERBOSITY` env var is set to one of the valid choices return that as the new default level. If it is not + - fall back to `_default_log_level` + """ + env_level_str = os.getenv("HF_HUB_VERBOSITY", None) + if env_level_str: + if env_level_str in log_levels: + return log_levels[env_level_str] + else: + logging.getLogger().warning( + f"Unknown option HF_HUB_VERBOSITY={env_level_str}, has to be one of: { ', '.join(log_levels.keys()) }" + ) + return _default_log_level + + +def _configure_library_root_logger() -> None: + library_root_logger = _get_library_root_logger() + library_root_logger.addHandler(logging.StreamHandler()) + library_root_logger.setLevel(_get_default_logging_level()) + + +def _reset_library_root_logger() -> None: + library_root_logger = _get_library_root_logger() + library_root_logger.setLevel(logging.NOTSET) + + +def get_logger(name: Optional[str] = None) -> logging.Logger: + """ + Returns a logger with the specified name. This function is not supposed + to be directly accessed by library users. + + Args: + name (`str`, *optional*): + The name of the logger to get, usually the filename + + Example: + + ```python + >>> from huggingface_hub import get_logger + + >>> logger = get_logger(__file__) + >>> logger.set_verbosity_info() + ``` + """ + + if name is None: + name = _get_library_name() + + return logging.getLogger(name) + + +def get_verbosity() -> int: + """Return the current level for the HuggingFace Hub's root logger. + + Returns: + Logging level, e.g., `huggingface_hub.logging.DEBUG` and + `huggingface_hub.logging.INFO`. + + + + HuggingFace Hub has following logging levels: + + - `huggingface_hub.logging.CRITICAL`, `huggingface_hub.logging.FATAL` + - `huggingface_hub.logging.ERROR` + - `huggingface_hub.logging.WARNING`, `huggingface_hub.logging.WARN` + - `huggingface_hub.logging.INFO` + - `huggingface_hub.logging.DEBUG` + + + """ + return _get_library_root_logger().getEffectiveLevel() + + +def set_verbosity(verbosity: int) -> None: + """ + Sets the level for the HuggingFace Hub's root logger. + + Args: + verbosity (`int`): + Logging level, e.g., `huggingface_hub.logging.DEBUG` and + `huggingface_hub.logging.INFO`. + """ + _get_library_root_logger().setLevel(verbosity) + + +def set_verbosity_info(): + """ + Sets the verbosity to `logging.INFO`. + """ + return set_verbosity(INFO) + + +def set_verbosity_warning(): + """ + Sets the verbosity to `logging.WARNING`. + """ + return set_verbosity(WARNING) + + +def set_verbosity_debug(): + """ + Sets the verbosity to `logging.DEBUG`. + """ + return set_verbosity(DEBUG) + + +def set_verbosity_error(): + """ + Sets the verbosity to `logging.ERROR`. + """ + return set_verbosity(ERROR) + + +def disable_propagation() -> None: + """ + Disable propagation of the library log outputs. Note that log propagation is + disabled by default. + """ + _get_library_root_logger().propagate = False + + +def enable_propagation() -> None: + """ + Enable propagation of the library log outputs. Please disable the + HuggingFace Hub's default handler to prevent double logging if the root + logger has been configured. + """ + _get_library_root_logger().propagate = True + + +_configure_library_root_logger() diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/sha.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/sha.py new file mode 100644 index 0000000000000000000000000000000000000000..233ab074e69a47de9a443a458ce44e1429a1e22c --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/sha.py @@ -0,0 +1,29 @@ +"""Utilities to efficiently compute the SHA 256 hash of a bunch of bytes.""" + +from typing import BinaryIO, Optional + +from .insecure_hashlib import sha256 + + +def sha_fileobj(fileobj: BinaryIO, chunk_size: Optional[int] = None) -> bytes: + """ + Computes the sha256 hash of the given file object, by chunks of size `chunk_size`. + + Args: + fileobj (file-like object): + The File object to compute sha256 for, typically obtained with `open(path, "rb")` + chunk_size (`int`, *optional*): + The number of bytes to read from `fileobj` at once, defaults to 1MB. + + Returns: + `bytes`: `fileobj`'s sha256 hash as bytes + """ + chunk_size = chunk_size if chunk_size is not None else 1024 * 1024 + + sha = sha256() + while True: + chunk = fileobj.read(chunk_size) + sha.update(chunk) + if not chunk: + break + return sha.digest() diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/tqdm.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/tqdm.py new file mode 100644 index 0000000000000000000000000000000000000000..da1e421a21e65c04b7c53efd8f95d8df4f663473 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/tqdm.py @@ -0,0 +1,187 @@ +#!/usr/bin/env python +# coding=utf-8 +# Copyright 2021 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License +"""Utility helpers to handle progress bars in `huggingface_hub`. + +Example: + 1. Use `huggingface_hub.utils.tqdm` as you would use `tqdm.tqdm` or `tqdm.auto.tqdm`. + 2. To disable progress bars, either use `disable_progress_bars()` helper or set the + environment variable `HF_HUB_DISABLE_PROGRESS_BARS` to 1. + 3. To re-enable progress bars, use `enable_progress_bars()`. + 4. To check whether progress bars are disabled, use `are_progress_bars_disabled()`. + +NOTE: Environment variable `HF_HUB_DISABLE_PROGRESS_BARS` has the priority. + +Example: + ```py + from huggingface_hub.utils import ( + are_progress_bars_disabled, + disable_progress_bars, + enable_progress_bars, + tqdm, + ) + + # Disable progress bars globally + disable_progress_bars() + + # Use as normal `tqdm` + for _ in tqdm(range(5)): + do_something() + + # Still not showing progress bars, as `disable=False` is overwritten to `True`. + for _ in tqdm(range(5), disable=False): + do_something() + + are_progress_bars_disabled() # True + + # Re-enable progress bars globally + enable_progress_bars() + + # Progress bar will be shown ! + for _ in tqdm(range(5)): + do_something() + ``` +""" + +import io +import warnings +from contextlib import contextmanager +from pathlib import Path +from typing import Iterator, Optional, Union + +from tqdm.auto import tqdm as old_tqdm + +from ..constants import HF_HUB_DISABLE_PROGRESS_BARS + + +# `HF_HUB_DISABLE_PROGRESS_BARS` is `Optional[bool]` while `_hf_hub_progress_bars_disabled` +# is a `bool`. If `HF_HUB_DISABLE_PROGRESS_BARS` is set to True or False, it has priority. +# If `HF_HUB_DISABLE_PROGRESS_BARS` is None, it means the user have not set the +# environment variable and is free to enable/disable progress bars programmatically. +# TL;DR: env variable has priority over code. +# +# By default, progress bars are enabled. +_hf_hub_progress_bars_disabled: bool = HF_HUB_DISABLE_PROGRESS_BARS or False + + +def disable_progress_bars() -> None: + """ + Disable globally progress bars used in `huggingface_hub` except if `HF_HUB_DISABLE_PROGRESS_BARS` environment + variable has been set. + + Use [`~utils.enable_progress_bars`] to re-enable them. + """ + if HF_HUB_DISABLE_PROGRESS_BARS is False: + warnings.warn( + "Cannot disable progress bars: environment variable `HF_HUB_DISABLE_PROGRESS_BARS=0` is set and has" + " priority." + ) + return + global _hf_hub_progress_bars_disabled + _hf_hub_progress_bars_disabled = True + + +def enable_progress_bars() -> None: + """ + Enable globally progress bars used in `huggingface_hub` except if `HF_HUB_DISABLE_PROGRESS_BARS` environment + variable has been set. + + Use [`~utils.disable_progress_bars`] to disable them. + """ + if HF_HUB_DISABLE_PROGRESS_BARS is True: + warnings.warn( + "Cannot enable progress bars: environment variable `HF_HUB_DISABLE_PROGRESS_BARS=1` is set and has" + " priority." + ) + return + global _hf_hub_progress_bars_disabled + _hf_hub_progress_bars_disabled = False + + +def are_progress_bars_disabled() -> bool: + """Return whether progress bars are globally disabled or not. + + Progress bars used in `huggingface_hub` can be enable or disabled globally using [`~utils.enable_progress_bars`] + and [`~utils.disable_progress_bars`] or by setting `HF_HUB_DISABLE_PROGRESS_BARS` as environment variable. + """ + global _hf_hub_progress_bars_disabled + return _hf_hub_progress_bars_disabled + + +class tqdm(old_tqdm): + """ + Class to override `disable` argument in case progress bars are globally disabled. + + Taken from https://github.com/tqdm/tqdm/issues/619#issuecomment-619639324. + """ + + def __init__(self, *args, **kwargs): + if are_progress_bars_disabled(): + kwargs["disable"] = True + super().__init__(*args, **kwargs) + + def __delattr__(self, attr: str) -> None: + """Fix for https://github.com/huggingface/huggingface_hub/issues/1603""" + try: + super().__delattr__(attr) + except AttributeError: + if attr != "_lock": + raise + + +@contextmanager +def tqdm_stream_file(path: Union[Path, str]) -> Iterator[io.BufferedReader]: + """ + Open a file as binary and wrap the `read` method to display a progress bar when it's streamed. + + First implemented in `transformers` in 2019 but removed when switched to git-lfs. Used in `huggingface_hub` to show + progress bar when uploading an LFS file to the Hub. See github.com/huggingface/transformers/pull/2078#discussion_r354739608 + for implementation details. + + Note: currently implementation handles only files stored on disk as it is the most common use case. Could be + extended to stream any `BinaryIO` object but we might have to debug some corner cases. + + Example: + ```py + >>> with tqdm_stream_file("config.json") as f: + >>> requests.put(url, data=f) + config.json: 100%|█████████████████████████| 8.19k/8.19k [00:02<00:00, 3.72kB/s] + ``` + """ + if isinstance(path, str): + path = Path(path) + + with path.open("rb") as f: + total_size = path.stat().st_size + pbar = tqdm( + unit="B", + unit_scale=True, + total=total_size, + initial=0, + desc=path.name, + ) + + f_read = f.read + + def _inner_read(size: Optional[int] = -1) -> bytes: + data = f_read(size) + pbar.update(len(data)) + return data + + f.read = _inner_read # type: ignore + + yield f + + pbar.close() diff --git a/env-llmeval/lib/python3.10/site-packages/sacrebleu/__main__.py b/env-llmeval/lib/python3.10/site-packages/sacrebleu/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..3833741e8076dbac776a383f8e05ce8cafaac92e --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sacrebleu/__main__.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +# Copyright 2017--2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You may not +# use this file except in compliance with the License. A copy of the License +# is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file is distributed on +# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +# express or implied. See the License for the specific language governing +# permissions and limitations under the License. + +""" +SacreBLEU provides hassle-free computation of shareable, comparable, and reproducible BLEU scores. +Inspired by Rico Sennrich's `multi-bleu-detok.perl`, it produces the official WMT scores but works with plain text. +It also knows all the standard test sets and handles downloading, processing, and tokenization for you. + +See the [README.md] file for more information. +""" +from .sacrebleu import main + +if __name__ == '__main__': + main() diff --git a/env-llmeval/lib/python3.10/site-packages/sacrebleu/compat.py b/env-llmeval/lib/python3.10/site-packages/sacrebleu/compat.py new file mode 100644 index 0000000000000000000000000000000000000000..573596037928ddc5b8c5b8df99202c13f0681943 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sacrebleu/compat.py @@ -0,0 +1,205 @@ +from typing import Sequence, Optional + +from .metrics import BLEU, CHRF, TER, BLEUScore, CHRFScore, TERScore + + +###################################################################### +# Backward compatibility functions for old style API access (< 1.4.11) +###################################################################### +def corpus_bleu(hypotheses: Sequence[str], + references: Sequence[Sequence[str]], + smooth_method='exp', + smooth_value=None, + force=False, + lowercase=False, + tokenize=BLEU.TOKENIZER_DEFAULT, + use_effective_order=False) -> BLEUScore: + """Computes BLEU for a corpus against a single (or multiple) reference(s). + This is the main CLI entry point for computing BLEU between a system output + and a reference sentence. + + :param hypotheses: A sequence of hypothesis strings. + :param references: A sequence of reference documents with document being + defined as a sequence of reference strings. + :param smooth_method: The smoothing method to use ('floor', 'add-k', 'exp' or 'none') + :param smooth_value: The smoothing value for `floor` and `add-k` methods. `None` falls back to default value. + :param force: Ignore data that looks already tokenized + :param lowercase: Lowercase the data + :param tokenize: The tokenizer to use + :param use_effective_order: Don't take into account n-gram orders without any match. + :return: a `BLEUScore` object + """ + metric = BLEU( + lowercase=lowercase, force=force, tokenize=tokenize, + smooth_method=smooth_method, smooth_value=smooth_value, + effective_order=use_effective_order) + + return metric.corpus_score(hypotheses, references) + + +def raw_corpus_bleu(hypotheses: Sequence[str], + references: Sequence[Sequence[str]], + smooth_value: Optional[float] = BLEU.SMOOTH_DEFAULTS['floor']) -> BLEUScore: + """Computes BLEU for a corpus against a single (or multiple) reference(s). + This convenience function assumes a particular set of arguments i.e. + it disables tokenization and applies a `floor` smoothing with value `0.1`. + + This convenience call does not apply any tokenization at all, + neither to the system output nor the reference. It just computes + BLEU on the "raw corpus" (hence the name). + + :param hypotheses: A sequence of hypothesis strings. + :param references: A sequence of reference documents with document being + defined as a sequence of reference strings. + :param smooth_value: The smoothing value for `floor`. If not given, the default of 0.1 is used. + :return: Returns a `BLEUScore` object. + + """ + return corpus_bleu( + hypotheses, references, smooth_method='floor', + smooth_value=smooth_value, force=True, tokenize='none', + use_effective_order=True) + + +def sentence_bleu(hypothesis: str, + references: Sequence[str], + smooth_method: str = 'exp', + smooth_value: Optional[float] = None, + lowercase: bool = False, + tokenize=BLEU.TOKENIZER_DEFAULT, + use_effective_order: bool = True) -> BLEUScore: + """ + Computes BLEU for a single sentence against a single (or multiple) reference(s). + + Disclaimer: Computing BLEU at the sentence level is not its intended use as + BLEU is a corpus-level metric. + + :param hypothesis: A single hypothesis string. + :param references: A sequence of reference strings. + :param smooth_method: The smoothing method to use ('floor', 'add-k', 'exp' or 'none') + :param smooth_value: The smoothing value for `floor` and `add-k` methods. `None` falls back to default value. + :param lowercase: Lowercase the data + :param tokenize: The tokenizer to use + :param use_effective_order: Don't take into account n-gram orders without any match. + :return: Returns a `BLEUScore` object. + """ + metric = BLEU( + lowercase=lowercase, tokenize=tokenize, force=False, + smooth_method=smooth_method, smooth_value=smooth_value, + effective_order=use_effective_order) + + return metric.sentence_score(hypothesis, references) + + +def corpus_chrf(hypotheses: Sequence[str], + references: Sequence[Sequence[str]], + char_order: int = CHRF.CHAR_ORDER, + word_order: int = CHRF.WORD_ORDER, + beta: int = CHRF.BETA, + remove_whitespace: bool = True, + eps_smoothing: bool = False) -> CHRFScore: + """ + Computes chrF for a corpus against a single (or multiple) reference(s). + If `word_order` equals to 2, the metric is referred to as chrF++. + + :param hypotheses: A sequence of hypothesis strings. + :param references: A sequence of reference documents with document being + defined as a sequence of reference strings. + :param char_order: Character n-gram order. + :param word_order: Word n-gram order. If equals to 2, the metric is referred to as chrF++. + :param beta: Determine the importance of recall w.r.t precision. + :param eps_smoothing: If `True`, applies epsilon smoothing similar + to reference chrF++.py, NLTK and Moses implementations. Otherwise, + it takes into account effective match order similar to sacreBLEU < 2.0.0. + :param remove_whitespace: If `True`, removes whitespaces prior to character n-gram extraction. + :return: A `CHRFScore` object. + """ + metric = CHRF( + char_order=char_order, + word_order=word_order, + beta=beta, + whitespace=not remove_whitespace, + eps_smoothing=eps_smoothing) + return metric.corpus_score(hypotheses, references) + + +def sentence_chrf(hypothesis: str, + references: Sequence[str], + char_order: int = CHRF.CHAR_ORDER, + word_order: int = CHRF.WORD_ORDER, + beta: int = CHRF.BETA, + remove_whitespace: bool = True, + eps_smoothing: bool = False) -> CHRFScore: + """ + Computes chrF for a single sentence against a single (or multiple) reference(s). + If `word_order` equals to 2, the metric is referred to as chrF++. + + :param hypothesis: A single hypothesis string. + :param references: A sequence of reference strings. + :param char_order: Character n-gram order. + :param word_order: Word n-gram order. If equals to 2, the metric is referred to as chrF++. + :param beta: Determine the importance of recall w.r.t precision. + :param eps_smoothing: If `True`, applies epsilon smoothing similar + to reference chrF++.py, NLTK and Moses implementations. Otherwise, + it takes into account effective match order similar to sacreBLEU < 2.0.0. + :param remove_whitespace: If `True`, removes whitespaces prior to character n-gram extraction. + :return: A `CHRFScore` object. + """ + metric = CHRF( + char_order=char_order, + word_order=word_order, + beta=beta, + whitespace=not remove_whitespace, + eps_smoothing=eps_smoothing) + return metric.sentence_score(hypothesis, references) + + +def corpus_ter(hypotheses: Sequence[str], + references: Sequence[Sequence[str]], + normalized: bool = False, + no_punct: bool = False, + asian_support: bool = False, + case_sensitive: bool = False) -> TERScore: + """ + Computes TER for a corpus against a single (or multiple) reference(s). + + :param hypotheses: A sequence of hypothesis strings. + :param references: A sequence of reference documents with document being + defined as a sequence of reference strings. + :param normalized: Enable character normalization. + :param no_punct: Remove punctuation. + :param asian_support: Enable special treatment of Asian characters. + :param case_sensitive: Enables case-sensitivity. + :return: A `TERScore` object. + """ + metric = TER( + normalized=normalized, + no_punct=no_punct, + asian_support=asian_support, + case_sensitive=case_sensitive) + return metric.corpus_score(hypotheses, references) + + +def sentence_ter(hypothesis: str, + references: Sequence[str], + normalized: bool = False, + no_punct: bool = False, + asian_support: bool = False, + case_sensitive: bool = False) -> TERScore: + """ + Computes TER for a single hypothesis against a single (or multiple) reference(s). + + :param hypothesis: A single hypothesis string. + :param references: A sequence of reference strings. + :param normalized: Enable character normalization. + :param no_punct: Remove punctuation. + :param asian_support: Enable special treatment of Asian characters. + :param case_sensitive: Enable case-sensitivity. + :return: A `TERScore` object. + """ + metric = TER( + normalized=normalized, + no_punct=no_punct, + asian_support=asian_support, + case_sensitive=case_sensitive) + return metric.sentence_score(hypothesis, references) diff --git a/env-llmeval/lib/python3.10/site-packages/sacrebleu/dataset/__pycache__/__init__.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sacrebleu/dataset/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e7a782917ef59a85e706ebcf1bf281a8d90c2ec Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sacrebleu/dataset/__pycache__/__init__.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sacrebleu/dataset/__pycache__/fake_sgml.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sacrebleu/dataset/__pycache__/fake_sgml.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..627849f1fa271ac01479faf255861e72384d81d3 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sacrebleu/dataset/__pycache__/fake_sgml.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sacrebleu/py.typed b/env-llmeval/lib/python3.10/site-packages/sacrebleu/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/env-llmeval/lib/python3.10/site-packages/sacrebleu/sacrebleu.py b/env-llmeval/lib/python3.10/site-packages/sacrebleu/sacrebleu.py new file mode 100644 index 0000000000000000000000000000000000000000..d778e1db9fd55adf18e700876144c11b0e9f955d --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sacrebleu/sacrebleu.py @@ -0,0 +1,577 @@ +#!/usr/bin/env python3 + +# Copyright 2017--2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You may not +# use this file except in compliance with the License. A copy of the License +# is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file is distributed on +# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +# express or implied. See the License for the specific language governing +# permissions and limitations under the License. + +""" +SacreBLEU provides hassle-free computation of shareable, comparable, and reproducible BLEU scores. +Inspired by Rico Sennrich's `multi-bleu-detok.perl`, it produces the official WMT scores but works with plain text. +It also knows all the standard test sets and handles downloading, processing, and tokenization for you. + +See the [README.md] file for more information. +""" + +import io +import os +import sys +import logging +import pathlib +import argparse +from collections import defaultdict + + +# Allows calling the script as a standalone utility +# See: https://github.com/mjpost/sacrebleu/issues/86 +if __package__ is None and __name__ == '__main__': + parent = pathlib.Path(__file__).absolute().parents[1] + sys.path.insert(0, str(parent)) + __package__ = 'sacrebleu' + +from .dataset import DATASETS +from .metrics import METRICS +from .utils import smart_open, filter_subset, get_langpairs_for_testset, get_available_testsets +from .utils import print_test_set, print_subset_results, get_reference_files, download_test_set +from .utils import args_to_dict, sanity_check_lengths, print_results_table, print_single_results +from .utils import get_available_testsets_for_langpair, Color + +from . import __version__ as VERSION + +sacrelogger = logging.getLogger('sacrebleu') + +try: + # SIGPIPE is not available on Windows machines, throwing an exception. + from signal import SIGPIPE # type: ignore + + # If SIGPIPE is available, change behaviour to default instead of ignore. + from signal import signal, SIG_DFL + signal(SIGPIPE, SIG_DFL) +except ImportError: + pass + + +def parse_args(): + arg_parser = argparse.ArgumentParser( + description='sacreBLEU: Hassle-free computation of shareable BLEU scores.\n' + 'Quick usage: score your detokenized output against WMT\'14 EN-DE:\n' + ' cat output.detok.de | sacrebleu -t wmt14 -l en-de', + formatter_class=argparse.RawDescriptionHelpFormatter) + + arg_parser.add_argument('--citation', '--cite', default=False, action='store_true', + help='Dump the bibtex citation and quit.') + arg_parser.add_argument('--list', default=False, action='store_true', + help='Print a list of all available test sets.') + arg_parser.add_argument('--test-set', '-t', type=str, default=None, + help='The test set to use (see also --list) or a comma-separated list of test sets to be concatenated.') + arg_parser.add_argument('--language-pair', '-l', dest='langpair', default=None, + help='Source-target language pair (2-char ISO639-1 codes).') + arg_parser.add_argument('--origlang', '-ol', dest='origlang', default=None, + help='Use a subset of sentences with a given original language (2-char ISO639-1 codes), "non-" prefix means negation.') + arg_parser.add_argument('--subset', dest='subset', default=None, + help='Use a subset of sentences whose document annotation matches a given regex (see SUBSETS in the source code).') + arg_parser.add_argument('--download', type=str, default=None, + help='Download a test set and quit.') + arg_parser.add_argument('--echo', nargs="+", type=str, default=None, + help='Output the source (src), reference (ref), or other available field (docid, ref:A, ref:1 for example) to STDOUT and quit. ' + 'You can get available fields with options `--list` and `-t`' 'For example: `sacrebleu -t wmt21 --list`. ' + 'If multiple fields are given, they are outputted with tsv format in the order they are given.' + 'You can also use `--echo all` to output all available fields.') + + # I/O related arguments + # Multiple input files can be provided for significance testing for example + arg_parser.add_argument('--input', '-i', type=str, nargs='*', default=None, + help='Read input from file(s) instead of STDIN.') + arg_parser.add_argument('refs', nargs='*', default=[], + help='Optional list of references. If given, it should preceed the -i/--input argument.') + arg_parser.add_argument('--num-refs', '-nr', type=int, default=1, + help='Split the reference stream on tabs, and expect this many references. (Default: %(default)s)') + arg_parser.add_argument('--encoding', '-e', type=str, default='utf-8', + help='Open text files with specified encoding (Default: %(default)s)') + + # Metric selection + avail_metrics = [m.lower() for m in METRICS] + arg_parser.add_argument('--metrics', '-m', choices=avail_metrics, nargs='+', default=['bleu'], + help='Space-delimited list of metrics to compute (Default: bleu)') + arg_parser.add_argument('--sentence-level', '-sl', action='store_true', help='Compute metric for each sentence.') + + # BLEU-related arguments + # since sacreBLEU had only support for BLEU initially, the argument names + # are not prefixed with 'bleu' as in chrF arguments for example. + # Let's do that manually here through dest= options, as otherwise + # things will get quite hard to maintain when other metrics are added. + bleu_args = arg_parser.add_argument_group('BLEU related arguments') + + bleu_args.add_argument('--smooth-method', '-s', choices=METRICS['BLEU'].SMOOTH_DEFAULTS.keys(), default='exp', + dest='bleu_smooth_method', + help='Smoothing method: exponential decay, floor (increment zero counts), add-k (increment num/denom by k for n>1), or none. (Default: %(default)s)') + bleu_args.add_argument('--smooth-value', '-sv', type=float, default=None, + dest='bleu_smooth_value', + help='The smoothing value. Only valid for floor and add-k. ' + f"(Defaults: floor: {METRICS['BLEU'].SMOOTH_DEFAULTS['floor']}, " + f"add-k: {METRICS['BLEU'].SMOOTH_DEFAULTS['add-k']})") + bleu_args.add_argument('--tokenize', '-tok', choices=METRICS['BLEU'].TOKENIZERS, default=None, + dest='bleu_tokenize', + help='Tokenization method to use for BLEU. If not provided, defaults to `zh` for Chinese, ' + '`ja-mecab` for Japanese, `ko-mecab` for Korean and `13a` (mteval) otherwise.') + bleu_args.add_argument('--lowercase', '-lc', dest='bleu_lowercase', action='store_true', default=False, + help='If True, enables case-insensitivity. (Default: %(default)s)') + bleu_args.add_argument('--force', default=False, action='store_true', + dest='bleu_force', help='Insist that your tokenized input is actually detokenized.') + + # ChrF-related arguments + chrf_args = arg_parser.add_argument_group('chrF related arguments') + chrf_args.add_argument('--chrf-char-order', '-cc', type=int, default=METRICS['CHRF'].CHAR_ORDER, + help='Character n-gram order. (Default: %(default)s)') + chrf_args.add_argument('--chrf-word-order', '-cw', type=int, default=METRICS['CHRF'].WORD_ORDER, + help='Word n-gram order (Default: %(default)s). If equals to 2, the metric is referred to as chrF++.') + chrf_args.add_argument('--chrf-beta', type=int, default=METRICS['CHRF'].BETA, + help='Determine the importance of recall w.r.t precision. (Default: %(default)s)') + chrf_args.add_argument('--chrf-whitespace', action='store_true', default=False, + help='Include whitespaces when extracting character n-grams. (Default: %(default)s)') + chrf_args.add_argument('--chrf-lowercase', action='store_true', default=False, + help='Enable case-insensitivity. (Default: %(default)s)') + chrf_args.add_argument('--chrf-eps-smoothing', action='store_true', default=False, + help='Enables epsilon smoothing similar to chrF++.py, NLTK and Moses; instead of effective order smoothing. (Default: %(default)s)') + + # TER related arguments + ter_args = arg_parser.add_argument_group("TER related arguments (The defaults replicate TERCOM's behavior)") + ter_args.add_argument('--ter-case-sensitive', action='store_true', + help='Enables case sensitivity. (Default: %(default)s)') + ter_args.add_argument('--ter-asian-support', action='store_true', + help='Enables special treatment of Asian characters. (Default: %(default)s)') + ter_args.add_argument('--ter-no-punct', action='store_true', + help='Removes punctuation. (Default: %(default)s)') + ter_args.add_argument('--ter-normalized', action='store_true', + help='Applies basic normalization and tokenization. (Default: %(default)s)') + + # Bootstrap resampling for confidence intervals + sign_args = arg_parser.add_argument_group('Confidence interval (CI) estimation for single-system evaluation') + sign_args.add_argument('--confidence', '-ci', action='store_true', + help='Report confidence interval using bootstrap resampling.') + sign_args.add_argument('--confidence-n', '-cin', type=int, default=1000, + help='Set the number of bootstrap resamples for CI estimation (Default: %(default)s).') + + # Paired significance testing + pair_args = arg_parser.add_argument_group('Paired significance testing for multi-system evaluation') + pair_args_choice = pair_args.add_mutually_exclusive_group() + + pair_args_choice.add_argument('--paired-ar', '-par', action='store_true', + help='Perform paired test using approximate randomization (AR). This option is ' + 'mutually exclusive with --paired-bs (Default: %(default)s).') + pair_args_choice.add_argument('--paired-bs', '-pbs', action='store_true', + help='Perform paired test using bootstrap resampling. This option is ' + 'mutually exclusive with --paired-ar (Default: %(default)s).') + + pair_args.add_argument('--paired-ar-n', '-parn', type=int, default=10000, + help='Number of trials for approximate randomization test (Default: %(default)s).') + + pair_args.add_argument('--paired-bs-n', '-pbsn', type=int, default=1000, + help='Number of bootstrap resamples for paired bootstrap resampling test (Default: %(default)s).') + + pair_args.add_argument('--paired-jobs', '-j', type=int, default=1, + help='If 0, launches as many workers as the number of systems. If > 0, sets the number of workers manually. ' + 'This feature is currently not supported on Windows.') + + # Reporting related arguments + report_args = arg_parser.add_argument_group('Reporting related arguments') + report_args.add_argument('--quiet', '-q', default=False, action='store_true', + help='Suppress verbose messages.') + report_args.add_argument('--short', '-sh', default=False, action='store_true', + help='Produce a shorter (less human readable) signature.') + report_args.add_argument('--score-only', '-b', default=False, action='store_true', + help='Print only the computed score.') + report_args.add_argument('--width', '-w', type=int, default=1, + help='Floating point width (Default: %(default)s).') + report_args.add_argument('--detail', '-d', default=False, action='store_true', + help='Print detailed information (split test sets based on origlang).') + report_args.add_argument('--no-color', '-nc', action='store_true', + help='Disable the occasional use of terminal colors.') + + output_formats = ['json', 'text', 'latex'] + report_args.add_argument('--format', '-f', default='json', choices=output_formats, + help='Set the output format. `latex` is only valid for multi-system mode whereas ' + '`json` and `text` apply to single-system mode only. This flag is overridden if the ' + 'SACREBLEU_FORMAT environment variable is set to one of the valid choices (Default: %(default)s).') + + arg_parser.add_argument('--version', '-V', action='version', version='%(prog)s {}'.format(VERSION)) + + args = arg_parser.parse_args() + + # Override the format from the environment, if any + if 'SACREBLEU_FORMAT' in os.environ: + _new_value = os.environ['SACREBLEU_FORMAT'].lower() + if _new_value in output_formats: + args.format = _new_value + + return args + + +def main(): + args = parse_args() + + # Is paired test requested? + paired_test_mode = args.paired_bs or args.paired_ar + + # Explicitly set the encoding + sys.stdin = open(sys.stdin.fileno(), mode='r', encoding='utf-8', buffering=True, newline="\n") + sys.stdout = open(sys.stdout.fileno(), mode='w', encoding='utf-8', buffering=True) + + if os.environ.get('NO_COLOR', False) or args.no_color: + Color.ENABLE_COLORS = False + else: + # These should come after all stdout manipulations otherwise cause + # issues esp. on Windows + import colorama + colorama.init() + + if not args.quiet: + logging.basicConfig(level=logging.INFO, format='sacreBLEU: %(message)s') + + if args.download: + download_test_set(args.download, args.langpair) + sys.exit(0) + + if args.list: + if args.test_set: + langpairs = get_langpairs_for_testset(args.test_set) + for pair in langpairs: + fields = DATASETS[args.test_set].fieldnames(pair) + print(f'{pair}: {", ".join(fields)}') + else: + if args.langpair: + print(f'The available test sets for {args.langpair} are:') + testsets = get_available_testsets_for_langpair(args.langpair) + else: + print('The available test sets are:') + testsets = get_available_testsets() + for testset in sorted(testsets): + desc = DATASETS[testset].description.strip() + print(f'{testset:<30}: {desc}') + sys.exit(0) + + if args.sentence_level and len(args.metrics) > 1: + sacrelogger.error('Only one metric can be used in sentence-level mode.') + sys.exit(1) + + if args.citation: + if not args.test_set: + sacrelogger.error('I need a test set (-t).') + sys.exit(1) + for test_set in args.test_set.split(','): + if 'citation' not in DATASETS[test_set]: + sacrelogger.error(f'No citation found for {test_set}') + else: + print(DATASETS[test_set].citation) + sys.exit(0) + + if args.num_refs != 1 and (args.test_set is not None or len(args.refs) > 1): + sacrelogger.error('The --num-refs argument allows you to provide any number of tab-delimited references in a single file.') + sacrelogger.error('You can only use it with externally provided references, however (i.e., not with `-t`),') + sacrelogger.error('and you cannot then provide multiple reference files.') + sys.exit(1) + + if args.test_set is not None: + for test_set in args.test_set.split(','): + if test_set not in DATASETS: + sacrelogger.error(f'Unknown test set {test_set!r}') + sacrelogger.error('Please run with --list to see the available test sets.') + sys.exit(1) + + if args.test_set is None: + if len(args.refs) == 0: + sacrelogger.error('If manual references given, make sure to provide them ' + 'before the -i/--input argument to avoid confusion.') + sacrelogger.error('Otherwise, I need a predefined test set (-t) from the following list:') + sacrelogger.error(get_available_testsets()) + sys.exit(1) + elif len(args.refs) > 0: + sacrelogger.error('I need exactly one of (a) a predefined test set (-t) or (b) a list of references') + sys.exit(1) + elif args.langpair is None: + sacrelogger.error('I need a language pair (-l). Use --list to see available language pairs for this test set.') + sys.exit(1) + else: + for test_set in args.test_set.split(','): + langpairs = get_langpairs_for_testset(test_set) + if args.langpair not in langpairs: + sacrelogger.error(f'No such language pair {args.langpair!r}') + sacrelogger.error(f'Available language pairs for {test_set!r} are:') + for lp in langpairs: + sacrelogger.error(f' > {lp}') + sys.exit(1) + + if args.echo: + if args.langpair is None or args.test_set is None: + sacrelogger.warning("--echo requires a test set (--t) and a language pair (-l)") + sys.exit(1) + for test_set in args.test_set.split(','): + print_test_set(test_set, args.langpair, args.echo, args.origlang, args.subset) + sys.exit(0) + + # Hack: inject target language info for BLEU, so that it can + # select the tokenizer based on it + if args.langpair: + args.bleu_trg_lang = args.langpair.split('-')[1] + + if args.test_set is not None and args.bleu_tokenize == 'none': + sacrelogger.warning( + "You are turning off BLEU's internal tokenizer " + "presumably to supply your own tokenized files.") + sacrelogger.warning( + "Published numbers will not be comparable to other papers.") + + # concat_ref_files is a list of list of reference filenames + # (concatenation happens if multiple test sets are given through -t) + # Example: [[testset1_refA, testset1_refB], [testset2_refA, testset2_refB]] + concat_ref_files = [] + if args.test_set is None: + concat_ref_files.append(args.refs) + else: + # Multiple test sets can be given + for test_set in args.test_set.split(','): + ref_files = get_reference_files(test_set, args.langpair) + if len(ref_files) == 0: + sacrelogger.warning( + f'No references found for test set {test_set}/{args.langpair}.') + concat_ref_files.append(ref_files) + + ################# + # Read references + ################# + full_refs = [[] for x in range(max(len(concat_ref_files[0]), args.num_refs))] + for ref_files in concat_ref_files: + for refno, ref_file in enumerate(ref_files): + for lineno, line in enumerate(smart_open(ref_file, encoding=args.encoding), 1): + line = line.rstrip() + if args.num_refs == 1: + full_refs[refno].append(line) + else: + refs = line.split(sep='\t', maxsplit=args.num_refs - 1) + # We are strict in fixed number of references through CLI + # But the API supports having variable refs per each segment + # by simply having '' or None's as dummy placeholders + if len(refs) != args.num_refs: + sacrelogger.error(f'FATAL: line {lineno}: expected {args.num_refs} fields, but found {len(refs)}.') + sys.exit(17) + for refno, ref in enumerate(refs): + full_refs[refno].append(ref) + + # Decide on the number of final references, override the argument + args.num_refs = len(full_refs) + + # Read hypotheses + # Can't tokenize yet as each metric has its own way of tokenizing things + full_systems, sys_names = [], [] + + if args.input is None: + # Read from STDIN + inputfh = io.TextIOWrapper(sys.stdin.buffer, encoding=args.encoding) + + # guess the number of systems by looking at the first line + fields = inputfh.readline().rstrip().split('\t') + + # Set number of systems + num_sys = len(fields) + + # place the first lines already + full_systems = [[s] for s in fields] + + # Enumerate the systems + sys_names = [f'System {i + 1}' for i in range(num_sys)] + + # Read the rest + for line in inputfh: + fields = line.rstrip().split('\t') + if len(fields) != num_sys: + sacrelogger.error('FATAL: the number of tab-delimited fields in the input stream differ across lines.') + sys.exit(17) + # Place systems into the list + for sys_idx, sent in enumerate(fields): + full_systems[sys_idx].append(sent.rstrip()) + else: + # Separate files are given for each system output + # Ex: --input smt.txt nmt.txt + for fname in args.input: + sys_name = fname + + if sys_name in sys_names: + if paired_test_mode and sys_name == sys_names[0]: + # We skip loading a system, if it was already the baseline + sacrelogger.info(f'Ignoring {sys_name!r} as it was also given as the baseline.') + continue + else: + # To avoid ambiguities, we fail if two systems have same names + sacrelogger.error(f"{sys_name!r} already used to name a system.") + sacrelogger.error("Make sure to have a different basename for each system.") + sys.exit(1) + + # Read the system + lines = [] + for line in smart_open(fname, encoding=args.encoding): + lines.append(line.rstrip()) + full_systems.append(lines) + sys_names.append(sys_name) + + # Set final number of systems + num_sys = len(sys_names) + + # Add baseline prefix to the first system for clarity + if paired_test_mode: + if args.input is None: + # STDIN mode, no explicit system names + sys_names = ['Baseline'] + [f'System {i + 1}' for i in range(num_sys - 1)] + else: + # --input mode, we have names for the systems, just change the 1st one + sys_names[0] = f'Baseline: {sys_names[0]}' + + if args.sentence_level: + if num_sys > 1: + sacrelogger.error('Only one system can be evaluated in sentence-level mode.') + sys.exit(1) + if args.confidence or paired_test_mode: + sacrelogger.error('Statistical tests are unavailable in sentence-level mode.') + sys.exit(1) + + # >=2.0.0: effective_order is now part of BLEU class. For sentence-BLEU + # we now need to explicitly enable it without user's intervention + # for backward compatibility. + args.bleu_effective_order = True + + if paired_test_mode and num_sys == 1: + sacrelogger.error('Paired tests require multiple input systems given to --input (-i).') + sys.exit(1) + + if num_sys > 1 and args.confidence: + sacrelogger.error('Use paired tests (--paired) for multiple systems.') + sys.exit(1) + + # Filter subsets if requested + outputs = filter_subset( + [*full_systems, *full_refs], args.test_set, args.langpair, + args.origlang, args.subset) + + # Unpack systems & references back + systems, refs = outputs[:num_sys], outputs[num_sys:] + + # Perform some sanity checks + for system in systems: + if len(system) == 0: + message = f'Test set {args.test_set!r} contains no sentence' + if args.origlang is not None or args.subset is not None: + message += ' with' + if args.origlang: + message += f' origlang={args.origlang}' + if args.subset: + message += f' subset={args.subset}' + args.subset + sacrelogger.error(message) + sys.exit(1) + + # Check lengths + sanity_check_lengths(system, refs, test_set=args.test_set) + + # Create the metrics + metrics = {} + for name in args.metrics: + # Each metric's specific arguments are prefixed with `metricname_` + # for grouping. Filter accordingly and strip the prefixes prior to + # metric object construction. + metric_args = args_to_dict(args, name.lower(), strip_prefix=True) + + # This will cache reference stats for faster re-computation if required + metric_args['references'] = refs + + # Make it uppercase for the rest of the code + name = name.upper() + metrics[name] = METRICS[name](**metric_args) + + # Handle sentence level and quit + if args.sentence_level: + # one metric and one system in use for sentence-level + metric, system = list(metrics.values())[0], systems[0] + + for hypothesis, *references in zip(system, *refs): + score = metric.sentence_score(hypothesis, references) + sig = metric.get_signature().format(args.short) + print(score.format(args.width, args.score_only, sig)) + + sys.exit(0) + + if args.detail and args.format == 'json': + # The translationese info will interfere with JSON output, disable + args.format = 'text' + + ############################## + # Corpus level evaluation mode + ############################## + if num_sys == 1: + # Single system evaluation mode + results = [] + for name in sorted(metrics): + # compute the score + score = metrics[name].corpus_score( + system, references=None, + n_bootstrap=args.confidence_n if args.confidence else 1) + # get the signature + sig = metrics[name].get_signature().format( + args.short if args.format != 'json' else False) + results.append( + score.format(args.width, args.score_only, sig, args.format == 'json')) + + print_single_results(results, args) + + # Prints detailed information for translationese effect experiments + if args.detail: + print_subset_results(metrics, full_systems[0], full_refs, args) + else: + # Multi-system evaluation mode + named_systems = [(sys_names[i], systems[i]) for i in range(num_sys)] + sacrelogger.info(f'Found {num_sys} systems.') + + if not paired_test_mode: + # Bootstrap resampling or the usual single score computation mode + sigs = {} + scores = defaultdict(list) + scores['System'] = sys_names + + for sys_name, system in named_systems: + for name in sorted(metrics): + score = metrics[name].corpus_score(system, references=None) + sigs[score.name] = metrics[name].get_signature().format(args.short) + scores[score.name].append(score.format(args.width, True)) + + else: + # Paired significance testing mode + from .significance import PairedTest + + # Set params + test_type = 'bs' if args.paired_bs else 'ar' + n_samples = args.paired_bs_n if args.paired_bs else args.paired_ar_n + + ps = PairedTest(named_systems, metrics, references=None, + test_type=test_type, n_samples=n_samples, + n_jobs=args.paired_jobs) + + # Set back the number of trials + args.paired_n = ps.n_samples + + # Run the test + sigs, scores = ps() + + # Get signature strings + sigs = {k: v.format(args.short) for k, v in sigs.items()} + + # Dump the results + print_results_table(scores, sigs, args) + + +if __name__ == '__main__': + main() diff --git a/env-llmeval/lib/python3.10/site-packages/sacrebleu/significance.py b/env-llmeval/lib/python3.10/site-packages/sacrebleu/significance.py new file mode 100644 index 0000000000000000000000000000000000000000..a9c71d0ab935d0eb195b68126bcad4bdf0facd6e --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sacrebleu/significance.py @@ -0,0 +1,435 @@ +import os +import logging +import multiprocessing as mp +from typing import Sequence, Dict, Optional, Tuple, List, Union, Any, Mapping + +import numpy as np + +from .metrics.base import Metric, Score, Signature + +IS_WINDOWS = os.name == 'nt' + + +sacrelogger = logging.getLogger('sacrebleu') + + +class Result: + """A container to represent results from a particular statistical + significance test. + :param score: The floating point score for the system at hand. + :param p_value: If exists, represents the p-value when the system at + hand is compared to a baseline using a paired test. + :param mean: When paired bootstrap test is applied, this represents + the true mean score estimated from bootstrap resamples of the system. + :param ci: When paired bootstrap test is applied, this represents + the 95% confidence interval around the true mean score `sys_mean`. + """ + def __init__(self, score: float, p_value: Optional[float] = None, + mean: Optional[float] = None, ci: Optional[float] = None): + self.score = score + self.p_value = p_value + self.mean = mean + self.ci = ci + + def __repr__(self): + return ','.join([f'{k}={str(v)}' for k, v in self.__dict__.items()]) + + +def estimate_ci(scores: np.ndarray) -> Tuple[float, float]: + """Takes a list of scores and returns mean and 95% confidence + interval around the mean. + + :param scores: A list of floating point scores. + :return: A tuple of mean and the 95% CI. + """ + # Sort the scores + scores = np.sort(scores) + n = len(scores) + + # Get CI bounds (95%, i.e. 1/40 from left) + lower_idx = n // 40 + upper_idx = n - lower_idx - 1 + lower, upper = scores[lower_idx], scores[upper_idx] + ci = 0.5 * (upper - lower) + return (scores.mean(), ci) + + +def _bootstrap_resample(stats: List[List[Union[int, float]]], + metric: Metric, n_samples: int = 1000) -> Tuple[str, List[Score]]: + """Performs bootstrap resampling for a single system to estimate + a confidence interval around the true mean. + :param stats: A list of statistics extracted from the system's hypotheses. + :param metric: The `Metric` instance to be used for score computation. + :n_samples: Number of bootstrap resamples to use. + + :return: A tuple of the seed choice as string and the list of `Score` + instances for all bootstrap resamples. + """ + + # Set numpy RNG's seed + # If given -> Fix to the given value + # If given but =='[Nn]one', don't fix the seed i.e. pull entropy from OS + seed = os.environ.get('SACREBLEU_SEED', '12345') + _seed = None if seed.lower() == 'none' else int(seed) + rng = np.random.default_rng(_seed) + + # The indices that'll produce all bootstrap resamples at once + idxs = rng.choice(len(stats), size=(n_samples, len(stats)), replace=True) + + # convert to numpy array. float32 is more efficient + stats_np = np.array(stats, dtype='float32') + + # recompute scores for all resamples + scores = [ + metric._compute_score_from_stats(_s.sum(0)) for _s in stats_np[idxs]] + + return str(seed).lower(), scores + + +def _compute_p_value(stats: np.ndarray, real_difference: float) -> float: + """Computes the p-value given the sample statistics and the real statistic. + :param stats: A numpy array with the sample statistics. + :real_difference: The real statistic. + :return: The p-value. + """ + # Taken from: significance/StratifiedApproximateRandomizationTest.java + # https://github.com/jhclark/multeval.git + + # "the != is important. if we want to score the same system against itself + # having a zero difference should not be attributed to chance." + + c = np.sum(stats > real_difference).item() + + # "+1 applies here, though it only matters for small numbers of shufflings, + # which we typically never do. it's necessary to ensure the probability of + # falsely rejecting the null hypothesis is no greater than the rejection + # level of the test (see william and morgan on significance tests) + p = (c + 1) / (len(stats) + 1) + + return p + + +def _paired_ar_test(baseline_info: Dict[str, Tuple[np.ndarray, Result]], + sys_name: str, + hypotheses: Sequence[str], + references: Optional[Sequence[Sequence[str]]], + metrics: Dict[str, Metric], + n_samples: int = 10000, + n_ar_confidence: int = -1, + seed: Optional[int] = None) -> Tuple[str, Dict[str, Result]]: + """Paired two-sided approximate randomization (AR) test for MT evaluation. + + :param baseline_info: A dictionary with `Metric` instances as the keys, + that contains sufficient statistics and a `Result` instance for the baseline system. + :param sys_name: The name of the system to be evaluated. + :param hypotheses: A sequence of string hypotheses for the system. + :param references: A sequence of reference documents with document being + defined as a sequence of reference strings. If `None`, references + will be used through each metric's internal cache. + :param metrics: A dictionary of `Metric` instances that will be computed + for each system. + :param n_samples: The number of AR trials. + :param n_ar_confidence: The number of bootstrap resamples to use for + confidence estimation. A value of -1 disables confidence estimation. + :param seed: The seed value for the RNG. If `None`, the RNG will not be + fixed to a particular seed. + + :return: A tuple with first element being the system name and the second + being a `Result` namedtuple. + """ + # Seed the RNG + rng = np.random.default_rng(seed) + + # Generate indices that'll select stats + pos_sel = rng.integers(2, size=(n_samples, len(hypotheses)), dtype=bool) + + # Flip mask to obtain selectors for system hypotheses + neg_sel = ~pos_sel + + if n_ar_confidence > 0: + # Perform confidence estimation as well + bs_idxs = rng.choice( + len(hypotheses), size=(n_ar_confidence, len(hypotheses)), replace=True) + + results = {} + + for name, metric in metrics.items(): + # Use pre-computed match stats for the baseline + bl_stats, bl_result = baseline_info[name] + + # Compute system's stats and score + sacrelogger.info(f'Computing {name} for {sys_name!r} and extracting sufficient statistics') + sys_stats = metric._extract_corpus_statistics(hypotheses, references) + sys_score = metric._aggregate_and_compute(sys_stats) + + # original test statistic: absolute difference between baseline and the system + diff = abs(bl_result.score - sys_score.score) + + sacrelogger.info(f' > Performing approximate randomization test (# trials: {n_samples})') + # get shuffled pseudo systems + shuf_a = pos_sel @ bl_stats + neg_sel @ sys_stats + shuf_b = neg_sel @ bl_stats + pos_sel @ sys_stats + + # Aggregate trial stats and compute scores for each + scores_a = np.array( + [metric._aggregate_and_compute(x).score for x in shuf_a[:, None]]) + scores_b = np.array( + [metric._aggregate_and_compute(x).score for x in shuf_b[:, None]]) + + # Count the statistical difference and compute the p-value + p = _compute_p_value( + np.abs(np.array(scores_a) - np.array(scores_b)), diff) + + res = Result(sys_score.score, p) + + if n_ar_confidence > 0: + sacrelogger.info(f' > Performing bootstrap resampling for confidence interval (# resamples: {n_ar_confidence})') + sys_stats = np.array(sys_stats, dtype='float32') + # recompute scores for all resamples + sys_scores = np.array([ + metric._compute_score_from_stats(_s.sum(0)).score for _s in sys_stats[bs_idxs] + ]) + res.mean, res.ci = estimate_ci(sys_scores) + + # Store the result + results[name] = res + + return sys_name, results + + +def _paired_bs_test(baseline_info: Dict[str, Tuple[np.ndarray, Result]], + sys_name: str, + hypotheses: Sequence[str], + references: Optional[Sequence[Sequence[str]]], + metrics: Dict[str, Metric], + n_samples: int = 1000, + n_ar_confidence: int = -1, + seed: Optional[int] = None) -> Tuple[str, Dict[str, Result]]: + """Paired bootstrap resampling test for MT evaluation. This function + replicates the behavior of the Moses script called + `bootstrap-hypothesis-difference-significance.pl`. + + :param baseline_info: A dictionary with `Metric` instances as the keys, + that contains sufficient statistics and a `Result` instance for the baseline system. + :param sys_name: The name of the system to be evaluated. + :param hypotheses: A sequence of string hypotheses for the system. + :param references: A sequence of reference documents with document being + defined as a sequence of reference strings. If `None`, references + will be used through each metric's internal cache. + :param metrics: A dictionary of `Metric` instances that will be computed + for each system. + :param n_samples: The number of bootstrap resamples. + :param n_ar_confidence: This parameter is not used for this function but + is there for signature compatibility in the API. + :param seed: The seed value for the RNG. If `None`, the RNG will not be + fixed to a particular seed. + + :return: A tuple with first element being the system name and the second + being a `Result` namedtuple. + """ + # Seed the RNG + rng = np.random.default_rng(seed) + + results = {} + + # It takes ~10ms to generated the indices + idxs = rng.choice( + len(hypotheses), size=(n_samples, len(hypotheses)), replace=True) + + for name, metric in metrics.items(): + # Use pre-computed match stats for the baseline + bl_stats, bl_result = baseline_info[name] + + # Compute system's stats and score + sacrelogger.info(f'Computing {name} for {sys_name!r} and extracting sufficient statistics') + sys_stats = metric._extract_corpus_statistics(hypotheses, references) + sys_score = metric._aggregate_and_compute(sys_stats) + + # Convert to numpy arrays for efficient indexing + sys_stats = np.array(sys_stats, dtype='float32') + bl_stats = np.array(bl_stats, dtype='float32') + + # original test statistic: absolute difference between baseline and the system + diff = abs(bl_result.score - sys_score.score) + + sacrelogger.info(f' > Performing paired bootstrap resampling test (# resamples: {n_samples})') + scores_bl = np.array( + [metric._compute_score_from_stats(_s.sum(0)).score for _s in bl_stats[idxs]]) + scores_sys = np.array( + [metric._compute_score_from_stats(_s.sum(0)).score for _s in sys_stats[idxs]]) + + # Compute CI as well + sys_mean, sys_ci = estimate_ci(scores_sys) + + # Compute the statistics + sample_diffs = np.abs(scores_sys - scores_bl) + stats = sample_diffs - sample_diffs.mean() + + # Count the statistical difference and compute the p-value + p = _compute_p_value(stats, diff) + + results[name] = Result(sys_score.score, p, sys_mean, sys_ci) + + return sys_name, results + + +class PairedTest: + """This is the manager class that will call the actual standalone implementation + for approximate randomization or paired bootstrap resampling, based on the + `test_type` argument. + + :param named_systems: A lisf of (system_name, system_hypotheses) tuples on + which the test will be applied. + :param metrics: A dictionary of `Metric` instances that will be computed + for each system. + :param references: A sequence of reference documents with document being + defined as a sequence of reference strings. If `None`, already cached references + will be used through each metric's internal cache. + :param test_type: `ar` for approximate randomization, `bs` for paired bootstrap. + :param n_samples: The number of AR trials (for `ar`) or bootstrap resamples (for `bs`). + The defaults (10000 or 1000 respectively) will be used if 0 is passed. + :param n_ar_confidence: If `approximate randomization` is selected, the number + of bootstrap resamples to use for confidence estimation. A value of -1 disables + confidence estimation. 0 will use the default of 1000. + :param n_jobs: If 0, a worker process will be spawned for each system variant. + If > 0, the number of workers will be set accordingly. The default of 1 + does not use multi-processing. + """ + _DEFAULT_SAMPLES = { + 'ar': 10000, + 'bs': 1000, + } + + def __init__(self, named_systems: List[Tuple[str, Sequence[str]]], + metrics: Mapping[str, Metric], + references: Optional[Sequence[Sequence[str]]], + test_type: str = 'ar', + n_samples: int = 0, + n_ar_confidence: int = -1, + n_jobs: int = 1): + assert test_type in ('ar', 'bs'), f"Unknown test type {test_type!r}" + self.test_type = test_type + + # Set method + if self.test_type == 'ar': + self._fn = _paired_ar_test + elif self.test_type == 'bs': + self._fn = _paired_bs_test + + # Set numpy RNG's seed + # If given -> Fix to the given value + # If given but =='[Nn]one', don't fix the seed i.e. pull entropy from OS + seed = os.environ.get('SACREBLEU_SEED', '12345') + self._seed = None if seed.lower() == 'none' else int(seed) + self.n_jobs = n_jobs + self.references = references + self.named_systems = named_systems + + # Set the defaults if requested + self.n_ar_confidence = n_ar_confidence if n_ar_confidence != 0 else \ + self._DEFAULT_SAMPLES['bs'] + + self.n_samples = n_samples if n_samples > 0 else \ + self._DEFAULT_SAMPLES[self.test_type] + + # Number of systems (excluding the baseline) + self.n_systems = len(named_systems) - 1 + + # Decide on number of workers + if IS_WINDOWS: + sacrelogger.warning('Parallel tests are not supported on Windows.') + self.n_jobs = 1 + elif self.n_jobs == 0: + # Decide automatically + # Divide by two to ignore hyper-threading + n_max_jobs = mp.cpu_count() // 2 + if n_max_jobs == 0: + self.n_jobs = 1 + else: + # Don't use more workers than the number of CPUs + self.n_jobs = min(n_max_jobs, self.n_systems) + + self._signatures: Dict[str, Signature] = {} + self._baseline_info: Dict[str, Tuple[Any, Result]] = {} + + ################################################## + # Pre-compute and cache baseline system statistics + ################################################## + self.metrics = {} + + bl_name, bl_hyps = self.named_systems[0] + + for name, metric in metrics.items(): + sacrelogger.info(f'Pre-computing {name} statistics for {bl_name!r}') + bl_stats = metric._extract_corpus_statistics(bl_hyps, self.references) + bl_score = metric._aggregate_and_compute(bl_stats) + + # Compute CI for the baseline here once + confidence_n = self.n_samples if self.test_type == 'bs' \ + else self.n_ar_confidence + + bl_mean, bl_ci = None, None + if confidence_n > 0: + _, bl_scores = _bootstrap_resample(bl_stats, metric, confidence_n) + bl_mean, bl_ci = estimate_ci(np.array([x.score for x in bl_scores])) + + result = Result(bl_score.score, mean=bl_mean, ci=bl_ci) + # Use updated name for the metric + self._baseline_info[bl_score.name] = (bl_stats, result) + self.metrics[bl_score.name] = metric + + # Update metric signature as well + sig = metric.get_signature() + sig.update('seed', str(self._seed).lower()) + + # Num samples for bs, num trials for AR + sig.update(self.test_type, self.n_samples) + if self.n_ar_confidence > 0: + # Bootstrap is used for AR CI as well + sig.update('bs', self.n_ar_confidence) + self._signatures[bl_score.name] = sig + + def __call__(self) -> Tuple[Dict[str, Signature], Dict[str, List[Union[str, Result]]]]: + """Runs the paired test either on single or multiple worker processes.""" + tasks = [] + scores: Dict[str, List[Union[str, Result]]] = {} + + # Add the name column + scores['System'] = [ns[0] for ns in self.named_systems] + + # Store baseline results as the first position + for metric, (_, result) in self._baseline_info.items(): + scores[metric] = [result] + + # Prepare list of arguments for each comparison + # Skip the baseline (pos: 0) + for idx, (name, hyps) in enumerate(self.named_systems[1:]): + seed = self._seed if self._seed else None + + tasks.append( + (self._baseline_info, name, hyps, self.references, + self.metrics, self.n_samples, self.n_ar_confidence, seed)) + + # Run the test(s) + if self.n_jobs == 1: + results = [self._fn(*args) for args in tasks] + else: + # NOTE: The overhead of worker creation is not negligible + # but if you have many systems and TER enabled, this significantly + # speeds up the test. + # NOTE: This only works on Linux/Mac OS X but not Windows. Windows only + # supports `spawn` backend which requires things to be called + # from within __main__. + sacrelogger.info(f'Launching {self.n_jobs} parallel workers.') + with mp.get_context('fork').Pool(self.n_jobs) as pool: + jobs = [pool.apply_async(self._fn, args) for args in tasks] + + # wait for completion + results = [j.get() for j in jobs] + + # Keep the order deterministic + for sys_name, sys_results in results: + for metric, _result in sys_results.items(): + scores[metric].append(_result) + + return self._signatures, scores diff --git a/env-llmeval/lib/python3.10/site-packages/scikit_learn-1.4.2.dist-info/COPYING b/env-llmeval/lib/python3.10/site-packages/scikit_learn-1.4.2.dist-info/COPYING new file mode 100644 index 0000000000000000000000000000000000000000..b161c890897cc16c67281beac870f829e545f397 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scikit_learn-1.4.2.dist-info/COPYING @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2007-2023 The scikit-learn developers. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/env-llmeval/lib/python3.10/site-packages/scikit_learn-1.4.2.dist-info/INSTALLER b/env-llmeval/lib/python3.10/site-packages/scikit_learn-1.4.2.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scikit_learn-1.4.2.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/env-llmeval/lib/python3.10/site-packages/scikit_learn-1.4.2.dist-info/METADATA b/env-llmeval/lib/python3.10/site-packages/scikit_learn-1.4.2.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..c9a5851e27e0dd1886429f94f9902df0a25c13d2 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scikit_learn-1.4.2.dist-info/METADATA @@ -0,0 +1,282 @@ +Metadata-Version: 2.1 +Name: scikit-learn +Version: 1.4.2 +Summary: A set of python modules for machine learning and data mining +Home-page: https://scikit-learn.org +Download-URL: https://pypi.org/project/scikit-learn/#files +Maintainer: Andreas Mueller +Maintainer-email: amueller@ais.uni-bonn.de +License: new BSD +Project-URL: Bug Tracker, https://github.com/scikit-learn/scikit-learn/issues +Project-URL: Documentation, https://scikit-learn.org/stable/documentation.html +Project-URL: Source Code, https://github.com/scikit-learn/scikit-learn +Classifier: Intended Audience :: Science/Research +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Programming Language :: C +Classifier: Programming Language :: Python +Classifier: Topic :: Software Development +Classifier: Topic :: Scientific/Engineering +Classifier: Development Status :: 5 - Production/Stable +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: POSIX +Classifier: Operating System :: Unix +Classifier: Operating System :: MacOS +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Requires-Python: >=3.9 +License-File: COPYING +Requires-Dist: numpy >=1.19.5 +Requires-Dist: scipy >=1.6.0 +Requires-Dist: joblib >=1.2.0 +Requires-Dist: threadpoolctl >=2.0.0 +Provides-Extra: benchmark +Requires-Dist: matplotlib >=3.3.4 ; extra == 'benchmark' +Requires-Dist: pandas >=1.1.5 ; extra == 'benchmark' +Requires-Dist: memory-profiler >=0.57.0 ; extra == 'benchmark' +Provides-Extra: docs +Requires-Dist: matplotlib >=3.3.4 ; extra == 'docs' +Requires-Dist: scikit-image >=0.17.2 ; extra == 'docs' +Requires-Dist: pandas >=1.1.5 ; extra == 'docs' +Requires-Dist: seaborn >=0.9.0 ; extra == 'docs' +Requires-Dist: memory-profiler >=0.57.0 ; extra == 'docs' +Requires-Dist: sphinx >=6.0.0 ; extra == 'docs' +Requires-Dist: sphinx-copybutton >=0.5.2 ; extra == 'docs' +Requires-Dist: sphinx-gallery >=0.15.0 ; extra == 'docs' +Requires-Dist: numpydoc >=1.2.0 ; extra == 'docs' +Requires-Dist: Pillow >=7.1.2 ; extra == 'docs' +Requires-Dist: pooch >=1.6.0 ; extra == 'docs' +Requires-Dist: sphinx-prompt >=1.3.0 ; extra == 'docs' +Requires-Dist: sphinxext-opengraph >=0.4.2 ; extra == 'docs' +Requires-Dist: plotly >=5.14.0 ; extra == 'docs' +Provides-Extra: examples +Requires-Dist: matplotlib >=3.3.4 ; extra == 'examples' +Requires-Dist: scikit-image >=0.17.2 ; extra == 'examples' +Requires-Dist: pandas >=1.1.5 ; extra == 'examples' +Requires-Dist: seaborn >=0.9.0 ; extra == 'examples' +Requires-Dist: pooch >=1.6.0 ; extra == 'examples' +Requires-Dist: plotly >=5.14.0 ; extra == 'examples' +Provides-Extra: tests +Requires-Dist: matplotlib >=3.3.4 ; extra == 'tests' +Requires-Dist: scikit-image >=0.17.2 ; extra == 'tests' +Requires-Dist: pandas >=1.1.5 ; extra == 'tests' +Requires-Dist: pytest >=7.1.2 ; extra == 'tests' +Requires-Dist: pytest-cov >=2.9.0 ; extra == 'tests' +Requires-Dist: ruff >=0.0.272 ; extra == 'tests' +Requires-Dist: black >=23.3.0 ; extra == 'tests' +Requires-Dist: mypy >=1.3 ; extra == 'tests' +Requires-Dist: pyamg >=4.0.0 ; extra == 'tests' +Requires-Dist: polars >=0.19.12 ; extra == 'tests' +Requires-Dist: pyarrow >=12.0.0 ; extra == 'tests' +Requires-Dist: numpydoc >=1.2.0 ; extra == 'tests' +Requires-Dist: pooch >=1.6.0 ; extra == 'tests' + +.. -*- mode: rst -*- + +|Azure|_ |CirrusCI|_ |Codecov|_ |CircleCI|_ |Nightly wheels|_ |Black|_ |PythonVersion|_ |PyPi|_ |DOI|_ |Benchmark|_ + +.. |Azure| image:: https://dev.azure.com/scikit-learn/scikit-learn/_apis/build/status/scikit-learn.scikit-learn?branchName=main +.. _Azure: https://dev.azure.com/scikit-learn/scikit-learn/_build/latest?definitionId=1&branchName=main + +.. |CircleCI| image:: https://circleci.com/gh/scikit-learn/scikit-learn/tree/main.svg?style=shield +.. _CircleCI: https://circleci.com/gh/scikit-learn/scikit-learn + +.. |CirrusCI| image:: https://img.shields.io/cirrus/github/scikit-learn/scikit-learn/main?label=Cirrus%20CI +.. _CirrusCI: https://cirrus-ci.com/github/scikit-learn/scikit-learn/main + +.. |Codecov| image:: https://codecov.io/gh/scikit-learn/scikit-learn/branch/main/graph/badge.svg?token=Pk8G9gg3y9 +.. _Codecov: https://codecov.io/gh/scikit-learn/scikit-learn + +.. |Nightly wheels| image:: https://github.com/scikit-learn/scikit-learn/workflows/Wheel%20builder/badge.svg?event=schedule +.. _`Nightly wheels`: https://github.com/scikit-learn/scikit-learn/actions?query=workflow%3A%22Wheel+builder%22+event%3Aschedule + +.. |PythonVersion| image:: https://img.shields.io/pypi/pyversions/scikit-learn.svg +.. _PythonVersion: https://pypi.org/project/scikit-learn/ + +.. |PyPi| image:: https://img.shields.io/pypi/v/scikit-learn +.. _PyPi: https://pypi.org/project/scikit-learn + +.. |Black| image:: https://img.shields.io/badge/code%20style-black-000000.svg +.. _Black: https://github.com/psf/black + +.. |DOI| image:: https://zenodo.org/badge/21369/scikit-learn/scikit-learn.svg +.. _DOI: https://zenodo.org/badge/latestdoi/21369/scikit-learn/scikit-learn + +.. |Benchmark| image:: https://img.shields.io/badge/Benchmarked%20by-asv-blue +.. _`Benchmark`: https://scikit-learn.org/scikit-learn-benchmarks/ + +.. |PythonMinVersion| replace:: 3.9 +.. |NumPyMinVersion| replace:: 1.19.5 +.. |SciPyMinVersion| replace:: 1.6.0 +.. |JoblibMinVersion| replace:: 1.2.0 +.. |ThreadpoolctlMinVersion| replace:: 2.0.0 +.. |MatplotlibMinVersion| replace:: 3.3.4 +.. |Scikit-ImageMinVersion| replace:: 0.17.2 +.. |PandasMinVersion| replace:: 1.1.5 +.. |SeabornMinVersion| replace:: 0.9.0 +.. |PytestMinVersion| replace:: 7.1.2 +.. |PlotlyMinVersion| replace:: 5.14.0 + +.. image:: https://raw.githubusercontent.com/scikit-learn/scikit-learn/main/doc/logos/scikit-learn-logo.png + :target: https://scikit-learn.org/ + +**scikit-learn** is a Python module for machine learning built on top of +SciPy and is distributed under the 3-Clause BSD license. + +The project was started in 2007 by David Cournapeau as a Google Summer +of Code project, and since then many volunteers have contributed. See +the `About us `__ page +for a list of core contributors. + +It is currently maintained by a team of volunteers. + +Website: https://scikit-learn.org + +Installation +------------ + +Dependencies +~~~~~~~~~~~~ + +scikit-learn requires: + +- Python (>= |PythonMinVersion|) +- NumPy (>= |NumPyMinVersion|) +- SciPy (>= |SciPyMinVersion|) +- joblib (>= |JoblibMinVersion|) +- threadpoolctl (>= |ThreadpoolctlMinVersion|) + +======= + +**Scikit-learn 0.20 was the last version to support Python 2.7 and Python 3.4.** +scikit-learn 1.0 and later require Python 3.7 or newer. +scikit-learn 1.1 and later require Python 3.8 or newer. + +Scikit-learn plotting capabilities (i.e., functions start with ``plot_`` and +classes end with ``Display``) require Matplotlib (>= |MatplotlibMinVersion|). +For running the examples Matplotlib >= |MatplotlibMinVersion| is required. +A few examples require scikit-image >= |Scikit-ImageMinVersion|, a few examples +require pandas >= |PandasMinVersion|, some examples require seaborn >= +|SeabornMinVersion| and plotly >= |PlotlyMinVersion|. + +User installation +~~~~~~~~~~~~~~~~~ + +If you already have a working installation of NumPy and SciPy, +the easiest way to install scikit-learn is using ``pip``:: + + pip install -U scikit-learn + +or ``conda``:: + + conda install -c conda-forge scikit-learn + +The documentation includes more detailed `installation instructions `_. + + +Changelog +--------- + +See the `changelog `__ +for a history of notable changes to scikit-learn. + +Development +----------- + +We welcome new contributors of all experience levels. The scikit-learn +community goals are to be helpful, welcoming, and effective. The +`Development Guide `_ +has detailed information about contributing code, documentation, tests, and +more. We've included some basic information in this README. + +Important links +~~~~~~~~~~~~~~~ + +- Official source code repo: https://github.com/scikit-learn/scikit-learn +- Download releases: https://pypi.org/project/scikit-learn/ +- Issue tracker: https://github.com/scikit-learn/scikit-learn/issues + +Source code +~~~~~~~~~~~ + +You can check the latest sources with the command:: + + git clone https://github.com/scikit-learn/scikit-learn.git + +Contributing +~~~~~~~~~~~~ + +To learn more about making a contribution to scikit-learn, please see our +`Contributing guide +`_. + +Testing +~~~~~~~ + +After installation, you can launch the test suite from outside the source +directory (you will need to have ``pytest`` >= |PyTestMinVersion| installed):: + + pytest sklearn + +See the web page https://scikit-learn.org/dev/developers/contributing.html#testing-and-improving-test-coverage +for more information. + + Random number generation can be controlled during testing by setting + the ``SKLEARN_SEED`` environment variable. + +Submitting a Pull Request +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Before opening a Pull Request, have a look at the +full Contributing page to make sure your code complies +with our guidelines: https://scikit-learn.org/stable/developers/index.html + +Project History +--------------- + +The project was started in 2007 by David Cournapeau as a Google Summer +of Code project, and since then many volunteers have contributed. See +the `About us `__ page +for a list of core contributors. + +The project is currently maintained by a team of volunteers. + +**Note**: `scikit-learn` was previously referred to as `scikits.learn`. + +Help and Support +---------------- + +Documentation +~~~~~~~~~~~~~ + +- HTML documentation (stable release): https://scikit-learn.org +- HTML documentation (development version): https://scikit-learn.org/dev/ +- FAQ: https://scikit-learn.org/stable/faq.html + +Communication +~~~~~~~~~~~~~ + +- Mailing list: https://mail.python.org/mailman/listinfo/scikit-learn +- Gitter: https://gitter.im/scikit-learn/scikit-learn +- Logos & Branding: https://github.com/scikit-learn/scikit-learn/tree/main/doc/logos +- Blog: https://blog.scikit-learn.org +- Calendar: https://blog.scikit-learn.org/calendar/ +- Twitter: https://twitter.com/scikit_learn +- Stack Overflow: https://stackoverflow.com/questions/tagged/scikit-learn +- Github Discussions: https://github.com/scikit-learn/scikit-learn/discussions +- Website: https://scikit-learn.org +- LinkedIn: https://www.linkedin.com/company/scikit-learn +- YouTube: https://www.youtube.com/channel/UCJosFjYm0ZYVUARxuOZqnnw/playlists +- Facebook: https://www.facebook.com/scikitlearnofficial/ +- Instagram: https://www.instagram.com/scikitlearnofficial/ +- TikTok: https://www.tiktok.com/@scikit.learn + +Citation +~~~~~~~~ + +If you use scikit-learn in a scientific publication, we would appreciate citations: https://scikit-learn.org/stable/about.html#citing-scikit-learn diff --git a/env-llmeval/lib/python3.10/site-packages/scikit_learn-1.4.2.dist-info/RECORD b/env-llmeval/lib/python3.10/site-packages/scikit_learn-1.4.2.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..bf26f7e9a8dd1c2a84ad78d749adeff86a58e0c4 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scikit_learn-1.4.2.dist-info/RECORD @@ -0,0 +1,1320 @@ +scikit_learn-1.4.2.dist-info/COPYING,sha256=2B5zOc_vVX3r9tghTkoxrNAbMUTSs55CUTw8flwp5cI,1532 +scikit_learn-1.4.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +scikit_learn-1.4.2.dist-info/METADATA,sha256=LSlaPFxWsJ917qsSh9jKvdQuQFOxhWMKq6OOwxyXYkU,11206 +scikit_learn-1.4.2.dist-info/RECORD,, +scikit_learn-1.4.2.dist-info/WHEEL,sha256=CzQQWV-lNyM92gr3iaBk8dvO35YDHRxgzkZ-dxumUIM,152 +scikit_learn-1.4.2.dist-info/top_level.txt,sha256=RED9Cd42eES2ITQsRYJc34r65tejDc9eVxnPLzvX9Qg,8 +scikit_learn.libs/libgomp-a34b3233.so.1.0.0,sha256=On6uznIxkRvi-7Gz58tMtcLg-E4MK7c3OUcrWh_uyME,168193 +sklearn/__check_build/__init__.py,sha256=JruJx_tWLpC-K3O0b8tNRXthdPV86qfy9SpbOvscsgM,1680 +sklearn/__check_build/__pycache__/__init__.cpython-310.pyc,, +sklearn/__check_build/_check_build.cpython-310-x86_64-linux-gnu.so,sha256=cdFJiee-y59Nj5inW-9HZZ1kjghw6aSGkFErNZDOTco,51281 +sklearn/__init__.py,sha256=2TACobDuZbVMiTtXNcfnyrofI2TY0hgS8QJYZklaBT0,5015 +sklearn/__pycache__/__init__.cpython-310.pyc,, +sklearn/__pycache__/_config.cpython-310.pyc,, +sklearn/__pycache__/_distributor_init.cpython-310.pyc,, +sklearn/__pycache__/_min_dependencies.cpython-310.pyc,, +sklearn/__pycache__/base.cpython-310.pyc,, +sklearn/__pycache__/calibration.cpython-310.pyc,, +sklearn/__pycache__/conftest.cpython-310.pyc,, +sklearn/__pycache__/discriminant_analysis.cpython-310.pyc,, +sklearn/__pycache__/dummy.cpython-310.pyc,, +sklearn/__pycache__/exceptions.cpython-310.pyc,, +sklearn/__pycache__/isotonic.cpython-310.pyc,, +sklearn/__pycache__/kernel_approximation.cpython-310.pyc,, +sklearn/__pycache__/kernel_ridge.cpython-310.pyc,, +sklearn/__pycache__/multiclass.cpython-310.pyc,, +sklearn/__pycache__/multioutput.cpython-310.pyc,, +sklearn/__pycache__/naive_bayes.cpython-310.pyc,, +sklearn/__pycache__/pipeline.cpython-310.pyc,, +sklearn/__pycache__/random_projection.cpython-310.pyc,, +sklearn/_build_utils/__init__.py,sha256=9Ik8pfXFJRnME--_KzzrtIphncGUuYtXWQ3NFebLGs4,3610 +sklearn/_build_utils/__pycache__/__init__.cpython-310.pyc,, +sklearn/_build_utils/__pycache__/openmp_helpers.cpython-310.pyc,, +sklearn/_build_utils/__pycache__/pre_build_helpers.cpython-310.pyc,, +sklearn/_build_utils/__pycache__/tempita.cpython-310.pyc,, +sklearn/_build_utils/__pycache__/version.cpython-310.pyc,, +sklearn/_build_utils/openmp_helpers.py,sha256=qQn0P1DaPeAVRJ9ex9S6R3bX9rQKPs3bilwbaVHFzzc,4531 +sklearn/_build_utils/pre_build_helpers.py,sha256=wD5ICjm_mnx5vu671Gji6TTQwnxnRtzwStbP4b8tHww,2175 +sklearn/_build_utils/tempita.py,sha256=tbdUwI2z8sZsILx8HW14wvvnZ3nPJu3WSnbrSKNHv44,1580 +sklearn/_build_utils/version.py,sha256=XBgTAN5lyGcAdjCdO7m2Q7CDb5uqdmYzn-5te2TjRwc,369 +sklearn/_config.py,sha256=FNcObaJ5G2Wt8I7RoVvg16XETLNfRAYq-32nc7LRm8c,13493 +sklearn/_distributor_init.py,sha256=WNbFpommZbSnO0E2dEGphWbiyDPYluRs6Zm3M6qVl3g,345 +sklearn/_isotonic.cpython-310-x86_64-linux-gnu.so,sha256=kctj3XZuNiWdwmWEXBPdOeLyE4_5r8yCyx0pY_bsxAg,307073 +sklearn/_loss/__init__.py,sha256=h6rcvQ8upIDgpKkknp4tiCpB4Tc_F64SF0mqwIqFOOo,607 +sklearn/_loss/__pycache__/__init__.cpython-310.pyc,, +sklearn/_loss/__pycache__/link.cpython-310.pyc,, +sklearn/_loss/__pycache__/loss.cpython-310.pyc,, +sklearn/_loss/_loss.cpython-310-x86_64-linux-gnu.so,sha256=e4IlZL0WW-i9jhOvGbYSOV-MrnDflK3iE64cYwYweOA,3043289 +sklearn/_loss/_loss.pxd,sha256=Bfj-t0M0JWMNEJPSztH7TC4VTgzAiH82VcjM16IzzrY,4315 +sklearn/_loss/link.py,sha256=lTNOfhB8uJKu_gksS0Xs3L41z_-OS4fhJjiGGacElnE,8101 +sklearn/_loss/loss.py,sha256=7loXQtpcKLBssIYsskSf9MvFk6_BrPMM8aPhaNOW5pg,41236 +sklearn/_loss/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/_loss/tests/__pycache__/__init__.cpython-310.pyc,, +sklearn/_loss/tests/__pycache__/test_link.cpython-310.pyc,, +sklearn/_loss/tests/__pycache__/test_loss.cpython-310.pyc,, +sklearn/_loss/tests/test_link.py,sha256=XMHMLjmPA1RHLrAhexoMzVQRlokcCT9LMhajVVnneS0,3954 +sklearn/_loss/tests/test_loss.py,sha256=8XZkS-kHAxk_NLb8JtMQAbVe7umsrEpUAbFc9fXQAL8,48281 +sklearn/_min_dependencies.py,sha256=qia4qBZhJAkE0kswB7R1SZz3RthvyZCOcjZd360r1yc,2481 +sklearn/base.py,sha256=h_wcRlgLC8J94i0UP4OAt0emcPFWdT5apsyxzO3ZWyI,53077 +sklearn/calibration.py,sha256=sRaaATaWWO4ulouLs8GAu2TMoEN543MpjWcRoLd9FfI,49547 +sklearn/cluster/__init__.py,sha256=gmJNjlPlWd3BDjFysHYNjOVikk6Sya7sr_RdIliyHhs,1440 +sklearn/cluster/__pycache__/__init__.cpython-310.pyc,, +sklearn/cluster/__pycache__/_affinity_propagation.cpython-310.pyc,, +sklearn/cluster/__pycache__/_agglomerative.cpython-310.pyc,, +sklearn/cluster/__pycache__/_bicluster.cpython-310.pyc,, +sklearn/cluster/__pycache__/_birch.cpython-310.pyc,, +sklearn/cluster/__pycache__/_bisect_k_means.cpython-310.pyc,, +sklearn/cluster/__pycache__/_dbscan.cpython-310.pyc,, +sklearn/cluster/__pycache__/_feature_agglomeration.cpython-310.pyc,, +sklearn/cluster/__pycache__/_kmeans.cpython-310.pyc,, +sklearn/cluster/__pycache__/_mean_shift.cpython-310.pyc,, +sklearn/cluster/__pycache__/_optics.cpython-310.pyc,, +sklearn/cluster/__pycache__/_spectral.cpython-310.pyc,, +sklearn/cluster/_affinity_propagation.py,sha256=svVmof62bCXaxHNXiyYtdpC0vBGOBwZxDurQVHGP2Yg,20512 +sklearn/cluster/_agglomerative.py,sha256=qN-zIElSTWT8fV7z_FZD5wUFww5LxGyPAI8_9Yyt8ME,49039 +sklearn/cluster/_bicluster.py,sha256=4S3MjZWSfCnPCd0VQfB610PJxfp3-wpRtoT9yvpFjLI,22157 +sklearn/cluster/_birch.py,sha256=iXlHqWOouJNbMIHOi0-PsnNrxg5klhc1NID_dTV4KII,26249 +sklearn/cluster/_bisect_k_means.py,sha256=dn6AaJCv1XkNSZA4M8phB3T94chx10lk377cDn-f-A8,19040 +sklearn/cluster/_dbscan.py,sha256=1T2rDaQitn0iDDF0jef8W27XXw0Tvve6Qdy2BTDjDvw,18290 +sklearn/cluster/_dbscan_inner.cpython-310-x86_64-linux-gnu.so,sha256=LhSRAcFX-Gy_gjokUDO1n7AZzXb6g2nSLtDULjWcjc8,221449 +sklearn/cluster/_feature_agglomeration.py,sha256=9eyY-7HLVKBNVy9uYXHshCWRchkZLaRac1FU_JmPKxI,3347 +sklearn/cluster/_hdbscan/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/cluster/_hdbscan/__pycache__/__init__.cpython-310.pyc,, +sklearn/cluster/_hdbscan/__pycache__/hdbscan.cpython-310.pyc,, +sklearn/cluster/_hdbscan/_linkage.cpython-310-x86_64-linux-gnu.so,sha256=QPKua9nh1i0ZnQY2wZTr0EkPpUabBRa_D-yv5drum-I,257737 +sklearn/cluster/_hdbscan/_reachability.cpython-310-x86_64-linux-gnu.so,sha256=fohsD__saJsOWrcAGW5K22rWsWj5SJpQcrKX21JjRbY,364553 +sklearn/cluster/_hdbscan/_tree.cpython-310-x86_64-linux-gnu.so,sha256=786Y1WBySzFR-pjID3c3hjt-UEUKPS-rB9d7DDGbRps,385041 +sklearn/cluster/_hdbscan/_tree.pxd,sha256=Nm7ghFqifD2vLnyBoCQCn9eFsmoB8ITpEuCMItJZoM4,2150 +sklearn/cluster/_hdbscan/hdbscan.py,sha256=dC89rO5W8uMsTfnVTkZr7QDlkIFJnM_2BhozF5ompRk,41849 +sklearn/cluster/_hdbscan/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/cluster/_hdbscan/tests/__pycache__/__init__.cpython-310.pyc,, +sklearn/cluster/_hdbscan/tests/__pycache__/test_reachibility.cpython-310.pyc,, +sklearn/cluster/_hdbscan/tests/test_reachibility.py,sha256=XTEaYbj7i48dD3ImCC4jiVVPF1chsCTJvL78A6kgwVI,2064 +sklearn/cluster/_hierarchical_fast.cpython-310-x86_64-linux-gnu.so,sha256=5IWsSZgy4g_ZW2Tkij1rEHrZ6KRFAeJnaTzT0hdwagM,332041 +sklearn/cluster/_hierarchical_fast.pxd,sha256=JlWtArNtEgc2RBeCJRADftNTPwNV_M-OAsAJz7lHqzY,245 +sklearn/cluster/_k_means_common.cpython-310-x86_64-linux-gnu.so,sha256=zDNJO2tPldG--L7w6oPPCjpYecxrnJ9yafiwRx8-Pzg,528553 +sklearn/cluster/_k_means_common.pxd,sha256=6QW18TtC1wGpyTd0cdG9PxSYTiP4ZN3hj6ltJWrdaic,887 +sklearn/cluster/_k_means_elkan.cpython-310-x86_64-linux-gnu.so,sha256=lZS6V4CUPoS_k15xEUVeBynMzNcMAV8rKMdFsdrCFJ4,525713 +sklearn/cluster/_k_means_lloyd.cpython-310-x86_64-linux-gnu.so,sha256=EAMizxqj6XUAtJljO10E1r5UYs9kF9ssOjHjKHd19rE,381249 +sklearn/cluster/_k_means_minibatch.cpython-310-x86_64-linux-gnu.so,sha256=2uA5WGiNe_-73bwbxPntDtvFqTwIQi0M__ja3EklQ6Y,323521 +sklearn/cluster/_kmeans.py,sha256=tQoOJiD6SkTge6863fMpP_pJN5qET5tqqj75UDbG0Io,82683 +sklearn/cluster/_mean_shift.py,sha256=HVOYLcRVbJagF0olj3atEx_7dl-93AxYrpLfzQtcR-Q,20156 +sklearn/cluster/_optics.py,sha256=WGairyeJcQgkc90bLiIEzV4jpTnTz0XGNsEI3Nmb_wQ,44710 +sklearn/cluster/_spectral.py,sha256=Ll9UD3VCzj9fjpzXjhfkmiCFh39PS6w1Nm4_xaK5Wvo,30496 +sklearn/cluster/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/cluster/tests/__pycache__/__init__.cpython-310.pyc,, +sklearn/cluster/tests/__pycache__/common.cpython-310.pyc,, +sklearn/cluster/tests/__pycache__/test_affinity_propagation.cpython-310.pyc,, +sklearn/cluster/tests/__pycache__/test_bicluster.cpython-310.pyc,, +sklearn/cluster/tests/__pycache__/test_birch.cpython-310.pyc,, +sklearn/cluster/tests/__pycache__/test_bisect_k_means.cpython-310.pyc,, +sklearn/cluster/tests/__pycache__/test_dbscan.cpython-310.pyc,, +sklearn/cluster/tests/__pycache__/test_feature_agglomeration.cpython-310.pyc,, +sklearn/cluster/tests/__pycache__/test_hdbscan.cpython-310.pyc,, +sklearn/cluster/tests/__pycache__/test_hierarchical.cpython-310.pyc,, +sklearn/cluster/tests/__pycache__/test_k_means.cpython-310.pyc,, +sklearn/cluster/tests/__pycache__/test_mean_shift.cpython-310.pyc,, +sklearn/cluster/tests/__pycache__/test_optics.cpython-310.pyc,, +sklearn/cluster/tests/__pycache__/test_spectral.cpython-310.pyc,, +sklearn/cluster/tests/common.py,sha256=1jmt9fXRXYt9TYCwJFcgDGV10slNNjJW7_2tRCSzJBY,880 +sklearn/cluster/tests/test_affinity_propagation.py,sha256=p-q92owXh0cG1oPD3d5VZOfQoZMwEeDfRlTAS25NTa0,11898 +sklearn/cluster/tests/test_bicluster.py,sha256=JJjahw-5rSvyNcKpz0ZtM1jl07jvLAB5D9zdzcqMXU4,9126 +sklearn/cluster/tests/test_birch.py,sha256=1vCTQlIByLia7dwJ8Lequ6OhDuuUjnIbayPgoxk0lD0,8606 +sklearn/cluster/tests/test_bisect_k_means.py,sha256=1hf2vfXJ_0aIncY-bZMgx5TXTzGI49YCfVxChYrsLno,5139 +sklearn/cluster/tests/test_dbscan.py,sha256=JSM4FNsCxmH0VyOFSqkdgyB85JdXUMQtd-8lwS7yXSQ,15704 +sklearn/cluster/tests/test_feature_agglomeration.py,sha256=2QkZ3T7Mvfg1XwGh_3-NoNnsnHpIgCxSg5yz4z3KVeo,2758 +sklearn/cluster/tests/test_hdbscan.py,sha256=0GqV7x2I03IjsH5IcDLK8IiwHnZzmYi_BOIG87FNpxY,19392 +sklearn/cluster/tests/test_hierarchical.py,sha256=UJCK18h_TwJ84wn02hOtT3Au8KjLFowRxjkxJ-gVgtg,32593 +sklearn/cluster/tests/test_k_means.py,sha256=CLs8bYbbOY32A0Xpy3kwejgXwcNkHO9P1iJ5nUiIYYA,48900 +sklearn/cluster/tests/test_mean_shift.py,sha256=5lHWOiId4Amtf2QKOYAhRvKREqOTRoQmYo-JLAYUBCc,6740 +sklearn/cluster/tests/test_optics.py,sha256=cEfXbSTjRIQH-sSyermCf_eS7isa40mfAdIqYSsTMY0,23214 +sklearn/cluster/tests/test_spectral.py,sha256=2Iz8eEYiS1d390L3KFpHffjfUXhq1FsGvysIIKXZt64,11903 +sklearn/compose/__init__.py,sha256=3oylapF_cdAjGu_O0dG5y_lVgysP_82YCgMw-dGvEwU,497 +sklearn/compose/__pycache__/__init__.cpython-310.pyc,, +sklearn/compose/__pycache__/_column_transformer.cpython-310.pyc,, +sklearn/compose/__pycache__/_target.cpython-310.pyc,, +sklearn/compose/_column_transformer.py,sha256=WwDIU3wRqL_3JGmaSM7NMr5Y8UXR-cxLqfbhst_urQM,57863 +sklearn/compose/_target.py,sha256=wMqlqp9siDJnPXLt6PZVw0vy23T2v5s4eP-Dl9l_sdU,11914 +sklearn/compose/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/compose/tests/__pycache__/__init__.cpython-310.pyc,, +sklearn/compose/tests/__pycache__/test_column_transformer.cpython-310.pyc,, +sklearn/compose/tests/__pycache__/test_target.cpython-310.pyc,, +sklearn/compose/tests/test_column_transformer.py,sha256=4ImMmeQ-opmKw3h3ityPoXNuM726gUUYwvLjLhEpWSc,88405 +sklearn/compose/tests/test_target.py,sha256=QitfNBvImH78zJ6PZq2djXqN3TRIXUoEjUrk6zrMzM0,13153 +sklearn/conftest.py,sha256=mvWtOrXq6ckIvxYL-WJEeKA22Bu4t87aKaV7KeMw4-U,10497 +sklearn/covariance/__init__.py,sha256=QIZ6_Kv3C0mYMzIiUVrLV78CABMB5XgDjviFL3vLuvs,1116 +sklearn/covariance/__pycache__/__init__.cpython-310.pyc,, +sklearn/covariance/__pycache__/_elliptic_envelope.cpython-310.pyc,, +sklearn/covariance/__pycache__/_empirical_covariance.cpython-310.pyc,, +sklearn/covariance/__pycache__/_graph_lasso.cpython-310.pyc,, +sklearn/covariance/__pycache__/_robust_covariance.cpython-310.pyc,, +sklearn/covariance/__pycache__/_shrunk_covariance.cpython-310.pyc,, +sklearn/covariance/_elliptic_envelope.py,sha256=ceE6aGsrBFdEWkASDAWcJz0mk8Qv2meEu3hRBN5mAlw,9073 +sklearn/covariance/_empirical_covariance.py,sha256=2WJLKg6Rtf2sX4APZIU1AF0Ak2AiOCTP4rbWycf8lY8,12066 +sklearn/covariance/_graph_lasso.py,sha256=ZUBmJZwBFV8v1SeYJ--NRTPZMDH575IAaWMc0BIgDfE,39099 +sklearn/covariance/_robust_covariance.py,sha256=YxvsfJNRwjOJvbnU-9DdVBxRUcDQyZ2PD30pC6reN1Y,33901 +sklearn/covariance/_shrunk_covariance.py,sha256=Wh-9P54AOAYuEY1HHxBhc-Y0Kxlo7q8ryL3i3VwCmcg,27837 +sklearn/covariance/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/covariance/tests/__pycache__/__init__.cpython-310.pyc,, +sklearn/covariance/tests/__pycache__/test_covariance.cpython-310.pyc,, +sklearn/covariance/tests/__pycache__/test_elliptic_envelope.cpython-310.pyc,, +sklearn/covariance/tests/__pycache__/test_graphical_lasso.cpython-310.pyc,, +sklearn/covariance/tests/__pycache__/test_robust_covariance.cpython-310.pyc,, +sklearn/covariance/tests/test_covariance.py,sha256=68giftSkZ5lXHCVKZ6TYXdp0ukYSznhIbliJT83qOTE,14154 +sklearn/covariance/tests/test_elliptic_envelope.py,sha256=xCxtRYDNADB22KJURLGRqI2OoWh4LLfazpjgsIWOzH4,1587 +sklearn/covariance/tests/test_graphical_lasso.py,sha256=XOSg2PN_MACNcsnoh44juz7jozxrJlYr1-WqfC21tO0,10237 +sklearn/covariance/tests/test_robust_covariance.py,sha256=dM2CUrR9oPcVLhDjTHpvSHHU2GE2EBgtsFsiPNEPEOE,6384 +sklearn/cross_decomposition/__init__.py,sha256=Ga98Z9vAIoQO6RD5C2HMdRdQd-LcbcuyF0HmkfWYmFY,121 +sklearn/cross_decomposition/__pycache__/__init__.cpython-310.pyc,, +sklearn/cross_decomposition/__pycache__/_pls.cpython-310.pyc,, +sklearn/cross_decomposition/_pls.py,sha256=W19rbWEYhqrG5fH2LTd0-iaD6hHAIOnJf5RgdWzzrys,36773 +sklearn/cross_decomposition/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/cross_decomposition/tests/__pycache__/__init__.cpython-310.pyc,, +sklearn/cross_decomposition/tests/__pycache__/test_pls.cpython-310.pyc,, +sklearn/cross_decomposition/tests/test_pls.py,sha256=gfAaqMbUIRfz_XKIFktcddiRoO8Li3y4_zcKYbIuEcI,22294 +sklearn/datasets/__init__.py,sha256=Pbx-Q71GbemvICwD8-ISxH3iKb7nyrB2SYsyIJdBZVk,5170 +sklearn/datasets/__pycache__/__init__.cpython-310.pyc,, +sklearn/datasets/__pycache__/_arff_parser.cpython-310.pyc,, +sklearn/datasets/__pycache__/_base.cpython-310.pyc,, +sklearn/datasets/__pycache__/_california_housing.cpython-310.pyc,, +sklearn/datasets/__pycache__/_covtype.cpython-310.pyc,, +sklearn/datasets/__pycache__/_kddcup99.cpython-310.pyc,, +sklearn/datasets/__pycache__/_lfw.cpython-310.pyc,, +sklearn/datasets/__pycache__/_olivetti_faces.cpython-310.pyc,, +sklearn/datasets/__pycache__/_openml.cpython-310.pyc,, +sklearn/datasets/__pycache__/_rcv1.cpython-310.pyc,, +sklearn/datasets/__pycache__/_samples_generator.cpython-310.pyc,, +sklearn/datasets/__pycache__/_species_distributions.cpython-310.pyc,, +sklearn/datasets/__pycache__/_svmlight_format_io.cpython-310.pyc,, +sklearn/datasets/__pycache__/_twenty_newsgroups.cpython-310.pyc,, +sklearn/datasets/_arff_parser.py,sha256=-4QnUA8iBRy3ke3rJAnBTSJcGvP-ESyzdzjWNnTe1yE,19046 +sklearn/datasets/_base.py,sha256=BJ1O3bH96OsLMrHMk-Gmdeo1xGO7dGCEbLEjIeeJk5w,46825 +sklearn/datasets/_california_housing.py,sha256=MgHNMr3nKsTBwzNJAnOuEIRRiJufO8umPIDuCBSLw4Y,6707 +sklearn/datasets/_covtype.py,sha256=W9gRIVPQtRIWlrkldUDeksIjXTDYx6c0e_OmEBI8MVc,7603 +sklearn/datasets/_kddcup99.py,sha256=R9CH2XoZLq9w9o6ENKuXfgb1BBxf-Nu65mGm_WFz7Aw,13168 +sklearn/datasets/_lfw.py,sha256=xexQxyAGh3DlPqoiy_rZhA4lVJXFD-8FodfQX2Zjzis,20477 +sklearn/datasets/_olivetti_faces.py,sha256=y7-SibQqxGfuSxD_Pp2ATjpSsq1rdieAGdYiyjQ-cG4,5322 +sklearn/datasets/_openml.py,sha256=XQ1CF6rqHqoI41LB9QL_iMxy10feNCkkmlG_mPW5kHA,41405 +sklearn/datasets/_rcv1.py,sha256=2dxAgHqOYIQpc4S8wHyyS_VTEa7ecYKrEDFB0MLkz58,11086 +sklearn/datasets/_samples_generator.py,sha256=DKy7kYCYpSdnZnJqScF0N6z7789g4VZOrIoMIHc4wdU,74553 +sklearn/datasets/_species_distributions.py,sha256=1wR3_fJrWCgIP-mYXp0GPRQicIBv7QYH9GfBFnMvyQ8,9189 +sklearn/datasets/_svmlight_format_fast.cpython-310-x86_64-linux-gnu.so,sha256=5dAqQdCGu4VaqcaW8tp6fAg-6RqJ1QHT9gZkmsZ7Gk0,590249 +sklearn/datasets/_svmlight_format_io.py,sha256=xj_LWToq8qMPjnPXtHaf_GGa8vZEP-IdRg5T2bTPTcE,20735 +sklearn/datasets/_twenty_newsgroups.py,sha256=voYQ_guybY3A77HnGYkJIc2LeJatPRirx3QqWNCvzUY,18913 +sklearn/datasets/data/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/datasets/data/__pycache__/__init__.cpython-310.pyc,, +sklearn/datasets/data/boston_house_prices.csv,sha256=2YISY2AmVE_JucDzcuX4GYcub6b6dXqwJe_doiGA8tY,34742 +sklearn/datasets/data/breast_cancer.csv,sha256=_tPrctBXXvYZIpP1CTxugBsUdrV30Dhr9EVVBFIhcu0,119913 +sklearn/datasets/data/diabetes_data_raw.csv.gz,sha256=o-lMx86gD4qE-l9jRSA5E6aO-kLfGPh935vq1yG_1QM,7105 +sklearn/datasets/data/diabetes_target.csv.gz,sha256=jlP2XrgR30PCBvNTS7OvDl_tITvDfta6NjEBV9YCOAM,1050 +sklearn/datasets/data/digits.csv.gz,sha256=CfZubeve4s0rWuWeDWq7tz_CsOAYXS4ZV-nrtR4jqiI,57523 +sklearn/datasets/data/iris.csv,sha256=8T_6j91W_Y5sjRbUCBo_vTEUvNCq5CVsQyBRac2dFEk,2734 +sklearn/datasets/data/linnerud_exercise.csv,sha256=y42MJJN2Q_okWWgu-4bF5me81t2TEJ7vgZZNnp8Rv4w,212 +sklearn/datasets/data/linnerud_physiological.csv,sha256=K_fgXBzX0K3w7KHkVpQfYkvtCk_JZpTWDQ_3hT7F_Pc,219 +sklearn/datasets/data/wine_data.csv,sha256=EOioApCLNPhuXajOli88gGaUvJhFChj2GFGvWfMkvt4,11157 +sklearn/datasets/descr/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/datasets/descr/__pycache__/__init__.cpython-310.pyc,, +sklearn/datasets/descr/breast_cancer.rst,sha256=gQy8SJmgJRvjH4zMTmGFkeKK0jyrFyJ-08By1PFzJ7Q,4811 +sklearn/datasets/descr/california_housing.rst,sha256=HBKYZzFjy739ZXX7vWoaRR0yfbw9xkJh6T9u7hQ0znA,1727 +sklearn/datasets/descr/covtype.rst,sha256=C6DmczitjtnrO-XhCIi8WqNT0uPgYnPWNYtKwJTwcn4,1191 +sklearn/datasets/descr/diabetes.rst,sha256=B9z8E5V6gkhb385Ers_7py55d1lZZtEYuB8WLLgn44E,1455 +sklearn/datasets/descr/digits.rst,sha256=iSCr2_fkFa_kMqJQpXkTAImrVDRXBArpZyEkebwVGag,2024 +sklearn/datasets/descr/iris.rst,sha256=t_96OerSrGIHOcfcya-69T0f36nWy6f7TUw9Ex_GwP4,2665 +sklearn/datasets/descr/kddcup99.rst,sha256=lcQA9DcRf3q0Okx8CLUG9avp86rxu6XhsEvrI99FoOQ,3950 +sklearn/datasets/descr/lfw.rst,sha256=soc3irgBLfBmHhRV5reiNq_fdtYrt70p_8LvKTsKQpw,4305 +sklearn/datasets/descr/linnerud.rst,sha256=mwQCX1cbqAqI9YgyXTv_SpMFJaBRgLjTYM-J2Q_M_4U,735 +sklearn/datasets/descr/olivetti_faces.rst,sha256=i8Y7-g4fOPdLvupgJ8i_ze1pA0hGpfDgAoPCGvCPFxI,1834 +sklearn/datasets/descr/rcv1.rst,sha256=3YqlbAwTbg72GXQjlNDtVXJdUPYoRcnZ-bG5vv8o-GM,2466 +sklearn/datasets/descr/species_distributions.rst,sha256=tu6kc_gE8kpjmg60LCjvUMIFDUEy0JadbTrpkvug_Ew,1547 +sklearn/datasets/descr/twenty_newsgroups.rst,sha256=1ADsYCB1zlNfXGYe6dzmeItGNp7kUec68s32dMUjjUQ,10823 +sklearn/datasets/descr/wine_data.rst,sha256=B9qRn3lNE-_1K68Mbv0lX-Y0bffqNEZ6dn_PjMHo-6I,3332 +sklearn/datasets/images/README.txt,sha256=P39i_fcnXC9qTHhglwo57LiFnc-1BiWgFGjRlg_MwG8,712 +sklearn/datasets/images/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/datasets/images/__pycache__/__init__.cpython-310.pyc,, +sklearn/datasets/images/china.jpg,sha256=g3gCWtJRnWSdAuMr2YmQ20q1cjV9nwmEHC-_u0_vrSk,196653 +sklearn/datasets/images/flower.jpg,sha256=p39uxB41Ov34vf8uqYGylVU12NgylPjPpJz05CPdVjg,142987 +sklearn/datasets/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/datasets/tests/__pycache__/__init__.cpython-310.pyc,, +sklearn/datasets/tests/__pycache__/test_20news.cpython-310.pyc,, +sklearn/datasets/tests/__pycache__/test_arff_parser.cpython-310.pyc,, +sklearn/datasets/tests/__pycache__/test_base.cpython-310.pyc,, +sklearn/datasets/tests/__pycache__/test_california_housing.cpython-310.pyc,, +sklearn/datasets/tests/__pycache__/test_common.cpython-310.pyc,, +sklearn/datasets/tests/__pycache__/test_covtype.cpython-310.pyc,, +sklearn/datasets/tests/__pycache__/test_kddcup99.cpython-310.pyc,, +sklearn/datasets/tests/__pycache__/test_lfw.cpython-310.pyc,, +sklearn/datasets/tests/__pycache__/test_olivetti_faces.cpython-310.pyc,, +sklearn/datasets/tests/__pycache__/test_openml.cpython-310.pyc,, +sklearn/datasets/tests/__pycache__/test_rcv1.cpython-310.pyc,, +sklearn/datasets/tests/__pycache__/test_samples_generator.cpython-310.pyc,, +sklearn/datasets/tests/__pycache__/test_svmlight_format.cpython-310.pyc,, +sklearn/datasets/tests/data/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/datasets/tests/data/__pycache__/__init__.cpython-310.pyc,, +sklearn/datasets/tests/data/openml/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/datasets/tests/data/openml/__pycache__/__init__.cpython-310.pyc,, +sklearn/datasets/tests/data/openml/id_1/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/datasets/tests/data/openml/id_1/__pycache__/__init__.cpython-310.pyc,, +sklearn/datasets/tests/data/openml/id_1/api-v1-jd-1.json.gz,sha256=hi4IUgokM6SVo7066f2ebHxUCpxjLbKbuCUnhMva13k,1786 +sklearn/datasets/tests/data/openml/id_1/api-v1-jdf-1.json.gz,sha256=qWba1Yz1-8kUo3StVVbAQU9e2WIjftVaN5_pbjCNAN4,889 +sklearn/datasets/tests/data/openml/id_1/api-v1-jdq-1.json.gz,sha256=hKhybSw_i7ynnVTYsZEVh0SxmTFG-PCDsRGo6nhTYFc,145 +sklearn/datasets/tests/data/openml/id_1/data-v1-dl-1.arff.gz,sha256=z-iUW5SXcLDaQtr1jOZ9HF_uJc97T9FFFhg3wqvAlCk,1841 +sklearn/datasets/tests/data/openml/id_1119/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/datasets/tests/data/openml/id_1119/__pycache__/__init__.cpython-310.pyc,, +sklearn/datasets/tests/data/openml/id_1119/api-v1-jd-1119.json.gz,sha256=xB5fuz5ZzU3oge18j4j5sDp1DVN7pjWByv3mqv13rcE,711 +sklearn/datasets/tests/data/openml/id_1119/api-v1-jdf-1119.json.gz,sha256=gviZ7cWctB_dZxslaiKOXgbfxeJMknEudQBbJRsACGU,1108 +sklearn/datasets/tests/data/openml/id_1119/api-v1-jdl-dn-adult-census-l-2-dv-1.json.gz,sha256=Sl3DbKl1gxOXiyqdecznY8b4TV2V8VrFV7PXSC8i7iE,364 +sklearn/datasets/tests/data/openml/id_1119/api-v1-jdl-dn-adult-census-l-2-s-act-.json.gz,sha256=bsCVV4iRT6gfaY6XpNGv93PXoSXtbnacYnGgtI_EAR0,363 +sklearn/datasets/tests/data/openml/id_1119/api-v1-jdq-1119.json.gz,sha256=73y8tYwu3P6kXAWLdR-vd4PnEEYqkk6arK2NR6fp-Us,1549 +sklearn/datasets/tests/data/openml/id_1119/data-v1-dl-54002.arff.gz,sha256=aTGvJWGV_N0uR92LD57fFvvwOxmOd7cOPf2Yd83wlRU,1190 +sklearn/datasets/tests/data/openml/id_1590/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/datasets/tests/data/openml/id_1590/__pycache__/__init__.cpython-310.pyc,, +sklearn/datasets/tests/data/openml/id_1590/api-v1-jd-1590.json.gz,sha256=mxBa3-3GtrgvRpXKm_4jI5MDTN95gDUj85em3Fv4JNE,1544 +sklearn/datasets/tests/data/openml/id_1590/api-v1-jdf-1590.json.gz,sha256=BG9eYFZGk_DzuOOCclyAEsPgWGRxOcJGhc7JhOQPzQA,1032 +sklearn/datasets/tests/data/openml/id_1590/api-v1-jdq-1590.json.gz,sha256=RLmw0pCh4zlpWkMUOPhAgAccVjUWHDl33Rf0wnsAo0o,1507 +sklearn/datasets/tests/data/openml/id_1590/data-v1-dl-1595261.arff.gz,sha256=7h3N9Y8vEHL33RtDOIlpxRvGz-d24-lGWuanVuXdsQo,1152 +sklearn/datasets/tests/data/openml/id_2/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/datasets/tests/data/openml/id_2/__pycache__/__init__.cpython-310.pyc,, +sklearn/datasets/tests/data/openml/id_2/api-v1-jd-2.json.gz,sha256=pnLUNbl6YDPf0dKlyCPSN60YZRAb1eQDzZm1vguk4Ds,1363 +sklearn/datasets/tests/data/openml/id_2/api-v1-jdf-2.json.gz,sha256=wbg4en0IAUocCYB65FjKdmarijxXnL-xieCcbX3okqY,866 +sklearn/datasets/tests/data/openml/id_2/api-v1-jdl-dn-anneal-l-2-dv-1.json.gz,sha256=6QCxkHlSJP9I5GocArEAINTJhroUKIDALIbwtHLe08k,309 +sklearn/datasets/tests/data/openml/id_2/api-v1-jdl-dn-anneal-l-2-s-act-.json.gz,sha256=_2Ily5gmDKTr7AFaGidU8qew2_tNDxfc9nJ1QhVOKhA,346 +sklearn/datasets/tests/data/openml/id_2/api-v1-jdq-2.json.gz,sha256=xG9sXyIdh33mBLkGQDsgy99nTxIlvNuz4VvRiCpppHE,1501 +sklearn/datasets/tests/data/openml/id_2/data-v1-dl-1666876.arff.gz,sha256=z-iUW5SXcLDaQtr1jOZ9HF_uJc97T9FFFhg3wqvAlCk,1841 +sklearn/datasets/tests/data/openml/id_292/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/datasets/tests/data/openml/id_292/__pycache__/__init__.cpython-310.pyc,, +sklearn/datasets/tests/data/openml/id_292/api-v1-jd-292.json.gz,sha256=Hmo4152PnlOizhG2i0FTBi1OluwLNo0CsuZPGzPFFpM,551 +sklearn/datasets/tests/data/openml/id_292/api-v1-jd-40981.json.gz,sha256=wm3L4wz7ORYfMFsrPUOptQrcizaNB0lWjEcQbL2yCJc,553 +sklearn/datasets/tests/data/openml/id_292/api-v1-jdf-292.json.gz,sha256=JVwW8z7Sln_hAM2AEafmn3iWA3JLHsLs-R3-tyBnwZA,306 +sklearn/datasets/tests/data/openml/id_292/api-v1-jdf-40981.json.gz,sha256=JVwW8z7Sln_hAM2AEafmn3iWA3JLHsLs-R3-tyBnwZA,306 +sklearn/datasets/tests/data/openml/id_292/api-v1-jdl-dn-australian-l-2-dv-1-s-dact.json.gz,sha256=jvYCVCX9_F9zZVXqOFJSr1vL9iODYV24JIk2bU-WoKc,327 +sklearn/datasets/tests/data/openml/id_292/api-v1-jdl-dn-australian-l-2-dv-1.json.gz,sha256=naCemmAx0GDsQW9jmmvzSYnmyIzmQdEGIeuQa6HYwpM,99 +sklearn/datasets/tests/data/openml/id_292/api-v1-jdl-dn-australian-l-2-s-act-.json.gz,sha256=NYkNCBZcgEUmtIqtRi18zAnoCL15dbpgS9YSuWCHl6w,319 +sklearn/datasets/tests/data/openml/id_292/data-v1-dl-49822.arff.gz,sha256=t-4kravUqu1kGbQ_6dP4bVX89L7g8WmK4h2GwnATFOM,2532 +sklearn/datasets/tests/data/openml/id_3/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/datasets/tests/data/openml/id_3/__pycache__/__init__.cpython-310.pyc,, +sklearn/datasets/tests/data/openml/id_3/api-v1-jd-3.json.gz,sha256=BmohZnmxl8xRlG4X7pouKCFUJZkbDOt_EJiMFPfz-Gk,2473 +sklearn/datasets/tests/data/openml/id_3/api-v1-jdf-3.json.gz,sha256=7E8ta8TfOIKwi7oBVx4HkqVveeCpItmEiXdzrNKEtCY,535 +sklearn/datasets/tests/data/openml/id_3/api-v1-jdq-3.json.gz,sha256=Ce8Zz60lxd5Ifduu88TQaMowY3d3MKKI39b1CWoMb0Y,1407 +sklearn/datasets/tests/data/openml/id_3/data-v1-dl-3.arff.gz,sha256=xj_fiGF2HxynBQn30tFpp8wFOYjHt8CcCabbYSTiCL4,19485 +sklearn/datasets/tests/data/openml/id_40589/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/datasets/tests/data/openml/id_40589/__pycache__/__init__.cpython-310.pyc,, +sklearn/datasets/tests/data/openml/id_40589/api-v1-jd-40589.json.gz,sha256=WdGqawLSNYwW-p5Pvv9SOjvRDr04x8NxkR-oM1573L8,598 +sklearn/datasets/tests/data/openml/id_40589/api-v1-jdf-40589.json.gz,sha256=gmurBXo5KfQRibxRr6ChdSaV5jzPIOEoymEp6eMyH8I,856 +sklearn/datasets/tests/data/openml/id_40589/api-v1-jdl-dn-emotions-l-2-dv-3.json.gz,sha256=Geayoqj-xUA8FGZCpNwuB31mo6Gsh-gjm9HdMckoq5w,315 +sklearn/datasets/tests/data/openml/id_40589/api-v1-jdl-dn-emotions-l-2-s-act-.json.gz,sha256=TaY6YBYzQLbhiSKr_n8fKnp9oj2mPCaTJJhdYf-qYHU,318 +sklearn/datasets/tests/data/openml/id_40589/api-v1-jdq-40589.json.gz,sha256=0PeXMZPrNdGemdHYvKPH86i40EEFCK80rVca7o7FqwU,913 +sklearn/datasets/tests/data/openml/id_40589/data-v1-dl-4644182.arff.gz,sha256=LEImVQgnzv81CcZxecRz4UOFzuIGU2Ni5XxeDfx3Ub8,4344 +sklearn/datasets/tests/data/openml/id_40675/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/datasets/tests/data/openml/id_40675/__pycache__/__init__.cpython-310.pyc,, +sklearn/datasets/tests/data/openml/id_40675/api-v1-jd-40675.json.gz,sha256=p4d3LWD7_MIaDpb9gZBvA1QuC5QtGdzJXa5HSYlTpP0,323 +sklearn/datasets/tests/data/openml/id_40675/api-v1-jdf-40675.json.gz,sha256=1I2WeXida699DTw0bjV211ibZjw2QJQvnB26duNV-qo,307 +sklearn/datasets/tests/data/openml/id_40675/api-v1-jdl-dn-glass2-l-2-dv-1-s-dact.json.gz,sha256=Ie0ezF2HSVbpUak2HyUa-yFlrdqSeYyJyl4vl66A3Y8,317 +sklearn/datasets/tests/data/openml/id_40675/api-v1-jdl-dn-glass2-l-2-dv-1.json.gz,sha256=rQpKVHdgU4D4gZzoQNu5KKPQhCZ8US9stQ1b4vfHa8I,85 +sklearn/datasets/tests/data/openml/id_40675/api-v1-jdl-dn-glass2-l-2-s-act-.json.gz,sha256=FBumMOA56kS7rvkqKI4tlk_Dqi74BalyO0qsc4ompic,88 +sklearn/datasets/tests/data/openml/id_40675/api-v1-jdq-40675.json.gz,sha256=iPzcOm_tVpfzbcJi9pv_-4FHZ84zb_KKId7zqsk3sIw,886 +sklearn/datasets/tests/data/openml/id_40675/data-v1-dl-4965250.arff.gz,sha256=VD0IhzEvQ9n2Wn4dCL54okNjafYy1zgrQTTOu1JaSKM,3000 +sklearn/datasets/tests/data/openml/id_40945/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/datasets/tests/data/openml/id_40945/__pycache__/__init__.cpython-310.pyc,, +sklearn/datasets/tests/data/openml/id_40945/api-v1-jd-40945.json.gz,sha256=AogsawLE4GjvKxbzfzOuPV6d0XyinQFmLGkk4WQn610,437 +sklearn/datasets/tests/data/openml/id_40945/api-v1-jdf-40945.json.gz,sha256=lfCTjf3xuH0P_E1SbyyR4JfvdolIC2k5cBJtkI8pEDA,320 +sklearn/datasets/tests/data/openml/id_40945/api-v1-jdq-40945.json.gz,sha256=nH5aRlVKtqgSGDLcDNn3pg9QNM7xpafWE0a72RJRa1Q,1042 +sklearn/datasets/tests/data/openml/id_40945/data-v1-dl-16826755.arff.gz,sha256=UW6WH1GYduX4mzOaA2SgjdZBYKw6TXbV7GKVW_1tbOU,32243 +sklearn/datasets/tests/data/openml/id_40966/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/datasets/tests/data/openml/id_40966/__pycache__/__init__.cpython-310.pyc,, +sklearn/datasets/tests/data/openml/id_40966/api-v1-jd-40966.json.gz,sha256=NsY8OsjJ21mRCsv0x3LNUwQMzQ6sCwRSYR3XrY2lBHQ,1660 +sklearn/datasets/tests/data/openml/id_40966/api-v1-jdf-40966.json.gz,sha256=itrI4vjLy_qWd6zdSSepYUMEZdLJlAGDIWC-RVz6ztg,3690 +sklearn/datasets/tests/data/openml/id_40966/api-v1-jdl-dn-miceprotein-l-2-dv-4.json.gz,sha256=8MIDtGJxdc679SfYGRekmZEa-RX28vRu5ySEKKlI1gM,325 +sklearn/datasets/tests/data/openml/id_40966/api-v1-jdl-dn-miceprotein-l-2-s-act-.json.gz,sha256=MBOWtKQsgUsaFQON38vPXIWQUBIxdH0NwqUAuEsv0N8,328 +sklearn/datasets/tests/data/openml/id_40966/api-v1-jdq-40966.json.gz,sha256=Pe6DmH__qOwg4js8q8ANQr63pGmva9gDkJmYwWh_pjQ,934 +sklearn/datasets/tests/data/openml/id_40966/data-v1-dl-17928620.arff.gz,sha256=HF_ZP_7H3rY6lA_WmFNN1-u32zSfwYOTAEHL8X5g4sw,6471 +sklearn/datasets/tests/data/openml/id_42074/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/datasets/tests/data/openml/id_42074/__pycache__/__init__.cpython-310.pyc,, +sklearn/datasets/tests/data/openml/id_42074/api-v1-jd-42074.json.gz,sha256=9EOzrdc3XKkuzpKWuESaB4AwXTtSEMhJlL3qs2Jx1io,584 +sklearn/datasets/tests/data/openml/id_42074/api-v1-jdf-42074.json.gz,sha256=OLdOfwKmH_Vbz6xNhxA9W__EP-uwwBnZqqFi-PdpMGg,272 +sklearn/datasets/tests/data/openml/id_42074/api-v1-jdq-42074.json.gz,sha256=h0KnS9W8EgrNkYbIqHN8tCDtmwCfreALJOfOUhd5fyw,722 +sklearn/datasets/tests/data/openml/id_42074/data-v1-dl-21552912.arff.gz,sha256=9iPnd8CjaubIL64Qp8IIjLODKY6iRFlb-NyVRJyb5MQ,2326 +sklearn/datasets/tests/data/openml/id_42585/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/datasets/tests/data/openml/id_42585/__pycache__/__init__.cpython-310.pyc,, +sklearn/datasets/tests/data/openml/id_42585/api-v1-jd-42585.json.gz,sha256=fMvxOOBmOJX5z1ERNrxjlcFT9iOK8urLajZ-huFdGnE,1492 +sklearn/datasets/tests/data/openml/id_42585/api-v1-jdf-42585.json.gz,sha256=CYUEWkVMgYa05pDr77bOoe98EyksmNUKvaRwoP861CU,312 +sklearn/datasets/tests/data/openml/id_42585/api-v1-jdq-42585.json.gz,sha256=Nzbn_retMMaGdcLE5IqfsmLoAwjJCDsQDd0DOdofwoI,348 +sklearn/datasets/tests/data/openml/id_42585/data-v1-dl-21854866.arff.gz,sha256=yNAMZpBXap7Dnhy3cFThMpa-D966sPs1pkoOhie25vM,4519 +sklearn/datasets/tests/data/openml/id_561/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/datasets/tests/data/openml/id_561/__pycache__/__init__.cpython-310.pyc,, +sklearn/datasets/tests/data/openml/id_561/api-v1-jd-561.json.gz,sha256=odOP3WAbZ7ucbRYVL1Pd8Wagz8_vT6hkOOiZv-RJImw,1798 +sklearn/datasets/tests/data/openml/id_561/api-v1-jdf-561.json.gz,sha256=QHQk-3nMMLjp_5CQCzvykkSsfzeX8ni1vmAoQ_lZtO4,425 +sklearn/datasets/tests/data/openml/id_561/api-v1-jdl-dn-cpu-l-2-dv-1.json.gz,sha256=BwOwriC5_3UIfcYBZA7ljxwq1naIWOohokUVHam6jkw,301 +sklearn/datasets/tests/data/openml/id_561/api-v1-jdl-dn-cpu-l-2-s-act-.json.gz,sha256=cNRZath5VHhjEJ2oZ1wreJ0H32a1Jtfry86WFsTJuUw,347 +sklearn/datasets/tests/data/openml/id_561/api-v1-jdq-561.json.gz,sha256=h0Oy2T0sYqgvtH4fvAArl-Ja3Ptb8fyya1itC-0VvUg,1074 +sklearn/datasets/tests/data/openml/id_561/data-v1-dl-52739.arff.gz,sha256=6WFCteAN_sJhewwi1xkrNAriwo7D_8OolMW-dGuXClk,3303 +sklearn/datasets/tests/data/openml/id_61/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/datasets/tests/data/openml/id_61/__pycache__/__init__.cpython-310.pyc,, +sklearn/datasets/tests/data/openml/id_61/api-v1-jd-61.json.gz,sha256=pcfnmqQe9YCDj7n8GQYoDwdsR74XQf3dUATdtQDrV_4,898 +sklearn/datasets/tests/data/openml/id_61/api-v1-jdf-61.json.gz,sha256=M8vWrpRboElpNwqzVgTpNjyHJWOTSTOCtRGKidWThtY,268 +sklearn/datasets/tests/data/openml/id_61/api-v1-jdl-dn-iris-l-2-dv-1.json.gz,sha256=C84gquf9kDeW2W1bOjZ3twWPvF8_4Jlu6dSR5O4j0TI,293 +sklearn/datasets/tests/data/openml/id_61/api-v1-jdl-dn-iris-l-2-s-act-.json.gz,sha256=qfS5MXmX32PtjSuwc6OQY0TA4L4Bf9OE6uw2zti5S64,330 +sklearn/datasets/tests/data/openml/id_61/api-v1-jdq-61.json.gz,sha256=QkzUfBKlHHu42BafrID7VgHxUr14RoskHUsRW_fSLyA,1121 +sklearn/datasets/tests/data/openml/id_61/data-v1-dl-61.arff.gz,sha256=r-RzaSRgZjiYTlcyNRkQJdQZxUXTHciHTJa3L17F23M,2342 +sklearn/datasets/tests/data/openml/id_62/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/datasets/tests/data/openml/id_62/__pycache__/__init__.cpython-310.pyc,, +sklearn/datasets/tests/data/openml/id_62/api-v1-jd-62.json.gz,sha256=fvNVGtR9SAI8Wh8c8HcEeppLlVRLuR1Khgl_i1dPjQc,656 +sklearn/datasets/tests/data/openml/id_62/api-v1-jdf-62.json.gz,sha256=SJsXcSbLfzNcsiBwkjO5RtOgrXHTi7ptSLeRhxRuWFo,817 +sklearn/datasets/tests/data/openml/id_62/api-v1-jdq-62.json.gz,sha256=J4pSpS1WnwfRTGp4d7EEdix32qxCn7H9mBegN41uxjQ,805 +sklearn/datasets/tests/data/openml/id_62/data-v1-dl-52352.arff.gz,sha256=-1gwyCES9ipADIKsHxtethwpwKfMcrpW0q7_D66KYPk,1625 +sklearn/datasets/tests/data/svmlight_classification.txt,sha256=6u8QK0PeHOxvx7fOYdPsJZTgJfS6SD58WWPYgYz4B3U,254 +sklearn/datasets/tests/data/svmlight_invalid.txt,sha256=ueCvdPekdiYpH8FAH_AW9MHiyMd9SulhrkJ8FQm3ol8,54 +sklearn/datasets/tests/data/svmlight_invalid_order.txt,sha256=xSNKVNcM7TuWkTyTZnQSTTcoBdERxUKoM2yz_gFCaHA,23 +sklearn/datasets/tests/data/svmlight_multilabel.txt,sha256=Pvs1p_nQFKLOfjLJEXNjJeOadVqVulQ_AGVkj7Js5vA,105 +sklearn/datasets/tests/test_20news.py,sha256=Hym_e4P4GkhyBIZ6JfisnCxWEwp1M1qfsfp9shxqCzE,5339 +sklearn/datasets/tests/test_arff_parser.py,sha256=d-kOepobTzFS1w4U23hp0NAC4t8h7d6fP2mWiim89xo,8088 +sklearn/datasets/tests/test_base.py,sha256=3aqHTrwaZW9PVSHK1jeWwW32SqMAugkwEmhbVlobnpo,11996 +sklearn/datasets/tests/test_california_housing.py,sha256=pHO5B6_RrfyPp4bwUrrwHn6VUhJSqizOe5DPw7I9uGs,1368 +sklearn/datasets/tests/test_common.py,sha256=KC0OCuZCSsjzodQXY8aVkgFLLMylkeYK-VJyUJx7S1E,4379 +sklearn/datasets/tests/test_covtype.py,sha256=bjNddYKznLuc-GICOfZD_G0wOgEDiRawc7yg0W0TurM,1756 +sklearn/datasets/tests/test_kddcup99.py,sha256=RAP_s4uVrHYtkmDapHLjjl36heImoGa42VAvU9vZPV4,2606 +sklearn/datasets/tests/test_lfw.py,sha256=ymd_LfoU1WZKDOXgsQEjdMUpfgXIjIxV3lMb47KKujs,8229 +sklearn/datasets/tests/test_olivetti_faces.py,sha256=d2r43YseviKoA9OyX6JvDyXvY8lFRfV__j5hippkYY0,919 +sklearn/datasets/tests/test_openml.py,sha256=6XejfdYalo507PbvwdeinI1ubAOAr_QR-BBpv07ahpY,55329 +sklearn/datasets/tests/test_rcv1.py,sha256=_MI_VuGKrZIIV-WMVxOEKMh94DqzhCrxV7l1E3NGkNM,2343 +sklearn/datasets/tests/test_samples_generator.py,sha256=Nrov2s39olFK7S4fpmCwbdgdxrphJnkXCr3o6lQjVb4,23704 +sklearn/datasets/tests/test_svmlight_format.py,sha256=zvfWSYxjakXnTX6TfokviHxyaZcmjzglCHV1QnkyHAg,20269 +sklearn/decomposition/__init__.py,sha256=hDGJOjAgeeYsMsO5o8PSGLAYmfiS6WRjIGO8OdvSxN4,1296 +sklearn/decomposition/__pycache__/__init__.cpython-310.pyc,, +sklearn/decomposition/__pycache__/_base.cpython-310.pyc,, +sklearn/decomposition/__pycache__/_dict_learning.cpython-310.pyc,, +sklearn/decomposition/__pycache__/_factor_analysis.cpython-310.pyc,, +sklearn/decomposition/__pycache__/_fastica.cpython-310.pyc,, +sklearn/decomposition/__pycache__/_incremental_pca.cpython-310.pyc,, +sklearn/decomposition/__pycache__/_kernel_pca.cpython-310.pyc,, +sklearn/decomposition/__pycache__/_lda.cpython-310.pyc,, +sklearn/decomposition/__pycache__/_nmf.cpython-310.pyc,, +sklearn/decomposition/__pycache__/_pca.cpython-310.pyc,, +sklearn/decomposition/__pycache__/_sparse_pca.cpython-310.pyc,, +sklearn/decomposition/__pycache__/_truncated_svd.cpython-310.pyc,, +sklearn/decomposition/_base.py,sha256=ffm1H9Yi3QG8z8pdM3GH4KHx0dUS_BPmqv1UMdvHiWo,6545 +sklearn/decomposition/_cdnmf_fast.cpython-310-x86_64-linux-gnu.so,sha256=E2g9knNUDZhCsUYdgJINy6ZdOgJ3htYOYzXK_SaZ0r4,245625 +sklearn/decomposition/_dict_learning.py,sha256=KHSSXRymhMbdCbFZYN5ZfuMReiDUW7h5n5_ikEOPfh0,76447 +sklearn/decomposition/_factor_analysis.py,sha256=dfC3QYDEyATPFRI8D_2SyhpSG1VJphX7l749PcT_8IU,15301 +sklearn/decomposition/_fastica.py,sha256=tL6X8rpkoH-taeWuHXHJEF0NAiJ3k_IwZaVPW0dv0v8,26439 +sklearn/decomposition/_incremental_pca.py,sha256=-xyUuHdG-0hE4ytUIc8dUXA-SzN0KMMU5ukE_Q1UsEo,15895 +sklearn/decomposition/_kernel_pca.py,sha256=XZmi51u5a314Ucx4leic0CJ-kmXzWCDi3ifZkzEtWqA,21922 +sklearn/decomposition/_lda.py,sha256=PxzDM2sKtBY5F5-6glXWj_XQwhu48nAE5gSzxvkwFcE,33064 +sklearn/decomposition/_nmf.py,sha256=cL5sFfYvdv4QrOyw2T0R8a5yf3l3Oxnw6aufG5iuOL4,82483 +sklearn/decomposition/_online_lda_fast.cpython-310-x86_64-linux-gnu.so,sha256=mV1lYjA0IxVAB84t5CAlHCcl3mS3mNneDyOwz1uW0i4,307137 +sklearn/decomposition/_pca.py,sha256=KV8m7CIfxJe6pKuV05b9srz0MKAdj35CnoqgJtDJalY,28402 +sklearn/decomposition/_sparse_pca.py,sha256=1QEwZkZ61wRWDnWmh5BBsI7NkubbYNOfpFyQtOGWlqA,18014 +sklearn/decomposition/_truncated_svd.py,sha256=WbIoXcppX5_MRfNH-XaNpnOR0hiQbS9Zn5Zx3pGHLjU,11489 +sklearn/decomposition/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/decomposition/tests/__pycache__/__init__.cpython-310.pyc,, +sklearn/decomposition/tests/__pycache__/test_dict_learning.cpython-310.pyc,, +sklearn/decomposition/tests/__pycache__/test_factor_analysis.cpython-310.pyc,, +sklearn/decomposition/tests/__pycache__/test_fastica.cpython-310.pyc,, +sklearn/decomposition/tests/__pycache__/test_incremental_pca.cpython-310.pyc,, +sklearn/decomposition/tests/__pycache__/test_kernel_pca.cpython-310.pyc,, +sklearn/decomposition/tests/__pycache__/test_nmf.cpython-310.pyc,, +sklearn/decomposition/tests/__pycache__/test_online_lda.cpython-310.pyc,, +sklearn/decomposition/tests/__pycache__/test_pca.cpython-310.pyc,, +sklearn/decomposition/tests/__pycache__/test_sparse_pca.cpython-310.pyc,, +sklearn/decomposition/tests/__pycache__/test_truncated_svd.cpython-310.pyc,, +sklearn/decomposition/tests/test_dict_learning.py,sha256=2DSscxDCuzl4aTJHIOyxwXIzf_-UFwNpS-N_eXhx420,30432 +sklearn/decomposition/tests/test_factor_analysis.py,sha256=vRdG7UgNwXVith_j7hi7NN-i7zEuDDVrmvrI2rWMDig,4172 +sklearn/decomposition/tests/test_fastica.py,sha256=rQjBsHH1Byt0JSHVLoC_iexG_RHZCS3vWaE6A9dvdfk,15503 +sklearn/decomposition/tests/test_incremental_pca.py,sha256=y8eL0TuPq3pozAlSnUa_IO_35ACQlUgqFceVKKLnQ1Q,15317 +sklearn/decomposition/tests/test_kernel_pca.py,sha256=pifqNdYRI8wYcGzn9aiidQDkauBhzy86vBCElzgTtl4,20772 +sklearn/decomposition/tests/test_nmf.py,sha256=VjLVciOIuLtcLRocB2Nd1GyMpgcaceFurTNEe00Jc_4,34178 +sklearn/decomposition/tests/test_online_lda.py,sha256=WOTsRNAdCr0yy2IjFa_XH7QQ0nTRQKMdpcgEb7Ru8tA,15825 +sklearn/decomposition/tests/test_pca.py,sha256=mUMr5Dss5UhpT-U1sFC1Cl9iH-D3g2G4gO4up_UBduA,35081 +sklearn/decomposition/tests/test_sparse_pca.py,sha256=ktJ8to_V8qYGOOrEt012xmVNWNsKLccjo252xwUdd6w,12866 +sklearn/decomposition/tests/test_truncated_svd.py,sha256=GEh38HYV9jjcbP0FCXzjTo4szDla6NqgLXgIxgW1yvA,7168 +sklearn/discriminant_analysis.py,sha256=GWA89yRds7Ry3ONy-1idzG4l39nsy3GnOgaC7sVTCK4,37501 +sklearn/dummy.py,sha256=xpThXdClt0lf-KFPdVnb2QAHSOAlTz35P2O3oNxyxDM,23817 +sklearn/ensemble/__init__.py,sha256=RSvD9tEa46dcyJkKZqTD2CZS1B7KAD2raG82TRMCuD4,1339 +sklearn/ensemble/__pycache__/__init__.cpython-310.pyc,, +sklearn/ensemble/__pycache__/_bagging.cpython-310.pyc,, +sklearn/ensemble/__pycache__/_base.cpython-310.pyc,, +sklearn/ensemble/__pycache__/_forest.cpython-310.pyc,, +sklearn/ensemble/__pycache__/_gb.cpython-310.pyc,, +sklearn/ensemble/__pycache__/_iforest.cpython-310.pyc,, +sklearn/ensemble/__pycache__/_stacking.cpython-310.pyc,, +sklearn/ensemble/__pycache__/_voting.cpython-310.pyc,, +sklearn/ensemble/__pycache__/_weight_boosting.cpython-310.pyc,, +sklearn/ensemble/_bagging.py,sha256=qXIILoAWZQJHt0C3GOdGwdC0EQ_K-db6BZLZDK6faSg,43259 +sklearn/ensemble/_base.py,sha256=qc_d7GmyO8EY9DBw9sazg5j1BtvfisfwDtThY3tZ4ow,10069 +sklearn/ensemble/_forest.py,sha256=MhVW5h7tnQMJpUrv2yKbLCIPStU1z3L95MdduZ9aroo,114121 +sklearn/ensemble/_gb.py,sha256=ealNbODotELREJAk15F403zjLwUuulaP1hADiL5Mmcw,86549 +sklearn/ensemble/_gradient_boosting.cpython-310-x86_64-linux-gnu.so,sha256=eBmh15i2ccMICZraHan_NJgJWteJ9WAScN0mrbRovMA,253745 +sklearn/ensemble/_hist_gradient_boosting/__init__.py,sha256=eQB-q0KuYskMBmetF1cg6AQnakxh9VaQsYfuALI2HNc,166 +sklearn/ensemble/_hist_gradient_boosting/__pycache__/__init__.cpython-310.pyc,, +sklearn/ensemble/_hist_gradient_boosting/__pycache__/binning.cpython-310.pyc,, +sklearn/ensemble/_hist_gradient_boosting/__pycache__/gradient_boosting.cpython-310.pyc,, +sklearn/ensemble/_hist_gradient_boosting/__pycache__/grower.cpython-310.pyc,, +sklearn/ensemble/_hist_gradient_boosting/__pycache__/predictor.cpython-310.pyc,, +sklearn/ensemble/_hist_gradient_boosting/_binning.cpython-310-x86_64-linux-gnu.so,sha256=yiY9l38txoZld5nU_ZDlo812Ofvx8pCsVZxbV7cCcP8,220953 +sklearn/ensemble/_hist_gradient_boosting/_bitset.cpython-310-x86_64-linux-gnu.so,sha256=--g_QAaOBxxrj4AUAeTOJbhcxnlE6QuzYGxaTSiq-Nk,220841 +sklearn/ensemble/_hist_gradient_boosting/_bitset.pxd,sha256=nzEGYyR63gAQmXbMoNwqu_erw51e3TveA9rTcfNCfuM,692 +sklearn/ensemble/_hist_gradient_boosting/_gradient_boosting.cpython-310-x86_64-linux-gnu.so,sha256=B2BeViDAb7pGPMkHFwec8CSvwQeLLgImlyFqLcjaUBE,229137 +sklearn/ensemble/_hist_gradient_boosting/_predictor.cpython-310-x86_64-linux-gnu.so,sha256=JZzVk9WBKZOC1ZKESWwOOMioHFcpU9rqxaWdMFJMFsA,249681 +sklearn/ensemble/_hist_gradient_boosting/binning.py,sha256=J1RrSjj3cDj7YfYBxDYtK_KI5AJlb_gcqgW0Szw8Gls,13385 +sklearn/ensemble/_hist_gradient_boosting/common.cpython-310-x86_64-linux-gnu.so,sha256=HvhZ6F8lDaigcvIRETe6CnPZd-Ossj2P3RhnI0bpbYk,146481 +sklearn/ensemble/_hist_gradient_boosting/common.pxd,sha256=x93vLeNO7RyWRLAG7LLXw8p2nxyfIb1CfOrsKkmlHqU,1295 +sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py,sha256=z4FtBxTvGg3xS34Xy22kBXD_m3tM5CuDJMJCxUgUsmo,92936 +sklearn/ensemble/_hist_gradient_boosting/grower.py,sha256=OWpVug6qGP51eJxXtB52cAHYK9d20XkcDtKihgYTTmY,31643 +sklearn/ensemble/_hist_gradient_boosting/histogram.cpython-310-x86_64-linux-gnu.so,sha256=fbSXsPQEjxtAK24yGPSGRaqk8R7q5KcLUCfm7ZtPPcg,327577 +sklearn/ensemble/_hist_gradient_boosting/predictor.py,sha256=J0Jo3GMj9oP3Qh9tpFF4aAtOnANGjgIlebOnFaVogLA,4971 +sklearn/ensemble/_hist_gradient_boosting/splitting.cpython-310-x86_64-linux-gnu.so,sha256=ic91kMoqWcsntsyuv1SiS6h01GUWdBgpIk1Jz-HYRC0,368601 +sklearn/ensemble/_hist_gradient_boosting/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/ensemble/_hist_gradient_boosting/tests/__pycache__/__init__.cpython-310.pyc,, +sklearn/ensemble/_hist_gradient_boosting/tests/__pycache__/test_binning.cpython-310.pyc,, +sklearn/ensemble/_hist_gradient_boosting/tests/__pycache__/test_bitset.cpython-310.pyc,, +sklearn/ensemble/_hist_gradient_boosting/tests/__pycache__/test_compare_lightgbm.cpython-310.pyc,, +sklearn/ensemble/_hist_gradient_boosting/tests/__pycache__/test_gradient_boosting.cpython-310.pyc,, +sklearn/ensemble/_hist_gradient_boosting/tests/__pycache__/test_grower.cpython-310.pyc,, +sklearn/ensemble/_hist_gradient_boosting/tests/__pycache__/test_histogram.cpython-310.pyc,, +sklearn/ensemble/_hist_gradient_boosting/tests/__pycache__/test_monotonic_contraints.cpython-310.pyc,, +sklearn/ensemble/_hist_gradient_boosting/tests/__pycache__/test_predictor.cpython-310.pyc,, +sklearn/ensemble/_hist_gradient_boosting/tests/__pycache__/test_splitting.cpython-310.pyc,, +sklearn/ensemble/_hist_gradient_boosting/tests/__pycache__/test_warm_start.cpython-310.pyc,, +sklearn/ensemble/_hist_gradient_boosting/tests/test_binning.py,sha256=aNXHw7u7IRAdEfHO2TWdjAmlj9y_SdhJir-w0yQ-fkc,16252 +sklearn/ensemble/_hist_gradient_boosting/tests/test_bitset.py,sha256=5QHny5G3p9tyExBsdsUVV2vFKgPI-vYDt-zvLpMBHXQ,2100 +sklearn/ensemble/_hist_gradient_boosting/tests/test_compare_lightgbm.py,sha256=cdWR8t7G8T4py8jKkF-nKj7st5vbf7ZYEGW4PqbuJpQ,10112 +sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py,sha256=An1lUfNtW_wOdNI2JAck6vNA_rwcN87juB17UQtUerM,60892 +sklearn/ensemble/_hist_gradient_boosting/tests/test_grower.py,sha256=mDda3Xp-vF2Kgqdz3bj5UUtC4jUZR--dCesLwmDI50c,23152 +sklearn/ensemble/_hist_gradient_boosting/tests/test_histogram.py,sha256=PBoacgv-6rOI5lTpzCyaafC9eDvyA6tb94RnDw_wLhs,8681 +sklearn/ensemble/_hist_gradient_boosting/tests/test_monotonic_contraints.py,sha256=nL5zxXNASEW6pgDuif2SNoaGsV4O5llKmBSt0-8YQCM,16257 +sklearn/ensemble/_hist_gradient_boosting/tests/test_predictor.py,sha256=wq5vXIMwh7Fr3wDeHGO2F-oNNXEH_hUdyOyS7SIGXpE,6345 +sklearn/ensemble/_hist_gradient_boosting/tests/test_splitting.py,sha256=nkX5rAlTeO6tPR4_K4Gc9bvViPu1HUboA7-vRdiTETo,38639 +sklearn/ensemble/_hist_gradient_boosting/tests/test_warm_start.py,sha256=3Q_3ZhKf94uvmADlNMj0Vpyp7gqjDd1czBzFW8pUuAQ,7933 +sklearn/ensemble/_hist_gradient_boosting/utils.cpython-310-x86_64-linux-gnu.so,sha256=iVTRDHU7XGxC0IFJe6deOk57Y202CNWJvsrIWQMxH7g,249745 +sklearn/ensemble/_iforest.py,sha256=aL_W3uV-8E9Bp0S5HS7jNCQ4N1ABD8pCRtSDb4CWJeU,20427 +sklearn/ensemble/_stacking.py,sha256=u0v3-k2GXMXrdB0fV3UfhJ28CAyUuOyYinnmK0BUgBI,39027 +sklearn/ensemble/_voting.py,sha256=vy6WPhUfaz9aChF0W2bdebHN1wBrD98i3UIEpPV8Fng,23331 +sklearn/ensemble/_weight_boosting.py,sha256=ggLOV-Vr_KND_lYJiD_9EhoyBJT-8LKPzjhipCDlkyE,45369 +sklearn/ensemble/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/ensemble/tests/__pycache__/__init__.cpython-310.pyc,, +sklearn/ensemble/tests/__pycache__/test_bagging.cpython-310.pyc,, +sklearn/ensemble/tests/__pycache__/test_base.cpython-310.pyc,, +sklearn/ensemble/tests/__pycache__/test_common.cpython-310.pyc,, +sklearn/ensemble/tests/__pycache__/test_forest.cpython-310.pyc,, +sklearn/ensemble/tests/__pycache__/test_gradient_boosting.cpython-310.pyc,, +sklearn/ensemble/tests/__pycache__/test_iforest.cpython-310.pyc,, +sklearn/ensemble/tests/__pycache__/test_stacking.cpython-310.pyc,, +sklearn/ensemble/tests/__pycache__/test_voting.cpython-310.pyc,, +sklearn/ensemble/tests/__pycache__/test_weight_boosting.cpython-310.pyc,, +sklearn/ensemble/tests/test_bagging.py,sha256=IK_ta2LyqKQVsA4VSNtYYTSo5-P9UIEKQOu3hcWdSOw,30204 +sklearn/ensemble/tests/test_base.py,sha256=7E-TUzBWj17l1AFOx_iXSFeVnpk-ySFsQxc--_WkfrQ,3637 +sklearn/ensemble/tests/test_common.py,sha256=xgl3R6ry0FhN-cbhYcuPKzPpPawqsizBDgdDzeB5Fog,9150 +sklearn/ensemble/tests/test_forest.py,sha256=d_cWIBIG_AVwvDdxcD4ezqM_BqROdqba31eLtbhC0_o,62547 +sklearn/ensemble/tests/test_gradient_boosting.py,sha256=VQ03n0WqmdAp38a9VtQXLw5xrQyui50aBv1LOBBI-vc,58784 +sklearn/ensemble/tests/test_iforest.py,sha256=d3St6sjEGD5d2OmlBZcMnMwXRWCWNrzvmqW9_-XU9aU,12484 +sklearn/ensemble/tests/test_stacking.py,sha256=fpbB1ap5QUddE6KkU3XHDnSZrr3T3hPYmYENBVa1dsg,29896 +sklearn/ensemble/tests/test_voting.py,sha256=VPnVqIr3-PXRS1pFyrBX1dGVsY8vH81uIb92AmUfuLc,24015 +sklearn/ensemble/tests/test_weight_boosting.py,sha256=YmLdvEYIEZML19TnRL7PVJX5PIM4bqdoViuOlZ6PwGY,25403 +sklearn/exceptions.py,sha256=h1GgvgS6iQrKSPYhJHP-XL4ucrWw3VWybIH-PBx_qlQ,6117 +sklearn/experimental/__init__.py,sha256=pWa_UcYBSxmQSZSajN60f97qpKLnE_2etPGLxv1aGsM,252 +sklearn/experimental/__pycache__/__init__.cpython-310.pyc,, +sklearn/experimental/__pycache__/enable_halving_search_cv.cpython-310.pyc,, +sklearn/experimental/__pycache__/enable_hist_gradient_boosting.cpython-310.pyc,, +sklearn/experimental/__pycache__/enable_iterative_imputer.cpython-310.pyc,, +sklearn/experimental/enable_halving_search_cv.py,sha256=BkTrG-7xI1EBAamq4bLsSn_vwGyALDGRPxn3p0PcqHY,1210 +sklearn/experimental/enable_hist_gradient_boosting.py,sha256=bBYxZhuti1zFRJpSrkNSgbpSFd4E4gr7z-WKEA9rOQo,746 +sklearn/experimental/enable_iterative_imputer.py,sha256=4DpNhRtWoYgDHXVLsBL30zqAwupL5HRKz40TJWwv4qo,688 +sklearn/experimental/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/experimental/tests/__pycache__/__init__.cpython-310.pyc,, +sklearn/experimental/tests/__pycache__/test_enable_hist_gradient_boosting.cpython-310.pyc,, +sklearn/experimental/tests/__pycache__/test_enable_iterative_imputer.cpython-310.pyc,, +sklearn/experimental/tests/__pycache__/test_enable_successive_halving.cpython-310.pyc,, +sklearn/experimental/tests/test_enable_hist_gradient_boosting.py,sha256=yK6u6Rw-18L3BvCXFuAoiYu0ejaRs2jo0U4trj8txPk,666 +sklearn/experimental/tests/test_enable_iterative_imputer.py,sha256=DhjyTu1pyNtknhA2seGOUH-Ygq07G6PFE-Y6gxf-1Fs,1683 +sklearn/experimental/tests/test_enable_successive_halving.py,sha256=uMIi0nVBvAOVGwx0hioe7G7YtsKB_z2ACpHCW2kpFMc,1890 +sklearn/externals/__init__.py,sha256=jo7XxwlsquXvHghwURnScmXn3XraDerjG1fNR_e11-U,42 +sklearn/externals/__pycache__/__init__.cpython-310.pyc,, +sklearn/externals/__pycache__/_arff.cpython-310.pyc,, +sklearn/externals/__pycache__/conftest.cpython-310.pyc,, +sklearn/externals/_arff.py,sha256=YXR8xgF1IxyugQV70YHNjmza2yuz86zhVM1i6AI-RSA,38341 +sklearn/externals/_packaging/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/externals/_packaging/__pycache__/__init__.cpython-310.pyc,, +sklearn/externals/_packaging/__pycache__/_structures.cpython-310.pyc,, +sklearn/externals/_packaging/__pycache__/version.cpython-310.pyc,, +sklearn/externals/_packaging/_structures.py,sha256=Ofe3RryZqacr5auj4s7MsEylGigfeyf8sagFvK-rPv0,2922 +sklearn/externals/_packaging/version.py,sha256=IDbp4Q6S9OZ3mP57YCDerh4Xm0s6AUqSi6CbFJ3eQyI,16134 +sklearn/externals/_scipy/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/externals/_scipy/__pycache__/__init__.cpython-310.pyc,, +sklearn/externals/_scipy/sparse/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/externals/_scipy/sparse/__pycache__/__init__.cpython-310.pyc,, +sklearn/externals/_scipy/sparse/csgraph/__init__.py,sha256=GMAcZXBWt9Dp0QEOeCsQglt8CWB6_stqr7Wf_LfH0tE,34 +sklearn/externals/_scipy/sparse/csgraph/__pycache__/__init__.cpython-310.pyc,, +sklearn/externals/_scipy/sparse/csgraph/__pycache__/_laplacian.cpython-310.pyc,, +sklearn/externals/_scipy/sparse/csgraph/_laplacian.py,sha256=-CiehMT6O8Fk0Yxo4K4BVXrkRTymisAsjv8ck3XSgfw,18150 +sklearn/externals/conftest.py,sha256=NDEaeaJzvW8UZUaFivG1pF9FnrwPR2CfVajgJqISkZY,301 +sklearn/feature_extraction/__init__.py,sha256=3fQtwgSfy-w5zrveCeVDj3CDmXll-ZVFTqPvNsGK-Ns,439 +sklearn/feature_extraction/__pycache__/__init__.cpython-310.pyc,, +sklearn/feature_extraction/__pycache__/_dict_vectorizer.cpython-310.pyc,, +sklearn/feature_extraction/__pycache__/_hash.cpython-310.pyc,, +sklearn/feature_extraction/__pycache__/_stop_words.cpython-310.pyc,, +sklearn/feature_extraction/__pycache__/image.cpython-310.pyc,, +sklearn/feature_extraction/__pycache__/text.cpython-310.pyc,, +sklearn/feature_extraction/_dict_vectorizer.py,sha256=YsI6v7I8x-u1-RvhbMHmzPSMSwuOe033yFi7DHzOziE,15718 +sklearn/feature_extraction/_hash.py,sha256=PCcvcBVR4Q28VmByIpiJBZkNs3tM-r7-r64oqKc__3s,7382 +sklearn/feature_extraction/_hashing_fast.cpython-310-x86_64-linux-gnu.so,sha256=zNz_tyaGipADzrYVFBYQ_DUCieWxc-iFpVXjXQsI92E,110289 +sklearn/feature_extraction/_stop_words.py,sha256=ErqFJABA33Wr92H4VSH7ZqrYJ2CbTioOMMASuoB7hrs,5645 +sklearn/feature_extraction/image.py,sha256=jRWj-655lyLhpEgGfG6DeKn3gpmpKMnS1tRmW-MZ5YE,23024 +sklearn/feature_extraction/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/feature_extraction/tests/__pycache__/__init__.cpython-310.pyc,, +sklearn/feature_extraction/tests/__pycache__/test_dict_vectorizer.cpython-310.pyc,, +sklearn/feature_extraction/tests/__pycache__/test_feature_hasher.cpython-310.pyc,, +sklearn/feature_extraction/tests/__pycache__/test_image.cpython-310.pyc,, +sklearn/feature_extraction/tests/__pycache__/test_text.cpython-310.pyc,, +sklearn/feature_extraction/tests/test_dict_vectorizer.py,sha256=FqXV_QEoKyHqgUGouZb3UWB9C-nTfS_wNOuo25o78a0,8272 +sklearn/feature_extraction/tests/test_feature_hasher.py,sha256=WT6h7r7k7gwS3-CvxO4F4ssw4jXSfptTGQKJL9i4D58,5046 +sklearn/feature_extraction/tests/test_image.py,sha256=tfkHiWMMuAeBViFDy3XK-XylnteOYk_cPtlJ1GBmxpk,12154 +sklearn/feature_extraction/tests/test_text.py,sha256=kyBV6n2o-7cTfd1eB011MxOvQucyOmMUOgI1gTLW5xU,53098 +sklearn/feature_extraction/text.py,sha256=wwLJa5ZDZktGwkFN0Ll99BXqX9wfNEeEIgJ91Hv-n_k,78015 +sklearn/feature_selection/__init__.py,sha256=Y3yLE0hnG6-DSRjVSpaFbJhm0SwXfrkkrGSnMu_l4sA,1111 +sklearn/feature_selection/__pycache__/__init__.cpython-310.pyc,, +sklearn/feature_selection/__pycache__/_base.cpython-310.pyc,, +sklearn/feature_selection/__pycache__/_from_model.cpython-310.pyc,, +sklearn/feature_selection/__pycache__/_mutual_info.cpython-310.pyc,, +sklearn/feature_selection/__pycache__/_rfe.cpython-310.pyc,, +sklearn/feature_selection/__pycache__/_sequential.cpython-310.pyc,, +sklearn/feature_selection/__pycache__/_univariate_selection.cpython-310.pyc,, +sklearn/feature_selection/__pycache__/_variance_threshold.cpython-310.pyc,, +sklearn/feature_selection/_base.py,sha256=r-ccLUsyjkUtX0uV5p1fOIxKLKI2LRKYMfiRnxkOFPg,9398 +sklearn/feature_selection/_from_model.py,sha256=1eKI8Pp2jTOg6PSvR646jll8EoIGVxnfvUBKFYFRrBo,18920 +sklearn/feature_selection/_mutual_info.py,sha256=B3d9U6rzWilnQZwbmqFiivV3jKTxYF33-3Q9tlxdJ1o,18323 +sklearn/feature_selection/_rfe.py,sha256=Rz0C7SBxBZL5FPmjZNO5CAGzvTpjqRX-Pw7cfOLFRfI,28067 +sklearn/feature_selection/_sequential.py,sha256=tEYDrx1EJ4dbDfP8mPq9iMqkCZJ7GJWBwlMNkzceDNQ,11461 +sklearn/feature_selection/_univariate_selection.py,sha256=D_9Wgi_oUS-P7u96yE8dGZJersILOkrngPDrdNl1c9I,40350 +sklearn/feature_selection/_variance_threshold.py,sha256=WP4plcHw5VoDPc8DXMnHCOgP_sXn8RVHK36KQWkUh2A,4467 +sklearn/feature_selection/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/feature_selection/tests/__pycache__/__init__.cpython-310.pyc,, +sklearn/feature_selection/tests/__pycache__/test_base.cpython-310.pyc,, +sklearn/feature_selection/tests/__pycache__/test_chi2.cpython-310.pyc,, +sklearn/feature_selection/tests/__pycache__/test_feature_select.cpython-310.pyc,, +sklearn/feature_selection/tests/__pycache__/test_from_model.cpython-310.pyc,, +sklearn/feature_selection/tests/__pycache__/test_mutual_info.cpython-310.pyc,, +sklearn/feature_selection/tests/__pycache__/test_rfe.cpython-310.pyc,, +sklearn/feature_selection/tests/__pycache__/test_sequential.cpython-310.pyc,, +sklearn/feature_selection/tests/__pycache__/test_variance_threshold.cpython-310.pyc,, +sklearn/feature_selection/tests/test_base.py,sha256=jerTDsOutG3KjUUuBmGvt7GKKrTckCFYt1_49raVM1c,4781 +sklearn/feature_selection/tests/test_chi2.py,sha256=c6L3cs9DYulMNUTjnZJo7VURucjhUHLYzG2EaRE9N1c,3139 +sklearn/feature_selection/tests/test_feature_select.py,sha256=eve6wxRgLiNJCbAY1hA-zULouSMg4PciPDCU4uKUt08,32506 +sklearn/feature_selection/tests/test_from_model.py,sha256=nqWJPXgTEG6rlls6mpMN1wNKuFQrFs4ULd3-TfB_4BA,23051 +sklearn/feature_selection/tests/test_mutual_info.py,sha256=OK0btiS0OVknVErUhOMWaIiz8qvZlrG2KmqCZnl09wg,9182 +sklearn/feature_selection/tests/test_rfe.py,sha256=jNZdzozS_FfP9qZOjSNl01cq3D5WIXW5FDyubhXYP0Y,20881 +sklearn/feature_selection/tests/test_sequential.py,sha256=LcjXZDFL5WOgzvwgIWkQDC6EWXoA5LYc-VeWYy2SblM,10592 +sklearn/feature_selection/tests/test_variance_threshold.py,sha256=tKaSBkRgVBzo3xC0lT6nLNNzKW4M-5t_sAFJgUmr--g,2640 +sklearn/gaussian_process/__init__.py,sha256=FjnQR6y5UQeaO_EURpIMUHhAHRCvhKYke-i5NUcQipE,504 +sklearn/gaussian_process/__pycache__/__init__.cpython-310.pyc,, +sklearn/gaussian_process/__pycache__/_gpc.cpython-310.pyc,, +sklearn/gaussian_process/__pycache__/_gpr.cpython-310.pyc,, +sklearn/gaussian_process/__pycache__/kernels.cpython-310.pyc,, +sklearn/gaussian_process/_gpc.py,sha256=5sKWdevP-qiItuMkFdMNUcxiAr8eQ8al0cfraSYWLYk,36524 +sklearn/gaussian_process/_gpr.py,sha256=ExqrXEWWLocBB4Tb4FYLJ6eedPNtcYQDmjlb1tK8bcI,28140 +sklearn/gaussian_process/kernels.py,sha256=KOkGjxDi-tyuXHNnBWS45S9g_05IEGfP-q25wRhb_UE,85400 +sklearn/gaussian_process/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/gaussian_process/tests/__pycache__/__init__.cpython-310.pyc,, +sklearn/gaussian_process/tests/__pycache__/_mini_sequence_kernel.cpython-310.pyc,, +sklearn/gaussian_process/tests/__pycache__/test_gpc.cpython-310.pyc,, +sklearn/gaussian_process/tests/__pycache__/test_gpr.cpython-310.pyc,, +sklearn/gaussian_process/tests/__pycache__/test_kernels.cpython-310.pyc,, +sklearn/gaussian_process/tests/_mini_sequence_kernel.py,sha256=YpD-vtJFSVdzVmJxHDmEdFGl6cOQ4J98mLpjFCFThys,1571 +sklearn/gaussian_process/tests/test_gpc.py,sha256=wEmrJy4QXzLK9yMitspUDtbo7ah9iOe7oUlwKAJhvkM,10020 +sklearn/gaussian_process/tests/test_gpr.py,sha256=rL6gsDsK0Grlspgkuf8V6ziqE4M2EPIrRwvvnrZmtIs,29775 +sklearn/gaussian_process/tests/test_kernels.py,sha256=MVsPw2Ie4bdtRiAwkuXXix_fPkCK56lqYtW5JWsmJDs,13570 +sklearn/impute/__init__.py,sha256=Ph4HQbNzVak2mVqSkq82KnXGyum-l6GmmSCPPPWLsrY,943 +sklearn/impute/__pycache__/__init__.cpython-310.pyc,, +sklearn/impute/__pycache__/_base.cpython-310.pyc,, +sklearn/impute/__pycache__/_iterative.cpython-310.pyc,, +sklearn/impute/__pycache__/_knn.cpython-310.pyc,, +sklearn/impute/_base.py,sha256=eBDVk6ojF4dBVKEn4OybjpaN72iSPGGlfo2a8tkIEiw,40012 +sklearn/impute/_iterative.py,sha256=2oxREIeBvtuGNGUd89dUv65ZGt2b3naVOGB0IiKC8bs,35716 +sklearn/impute/_knn.py,sha256=d4mbTlYwQtpuSzTX8PyDsoNbU5LzjtSHalttCLvm8xw,14662 +sklearn/impute/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/impute/tests/__pycache__/__init__.cpython-310.pyc,, +sklearn/impute/tests/__pycache__/test_base.cpython-310.pyc,, +sklearn/impute/tests/__pycache__/test_common.cpython-310.pyc,, +sklearn/impute/tests/__pycache__/test_impute.cpython-310.pyc,, +sklearn/impute/tests/__pycache__/test_knn.cpython-310.pyc,, +sklearn/impute/tests/test_base.py,sha256=L-RND6V8s4g40Uy65BIdQG1oEtHgOWBliBH4bUVdVQc,3367 +sklearn/impute/tests/test_common.py,sha256=fObDDBu87W8j6Rpc61GtAkNILvWe2s49Wskb7thMvSM,7610 +sklearn/impute/tests/test_impute.py,sha256=u4nZ8I6kP0oXoySNFsBRUAjLXqECkTnP_5Cg2dO5snU,59674 +sklearn/impute/tests/test_knn.py,sha256=kPLvYHuZlY0BgUTgf_bsenI0vkdtNNiF4vC7526QQXw,16638 +sklearn/inspection/__init__.py,sha256=3z35-RH859bsJGG-xoyx4ug0RAHl4JzipPJYRR29vzY,452 +sklearn/inspection/__pycache__/__init__.cpython-310.pyc,, +sklearn/inspection/__pycache__/_partial_dependence.cpython-310.pyc,, +sklearn/inspection/__pycache__/_pd_utils.cpython-310.pyc,, +sklearn/inspection/__pycache__/_permutation_importance.cpython-310.pyc,, +sklearn/inspection/_partial_dependence.py,sha256=GSVLBS4jsAFaVNtgGMhvkJPfCLl9-P6wE6JoLIgI_-0,31782 +sklearn/inspection/_pd_utils.py,sha256=ABl-9L-ISk5SgQbG9LntK5PqFz-DJN2A0-yZftEzD1A,2137 +sklearn/inspection/_permutation_importance.py,sha256=Xn_9XqRA7nmjaQmMy04YXPXt9DwZgDcisXTJGayc-Lg,11501 +sklearn/inspection/_plot/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/inspection/_plot/__pycache__/__init__.cpython-310.pyc,, +sklearn/inspection/_plot/__pycache__/decision_boundary.cpython-310.pyc,, +sklearn/inspection/_plot/__pycache__/partial_dependence.cpython-310.pyc,, +sklearn/inspection/_plot/decision_boundary.py,sha256=UnZ6utsvYn32dn0mHR4YGFdjgmolIuoZudIvRfYRs0Q,15199 +sklearn/inspection/_plot/partial_dependence.py,sha256=LYPQOMrQ4XtOT9nEqZN8W6MKfcELoSovaHZBf49NsJ0,59995 +sklearn/inspection/_plot/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/inspection/_plot/tests/__pycache__/__init__.cpython-310.pyc,, +sklearn/inspection/_plot/tests/__pycache__/test_boundary_decision_display.cpython-310.pyc,, +sklearn/inspection/_plot/tests/__pycache__/test_plot_partial_dependence.cpython-310.pyc,, +sklearn/inspection/_plot/tests/test_boundary_decision_display.py,sha256=4HjTW_PMSGJ8fSD8Hoe2UOXFww4WUf9Hpgg-YKIE1e4,21278 +sklearn/inspection/_plot/tests/test_plot_partial_dependence.py,sha256=YwkCq8P24iylYexK-KQm2ZEF8zSWZ_HDNnENRwuD5-8,36426 +sklearn/inspection/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/inspection/tests/__pycache__/__init__.cpython-310.pyc,, +sklearn/inspection/tests/__pycache__/test_partial_dependence.cpython-310.pyc,, +sklearn/inspection/tests/__pycache__/test_pd_utils.cpython-310.pyc,, +sklearn/inspection/tests/__pycache__/test_permutation_importance.cpython-310.pyc,, +sklearn/inspection/tests/test_partial_dependence.py,sha256=Bou6O0F0gybQQjHKWnwUBsMwM3_t8bq06fE1ilv3Cfs,33329 +sklearn/inspection/tests/test_pd_utils.py,sha256=t-8K4YbQAbVK4pcI1P9hr8-0iEgc72x_1-868HAhLBg,1640 +sklearn/inspection/tests/test_permutation_importance.py,sha256=O6G4XbuR34O8M-AcjgNX_AJtSt6NAiuFr-2h8HemaVE,19940 +sklearn/isotonic.py,sha256=-eugGsWN64AoM1UMVYMuvLdnL45_eht-EUU2_ZdKIdc,16637 +sklearn/kernel_approximation.py,sha256=nU45YzkZLn1HoRbPFvZO4_oIO_Pzbwf6qkcBddQvMSU,40838 +sklearn/kernel_ridge.py,sha256=TOKKFRzoTUD99s_uc1dqs8KoDYlT3OqQgIJ5CeqVE1M,9185 +sklearn/linear_model/__init__.py,sha256=6tSQhCEgg7AKO4qNZnWtySPRfzrKlprmeG4NehEPkBo,2529 +sklearn/linear_model/__pycache__/__init__.cpython-310.pyc,, +sklearn/linear_model/__pycache__/_base.cpython-310.pyc,, +sklearn/linear_model/__pycache__/_bayes.cpython-310.pyc,, +sklearn/linear_model/__pycache__/_coordinate_descent.cpython-310.pyc,, +sklearn/linear_model/__pycache__/_huber.cpython-310.pyc,, +sklearn/linear_model/__pycache__/_least_angle.cpython-310.pyc,, +sklearn/linear_model/__pycache__/_linear_loss.cpython-310.pyc,, +sklearn/linear_model/__pycache__/_logistic.cpython-310.pyc,, +sklearn/linear_model/__pycache__/_omp.cpython-310.pyc,, +sklearn/linear_model/__pycache__/_passive_aggressive.cpython-310.pyc,, +sklearn/linear_model/__pycache__/_perceptron.cpython-310.pyc,, +sklearn/linear_model/__pycache__/_quantile.cpython-310.pyc,, +sklearn/linear_model/__pycache__/_ransac.cpython-310.pyc,, +sklearn/linear_model/__pycache__/_ridge.cpython-310.pyc,, +sklearn/linear_model/__pycache__/_sag.cpython-310.pyc,, +sklearn/linear_model/__pycache__/_stochastic_gradient.cpython-310.pyc,, +sklearn/linear_model/__pycache__/_theil_sen.cpython-310.pyc,, +sklearn/linear_model/_base.py,sha256=bZ9tuHHeI0J0Jk5_vzLpDO75mmZQT3nc3dFh69ZDxNY,27254 +sklearn/linear_model/_bayes.py,sha256=STnQ-r57Ll32FyDxIjNJK6VqlnygIuyREHa-HYc9Oxc,29747 +sklearn/linear_model/_cd_fast.cpython-310-x86_64-linux-gnu.so,sha256=bHWtW1OqO54G2p0ukhdI463Vk6wlTOkpyaNmTsYTqA8,495809 +sklearn/linear_model/_coordinate_descent.py,sha256=RGbCsBXn31g_l1VidU2GYayHJBgFKC-vMnLN0hyLol0,109065 +sklearn/linear_model/_glm/__init__.py,sha256=vaLhPXiACndKUaLvWZDBlUbipsuEb79-dbKqbMrIppc,263 +sklearn/linear_model/_glm/__pycache__/__init__.cpython-310.pyc,, +sklearn/linear_model/_glm/__pycache__/_newton_solver.cpython-310.pyc,, +sklearn/linear_model/_glm/__pycache__/glm.cpython-310.pyc,, +sklearn/linear_model/_glm/_newton_solver.py,sha256=UHuEPm1ZYAQ4_aiW7yf5UEfojJilAWE_eVgwMfuVG8M,19275 +sklearn/linear_model/_glm/glm.py,sha256=jEhldFwsBWOXejoNSzsEnsB2w2QRYMtjh4s9XOwIG28,31930 +sklearn/linear_model/_glm/tests/__init__.py,sha256=-YHpqhr5PuflTU66U6sex61pDz1R8jl2sTr22hcbUL0,24 +sklearn/linear_model/_glm/tests/__pycache__/__init__.cpython-310.pyc,, +sklearn/linear_model/_glm/tests/__pycache__/test_glm.cpython-310.pyc,, +sklearn/linear_model/_glm/tests/test_glm.py,sha256=z7U7x5RvXSa41dBfooROVKVooYnBUadgcxM0wHgPei8,40696 +sklearn/linear_model/_huber.py,sha256=9n8GzFCh1jmOnzcDExJFTGRUuiVkp8TNX8zuZfYR6_k,12346 +sklearn/linear_model/_least_angle.py,sha256=JV5HDFqHhWXi6HABad7sfOSaYyx8mB-lk7sZqa25pEs,81551 +sklearn/linear_model/_linear_loss.py,sha256=nGJM2OZJuEMB9-Hu1g6x7_t4ZRkPwRQiPNgCtWjueIs,26796 +sklearn/linear_model/_logistic.py,sha256=a3WNhzGlrQgPzNjSKBAOmeuOCtAGZmU6G7Oa8qSxOBs,84028 +sklearn/linear_model/_omp.py,sha256=KBvFm7SyXg4CKo5HG60Lbfz1FoIlpVcfe4H6De589eI,37378 +sklearn/linear_model/_passive_aggressive.py,sha256=b_W3ZwCFkl-sRI3QcUvuXaV9zJFASgx1s5aB7EYfBc0,19323 +sklearn/linear_model/_perceptron.py,sha256=p9ZHZbhx8Tg11zaU6sixaIbf0RE3_2v2g3-FgKJMhxM,7707 +sklearn/linear_model/_quantile.py,sha256=XPD5jYhfLSMJNH05LMD6G-XeebHejjZS9VmvI-wS050,10790 +sklearn/linear_model/_ransac.py,sha256=HjA6TdSe8cTngxekVrveldi9cKLjrnRzPYEp8EoQnNU,22163 +sklearn/linear_model/_ridge.py,sha256=alJBBnePRcxPm_ObfnrOi96wc9dBN25JSVIRDNKOh5Q,93020 +sklearn/linear_model/_sag.py,sha256=imvKwV9VFDYBS8dYvad7yLzH47VSqwqoGtERrsKyWOY,12320 +sklearn/linear_model/_sag_fast.cpython-310-x86_64-linux-gnu.so,sha256=ZcQjB29GZLkJtf_zF_pUY0A94GczJ7XAtk_-6ZrcQVQ,306897 +sklearn/linear_model/_sgd_fast.cpython-310-x86_64-linux-gnu.so,sha256=ryq0M3lgptV73gV53lIUormar9vpU5fKDD93--Jqwuo,385001 +sklearn/linear_model/_sgd_fast.pxd,sha256=vamOXNBtVxqTymLrbwjNp3NHfjWX0q701CrnocsX-0M,897 +sklearn/linear_model/_stochastic_gradient.py,sha256=1P2ddZnhCvm8MehuNi6bZZ6iKbFt7Acgt273DzZORD8,89642 +sklearn/linear_model/_theil_sen.py,sha256=WCBxOSHe_-5TkzCWo37vyVLutITbgcwv0V_W4jNs4C8,15814 +sklearn/linear_model/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/linear_model/tests/__pycache__/__init__.cpython-310.pyc,, +sklearn/linear_model/tests/__pycache__/test_base.cpython-310.pyc,, +sklearn/linear_model/tests/__pycache__/test_bayes.cpython-310.pyc,, +sklearn/linear_model/tests/__pycache__/test_common.cpython-310.pyc,, +sklearn/linear_model/tests/__pycache__/test_coordinate_descent.cpython-310.pyc,, +sklearn/linear_model/tests/__pycache__/test_huber.cpython-310.pyc,, +sklearn/linear_model/tests/__pycache__/test_least_angle.cpython-310.pyc,, +sklearn/linear_model/tests/__pycache__/test_linear_loss.cpython-310.pyc,, +sklearn/linear_model/tests/__pycache__/test_logistic.cpython-310.pyc,, +sklearn/linear_model/tests/__pycache__/test_omp.cpython-310.pyc,, +sklearn/linear_model/tests/__pycache__/test_passive_aggressive.cpython-310.pyc,, +sklearn/linear_model/tests/__pycache__/test_perceptron.cpython-310.pyc,, +sklearn/linear_model/tests/__pycache__/test_quantile.cpython-310.pyc,, +sklearn/linear_model/tests/__pycache__/test_ransac.cpython-310.pyc,, +sklearn/linear_model/tests/__pycache__/test_ridge.cpython-310.pyc,, +sklearn/linear_model/tests/__pycache__/test_sag.cpython-310.pyc,, +sklearn/linear_model/tests/__pycache__/test_sgd.cpython-310.pyc,, +sklearn/linear_model/tests/__pycache__/test_sparse_coordinate_descent.cpython-310.pyc,, +sklearn/linear_model/tests/__pycache__/test_theil_sen.cpython-310.pyc,, +sklearn/linear_model/tests/test_base.py,sha256=2NhWnz2FjsOF411kl1ESnTJ7ZD3r8Fr9vcCHklK15I8,27229 +sklearn/linear_model/tests/test_bayes.py,sha256=Uc6AdYjx0-5yrylL1hng-iWdEMzxgoRCxAmmYrkApnw,11584 +sklearn/linear_model/tests/test_common.py,sha256=SY7Dd966eZh_skRPCn_hxTfRVFvQkx-NvT8gQINk8hg,4687 +sklearn/linear_model/tests/test_coordinate_descent.py,sha256=FATr-ebv3iSAJwIW_9OD-FT8pBNgJvC4SjcLw0Q6djk,56926 +sklearn/linear_model/tests/test_huber.py,sha256=ExSNx9Xbze4i63cPj7JzsDbPLe6sh8E6CIz4ExEAHtg,7598 +sklearn/linear_model/tests/test_least_angle.py,sha256=9Lk2lhvQpjHfCijgAMUqUj1oNXsCFA0dk1b6AmMtK8k,29553 +sklearn/linear_model/tests/test_linear_loss.py,sha256=cb5WAL0Im_kHbfKJwXWc1wevR5BICpsloWIdDKWbQ3w,12851 +sklearn/linear_model/tests/test_logistic.py,sha256=KM9CDPRWSPilAwQHcTsmZ8FufcyL0YQwI-WIOO1spjc,75541 +sklearn/linear_model/tests/test_omp.py,sha256=bNwa-VyUMMAIUZWaT7gjJJAqq2YaeJMXxQHp8a4Vlac,8913 +sklearn/linear_model/tests/test_passive_aggressive.py,sha256=oylJ8F5LNg0br4zX2LXZRU8FMUECnhsaVL0r8mxmd1Q,8994 +sklearn/linear_model/tests/test_perceptron.py,sha256=rsNfXmS37bAZeZ04kRNhc2PXr4WjjTWDaxW_gNmMCkI,2608 +sklearn/linear_model/tests/test_quantile.py,sha256=nRCu1mou5LF5L9PBQsredTuikzzNwaCMxEFpEVN56T0,11425 +sklearn/linear_model/tests/test_ransac.py,sha256=Nwf_kbnOOyEQvrsfJ9sWHRRxp7BCnupAiX1qbFmsT1k,16778 +sklearn/linear_model/tests/test_ridge.py,sha256=r6xw8diYWugeZmEnZi92UcesKImu5_7dzWkAq_eFFFw,70145 +sklearn/linear_model/tests/test_sag.py,sha256=50W_5pcpA12znM0FGSQOoZP0OycRu6EarHv1LJBK9Go,31398 +sklearn/linear_model/tests/test_sgd.py,sha256=3Nw4IrdNDkgzu6EAqg9oByvZr4lLez75OqcRvoGkoRo,70696 +sklearn/linear_model/tests/test_sparse_coordinate_descent.py,sha256=2_IRPgEBCa6eWM_vtHfVHqX8-LDN7pj027WSpFHjWys,12654 +sklearn/linear_model/tests/test_theil_sen.py,sha256=JzsRgQy-uFE4cscZeRkWoO8fnNMbs4WbWrmcsictlQI,9881 +sklearn/manifold/__init__.py,sha256=yvhOlk50TCT-OMkivl5v6FeUGmmAgnC-C8o1IF0okcU,533 +sklearn/manifold/__pycache__/__init__.cpython-310.pyc,, +sklearn/manifold/__pycache__/_isomap.cpython-310.pyc,, +sklearn/manifold/__pycache__/_locally_linear.cpython-310.pyc,, +sklearn/manifold/__pycache__/_mds.cpython-310.pyc,, +sklearn/manifold/__pycache__/_spectral_embedding.cpython-310.pyc,, +sklearn/manifold/__pycache__/_t_sne.cpython-310.pyc,, +sklearn/manifold/_barnes_hut_tsne.cpython-310-x86_64-linux-gnu.so,sha256=HbcOT8ngJhizKXTOpu8g2WTfwaUBAAgLnM0TT3cmA6s,249777 +sklearn/manifold/_isomap.py,sha256=ECrmC0y1lLVBLeHqorF0MypxTbMZY3IIK0mQDD-bHDM,15587 +sklearn/manifold/_locally_linear.py,sha256=9X65zCp6mms8QR-GNMjgbJUYl2ZDf9jfhlgHbzcC2kA,29408 +sklearn/manifold/_mds.py,sha256=BUrTzatb6oG-GG5J_Exf6aEsnhv_KoY5DacPU1kxBV8,23693 +sklearn/manifold/_spectral_embedding.py,sha256=_n6DsuOIuvCiZoeScRjfilf7dYBErqM6qU6-ZJUax6Q,29120 +sklearn/manifold/_t_sne.py,sha256=rBZ3HPZlyNMXWcBJrJO1w6wJ_Vha5KRWOz8W7OV2Kz0,43994 +sklearn/manifold/_utils.cpython-310-x86_64-linux-gnu.so,sha256=fnVMELLk-VXByqxRiWw6p9-37NhDNoU4I_R4PzFjPG0,224969 +sklearn/manifold/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/manifold/tests/__pycache__/__init__.cpython-310.pyc,, +sklearn/manifold/tests/__pycache__/test_isomap.cpython-310.pyc,, +sklearn/manifold/tests/__pycache__/test_locally_linear.cpython-310.pyc,, +sklearn/manifold/tests/__pycache__/test_mds.cpython-310.pyc,, +sklearn/manifold/tests/__pycache__/test_spectral_embedding.cpython-310.pyc,, +sklearn/manifold/tests/__pycache__/test_t_sne.cpython-310.pyc,, +sklearn/manifold/tests/test_isomap.py,sha256=Wl4voE-7ZRpK6YS6JKyEpAhccA0ReBlGyLNU-p4hQWc,12074 +sklearn/manifold/tests/test_locally_linear.py,sha256=yxsUuJ7vzm2VxiLi1fuZjzICS_0mXrwIicJHLC79eDM,5772 +sklearn/manifold/tests/test_mds.py,sha256=x9fZ7tRHUoq4cN7JeW80pZARF-vouj1w4fZRBvjsMKc,3043 +sklearn/manifold/tests/test_spectral_embedding.py,sha256=maxnLdSJmSqTwgOxmOQ4wLVQ47KZ5hZEgU2an20GQfo,19398 +sklearn/manifold/tests/test_t_sne.py,sha256=-wY0kWKltNWS_p2XqA9HRXNpn-nuu2X_DbCEypxEb6s,38871 +sklearn/metrics/__init__.py,sha256=JUVKI03c4fpjAdNWDUjmxkCSlF61Y8mBD64yQ9Q44xc,4554 +sklearn/metrics/__pycache__/__init__.cpython-310.pyc,, +sklearn/metrics/__pycache__/_base.cpython-310.pyc,, +sklearn/metrics/__pycache__/_classification.cpython-310.pyc,, +sklearn/metrics/__pycache__/_ranking.cpython-310.pyc,, +sklearn/metrics/__pycache__/_regression.cpython-310.pyc,, +sklearn/metrics/__pycache__/_scorer.cpython-310.pyc,, +sklearn/metrics/__pycache__/pairwise.cpython-310.pyc,, +sklearn/metrics/_base.py,sha256=WjC_Z-C5TGadsgstffA5dd25jfNoqnBf4750ZzVMw8c,7292 +sklearn/metrics/_classification.py,sha256=kMgwCC5p-wfLynHxsRSLX0Dba7YoDugk54jPc6oHHds,121687 +sklearn/metrics/_dist_metrics.cpython-310-x86_64-linux-gnu.so,sha256=hU6F2nIORqrT0NixeGPK2jAH9FUjWTIOZ3VeRWvpgvE,720825 +sklearn/metrics/_dist_metrics.pxd,sha256=uyKN7HH9w1cim9EvV3VOenBva6an14EAeKik5I6CLC4,7481 +sklearn/metrics/_pairwise_distances_reduction/__init__.py,sha256=L5bCYy276KPl6CLELT4oXlRr1irwb5GUz5PdlgEAxow,5122 +sklearn/metrics/_pairwise_distances_reduction/__pycache__/__init__.cpython-310.pyc,, +sklearn/metrics/_pairwise_distances_reduction/__pycache__/_dispatcher.cpython-310.pyc,, +sklearn/metrics/_pairwise_distances_reduction/_argkmin.cpython-310-x86_64-linux-gnu.so,sha256=o9TUMftV1dLCQUmJe2EBlIXNix0PeyFTDMzhXhAysT0,377049 +sklearn/metrics/_pairwise_distances_reduction/_argkmin.pxd,sha256=IKvJiVHOjDUl--qruBhGyeasyY9zwfWwH--PXRmbXeg,1752 +sklearn/metrics/_pairwise_distances_reduction/_argkmin_classmode.cpython-310-x86_64-linux-gnu.so,sha256=MMAmifIhM62zM4mn_vdgsp0xskSAFxflR5fkMuMNh-E,282617 +sklearn/metrics/_pairwise_distances_reduction/_base.cpython-310-x86_64-linux-gnu.so,sha256=FyhO3-NvE4VKiAw6ngTTagjzVUH_S0duaTNxR4oR57U,344609 +sklearn/metrics/_pairwise_distances_reduction/_base.pxd,sha256=MihUlUL1_7nH_dN_j17OfY8aZ7aqU34YbCRGZHdxVhg,6996 +sklearn/metrics/_pairwise_distances_reduction/_classmode.pxd,sha256=DndeCKL21LyIGbp42nlWI9CKoyErDByZyQawUagL1XE,151 +sklearn/metrics/_pairwise_distances_reduction/_datasets_pair.cpython-310-x86_64-linux-gnu.so,sha256=GuNkOEcxSR1JiLXce2ajVjSc03At9OXuXC-p2UyBTLY,499553 +sklearn/metrics/_pairwise_distances_reduction/_datasets_pair.pxd,sha256=YIRh4JJd0PpYIaCmXkgIxadeS617pD9oaqaCRGDQ_wg,2911 +sklearn/metrics/_pairwise_distances_reduction/_dispatcher.py,sha256=qeMkh0ViX29TRnZkEEMkBXxi0G0vwTnVKyrhwzyE3rE,29726 +sklearn/metrics/_pairwise_distances_reduction/_middle_term_computer.cpython-310-x86_64-linux-gnu.so,sha256=ui_jc74TKc-D5bHuLLDZEXcR0o4jSEpxFb5nbk7lxOA,509657 +sklearn/metrics/_pairwise_distances_reduction/_middle_term_computer.pxd,sha256=aDdwzZrYwTCD1By1UZ81e13TerdXhGCHD6rdlo8Q17M,10110 +sklearn/metrics/_pairwise_distances_reduction/_radius_neighbors.cpython-310-x86_64-linux-gnu.so,sha256=JDOvMHxaIkR_D9Ep4jXObh1NFBLaEzVbMhwjuSxQEyg,392833 +sklearn/metrics/_pairwise_distances_reduction/_radius_neighbors.pxd,sha256=igbfvppcbA4SXjHS_aqMpK33JOCPgIMh3MFjvbKfCSk,5662 +sklearn/metrics/_pairwise_distances_reduction/_radius_neighbors_classmode.cpython-310-x86_64-linux-gnu.so,sha256=3Ya0WE39JlMZf2gBxc3nKMEI0LJ6ZhaI2aZnV5yBo1Q,307249 +sklearn/metrics/_pairwise_fast.cpython-310-x86_64-linux-gnu.so,sha256=7DXkxWTfHq2FKzP_2UbeA-tXGgtnB3sexm29UaaQ2uI,307209 +sklearn/metrics/_plot/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/metrics/_plot/__pycache__/__init__.cpython-310.pyc,, +sklearn/metrics/_plot/__pycache__/confusion_matrix.cpython-310.pyc,, +sklearn/metrics/_plot/__pycache__/det_curve.cpython-310.pyc,, +sklearn/metrics/_plot/__pycache__/precision_recall_curve.cpython-310.pyc,, +sklearn/metrics/_plot/__pycache__/regression.cpython-310.pyc,, +sklearn/metrics/_plot/__pycache__/roc_curve.cpython-310.pyc,, +sklearn/metrics/_plot/confusion_matrix.py,sha256=dL2DklWIB38whTFvYrT7RcZiebpbRRlanZm7CekXuaQ,16355 +sklearn/metrics/_plot/det_curve.py,sha256=twcA1JQzSTLE8D4Z68xY6m-qq8P9MlWvfkrosZC-J0s,10770 +sklearn/metrics/_plot/precision_recall_curve.py,sha256=XJnO4-s3fSMv0y5LQ9ln-Ct4ADebDJ5B-bACiKX8VDo,17688 +sklearn/metrics/_plot/regression.py,sha256=eXOZiBoDCBomDxd80N1oNkem1SrgjQHTLEpslCIESco,14346 +sklearn/metrics/_plot/roc_curve.py,sha256=o01tY9ci7B0YRGhia-ToGEuk54t0n0xYjvDetcntTeA,13545 +sklearn/metrics/_plot/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/metrics/_plot/tests/__pycache__/__init__.cpython-310.pyc,, +sklearn/metrics/_plot/tests/__pycache__/test_common_curve_display.cpython-310.pyc,, +sklearn/metrics/_plot/tests/__pycache__/test_confusion_matrix_display.cpython-310.pyc,, +sklearn/metrics/_plot/tests/__pycache__/test_det_curve_display.cpython-310.pyc,, +sklearn/metrics/_plot/tests/__pycache__/test_precision_recall_display.cpython-310.pyc,, +sklearn/metrics/_plot/tests/__pycache__/test_predict_error_display.cpython-310.pyc,, +sklearn/metrics/_plot/tests/__pycache__/test_roc_curve_display.cpython-310.pyc,, +sklearn/metrics/_plot/tests/test_common_curve_display.py,sha256=A2r2-yd6syyfyamG1h_GOaL2W9S8wcv88LYfynHbw6M,8815 +sklearn/metrics/_plot/tests/test_confusion_matrix_display.py,sha256=OpUPXurw7DNM9kpp1ATus2RXjxWD7iHTAsqHo8t0JKc,13705 +sklearn/metrics/_plot/tests/test_det_curve_display.py,sha256=uNXmzZ3pIWvnzDiPHBVB0jmuLRsRrO3eK7P-btuyJvQ,3426 +sklearn/metrics/_plot/tests/test_precision_recall_display.py,sha256=TdDMh3ws9RjvLZlKGjkG-TzDRFTc-WNyRL7XGiIrSEE,13100 +sklearn/metrics/_plot/tests/test_predict_error_display.py,sha256=N2GkMVTVXT2miRmNJXTVqnD6JOJu76Om3p4qqBBpr_Y,5786 +sklearn/metrics/_plot/tests/test_roc_curve_display.py,sha256=zGCZrlRPWui4P159bMaVJUISQ4k8l_96vwx7Pw96XAQ,10135 +sklearn/metrics/_ranking.py,sha256=OdDOWILlnxCwnlV7Mgvc5I6vmr60mCMW5wHUvwSk_Jg,75994 +sklearn/metrics/_regression.py,sha256=AP-bMHBlv3Wvd6ED4DMKviUOeRjuFGlVBVH_rRvdgp8,61720 +sklearn/metrics/_scorer.py,sha256=gnfOJ_op78C5jj-N7bUwRHAUJ2j5jvazjXuX9ieIbh4,33389 +sklearn/metrics/cluster/__init__.py,sha256=6pZddbfb9ZXYQyX64s6Jjgv_m_4c9RUcIAHRM7VQcj0,1396 +sklearn/metrics/cluster/__pycache__/__init__.cpython-310.pyc,, +sklearn/metrics/cluster/__pycache__/_bicluster.cpython-310.pyc,, +sklearn/metrics/cluster/__pycache__/_supervised.cpython-310.pyc,, +sklearn/metrics/cluster/__pycache__/_unsupervised.cpython-310.pyc,, +sklearn/metrics/cluster/_bicluster.py,sha256=jTfT3BsLJgAHGiQXrYWAwY0kSczOCdgkA58Ob9Q1vus,3378 +sklearn/metrics/cluster/_expected_mutual_info_fast.cpython-310-x86_64-linux-gnu.so,sha256=eBAEpEW0R3wamiWAC0Y1Itnga8tBtyTQulsIDv2GOx0,249617 +sklearn/metrics/cluster/_supervised.py,sha256=icnAgeCbQVZwMwQBe23QpF6MaMZ1lSZR6cLqJ8dGrXQ,44498 +sklearn/metrics/cluster/_unsupervised.py,sha256=7ZGogwkpWOCQMm6JqyWfF6b6SV5hStsO_IXPC4Oil3A,17063 +sklearn/metrics/cluster/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/metrics/cluster/tests/__pycache__/__init__.cpython-310.pyc,, +sklearn/metrics/cluster/tests/__pycache__/test_bicluster.cpython-310.pyc,, +sklearn/metrics/cluster/tests/__pycache__/test_common.cpython-310.pyc,, +sklearn/metrics/cluster/tests/__pycache__/test_supervised.cpython-310.pyc,, +sklearn/metrics/cluster/tests/__pycache__/test_unsupervised.cpython-310.pyc,, +sklearn/metrics/cluster/tests/test_bicluster.py,sha256=KecSxviHfRfUMNVZ0g77Ykx96QAuKoax0YUY8paQjFg,1719 +sklearn/metrics/cluster/tests/test_common.py,sha256=OMkbcRz79VNnWsb2EDctzuD5jWHDpbPHT77jyDc_zWg,7755 +sklearn/metrics/cluster/tests/test_supervised.py,sha256=RROPHFeKWDeEtzuPsIn-CP8_i10m2f9txI0PR9_V8hE,17873 +sklearn/metrics/cluster/tests/test_unsupervised.py,sha256=eAic9M_89S8Xbk1hEX0xyIeBW2GrAwPOTpNuNob3TaU,12269 +sklearn/metrics/pairwise.py,sha256=4geFniY4-JPM5GWl1XPFKqaNQmMS6YY2khZe98nBvqo,85973 +sklearn/metrics/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/metrics/tests/__pycache__/__init__.cpython-310.pyc,, +sklearn/metrics/tests/__pycache__/test_classification.cpython-310.pyc,, +sklearn/metrics/tests/__pycache__/test_common.cpython-310.pyc,, +sklearn/metrics/tests/__pycache__/test_dist_metrics.cpython-310.pyc,, +sklearn/metrics/tests/__pycache__/test_pairwise.cpython-310.pyc,, +sklearn/metrics/tests/__pycache__/test_pairwise_distances_reduction.cpython-310.pyc,, +sklearn/metrics/tests/__pycache__/test_ranking.cpython-310.pyc,, +sklearn/metrics/tests/__pycache__/test_regression.cpython-310.pyc,, +sklearn/metrics/tests/__pycache__/test_score_objects.cpython-310.pyc,, +sklearn/metrics/tests/test_classification.py,sha256=BhDlDMA3xkk7M4pr3gq3OeazCOQGv5I0DYNahHl5mcg,101469 +sklearn/metrics/tests/test_common.py,sha256=v0hzqsDVldMoegkFPUmuz5IQX1s72ZX4kxQCi4Lhra4,60017 +sklearn/metrics/tests/test_dist_metrics.py,sha256=W-yVTM8LQ1C-VYgLu450dDy3mYvgvqjoRX476-bM0E0,14802 +sklearn/metrics/tests/test_pairwise.py,sha256=G7e4tg-YJCP09-FiWxx0CfpdudhO2SvhdL_bXiso_W4,56671 +sklearn/metrics/tests/test_pairwise_distances_reduction.py,sha256=-hMjyDA0OHHyfjYQLEk2EkwlRnCaB61iZgrF5cpHCDI,53017 +sklearn/metrics/tests/test_ranking.py,sha256=5bkKeiU6_sqFN-tfztL6nUYJUH1bTd1YVLxlCdUnsSY,82385 +sklearn/metrics/tests/test_regression.py,sha256=03afzfelew-lWexi9kwfGI8piVd2pefS-xcJAUbtav8,27231 +sklearn/metrics/tests/test_score_objects.py,sha256=nFN_XqApK5NFN05gZZOVRjo9h8ZSiRYCahaUTAmnOc8,53184 +sklearn/mixture/__init__.py,sha256=1c5Ss-UEnXZNlyEKN11jPw5QzPYNxn6n1YY3VtzWyXA,243 +sklearn/mixture/__pycache__/__init__.cpython-310.pyc,, +sklearn/mixture/__pycache__/_base.cpython-310.pyc,, +sklearn/mixture/__pycache__/_bayesian_mixture.cpython-310.pyc,, +sklearn/mixture/__pycache__/_gaussian_mixture.cpython-310.pyc,, +sklearn/mixture/_base.py,sha256=mI0zB_yhFCaog5XQqOKACQy0GztM-MhlSmXLYb0PK4g,18718 +sklearn/mixture/_bayesian_mixture.py,sha256=9_bWvxgoUrW6PJCM3CMNh4H27_a2ycMZVUGGD5-4LVU,33467 +sklearn/mixture/_gaussian_mixture.py,sha256=Xn4Oavq0PZOTJNX1bw32IMSTNmj_jewxNxTLiYV6jQs,31659 +sklearn/mixture/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/mixture/tests/__pycache__/__init__.cpython-310.pyc,, +sklearn/mixture/tests/__pycache__/test_bayesian_mixture.cpython-310.pyc,, +sklearn/mixture/tests/__pycache__/test_gaussian_mixture.cpython-310.pyc,, +sklearn/mixture/tests/__pycache__/test_mixture.cpython-310.pyc,, +sklearn/mixture/tests/test_bayesian_mixture.py,sha256=rNDmWnACHub_f4CGl5GeRPt-l3MqhGcREMtZFszIgXk,17110 +sklearn/mixture/tests/test_gaussian_mixture.py,sha256=LBWfWSpeWBB0_nr3AiQwM0isQhv7Z32-655AsCstFHg,47721 +sklearn/mixture/tests/test_mixture.py,sha256=8TOVUJp9u9bi73KU2GaYhxPrB_s3U5vD0jLtIXDiAbM,992 +sklearn/model_selection/__init__.py,sha256=CUpYGOYvE8nZoMR6gdqc3rB3wsrOqRYIrg5-gouoOzI,2316 +sklearn/model_selection/__pycache__/__init__.cpython-310.pyc,, +sklearn/model_selection/__pycache__/_plot.cpython-310.pyc,, +sklearn/model_selection/__pycache__/_search.cpython-310.pyc,, +sklearn/model_selection/__pycache__/_search_successive_halving.cpython-310.pyc,, +sklearn/model_selection/__pycache__/_split.cpython-310.pyc,, +sklearn/model_selection/__pycache__/_validation.cpython-310.pyc,, +sklearn/model_selection/_plot.py,sha256=h68rAhmsYQ7ubnxEtYpPA5WPxqy98kqxU-vcu615j5E,35291 +sklearn/model_selection/_search.py,sha256=M8HbvD99GlmA70fEnSe5m0x1jUkYnbDM-MavFLRAXTk,75511 +sklearn/model_selection/_search_successive_halving.py,sha256=4LzlzkYXpMVDscX-6OqiLC_auZ8nQq8y8mQBuDBxPaI,43900 +sklearn/model_selection/_split.py,sha256=lCjgz-MketLeqSW1djkS8KFpBS6AZQvmNEfSQyUM-Lk,99167 +sklearn/model_selection/_validation.py,sha256=f-bKWlKHHuaqmsLTfcgpzZAxL8lHNH5Xnsbox9uZOgA,88502 +sklearn/model_selection/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/model_selection/tests/__pycache__/__init__.cpython-310.pyc,, +sklearn/model_selection/tests/__pycache__/common.cpython-310.pyc,, +sklearn/model_selection/tests/__pycache__/test_plot.cpython-310.pyc,, +sklearn/model_selection/tests/__pycache__/test_search.cpython-310.pyc,, +sklearn/model_selection/tests/__pycache__/test_split.cpython-310.pyc,, +sklearn/model_selection/tests/__pycache__/test_successive_halving.cpython-310.pyc,, +sklearn/model_selection/tests/__pycache__/test_validation.cpython-310.pyc,, +sklearn/model_selection/tests/common.py,sha256=PrR7WoVcn4MdG4DPrOvuZ1jrOIZPFPok20zannr4dwI,641 +sklearn/model_selection/tests/test_plot.py,sha256=SHEVhEgg8Ar4Aic-uLQxxHRpitKdkF50SxyosZXWeWY,19330 +sklearn/model_selection/tests/test_search.py,sha256=b2vco1mttHy5xlkZf6C2-oy0g8EKjN1zrA_DceZw8dc,84676 +sklearn/model_selection/tests/test_split.py,sha256=89bSigW200izAmnePEfGuOEf9kcEyuij0PG4SJ-jaX8,71585 +sklearn/model_selection/tests/test_successive_halving.py,sha256=XRpwkf-GLoqKyS7BGpPXJgiU4Hu9K4OOymMxRd2R3bM,28876 +sklearn/model_selection/tests/test_validation.py,sha256=SCutRhi7WgozJ2HiCZL_KaEBkFZZ4BP2s-mUBK1tpXQ,88874 +sklearn/multiclass.py,sha256=kDl_rhoa6x2KEK0PYyysQQHcmel4mOV2nFezGUG-u5c,43819 +sklearn/multioutput.py,sha256=eNg00fTjQJ52KrYQLe5szjZyP6xyHCE43r2n9tBuerw,40821 +sklearn/naive_bayes.py,sha256=hzSLegXMPpspWqxOagemcpIeTiTv9j4-F7trAqei29s,55670 +sklearn/neighbors/__init__.py,sha256=oYtShbfAlQmHKtukZN1cB4mANgk0XH5Je6LcBcc3KWU,1219 +sklearn/neighbors/__pycache__/__init__.cpython-310.pyc,, +sklearn/neighbors/__pycache__/_base.cpython-310.pyc,, +sklearn/neighbors/__pycache__/_classification.cpython-310.pyc,, +sklearn/neighbors/__pycache__/_graph.cpython-310.pyc,, +sklearn/neighbors/__pycache__/_kde.cpython-310.pyc,, +sklearn/neighbors/__pycache__/_lof.cpython-310.pyc,, +sklearn/neighbors/__pycache__/_nca.cpython-310.pyc,, +sklearn/neighbors/__pycache__/_nearest_centroid.cpython-310.pyc,, +sklearn/neighbors/__pycache__/_regression.cpython-310.pyc,, +sklearn/neighbors/__pycache__/_unsupervised.cpython-310.pyc,, +sklearn/neighbors/_ball_tree.cpython-310-x86_64-linux-gnu.so,sha256=zr7PTp2pnXfCifgefJdUF8fOKQTMqhpGN-eEi8axna0,774265 +sklearn/neighbors/_base.py,sha256=heTIm4F5hLlWdS0K9YumnBn0_UAytJgoWXweYxaBtiY,51658 +sklearn/neighbors/_classification.py,sha256=KTg3Zaw3iBtrUJw1MqrCXzppVDen3NC3QfJbur7TKjk,31731 +sklearn/neighbors/_graph.py,sha256=8fxtFbnUAJK5a-KpvZ4L-JjrhwcF4xT-BsoevmvJybU,25037 +sklearn/neighbors/_kd_tree.cpython-310-x86_64-linux-gnu.so,sha256=uLTbqpqXGyV6mW_kPznddB479YWg2AedIGdbOUcGGxg,774265 +sklearn/neighbors/_kde.py,sha256=Q33slUSLFOS0tX6sbpC1oLplc56xPETeJzE7vmWYTzQ,12461 +sklearn/neighbors/_lof.py,sha256=DiDUtX_2AD7N44vaU4Az7aMN_ZmgHe0LLnolm7-NjZQ,19708 +sklearn/neighbors/_nca.py,sha256=GUF6lhQh5Tl8xr725oxHOSeOGlVAg8ZRVST-T0U4CdI,19586 +sklearn/neighbors/_nearest_centroid.py,sha256=sZhThggQZbynbh7YwbyE98SzK6wQAgnwy3SD1yjyMDM,9645 +sklearn/neighbors/_partition_nodes.cpython-310-x86_64-linux-gnu.so,sha256=wnts5K9J-5wKXjrbxN6tbjYuc4eGv44fIx8tUiHjJP8,45289 +sklearn/neighbors/_partition_nodes.pxd,sha256=rngZZqkJWPnBW8BRvk0FgM817-lcHgCoBWEd91X0Dbc,288 +sklearn/neighbors/_quad_tree.cpython-310-x86_64-linux-gnu.so,sha256=jSTqsOd4dfQA3LhsaGWzLkbHZrZR0q3Cn4_pOLZxGeo,315401 +sklearn/neighbors/_quad_tree.pxd,sha256=G4ohAXB3bNYtGCQR-2U-hiGYk4yD6iL9OcpXqE8Xxms,4259 +sklearn/neighbors/_regression.py,sha256=NTRA-FqsIXCGkamHQozTImdsxIZ9YeNx1fPwXrqKeBY,18123 +sklearn/neighbors/_unsupervised.py,sha256=-cZCICevUiAmYm8mcI5ysPjxHQLQ4slcZKQGhEqj2BU,6179 +sklearn/neighbors/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/neighbors/tests/__pycache__/__init__.cpython-310.pyc,, +sklearn/neighbors/tests/__pycache__/test_ball_tree.cpython-310.pyc,, +sklearn/neighbors/tests/__pycache__/test_graph.cpython-310.pyc,, +sklearn/neighbors/tests/__pycache__/test_kd_tree.cpython-310.pyc,, +sklearn/neighbors/tests/__pycache__/test_kde.cpython-310.pyc,, +sklearn/neighbors/tests/__pycache__/test_lof.cpython-310.pyc,, +sklearn/neighbors/tests/__pycache__/test_nca.cpython-310.pyc,, +sklearn/neighbors/tests/__pycache__/test_nearest_centroid.cpython-310.pyc,, +sklearn/neighbors/tests/__pycache__/test_neighbors.cpython-310.pyc,, +sklearn/neighbors/tests/__pycache__/test_neighbors_pipeline.cpython-310.pyc,, +sklearn/neighbors/tests/__pycache__/test_neighbors_tree.cpython-310.pyc,, +sklearn/neighbors/tests/__pycache__/test_quad_tree.cpython-310.pyc,, +sklearn/neighbors/tests/test_ball_tree.py,sha256=hpoJiFpMrGxw0FEhd-KghO8zWtonaqSr1JgbKB7sdN0,7097 +sklearn/neighbors/tests/test_graph.py,sha256=QdJvyK2N138biDPhixx_Z9xbJ7R-aSxz5mhSSvh-HRg,3547 +sklearn/neighbors/tests/test_kd_tree.py,sha256=4cE2XJO0umuWnWPQluOMR9jfeJKDXmFETowsLElwKCI,3898 +sklearn/neighbors/tests/test_kde.py,sha256=kEZsv-8U0oWrkAVuzRidsqL5w1jQZ2b7tK9pFZYnm44,9745 +sklearn/neighbors/tests/test_lof.py,sha256=8ZOHkxKArqaVUHDn9yspJV3y-MzRYYTm-CykXxLx2yQ,12899 +sklearn/neighbors/tests/test_nca.py,sha256=dzdlTxsEUc7RBeVh12BCWlAcJRjCkfIQxOTh16kxkek,19052 +sklearn/neighbors/tests/test_nearest_centroid.py,sha256=uevLVoTjrbYAzKCokCjNnE2lTbzdOH67kgxBGBf7wio,5672 +sklearn/neighbors/tests/test_neighbors.py,sha256=E-sVzwTuE4ZGTMpLI2Mif0W9VsbV94lsjLO9scClQKs,81900 +sklearn/neighbors/tests/test_neighbors_pipeline.py,sha256=CZRj-Kvkeib7ljclLMW05ILcpk3jcgjmqXHaU4PWCE0,8137 +sklearn/neighbors/tests/test_neighbors_tree.py,sha256=8PMvvvHE8LkYT9oKeRvYvsi97HhmG1-_pTeFcTslpOM,9281 +sklearn/neighbors/tests/test_quad_tree.py,sha256=y_WE4jNxliYos_SiICl_miGIya2IJlu71rXzwvQw2qk,4856 +sklearn/neural_network/__init__.py,sha256=xEslFJWTVDhzQzsuBV2VCvfmSxUnxYkcuWu6SrlO-rU,273 +sklearn/neural_network/__pycache__/__init__.cpython-310.pyc,, +sklearn/neural_network/__pycache__/_base.cpython-310.pyc,, +sklearn/neural_network/__pycache__/_multilayer_perceptron.cpython-310.pyc,, +sklearn/neural_network/__pycache__/_rbm.cpython-310.pyc,, +sklearn/neural_network/__pycache__/_stochastic_optimizers.cpython-310.pyc,, +sklearn/neural_network/_base.py,sha256=NfmnHxbXeY7PAtWwpcFxqQYGCpJyaStHVug44WGX0WE,6329 +sklearn/neural_network/_multilayer_perceptron.py,sha256=h0ShX9OEVERF5bq8kWBNNYOe4-ImA0aHjm0-G02ZNqo,60524 +sklearn/neural_network/_rbm.py,sha256=svNo2BJCW7Nz4jV44hyYGSH1xQfcGCJRv0J0OYFO07E,15121 +sklearn/neural_network/_stochastic_optimizers.py,sha256=ZJSXQyJzouUJjj0X2CK463EgI4wpQYtrrMptkCye-2c,8823 +sklearn/neural_network/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/neural_network/tests/__pycache__/__init__.cpython-310.pyc,, +sklearn/neural_network/tests/__pycache__/test_base.cpython-310.pyc,, +sklearn/neural_network/tests/__pycache__/test_mlp.cpython-310.pyc,, +sklearn/neural_network/tests/__pycache__/test_rbm.cpython-310.pyc,, +sklearn/neural_network/tests/__pycache__/test_stochastic_optimizers.cpython-310.pyc,, +sklearn/neural_network/tests/test_base.py,sha256=YwqN20qHbC_5ZsPRDJyducMZfu-D3V5b1zmpj0C3au8,796 +sklearn/neural_network/tests/test_mlp.py,sha256=VCtmb1cVy9nJrtFLdwQfYFRVz94vvHGyPSR8Hf6-5Ek,31862 +sklearn/neural_network/tests/test_rbm.py,sha256=Ucezw6y1X0HU9PEC9lniKrqXplVXjfX5yjWueHIPPkg,8048 +sklearn/neural_network/tests/test_stochastic_optimizers.py,sha256=9JhAPo1Qc0sA735qPORoKtS04bCTts9lQ65P9Qlhtyo,4137 +sklearn/pipeline.py,sha256=s0uOf3NQ1ZArYI3nwZ1DWejNLo55nBhkBl8nPU9aEhA,66341 +sklearn/preprocessing/__init__.py,sha256=FVVSh0K0CzwHL_zgm_cfrFrmTfEJ7dwh24RzDYyHwyo,1460 +sklearn/preprocessing/__pycache__/__init__.cpython-310.pyc,, +sklearn/preprocessing/__pycache__/_data.cpython-310.pyc,, +sklearn/preprocessing/__pycache__/_discretization.cpython-310.pyc,, +sklearn/preprocessing/__pycache__/_encoders.cpython-310.pyc,, +sklearn/preprocessing/__pycache__/_function_transformer.cpython-310.pyc,, +sklearn/preprocessing/__pycache__/_label.cpython-310.pyc,, +sklearn/preprocessing/__pycache__/_polynomial.cpython-310.pyc,, +sklearn/preprocessing/__pycache__/_target_encoder.cpython-310.pyc,, +sklearn/preprocessing/_csr_polynomial_expansion.cpython-310-x86_64-linux-gnu.so,sha256=qLpJ53RN2aePBI1-H7IOczWKmEkoaKoSA1Dxyko4pFM,491585 +sklearn/preprocessing/_data.py,sha256=pkUi4XZuy_l7d9_NPMEhyEbht9ZGIwcvac8a6PwQGhM,125337 +sklearn/preprocessing/_discretization.py,sha256=CcQMmW4Cc4vL5OnhrBAcs8604IbirUISkUP9eQNDjQI,17376 +sklearn/preprocessing/_encoders.py,sha256=xUPLS-jhshgHPgeGQteIgMOwEoDRwwoemK9fi9FwT80,67754 +sklearn/preprocessing/_function_transformer.py,sha256=JR9vVxGCHFL17DlH1zM9StrCnUR84JplmpopLlsZUTY,16633 +sklearn/preprocessing/_label.py,sha256=Oud8OIGsfp4tuIcm-67rGgP9CxUomQOoG50EAsesICc,30800 +sklearn/preprocessing/_polynomial.py,sha256=EyM35Uk7krG65JXm1-jwBvFmS7Rfu-FLX1WYfokK_LY,47444 +sklearn/preprocessing/_target_encoder.py,sha256=Vr29eER6I3L-g4fsVyX4P_PKHs0R_qLFDfGfUbfg6vY,20476 +sklearn/preprocessing/_target_encoder_fast.cpython-310-x86_64-linux-gnu.so,sha256=NxImRT6vYf08qn6Ech4UC8OgRj0yzhRBn7O8hz2TBVM,569905 +sklearn/preprocessing/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/preprocessing/tests/__pycache__/__init__.cpython-310.pyc,, +sklearn/preprocessing/tests/__pycache__/test_common.cpython-310.pyc,, +sklearn/preprocessing/tests/__pycache__/test_data.cpython-310.pyc,, +sklearn/preprocessing/tests/__pycache__/test_discretization.cpython-310.pyc,, +sklearn/preprocessing/tests/__pycache__/test_encoders.cpython-310.pyc,, +sklearn/preprocessing/tests/__pycache__/test_function_transformer.cpython-310.pyc,, +sklearn/preprocessing/tests/__pycache__/test_label.cpython-310.pyc,, +sklearn/preprocessing/tests/__pycache__/test_polynomial.cpython-310.pyc,, +sklearn/preprocessing/tests/__pycache__/test_target_encoder.cpython-310.pyc,, +sklearn/preprocessing/tests/test_common.py,sha256=1gLqwBEMTpCJOMsftAwACox0d8wbqfB9z-JtRLlx9NM,6793 +sklearn/preprocessing/tests/test_data.py,sha256=8FwhXLqwlBtvmdowUH1ta-oBR_9rzTH5TlLxUELon58,94473 +sklearn/preprocessing/tests/test_discretization.py,sha256=DONU9R99_U13m8X7ov0WhFXVaj0C0a0Fu3xDQBqioKo,18054 +sklearn/preprocessing/tests/test_encoders.py,sha256=Jiz_L7a9thKlffgFi97evLvSuzsjBKytvmrxgQrdt-8,78684 +sklearn/preprocessing/tests/test_function_transformer.py,sha256=vo9Fei9PXJ3a9zqYbqwbFkwPpmlpffxNUOJ0Pgt3VhA,19827 +sklearn/preprocessing/tests/test_label.py,sha256=ufVtUsrYCn30ovYRnokrZN7F1_I2CgP7E53J9xz0Q3w,23634 +sklearn/preprocessing/tests/test_polynomial.py,sha256=Irt2g5oMUJQkz9Px5MPxa6yAh77IK15XbuwF-Yui74c,42411 +sklearn/preprocessing/tests/test_target_encoder.py,sha256=Q-KoQ6CvyMbgqI9DsPJ7p06QjfANqFsgibwtgyad5L0,27915 +sklearn/random_projection.py,sha256=GgJM_r7GffPW12bMjsWG0AUFlXNSH6lhgLtD3Hm_oq4,28095 +sklearn/semi_supervised/__init__.py,sha256=7JKLmXpZsl1U-4PY8V9IwqjIGWxvngEQWaEqMokg1Rg,448 +sklearn/semi_supervised/__pycache__/__init__.cpython-310.pyc,, +sklearn/semi_supervised/__pycache__/_label_propagation.cpython-310.pyc,, +sklearn/semi_supervised/__pycache__/_self_training.cpython-310.pyc,, +sklearn/semi_supervised/_label_propagation.py,sha256=_yfmtGcm_9KYy6W8CQpaOEc-CEKWbNTdFwCR_GRtUUc,21294 +sklearn/semi_supervised/_self_training.py,sha256=FiXc9mfrFh33C71N4enyTVxg4il7PHfCcU2lwS2uMhk,14342 +sklearn/semi_supervised/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/semi_supervised/tests/__pycache__/__init__.cpython-310.pyc,, +sklearn/semi_supervised/tests/__pycache__/test_label_propagation.cpython-310.pyc,, +sklearn/semi_supervised/tests/__pycache__/test_self_training.cpython-310.pyc,, +sklearn/semi_supervised/tests/test_label_propagation.py,sha256=R-Lkmzc5k5JFpcSUi0_EbUyTUBNTw4HrGAeOALICiK8,8803 +sklearn/semi_supervised/tests/test_self_training.py,sha256=QrLkQD4b2wLwZ2uvVk0AOGFwCaYobirgPUqBMZMmKgU,12543 +sklearn/svm/__init__.py,sha256=kxgE5R-_9xxQTPiwVXfSTkaWdaH2lfWzooXqpDzXZNQ,636 +sklearn/svm/__pycache__/__init__.cpython-310.pyc,, +sklearn/svm/__pycache__/_base.cpython-310.pyc,, +sklearn/svm/__pycache__/_bounds.cpython-310.pyc,, +sklearn/svm/__pycache__/_classes.cpython-310.pyc,, +sklearn/svm/_base.py,sha256=xtK0rgQe2XNBJfGRetK2nzPIRXUJdlH8gEh_b6trlGU,42474 +sklearn/svm/_bounds.py,sha256=8N53Wjx_F76pHCOP1EfTm8GRjjt9U-onTvb7IHmgFCs,3251 +sklearn/svm/_classes.py,sha256=rzmphrEcRUindolDnLgiClHonEYGTO57uV284sFYZ8E,66940 +sklearn/svm/_liblinear.cpython-310-x86_64-linux-gnu.so,sha256=3FM1IV0qEcOnEfw3VYgXBaiHD5r4Osm2GQH43dQy-4E,543113 +sklearn/svm/_libsvm.cpython-310-x86_64-linux-gnu.so,sha256=hyU5JuzpTMfH18KOGK6oXWblsVzyLgI-b_4UxMQOmBE,968673 +sklearn/svm/_libsvm_sparse.cpython-310-x86_64-linux-gnu.so,sha256=qH-Lgg4p0Cy1C55lxhwpCE4kZj_6txkU1i7mtIeJFCY,927689 +sklearn/svm/_newrand.cpython-310-x86_64-linux-gnu.so,sha256=srKE3DH6gtMwcQFLnHgWG05UPC2xaQCDpPVBxs-T7DE,68241 +sklearn/svm/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/svm/tests/__pycache__/__init__.cpython-310.pyc,, +sklearn/svm/tests/__pycache__/test_bounds.cpython-310.pyc,, +sklearn/svm/tests/__pycache__/test_sparse.cpython-310.pyc,, +sklearn/svm/tests/__pycache__/test_svm.cpython-310.pyc,, +sklearn/svm/tests/test_bounds.py,sha256=PcJwSEhh_ChQfEASag3RU92Q_ASyNDeAYcQmlSmNrOI,5232 +sklearn/svm/tests/test_sparse.py,sha256=EPW5UE4LKBfN-Xh39vC55784Jb38W7466CWwfPUZJL8,15697 +sklearn/svm/tests/test_svm.py,sha256=0LyLMzJDto7zy5B_i4e4SXPUofzujLugkuokyfauZBo,49059 +sklearn/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/tests/__pycache__/__init__.cpython-310.pyc,, +sklearn/tests/__pycache__/metadata_routing_common.cpython-310.pyc,, +sklearn/tests/__pycache__/random_seed.cpython-310.pyc,, +sklearn/tests/__pycache__/test_base.cpython-310.pyc,, +sklearn/tests/__pycache__/test_build.cpython-310.pyc,, +sklearn/tests/__pycache__/test_calibration.cpython-310.pyc,, +sklearn/tests/__pycache__/test_check_build.cpython-310.pyc,, +sklearn/tests/__pycache__/test_common.cpython-310.pyc,, +sklearn/tests/__pycache__/test_config.cpython-310.pyc,, +sklearn/tests/__pycache__/test_discriminant_analysis.cpython-310.pyc,, +sklearn/tests/__pycache__/test_docstring_parameters.cpython-310.pyc,, +sklearn/tests/__pycache__/test_docstrings.cpython-310.pyc,, +sklearn/tests/__pycache__/test_dummy.cpython-310.pyc,, +sklearn/tests/__pycache__/test_init.cpython-310.pyc,, +sklearn/tests/__pycache__/test_isotonic.cpython-310.pyc,, +sklearn/tests/__pycache__/test_kernel_approximation.cpython-310.pyc,, +sklearn/tests/__pycache__/test_kernel_ridge.cpython-310.pyc,, +sklearn/tests/__pycache__/test_metadata_routing.cpython-310.pyc,, +sklearn/tests/__pycache__/test_metaestimators.cpython-310.pyc,, +sklearn/tests/__pycache__/test_metaestimators_metadata_routing.cpython-310.pyc,, +sklearn/tests/__pycache__/test_min_dependencies_readme.cpython-310.pyc,, +sklearn/tests/__pycache__/test_multiclass.cpython-310.pyc,, +sklearn/tests/__pycache__/test_multioutput.cpython-310.pyc,, +sklearn/tests/__pycache__/test_naive_bayes.cpython-310.pyc,, +sklearn/tests/__pycache__/test_pipeline.cpython-310.pyc,, +sklearn/tests/__pycache__/test_public_functions.cpython-310.pyc,, +sklearn/tests/__pycache__/test_random_projection.cpython-310.pyc,, +sklearn/tests/metadata_routing_common.py,sha256=zNcUP_zepvLMZWqAztIOnt7qy1zehlISMV5bui21xk0,15568 +sklearn/tests/random_seed.py,sha256=QfxcXUSQsP1MlJYJmBaNJX8UrdnIBZmR0EMIqDISMqM,3311 +sklearn/tests/test_base.py,sha256=CoGYp8RW9JlWKtUxlVkryv5dAHxHiVJBc49LSCmu9Kw,28614 +sklearn/tests/test_build.py,sha256=xvLlCpUSgJQzAFcPp4bo8je9a5gcvN4PIIXmTo19G1s,1167 +sklearn/tests/test_calibration.py,sha256=cF8PhN5kY9Hzv1mB3_cjxyBP9Ahfl_bUaGEzM6BfDS4,40422 +sklearn/tests/test_check_build.py,sha256=bHvDtqeNsptzCqNMSqfWa00eg1CqCubL8KqvxBbXm84,267 +sklearn/tests/test_common.py,sha256=yCkbySLNEM3KjDfU2qKf-Z50cYIHbYvOdmr7eeIstR0,19553 +sklearn/tests/test_config.py,sha256=eQNukGqspjvxLNZZReyoqCGBrqhQDwV1fh3mpbOKWzA,6807 +sklearn/tests/test_discriminant_analysis.py,sha256=L6_53Mk0Vuhv9zV_BQ87DdC_pyKEsSczr3tU_sfR1p8,23194 +sklearn/tests/test_docstring_parameters.py,sha256=wY29rvWXTAQe0csBPYGOYfKy8H_124KEBst7wQ_Z4_A,11813 +sklearn/tests/test_docstrings.py,sha256=s6EDWnfj4P9K826oMAQlOHYI5L8s1Dqg3WGAYUbdsoM,6841 +sklearn/tests/test_dummy.py,sha256=pzBeUN_-sqLVcY2jpyDkQA6oh8IIOmlxI9-587NCKjs,21319 +sklearn/tests/test_init.py,sha256=sK3-WZX96Zphoh3SGS6sxs0UxhjFzlXmXVK-mQNl2KU,470 +sklearn/tests/test_isotonic.py,sha256=MHOW5pF9-Gc9TT7Ew1GdKmaw3_gCc3J0iCxXaDu1qHk,22169 +sklearn/tests/test_kernel_approximation.py,sha256=m_Dchs6_fyZ7vGw68LIAGD-Mz0bPjX-EP79dHKuenx8,16878 +sklearn/tests/test_kernel_ridge.py,sha256=qkwUUjuY5O1uMiXi9gAS-wXOCHa62F5T7VJnNdZdGOE,2888 +sklearn/tests/test_metadata_routing.py,sha256=8Nof-JOSlyekPE_cwO_Snoh0_cS8HjaebhuWylDF96E,34758 +sklearn/tests/test_metaestimators.py,sha256=ok5sztXRlL5XQNgfj6tYUe09VNb7mNjqCfPVsdr9J4k,10298 +sklearn/tests/test_metaestimators_metadata_routing.py,sha256=aOr9knXDL7kQDfWqEhTHWzyjFkwfSaEBG7og6drXW90,22521 +sklearn/tests/test_min_dependencies_readme.py,sha256=tCsOzkLFf4ObXqLR6qvg9sCjT6uV2qaGoUwfqdqgxM8,3222 +sklearn/tests/test_multiclass.py,sha256=bwHLep1y4CadAjpnvBpXjARqOrTHiN_IEUb8Tdl13Uo,33480 +sklearn/tests/test_multioutput.py,sha256=hQmcZ6vLb3iHyDEysWY_LyNtzCC9gSueu24JBB0L3ZQ,29175 +sklearn/tests/test_naive_bayes.py,sha256=ZKqQGY0kqh_GHN48RAC6e7lcaQ_anFHTI3p50ni4-_s,35027 +sklearn/tests/test_pipeline.py,sha256=NJXdd6d_VYOMSX_riyEPdaHM41jOrB65MgOEIOgr5Bw,63837 +sklearn/tests/test_public_functions.py,sha256=0mrfIpgnzgZ97K3EQzFVgiHb9Qm_Dqe8YnkMFXzB5cE,16477 +sklearn/tests/test_random_projection.py,sha256=PHgMtjxt5qvy6IM0YY6eWmNLelxdT2H4kF8BQbUBeRc,19583 +sklearn/tree/__init__.py,sha256=Bycl-qSX3rkvyaJEP9zbQ0u1XaWIhf6YG_j-1vQi8qM,534 +sklearn/tree/__pycache__/__init__.cpython-310.pyc,, +sklearn/tree/__pycache__/_classes.cpython-310.pyc,, +sklearn/tree/__pycache__/_export.cpython-310.pyc,, +sklearn/tree/__pycache__/_reingold_tilford.cpython-310.pyc,, +sklearn/tree/_classes.py,sha256=hUopTFu7OY3pOG55ysoNF43EEj8wnnL1Fqg1At-8JjI,75272 +sklearn/tree/_criterion.cpython-310-x86_64-linux-gnu.so,sha256=tEu3Q9K5adp3zkGpb3i2rTsTby7zdjUdnCT4u32K9I0,364313 +sklearn/tree/_criterion.pxd,sha256=ZDm4GRd_Gv1Drqj3074zi9KRb_P6m2vVx8rsMGt0-AI,4760 +sklearn/tree/_export.py,sha256=l4L2TuKDltxl_swcSV0NRnd5znRVlY9-UuD5KG8WljQ,39293 +sklearn/tree/_reingold_tilford.py,sha256=bFtCLvNsGkYC7FrAA0106nSU2BsL7mV0EYluA9D9cv4,5142 +sklearn/tree/_splitter.cpython-310-x86_64-linux-gnu.so,sha256=Swpo6CQLirkAn0PJzBxEZIlvACM-XpfBy6slEVd4TU4,388873 +sklearn/tree/_splitter.pxd,sha256=TDEF6Mpn5kgwNFdrW5pZcHrsRPmKSaGKmnUXUoIGITA,4784 +sklearn/tree/_tree.cpython-310-x86_64-linux-gnu.so,sha256=TwlVjS7PY_h11EquRAZT8qrlFGHOTSsvlqCxPIvPYIE,674257 +sklearn/tree/_tree.pxd,sha256=nkqGcmtdlUpoJ2tc3kzuxrKyLMn13p3HV3VMXvaTFKs,4679 +sklearn/tree/_utils.cpython-310-x86_64-linux-gnu.so,sha256=u9hZX8dliOv-nQeQz9vRGyGRFD735g2dYmyV4nJpurc,294689 +sklearn/tree/_utils.pxd,sha256=-33LOA5M0UZY2vcp8JhkC_c_glaTueCAQ0GnzJwT5WE,3818 +sklearn/tree/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/tree/tests/__pycache__/__init__.cpython-310.pyc,, +sklearn/tree/tests/__pycache__/test_export.cpython-310.pyc,, +sklearn/tree/tests/__pycache__/test_monotonic_tree.cpython-310.pyc,, +sklearn/tree/tests/__pycache__/test_reingold_tilford.cpython-310.pyc,, +sklearn/tree/tests/__pycache__/test_tree.cpython-310.pyc,, +sklearn/tree/tests/test_export.py,sha256=Z2TX6RK1ltOBNlwI53BshtXRTd2yG0rkjD9_x1pBOE0,17471 +sklearn/tree/tests/test_monotonic_tree.py,sha256=MSmAMPPKeqyZ9EyD0G77PoRKPBPoWBaDd8WV3GHP8ZQ,18590 +sklearn/tree/tests/test_reingold_tilford.py,sha256=xRt_Hlm-fGJ2onva4L9eL5mNdcHwWhPEppwNjP4VEJs,1461 +sklearn/tree/tests/test_tree.py,sha256=w5B2AYCmUeB5A-NY0cPkbPEpe9_1yyZ57aEbVkWM5Mk,94675 +sklearn/utils/__init__.py,sha256=-QnEFTn4QK5RaFdxU1ckf-gKrQpvBPm-3j5HEu1mQzs,40703 +sklearn/utils/__pycache__/__init__.cpython-310.pyc,, +sklearn/utils/__pycache__/_arpack.cpython-310.pyc,, +sklearn/utils/__pycache__/_array_api.cpython-310.pyc,, +sklearn/utils/__pycache__/_available_if.cpython-310.pyc,, +sklearn/utils/__pycache__/_bunch.cpython-310.pyc,, +sklearn/utils/__pycache__/_encode.cpython-310.pyc,, +sklearn/utils/__pycache__/_estimator_html_repr.cpython-310.pyc,, +sklearn/utils/__pycache__/_joblib.cpython-310.pyc,, +sklearn/utils/__pycache__/_mask.cpython-310.pyc,, +sklearn/utils/__pycache__/_metadata_requests.cpython-310.pyc,, +sklearn/utils/__pycache__/_mocking.cpython-310.pyc,, +sklearn/utils/__pycache__/_param_validation.cpython-310.pyc,, +sklearn/utils/__pycache__/_plotting.cpython-310.pyc,, +sklearn/utils/__pycache__/_pprint.cpython-310.pyc,, +sklearn/utils/__pycache__/_response.cpython-310.pyc,, +sklearn/utils/__pycache__/_set_output.cpython-310.pyc,, +sklearn/utils/__pycache__/_show_versions.cpython-310.pyc,, +sklearn/utils/__pycache__/_tags.cpython-310.pyc,, +sklearn/utils/__pycache__/_testing.cpython-310.pyc,, +sklearn/utils/__pycache__/class_weight.cpython-310.pyc,, +sklearn/utils/__pycache__/deprecation.cpython-310.pyc,, +sklearn/utils/__pycache__/discovery.cpython-310.pyc,, +sklearn/utils/__pycache__/estimator_checks.cpython-310.pyc,, +sklearn/utils/__pycache__/extmath.cpython-310.pyc,, +sklearn/utils/__pycache__/fixes.cpython-310.pyc,, +sklearn/utils/__pycache__/graph.cpython-310.pyc,, +sklearn/utils/__pycache__/metadata_routing.cpython-310.pyc,, +sklearn/utils/__pycache__/metaestimators.cpython-310.pyc,, +sklearn/utils/__pycache__/multiclass.cpython-310.pyc,, +sklearn/utils/__pycache__/optimize.cpython-310.pyc,, +sklearn/utils/__pycache__/parallel.cpython-310.pyc,, +sklearn/utils/__pycache__/random.cpython-310.pyc,, +sklearn/utils/__pycache__/sparsefuncs.cpython-310.pyc,, +sklearn/utils/__pycache__/stats.cpython-310.pyc,, +sklearn/utils/__pycache__/validation.cpython-310.pyc,, +sklearn/utils/_arpack.py,sha256=TxhOiluYxwPM3AV07RJGT0dosprJM6ga_f_Tno8yrJI,1129 +sklearn/utils/_array_api.py,sha256=kx0nSZa98mbXneuLAPNXzjd8RZ5iHhWV4SSduSBVpQU,18876 +sklearn/utils/_available_if.py,sha256=Kop8zZ3I4STHCPt8LyB8GzRT1utlHSuf329pADbxzbs,2873 +sklearn/utils/_bunch.py,sha256=YICcv-loEvJiJHHIzLu-Sia9VMxkdqfBuaRc_1bd474,2096 +sklearn/utils/_cython_blas.cpython-310-x86_64-linux-gnu.so,sha256=z0uJd46Fm8h33u1Fzqp5laHMinfovS60Gvd33NHqA0s,528377 +sklearn/utils/_cython_blas.pxd,sha256=Kx-TV-Wy3JD8JAROmcAB3623tmk01WnffCiFLResUZI,1565 +sklearn/utils/_encode.py,sha256=QmELuyvpp7KMe1n4PzPJd6VJOtjAPj9guqEUUQ6ikzE,11379 +sklearn/utils/_estimator_html_repr.css,sha256=S097GeV_Ajaspg_rNppjoEjbhPHKJNtIhp7pmKGyCck,11016 +sklearn/utils/_estimator_html_repr.py,sha256=8ShSN2xBBZMeEeV5hrYM8TKWsWnyvD5aGkFtu6oxZe0,18308 +sklearn/utils/_fast_dict.cpython-310-x86_64-linux-gnu.so,sha256=yNU4CmyfXpPinSJqNi9Quy9d1cHf3rOrMqBqyEywQ4Q,287705 +sklearn/utils/_fast_dict.pxd,sha256=_EqkuVnVd7LJr72_Kg5l52da2ZlqXWK_EmE7ukAD5W0,476 +sklearn/utils/_heap.cpython-310-x86_64-linux-gnu.so,sha256=fiedcLQDP_mkSjhLmgPYNBZSS-d50RFGO0kadORd-G0,34521 +sklearn/utils/_heap.pxd,sha256=FXcpp-JAYxvFGZqLZ6IrJieDZ9_W2hP4sVOLY4fzJAQ,256 +sklearn/utils/_isfinite.cpython-310-x86_64-linux-gnu.so,sha256=wFaDrgLtZJcuVmJnHOPKGKb4bR2WIQ04nj9WQyQ_ZB8,286649 +sklearn/utils/_joblib.py,sha256=pUOY1HrRIB-U64V1J5-i4z7BJcY8TpUkpx17Z8yzdSw,710 +sklearn/utils/_mask.py,sha256=Q6-kG--ba8BFMRSOUPU9H38M9exXCdiz3KrNRcoHhzE,1798 +sklearn/utils/_metadata_requests.py,sha256=Q-QnTaxc2xWOFpFqV32YxShLdxmNMsqZDsqAT6KSxnE,54375 +sklearn/utils/_mocking.py,sha256=IhE9FooFgHNIvamTEZWLSn6aEKrGixQaykOjmPlCBus,13093 +sklearn/utils/_openmp_helpers.cpython-310-x86_64-linux-gnu.so,sha256=E-nQlKjh7txdWkWG2Ectsk46KrHYBa1lTUbRGp09cQU,80553 +sklearn/utils/_openmp_helpers.pxd,sha256=ORtNXjPXDBOmoHW6--54wwrMEIZptCAZ6T8CJPCuJ-0,1069 +sklearn/utils/_param_validation.py,sha256=uirAI5SGQxD_4jG5GiDSscE-kFJLb2nIrh-pOyIn6pk,28445 +sklearn/utils/_plotting.py,sha256=WDBp1t4t5fZsb4USxiXfvsWbCTdXkVmJ1bZNx9aF8eU,3473 +sklearn/utils/_pprint.py,sha256=i1LEHJl34WYC1cjLmNJPNI01or5zfcPz3Y6Apfk0GME,18516 +sklearn/utils/_random.cpython-310-x86_64-linux-gnu.so,sha256=oNNaytrTHbpxF2zAAdglpG39WPOG0BoZZviMzD7BwIA,356297 +sklearn/utils/_random.pxd,sha256=rpNOrC7Y9gAdh8nYI-CX_6zXZF4fAvl66UUem6NR9pA,1241 +sklearn/utils/_response.py,sha256=50rVUNkrDO-X61AAI-B0PJpEYkjnGRbVpGB-DHaWdDQ,11563 +sklearn/utils/_seq_dataset.cpython-310-x86_64-linux-gnu.so,sha256=IZ9sZIlZ-8GU_r8PfC_3aTrv9R42RGPCiTRzN8yoQIo,331577 +sklearn/utils/_seq_dataset.pxd,sha256=QcjypOmJmox4q2AcisLcvuzk_UbQLDZk7wPgawvHGBE,3634 +sklearn/utils/_set_output.py,sha256=SFYPBHS2tnXneGVDkIuvP9-MOzLkHuToIqzsn3Yf820,14015 +sklearn/utils/_show_versions.py,sha256=VrBM2tc0SufP7THoTgBGRcLpdCTE9kBRG4C0gtARyRQ,2491 +sklearn/utils/_sorting.cpython-310-x86_64-linux-gnu.so,sha256=pPP7AKbyT5SIcY0Fu7iCElkphwsqBI4cFc4YS9e2JCs,34561 +sklearn/utils/_sorting.pxd,sha256=i8Bkh1j07pgP6pIvzFxFIZ7uAlR1fQOCbIHh7v04xw8,161 +sklearn/utils/_tags.py,sha256=4mEPJWv5QYBeV7UG5ySrggu5dygPx-zr3e-CmHb7JQY,2071 +sklearn/utils/_testing.py,sha256=_pKr4NsMRb4w8Ty_GDz6VqLFlW1z0JP-md1zLoIcVg4,39674 +sklearn/utils/_typedefs.cpython-310-x86_64-linux-gnu.so,sha256=0AexPwF7uB4S6N4kLlX4z8eYSNZIm1eR1dwpOy2_rMM,270217 +sklearn/utils/_typedefs.pxd,sha256=jAwP7opXLyBFpvi0mQ4OM0Z1x4jPT_Nna3I6wfJ9dsk,1403 +sklearn/utils/_vector_sentinel.cpython-310-x86_64-linux-gnu.so,sha256=ksgzgoxZbxFdkuKVhfmpFtctK47IhRHmmo7Tyy9Y6AU,176385 +sklearn/utils/_vector_sentinel.pxd,sha256=G_im5dT6DaREJgMAGu2MCd-tj5E-elc5mYX4sulSYW0,296 +sklearn/utils/_weight_vector.cpython-310-x86_64-linux-gnu.so,sha256=_lReRmlohKAQJ6SLdlJaZkBEnjLMf1dU7yQ_jEXrg6c,208457 +sklearn/utils/_weight_vector.pxd,sha256=UqpeZU6jrMxwqqKBPTqNXlBZNbNECTJVAvfOUz1Df84,1717 +sklearn/utils/arrayfuncs.cpython-310-x86_64-linux-gnu.so,sha256=ytyNE50WQkSCOLXJhVGX913OVv8ZwCNYQ1Ms6BE3SbI,307089 +sklearn/utils/class_weight.py,sha256=UEwjK6R1ud5PyQFKEdC8wlW7mdkZgAji5CN9MnezDFY,8245 +sklearn/utils/deprecation.py,sha256=PcrmDIaYaRzTOsvdjUlZ4lwYJKXmdA99Pq6vt-lZksc,3295 +sklearn/utils/discovery.py,sha256=mufDzgpLrGyfKP1HPP8fjXmygKAdbYB0o2DP2LwKWH4,9109 +sklearn/utils/estimator_checks.py,sha256=NJ3pxU0sRbr661IJq2Jp3AIIKF07dXx9Or4NWeeSQuM,167648 +sklearn/utils/extmath.py,sha256=qPcNcMhQkrfEPzaDKPBSPnJWDnhF_SLjaXwX6L5XqJ8,44378 +sklearn/utils/fixes.py,sha256=CQWtRmQO9XFjV5Fsdc8rX8fHrq1VNlOj70ybeLZjUY8,14146 +sklearn/utils/graph.py,sha256=r0fWiMj5YmugSi3XPcTig2ICtZZmfGHOxdrpYIzuPGc,5852 +sklearn/utils/metadata_routing.py,sha256=KzD7vN_MTm_PRNBr_f4qgPilWS8zZ1lL_nnpJJVLI4c,958 +sklearn/utils/metaestimators.py,sha256=vlI1JSQfkXMp4ciM12xWid7kJW9qh5ynpwvoVhXsRrw,5869 +sklearn/utils/multiclass.py,sha256=GheesGFRDFAam8j04ClHJBggPNl0dAie2q9J5Q06ibU,18935 +sklearn/utils/murmurhash.cpython-310-x86_64-linux-gnu.so,sha256=Ia5cUKQdmvUWcO-uhq4kD8KS53bCnv3IKPCBJbqTlao,254273 +sklearn/utils/murmurhash.pxd,sha256=ayAPsMu45zckS93jB0fie2lv8b1-FLfOh_uGDw-0Ev4,864 +sklearn/utils/optimize.py,sha256=V7A0ucjC_P7FosmgxRbPKntA4WEKBgvtM6-TCOt9hDs,9116 +sklearn/utils/parallel.py,sha256=UrPPun6NuBN87NkZ9LUKezV5VJOqBMC4xuuRZZUEvME,4256 +sklearn/utils/random.py,sha256=Tews9aAstPUksIxYjVIg-wP1R7_LA50woOeMZjWi060,3723 +sklearn/utils/sparsefuncs.py,sha256=TpyYWfgmBHXmGbNvZ95chDGtkFEjlHiJRfa0jH97LSs,22673 +sklearn/utils/sparsefuncs_fast.cpython-310-x86_64-linux-gnu.so,sha256=LZHO1XE7ASJ-fyGXQg092DQqsfE-I_aJwUG81dAAq-Y,839729 +sklearn/utils/stats.py,sha256=fdiYo9g8IkeUkw7TsVomxWqhQbsCqHLNmEphVRoLaDY,2357 +sklearn/utils/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sklearn/utils/tests/__pycache__/__init__.cpython-310.pyc,, +sklearn/utils/tests/__pycache__/test_arpack.cpython-310.pyc,, +sklearn/utils/tests/__pycache__/test_array_api.cpython-310.pyc,, +sklearn/utils/tests/__pycache__/test_arrayfuncs.cpython-310.pyc,, +sklearn/utils/tests/__pycache__/test_bunch.cpython-310.pyc,, +sklearn/utils/tests/__pycache__/test_class_weight.cpython-310.pyc,, +sklearn/utils/tests/__pycache__/test_cython_blas.cpython-310.pyc,, +sklearn/utils/tests/__pycache__/test_cython_templating.cpython-310.pyc,, +sklearn/utils/tests/__pycache__/test_deprecation.cpython-310.pyc,, +sklearn/utils/tests/__pycache__/test_encode.cpython-310.pyc,, +sklearn/utils/tests/__pycache__/test_estimator_checks.cpython-310.pyc,, +sklearn/utils/tests/__pycache__/test_estimator_html_repr.cpython-310.pyc,, +sklearn/utils/tests/__pycache__/test_extmath.cpython-310.pyc,, +sklearn/utils/tests/__pycache__/test_fast_dict.cpython-310.pyc,, +sklearn/utils/tests/__pycache__/test_fixes.cpython-310.pyc,, +sklearn/utils/tests/__pycache__/test_graph.cpython-310.pyc,, +sklearn/utils/tests/__pycache__/test_metaestimators.cpython-310.pyc,, +sklearn/utils/tests/__pycache__/test_mocking.cpython-310.pyc,, +sklearn/utils/tests/__pycache__/test_multiclass.cpython-310.pyc,, +sklearn/utils/tests/__pycache__/test_murmurhash.cpython-310.pyc,, +sklearn/utils/tests/__pycache__/test_optimize.cpython-310.pyc,, +sklearn/utils/tests/__pycache__/test_parallel.cpython-310.pyc,, +sklearn/utils/tests/__pycache__/test_param_validation.cpython-310.pyc,, +sklearn/utils/tests/__pycache__/test_plotting.cpython-310.pyc,, +sklearn/utils/tests/__pycache__/test_pprint.cpython-310.pyc,, +sklearn/utils/tests/__pycache__/test_random.cpython-310.pyc,, +sklearn/utils/tests/__pycache__/test_response.cpython-310.pyc,, +sklearn/utils/tests/__pycache__/test_seq_dataset.cpython-310.pyc,, +sklearn/utils/tests/__pycache__/test_set_output.cpython-310.pyc,, +sklearn/utils/tests/__pycache__/test_shortest_path.cpython-310.pyc,, +sklearn/utils/tests/__pycache__/test_show_versions.cpython-310.pyc,, +sklearn/utils/tests/__pycache__/test_sparsefuncs.cpython-310.pyc,, +sklearn/utils/tests/__pycache__/test_stats.cpython-310.pyc,, +sklearn/utils/tests/__pycache__/test_tags.cpython-310.pyc,, +sklearn/utils/tests/__pycache__/test_testing.cpython-310.pyc,, +sklearn/utils/tests/__pycache__/test_typedefs.cpython-310.pyc,, +sklearn/utils/tests/__pycache__/test_utils.cpython-310.pyc,, +sklearn/utils/tests/__pycache__/test_validation.cpython-310.pyc,, +sklearn/utils/tests/__pycache__/test_weight_vector.cpython-310.pyc,, +sklearn/utils/tests/test_arpack.py,sha256=EL3_6a1iDpl8Q-0A8iv6YrwycX0zBwWsL_6cEm3i6lo,490 +sklearn/utils/tests/test_array_api.py,sha256=FT31mXXZVAfe0GlqAs_Hd8cNfAx_ByopltXDoWElGl8,10842 +sklearn/utils/tests/test_arrayfuncs.py,sha256=YKV_XxKozQ5T2CKjovxlGp3orIq0GE5PzHzzbFWVpAY,1310 +sklearn/utils/tests/test_bunch.py,sha256=QZXKwtgneO2wcnnrbMVM_QNfVlVec8eLw0JYtL_ExMI,813 +sklearn/utils/tests/test_class_weight.py,sha256=ULBQ2kTnf1vXVq5piE7RykNtcBjQ4wztsVlmowRFxdc,12309 +sklearn/utils/tests/test_cython_blas.py,sha256=qLgkzvgCOhK5TB1OTGr3Y4ouSQ233srPFXPH8z9v4Y8,6459 +sklearn/utils/tests/test_cython_templating.py,sha256=9VKL_qffGetSHP5o63bhvP0P4OswuFvCsCFKnIABREc,834 +sklearn/utils/tests/test_deprecation.py,sha256=ZFC-uU7o1yJo-iWQ6dbJjyxdkv-YHXxvmNqaTzAjSZc,2023 +sklearn/utils/tests/test_encode.py,sha256=QiiG0ArBGF7ENYrvcgPGwjYgUdn3W6Ch_GE9VEF2DWI,9603 +sklearn/utils/tests/test_estimator_checks.py,sha256=Q0vX0NOsIfmRvoszyYjYedwSidtsxUoJMjijHgNy_zI,43757 +sklearn/utils/tests/test_estimator_html_repr.py,sha256=laE-N_y9W71guyDJto2DHnXoF8OIXh9szLCigO4chOs,18057 +sklearn/utils/tests/test_extmath.py,sha256=fxjeDqqD75B1tt-uDUK5vMVCB_ivMwi2gSasxKaIgOM,36993 +sklearn/utils/tests/test_fast_dict.py,sha256=68dA5PzUI7thW9NFY0oo1Me1aqJdx8z02xThJsUTgqo,1356 +sklearn/utils/tests/test_fixes.py,sha256=M5FbBx2l68m8Fg6ekuhovJ2Z8inzuB3eqUUe3whWPjQ,5722 +sklearn/utils/tests/test_graph.py,sha256=0FGOXawAnpEg2wYW5PEkJsLmIlz1zVTIgFP5IJqdXpc,3047 +sklearn/utils/tests/test_metaestimators.py,sha256=x_0agW4puaVCmqPwBrk3FrWIZeK3qgM9eNJWUxYD640,2107 +sklearn/utils/tests/test_mocking.py,sha256=bq8wqsRlN4duGu7zx0mMo99yY8KpKk6gLZC0SmfXLBE,6075 +sklearn/utils/tests/test_multiclass.py,sha256=ScMu6KDToCiGKnoIJG3HPI7vstvGOGe2eISE-nOGp2E,20238 +sklearn/utils/tests/test_murmurhash.py,sha256=u9nLrCI1mP7rFGj2OWUEpPIhC2Z8WWWSfwl-IaaOuXQ,2515 +sklearn/utils/tests/test_optimize.py,sha256=Nc3GQ-y5ppRfPoduTuvGv9DS-MmkeO-71ySJq8DOVuQ,768 +sklearn/utils/tests/test_parallel.py,sha256=mZUbOoo44Jfa54N0Bw2NL9zRLtpH4v39AXy-0_bWdGs,3650 +sklearn/utils/tests/test_param_validation.py,sha256=PjJ8-S7o5wBJ9Qmsz7MMnnk38iprXa-ejtmThZ4YMuk,24201 +sklearn/utils/tests/test_plotting.py,sha256=_qetb2NqEqQs-2sVLAydoW2VfJWnU6AixzlMzmUy0dw,2768 +sklearn/utils/tests/test_pprint.py,sha256=qm6MKEgzkfHBR-RQyI5S56Twkmzp-C4OsAPdzlJtjqE,27339 +sklearn/utils/tests/test_random.py,sha256=ItwX9BV-LvEPMuco4JoXsLPjtDh012t-PCfwFy2FPyM,7157 +sklearn/utils/tests/test_response.py,sha256=eU7uqsOKp9lVhxRpTzFvNpF2Lppnu9cVgZArtyvZx7M,12608 +sklearn/utils/tests/test_seq_dataset.py,sha256=9periHtRAYQ56vkfB7YWfAueXTEzpna51VRoctWNYHE,5890 +sklearn/utils/tests/test_set_output.py,sha256=UYJEjYeHZtY_Nn87Tz2jE3VEYf9zcpkJeABK9kYL2tM,15290 +sklearn/utils/tests/test_shortest_path.py,sha256=XN1SF7TfMo8tQCC-bUV2wK99jR32hEM7xZOl54NbIoQ,1846 +sklearn/utils/tests/test_show_versions.py,sha256=Yk726ydbUgfB9RSy_UYh9jPmriKHcI3JlWmREOTxO-8,1006 +sklearn/utils/tests/test_sparsefuncs.py,sha256=QeBQ0U-KodfZpR5N8-BZ1zzkMEyQxR7hqK6VBIesSHs,34923 +sklearn/utils/tests/test_stats.py,sha256=Phl42HdzIexmoBxQDvBh2erZo53xm9q7JTiGq_l3It8,2760 +sklearn/utils/tests/test_tags.py,sha256=1hqW8joq6t6Hr9AG00x-hp9ba9PtIM7r6az7WJ1_DCo,1396 +sklearn/utils/tests/test_testing.py,sha256=2X_0N8qp9Tg1Tfvt0GZsDEaVC3mvr1QpP6ty1WxbteA,27802 +sklearn/utils/tests/test_typedefs.py,sha256=eCKBm66loSHimj73jqVeYsOccxQQSmfq8rc-a8uYuGM,631 +sklearn/utils/tests/test_utils.py,sha256=gUwT8UREriHUFqDKGf1YD-ybOiuZZiLiLhuxF0bdiog,29562 +sklearn/utils/tests/test_validation.py,sha256=C45x183s9Tds2JZ6JLMGAduzyX3bJ4VWV0yVZw5_SR4,69302 +sklearn/utils/tests/test_weight_vector.py,sha256=eay4_mfrN7vg2ZGoXmZ06cU9CLQYBJKMR_dK6s2Wyic,665 +sklearn/utils/validation.py,sha256=GU-PcxpY7VhCY-Li4yLPvchKy8B8lTdjW-o9Re3cuts,88758 diff --git a/env-llmeval/lib/python3.10/site-packages/scikit_learn-1.4.2.dist-info/WHEEL b/env-llmeval/lib/python3.10/site-packages/scikit_learn-1.4.2.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..9bb86cf30c63df9170e9af3dd246ce6f41270402 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scikit_learn-1.4.2.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.43.0) +Root-Is-Purelib: false +Tag: cp310-cp310-manylinux_2_17_x86_64 +Tag: cp310-cp310-manylinux2014_x86_64 + diff --git a/env-llmeval/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Catamarca b/env-llmeval/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Catamarca new file mode 100644 index 0000000000000000000000000000000000000000..1dcc8d85434c9d016f170cb2f16811ebef327b77 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Catamarca differ diff --git a/env-llmeval/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Cordoba b/env-llmeval/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Cordoba new file mode 100644 index 0000000000000000000000000000000000000000..35a52e53d123b5ef5d293b3af19046630f02bb66 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Cordoba differ diff --git a/env-llmeval/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/La_Rioja b/env-llmeval/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/La_Rioja new file mode 100644 index 0000000000000000000000000000000000000000..23fca12205222be27c167e597df5086520f699cf Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/La_Rioja differ diff --git a/env-llmeval/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Salta b/env-llmeval/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Salta new file mode 100644 index 0000000000000000000000000000000000000000..58863e0436d16ef8ff8ba3d96b452086e4ae8ff5 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Salta differ diff --git a/env-llmeval/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/San_Juan b/env-llmeval/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/San_Juan new file mode 100644 index 0000000000000000000000000000000000000000..7eba33c1c5b13cbd9b7566f450d524a45cf8b65e Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/San_Juan differ diff --git a/env-llmeval/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Tucuman b/env-llmeval/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Tucuman new file mode 100644 index 0000000000000000000000000000000000000000..10556d5d856a0f33afd8da2b07a2005e7be80fb0 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Tucuman differ diff --git a/env-llmeval/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Ushuaia b/env-llmeval/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Ushuaia new file mode 100644 index 0000000000000000000000000000000000000000..e0317502769271ad0c038493df2ad2b90ec402d4 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Ushuaia differ diff --git a/env-llmeval/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/__init__.py b/env-llmeval/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/env-llmeval/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/__pycache__/__init__.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..758f69499bbcbe2fbf15a850a35e85c2f39fbf56 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/__pycache__/__init__.cpython-310.pyc differ