diff --git a/venv/lib/python3.10/site-packages/MarkupSafe-3.0.2.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/MarkupSafe-3.0.2.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/venv/lib/python3.10/site-packages/MarkupSafe-3.0.2.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/lib/python3.10/site-packages/MarkupSafe-3.0.2.dist-info/LICENSE.txt b/venv/lib/python3.10/site-packages/MarkupSafe-3.0.2.dist-info/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..9d227a0cc43c3268d15722b763bd94ad298645a1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/MarkupSafe-3.0.2.dist-info/LICENSE.txt @@ -0,0 +1,28 @@ +Copyright 2010 Pallets + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. 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. + +3. 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/venv/lib/python3.10/site-packages/MarkupSafe-3.0.2.dist-info/METADATA b/venv/lib/python3.10/site-packages/MarkupSafe-3.0.2.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..82261f2a4657ed8938325e2f449c1d6cbd4ea7fc --- /dev/null +++ b/venv/lib/python3.10/site-packages/MarkupSafe-3.0.2.dist-info/METADATA @@ -0,0 +1,92 @@ +Metadata-Version: 2.1 +Name: MarkupSafe +Version: 3.0.2 +Summary: Safely add untrusted strings to HTML/XML markup. +Maintainer-email: Pallets +License: Copyright 2010 Pallets + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. 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. + + 3. 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. + +Project-URL: Donate, https://palletsprojects.com/donate +Project-URL: Documentation, https://markupsafe.palletsprojects.com/ +Project-URL: Changes, https://markupsafe.palletsprojects.com/changes/ +Project-URL: Source, https://github.com/pallets/markupsafe/ +Project-URL: Chat, https://discord.gg/pallets +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Web Environment +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content +Classifier: Topic :: Text Processing :: Markup :: HTML +Classifier: Typing :: Typed +Requires-Python: >=3.9 +Description-Content-Type: text/markdown +License-File: LICENSE.txt + +# MarkupSafe + +MarkupSafe implements a text object that escapes characters so it is +safe to use in HTML and XML. Characters that have special meanings are +replaced so that they display as the actual characters. This mitigates +injection attacks, meaning untrusted user input can safely be displayed +on a page. + + +## Examples + +```pycon +>>> from markupsafe import Markup, escape + +>>> # escape replaces special characters and wraps in Markup +>>> escape("") +Markup('<script>alert(document.cookie);</script>') + +>>> # wrap in Markup to mark text "safe" and prevent escaping +>>> Markup("Hello") +Markup('hello') + +>>> escape(Markup("Hello")) +Markup('hello') + +>>> # Markup is a str subclass +>>> # methods and operators escape their arguments +>>> template = Markup("Hello {name}") +>>> template.format(name='"World"') +Markup('Hello "World"') +``` + +## Donate + +The Pallets organization develops and supports MarkupSafe and other +popular packages. In order to grow the community of contributors and +users, and allow the maintainers to devote more time to the projects, +[please donate today][]. + +[please donate today]: https://palletsprojects.com/donate diff --git a/venv/lib/python3.10/site-packages/MarkupSafe-3.0.2.dist-info/RECORD b/venv/lib/python3.10/site-packages/MarkupSafe-3.0.2.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..6622392965d37c3d3e717dade55e75a812313ae6 --- /dev/null +++ b/venv/lib/python3.10/site-packages/MarkupSafe-3.0.2.dist-info/RECORD @@ -0,0 +1,14 @@ +MarkupSafe-3.0.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +MarkupSafe-3.0.2.dist-info/LICENSE.txt,sha256=SJqOEQhQntmKN7uYPhHg9-HTHwvY-Zp5yESOf_N9B-o,1475 +MarkupSafe-3.0.2.dist-info/METADATA,sha256=aAwbZhSmXdfFuMM-rEHpeiHRkBOGESyVLJIuwzHP-nw,3975 +MarkupSafe-3.0.2.dist-info/RECORD,, +MarkupSafe-3.0.2.dist-info/WHEEL,sha256=_kVlewavvOSnwZE_whBk3jlE_Ob-nL5GvlVcLkpXSD8,151 +MarkupSafe-3.0.2.dist-info/top_level.txt,sha256=qy0Plje5IJuvsCBjejJyhDCjEAdcDLK_2agVcex8Z6U,11 +markupsafe/__init__.py,sha256=sr-U6_27DfaSrj5jnHYxWN-pvhM27sjlDplMDPZKm7k,13214 +markupsafe/__pycache__/__init__.cpython-310.pyc,, +markupsafe/__pycache__/_native.cpython-310.pyc,, +markupsafe/_native.py,sha256=hSLs8Jmz5aqayuengJJ3kdT5PwNpBWpKrmQSdipndC8,210 +markupsafe/_speedups.c,sha256=O7XulmTo-epI6n2FtMVOrJXl8EAaIwD2iNYmBI5SEoQ,4149 +markupsafe/_speedups.cpython-310-x86_64-linux-gnu.so,sha256=x4RoxWgyqAEokk-AZrWvrLDxLE-dm-zZSZYV_gOiLJA,34976 +markupsafe/_speedups.pyi,sha256=ENd1bYe7gbBUf2ywyYWOGUpnXOHNJ-cgTNqetlW8h5k,41 +markupsafe/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/venv/lib/python3.10/site-packages/MarkupSafe-3.0.2.dist-info/WHEEL b/venv/lib/python3.10/site-packages/MarkupSafe-3.0.2.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..78f844eac9fa4e8d81847942242b62043486d709 --- /dev/null +++ b/venv/lib/python3.10/site-packages/MarkupSafe-3.0.2.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: setuptools (75.2.0) +Root-Is-Purelib: false +Tag: cp310-cp310-manylinux_2_17_x86_64 +Tag: cp310-cp310-manylinux2014_x86_64 + diff --git a/venv/lib/python3.10/site-packages/MarkupSafe-3.0.2.dist-info/top_level.txt b/venv/lib/python3.10/site-packages/MarkupSafe-3.0.2.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..75bf729258f9daef77370b6df1a57940f90fc23f --- /dev/null +++ b/venv/lib/python3.10/site-packages/MarkupSafe-3.0.2.dist-info/top_level.txt @@ -0,0 +1 @@ +markupsafe diff --git a/venv/lib/python3.10/site-packages/absl_py-2.3.1.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/absl_py-2.3.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/venv/lib/python3.10/site-packages/absl_py-2.3.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/lib/python3.10/site-packages/absl_py-2.3.1.dist-info/METADATA b/venv/lib/python3.10/site-packages/absl_py-2.3.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..aa710852bf76ca2a1f0429ec6296a8d049d8bcdc --- /dev/null +++ b/venv/lib/python3.10/site-packages/absl_py-2.3.1.dist-info/METADATA @@ -0,0 +1,101 @@ +Metadata-Version: 2.4 +Name: absl-py +Version: 2.3.1 +Summary: Abseil Python Common Libraries, see https://github.com/abseil/abseil-py. +Project-URL: Changelog, https://github.com/abseil/abseil-py/blob/main/CHANGELOG.md +Project-URL: Documentation, https://abseil.io/docs/python/ +Project-URL: Issues, https://github.com/abseil/abseil-py/issues +Project-URL: Source, https://github.com/abseil/abseil-py +Author: The Abseil Authors +License-Expression: Apache-2.0 +License-File: AUTHORS +License-File: LICENSE +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Operating System :: OS Independent +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: Programming Language :: Python :: 3.13 +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Requires-Python: >=3.8 +Description-Content-Type: text/markdown + +[![Package version](https://img.shields.io/pypi/v/absl-py)](https://pypi.org/project/absl-py) +[![Supported Python versions](https://img.shields.io/pypi/pyversions/absl-py.svg?style=flat-square)](https://pypi.org/project/absl-py) +[![License](https://img.shields.io/github/license/abseil/abseil-py)](https://github.com/abseil/abseil-py/blob/main/LICENSE) +[![Build Status](https://github.com/abseil/abseil-py/actions/workflows/test.yml/badge.svg?branch=main)](https://github.com/abseil/abseil-py/actions) +[![Overall downloads](https://pepy.tech/badge/absl-py)](https://pepy.tech/project/absl-py) +[![Last month downloads](https://pepy.tech/badge/absl-py/month)](https://pepy.tech/project/absl-py) + +# Abseil Python Common Libraries + +This repository is a collection of Python library code for building Python +applications. The code is collected from Google's own Python code base, and has +been extensively tested and used in production. + +## Features + +* Simple application startup +* Distributed commandline flags system +* Custom logging module with additional features +* Testing utilities + +## Getting Started + +### Installation + +To install the package, simply run: + +```bash +pip install absl-py +``` + +Or install from source: + +```bash +pip install . +``` + +### Running Tests + +To run Abseil tests, you can clone the git repo and run +[bazel](https://bazel.build/): + +```bash +git clone https://github.com/abseil/abseil-py.git +cd abseil-py +bazel test absl/... +``` + +Please also validate the type annotations against the latest mypy: + +```bash +pip install mypy +mypy absl +``` + +### Example Code + +Please refer to +[smoke_tests/sample_app.py](https://github.com/abseil/abseil-py/blob/main/smoke_tests/sample_app.py) +as an example to get started. + +## Documentation + +See the [Abseil Python Developer Guide](https://abseil.io/docs/python/). + +## Future Releases + +The current repository includes an initial set of libraries for early adoption. +More components and interoperability with Abseil C++ Common Libraries +will come in future releases. + +## License + +The Abseil Python library is licensed under the terms of the Apache +license. See [LICENSE](LICENSE) for more information. diff --git a/venv/lib/python3.10/site-packages/absl_py-2.3.1.dist-info/RECORD b/venv/lib/python3.10/site-packages/absl_py-2.3.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..0775e3ebf75b79f0e06fc1acd5e6d62ddaa75c84 --- /dev/null +++ b/venv/lib/python3.10/site-packages/absl_py-2.3.1.dist-info/RECORD @@ -0,0 +1,53 @@ +absl/__init__.py,sha256=9iJ5PwnoYh12ztceccjD2JbnSvx6d2JVElEurn9cqJk,607 +absl/__pycache__/__init__.cpython-310.pyc,, +absl/__pycache__/app.cpython-310.pyc,, +absl/__pycache__/command_name.cpython-310.pyc,, +absl/app.py,sha256=0WJpjLaYcgcXtl9NTn-i5jSEfAoweMg4SXAel2XLF0Y,15360 +absl/app.pyi,sha256=NdRh0OBqWHKnc3hEjdLaspLdu6aDHn3XP360ZPZeQE8,1885 +absl/command_name.py,sha256=FgWUMHmlX0yQxEuMPXxFxn5ayWWZSLB0cq8Vx361TpU,2283 +absl/flags/__init__.py,sha256=n_uLeSK-15_1DKLb0wXivmt6A8xvADDC87D1yoJdqVU,7665 +absl/flags/__pycache__/__init__.cpython-310.pyc,, +absl/flags/__pycache__/_argument_parser.cpython-310.pyc,, +absl/flags/__pycache__/_defines.cpython-310.pyc,, +absl/flags/__pycache__/_exceptions.cpython-310.pyc,, +absl/flags/__pycache__/_flag.cpython-310.pyc,, +absl/flags/__pycache__/_flagvalues.cpython-310.pyc,, +absl/flags/__pycache__/_helpers.cpython-310.pyc,, +absl/flags/__pycache__/_validators.cpython-310.pyc,, +absl/flags/__pycache__/_validators_classes.cpython-310.pyc,, +absl/flags/__pycache__/argparse_flags.cpython-310.pyc,, +absl/flags/_argument_parser.py,sha256=arzkHA3CbPJdJ7diqUyskdoaLtKt8Aij1EZCVH_qJHU,20629 +absl/flags/_defines.py,sha256=NAK489NGv3YMvbYj2Jzl6q89HmAtmMI65di1L_RK7XE,52895 +absl/flags/_exceptions.py,sha256=FZzlzhvkjqPImTxXqbS1pSPYKr_TvtOd5ellvoiVLDI,3619 +absl/flags/_flag.py,sha256=mdMJFklKQdCi9WsWPvUlmBRoQ2IAPW0Z0lDIKj0Lsx8,20079 +absl/flags/_flagvalues.py,sha256=cGzMsWxthqGYfpESReRSJCXjpRujosSmTT-efJW3CbQ,54364 +absl/flags/_helpers.py,sha256=MHbgtRkbNpVnrr7_NCdkFi_x3voQa-1-bypqsunHCJE,14154 +absl/flags/_validators.py,sha256=VcsJtZzohliNxsI974NECYpeozD8rswHNHXggrQ4BLo,14140 +absl/flags/_validators_classes.py,sha256=PGUWzO7v3wPOHb9leIKKzry3q-pPeKCoMB_O7prLdnY,6093 +absl/flags/argparse_flags.py,sha256=usJudgMpy3P6Vvq7-LmJNa2Rj3ygHM3hwDTGd1mbAzc,14386 +absl/logging/__init__.py,sha256=XpcmJrFEzDK2iWTlmDwtNSScSiGiNedFibWuW0tWMbk,43583 +absl/logging/__init__.pyi,sha256=39EEBOH_rAyDQJpwyito2vo4IAZP9hnw3-wXC_Gulvc,5925 +absl/logging/__pycache__/__init__.cpython-310.pyc,, +absl/logging/__pycache__/converter.cpython-310.pyc,, +absl/logging/converter.py,sha256=6eBymfv9UNkog0BGat4HPWlxC_oSqvHcQ46jnSdtaMg,6323 +absl/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +absl/testing/__init__.py,sha256=7cM57swk2T1Hc5wxmt-JpcaR6xfdPJyL_lyRqgODvuM,584 +absl/testing/__pycache__/__init__.cpython-310.pyc,, +absl/testing/__pycache__/_bazelize_command.cpython-310.pyc,, +absl/testing/__pycache__/_pretty_print_reporter.cpython-310.pyc,, +absl/testing/__pycache__/absltest.cpython-310.pyc,, +absl/testing/__pycache__/flagsaver.cpython-310.pyc,, +absl/testing/__pycache__/parameterized.cpython-310.pyc,, +absl/testing/__pycache__/xml_reporter.cpython-310.pyc,, +absl/testing/_bazelize_command.py,sha256=qpioV02ln2sBBJ9kdlHgNpKk8_wxdz2hJGKbG6EWZMI,2287 +absl/testing/_pretty_print_reporter.py,sha256=PZh9NXSXBbXDi0FOk-BOmpse8LXa92Er16tgyBRogMs,3065 +absl/testing/absltest.py,sha256=PW4c4SVlOUPSvFIhayimJY2LEbJ7BAojob6u9SBUrck,105675 +absl/testing/flagsaver.py,sha256=HIWzFyayy-Pa8TqTAXF7BtHQ7s9Uk68KE8AVVAM0o0w,13346 +absl/testing/parameterized.py,sha256=TpTlWTUXjikGeUDE45AgubvnmHsPbFNj-wUtAwT-e6E,27817 +absl/testing/xml_reporter.py,sha256=YFkM7SROW8aeoCCn8IsGZ4cqXu4x8MwL1oN42-OtPKI,21430 +absl_py-2.3.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +absl_py-2.3.1.dist-info/METADATA,sha256=2HZS24vkmHw7GQqUWcDE_FdVXjW1dgVS7pWPdWJ5Yvg,3331 +absl_py-2.3.1.dist-info/RECORD,, +absl_py-2.3.1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87 +absl_py-2.3.1.dist-info/licenses/AUTHORS,sha256=YoLudsylaQg7W5mLn4FroQMuEnuNx8RpQrhkd_xvv6U,296 +absl_py-2.3.1.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358 diff --git a/venv/lib/python3.10/site-packages/absl_py-2.3.1.dist-info/WHEEL b/venv/lib/python3.10/site-packages/absl_py-2.3.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..12228d414b6cfed7c39d3781c85c63256a1d7fb5 --- /dev/null +++ b/venv/lib/python3.10/site-packages/absl_py-2.3.1.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.27.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/venv/lib/python3.10/site-packages/absl_py-2.3.1.dist-info/licenses/AUTHORS b/venv/lib/python3.10/site-packages/absl_py-2.3.1.dist-info/licenses/AUTHORS new file mode 100644 index 0000000000000000000000000000000000000000..23b11ada16bb8e69695cf52e5994784d98054e0d --- /dev/null +++ b/venv/lib/python3.10/site-packages/absl_py-2.3.1.dist-info/licenses/AUTHORS @@ -0,0 +1,7 @@ +# This is the list of Abseil authors for copyright purposes. +# +# This does not necessarily list everyone who has contributed code, since in +# some cases, their employer may be the copyright holder. To see the full list +# of contributors, see the revision history in source control. + +Google Inc. diff --git a/venv/lib/python3.10/site-packages/absl_py-2.3.1.dist-info/licenses/LICENSE b/venv/lib/python3.10/site-packages/absl_py-2.3.1.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/venv/lib/python3.10/site-packages/absl_py-2.3.1.dist-info/licenses/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/venv/lib/python3.10/site-packages/attr/__init__.py b/venv/lib/python3.10/site-packages/attr/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5c6e0650bc4bf53806420d7ef5f881ecd2bd77ea --- /dev/null +++ b/venv/lib/python3.10/site-packages/attr/__init__.py @@ -0,0 +1,104 @@ +# SPDX-License-Identifier: MIT + +""" +Classes Without Boilerplate +""" + +from functools import partial +from typing import Callable, Literal, Protocol + +from . import converters, exceptions, filters, setters, validators +from ._cmp import cmp_using +from ._config import get_run_validators, set_run_validators +from ._funcs import asdict, assoc, astuple, has, resolve_types +from ._make import ( + NOTHING, + Attribute, + Converter, + Factory, + _Nothing, + attrib, + attrs, + evolve, + fields, + fields_dict, + make_class, + validate, +) +from ._next_gen import define, field, frozen, mutable +from ._version_info import VersionInfo + + +s = attributes = attrs +ib = attr = attrib +dataclass = partial(attrs, auto_attribs=True) # happy Easter ;) + + +class AttrsInstance(Protocol): + pass + + +NothingType = Literal[_Nothing.NOTHING] + +__all__ = [ + "NOTHING", + "Attribute", + "AttrsInstance", + "Converter", + "Factory", + "NothingType", + "asdict", + "assoc", + "astuple", + "attr", + "attrib", + "attributes", + "attrs", + "cmp_using", + "converters", + "define", + "evolve", + "exceptions", + "field", + "fields", + "fields_dict", + "filters", + "frozen", + "get_run_validators", + "has", + "ib", + "make_class", + "mutable", + "resolve_types", + "s", + "set_run_validators", + "setters", + "validate", + "validators", +] + + +def _make_getattr(mod_name: str) -> Callable: + """ + Create a metadata proxy for packaging information that uses *mod_name* in + its warnings and errors. + """ + + def __getattr__(name: str) -> str: + if name not in ("__version__", "__version_info__"): + msg = f"module {mod_name} has no attribute {name}" + raise AttributeError(msg) + + from importlib.metadata import metadata + + meta = metadata("attrs") + + if name == "__version_info__": + return VersionInfo._from_version_string(meta["version"]) + + return meta["version"] + + return __getattr__ + + +__getattr__ = _make_getattr(__name__) diff --git a/venv/lib/python3.10/site-packages/attr/__init__.pyi b/venv/lib/python3.10/site-packages/attr/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..133e50105de3cef606889f32d85f324d94ee40f3 --- /dev/null +++ b/venv/lib/python3.10/site-packages/attr/__init__.pyi @@ -0,0 +1,389 @@ +import enum +import sys + +from typing import ( + Any, + Callable, + Generic, + Literal, + Mapping, + Protocol, + Sequence, + TypeVar, + overload, +) + +# `import X as X` is required to make these public +from . import converters as converters +from . import exceptions as exceptions +from . import filters as filters +from . import setters as setters +from . import validators as validators +from ._cmp import cmp_using as cmp_using +from ._typing_compat import AttrsInstance_ +from ._version_info import VersionInfo +from attrs import ( + define as define, + field as field, + mutable as mutable, + frozen as frozen, + _EqOrderType, + _ValidatorType, + _ConverterType, + _ReprArgType, + _OnSetAttrType, + _OnSetAttrArgType, + _FieldTransformer, + _ValidatorArgType, +) + +if sys.version_info >= (3, 10): + from typing import TypeGuard, TypeAlias +else: + from typing_extensions import TypeGuard, TypeAlias + +if sys.version_info >= (3, 11): + from typing import dataclass_transform +else: + from typing_extensions import dataclass_transform + +__version__: str +__version_info__: VersionInfo +__title__: str +__description__: str +__url__: str +__uri__: str +__author__: str +__email__: str +__license__: str +__copyright__: str + +_T = TypeVar("_T") +_C = TypeVar("_C", bound=type) + +_FilterType = Callable[["Attribute[_T]", _T], bool] + +# We subclass this here to keep the protocol's qualified name clean. +class AttrsInstance(AttrsInstance_, Protocol): + pass + +_A = TypeVar("_A", bound=type[AttrsInstance]) + +class _Nothing(enum.Enum): + NOTHING = enum.auto() + +NOTHING = _Nothing.NOTHING +NothingType: TypeAlias = Literal[_Nothing.NOTHING] + +# NOTE: Factory lies about its return type to make this possible: +# `x: List[int] # = Factory(list)` +# Work around mypy issue #4554 in the common case by using an overload. + +@overload +def Factory(factory: Callable[[], _T]) -> _T: ... +@overload +def Factory( + factory: Callable[[Any], _T], + takes_self: Literal[True], +) -> _T: ... +@overload +def Factory( + factory: Callable[[], _T], + takes_self: Literal[False], +) -> _T: ... + +In = TypeVar("In") +Out = TypeVar("Out") + +class Converter(Generic[In, Out]): + @overload + def __init__(self, converter: Callable[[In], Out]) -> None: ... + @overload + def __init__( + self, + converter: Callable[[In, AttrsInstance, Attribute], Out], + *, + takes_self: Literal[True], + takes_field: Literal[True], + ) -> None: ... + @overload + def __init__( + self, + converter: Callable[[In, Attribute], Out], + *, + takes_field: Literal[True], + ) -> None: ... + @overload + def __init__( + self, + converter: Callable[[In, AttrsInstance], Out], + *, + takes_self: Literal[True], + ) -> None: ... + +class Attribute(Generic[_T]): + name: str + default: _T | None + validator: _ValidatorType[_T] | None + repr: _ReprArgType + cmp: _EqOrderType + eq: _EqOrderType + order: _EqOrderType + hash: bool | None + init: bool + converter: Converter | None + metadata: dict[Any, Any] + type: type[_T] | None + kw_only: bool + on_setattr: _OnSetAttrType + alias: str | None + + def evolve(self, **changes: Any) -> "Attribute[Any]": ... + +# NOTE: We had several choices for the annotation to use for type arg: +# 1) Type[_T] +# - Pros: Handles simple cases correctly +# - Cons: Might produce less informative errors in the case of conflicting +# TypeVars e.g. `attr.ib(default='bad', type=int)` +# 2) Callable[..., _T] +# - Pros: Better error messages than #1 for conflicting TypeVars +# - Cons: Terrible error messages for validator checks. +# e.g. attr.ib(type=int, validator=validate_str) +# -> error: Cannot infer function type argument +# 3) type (and do all of the work in the mypy plugin) +# - Pros: Simple here, and we could customize the plugin with our own errors. +# - Cons: Would need to write mypy plugin code to handle all the cases. +# We chose option #1. + +# `attr` lies about its return type to make the following possible: +# attr() -> Any +# attr(8) -> int +# attr(validator=) -> Whatever the callable expects. +# This makes this type of assignments possible: +# x: int = attr(8) +# +# This form catches explicit None or no default but with no other arguments +# returns Any. +@overload +def attrib( + default: None = ..., + validator: None = ..., + repr: _ReprArgType = ..., + cmp: _EqOrderType | None = ..., + hash: bool | None = ..., + init: bool = ..., + metadata: Mapping[Any, Any] | None = ..., + type: None = ..., + converter: None = ..., + factory: None = ..., + kw_only: bool = ..., + eq: _EqOrderType | None = ..., + order: _EqOrderType | None = ..., + on_setattr: _OnSetAttrArgType | None = ..., + alias: str | None = ..., +) -> Any: ... + +# This form catches an explicit None or no default and infers the type from the +# other arguments. +@overload +def attrib( + default: None = ..., + validator: _ValidatorArgType[_T] | None = ..., + repr: _ReprArgType = ..., + cmp: _EqOrderType | None = ..., + hash: bool | None = ..., + init: bool = ..., + metadata: Mapping[Any, Any] | None = ..., + type: type[_T] | None = ..., + converter: _ConverterType + | list[_ConverterType] + | tuple[_ConverterType] + | None = ..., + factory: Callable[[], _T] | None = ..., + kw_only: bool = ..., + eq: _EqOrderType | None = ..., + order: _EqOrderType | None = ..., + on_setattr: _OnSetAttrArgType | None = ..., + alias: str | None = ..., +) -> _T: ... + +# This form catches an explicit default argument. +@overload +def attrib( + default: _T, + validator: _ValidatorArgType[_T] | None = ..., + repr: _ReprArgType = ..., + cmp: _EqOrderType | None = ..., + hash: bool | None = ..., + init: bool = ..., + metadata: Mapping[Any, Any] | None = ..., + type: type[_T] | None = ..., + converter: _ConverterType + | list[_ConverterType] + | tuple[_ConverterType] + | None = ..., + factory: Callable[[], _T] | None = ..., + kw_only: bool = ..., + eq: _EqOrderType | None = ..., + order: _EqOrderType | None = ..., + on_setattr: _OnSetAttrArgType | None = ..., + alias: str | None = ..., +) -> _T: ... + +# This form covers type=non-Type: e.g. forward references (str), Any +@overload +def attrib( + default: _T | None = ..., + validator: _ValidatorArgType[_T] | None = ..., + repr: _ReprArgType = ..., + cmp: _EqOrderType | None = ..., + hash: bool | None = ..., + init: bool = ..., + metadata: Mapping[Any, Any] | None = ..., + type: object = ..., + converter: _ConverterType + | list[_ConverterType] + | tuple[_ConverterType] + | None = ..., + factory: Callable[[], _T] | None = ..., + kw_only: bool = ..., + eq: _EqOrderType | None = ..., + order: _EqOrderType | None = ..., + on_setattr: _OnSetAttrArgType | None = ..., + alias: str | None = ..., +) -> Any: ... +@overload +@dataclass_transform(order_default=True, field_specifiers=(attrib, field)) +def attrs( + maybe_cls: _C, + these: dict[str, Any] | None = ..., + repr_ns: str | None = ..., + repr: bool = ..., + cmp: _EqOrderType | None = ..., + hash: bool | None = ..., + init: bool = ..., + slots: bool = ..., + frozen: bool = ..., + weakref_slot: bool = ..., + str: bool = ..., + auto_attribs: bool = ..., + kw_only: bool = ..., + cache_hash: bool = ..., + auto_exc: bool = ..., + eq: _EqOrderType | None = ..., + order: _EqOrderType | None = ..., + auto_detect: bool = ..., + collect_by_mro: bool = ..., + getstate_setstate: bool | None = ..., + on_setattr: _OnSetAttrArgType | None = ..., + field_transformer: _FieldTransformer | None = ..., + match_args: bool = ..., + unsafe_hash: bool | None = ..., +) -> _C: ... +@overload +@dataclass_transform(order_default=True, field_specifiers=(attrib, field)) +def attrs( + maybe_cls: None = ..., + these: dict[str, Any] | None = ..., + repr_ns: str | None = ..., + repr: bool = ..., + cmp: _EqOrderType | None = ..., + hash: bool | None = ..., + init: bool = ..., + slots: bool = ..., + frozen: bool = ..., + weakref_slot: bool = ..., + str: bool = ..., + auto_attribs: bool = ..., + kw_only: bool = ..., + cache_hash: bool = ..., + auto_exc: bool = ..., + eq: _EqOrderType | None = ..., + order: _EqOrderType | None = ..., + auto_detect: bool = ..., + collect_by_mro: bool = ..., + getstate_setstate: bool | None = ..., + on_setattr: _OnSetAttrArgType | None = ..., + field_transformer: _FieldTransformer | None = ..., + match_args: bool = ..., + unsafe_hash: bool | None = ..., +) -> Callable[[_C], _C]: ... +def fields(cls: type[AttrsInstance]) -> Any: ... +def fields_dict(cls: type[AttrsInstance]) -> dict[str, Attribute[Any]]: ... +def validate(inst: AttrsInstance) -> None: ... +def resolve_types( + cls: _A, + globalns: dict[str, Any] | None = ..., + localns: dict[str, Any] | None = ..., + attribs: list[Attribute[Any]] | None = ..., + include_extras: bool = ..., +) -> _A: ... + +# TODO: add support for returning a proper attrs class from the mypy plugin +# we use Any instead of _CountingAttr so that e.g. `make_class('Foo', +# [attr.ib()])` is valid +def make_class( + name: str, + attrs: list[str] | tuple[str, ...] | dict[str, Any], + bases: tuple[type, ...] = ..., + class_body: dict[str, Any] | None = ..., + repr_ns: str | None = ..., + repr: bool = ..., + cmp: _EqOrderType | None = ..., + hash: bool | None = ..., + init: bool = ..., + slots: bool = ..., + frozen: bool = ..., + weakref_slot: bool = ..., + str: bool = ..., + auto_attribs: bool = ..., + kw_only: bool = ..., + cache_hash: bool = ..., + auto_exc: bool = ..., + eq: _EqOrderType | None = ..., + order: _EqOrderType | None = ..., + collect_by_mro: bool = ..., + on_setattr: _OnSetAttrArgType | None = ..., + field_transformer: _FieldTransformer | None = ..., +) -> type: ... + +# _funcs -- + +# TODO: add support for returning TypedDict from the mypy plugin +# FIXME: asdict/astuple do not honor their factory args. Waiting on one of +# these: +# https://github.com/python/mypy/issues/4236 +# https://github.com/python/typing/issues/253 +# XXX: remember to fix attrs.asdict/astuple too! +def asdict( + inst: AttrsInstance, + recurse: bool = ..., + filter: _FilterType[Any] | None = ..., + dict_factory: type[Mapping[Any, Any]] = ..., + retain_collection_types: bool = ..., + value_serializer: Callable[[type, Attribute[Any], Any], Any] | None = ..., + tuple_keys: bool | None = ..., +) -> dict[str, Any]: ... + +# TODO: add support for returning NamedTuple from the mypy plugin +def astuple( + inst: AttrsInstance, + recurse: bool = ..., + filter: _FilterType[Any] | None = ..., + tuple_factory: type[Sequence[Any]] = ..., + retain_collection_types: bool = ..., +) -> tuple[Any, ...]: ... +def has(cls: type) -> TypeGuard[type[AttrsInstance]]: ... +def assoc(inst: _T, **changes: Any) -> _T: ... +def evolve(inst: _T, **changes: Any) -> _T: ... + +# _config -- + +def set_run_validators(run: bool) -> None: ... +def get_run_validators() -> bool: ... + +# aliases -- + +s = attributes = attrs +ib = attr = attrib +dataclass = attrs # Technically, partial(attrs, auto_attribs=True) ;) diff --git a/venv/lib/python3.10/site-packages/attr/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/attr/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..981e0a755f347c0dd69a6df90a47ab1fe3d3f1d1 Binary files /dev/null and b/venv/lib/python3.10/site-packages/attr/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/attr/__pycache__/_cmp.cpython-310.pyc b/venv/lib/python3.10/site-packages/attr/__pycache__/_cmp.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d31bedb334191cbfe3cd4596dc8109f2dbc98a6 Binary files /dev/null and b/venv/lib/python3.10/site-packages/attr/__pycache__/_cmp.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/attr/__pycache__/_compat.cpython-310.pyc b/venv/lib/python3.10/site-packages/attr/__pycache__/_compat.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c1b2c6b4c9435a6137d5f65c3a8f5bdc3dcbacb2 Binary files /dev/null and b/venv/lib/python3.10/site-packages/attr/__pycache__/_compat.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/attr/__pycache__/_config.cpython-310.pyc b/venv/lib/python3.10/site-packages/attr/__pycache__/_config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..044d5a63bfb235b829bc58dba6e202ef57d922bf Binary files /dev/null and b/venv/lib/python3.10/site-packages/attr/__pycache__/_config.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/attr/__pycache__/_funcs.cpython-310.pyc b/venv/lib/python3.10/site-packages/attr/__pycache__/_funcs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..63dbb0b44af241c3a55f059c033294fdc01da9e1 Binary files /dev/null and b/venv/lib/python3.10/site-packages/attr/__pycache__/_funcs.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/attr/__pycache__/_make.cpython-310.pyc b/venv/lib/python3.10/site-packages/attr/__pycache__/_make.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f144999385fe81ba0ed68e2890495aa56894bae5 Binary files /dev/null and b/venv/lib/python3.10/site-packages/attr/__pycache__/_make.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/attr/__pycache__/_next_gen.cpython-310.pyc b/venv/lib/python3.10/site-packages/attr/__pycache__/_next_gen.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9ea3e3826f137bdf0d57f3d0e2ad5d99db9d32b Binary files /dev/null and b/venv/lib/python3.10/site-packages/attr/__pycache__/_next_gen.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/attr/__pycache__/_version_info.cpython-310.pyc b/venv/lib/python3.10/site-packages/attr/__pycache__/_version_info.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea2e1e4166ffc43b22d55656c7dd61ef4fa34616 Binary files /dev/null and b/venv/lib/python3.10/site-packages/attr/__pycache__/_version_info.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/attr/__pycache__/converters.cpython-310.pyc b/venv/lib/python3.10/site-packages/attr/__pycache__/converters.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca3d0249271dbf65b7a6db8cbccb09e15bbdce9e Binary files /dev/null and b/venv/lib/python3.10/site-packages/attr/__pycache__/converters.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/attr/__pycache__/exceptions.cpython-310.pyc b/venv/lib/python3.10/site-packages/attr/__pycache__/exceptions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a8a1db5d8601988c530a98efd134761b47c077e Binary files /dev/null and b/venv/lib/python3.10/site-packages/attr/__pycache__/exceptions.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/attr/__pycache__/filters.cpython-310.pyc b/venv/lib/python3.10/site-packages/attr/__pycache__/filters.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c5470c6f1be275a614178840c6dae8c0b409d37a Binary files /dev/null and b/venv/lib/python3.10/site-packages/attr/__pycache__/filters.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/attr/__pycache__/setters.cpython-310.pyc b/venv/lib/python3.10/site-packages/attr/__pycache__/setters.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00b48e77477184086bbc4bcac4edbaade65a65f2 Binary files /dev/null and b/venv/lib/python3.10/site-packages/attr/__pycache__/setters.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/attr/__pycache__/validators.cpython-310.pyc b/venv/lib/python3.10/site-packages/attr/__pycache__/validators.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cec46c87280e7a80b5f55d7e0abc8490d2643820 Binary files /dev/null and b/venv/lib/python3.10/site-packages/attr/__pycache__/validators.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/attr/_cmp.py b/venv/lib/python3.10/site-packages/attr/_cmp.py new file mode 100644 index 0000000000000000000000000000000000000000..09bab491f83ef4d15129f34b5f5a9e69bb34d63c --- /dev/null +++ b/venv/lib/python3.10/site-packages/attr/_cmp.py @@ -0,0 +1,160 @@ +# SPDX-License-Identifier: MIT + + +import functools +import types + +from ._make import __ne__ + + +_operation_names = {"eq": "==", "lt": "<", "le": "<=", "gt": ">", "ge": ">="} + + +def cmp_using( + eq=None, + lt=None, + le=None, + gt=None, + ge=None, + require_same_type=True, + class_name="Comparable", +): + """ + Create a class that can be passed into `attrs.field`'s ``eq``, ``order``, + and ``cmp`` arguments to customize field comparison. + + The resulting class will have a full set of ordering methods if at least + one of ``{lt, le, gt, ge}`` and ``eq`` are provided. + + Args: + eq (typing.Callable | None): + Callable used to evaluate equality of two objects. + + lt (typing.Callable | None): + Callable used to evaluate whether one object is less than another + object. + + le (typing.Callable | None): + Callable used to evaluate whether one object is less than or equal + to another object. + + gt (typing.Callable | None): + Callable used to evaluate whether one object is greater than + another object. + + ge (typing.Callable | None): + Callable used to evaluate whether one object is greater than or + equal to another object. + + require_same_type (bool): + When `True`, equality and ordering methods will return + `NotImplemented` if objects are not of the same type. + + class_name (str | None): Name of class. Defaults to "Comparable". + + See `comparison` for more details. + + .. versionadded:: 21.1.0 + """ + + body = { + "__slots__": ["value"], + "__init__": _make_init(), + "_requirements": [], + "_is_comparable_to": _is_comparable_to, + } + + # Add operations. + num_order_functions = 0 + has_eq_function = False + + if eq is not None: + has_eq_function = True + body["__eq__"] = _make_operator("eq", eq) + body["__ne__"] = __ne__ + + if lt is not None: + num_order_functions += 1 + body["__lt__"] = _make_operator("lt", lt) + + if le is not None: + num_order_functions += 1 + body["__le__"] = _make_operator("le", le) + + if gt is not None: + num_order_functions += 1 + body["__gt__"] = _make_operator("gt", gt) + + if ge is not None: + num_order_functions += 1 + body["__ge__"] = _make_operator("ge", ge) + + type_ = types.new_class( + class_name, (object,), {}, lambda ns: ns.update(body) + ) + + # Add same type requirement. + if require_same_type: + type_._requirements.append(_check_same_type) + + # Add total ordering if at least one operation was defined. + if 0 < num_order_functions < 4: + if not has_eq_function: + # functools.total_ordering requires __eq__ to be defined, + # so raise early error here to keep a nice stack. + msg = "eq must be define is order to complete ordering from lt, le, gt, ge." + raise ValueError(msg) + type_ = functools.total_ordering(type_) + + return type_ + + +def _make_init(): + """ + Create __init__ method. + """ + + def __init__(self, value): + """ + Initialize object with *value*. + """ + self.value = value + + return __init__ + + +def _make_operator(name, func): + """ + Create operator method. + """ + + def method(self, other): + if not self._is_comparable_to(other): + return NotImplemented + + result = func(self.value, other.value) + if result is NotImplemented: + return NotImplemented + + return result + + method.__name__ = f"__{name}__" + method.__doc__ = ( + f"Return a {_operation_names[name]} b. Computed by attrs." + ) + + return method + + +def _is_comparable_to(self, other): + """ + Check whether `other` is comparable to `self`. + """ + return all(func(self, other) for func in self._requirements) + + +def _check_same_type(self, other): + """ + Return True if *self* and *other* are of the same type, False otherwise. + """ + return other.value.__class__ is self.value.__class__ diff --git a/venv/lib/python3.10/site-packages/attr/_cmp.pyi b/venv/lib/python3.10/site-packages/attr/_cmp.pyi new file mode 100644 index 0000000000000000000000000000000000000000..cc7893b04520afa719b1412c7646c3c1b39bf94b --- /dev/null +++ b/venv/lib/python3.10/site-packages/attr/_cmp.pyi @@ -0,0 +1,13 @@ +from typing import Any, Callable + +_CompareWithType = Callable[[Any, Any], bool] + +def cmp_using( + eq: _CompareWithType | None = ..., + lt: _CompareWithType | None = ..., + le: _CompareWithType | None = ..., + gt: _CompareWithType | None = ..., + ge: _CompareWithType | None = ..., + require_same_type: bool = ..., + class_name: str = ..., +) -> type: ... diff --git a/venv/lib/python3.10/site-packages/attr/_compat.py b/venv/lib/python3.10/site-packages/attr/_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..22fcd78387b7b36f005ec5eee3fbf784ba87a93d --- /dev/null +++ b/venv/lib/python3.10/site-packages/attr/_compat.py @@ -0,0 +1,94 @@ +# SPDX-License-Identifier: MIT + +import inspect +import platform +import sys +import threading + +from collections.abc import Mapping, Sequence # noqa: F401 +from typing import _GenericAlias + + +PYPY = platform.python_implementation() == "PyPy" +PY_3_9_PLUS = sys.version_info[:2] >= (3, 9) +PY_3_10_PLUS = sys.version_info[:2] >= (3, 10) +PY_3_11_PLUS = sys.version_info[:2] >= (3, 11) +PY_3_12_PLUS = sys.version_info[:2] >= (3, 12) +PY_3_13_PLUS = sys.version_info[:2] >= (3, 13) +PY_3_14_PLUS = sys.version_info[:2] >= (3, 14) + + +if PY_3_14_PLUS: # pragma: no cover + import annotationlib + + _get_annotations = annotationlib.get_annotations + +else: + + def _get_annotations(cls): + """ + Get annotations for *cls*. + """ + return cls.__dict__.get("__annotations__", {}) + + +class _AnnotationExtractor: + """ + Extract type annotations from a callable, returning None whenever there + is none. + """ + + __slots__ = ["sig"] + + def __init__(self, callable): + try: + self.sig = inspect.signature(callable) + except (ValueError, TypeError): # inspect failed + self.sig = None + + def get_first_param_type(self): + """ + Return the type annotation of the first argument if it's not empty. + """ + if not self.sig: + return None + + params = list(self.sig.parameters.values()) + if params and params[0].annotation is not inspect.Parameter.empty: + return params[0].annotation + + return None + + def get_return_type(self): + """ + Return the return type if it's not empty. + """ + if ( + self.sig + and self.sig.return_annotation is not inspect.Signature.empty + ): + return self.sig.return_annotation + + return None + + +# Thread-local global to track attrs instances which are already being repr'd. +# This is needed because there is no other (thread-safe) way to pass info +# about the instances that are already being repr'd through the call stack +# in order to ensure we don't perform infinite recursion. +# +# For instance, if an instance contains a dict which contains that instance, +# we need to know that we're already repr'ing the outside instance from within +# the dict's repr() call. +# +# This lives here rather than in _make.py so that the functions in _make.py +# don't have a direct reference to the thread-local in their globals dict. +# If they have such a reference, it breaks cloudpickle. +repr_context = threading.local() + + +def get_generic_base(cl): + """If this is a generic class (A[str]), return the generic base for it.""" + if cl.__class__ is _GenericAlias: + return cl.__origin__ + return None diff --git a/venv/lib/python3.10/site-packages/attr/_config.py b/venv/lib/python3.10/site-packages/attr/_config.py new file mode 100644 index 0000000000000000000000000000000000000000..4b257726fb1e8b95583ecc3eee8d153336dc4089 --- /dev/null +++ b/venv/lib/python3.10/site-packages/attr/_config.py @@ -0,0 +1,31 @@ +# SPDX-License-Identifier: MIT + +__all__ = ["get_run_validators", "set_run_validators"] + +_run_validators = True + + +def set_run_validators(run): + """ + Set whether or not validators are run. By default, they are run. + + .. deprecated:: 21.3.0 It will not be removed, but it also will not be + moved to new ``attrs`` namespace. Use `attrs.validators.set_disabled()` + instead. + """ + if not isinstance(run, bool): + msg = "'run' must be bool." + raise TypeError(msg) + global _run_validators + _run_validators = run + + +def get_run_validators(): + """ + Return whether or not validators are run. + + .. deprecated:: 21.3.0 It will not be removed, but it also will not be + moved to new ``attrs`` namespace. Use `attrs.validators.get_disabled()` + instead. + """ + return _run_validators diff --git a/venv/lib/python3.10/site-packages/attr/_funcs.py b/venv/lib/python3.10/site-packages/attr/_funcs.py new file mode 100644 index 0000000000000000000000000000000000000000..c39fb8aa5a9426c18157253aad4b0168084eeb1a --- /dev/null +++ b/venv/lib/python3.10/site-packages/attr/_funcs.py @@ -0,0 +1,468 @@ +# SPDX-License-Identifier: MIT + + +import copy + +from ._compat import PY_3_9_PLUS, get_generic_base +from ._make import _OBJ_SETATTR, NOTHING, fields +from .exceptions import AttrsAttributeNotFoundError + + +def asdict( + inst, + recurse=True, + filter=None, + dict_factory=dict, + retain_collection_types=False, + value_serializer=None, +): + """ + Return the *attrs* attribute values of *inst* as a dict. + + Optionally recurse into other *attrs*-decorated classes. + + Args: + inst: Instance of an *attrs*-decorated class. + + recurse (bool): Recurse into classes that are also *attrs*-decorated. + + filter (~typing.Callable): + A callable whose return code determines whether an attribute or + element is included (`True`) or dropped (`False`). Is called with + the `attrs.Attribute` as the first argument and the value as the + second argument. + + dict_factory (~typing.Callable): + A callable to produce dictionaries from. For example, to produce + ordered dictionaries instead of normal Python dictionaries, pass in + ``collections.OrderedDict``. + + retain_collection_types (bool): + Do not convert to `list` when encountering an attribute whose type + is `tuple` or `set`. Only meaningful if *recurse* is `True`. + + value_serializer (typing.Callable | None): + A hook that is called for every attribute or dict key/value. It + receives the current instance, field and value and must return the + (updated) value. The hook is run *after* the optional *filter* has + been applied. + + Returns: + Return type of *dict_factory*. + + Raises: + attrs.exceptions.NotAnAttrsClassError: + If *cls* is not an *attrs* class. + + .. versionadded:: 16.0.0 *dict_factory* + .. versionadded:: 16.1.0 *retain_collection_types* + .. versionadded:: 20.3.0 *value_serializer* + .. versionadded:: 21.3.0 + If a dict has a collection for a key, it is serialized as a tuple. + """ + attrs = fields(inst.__class__) + rv = dict_factory() + for a in attrs: + v = getattr(inst, a.name) + if filter is not None and not filter(a, v): + continue + + if value_serializer is not None: + v = value_serializer(inst, a, v) + + if recurse is True: + if has(v.__class__): + rv[a.name] = asdict( + v, + recurse=True, + filter=filter, + dict_factory=dict_factory, + retain_collection_types=retain_collection_types, + value_serializer=value_serializer, + ) + elif isinstance(v, (tuple, list, set, frozenset)): + cf = v.__class__ if retain_collection_types is True else list + items = [ + _asdict_anything( + i, + is_key=False, + filter=filter, + dict_factory=dict_factory, + retain_collection_types=retain_collection_types, + value_serializer=value_serializer, + ) + for i in v + ] + try: + rv[a.name] = cf(items) + except TypeError: + if not issubclass(cf, tuple): + raise + # Workaround for TypeError: cf.__new__() missing 1 required + # positional argument (which appears, for a namedturle) + rv[a.name] = cf(*items) + elif isinstance(v, dict): + df = dict_factory + rv[a.name] = df( + ( + _asdict_anything( + kk, + is_key=True, + filter=filter, + dict_factory=df, + retain_collection_types=retain_collection_types, + value_serializer=value_serializer, + ), + _asdict_anything( + vv, + is_key=False, + filter=filter, + dict_factory=df, + retain_collection_types=retain_collection_types, + value_serializer=value_serializer, + ), + ) + for kk, vv in v.items() + ) + else: + rv[a.name] = v + else: + rv[a.name] = v + return rv + + +def _asdict_anything( + val, + is_key, + filter, + dict_factory, + retain_collection_types, + value_serializer, +): + """ + ``asdict`` only works on attrs instances, this works on anything. + """ + if getattr(val.__class__, "__attrs_attrs__", None) is not None: + # Attrs class. + rv = asdict( + val, + recurse=True, + filter=filter, + dict_factory=dict_factory, + retain_collection_types=retain_collection_types, + value_serializer=value_serializer, + ) + elif isinstance(val, (tuple, list, set, frozenset)): + if retain_collection_types is True: + cf = val.__class__ + elif is_key: + cf = tuple + else: + cf = list + + rv = cf( + [ + _asdict_anything( + i, + is_key=False, + filter=filter, + dict_factory=dict_factory, + retain_collection_types=retain_collection_types, + value_serializer=value_serializer, + ) + for i in val + ] + ) + elif isinstance(val, dict): + df = dict_factory + rv = df( + ( + _asdict_anything( + kk, + is_key=True, + filter=filter, + dict_factory=df, + retain_collection_types=retain_collection_types, + value_serializer=value_serializer, + ), + _asdict_anything( + vv, + is_key=False, + filter=filter, + dict_factory=df, + retain_collection_types=retain_collection_types, + value_serializer=value_serializer, + ), + ) + for kk, vv in val.items() + ) + else: + rv = val + if value_serializer is not None: + rv = value_serializer(None, None, rv) + + return rv + + +def astuple( + inst, + recurse=True, + filter=None, + tuple_factory=tuple, + retain_collection_types=False, +): + """ + Return the *attrs* attribute values of *inst* as a tuple. + + Optionally recurse into other *attrs*-decorated classes. + + Args: + inst: Instance of an *attrs*-decorated class. + + recurse (bool): + Recurse into classes that are also *attrs*-decorated. + + filter (~typing.Callable): + A callable whose return code determines whether an attribute or + element is included (`True`) or dropped (`False`). Is called with + the `attrs.Attribute` as the first argument and the value as the + second argument. + + tuple_factory (~typing.Callable): + A callable to produce tuples from. For example, to produce lists + instead of tuples. + + retain_collection_types (bool): + Do not convert to `list` or `dict` when encountering an attribute + which type is `tuple`, `dict` or `set`. Only meaningful if + *recurse* is `True`. + + Returns: + Return type of *tuple_factory* + + Raises: + attrs.exceptions.NotAnAttrsClassError: + If *cls* is not an *attrs* class. + + .. versionadded:: 16.2.0 + """ + attrs = fields(inst.__class__) + rv = [] + retain = retain_collection_types # Very long. :/ + for a in attrs: + v = getattr(inst, a.name) + if filter is not None and not filter(a, v): + continue + if recurse is True: + if has(v.__class__): + rv.append( + astuple( + v, + recurse=True, + filter=filter, + tuple_factory=tuple_factory, + retain_collection_types=retain, + ) + ) + elif isinstance(v, (tuple, list, set, frozenset)): + cf = v.__class__ if retain is True else list + items = [ + ( + astuple( + j, + recurse=True, + filter=filter, + tuple_factory=tuple_factory, + retain_collection_types=retain, + ) + if has(j.__class__) + else j + ) + for j in v + ] + try: + rv.append(cf(items)) + except TypeError: + if not issubclass(cf, tuple): + raise + # Workaround for TypeError: cf.__new__() missing 1 required + # positional argument (which appears, for a namedturle) + rv.append(cf(*items)) + elif isinstance(v, dict): + df = v.__class__ if retain is True else dict + rv.append( + df( + ( + ( + astuple( + kk, + tuple_factory=tuple_factory, + retain_collection_types=retain, + ) + if has(kk.__class__) + else kk + ), + ( + astuple( + vv, + tuple_factory=tuple_factory, + retain_collection_types=retain, + ) + if has(vv.__class__) + else vv + ), + ) + for kk, vv in v.items() + ) + ) + else: + rv.append(v) + else: + rv.append(v) + + return rv if tuple_factory is list else tuple_factory(rv) + + +def has(cls): + """ + Check whether *cls* is a class with *attrs* attributes. + + Args: + cls (type): Class to introspect. + + Raises: + TypeError: If *cls* is not a class. + + Returns: + bool: + """ + attrs = getattr(cls, "__attrs_attrs__", None) + if attrs is not None: + return True + + # No attrs, maybe it's a specialized generic (A[str])? + generic_base = get_generic_base(cls) + if generic_base is not None: + generic_attrs = getattr(generic_base, "__attrs_attrs__", None) + if generic_attrs is not None: + # Stick it on here for speed next time. + cls.__attrs_attrs__ = generic_attrs + return generic_attrs is not None + return False + + +def assoc(inst, **changes): + """ + Copy *inst* and apply *changes*. + + This is different from `evolve` that applies the changes to the arguments + that create the new instance. + + `evolve`'s behavior is preferable, but there are `edge cases`_ where it + doesn't work. Therefore `assoc` is deprecated, but will not be removed. + + .. _`edge cases`: https://github.com/python-attrs/attrs/issues/251 + + Args: + inst: Instance of a class with *attrs* attributes. + + changes: Keyword changes in the new copy. + + Returns: + A copy of inst with *changes* incorporated. + + Raises: + attrs.exceptions.AttrsAttributeNotFoundError: + If *attr_name* couldn't be found on *cls*. + + attrs.exceptions.NotAnAttrsClassError: + If *cls* is not an *attrs* class. + + .. deprecated:: 17.1.0 + Use `attrs.evolve` instead if you can. This function will not be + removed du to the slightly different approach compared to + `attrs.evolve`, though. + """ + new = copy.copy(inst) + attrs = fields(inst.__class__) + for k, v in changes.items(): + a = getattr(attrs, k, NOTHING) + if a is NOTHING: + msg = f"{k} is not an attrs attribute on {new.__class__}." + raise AttrsAttributeNotFoundError(msg) + _OBJ_SETATTR(new, k, v) + return new + + +def resolve_types( + cls, globalns=None, localns=None, attribs=None, include_extras=True +): + """ + Resolve any strings and forward annotations in type annotations. + + This is only required if you need concrete types in :class:`Attribute`'s + *type* field. In other words, you don't need to resolve your types if you + only use them for static type checking. + + With no arguments, names will be looked up in the module in which the class + was created. If this is not what you want, for example, if the name only + exists inside a method, you may pass *globalns* or *localns* to specify + other dictionaries in which to look up these names. See the docs of + `typing.get_type_hints` for more details. + + Args: + cls (type): Class to resolve. + + globalns (dict | None): Dictionary containing global variables. + + localns (dict | None): Dictionary containing local variables. + + attribs (list | None): + List of attribs for the given class. This is necessary when calling + from inside a ``field_transformer`` since *cls* is not an *attrs* + class yet. + + include_extras (bool): + Resolve more accurately, if possible. Pass ``include_extras`` to + ``typing.get_hints``, if supported by the typing module. On + supported Python versions (3.9+), this resolves the types more + accurately. + + Raises: + TypeError: If *cls* is not a class. + + attrs.exceptions.NotAnAttrsClassError: + If *cls* is not an *attrs* class and you didn't pass any attribs. + + NameError: If types cannot be resolved because of missing variables. + + Returns: + *cls* so you can use this function also as a class decorator. Please + note that you have to apply it **after** `attrs.define`. That means the + decorator has to come in the line **before** `attrs.define`. + + .. versionadded:: 20.1.0 + .. versionadded:: 21.1.0 *attribs* + .. versionadded:: 23.1.0 *include_extras* + """ + # Since calling get_type_hints is expensive we cache whether we've + # done it already. + if getattr(cls, "__attrs_types_resolved__", None) != cls: + import typing + + kwargs = {"globalns": globalns, "localns": localns} + + if PY_3_9_PLUS: + kwargs["include_extras"] = include_extras + + hints = typing.get_type_hints(cls, **kwargs) + for field in fields(cls) if attribs is None else attribs: + if field.name in hints: + # Since fields have been frozen we must work around it. + _OBJ_SETATTR(field, "type", hints[field.name]) + # We store the class we resolved so that subclasses know they haven't + # been resolved. + cls.__attrs_types_resolved__ = cls + + # Return the class so you can use it as a decorator too. + return cls diff --git a/venv/lib/python3.10/site-packages/attr/_make.py b/venv/lib/python3.10/site-packages/attr/_make.py new file mode 100644 index 0000000000000000000000000000000000000000..e84d9792a744f34934a45b26d457f669596f7dee --- /dev/null +++ b/venv/lib/python3.10/site-packages/attr/_make.py @@ -0,0 +1,3123 @@ +# SPDX-License-Identifier: MIT + +from __future__ import annotations + +import abc +import contextlib +import copy +import enum +import inspect +import itertools +import linecache +import sys +import types +import unicodedata + +from collections.abc import Callable, Mapping +from functools import cached_property +from typing import Any, NamedTuple, TypeVar + +# We need to import _compat itself in addition to the _compat members to avoid +# having the thread-local in the globals here. +from . import _compat, _config, setters +from ._compat import ( + PY_3_10_PLUS, + PY_3_11_PLUS, + PY_3_13_PLUS, + _AnnotationExtractor, + _get_annotations, + get_generic_base, +) +from .exceptions import ( + DefaultAlreadySetError, + FrozenInstanceError, + NotAnAttrsClassError, + UnannotatedAttributeError, +) + + +# This is used at least twice, so cache it here. +_OBJ_SETATTR = object.__setattr__ +_INIT_FACTORY_PAT = "__attr_factory_%s" +_CLASSVAR_PREFIXES = ( + "typing.ClassVar", + "t.ClassVar", + "ClassVar", + "typing_extensions.ClassVar", +) +# we don't use a double-underscore prefix because that triggers +# name mangling when trying to create a slot for the field +# (when slots=True) +_HASH_CACHE_FIELD = "_attrs_cached_hash" + +_EMPTY_METADATA_SINGLETON = types.MappingProxyType({}) + +# Unique object for unequivocal getattr() defaults. +_SENTINEL = object() + +_DEFAULT_ON_SETATTR = setters.pipe(setters.convert, setters.validate) + + +class _Nothing(enum.Enum): + """ + Sentinel to indicate the lack of a value when `None` is ambiguous. + + If extending attrs, you can use ``typing.Literal[NOTHING]`` to show + that a value may be ``NOTHING``. + + .. versionchanged:: 21.1.0 ``bool(NOTHING)`` is now False. + .. versionchanged:: 22.2.0 ``NOTHING`` is now an ``enum.Enum`` variant. + """ + + NOTHING = enum.auto() + + def __repr__(self): + return "NOTHING" + + def __bool__(self): + return False + + +NOTHING = _Nothing.NOTHING +""" +Sentinel to indicate the lack of a value when `None` is ambiguous. + +When using in 3rd party code, use `attrs.NothingType` for type annotations. +""" + + +class _CacheHashWrapper(int): + """ + An integer subclass that pickles / copies as None + + This is used for non-slots classes with ``cache_hash=True``, to avoid + serializing a potentially (even likely) invalid hash value. Since `None` + is the default value for uncalculated hashes, whenever this is copied, + the copy's value for the hash should automatically reset. + + See GH #613 for more details. + """ + + def __reduce__(self, _none_constructor=type(None), _args=()): # noqa: B008 + return _none_constructor, _args + + +def attrib( + default=NOTHING, + validator=None, + repr=True, + cmp=None, + hash=None, + init=True, + metadata=None, + type=None, + converter=None, + factory=None, + kw_only=False, + eq=None, + order=None, + on_setattr=None, + alias=None, +): + """ + Create a new field / attribute on a class. + + Identical to `attrs.field`, except it's not keyword-only. + + Consider using `attrs.field` in new code (``attr.ib`` will *never* go away, + though). + + .. warning:: + + Does **nothing** unless the class is also decorated with + `attr.s` (or similar)! + + + .. versionadded:: 15.2.0 *convert* + .. versionadded:: 16.3.0 *metadata* + .. versionchanged:: 17.1.0 *validator* can be a ``list`` now. + .. versionchanged:: 17.1.0 + *hash* is `None` and therefore mirrors *eq* by default. + .. versionadded:: 17.3.0 *type* + .. deprecated:: 17.4.0 *convert* + .. versionadded:: 17.4.0 + *converter* as a replacement for the deprecated *convert* to achieve + consistency with other noun-based arguments. + .. versionadded:: 18.1.0 + ``factory=f`` is syntactic sugar for ``default=attr.Factory(f)``. + .. versionadded:: 18.2.0 *kw_only* + .. versionchanged:: 19.2.0 *convert* keyword argument removed. + .. versionchanged:: 19.2.0 *repr* also accepts a custom callable. + .. deprecated:: 19.2.0 *cmp* Removal on or after 2021-06-01. + .. versionadded:: 19.2.0 *eq* and *order* + .. versionadded:: 20.1.0 *on_setattr* + .. versionchanged:: 20.3.0 *kw_only* backported to Python 2 + .. versionchanged:: 21.1.0 + *eq*, *order*, and *cmp* also accept a custom callable + .. versionchanged:: 21.1.0 *cmp* undeprecated + .. versionadded:: 22.2.0 *alias* + """ + eq, eq_key, order, order_key = _determine_attrib_eq_order( + cmp, eq, order, True + ) + + if hash is not None and hash is not True and hash is not False: + msg = "Invalid value for hash. Must be True, False, or None." + raise TypeError(msg) + + if factory is not None: + if default is not NOTHING: + msg = ( + "The `default` and `factory` arguments are mutually exclusive." + ) + raise ValueError(msg) + if not callable(factory): + msg = "The `factory` argument must be a callable." + raise ValueError(msg) + default = Factory(factory) + + if metadata is None: + metadata = {} + + # Apply syntactic sugar by auto-wrapping. + if isinstance(on_setattr, (list, tuple)): + on_setattr = setters.pipe(*on_setattr) + + if validator and isinstance(validator, (list, tuple)): + validator = and_(*validator) + + if converter and isinstance(converter, (list, tuple)): + converter = pipe(*converter) + + return _CountingAttr( + default=default, + validator=validator, + repr=repr, + cmp=None, + hash=hash, + init=init, + converter=converter, + metadata=metadata, + type=type, + kw_only=kw_only, + eq=eq, + eq_key=eq_key, + order=order, + order_key=order_key, + on_setattr=on_setattr, + alias=alias, + ) + + +def _compile_and_eval( + script: str, + globs: dict[str, Any] | None, + locs: Mapping[str, object] | None = None, + filename: str = "", +) -> None: + """ + Evaluate the script with the given global (globs) and local (locs) + variables. + """ + bytecode = compile(script, filename, "exec") + eval(bytecode, globs, locs) + + +def _linecache_and_compile( + script: str, + filename: str, + globs: dict[str, Any] | None, + locals: Mapping[str, object] | None = None, +) -> dict[str, Any]: + """ + Cache the script with _linecache_, compile it and return the _locals_. + """ + + locs = {} if locals is None else locals + + # In order of debuggers like PDB being able to step through the code, + # we add a fake linecache entry. + count = 1 + base_filename = filename + while True: + linecache_tuple = ( + len(script), + None, + script.splitlines(True), + filename, + ) + old_val = linecache.cache.setdefault(filename, linecache_tuple) + if old_val == linecache_tuple: + break + + filename = f"{base_filename[:-1]}-{count}>" + count += 1 + + _compile_and_eval(script, globs, locs, filename) + + return locs + + +def _make_attr_tuple_class(cls_name: str, attr_names: list[str]) -> type: + """ + Create a tuple subclass to hold `Attribute`s for an `attrs` class. + + The subclass is a bare tuple with properties for names. + + class MyClassAttributes(tuple): + __slots__ = () + x = property(itemgetter(0)) + """ + attr_class_name = f"{cls_name}Attributes" + body = {} + for i, attr_name in enumerate(attr_names): + + def getter(self, i=i): + return self[i] + + body[attr_name] = property(getter) + return type(attr_class_name, (tuple,), body) + + +# Tuple class for extracted attributes from a class definition. +# `base_attrs` is a subset of `attrs`. +class _Attributes(NamedTuple): + attrs: type + base_attrs: list[Attribute] + base_attrs_map: dict[str, type] + + +def _is_class_var(annot): + """ + Check whether *annot* is a typing.ClassVar. + + The string comparison hack is used to avoid evaluating all string + annotations which would put attrs-based classes at a performance + disadvantage compared to plain old classes. + """ + annot = str(annot) + + # Annotation can be quoted. + if annot.startswith(("'", '"')) and annot.endswith(("'", '"')): + annot = annot[1:-1] + + return annot.startswith(_CLASSVAR_PREFIXES) + + +def _has_own_attribute(cls, attrib_name): + """ + Check whether *cls* defines *attrib_name* (and doesn't just inherit it). + """ + return attrib_name in cls.__dict__ + + +def _collect_base_attrs( + cls, taken_attr_names +) -> tuple[list[Attribute], dict[str, type]]: + """ + Collect attr.ibs from base classes of *cls*, except *taken_attr_names*. + """ + base_attrs = [] + base_attr_map = {} # A dictionary of base attrs to their classes. + + # Traverse the MRO and collect attributes. + for base_cls in reversed(cls.__mro__[1:-1]): + for a in getattr(base_cls, "__attrs_attrs__", []): + if a.inherited or a.name in taken_attr_names: + continue + + a = a.evolve(inherited=True) # noqa: PLW2901 + base_attrs.append(a) + base_attr_map[a.name] = base_cls + + # For each name, only keep the freshest definition i.e. the furthest at the + # back. base_attr_map is fine because it gets overwritten with every new + # instance. + filtered = [] + seen = set() + for a in reversed(base_attrs): + if a.name in seen: + continue + filtered.insert(0, a) + seen.add(a.name) + + return filtered, base_attr_map + + +def _collect_base_attrs_broken(cls, taken_attr_names): + """ + Collect attr.ibs from base classes of *cls*, except *taken_attr_names*. + + N.B. *taken_attr_names* will be mutated. + + Adhere to the old incorrect behavior. + + Notably it collects from the front and considers inherited attributes which + leads to the buggy behavior reported in #428. + """ + base_attrs = [] + base_attr_map = {} # A dictionary of base attrs to their classes. + + # Traverse the MRO and collect attributes. + for base_cls in cls.__mro__[1:-1]: + for a in getattr(base_cls, "__attrs_attrs__", []): + if a.name in taken_attr_names: + continue + + a = a.evolve(inherited=True) # noqa: PLW2901 + taken_attr_names.add(a.name) + base_attrs.append(a) + base_attr_map[a.name] = base_cls + + return base_attrs, base_attr_map + + +def _transform_attrs( + cls, these, auto_attribs, kw_only, collect_by_mro, field_transformer +) -> _Attributes: + """ + Transform all `_CountingAttr`s on a class into `Attribute`s. + + If *these* is passed, use that and don't look for them on the class. + + If *collect_by_mro* is True, collect them in the correct MRO order, + otherwise use the old -- incorrect -- order. See #428. + + Return an `_Attributes`. + """ + cd = cls.__dict__ + anns = _get_annotations(cls) + + if these is not None: + ca_list = list(these.items()) + elif auto_attribs is True: + ca_names = { + name + for name, attr in cd.items() + if attr.__class__ is _CountingAttr + } + ca_list = [] + annot_names = set() + for attr_name, type in anns.items(): + if _is_class_var(type): + continue + annot_names.add(attr_name) + a = cd.get(attr_name, NOTHING) + + if a.__class__ is not _CountingAttr: + a = attrib(a) + ca_list.append((attr_name, a)) + + unannotated = ca_names - annot_names + if unannotated: + raise UnannotatedAttributeError( + "The following `attr.ib`s lack a type annotation: " + + ", ".join( + sorted(unannotated, key=lambda n: cd.get(n).counter) + ) + + "." + ) + else: + ca_list = sorted( + ( + (name, attr) + for name, attr in cd.items() + if attr.__class__ is _CountingAttr + ), + key=lambda e: e[1].counter, + ) + + fca = Attribute.from_counting_attr + own_attrs = [ + fca(attr_name, ca, anns.get(attr_name)) for attr_name, ca in ca_list + ] + + if collect_by_mro: + base_attrs, base_attr_map = _collect_base_attrs( + cls, {a.name for a in own_attrs} + ) + else: + base_attrs, base_attr_map = _collect_base_attrs_broken( + cls, {a.name for a in own_attrs} + ) + + if kw_only: + own_attrs = [a.evolve(kw_only=True) for a in own_attrs] + base_attrs = [a.evolve(kw_only=True) for a in base_attrs] + + attrs = base_attrs + own_attrs + + if field_transformer is not None: + attrs = tuple(field_transformer(cls, attrs)) + + # Check attr order after executing the field_transformer. + # Mandatory vs non-mandatory attr order only matters when they are part of + # the __init__ signature and when they aren't kw_only (which are moved to + # the end and can be mandatory or non-mandatory in any order, as they will + # be specified as keyword args anyway). Check the order of those attrs: + had_default = False + for a in (a for a in attrs if a.init is not False and a.kw_only is False): + if had_default is True and a.default is NOTHING: + msg = f"No mandatory attributes allowed after an attribute with a default value or factory. Attribute in question: {a!r}" + raise ValueError(msg) + + if had_default is False and a.default is not NOTHING: + had_default = True + + # Resolve default field alias after executing field_transformer. + # This allows field_transformer to differentiate between explicit vs + # default aliases and supply their own defaults. + for a in attrs: + if not a.alias: + # Evolve is very slow, so we hold our nose and do it dirty. + _OBJ_SETATTR.__get__(a)("alias", _default_init_alias_for(a.name)) + + # Create AttrsClass *after* applying the field_transformer since it may + # add or remove attributes! + attr_names = [a.name for a in attrs] + AttrsClass = _make_attr_tuple_class(cls.__name__, attr_names) + + return _Attributes(AttrsClass(attrs), base_attrs, base_attr_map) + + +def _make_cached_property_getattr(cached_properties, original_getattr, cls): + lines = [ + # Wrapped to get `__class__` into closure cell for super() + # (It will be replaced with the newly constructed class after construction). + "def wrapper(_cls):", + " __class__ = _cls", + " def __getattr__(self, item, cached_properties=cached_properties, original_getattr=original_getattr, _cached_setattr_get=_cached_setattr_get):", + " func = cached_properties.get(item)", + " if func is not None:", + " result = func(self)", + " _setter = _cached_setattr_get(self)", + " _setter(item, result)", + " return result", + ] + if original_getattr is not None: + lines.append( + " return original_getattr(self, item)", + ) + else: + lines.extend( + [ + " try:", + " return super().__getattribute__(item)", + " except AttributeError:", + " if not hasattr(super(), '__getattr__'):", + " raise", + " return super().__getattr__(item)", + " original_error = f\"'{self.__class__.__name__}' object has no attribute '{item}'\"", + " raise AttributeError(original_error)", + ] + ) + + lines.extend( + [ + " return __getattr__", + "__getattr__ = wrapper(_cls)", + ] + ) + + unique_filename = _generate_unique_filename(cls, "getattr") + + glob = { + "cached_properties": cached_properties, + "_cached_setattr_get": _OBJ_SETATTR.__get__, + "original_getattr": original_getattr, + } + + return _linecache_and_compile( + "\n".join(lines), unique_filename, glob, locals={"_cls": cls} + )["__getattr__"] + + +def _frozen_setattrs(self, name, value): + """ + Attached to frozen classes as __setattr__. + """ + if isinstance(self, BaseException) and name in ( + "__cause__", + "__context__", + "__traceback__", + "__suppress_context__", + "__notes__", + ): + BaseException.__setattr__(self, name, value) + return + + raise FrozenInstanceError + + +def _frozen_delattrs(self, name): + """ + Attached to frozen classes as __delattr__. + """ + if isinstance(self, BaseException) and name in ("__notes__",): + BaseException.__delattr__(self, name) + return + + raise FrozenInstanceError + + +def evolve(*args, **changes): + """ + Create a new instance, based on the first positional argument with + *changes* applied. + + .. tip:: + + On Python 3.13 and later, you can also use `copy.replace` instead. + + Args: + + inst: + Instance of a class with *attrs* attributes. *inst* must be passed + as a positional argument. + + changes: + Keyword changes in the new copy. + + Returns: + A copy of inst with *changes* incorporated. + + Raises: + TypeError: + If *attr_name* couldn't be found in the class ``__init__``. + + attrs.exceptions.NotAnAttrsClassError: + If *cls* is not an *attrs* class. + + .. versionadded:: 17.1.0 + .. deprecated:: 23.1.0 + It is now deprecated to pass the instance using the keyword argument + *inst*. It will raise a warning until at least April 2024, after which + it will become an error. Always pass the instance as a positional + argument. + .. versionchanged:: 24.1.0 + *inst* can't be passed as a keyword argument anymore. + """ + try: + (inst,) = args + except ValueError: + msg = ( + f"evolve() takes 1 positional argument, but {len(args)} were given" + ) + raise TypeError(msg) from None + + cls = inst.__class__ + attrs = fields(cls) + for a in attrs: + if not a.init: + continue + attr_name = a.name # To deal with private attributes. + init_name = a.alias + if init_name not in changes: + changes[init_name] = getattr(inst, attr_name) + + return cls(**changes) + + +class _ClassBuilder: + """ + Iteratively build *one* class. + """ + + __slots__ = ( + "_add_method_dunders", + "_attr_names", + "_attrs", + "_base_attr_map", + "_base_names", + "_cache_hash", + "_cls", + "_cls_dict", + "_delete_attribs", + "_frozen", + "_has_custom_setattr", + "_has_post_init", + "_has_pre_init", + "_is_exc", + "_on_setattr", + "_pre_init_has_args", + "_repr_added", + "_script_snippets", + "_slots", + "_weakref_slot", + "_wrote_own_setattr", + ) + + def __init__( + self, + cls: type, + these, + slots, + frozen, + weakref_slot, + getstate_setstate, + auto_attribs, + kw_only, + cache_hash, + is_exc, + collect_by_mro, + on_setattr, + has_custom_setattr, + field_transformer, + ): + attrs, base_attrs, base_map = _transform_attrs( + cls, + these, + auto_attribs, + kw_only, + collect_by_mro, + field_transformer, + ) + + self._cls = cls + self._cls_dict = dict(cls.__dict__) if slots else {} + self._attrs = attrs + self._base_names = {a.name for a in base_attrs} + self._base_attr_map = base_map + self._attr_names = tuple(a.name for a in attrs) + self._slots = slots + self._frozen = frozen + self._weakref_slot = weakref_slot + self._cache_hash = cache_hash + self._has_pre_init = bool(getattr(cls, "__attrs_pre_init__", False)) + self._pre_init_has_args = False + if self._has_pre_init: + # Check if the pre init method has more arguments than just `self` + # We want to pass arguments if pre init expects arguments + pre_init_func = cls.__attrs_pre_init__ + pre_init_signature = inspect.signature(pre_init_func) + self._pre_init_has_args = len(pre_init_signature.parameters) > 1 + self._has_post_init = bool(getattr(cls, "__attrs_post_init__", False)) + self._delete_attribs = not bool(these) + self._is_exc = is_exc + self._on_setattr = on_setattr + + self._has_custom_setattr = has_custom_setattr + self._wrote_own_setattr = False + + self._cls_dict["__attrs_attrs__"] = self._attrs + + if frozen: + self._cls_dict["__setattr__"] = _frozen_setattrs + self._cls_dict["__delattr__"] = _frozen_delattrs + + self._wrote_own_setattr = True + elif on_setattr in ( + _DEFAULT_ON_SETATTR, + setters.validate, + setters.convert, + ): + has_validator = has_converter = False + for a in attrs: + if a.validator is not None: + has_validator = True + if a.converter is not None: + has_converter = True + + if has_validator and has_converter: + break + if ( + ( + on_setattr == _DEFAULT_ON_SETATTR + and not (has_validator or has_converter) + ) + or (on_setattr == setters.validate and not has_validator) + or (on_setattr == setters.convert and not has_converter) + ): + # If class-level on_setattr is set to convert + validate, but + # there's no field to convert or validate, pretend like there's + # no on_setattr. + self._on_setattr = None + + if getstate_setstate: + ( + self._cls_dict["__getstate__"], + self._cls_dict["__setstate__"], + ) = self._make_getstate_setstate() + + # tuples of script, globs, hook + self._script_snippets: list[ + tuple[str, dict, Callable[[dict, dict], Any]] + ] = [] + self._repr_added = False + + # We want to only do this check once; in 99.9% of cases these + # exist. + if not hasattr(self._cls, "__module__") or not hasattr( + self._cls, "__qualname__" + ): + self._add_method_dunders = self._add_method_dunders_safe + else: + self._add_method_dunders = self._add_method_dunders_unsafe + + def __repr__(self): + return f"<_ClassBuilder(cls={self._cls.__name__})>" + + def _eval_snippets(self) -> None: + """ + Evaluate any registered snippets in one go. + """ + script = "\n".join([snippet[0] for snippet in self._script_snippets]) + globs = {} + for _, snippet_globs, _ in self._script_snippets: + globs.update(snippet_globs) + + locs = _linecache_and_compile( + script, + _generate_unique_filename(self._cls, "methods"), + globs, + ) + + for _, _, hook in self._script_snippets: + hook(self._cls_dict, locs) + + def build_class(self): + """ + Finalize class based on the accumulated configuration. + + Builder cannot be used after calling this method. + """ + self._eval_snippets() + if self._slots is True: + cls = self._create_slots_class() + else: + cls = self._patch_original_class() + if PY_3_10_PLUS: + cls = abc.update_abstractmethods(cls) + + # The method gets only called if it's not inherited from a base class. + # _has_own_attribute does NOT work properly for classmethods. + if ( + getattr(cls, "__attrs_init_subclass__", None) + and "__attrs_init_subclass__" not in cls.__dict__ + ): + cls.__attrs_init_subclass__() + + return cls + + def _patch_original_class(self): + """ + Apply accumulated methods and return the class. + """ + cls = self._cls + base_names = self._base_names + + # Clean class of attribute definitions (`attr.ib()`s). + if self._delete_attribs: + for name in self._attr_names: + if ( + name not in base_names + and getattr(cls, name, _SENTINEL) is not _SENTINEL + ): + # An AttributeError can happen if a base class defines a + # class variable and we want to set an attribute with the + # same name by using only a type annotation. + with contextlib.suppress(AttributeError): + delattr(cls, name) + + # Attach our dunder methods. + for name, value in self._cls_dict.items(): + setattr(cls, name, value) + + # If we've inherited an attrs __setattr__ and don't write our own, + # reset it to object's. + if not self._wrote_own_setattr and getattr( + cls, "__attrs_own_setattr__", False + ): + cls.__attrs_own_setattr__ = False + + if not self._has_custom_setattr: + cls.__setattr__ = _OBJ_SETATTR + + return cls + + def _create_slots_class(self): + """ + Build and return a new class with a `__slots__` attribute. + """ + cd = { + k: v + for k, v in self._cls_dict.items() + if k not in (*tuple(self._attr_names), "__dict__", "__weakref__") + } + + # If our class doesn't have its own implementation of __setattr__ + # (either from the user or by us), check the bases, if one of them has + # an attrs-made __setattr__, that needs to be reset. We don't walk the + # MRO because we only care about our immediate base classes. + # XXX: This can be confused by subclassing a slotted attrs class with + # XXX: a non-attrs class and subclass the resulting class with an attrs + # XXX: class. See `test_slotted_confused` for details. For now that's + # XXX: OK with us. + if not self._wrote_own_setattr: + cd["__attrs_own_setattr__"] = False + + if not self._has_custom_setattr: + for base_cls in self._cls.__bases__: + if base_cls.__dict__.get("__attrs_own_setattr__", False): + cd["__setattr__"] = _OBJ_SETATTR + break + + # Traverse the MRO to collect existing slots + # and check for an existing __weakref__. + existing_slots = {} + weakref_inherited = False + for base_cls in self._cls.__mro__[1:-1]: + if base_cls.__dict__.get("__weakref__", None) is not None: + weakref_inherited = True + existing_slots.update( + { + name: getattr(base_cls, name) + for name in getattr(base_cls, "__slots__", []) + } + ) + + base_names = set(self._base_names) + + names = self._attr_names + if ( + self._weakref_slot + and "__weakref__" not in getattr(self._cls, "__slots__", ()) + and "__weakref__" not in names + and not weakref_inherited + ): + names += ("__weakref__",) + + cached_properties = { + name: cached_prop.func + for name, cached_prop in cd.items() + if isinstance(cached_prop, cached_property) + } + + # Collect methods with a `__class__` reference that are shadowed in the new class. + # To know to update them. + additional_closure_functions_to_update = [] + if cached_properties: + class_annotations = _get_annotations(self._cls) + for name, func in cached_properties.items(): + # Add cached properties to names for slotting. + names += (name,) + # Clear out function from class to avoid clashing. + del cd[name] + additional_closure_functions_to_update.append(func) + annotation = inspect.signature(func).return_annotation + if annotation is not inspect.Parameter.empty: + class_annotations[name] = annotation + + original_getattr = cd.get("__getattr__") + if original_getattr is not None: + additional_closure_functions_to_update.append(original_getattr) + + cd["__getattr__"] = _make_cached_property_getattr( + cached_properties, original_getattr, self._cls + ) + + # We only add the names of attributes that aren't inherited. + # Setting __slots__ to inherited attributes wastes memory. + slot_names = [name for name in names if name not in base_names] + + # There are slots for attributes from current class + # that are defined in parent classes. + # As their descriptors may be overridden by a child class, + # we collect them here and update the class dict + reused_slots = { + slot: slot_descriptor + for slot, slot_descriptor in existing_slots.items() + if slot in slot_names + } + slot_names = [name for name in slot_names if name not in reused_slots] + cd.update(reused_slots) + if self._cache_hash: + slot_names.append(_HASH_CACHE_FIELD) + + cd["__slots__"] = tuple(slot_names) + + cd["__qualname__"] = self._cls.__qualname__ + + # Create new class based on old class and our methods. + cls = type(self._cls)(self._cls.__name__, self._cls.__bases__, cd) + + # The following is a fix for + # . + # If a method mentions `__class__` or uses the no-arg super(), the + # compiler will bake a reference to the class in the method itself + # as `method.__closure__`. Since we replace the class with a + # clone, we rewrite these references so it keeps working. + for item in itertools.chain( + cls.__dict__.values(), additional_closure_functions_to_update + ): + if isinstance(item, (classmethod, staticmethod)): + # Class- and staticmethods hide their functions inside. + # These might need to be rewritten as well. + closure_cells = getattr(item.__func__, "__closure__", None) + elif isinstance(item, property): + # Workaround for property `super()` shortcut (PY3-only). + # There is no universal way for other descriptors. + closure_cells = getattr(item.fget, "__closure__", None) + else: + closure_cells = getattr(item, "__closure__", None) + + if not closure_cells: # Catch None or the empty list. + continue + for cell in closure_cells: + try: + match = cell.cell_contents is self._cls + except ValueError: # noqa: PERF203 + # ValueError: Cell is empty + pass + else: + if match: + cell.cell_contents = cls + return cls + + def add_repr(self, ns): + script, globs = _make_repr_script(self._attrs, ns) + + def _attach_repr(cls_dict, globs): + cls_dict["__repr__"] = self._add_method_dunders(globs["__repr__"]) + + self._script_snippets.append((script, globs, _attach_repr)) + self._repr_added = True + return self + + def add_str(self): + if not self._repr_added: + msg = "__str__ can only be generated if a __repr__ exists." + raise ValueError(msg) + + def __str__(self): + return self.__repr__() + + self._cls_dict["__str__"] = self._add_method_dunders(__str__) + return self + + def _make_getstate_setstate(self): + """ + Create custom __setstate__ and __getstate__ methods. + """ + # __weakref__ is not writable. + state_attr_names = tuple( + an for an in self._attr_names if an != "__weakref__" + ) + + def slots_getstate(self): + """ + Automatically created by attrs. + """ + return {name: getattr(self, name) for name in state_attr_names} + + hash_caching_enabled = self._cache_hash + + def slots_setstate(self, state): + """ + Automatically created by attrs. + """ + __bound_setattr = _OBJ_SETATTR.__get__(self) + if isinstance(state, tuple): + # Backward compatibility with attrs instances pickled with + # attrs versions before v22.2.0 which stored tuples. + for name, value in zip(state_attr_names, state): + __bound_setattr(name, value) + else: + for name in state_attr_names: + if name in state: + __bound_setattr(name, state[name]) + + # The hash code cache is not included when the object is + # serialized, but it still needs to be initialized to None to + # indicate that the first call to __hash__ should be a cache + # miss. + if hash_caching_enabled: + __bound_setattr(_HASH_CACHE_FIELD, None) + + return slots_getstate, slots_setstate + + def make_unhashable(self): + self._cls_dict["__hash__"] = None + return self + + def add_hash(self): + script, globs = _make_hash_script( + self._cls, + self._attrs, + frozen=self._frozen, + cache_hash=self._cache_hash, + ) + + def attach_hash(cls_dict: dict, locs: dict) -> None: + cls_dict["__hash__"] = self._add_method_dunders(locs["__hash__"]) + + self._script_snippets.append((script, globs, attach_hash)) + + return self + + def add_init(self): + script, globs, annotations = _make_init_script( + self._cls, + self._attrs, + self._has_pre_init, + self._pre_init_has_args, + self._has_post_init, + self._frozen, + self._slots, + self._cache_hash, + self._base_attr_map, + self._is_exc, + self._on_setattr, + attrs_init=False, + ) + + def _attach_init(cls_dict, globs): + init = globs["__init__"] + init.__annotations__ = annotations + cls_dict["__init__"] = self._add_method_dunders(init) + + self._script_snippets.append((script, globs, _attach_init)) + + return self + + def add_replace(self): + self._cls_dict["__replace__"] = self._add_method_dunders( + lambda self, **changes: evolve(self, **changes) + ) + return self + + def add_match_args(self): + self._cls_dict["__match_args__"] = tuple( + field.name + for field in self._attrs + if field.init and not field.kw_only + ) + + def add_attrs_init(self): + script, globs, annotations = _make_init_script( + self._cls, + self._attrs, + self._has_pre_init, + self._pre_init_has_args, + self._has_post_init, + self._frozen, + self._slots, + self._cache_hash, + self._base_attr_map, + self._is_exc, + self._on_setattr, + attrs_init=True, + ) + + def _attach_attrs_init(cls_dict, globs): + init = globs["__attrs_init__"] + init.__annotations__ = annotations + cls_dict["__attrs_init__"] = self._add_method_dunders(init) + + self._script_snippets.append((script, globs, _attach_attrs_init)) + + return self + + def add_eq(self): + cd = self._cls_dict + + script, globs = _make_eq_script(self._attrs) + + def _attach_eq(cls_dict, globs): + cls_dict["__eq__"] = self._add_method_dunders(globs["__eq__"]) + + self._script_snippets.append((script, globs, _attach_eq)) + + cd["__ne__"] = __ne__ + + return self + + def add_order(self): + cd = self._cls_dict + + cd["__lt__"], cd["__le__"], cd["__gt__"], cd["__ge__"] = ( + self._add_method_dunders(meth) + for meth in _make_order(self._cls, self._attrs) + ) + + return self + + def add_setattr(self): + sa_attrs = {} + for a in self._attrs: + on_setattr = a.on_setattr or self._on_setattr + if on_setattr and on_setattr is not setters.NO_OP: + sa_attrs[a.name] = a, on_setattr + + if not sa_attrs: + return self + + if self._has_custom_setattr: + # We need to write a __setattr__ but there already is one! + msg = "Can't combine custom __setattr__ with on_setattr hooks." + raise ValueError(msg) + + # docstring comes from _add_method_dunders + def __setattr__(self, name, val): + try: + a, hook = sa_attrs[name] + except KeyError: + nval = val + else: + nval = hook(self, a, val) + + _OBJ_SETATTR(self, name, nval) + + self._cls_dict["__attrs_own_setattr__"] = True + self._cls_dict["__setattr__"] = self._add_method_dunders(__setattr__) + self._wrote_own_setattr = True + + return self + + def _add_method_dunders_unsafe(self, method: Callable) -> Callable: + """ + Add __module__ and __qualname__ to a *method*. + """ + method.__module__ = self._cls.__module__ + + method.__qualname__ = f"{self._cls.__qualname__}.{method.__name__}" + + method.__doc__ = ( + f"Method generated by attrs for class {self._cls.__qualname__}." + ) + + return method + + def _add_method_dunders_safe(self, method: Callable) -> Callable: + """ + Add __module__ and __qualname__ to a *method* if possible. + """ + with contextlib.suppress(AttributeError): + method.__module__ = self._cls.__module__ + + with contextlib.suppress(AttributeError): + method.__qualname__ = f"{self._cls.__qualname__}.{method.__name__}" + + with contextlib.suppress(AttributeError): + method.__doc__ = f"Method generated by attrs for class {self._cls.__qualname__}." + + return method + + +def _determine_attrs_eq_order(cmp, eq, order, default_eq): + """ + Validate the combination of *cmp*, *eq*, and *order*. Derive the effective + values of eq and order. If *eq* is None, set it to *default_eq*. + """ + if cmp is not None and any((eq is not None, order is not None)): + msg = "Don't mix `cmp` with `eq' and `order`." + raise ValueError(msg) + + # cmp takes precedence due to bw-compatibility. + if cmp is not None: + return cmp, cmp + + # If left None, equality is set to the specified default and ordering + # mirrors equality. + if eq is None: + eq = default_eq + + if order is None: + order = eq + + if eq is False and order is True: + msg = "`order` can only be True if `eq` is True too." + raise ValueError(msg) + + return eq, order + + +def _determine_attrib_eq_order(cmp, eq, order, default_eq): + """ + Validate the combination of *cmp*, *eq*, and *order*. Derive the effective + values of eq and order. If *eq* is None, set it to *default_eq*. + """ + if cmp is not None and any((eq is not None, order is not None)): + msg = "Don't mix `cmp` with `eq' and `order`." + raise ValueError(msg) + + def decide_callable_or_boolean(value): + """ + Decide whether a key function is used. + """ + if callable(value): + value, key = True, value + else: + key = None + return value, key + + # cmp takes precedence due to bw-compatibility. + if cmp is not None: + cmp, cmp_key = decide_callable_or_boolean(cmp) + return cmp, cmp_key, cmp, cmp_key + + # If left None, equality is set to the specified default and ordering + # mirrors equality. + if eq is None: + eq, eq_key = default_eq, None + else: + eq, eq_key = decide_callable_or_boolean(eq) + + if order is None: + order, order_key = eq, eq_key + else: + order, order_key = decide_callable_or_boolean(order) + + if eq is False and order is True: + msg = "`order` can only be True if `eq` is True too." + raise ValueError(msg) + + return eq, eq_key, order, order_key + + +def _determine_whether_to_implement( + cls, flag, auto_detect, dunders, default=True +): + """ + Check whether we should implement a set of methods for *cls*. + + *flag* is the argument passed into @attr.s like 'init', *auto_detect* the + same as passed into @attr.s and *dunders* is a tuple of attribute names + whose presence signal that the user has implemented it themselves. + + Return *default* if no reason for either for or against is found. + """ + if flag is True or flag is False: + return flag + + if flag is None and auto_detect is False: + return default + + # Logically, flag is None and auto_detect is True here. + for dunder in dunders: + if _has_own_attribute(cls, dunder): + return False + + return default + + +def attrs( + maybe_cls=None, + these=None, + repr_ns=None, + repr=None, + cmp=None, + hash=None, + init=None, + slots=False, + frozen=False, + weakref_slot=True, + str=False, + auto_attribs=False, + kw_only=False, + cache_hash=False, + auto_exc=False, + eq=None, + order=None, + auto_detect=False, + collect_by_mro=False, + getstate_setstate=None, + on_setattr=None, + field_transformer=None, + match_args=True, + unsafe_hash=None, +): + r""" + A class decorator that adds :term:`dunder methods` according to the + specified attributes using `attr.ib` or the *these* argument. + + Consider using `attrs.define` / `attrs.frozen` in new code (``attr.s`` will + *never* go away, though). + + Args: + repr_ns (str): + When using nested classes, there was no way in Python 2 to + automatically detect that. This argument allows to set a custom + name for a more meaningful ``repr`` output. This argument is + pointless in Python 3 and is therefore deprecated. + + .. caution:: + Refer to `attrs.define` for the rest of the parameters, but note that they + can have different defaults. + + Notably, leaving *on_setattr* as `None` will **not** add any hooks. + + .. versionadded:: 16.0.0 *slots* + .. versionadded:: 16.1.0 *frozen* + .. versionadded:: 16.3.0 *str* + .. versionadded:: 16.3.0 Support for ``__attrs_post_init__``. + .. versionchanged:: 17.1.0 + *hash* supports `None` as value which is also the default now. + .. versionadded:: 17.3.0 *auto_attribs* + .. versionchanged:: 18.1.0 + If *these* is passed, no attributes are deleted from the class body. + .. versionchanged:: 18.1.0 If *these* is ordered, the order is retained. + .. versionadded:: 18.2.0 *weakref_slot* + .. deprecated:: 18.2.0 + ``__lt__``, ``__le__``, ``__gt__``, and ``__ge__`` now raise a + `DeprecationWarning` if the classes compared are subclasses of + each other. ``__eq`` and ``__ne__`` never tried to compared subclasses + to each other. + .. versionchanged:: 19.2.0 + ``__lt__``, ``__le__``, ``__gt__``, and ``__ge__`` now do not consider + subclasses comparable anymore. + .. versionadded:: 18.2.0 *kw_only* + .. versionadded:: 18.2.0 *cache_hash* + .. versionadded:: 19.1.0 *auto_exc* + .. deprecated:: 19.2.0 *cmp* Removal on or after 2021-06-01. + .. versionadded:: 19.2.0 *eq* and *order* + .. versionadded:: 20.1.0 *auto_detect* + .. versionadded:: 20.1.0 *collect_by_mro* + .. versionadded:: 20.1.0 *getstate_setstate* + .. versionadded:: 20.1.0 *on_setattr* + .. versionadded:: 20.3.0 *field_transformer* + .. versionchanged:: 21.1.0 + ``init=False`` injects ``__attrs_init__`` + .. versionchanged:: 21.1.0 Support for ``__attrs_pre_init__`` + .. versionchanged:: 21.1.0 *cmp* undeprecated + .. versionadded:: 21.3.0 *match_args* + .. versionadded:: 22.2.0 + *unsafe_hash* as an alias for *hash* (for :pep:`681` compliance). + .. deprecated:: 24.1.0 *repr_ns* + .. versionchanged:: 24.1.0 + Instances are not compared as tuples of attributes anymore, but using a + big ``and`` condition. This is faster and has more correct behavior for + uncomparable values like `math.nan`. + .. versionadded:: 24.1.0 + If a class has an *inherited* classmethod called + ``__attrs_init_subclass__``, it is executed after the class is created. + .. deprecated:: 24.1.0 *hash* is deprecated in favor of *unsafe_hash*. + """ + if repr_ns is not None: + import warnings + + warnings.warn( + DeprecationWarning( + "The `repr_ns` argument is deprecated and will be removed in or after August 2025." + ), + stacklevel=2, + ) + + eq_, order_ = _determine_attrs_eq_order(cmp, eq, order, None) + + # unsafe_hash takes precedence due to PEP 681. + if unsafe_hash is not None: + hash = unsafe_hash + + if isinstance(on_setattr, (list, tuple)): + on_setattr = setters.pipe(*on_setattr) + + def wrap(cls): + is_frozen = frozen or _has_frozen_base_class(cls) + is_exc = auto_exc is True and issubclass(cls, BaseException) + has_own_setattr = auto_detect and _has_own_attribute( + cls, "__setattr__" + ) + + if has_own_setattr and is_frozen: + msg = "Can't freeze a class with a custom __setattr__." + raise ValueError(msg) + + builder = _ClassBuilder( + cls, + these, + slots, + is_frozen, + weakref_slot, + _determine_whether_to_implement( + cls, + getstate_setstate, + auto_detect, + ("__getstate__", "__setstate__"), + default=slots, + ), + auto_attribs, + kw_only, + cache_hash, + is_exc, + collect_by_mro, + on_setattr, + has_own_setattr, + field_transformer, + ) + + if _determine_whether_to_implement( + cls, repr, auto_detect, ("__repr__",) + ): + builder.add_repr(repr_ns) + + if str is True: + builder.add_str() + + eq = _determine_whether_to_implement( + cls, eq_, auto_detect, ("__eq__", "__ne__") + ) + if not is_exc and eq is True: + builder.add_eq() + if not is_exc and _determine_whether_to_implement( + cls, order_, auto_detect, ("__lt__", "__le__", "__gt__", "__ge__") + ): + builder.add_order() + + if not frozen: + builder.add_setattr() + + nonlocal hash + if ( + hash is None + and auto_detect is True + and _has_own_attribute(cls, "__hash__") + ): + hash = False + + if hash is not True and hash is not False and hash is not None: + # Can't use `hash in` because 1 == True for example. + msg = "Invalid value for hash. Must be True, False, or None." + raise TypeError(msg) + + if hash is False or (hash is None and eq is False) or is_exc: + # Don't do anything. Should fall back to __object__'s __hash__ + # which is by id. + if cache_hash: + msg = "Invalid value for cache_hash. To use hash caching, hashing must be either explicitly or implicitly enabled." + raise TypeError(msg) + elif hash is True or ( + hash is None and eq is True and is_frozen is True + ): + # Build a __hash__ if told so, or if it's safe. + builder.add_hash() + else: + # Raise TypeError on attempts to hash. + if cache_hash: + msg = "Invalid value for cache_hash. To use hash caching, hashing must be either explicitly or implicitly enabled." + raise TypeError(msg) + builder.make_unhashable() + + if _determine_whether_to_implement( + cls, init, auto_detect, ("__init__",) + ): + builder.add_init() + else: + builder.add_attrs_init() + if cache_hash: + msg = "Invalid value for cache_hash. To use hash caching, init must be True." + raise TypeError(msg) + + if PY_3_13_PLUS and not _has_own_attribute(cls, "__replace__"): + builder.add_replace() + + if ( + PY_3_10_PLUS + and match_args + and not _has_own_attribute(cls, "__match_args__") + ): + builder.add_match_args() + + return builder.build_class() + + # maybe_cls's type depends on the usage of the decorator. It's a class + # if it's used as `@attrs` but `None` if used as `@attrs()`. + if maybe_cls is None: + return wrap + + return wrap(maybe_cls) + + +_attrs = attrs +""" +Internal alias so we can use it in functions that take an argument called +*attrs*. +""" + + +def _has_frozen_base_class(cls): + """ + Check whether *cls* has a frozen ancestor by looking at its + __setattr__. + """ + return cls.__setattr__ is _frozen_setattrs + + +def _generate_unique_filename(cls: type, func_name: str) -> str: + """ + Create a "filename" suitable for a function being generated. + """ + return ( + f"" + ) + + +def _make_hash_script( + cls: type, attrs: list[Attribute], frozen: bool, cache_hash: bool +) -> tuple[str, dict]: + attrs = tuple( + a for a in attrs if a.hash is True or (a.hash is None and a.eq is True) + ) + + tab = " " + + type_hash = hash(_generate_unique_filename(cls, "hash")) + # If eq is custom generated, we need to include the functions in globs + globs = {} + + hash_def = "def __hash__(self" + hash_func = "hash((" + closing_braces = "))" + if not cache_hash: + hash_def += "):" + else: + hash_def += ", *" + + hash_def += ", _cache_wrapper=__import__('attr._make')._make._CacheHashWrapper):" + hash_func = "_cache_wrapper(" + hash_func + closing_braces += ")" + + method_lines = [hash_def] + + def append_hash_computation_lines(prefix, indent): + """ + Generate the code for actually computing the hash code. + Below this will either be returned directly or used to compute + a value which is then cached, depending on the value of cache_hash + """ + + method_lines.extend( + [ + indent + prefix + hash_func, + indent + f" {type_hash},", + ] + ) + + for a in attrs: + if a.eq_key: + cmp_name = f"_{a.name}_key" + globs[cmp_name] = a.eq_key + method_lines.append( + indent + f" {cmp_name}(self.{a.name})," + ) + else: + method_lines.append(indent + f" self.{a.name},") + + method_lines.append(indent + " " + closing_braces) + + if cache_hash: + method_lines.append(tab + f"if self.{_HASH_CACHE_FIELD} is None:") + if frozen: + append_hash_computation_lines( + f"object.__setattr__(self, '{_HASH_CACHE_FIELD}', ", tab * 2 + ) + method_lines.append(tab * 2 + ")") # close __setattr__ + else: + append_hash_computation_lines( + f"self.{_HASH_CACHE_FIELD} = ", tab * 2 + ) + method_lines.append(tab + f"return self.{_HASH_CACHE_FIELD}") + else: + append_hash_computation_lines("return ", tab) + + script = "\n".join(method_lines) + return script, globs + + +def _add_hash(cls: type, attrs: list[Attribute]): + """ + Add a hash method to *cls*. + """ + script, globs = _make_hash_script( + cls, attrs, frozen=False, cache_hash=False + ) + _compile_and_eval( + script, globs, filename=_generate_unique_filename(cls, "__hash__") + ) + cls.__hash__ = globs["__hash__"] + return cls + + +def __ne__(self, other): + """ + Check equality and either forward a NotImplemented or + return the result negated. + """ + result = self.__eq__(other) + if result is NotImplemented: + return NotImplemented + + return not result + + +def _make_eq_script(attrs: list) -> tuple[str, dict]: + """ + Create __eq__ method for *cls* with *attrs*. + """ + attrs = [a for a in attrs if a.eq] + + lines = [ + "def __eq__(self, other):", + " if other.__class__ is not self.__class__:", + " return NotImplemented", + ] + + globs = {} + if attrs: + lines.append(" return (") + for a in attrs: + if a.eq_key: + cmp_name = f"_{a.name}_key" + # Add the key function to the global namespace + # of the evaluated function. + globs[cmp_name] = a.eq_key + lines.append( + f" {cmp_name}(self.{a.name}) == {cmp_name}(other.{a.name})" + ) + else: + lines.append(f" self.{a.name} == other.{a.name}") + if a is not attrs[-1]: + lines[-1] = f"{lines[-1]} and" + lines.append(" )") + else: + lines.append(" return True") + + script = "\n".join(lines) + + return script, globs + + +def _make_order(cls, attrs): + """ + Create ordering methods for *cls* with *attrs*. + """ + attrs = [a for a in attrs if a.order] + + def attrs_to_tuple(obj): + """ + Save us some typing. + """ + return tuple( + key(value) if key else value + for value, key in ( + (getattr(obj, a.name), a.order_key) for a in attrs + ) + ) + + def __lt__(self, other): + """ + Automatically created by attrs. + """ + if other.__class__ is self.__class__: + return attrs_to_tuple(self) < attrs_to_tuple(other) + + return NotImplemented + + def __le__(self, other): + """ + Automatically created by attrs. + """ + if other.__class__ is self.__class__: + return attrs_to_tuple(self) <= attrs_to_tuple(other) + + return NotImplemented + + def __gt__(self, other): + """ + Automatically created by attrs. + """ + if other.__class__ is self.__class__: + return attrs_to_tuple(self) > attrs_to_tuple(other) + + return NotImplemented + + def __ge__(self, other): + """ + Automatically created by attrs. + """ + if other.__class__ is self.__class__: + return attrs_to_tuple(self) >= attrs_to_tuple(other) + + return NotImplemented + + return __lt__, __le__, __gt__, __ge__ + + +def _add_eq(cls, attrs=None): + """ + Add equality methods to *cls* with *attrs*. + """ + if attrs is None: + attrs = cls.__attrs_attrs__ + + script, globs = _make_eq_script(attrs) + _compile_and_eval( + script, globs, filename=_generate_unique_filename(cls, "__eq__") + ) + cls.__eq__ = globs["__eq__"] + cls.__ne__ = __ne__ + + return cls + + +def _make_repr_script(attrs, ns) -> tuple[str, dict]: + """ + Create the source and globs for a __repr__ and return it. + """ + # Figure out which attributes to include, and which function to use to + # format them. The a.repr value can be either bool or a custom + # callable. + attr_names_with_reprs = tuple( + (a.name, (repr if a.repr is True else a.repr), a.init) + for a in attrs + if a.repr is not False + ) + globs = { + name + "_repr": r for name, r, _ in attr_names_with_reprs if r != repr + } + globs["_compat"] = _compat + globs["AttributeError"] = AttributeError + globs["NOTHING"] = NOTHING + attribute_fragments = [] + for name, r, i in attr_names_with_reprs: + accessor = ( + "self." + name if i else 'getattr(self, "' + name + '", NOTHING)' + ) + fragment = ( + "%s={%s!r}" % (name, accessor) + if r == repr + else "%s={%s_repr(%s)}" % (name, name, accessor) + ) + attribute_fragments.append(fragment) + repr_fragment = ", ".join(attribute_fragments) + + if ns is None: + cls_name_fragment = '{self.__class__.__qualname__.rsplit(">.", 1)[-1]}' + else: + cls_name_fragment = ns + ".{self.__class__.__name__}" + + lines = [ + "def __repr__(self):", + " try:", + " already_repring = _compat.repr_context.already_repring", + " except AttributeError:", + " already_repring = {id(self),}", + " _compat.repr_context.already_repring = already_repring", + " else:", + " if id(self) in already_repring:", + " return '...'", + " else:", + " already_repring.add(id(self))", + " try:", + f" return f'{cls_name_fragment}({repr_fragment})'", + " finally:", + " already_repring.remove(id(self))", + ] + + return "\n".join(lines), globs + + +def _add_repr(cls, ns=None, attrs=None): + """ + Add a repr method to *cls*. + """ + if attrs is None: + attrs = cls.__attrs_attrs__ + + script, globs = _make_repr_script(attrs, ns) + _compile_and_eval( + script, globs, filename=_generate_unique_filename(cls, "__repr__") + ) + cls.__repr__ = globs["__repr__"] + return cls + + +def fields(cls): + """ + Return the tuple of *attrs* attributes for a class. + + The tuple also allows accessing the fields by their names (see below for + examples). + + Args: + cls (type): Class to introspect. + + Raises: + TypeError: If *cls* is not a class. + + attrs.exceptions.NotAnAttrsClassError: + If *cls* is not an *attrs* class. + + Returns: + tuple (with name accessors) of `attrs.Attribute` + + .. versionchanged:: 16.2.0 Returned tuple allows accessing the fields + by name. + .. versionchanged:: 23.1.0 Add support for generic classes. + """ + generic_base = get_generic_base(cls) + + if generic_base is None and not isinstance(cls, type): + msg = "Passed object must be a class." + raise TypeError(msg) + + attrs = getattr(cls, "__attrs_attrs__", None) + + if attrs is None: + if generic_base is not None: + attrs = getattr(generic_base, "__attrs_attrs__", None) + if attrs is not None: + # Even though this is global state, stick it on here to speed + # it up. We rely on `cls` being cached for this to be + # efficient. + cls.__attrs_attrs__ = attrs + return attrs + msg = f"{cls!r} is not an attrs-decorated class." + raise NotAnAttrsClassError(msg) + + return attrs + + +def fields_dict(cls): + """ + Return an ordered dictionary of *attrs* attributes for a class, whose keys + are the attribute names. + + Args: + cls (type): Class to introspect. + + Raises: + TypeError: If *cls* is not a class. + + attrs.exceptions.NotAnAttrsClassError: + If *cls* is not an *attrs* class. + + Returns: + dict[str, attrs.Attribute]: Dict of attribute name to definition + + .. versionadded:: 18.1.0 + """ + if not isinstance(cls, type): + msg = "Passed object must be a class." + raise TypeError(msg) + attrs = getattr(cls, "__attrs_attrs__", None) + if attrs is None: + msg = f"{cls!r} is not an attrs-decorated class." + raise NotAnAttrsClassError(msg) + return {a.name: a for a in attrs} + + +def validate(inst): + """ + Validate all attributes on *inst* that have a validator. + + Leaves all exceptions through. + + Args: + inst: Instance of a class with *attrs* attributes. + """ + if _config._run_validators is False: + return + + for a in fields(inst.__class__): + v = a.validator + if v is not None: + v(inst, a, getattr(inst, a.name)) + + +def _is_slot_attr(a_name, base_attr_map): + """ + Check if the attribute name comes from a slot class. + """ + cls = base_attr_map.get(a_name) + return cls and "__slots__" in cls.__dict__ + + +def _make_init_script( + cls, + attrs, + pre_init, + pre_init_has_args, + post_init, + frozen, + slots, + cache_hash, + base_attr_map, + is_exc, + cls_on_setattr, + attrs_init, +) -> tuple[str, dict, dict]: + has_cls_on_setattr = ( + cls_on_setattr is not None and cls_on_setattr is not setters.NO_OP + ) + + if frozen and has_cls_on_setattr: + msg = "Frozen classes can't use on_setattr." + raise ValueError(msg) + + needs_cached_setattr = cache_hash or frozen + filtered_attrs = [] + attr_dict = {} + for a in attrs: + if not a.init and a.default is NOTHING: + continue + + filtered_attrs.append(a) + attr_dict[a.name] = a + + if a.on_setattr is not None: + if frozen is True: + msg = "Frozen classes can't use on_setattr." + raise ValueError(msg) + + needs_cached_setattr = True + elif has_cls_on_setattr and a.on_setattr is not setters.NO_OP: + needs_cached_setattr = True + + script, globs, annotations = _attrs_to_init_script( + filtered_attrs, + frozen, + slots, + pre_init, + pre_init_has_args, + post_init, + cache_hash, + base_attr_map, + is_exc, + needs_cached_setattr, + has_cls_on_setattr, + "__attrs_init__" if attrs_init else "__init__", + ) + if cls.__module__ in sys.modules: + # This makes typing.get_type_hints(CLS.__init__) resolve string types. + globs.update(sys.modules[cls.__module__].__dict__) + + globs.update({"NOTHING": NOTHING, "attr_dict": attr_dict}) + + if needs_cached_setattr: + # Save the lookup overhead in __init__ if we need to circumvent + # setattr hooks. + globs["_cached_setattr_get"] = _OBJ_SETATTR.__get__ + + return script, globs, annotations + + +def _setattr(attr_name: str, value_var: str, has_on_setattr: bool) -> str: + """ + Use the cached object.setattr to set *attr_name* to *value_var*. + """ + return f"_setattr('{attr_name}', {value_var})" + + +def _setattr_with_converter( + attr_name: str, value_var: str, has_on_setattr: bool, converter: Converter +) -> str: + """ + Use the cached object.setattr to set *attr_name* to *value_var*, but run + its converter first. + """ + return f"_setattr('{attr_name}', {converter._fmt_converter_call(attr_name, value_var)})" + + +def _assign(attr_name: str, value: str, has_on_setattr: bool) -> str: + """ + Unless *attr_name* has an on_setattr hook, use normal assignment. Otherwise + relegate to _setattr. + """ + if has_on_setattr: + return _setattr(attr_name, value, True) + + return f"self.{attr_name} = {value}" + + +def _assign_with_converter( + attr_name: str, value_var: str, has_on_setattr: bool, converter: Converter +) -> str: + """ + Unless *attr_name* has an on_setattr hook, use normal assignment after + conversion. Otherwise relegate to _setattr_with_converter. + """ + if has_on_setattr: + return _setattr_with_converter(attr_name, value_var, True, converter) + + return f"self.{attr_name} = {converter._fmt_converter_call(attr_name, value_var)}" + + +def _determine_setters( + frozen: bool, slots: bool, base_attr_map: dict[str, type] +): + """ + Determine the correct setter functions based on whether a class is frozen + and/or slotted. + """ + if frozen is True: + if slots is True: + return (), _setattr, _setattr_with_converter + + # Dict frozen classes assign directly to __dict__. + # But only if the attribute doesn't come from an ancestor slot + # class. + # Note _inst_dict will be used again below if cache_hash is True + + def fmt_setter( + attr_name: str, value_var: str, has_on_setattr: bool + ) -> str: + if _is_slot_attr(attr_name, base_attr_map): + return _setattr(attr_name, value_var, has_on_setattr) + + return f"_inst_dict['{attr_name}'] = {value_var}" + + def fmt_setter_with_converter( + attr_name: str, + value_var: str, + has_on_setattr: bool, + converter: Converter, + ) -> str: + if has_on_setattr or _is_slot_attr(attr_name, base_attr_map): + return _setattr_with_converter( + attr_name, value_var, has_on_setattr, converter + ) + + return f"_inst_dict['{attr_name}'] = {converter._fmt_converter_call(attr_name, value_var)}" + + return ( + ("_inst_dict = self.__dict__",), + fmt_setter, + fmt_setter_with_converter, + ) + + # Not frozen -- we can just assign directly. + return (), _assign, _assign_with_converter + + +def _attrs_to_init_script( + attrs: list[Attribute], + is_frozen: bool, + is_slotted: bool, + call_pre_init: bool, + pre_init_has_args: bool, + call_post_init: bool, + does_cache_hash: bool, + base_attr_map: dict[str, type], + is_exc: bool, + needs_cached_setattr: bool, + has_cls_on_setattr: bool, + method_name: str, +) -> tuple[str, dict, dict]: + """ + Return a script of an initializer for *attrs*, a dict of globals, and + annotations for the initializer. + + The globals are required by the generated script. + """ + lines = ["self.__attrs_pre_init__()"] if call_pre_init else [] + + if needs_cached_setattr: + lines.append( + # Circumvent the __setattr__ descriptor to save one lookup per + # assignment. Note _setattr will be used again below if + # does_cache_hash is True. + "_setattr = _cached_setattr_get(self)" + ) + + extra_lines, fmt_setter, fmt_setter_with_converter = _determine_setters( + is_frozen, is_slotted, base_attr_map + ) + lines.extend(extra_lines) + + args = [] + kw_only_args = [] + attrs_to_validate = [] + + # This is a dictionary of names to validator and converter callables. + # Injecting this into __init__ globals lets us avoid lookups. + names_for_globals = {} + annotations = {"return": None} + + for a in attrs: + if a.validator: + attrs_to_validate.append(a) + + attr_name = a.name + has_on_setattr = a.on_setattr is not None or ( + a.on_setattr is not setters.NO_OP and has_cls_on_setattr + ) + # a.alias is set to maybe-mangled attr_name in _ClassBuilder if not + # explicitly provided + arg_name = a.alias + + has_factory = isinstance(a.default, Factory) + maybe_self = "self" if has_factory and a.default.takes_self else "" + + if a.converter is not None and not isinstance(a.converter, Converter): + converter = Converter(a.converter) + else: + converter = a.converter + + if a.init is False: + if has_factory: + init_factory_name = _INIT_FACTORY_PAT % (a.name,) + if converter is not None: + lines.append( + fmt_setter_with_converter( + attr_name, + init_factory_name + f"({maybe_self})", + has_on_setattr, + converter, + ) + ) + names_for_globals[converter._get_global_name(a.name)] = ( + converter.converter + ) + else: + lines.append( + fmt_setter( + attr_name, + init_factory_name + f"({maybe_self})", + has_on_setattr, + ) + ) + names_for_globals[init_factory_name] = a.default.factory + elif converter is not None: + lines.append( + fmt_setter_with_converter( + attr_name, + f"attr_dict['{attr_name}'].default", + has_on_setattr, + converter, + ) + ) + names_for_globals[converter._get_global_name(a.name)] = ( + converter.converter + ) + else: + lines.append( + fmt_setter( + attr_name, + f"attr_dict['{attr_name}'].default", + has_on_setattr, + ) + ) + elif a.default is not NOTHING and not has_factory: + arg = f"{arg_name}=attr_dict['{attr_name}'].default" + if a.kw_only: + kw_only_args.append(arg) + else: + args.append(arg) + + if converter is not None: + lines.append( + fmt_setter_with_converter( + attr_name, arg_name, has_on_setattr, converter + ) + ) + names_for_globals[converter._get_global_name(a.name)] = ( + converter.converter + ) + else: + lines.append(fmt_setter(attr_name, arg_name, has_on_setattr)) + + elif has_factory: + arg = f"{arg_name}=NOTHING" + if a.kw_only: + kw_only_args.append(arg) + else: + args.append(arg) + lines.append(f"if {arg_name} is not NOTHING:") + + init_factory_name = _INIT_FACTORY_PAT % (a.name,) + if converter is not None: + lines.append( + " " + + fmt_setter_with_converter( + attr_name, arg_name, has_on_setattr, converter + ) + ) + lines.append("else:") + lines.append( + " " + + fmt_setter_with_converter( + attr_name, + init_factory_name + "(" + maybe_self + ")", + has_on_setattr, + converter, + ) + ) + names_for_globals[converter._get_global_name(a.name)] = ( + converter.converter + ) + else: + lines.append( + " " + fmt_setter(attr_name, arg_name, has_on_setattr) + ) + lines.append("else:") + lines.append( + " " + + fmt_setter( + attr_name, + init_factory_name + "(" + maybe_self + ")", + has_on_setattr, + ) + ) + names_for_globals[init_factory_name] = a.default.factory + else: + if a.kw_only: + kw_only_args.append(arg_name) + else: + args.append(arg_name) + + if converter is not None: + lines.append( + fmt_setter_with_converter( + attr_name, arg_name, has_on_setattr, converter + ) + ) + names_for_globals[converter._get_global_name(a.name)] = ( + converter.converter + ) + else: + lines.append(fmt_setter(attr_name, arg_name, has_on_setattr)) + + if a.init is True: + if a.type is not None and converter is None: + annotations[arg_name] = a.type + elif converter is not None and converter._first_param_type: + # Use the type from the converter if present. + annotations[arg_name] = converter._first_param_type + + if attrs_to_validate: # we can skip this if there are no validators. + names_for_globals["_config"] = _config + lines.append("if _config._run_validators is True:") + for a in attrs_to_validate: + val_name = "__attr_validator_" + a.name + attr_name = "__attr_" + a.name + lines.append(f" {val_name}(self, {attr_name}, self.{a.name})") + names_for_globals[val_name] = a.validator + names_for_globals[attr_name] = a + + if call_post_init: + lines.append("self.__attrs_post_init__()") + + # Because this is set only after __attrs_post_init__ is called, a crash + # will result if post-init tries to access the hash code. This seemed + # preferable to setting this beforehand, in which case alteration to field + # values during post-init combined with post-init accessing the hash code + # would result in silent bugs. + if does_cache_hash: + if is_frozen: + if is_slotted: + init_hash_cache = f"_setattr('{_HASH_CACHE_FIELD}', None)" + else: + init_hash_cache = f"_inst_dict['{_HASH_CACHE_FIELD}'] = None" + else: + init_hash_cache = f"self.{_HASH_CACHE_FIELD} = None" + lines.append(init_hash_cache) + + # For exceptions we rely on BaseException.__init__ for proper + # initialization. + if is_exc: + vals = ",".join(f"self.{a.name}" for a in attrs if a.init) + + lines.append(f"BaseException.__init__(self, {vals})") + + args = ", ".join(args) + pre_init_args = args + if kw_only_args: + # leading comma & kw_only args + args += f"{', ' if args else ''}*, {', '.join(kw_only_args)}" + pre_init_kw_only_args = ", ".join( + [ + f"{kw_arg_name}={kw_arg_name}" + # We need to remove the defaults from the kw_only_args. + for kw_arg_name in (kwa.split("=")[0] for kwa in kw_only_args) + ] + ) + pre_init_args += ", " if pre_init_args else "" + pre_init_args += pre_init_kw_only_args + + if call_pre_init and pre_init_has_args: + # If pre init method has arguments, pass same arguments as `__init__`. + lines[0] = f"self.__attrs_pre_init__({pre_init_args})" + + # Python <3.12 doesn't allow backslashes in f-strings. + NL = "\n " + return ( + f"""def {method_name}(self, {args}): + {NL.join(lines) if lines else "pass"} +""", + names_for_globals, + annotations, + ) + + +def _default_init_alias_for(name: str) -> str: + """ + The default __init__ parameter name for a field. + + This performs private-name adjustment via leading-unscore stripping, + and is the default value of Attribute.alias if not provided. + """ + + return name.lstrip("_") + + +class Attribute: + """ + *Read-only* representation of an attribute. + + .. warning:: + + You should never instantiate this class yourself. + + The class has *all* arguments of `attr.ib` (except for ``factory`` which is + only syntactic sugar for ``default=Factory(...)`` plus the following: + + - ``name`` (`str`): The name of the attribute. + - ``alias`` (`str`): The __init__ parameter name of the attribute, after + any explicit overrides and default private-attribute-name handling. + - ``inherited`` (`bool`): Whether or not that attribute has been inherited + from a base class. + - ``eq_key`` and ``order_key`` (`typing.Callable` or `None`): The + callables that are used for comparing and ordering objects by this + attribute, respectively. These are set by passing a callable to + `attr.ib`'s ``eq``, ``order``, or ``cmp`` arguments. See also + :ref:`comparison customization `. + + Instances of this class are frequently used for introspection purposes + like: + + - `fields` returns a tuple of them. + - Validators get them passed as the first argument. + - The :ref:`field transformer ` hook receives a list of + them. + - The ``alias`` property exposes the __init__ parameter name of the field, + with any overrides and default private-attribute handling applied. + + + .. versionadded:: 20.1.0 *inherited* + .. versionadded:: 20.1.0 *on_setattr* + .. versionchanged:: 20.2.0 *inherited* is not taken into account for + equality checks and hashing anymore. + .. versionadded:: 21.1.0 *eq_key* and *order_key* + .. versionadded:: 22.2.0 *alias* + + For the full version history of the fields, see `attr.ib`. + """ + + # These slots must NOT be reordered because we use them later for + # instantiation. + __slots__ = ( # noqa: RUF023 + "name", + "default", + "validator", + "repr", + "eq", + "eq_key", + "order", + "order_key", + "hash", + "init", + "metadata", + "type", + "converter", + "kw_only", + "inherited", + "on_setattr", + "alias", + ) + + def __init__( + self, + name, + default, + validator, + repr, + cmp, # XXX: unused, remove along with other cmp code. + hash, + init, + inherited, + metadata=None, + type=None, + converter=None, + kw_only=False, + eq=None, + eq_key=None, + order=None, + order_key=None, + on_setattr=None, + alias=None, + ): + eq, eq_key, order, order_key = _determine_attrib_eq_order( + cmp, eq_key or eq, order_key or order, True + ) + + # Cache this descriptor here to speed things up later. + bound_setattr = _OBJ_SETATTR.__get__(self) + + # Despite the big red warning, people *do* instantiate `Attribute` + # themselves. + bound_setattr("name", name) + bound_setattr("default", default) + bound_setattr("validator", validator) + bound_setattr("repr", repr) + bound_setattr("eq", eq) + bound_setattr("eq_key", eq_key) + bound_setattr("order", order) + bound_setattr("order_key", order_key) + bound_setattr("hash", hash) + bound_setattr("init", init) + bound_setattr("converter", converter) + bound_setattr( + "metadata", + ( + types.MappingProxyType(dict(metadata)) # Shallow copy + if metadata + else _EMPTY_METADATA_SINGLETON + ), + ) + bound_setattr("type", type) + bound_setattr("kw_only", kw_only) + bound_setattr("inherited", inherited) + bound_setattr("on_setattr", on_setattr) + bound_setattr("alias", alias) + + def __setattr__(self, name, value): + raise FrozenInstanceError + + @classmethod + def from_counting_attr(cls, name: str, ca: _CountingAttr, type=None): + # type holds the annotated value. deal with conflicts: + if type is None: + type = ca.type + elif ca.type is not None: + msg = f"Type annotation and type argument cannot both be present for '{name}'." + raise ValueError(msg) + return cls( + name, + ca._default, + ca._validator, + ca.repr, + None, + ca.hash, + ca.init, + False, + ca.metadata, + type, + ca.converter, + ca.kw_only, + ca.eq, + ca.eq_key, + ca.order, + ca.order_key, + ca.on_setattr, + ca.alias, + ) + + # Don't use attrs.evolve since fields(Attribute) doesn't work + def evolve(self, **changes): + """ + Copy *self* and apply *changes*. + + This works similarly to `attrs.evolve` but that function does not work + with :class:`attrs.Attribute`. + + It is mainly meant to be used for `transform-fields`. + + .. versionadded:: 20.3.0 + """ + new = copy.copy(self) + + new._setattrs(changes.items()) + + return new + + # Don't use _add_pickle since fields(Attribute) doesn't work + def __getstate__(self): + """ + Play nice with pickle. + """ + return tuple( + getattr(self, name) if name != "metadata" else dict(self.metadata) + for name in self.__slots__ + ) + + def __setstate__(self, state): + """ + Play nice with pickle. + """ + self._setattrs(zip(self.__slots__, state)) + + def _setattrs(self, name_values_pairs): + bound_setattr = _OBJ_SETATTR.__get__(self) + for name, value in name_values_pairs: + if name != "metadata": + bound_setattr(name, value) + else: + bound_setattr( + name, + ( + types.MappingProxyType(dict(value)) + if value + else _EMPTY_METADATA_SINGLETON + ), + ) + + +_a = [ + Attribute( + name=name, + default=NOTHING, + validator=None, + repr=True, + cmp=None, + eq=True, + order=False, + hash=(name != "metadata"), + init=True, + inherited=False, + alias=_default_init_alias_for(name), + ) + for name in Attribute.__slots__ +] + +Attribute = _add_hash( + _add_eq( + _add_repr(Attribute, attrs=_a), + attrs=[a for a in _a if a.name != "inherited"], + ), + attrs=[a for a in _a if a.hash and a.name != "inherited"], +) + + +class _CountingAttr: + """ + Intermediate representation of attributes that uses a counter to preserve + the order in which the attributes have been defined. + + *Internal* data structure of the attrs library. Running into is most + likely the result of a bug like a forgotten `@attr.s` decorator. + """ + + __slots__ = ( + "_default", + "_validator", + "alias", + "converter", + "counter", + "eq", + "eq_key", + "hash", + "init", + "kw_only", + "metadata", + "on_setattr", + "order", + "order_key", + "repr", + "type", + ) + __attrs_attrs__ = ( + *tuple( + Attribute( + name=name, + alias=_default_init_alias_for(name), + default=NOTHING, + validator=None, + repr=True, + cmp=None, + hash=True, + init=True, + kw_only=False, + eq=True, + eq_key=None, + order=False, + order_key=None, + inherited=False, + on_setattr=None, + ) + for name in ( + "counter", + "_default", + "repr", + "eq", + "order", + "hash", + "init", + "on_setattr", + "alias", + ) + ), + Attribute( + name="metadata", + alias="metadata", + default=None, + validator=None, + repr=True, + cmp=None, + hash=False, + init=True, + kw_only=False, + eq=True, + eq_key=None, + order=False, + order_key=None, + inherited=False, + on_setattr=None, + ), + ) + cls_counter = 0 + + def __init__( + self, + default, + validator, + repr, + cmp, + hash, + init, + converter, + metadata, + type, + kw_only, + eq, + eq_key, + order, + order_key, + on_setattr, + alias, + ): + _CountingAttr.cls_counter += 1 + self.counter = _CountingAttr.cls_counter + self._default = default + self._validator = validator + self.converter = converter + self.repr = repr + self.eq = eq + self.eq_key = eq_key + self.order = order + self.order_key = order_key + self.hash = hash + self.init = init + self.metadata = metadata + self.type = type + self.kw_only = kw_only + self.on_setattr = on_setattr + self.alias = alias + + def validator(self, meth): + """ + Decorator that adds *meth* to the list of validators. + + Returns *meth* unchanged. + + .. versionadded:: 17.1.0 + """ + if self._validator is None: + self._validator = meth + else: + self._validator = and_(self._validator, meth) + return meth + + def default(self, meth): + """ + Decorator that allows to set the default for an attribute. + + Returns *meth* unchanged. + + Raises: + DefaultAlreadySetError: If default has been set before. + + .. versionadded:: 17.1.0 + """ + if self._default is not NOTHING: + raise DefaultAlreadySetError + + self._default = Factory(meth, takes_self=True) + + return meth + + +_CountingAttr = _add_eq(_add_repr(_CountingAttr)) + + +class Factory: + """ + Stores a factory callable. + + If passed as the default value to `attrs.field`, the factory is used to + generate a new value. + + Args: + factory (typing.Callable): + A callable that takes either none or exactly one mandatory + positional argument depending on *takes_self*. + + takes_self (bool): + Pass the partially initialized instance that is being initialized + as a positional argument. + + .. versionadded:: 17.1.0 *takes_self* + """ + + __slots__ = ("factory", "takes_self") + + def __init__(self, factory, takes_self=False): + self.factory = factory + self.takes_self = takes_self + + def __getstate__(self): + """ + Play nice with pickle. + """ + return tuple(getattr(self, name) for name in self.__slots__) + + def __setstate__(self, state): + """ + Play nice with pickle. + """ + for name, value in zip(self.__slots__, state): + setattr(self, name, value) + + +_f = [ + Attribute( + name=name, + default=NOTHING, + validator=None, + repr=True, + cmp=None, + eq=True, + order=False, + hash=True, + init=True, + inherited=False, + ) + for name in Factory.__slots__ +] + +Factory = _add_hash(_add_eq(_add_repr(Factory, attrs=_f), attrs=_f), attrs=_f) + + +class Converter: + """ + Stores a converter callable. + + Allows for the wrapped converter to take additional arguments. The + arguments are passed in the order they are documented. + + Args: + converter (Callable): A callable that converts the passed value. + + takes_self (bool): + Pass the partially initialized instance that is being initialized + as a positional argument. (default: `False`) + + takes_field (bool): + Pass the field definition (an :class:`Attribute`) into the + converter as a positional argument. (default: `False`) + + .. versionadded:: 24.1.0 + """ + + __slots__ = ( + "__call__", + "_first_param_type", + "_global_name", + "converter", + "takes_field", + "takes_self", + ) + + def __init__(self, converter, *, takes_self=False, takes_field=False): + self.converter = converter + self.takes_self = takes_self + self.takes_field = takes_field + + ex = _AnnotationExtractor(converter) + self._first_param_type = ex.get_first_param_type() + + if not (self.takes_self or self.takes_field): + self.__call__ = lambda value, _, __: self.converter(value) + elif self.takes_self and not self.takes_field: + self.__call__ = lambda value, instance, __: self.converter( + value, instance + ) + elif not self.takes_self and self.takes_field: + self.__call__ = lambda value, __, field: self.converter( + value, field + ) + else: + self.__call__ = lambda value, instance, field: self.converter( + value, instance, field + ) + + rt = ex.get_return_type() + if rt is not None: + self.__call__.__annotations__["return"] = rt + + @staticmethod + def _get_global_name(attr_name: str) -> str: + """ + Return the name that a converter for an attribute name *attr_name* + would have. + """ + return f"__attr_converter_{attr_name}" + + def _fmt_converter_call(self, attr_name: str, value_var: str) -> str: + """ + Return a string that calls the converter for an attribute name + *attr_name* and the value in variable named *value_var* according to + `self.takes_self` and `self.takes_field`. + """ + if not (self.takes_self or self.takes_field): + return f"{self._get_global_name(attr_name)}({value_var})" + + if self.takes_self and self.takes_field: + return f"{self._get_global_name(attr_name)}({value_var}, self, attr_dict['{attr_name}'])" + + if self.takes_self: + return f"{self._get_global_name(attr_name)}({value_var}, self)" + + return f"{self._get_global_name(attr_name)}({value_var}, attr_dict['{attr_name}'])" + + def __getstate__(self): + """ + Return a dict containing only converter and takes_self -- the rest gets + computed when loading. + """ + return { + "converter": self.converter, + "takes_self": self.takes_self, + "takes_field": self.takes_field, + } + + def __setstate__(self, state): + """ + Load instance from state. + """ + self.__init__(**state) + + +_f = [ + Attribute( + name=name, + default=NOTHING, + validator=None, + repr=True, + cmp=None, + eq=True, + order=False, + hash=True, + init=True, + inherited=False, + ) + for name in ("converter", "takes_self", "takes_field") +] + +Converter = _add_hash( + _add_eq(_add_repr(Converter, attrs=_f), attrs=_f), attrs=_f +) + + +def make_class( + name, attrs, bases=(object,), class_body=None, **attributes_arguments +): + r""" + A quick way to create a new class called *name* with *attrs*. + + .. note:: + + ``make_class()`` is a thin wrapper around `attr.s`, not `attrs.define` + which means that it doesn't come with some of the improved defaults. + + For example, if you want the same ``on_setattr`` behavior as in + `attrs.define`, you have to pass the hooks yourself: ``make_class(..., + on_setattr=setters.pipe(setters.convert, setters.validate)`` + + .. warning:: + + It is *your* duty to ensure that the class name and the attribute names + are valid identifiers. ``make_class()`` will *not* validate them for + you. + + Args: + name (str): The name for the new class. + + attrs (list | dict): + A list of names or a dictionary of mappings of names to `attr.ib`\ + s / `attrs.field`\ s. + + The order is deduced from the order of the names or attributes + inside *attrs*. Otherwise the order of the definition of the + attributes is used. + + bases (tuple[type, ...]): Classes that the new class will subclass. + + class_body (dict): + An optional dictionary of class attributes for the new class. + + attributes_arguments: Passed unmodified to `attr.s`. + + Returns: + type: A new class with *attrs*. + + .. versionadded:: 17.1.0 *bases* + .. versionchanged:: 18.1.0 If *attrs* is ordered, the order is retained. + .. versionchanged:: 23.2.0 *class_body* + .. versionchanged:: 25.2.0 Class names can now be unicode. + """ + # Class identifiers are converted into the normal form NFKC while parsing + name = unicodedata.normalize("NFKC", name) + + if isinstance(attrs, dict): + cls_dict = attrs + elif isinstance(attrs, (list, tuple)): + cls_dict = {a: attrib() for a in attrs} + else: + msg = "attrs argument must be a dict or a list." + raise TypeError(msg) + + pre_init = cls_dict.pop("__attrs_pre_init__", None) + post_init = cls_dict.pop("__attrs_post_init__", None) + user_init = cls_dict.pop("__init__", None) + + body = {} + if class_body is not None: + body.update(class_body) + if pre_init is not None: + body["__attrs_pre_init__"] = pre_init + if post_init is not None: + body["__attrs_post_init__"] = post_init + if user_init is not None: + body["__init__"] = user_init + + type_ = types.new_class(name, bases, {}, lambda ns: ns.update(body)) + + # For pickling to work, the __module__ variable needs to be set to the + # frame where the class is created. Bypass this step in environments where + # sys._getframe is not defined (Jython for example) or sys._getframe is not + # defined for arguments greater than 0 (IronPython). + with contextlib.suppress(AttributeError, ValueError): + type_.__module__ = sys._getframe(1).f_globals.get( + "__name__", "__main__" + ) + + # We do it here for proper warnings with meaningful stacklevel. + cmp = attributes_arguments.pop("cmp", None) + ( + attributes_arguments["eq"], + attributes_arguments["order"], + ) = _determine_attrs_eq_order( + cmp, + attributes_arguments.get("eq"), + attributes_arguments.get("order"), + True, + ) + + cls = _attrs(these=cls_dict, **attributes_arguments)(type_) + # Only add type annotations now or "_attrs()" will complain: + cls.__annotations__ = { + k: v.type for k, v in cls_dict.items() if v.type is not None + } + return cls + + +# These are required by within this module so we define them here and merely +# import into .validators / .converters. + + +@attrs(slots=True, unsafe_hash=True) +class _AndValidator: + """ + Compose many validators to a single one. + """ + + _validators = attrib() + + def __call__(self, inst, attr, value): + for v in self._validators: + v(inst, attr, value) + + +def and_(*validators): + """ + A validator that composes multiple validators into one. + + When called on a value, it runs all wrapped validators. + + Args: + validators (~collections.abc.Iterable[typing.Callable]): + Arbitrary number of validators. + + .. versionadded:: 17.1.0 + """ + vals = [] + for validator in validators: + vals.extend( + validator._validators + if isinstance(validator, _AndValidator) + else [validator] + ) + + return _AndValidator(tuple(vals)) + + +def pipe(*converters): + """ + A converter that composes multiple converters into one. + + When called on a value, it runs all wrapped converters, returning the + *last* value. + + Type annotations will be inferred from the wrapped converters', if they + have any. + + converters (~collections.abc.Iterable[typing.Callable]): + Arbitrary number of converters. + + .. versionadded:: 20.1.0 + """ + + return_instance = any(isinstance(c, Converter) for c in converters) + + if return_instance: + + def pipe_converter(val, inst, field): + for c in converters: + val = ( + c(val, inst, field) if isinstance(c, Converter) else c(val) + ) + + return val + + else: + + def pipe_converter(val): + for c in converters: + val = c(val) + + return val + + if not converters: + # If the converter list is empty, pipe_converter is the identity. + A = TypeVar("A") + pipe_converter.__annotations__.update({"val": A, "return": A}) + else: + # Get parameter type from first converter. + t = _AnnotationExtractor(converters[0]).get_first_param_type() + if t: + pipe_converter.__annotations__["val"] = t + + last = converters[-1] + if not PY_3_11_PLUS and isinstance(last, Converter): + last = last.__call__ + + # Get return type from last converter. + rt = _AnnotationExtractor(last).get_return_type() + if rt: + pipe_converter.__annotations__["return"] = rt + + if return_instance: + return Converter(pipe_converter, takes_self=True, takes_field=True) + return pipe_converter diff --git a/venv/lib/python3.10/site-packages/attr/_next_gen.py b/venv/lib/python3.10/site-packages/attr/_next_gen.py new file mode 100644 index 0000000000000000000000000000000000000000..9290664b2dca9285855a4c4c38bb09ca9e616f69 --- /dev/null +++ b/venv/lib/python3.10/site-packages/attr/_next_gen.py @@ -0,0 +1,623 @@ +# SPDX-License-Identifier: MIT + +""" +These are keyword-only APIs that call `attr.s` and `attr.ib` with different +default values. +""" + +from functools import partial + +from . import setters +from ._funcs import asdict as _asdict +from ._funcs import astuple as _astuple +from ._make import ( + _DEFAULT_ON_SETATTR, + NOTHING, + _frozen_setattrs, + attrib, + attrs, +) +from .exceptions import UnannotatedAttributeError + + +def define( + maybe_cls=None, + *, + these=None, + repr=None, + unsafe_hash=None, + hash=None, + init=None, + slots=True, + frozen=False, + weakref_slot=True, + str=False, + auto_attribs=None, + kw_only=False, + cache_hash=False, + auto_exc=True, + eq=None, + order=False, + auto_detect=True, + getstate_setstate=None, + on_setattr=None, + field_transformer=None, + match_args=True, +): + r""" + A class decorator that adds :term:`dunder methods` according to + :term:`fields ` specified using :doc:`type annotations `, + `field()` calls, or the *these* argument. + + Since *attrs* patches or replaces an existing class, you cannot use + `object.__init_subclass__` with *attrs* classes, because it runs too early. + As a replacement, you can define ``__attrs_init_subclass__`` on your class. + It will be called by *attrs* classes that subclass it after they're + created. See also :ref:`init-subclass`. + + Args: + slots (bool): + Create a :term:`slotted class ` that's more + memory-efficient. Slotted classes are generally superior to the + default dict classes, but have some gotchas you should know about, + so we encourage you to read the :term:`glossary entry `. + + auto_detect (bool): + Instead of setting the *init*, *repr*, *eq*, and *hash* arguments + explicitly, assume they are set to True **unless any** of the + involved methods for one of the arguments is implemented in the + *current* class (meaning, it is *not* inherited from some base + class). + + So, for example by implementing ``__eq__`` on a class yourself, + *attrs* will deduce ``eq=False`` and will create *neither* + ``__eq__`` *nor* ``__ne__`` (but Python classes come with a + sensible ``__ne__`` by default, so it *should* be enough to only + implement ``__eq__`` in most cases). + + Passing True or False` to *init*, *repr*, *eq*, or *hash* + overrides whatever *auto_detect* would determine. + + auto_exc (bool): + If the class subclasses `BaseException` (which implicitly includes + any subclass of any exception), the following happens to behave + like a well-behaved Python exception class: + + - the values for *eq*, *order*, and *hash* are ignored and the + instances compare and hash by the instance's ids [#]_ , + - all attributes that are either passed into ``__init__`` or have a + default value are additionally available as a tuple in the + ``args`` attribute, + - the value of *str* is ignored leaving ``__str__`` to base + classes. + + .. [#] + Note that *attrs* will *not* remove existing implementations of + ``__hash__`` or the equality methods. It just won't add own + ones. + + on_setattr (~typing.Callable | list[~typing.Callable] | None | ~typing.Literal[attrs.setters.NO_OP]): + A callable that is run whenever the user attempts to set an + attribute (either by assignment like ``i.x = 42`` or by using + `setattr` like ``setattr(i, "x", 42)``). It receives the same + arguments as validators: the instance, the attribute that is being + modified, and the new value. + + If no exception is raised, the attribute is set to the return value + of the callable. + + If a list of callables is passed, they're automatically wrapped in + an `attrs.setters.pipe`. + + If left None, the default behavior is to run converters and + validators whenever an attribute is set. + + init (bool): + Create a ``__init__`` method that initializes the *attrs* + attributes. Leading underscores are stripped for the argument name, + unless an alias is set on the attribute. + + .. seealso:: + `init` shows advanced ways to customize the generated + ``__init__`` method, including executing code before and after. + + repr(bool): + Create a ``__repr__`` method with a human readable representation + of *attrs* attributes. + + str (bool): + Create a ``__str__`` method that is identical to ``__repr__``. This + is usually not necessary except for `Exception`\ s. + + eq (bool | None): + If True or None (default), add ``__eq__`` and ``__ne__`` methods + that check two instances for equality. + + .. seealso:: + `comparison` describes how to customize the comparison behavior + going as far comparing NumPy arrays. + + order (bool | None): + If True, add ``__lt__``, ``__le__``, ``__gt__``, and ``__ge__`` + methods that behave like *eq* above and allow instances to be + ordered. + + They compare the instances as if they were tuples of their *attrs* + attributes if and only if the types of both classes are + *identical*. + + If `None` mirror value of *eq*. + + .. seealso:: `comparison` + + unsafe_hash (bool | None): + If None (default), the ``__hash__`` method is generated according + how *eq* and *frozen* are set. + + 1. If *both* are True, *attrs* will generate a ``__hash__`` for + you. + 2. If *eq* is True and *frozen* is False, ``__hash__`` will be set + to None, marking it unhashable (which it is). + 3. If *eq* is False, ``__hash__`` will be left untouched meaning + the ``__hash__`` method of the base class will be used. If the + base class is `object`, this means it will fall back to id-based + hashing. + + Although not recommended, you can decide for yourself and force + *attrs* to create one (for example, if the class is immutable even + though you didn't freeze it programmatically) by passing True or + not. Both of these cases are rather special and should be used + carefully. + + .. seealso:: + + - Our documentation on `hashing`, + - Python's documentation on `object.__hash__`, + - and the `GitHub issue that led to the default \ behavior + `_ for more + details. + + hash (bool | None): + Deprecated alias for *unsafe_hash*. *unsafe_hash* takes precedence. + + cache_hash (bool): + Ensure that the object's hash code is computed only once and stored + on the object. If this is set to True, hashing must be either + explicitly or implicitly enabled for this class. If the hash code + is cached, avoid any reassignments of fields involved in hash code + computation or mutations of the objects those fields point to after + object creation. If such changes occur, the behavior of the + object's hash code is undefined. + + frozen (bool): + Make instances immutable after initialization. If someone attempts + to modify a frozen instance, `attrs.exceptions.FrozenInstanceError` + is raised. + + .. note:: + + 1. This is achieved by installing a custom ``__setattr__`` + method on your class, so you can't implement your own. + + 2. True immutability is impossible in Python. + + 3. This *does* have a minor a runtime performance `impact + ` when initializing new instances. In other + words: ``__init__`` is slightly slower with ``frozen=True``. + + 4. If a class is frozen, you cannot modify ``self`` in + ``__attrs_post_init__`` or a self-written ``__init__``. You + can circumvent that limitation by using + ``object.__setattr__(self, "attribute_name", value)``. + + 5. Subclasses of a frozen class are frozen too. + + kw_only (bool): + Make all attributes keyword-only in the generated ``__init__`` (if + *init* is False, this parameter is ignored). + + weakref_slot (bool): + Make instances weak-referenceable. This has no effect unless + *slots* is True. + + field_transformer (~typing.Callable | None): + A function that is called with the original class object and all + fields right before *attrs* finalizes the class. You can use this, + for example, to automatically add converters or validators to + fields based on their types. + + .. seealso:: `transform-fields` + + match_args (bool): + If True (default), set ``__match_args__`` on the class to support + :pep:`634` (*Structural Pattern Matching*). It is a tuple of all + non-keyword-only ``__init__`` parameter names on Python 3.10 and + later. Ignored on older Python versions. + + collect_by_mro (bool): + If True, *attrs* collects attributes from base classes correctly + according to the `method resolution order + `_. If False, *attrs* + will mimic the (wrong) behavior of `dataclasses` and :pep:`681`. + + See also `issue #428 + `_. + + getstate_setstate (bool | None): + .. note:: + + This is usually only interesting for slotted classes and you + should probably just set *auto_detect* to True. + + If True, ``__getstate__`` and ``__setstate__`` are generated and + attached to the class. This is necessary for slotted classes to be + pickleable. If left None, it's True by default for slotted classes + and False for dict classes. + + If *auto_detect* is True, and *getstate_setstate* is left None, and + **either** ``__getstate__`` or ``__setstate__`` is detected + directly on the class (meaning: not inherited), it is set to False + (this is usually what you want). + + auto_attribs (bool | None): + If True, look at type annotations to determine which attributes to + use, like `dataclasses`. If False, it will only look for explicit + :func:`field` class attributes, like classic *attrs*. + + If left None, it will guess: + + 1. If any attributes are annotated and no unannotated + `attrs.field`\ s are found, it assumes *auto_attribs=True*. + 2. Otherwise it assumes *auto_attribs=False* and tries to collect + `attrs.field`\ s. + + If *attrs* decides to look at type annotations, **all** fields + **must** be annotated. If *attrs* encounters a field that is set to + a :func:`field` / `attr.ib` but lacks a type annotation, an + `attrs.exceptions.UnannotatedAttributeError` is raised. Use + ``field_name: typing.Any = field(...)`` if you don't want to set a + type. + + .. warning:: + + For features that use the attribute name to create decorators + (for example, :ref:`validators `), you still *must* + assign :func:`field` / `attr.ib` to them. Otherwise Python will + either not find the name or try to use the default value to + call, for example, ``validator`` on it. + + Attributes annotated as `typing.ClassVar`, and attributes that are + neither annotated nor set to an `field()` are **ignored**. + + these (dict[str, object]): + A dictionary of name to the (private) return value of `field()` + mappings. This is useful to avoid the definition of your attributes + within the class body because you can't (for example, if you want + to add ``__repr__`` methods to Django models) or don't want to. + + If *these* is not `None`, *attrs* will *not* search the class body + for attributes and will *not* remove any attributes from it. + + The order is deduced from the order of the attributes inside + *these*. + + Arguably, this is a rather obscure feature. + + .. versionadded:: 20.1.0 + .. versionchanged:: 21.3.0 Converters are also run ``on_setattr``. + .. versionadded:: 22.2.0 + *unsafe_hash* as an alias for *hash* (for :pep:`681` compliance). + .. versionchanged:: 24.1.0 + Instances are not compared as tuples of attributes anymore, but using a + big ``and`` condition. This is faster and has more correct behavior for + uncomparable values like `math.nan`. + .. versionadded:: 24.1.0 + If a class has an *inherited* classmethod called + ``__attrs_init_subclass__``, it is executed after the class is created. + .. deprecated:: 24.1.0 *hash* is deprecated in favor of *unsafe_hash*. + .. versionadded:: 24.3.0 + Unless already present, a ``__replace__`` method is automatically + created for `copy.replace` (Python 3.13+ only). + + .. note:: + + The main differences to the classic `attr.s` are: + + - Automatically detect whether or not *auto_attribs* should be `True` + (c.f. *auto_attribs* parameter). + - Converters and validators run when attributes are set by default -- + if *frozen* is `False`. + - *slots=True* + + Usually, this has only upsides and few visible effects in everyday + programming. But it *can* lead to some surprising behaviors, so + please make sure to read :term:`slotted classes`. + + - *auto_exc=True* + - *auto_detect=True* + - *order=False* + - Some options that were only relevant on Python 2 or were kept around + for backwards-compatibility have been removed. + + """ + + def do_it(cls, auto_attribs): + return attrs( + maybe_cls=cls, + these=these, + repr=repr, + hash=hash, + unsafe_hash=unsafe_hash, + init=init, + slots=slots, + frozen=frozen, + weakref_slot=weakref_slot, + str=str, + auto_attribs=auto_attribs, + kw_only=kw_only, + cache_hash=cache_hash, + auto_exc=auto_exc, + eq=eq, + order=order, + auto_detect=auto_detect, + collect_by_mro=True, + getstate_setstate=getstate_setstate, + on_setattr=on_setattr, + field_transformer=field_transformer, + match_args=match_args, + ) + + def wrap(cls): + """ + Making this a wrapper ensures this code runs during class creation. + + We also ensure that frozen-ness of classes is inherited. + """ + nonlocal frozen, on_setattr + + had_on_setattr = on_setattr not in (None, setters.NO_OP) + + # By default, mutable classes convert & validate on setattr. + if frozen is False and on_setattr is None: + on_setattr = _DEFAULT_ON_SETATTR + + # However, if we subclass a frozen class, we inherit the immutability + # and disable on_setattr. + for base_cls in cls.__bases__: + if base_cls.__setattr__ is _frozen_setattrs: + if had_on_setattr: + msg = "Frozen classes can't use on_setattr (frozen-ness was inherited)." + raise ValueError(msg) + + on_setattr = setters.NO_OP + break + + if auto_attribs is not None: + return do_it(cls, auto_attribs) + + try: + return do_it(cls, True) + except UnannotatedAttributeError: + return do_it(cls, False) + + # maybe_cls's type depends on the usage of the decorator. It's a class + # if it's used as `@attrs` but `None` if used as `@attrs()`. + if maybe_cls is None: + return wrap + + return wrap(maybe_cls) + + +mutable = define +frozen = partial(define, frozen=True, on_setattr=None) + + +def field( + *, + default=NOTHING, + validator=None, + repr=True, + hash=None, + init=True, + metadata=None, + type=None, + converter=None, + factory=None, + kw_only=False, + eq=None, + order=None, + on_setattr=None, + alias=None, +): + """ + Create a new :term:`field` / :term:`attribute` on a class. + + .. warning:: + + Does **nothing** unless the class is also decorated with + `attrs.define` (or similar)! + + Args: + default: + A value that is used if an *attrs*-generated ``__init__`` is used + and no value is passed while instantiating or the attribute is + excluded using ``init=False``. + + If the value is an instance of `attrs.Factory`, its callable will + be used to construct a new value (useful for mutable data types + like lists or dicts). + + If a default is not set (or set manually to `attrs.NOTHING`), a + value *must* be supplied when instantiating; otherwise a + `TypeError` will be raised. + + .. seealso:: `defaults` + + factory (~typing.Callable): + Syntactic sugar for ``default=attr.Factory(factory)``. + + validator (~typing.Callable | list[~typing.Callable]): + Callable that is called by *attrs*-generated ``__init__`` methods + after the instance has been initialized. They receive the + initialized instance, the :func:`~attrs.Attribute`, and the passed + value. + + The return value is *not* inspected so the validator has to throw + an exception itself. + + If a `list` is passed, its items are treated as validators and must + all pass. + + Validators can be globally disabled and re-enabled using + `attrs.validators.get_disabled` / `attrs.validators.set_disabled`. + + The validator can also be set using decorator notation as shown + below. + + .. seealso:: :ref:`validators` + + repr (bool | ~typing.Callable): + Include this attribute in the generated ``__repr__`` method. If + True, include the attribute; if False, omit it. By default, the + built-in ``repr()`` function is used. To override how the attribute + value is formatted, pass a ``callable`` that takes a single value + and returns a string. Note that the resulting string is used as-is, + which means it will be used directly *instead* of calling + ``repr()`` (the default). + + eq (bool | ~typing.Callable): + If True (default), include this attribute in the generated + ``__eq__`` and ``__ne__`` methods that check two instances for + equality. To override how the attribute value is compared, pass a + callable that takes a single value and returns the value to be + compared. + + .. seealso:: `comparison` + + order (bool | ~typing.Callable): + If True (default), include this attributes in the generated + ``__lt__``, ``__le__``, ``__gt__`` and ``__ge__`` methods. To + override how the attribute value is ordered, pass a callable that + takes a single value and returns the value to be ordered. + + .. seealso:: `comparison` + + hash (bool | None): + Include this attribute in the generated ``__hash__`` method. If + None (default), mirror *eq*'s value. This is the correct behavior + according the Python spec. Setting this value to anything else + than None is *discouraged*. + + .. seealso:: `hashing` + + init (bool): + Include this attribute in the generated ``__init__`` method. + + It is possible to set this to False and set a default value. In + that case this attributed is unconditionally initialized with the + specified default value or factory. + + .. seealso:: `init` + + converter (typing.Callable | Converter): + A callable that is called by *attrs*-generated ``__init__`` methods + to convert attribute's value to the desired format. + + If a vanilla callable is passed, it is given the passed-in value as + the only positional argument. It is possible to receive additional + arguments by wrapping the callable in a `Converter`. + + Either way, the returned value will be used as the new value of the + attribute. The value is converted before being passed to the + validator, if any. + + .. seealso:: :ref:`converters` + + metadata (dict | None): + An arbitrary mapping, to be used by third-party code. + + .. seealso:: `extending-metadata`. + + type (type): + The type of the attribute. Nowadays, the preferred method to + specify the type is using a variable annotation (see :pep:`526`). + This argument is provided for backwards-compatibility and for usage + with `make_class`. Regardless of the approach used, the type will + be stored on ``Attribute.type``. + + Please note that *attrs* doesn't do anything with this metadata by + itself. You can use it as part of your own code or for `static type + checking `. + + kw_only (bool): + Make this attribute keyword-only in the generated ``__init__`` (if + ``init`` is False, this parameter is ignored). + + on_setattr (~typing.Callable | list[~typing.Callable] | None | ~typing.Literal[attrs.setters.NO_OP]): + Allows to overwrite the *on_setattr* setting from `attr.s`. If left + None, the *on_setattr* value from `attr.s` is used. Set to + `attrs.setters.NO_OP` to run **no** `setattr` hooks for this + attribute -- regardless of the setting in `define()`. + + alias (str | None): + Override this attribute's parameter name in the generated + ``__init__`` method. If left None, default to ``name`` stripped + of leading underscores. See `private-attributes`. + + .. versionadded:: 20.1.0 + .. versionchanged:: 21.1.0 + *eq*, *order*, and *cmp* also accept a custom callable + .. versionadded:: 22.2.0 *alias* + .. versionadded:: 23.1.0 + The *type* parameter has been re-added; mostly for `attrs.make_class`. + Please note that type checkers ignore this metadata. + + .. seealso:: + + `attr.ib` + """ + return attrib( + default=default, + validator=validator, + repr=repr, + hash=hash, + init=init, + metadata=metadata, + type=type, + converter=converter, + factory=factory, + kw_only=kw_only, + eq=eq, + order=order, + on_setattr=on_setattr, + alias=alias, + ) + + +def asdict(inst, *, recurse=True, filter=None, value_serializer=None): + """ + Same as `attr.asdict`, except that collections types are always retained + and dict is always used as *dict_factory*. + + .. versionadded:: 21.3.0 + """ + return _asdict( + inst=inst, + recurse=recurse, + filter=filter, + value_serializer=value_serializer, + retain_collection_types=True, + ) + + +def astuple(inst, *, recurse=True, filter=None): + """ + Same as `attr.astuple`, except that collections types are always retained + and `tuple` is always used as the *tuple_factory*. + + .. versionadded:: 21.3.0 + """ + return _astuple( + inst=inst, recurse=recurse, filter=filter, retain_collection_types=True + ) diff --git a/venv/lib/python3.10/site-packages/attr/_typing_compat.pyi b/venv/lib/python3.10/site-packages/attr/_typing_compat.pyi new file mode 100644 index 0000000000000000000000000000000000000000..ca7b71e906a28f88726bbd342fdfe636af0281e7 --- /dev/null +++ b/venv/lib/python3.10/site-packages/attr/_typing_compat.pyi @@ -0,0 +1,15 @@ +from typing import Any, ClassVar, Protocol + +# MYPY is a special constant in mypy which works the same way as `TYPE_CHECKING`. +MYPY = False + +if MYPY: + # A protocol to be able to statically accept an attrs class. + class AttrsInstance_(Protocol): + __attrs_attrs__: ClassVar[Any] + +else: + # For type checkers without plug-in support use an empty protocol that + # will (hopefully) be combined into a union. + class AttrsInstance_(Protocol): + pass diff --git a/venv/lib/python3.10/site-packages/attr/_version_info.py b/venv/lib/python3.10/site-packages/attr/_version_info.py new file mode 100644 index 0000000000000000000000000000000000000000..51a1312f9759f21063caea779a62882d7f7c86ae --- /dev/null +++ b/venv/lib/python3.10/site-packages/attr/_version_info.py @@ -0,0 +1,86 @@ +# SPDX-License-Identifier: MIT + + +from functools import total_ordering + +from ._funcs import astuple +from ._make import attrib, attrs + + +@total_ordering +@attrs(eq=False, order=False, slots=True, frozen=True) +class VersionInfo: + """ + A version object that can be compared to tuple of length 1--4: + + >>> attr.VersionInfo(19, 1, 0, "final") <= (19, 2) + True + >>> attr.VersionInfo(19, 1, 0, "final") < (19, 1, 1) + True + >>> vi = attr.VersionInfo(19, 2, 0, "final") + >>> vi < (19, 1, 1) + False + >>> vi < (19,) + False + >>> vi == (19, 2,) + True + >>> vi == (19, 2, 1) + False + + .. versionadded:: 19.2 + """ + + year = attrib(type=int) + minor = attrib(type=int) + micro = attrib(type=int) + releaselevel = attrib(type=str) + + @classmethod + def _from_version_string(cls, s): + """ + Parse *s* and return a _VersionInfo. + """ + v = s.split(".") + if len(v) == 3: + v.append("final") + + return cls( + year=int(v[0]), minor=int(v[1]), micro=int(v[2]), releaselevel=v[3] + ) + + def _ensure_tuple(self, other): + """ + Ensure *other* is a tuple of a valid length. + + Returns a possibly transformed *other* and ourselves as a tuple of + the same length as *other*. + """ + + if self.__class__ is other.__class__: + other = astuple(other) + + if not isinstance(other, tuple): + raise NotImplementedError + + if not (1 <= len(other) <= 4): + raise NotImplementedError + + return astuple(self)[: len(other)], other + + def __eq__(self, other): + try: + us, them = self._ensure_tuple(other) + except NotImplementedError: + return NotImplemented + + return us == them + + def __lt__(self, other): + try: + us, them = self._ensure_tuple(other) + except NotImplementedError: + return NotImplemented + + # Since alphabetically "dev0" < "final" < "post1" < "post2", we don't + # have to do anything special with releaselevel for now. + return us < them diff --git a/venv/lib/python3.10/site-packages/attr/_version_info.pyi b/venv/lib/python3.10/site-packages/attr/_version_info.pyi new file mode 100644 index 0000000000000000000000000000000000000000..45ced086337783c4b73b26cd17d2c1c260e24029 --- /dev/null +++ b/venv/lib/python3.10/site-packages/attr/_version_info.pyi @@ -0,0 +1,9 @@ +class VersionInfo: + @property + def year(self) -> int: ... + @property + def minor(self) -> int: ... + @property + def micro(self) -> int: ... + @property + def releaselevel(self) -> str: ... diff --git a/venv/lib/python3.10/site-packages/attr/converters.py b/venv/lib/python3.10/site-packages/attr/converters.py new file mode 100644 index 0000000000000000000000000000000000000000..0a79deef04282fb33a42f6aca59563d49e70d4cb --- /dev/null +++ b/venv/lib/python3.10/site-packages/attr/converters.py @@ -0,0 +1,162 @@ +# SPDX-License-Identifier: MIT + +""" +Commonly useful converters. +""" + +import typing + +from ._compat import _AnnotationExtractor +from ._make import NOTHING, Converter, Factory, pipe + + +__all__ = [ + "default_if_none", + "optional", + "pipe", + "to_bool", +] + + +def optional(converter): + """ + A converter that allows an attribute to be optional. An optional attribute + is one which can be set to `None`. + + Type annotations will be inferred from the wrapped converter's, if it has + any. + + Args: + converter (typing.Callable): + the converter that is used for non-`None` values. + + .. versionadded:: 17.1.0 + """ + + if isinstance(converter, Converter): + + def optional_converter(val, inst, field): + if val is None: + return None + return converter(val, inst, field) + + else: + + def optional_converter(val): + if val is None: + return None + return converter(val) + + xtr = _AnnotationExtractor(converter) + + t = xtr.get_first_param_type() + if t: + optional_converter.__annotations__["val"] = typing.Optional[t] + + rt = xtr.get_return_type() + if rt: + optional_converter.__annotations__["return"] = typing.Optional[rt] + + if isinstance(converter, Converter): + return Converter(optional_converter, takes_self=True, takes_field=True) + + return optional_converter + + +def default_if_none(default=NOTHING, factory=None): + """ + A converter that allows to replace `None` values by *default* or the result + of *factory*. + + Args: + default: + Value to be used if `None` is passed. Passing an instance of + `attrs.Factory` is supported, however the ``takes_self`` option is + *not*. + + factory (typing.Callable): + A callable that takes no parameters whose result is used if `None` + is passed. + + Raises: + TypeError: If **neither** *default* or *factory* is passed. + + TypeError: If **both** *default* and *factory* are passed. + + ValueError: + If an instance of `attrs.Factory` is passed with + ``takes_self=True``. + + .. versionadded:: 18.2.0 + """ + if default is NOTHING and factory is None: + msg = "Must pass either `default` or `factory`." + raise TypeError(msg) + + if default is not NOTHING and factory is not None: + msg = "Must pass either `default` or `factory` but not both." + raise TypeError(msg) + + if factory is not None: + default = Factory(factory) + + if isinstance(default, Factory): + if default.takes_self: + msg = "`takes_self` is not supported by default_if_none." + raise ValueError(msg) + + def default_if_none_converter(val): + if val is not None: + return val + + return default.factory() + + else: + + def default_if_none_converter(val): + if val is not None: + return val + + return default + + return default_if_none_converter + + +def to_bool(val): + """ + Convert "boolean" strings (for example, from environment variables) to real + booleans. + + Values mapping to `True`: + + - ``True`` + - ``"true"`` / ``"t"`` + - ``"yes"`` / ``"y"`` + - ``"on"`` + - ``"1"`` + - ``1`` + + Values mapping to `False`: + + - ``False`` + - ``"false"`` / ``"f"`` + - ``"no"`` / ``"n"`` + - ``"off"`` + - ``"0"`` + - ``0`` + + Raises: + ValueError: For any other value. + + .. versionadded:: 21.3.0 + """ + if isinstance(val, str): + val = val.lower() + + if val in (True, "true", "t", "yes", "y", "on", "1", 1): + return True + if val in (False, "false", "f", "no", "n", "off", "0", 0): + return False + + msg = f"Cannot convert value to bool: {val!r}" + raise ValueError(msg) diff --git a/venv/lib/python3.10/site-packages/attr/converters.pyi b/venv/lib/python3.10/site-packages/attr/converters.pyi new file mode 100644 index 0000000000000000000000000000000000000000..12bd0c4f17bdc60fb8904598af0a3d56d5874a9e --- /dev/null +++ b/venv/lib/python3.10/site-packages/attr/converters.pyi @@ -0,0 +1,19 @@ +from typing import Callable, Any, overload + +from attrs import _ConverterType, _CallableConverterType + +@overload +def pipe(*validators: _CallableConverterType) -> _CallableConverterType: ... +@overload +def pipe(*validators: _ConverterType) -> _ConverterType: ... +@overload +def optional(converter: _CallableConverterType) -> _CallableConverterType: ... +@overload +def optional(converter: _ConverterType) -> _ConverterType: ... +@overload +def default_if_none(default: Any) -> _CallableConverterType: ... +@overload +def default_if_none( + *, factory: Callable[[], Any] +) -> _CallableConverterType: ... +def to_bool(val: str | int | bool) -> bool: ... diff --git a/venv/lib/python3.10/site-packages/attr/exceptions.py b/venv/lib/python3.10/site-packages/attr/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..3b7abb8154108aa1d0ae52fa9ee8e489f05b5563 --- /dev/null +++ b/venv/lib/python3.10/site-packages/attr/exceptions.py @@ -0,0 +1,95 @@ +# SPDX-License-Identifier: MIT + +from __future__ import annotations + +from typing import ClassVar + + +class FrozenError(AttributeError): + """ + A frozen/immutable instance or attribute have been attempted to be + modified. + + It mirrors the behavior of ``namedtuples`` by using the same error message + and subclassing `AttributeError`. + + .. versionadded:: 20.1.0 + """ + + msg = "can't set attribute" + args: ClassVar[tuple[str]] = [msg] + + +class FrozenInstanceError(FrozenError): + """ + A frozen instance has been attempted to be modified. + + .. versionadded:: 16.1.0 + """ + + +class FrozenAttributeError(FrozenError): + """ + A frozen attribute has been attempted to be modified. + + .. versionadded:: 20.1.0 + """ + + +class AttrsAttributeNotFoundError(ValueError): + """ + An *attrs* function couldn't find an attribute that the user asked for. + + .. versionadded:: 16.2.0 + """ + + +class NotAnAttrsClassError(ValueError): + """ + A non-*attrs* class has been passed into an *attrs* function. + + .. versionadded:: 16.2.0 + """ + + +class DefaultAlreadySetError(RuntimeError): + """ + A default has been set when defining the field and is attempted to be reset + using the decorator. + + .. versionadded:: 17.1.0 + """ + + +class UnannotatedAttributeError(RuntimeError): + """ + A class with ``auto_attribs=True`` has a field without a type annotation. + + .. versionadded:: 17.3.0 + """ + + +class PythonTooOldError(RuntimeError): + """ + It was attempted to use an *attrs* feature that requires a newer Python + version. + + .. versionadded:: 18.2.0 + """ + + +class NotCallableError(TypeError): + """ + A field requiring a callable has been set with a value that is not + callable. + + .. versionadded:: 19.2.0 + """ + + def __init__(self, msg, value): + super(TypeError, self).__init__(msg, value) + self.msg = msg + self.value = value + + def __str__(self): + return str(self.msg) diff --git a/venv/lib/python3.10/site-packages/attr/exceptions.pyi b/venv/lib/python3.10/site-packages/attr/exceptions.pyi new file mode 100644 index 0000000000000000000000000000000000000000..f2680118b404db8f5227d04d27e8439331341c4d --- /dev/null +++ b/venv/lib/python3.10/site-packages/attr/exceptions.pyi @@ -0,0 +1,17 @@ +from typing import Any + +class FrozenError(AttributeError): + msg: str = ... + +class FrozenInstanceError(FrozenError): ... +class FrozenAttributeError(FrozenError): ... +class AttrsAttributeNotFoundError(ValueError): ... +class NotAnAttrsClassError(ValueError): ... +class DefaultAlreadySetError(RuntimeError): ... +class UnannotatedAttributeError(RuntimeError): ... +class PythonTooOldError(RuntimeError): ... + +class NotCallableError(TypeError): + msg: str = ... + value: Any = ... + def __init__(self, msg: str, value: Any) -> None: ... diff --git a/venv/lib/python3.10/site-packages/attr/filters.py b/venv/lib/python3.10/site-packages/attr/filters.py new file mode 100644 index 0000000000000000000000000000000000000000..689b1705a60ff110d6077bab996f8b4588e55b82 --- /dev/null +++ b/venv/lib/python3.10/site-packages/attr/filters.py @@ -0,0 +1,72 @@ +# SPDX-License-Identifier: MIT + +""" +Commonly useful filters for `attrs.asdict` and `attrs.astuple`. +""" + +from ._make import Attribute + + +def _split_what(what): + """ + Returns a tuple of `frozenset`s of classes and attributes. + """ + return ( + frozenset(cls for cls in what if isinstance(cls, type)), + frozenset(cls for cls in what if isinstance(cls, str)), + frozenset(cls for cls in what if isinstance(cls, Attribute)), + ) + + +def include(*what): + """ + Create a filter that only allows *what*. + + Args: + what (list[type, str, attrs.Attribute]): + What to include. Can be a type, a name, or an attribute. + + Returns: + Callable: + A callable that can be passed to `attrs.asdict`'s and + `attrs.astuple`'s *filter* argument. + + .. versionchanged:: 23.1.0 Accept strings with field names. + """ + cls, names, attrs = _split_what(what) + + def include_(attribute, value): + return ( + value.__class__ in cls + or attribute.name in names + or attribute in attrs + ) + + return include_ + + +def exclude(*what): + """ + Create a filter that does **not** allow *what*. + + Args: + what (list[type, str, attrs.Attribute]): + What to exclude. Can be a type, a name, or an attribute. + + Returns: + Callable: + A callable that can be passed to `attrs.asdict`'s and + `attrs.astuple`'s *filter* argument. + + .. versionchanged:: 23.3.0 Accept field name string as input argument + """ + cls, names, attrs = _split_what(what) + + def exclude_(attribute, value): + return not ( + value.__class__ in cls + or attribute.name in names + or attribute in attrs + ) + + return exclude_ diff --git a/venv/lib/python3.10/site-packages/attr/filters.pyi b/venv/lib/python3.10/site-packages/attr/filters.pyi new file mode 100644 index 0000000000000000000000000000000000000000..974abdcdb51152393d9c9e460c21aa025c45880c --- /dev/null +++ b/venv/lib/python3.10/site-packages/attr/filters.pyi @@ -0,0 +1,6 @@ +from typing import Any + +from . import Attribute, _FilterType + +def include(*what: type | str | Attribute[Any]) -> _FilterType[Any]: ... +def exclude(*what: type | str | Attribute[Any]) -> _FilterType[Any]: ... diff --git a/venv/lib/python3.10/site-packages/attr/py.typed b/venv/lib/python3.10/site-packages/attr/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/attr/setters.py b/venv/lib/python3.10/site-packages/attr/setters.py new file mode 100644 index 0000000000000000000000000000000000000000..78b08398a6713fc5fa827c2dc853e0d05de743c4 --- /dev/null +++ b/venv/lib/python3.10/site-packages/attr/setters.py @@ -0,0 +1,79 @@ +# SPDX-License-Identifier: MIT + +""" +Commonly used hooks for on_setattr. +""" + +from . import _config +from .exceptions import FrozenAttributeError + + +def pipe(*setters): + """ + Run all *setters* and return the return value of the last one. + + .. versionadded:: 20.1.0 + """ + + def wrapped_pipe(instance, attrib, new_value): + rv = new_value + + for setter in setters: + rv = setter(instance, attrib, rv) + + return rv + + return wrapped_pipe + + +def frozen(_, __, ___): + """ + Prevent an attribute to be modified. + + .. versionadded:: 20.1.0 + """ + raise FrozenAttributeError + + +def validate(instance, attrib, new_value): + """ + Run *attrib*'s validator on *new_value* if it has one. + + .. versionadded:: 20.1.0 + """ + if _config._run_validators is False: + return new_value + + v = attrib.validator + if not v: + return new_value + + v(instance, attrib, new_value) + + return new_value + + +def convert(instance, attrib, new_value): + """ + Run *attrib*'s converter -- if it has one -- on *new_value* and return the + result. + + .. versionadded:: 20.1.0 + """ + c = attrib.converter + if c: + # This can be removed once we drop 3.8 and use attrs.Converter instead. + from ._make import Converter + + if not isinstance(c, Converter): + return c(new_value) + + return c(new_value, instance, attrib) + + return new_value + + +# Sentinel for disabling class-wide *on_setattr* hooks for certain attributes. +# Sphinx's autodata stopped working, so the docstring is inlined in the API +# docs. +NO_OP = object() diff --git a/venv/lib/python3.10/site-packages/attr/setters.pyi b/venv/lib/python3.10/site-packages/attr/setters.pyi new file mode 100644 index 0000000000000000000000000000000000000000..73abf36e7d5b0f5f56e7fddeee716824c1c60d58 --- /dev/null +++ b/venv/lib/python3.10/site-packages/attr/setters.pyi @@ -0,0 +1,20 @@ +from typing import Any, NewType, NoReturn, TypeVar + +from . import Attribute +from attrs import _OnSetAttrType + +_T = TypeVar("_T") + +def frozen( + instance: Any, attribute: Attribute[Any], new_value: Any +) -> NoReturn: ... +def pipe(*setters: _OnSetAttrType) -> _OnSetAttrType: ... +def validate(instance: Any, attribute: Attribute[_T], new_value: _T) -> _T: ... + +# convert is allowed to return Any, because they can be chained using pipe. +def convert( + instance: Any, attribute: Attribute[Any], new_value: Any +) -> Any: ... + +_NoOpType = NewType("_NoOpType", object) +NO_OP: _NoOpType diff --git a/venv/lib/python3.10/site-packages/attr/validators.py b/venv/lib/python3.10/site-packages/attr/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..e7b75525022a9d98f8153f17a0fed103b24c743b --- /dev/null +++ b/venv/lib/python3.10/site-packages/attr/validators.py @@ -0,0 +1,710 @@ +# SPDX-License-Identifier: MIT + +""" +Commonly useful validators. +""" + +import operator +import re + +from contextlib import contextmanager +from re import Pattern + +from ._config import get_run_validators, set_run_validators +from ._make import _AndValidator, and_, attrib, attrs +from .converters import default_if_none +from .exceptions import NotCallableError + + +__all__ = [ + "and_", + "deep_iterable", + "deep_mapping", + "disabled", + "ge", + "get_disabled", + "gt", + "in_", + "instance_of", + "is_callable", + "le", + "lt", + "matches_re", + "max_len", + "min_len", + "not_", + "optional", + "or_", + "set_disabled", +] + + +def set_disabled(disabled): + """ + Globally disable or enable running validators. + + By default, they are run. + + Args: + disabled (bool): If `True`, disable running all validators. + + .. warning:: + + This function is not thread-safe! + + .. versionadded:: 21.3.0 + """ + set_run_validators(not disabled) + + +def get_disabled(): + """ + Return a bool indicating whether validators are currently disabled or not. + + Returns: + bool:`True` if validators are currently disabled. + + .. versionadded:: 21.3.0 + """ + return not get_run_validators() + + +@contextmanager +def disabled(): + """ + Context manager that disables running validators within its context. + + .. warning:: + + This context manager is not thread-safe! + + .. versionadded:: 21.3.0 + """ + set_run_validators(False) + try: + yield + finally: + set_run_validators(True) + + +@attrs(repr=False, slots=True, unsafe_hash=True) +class _InstanceOfValidator: + type = attrib() + + def __call__(self, inst, attr, value): + """ + We use a callable class to be able to change the ``__repr__``. + """ + if not isinstance(value, self.type): + msg = f"'{attr.name}' must be {self.type!r} (got {value!r} that is a {value.__class__!r})." + raise TypeError( + msg, + attr, + self.type, + value, + ) + + def __repr__(self): + return f"" + + +def instance_of(type): + """ + A validator that raises a `TypeError` if the initializer is called with a + wrong type for this particular attribute (checks are performed using + `isinstance` therefore it's also valid to pass a tuple of types). + + Args: + type (type | tuple[type]): The type to check for. + + Raises: + TypeError: + With a human readable error message, the attribute (of type + `attrs.Attribute`), the expected type, and the value it got. + """ + return _InstanceOfValidator(type) + + +@attrs(repr=False, frozen=True, slots=True) +class _MatchesReValidator: + pattern = attrib() + match_func = attrib() + + def __call__(self, inst, attr, value): + """ + We use a callable class to be able to change the ``__repr__``. + """ + if not self.match_func(value): + msg = f"'{attr.name}' must match regex {self.pattern.pattern!r} ({value!r} doesn't)" + raise ValueError( + msg, + attr, + self.pattern, + value, + ) + + def __repr__(self): + return f"" + + +def matches_re(regex, flags=0, func=None): + r""" + A validator that raises `ValueError` if the initializer is called with a + string that doesn't match *regex*. + + Args: + regex (str, re.Pattern): + A regex string or precompiled pattern to match against + + flags (int): + Flags that will be passed to the underlying re function (default 0) + + func (typing.Callable): + Which underlying `re` function to call. Valid options are + `re.fullmatch`, `re.search`, and `re.match`; the default `None` + means `re.fullmatch`. For performance reasons, the pattern is + always precompiled using `re.compile`. + + .. versionadded:: 19.2.0 + .. versionchanged:: 21.3.0 *regex* can be a pre-compiled pattern. + """ + valid_funcs = (re.fullmatch, None, re.search, re.match) + if func not in valid_funcs: + msg = "'func' must be one of {}.".format( + ", ".join( + sorted((e and e.__name__) or "None" for e in set(valid_funcs)) + ) + ) + raise ValueError(msg) + + if isinstance(regex, Pattern): + if flags: + msg = "'flags' can only be used with a string pattern; pass flags to re.compile() instead" + raise TypeError(msg) + pattern = regex + else: + pattern = re.compile(regex, flags) + + if func is re.match: + match_func = pattern.match + elif func is re.search: + match_func = pattern.search + else: + match_func = pattern.fullmatch + + return _MatchesReValidator(pattern, match_func) + + +@attrs(repr=False, slots=True, unsafe_hash=True) +class _OptionalValidator: + validator = attrib() + + def __call__(self, inst, attr, value): + if value is None: + return + + self.validator(inst, attr, value) + + def __repr__(self): + return f"" + + +def optional(validator): + """ + A validator that makes an attribute optional. An optional attribute is one + which can be set to `None` in addition to satisfying the requirements of + the sub-validator. + + Args: + validator + (typing.Callable | tuple[typing.Callable] | list[typing.Callable]): + A validator (or validators) that is used for non-`None` values. + + .. versionadded:: 15.1.0 + .. versionchanged:: 17.1.0 *validator* can be a list of validators. + .. versionchanged:: 23.1.0 *validator* can also be a tuple of validators. + """ + if isinstance(validator, (list, tuple)): + return _OptionalValidator(_AndValidator(validator)) + + return _OptionalValidator(validator) + + +@attrs(repr=False, slots=True, unsafe_hash=True) +class _InValidator: + options = attrib() + _original_options = attrib(hash=False) + + def __call__(self, inst, attr, value): + try: + in_options = value in self.options + except TypeError: # e.g. `1 in "abc"` + in_options = False + + if not in_options: + msg = f"'{attr.name}' must be in {self._original_options!r} (got {value!r})" + raise ValueError( + msg, + attr, + self._original_options, + value, + ) + + def __repr__(self): + return f"" + + +def in_(options): + """ + A validator that raises a `ValueError` if the initializer is called with a + value that does not belong in the *options* provided. + + The check is performed using ``value in options``, so *options* has to + support that operation. + + To keep the validator hashable, dicts, lists, and sets are transparently + transformed into a `tuple`. + + Args: + options: Allowed options. + + Raises: + ValueError: + With a human readable error message, the attribute (of type + `attrs.Attribute`), the expected options, and the value it got. + + .. versionadded:: 17.1.0 + .. versionchanged:: 22.1.0 + The ValueError was incomplete until now and only contained the human + readable error message. Now it contains all the information that has + been promised since 17.1.0. + .. versionchanged:: 24.1.0 + *options* that are a list, dict, or a set are now transformed into a + tuple to keep the validator hashable. + """ + repr_options = options + if isinstance(options, (list, dict, set)): + options = tuple(options) + + return _InValidator(options, repr_options) + + +@attrs(repr=False, slots=False, unsafe_hash=True) +class _IsCallableValidator: + def __call__(self, inst, attr, value): + """ + We use a callable class to be able to change the ``__repr__``. + """ + if not callable(value): + message = ( + "'{name}' must be callable " + "(got {value!r} that is a {actual!r})." + ) + raise NotCallableError( + msg=message.format( + name=attr.name, value=value, actual=value.__class__ + ), + value=value, + ) + + def __repr__(self): + return "" + + +def is_callable(): + """ + A validator that raises a `attrs.exceptions.NotCallableError` if the + initializer is called with a value for this particular attribute that is + not callable. + + .. versionadded:: 19.1.0 + + Raises: + attrs.exceptions.NotCallableError: + With a human readable error message containing the attribute + (`attrs.Attribute`) name, and the value it got. + """ + return _IsCallableValidator() + + +@attrs(repr=False, slots=True, unsafe_hash=True) +class _DeepIterable: + member_validator = attrib(validator=is_callable()) + iterable_validator = attrib( + default=None, validator=optional(is_callable()) + ) + + def __call__(self, inst, attr, value): + """ + We use a callable class to be able to change the ``__repr__``. + """ + if self.iterable_validator is not None: + self.iterable_validator(inst, attr, value) + + for member in value: + self.member_validator(inst, attr, member) + + def __repr__(self): + iterable_identifier = ( + "" + if self.iterable_validator is None + else f" {self.iterable_validator!r}" + ) + return ( + f"" + ) + + +def deep_iterable(member_validator, iterable_validator=None): + """ + A validator that performs deep validation of an iterable. + + Args: + member_validator: Validator to apply to iterable members. + + iterable_validator: + Validator to apply to iterable itself (optional). + + Raises + TypeError: if any sub-validators fail + + .. versionadded:: 19.1.0 + """ + if isinstance(member_validator, (list, tuple)): + member_validator = and_(*member_validator) + return _DeepIterable(member_validator, iterable_validator) + + +@attrs(repr=False, slots=True, unsafe_hash=True) +class _DeepMapping: + key_validator = attrib(validator=is_callable()) + value_validator = attrib(validator=is_callable()) + mapping_validator = attrib(default=None, validator=optional(is_callable())) + + def __call__(self, inst, attr, value): + """ + We use a callable class to be able to change the ``__repr__``. + """ + if self.mapping_validator is not None: + self.mapping_validator(inst, attr, value) + + for key in value: + self.key_validator(inst, attr, key) + self.value_validator(inst, attr, value[key]) + + def __repr__(self): + return f"" + + +def deep_mapping(key_validator, value_validator, mapping_validator=None): + """ + A validator that performs deep validation of a dictionary. + + Args: + key_validator: Validator to apply to dictionary keys. + + value_validator: Validator to apply to dictionary values. + + mapping_validator: + Validator to apply to top-level mapping attribute (optional). + + .. versionadded:: 19.1.0 + + Raises: + TypeError: if any sub-validators fail + """ + return _DeepMapping(key_validator, value_validator, mapping_validator) + + +@attrs(repr=False, frozen=True, slots=True) +class _NumberValidator: + bound = attrib() + compare_op = attrib() + compare_func = attrib() + + def __call__(self, inst, attr, value): + """ + We use a callable class to be able to change the ``__repr__``. + """ + if not self.compare_func(value, self.bound): + msg = f"'{attr.name}' must be {self.compare_op} {self.bound}: {value}" + raise ValueError(msg) + + def __repr__(self): + return f"" + + +def lt(val): + """ + A validator that raises `ValueError` if the initializer is called with a + number larger or equal to *val*. + + The validator uses `operator.lt` to compare the values. + + Args: + val: Exclusive upper bound for values. + + .. versionadded:: 21.3.0 + """ + return _NumberValidator(val, "<", operator.lt) + + +def le(val): + """ + A validator that raises `ValueError` if the initializer is called with a + number greater than *val*. + + The validator uses `operator.le` to compare the values. + + Args: + val: Inclusive upper bound for values. + + .. versionadded:: 21.3.0 + """ + return _NumberValidator(val, "<=", operator.le) + + +def ge(val): + """ + A validator that raises `ValueError` if the initializer is called with a + number smaller than *val*. + + The validator uses `operator.ge` to compare the values. + + Args: + val: Inclusive lower bound for values + + .. versionadded:: 21.3.0 + """ + return _NumberValidator(val, ">=", operator.ge) + + +def gt(val): + """ + A validator that raises `ValueError` if the initializer is called with a + number smaller or equal to *val*. + + The validator uses `operator.ge` to compare the values. + + Args: + val: Exclusive lower bound for values + + .. versionadded:: 21.3.0 + """ + return _NumberValidator(val, ">", operator.gt) + + +@attrs(repr=False, frozen=True, slots=True) +class _MaxLengthValidator: + max_length = attrib() + + def __call__(self, inst, attr, value): + """ + We use a callable class to be able to change the ``__repr__``. + """ + if len(value) > self.max_length: + msg = f"Length of '{attr.name}' must be <= {self.max_length}: {len(value)}" + raise ValueError(msg) + + def __repr__(self): + return f"" + + +def max_len(length): + """ + A validator that raises `ValueError` if the initializer is called + with a string or iterable that is longer than *length*. + + Args: + length (int): Maximum length of the string or iterable + + .. versionadded:: 21.3.0 + """ + return _MaxLengthValidator(length) + + +@attrs(repr=False, frozen=True, slots=True) +class _MinLengthValidator: + min_length = attrib() + + def __call__(self, inst, attr, value): + """ + We use a callable class to be able to change the ``__repr__``. + """ + if len(value) < self.min_length: + msg = f"Length of '{attr.name}' must be >= {self.min_length}: {len(value)}" + raise ValueError(msg) + + def __repr__(self): + return f"" + + +def min_len(length): + """ + A validator that raises `ValueError` if the initializer is called + with a string or iterable that is shorter than *length*. + + Args: + length (int): Minimum length of the string or iterable + + .. versionadded:: 22.1.0 + """ + return _MinLengthValidator(length) + + +@attrs(repr=False, slots=True, unsafe_hash=True) +class _SubclassOfValidator: + type = attrib() + + def __call__(self, inst, attr, value): + """ + We use a callable class to be able to change the ``__repr__``. + """ + if not issubclass(value, self.type): + msg = f"'{attr.name}' must be a subclass of {self.type!r} (got {value!r})." + raise TypeError( + msg, + attr, + self.type, + value, + ) + + def __repr__(self): + return f"" + + +def _subclass_of(type): + """ + A validator that raises a `TypeError` if the initializer is called with a + wrong type for this particular attribute (checks are performed using + `issubclass` therefore it's also valid to pass a tuple of types). + + Args: + type (type | tuple[type, ...]): The type(s) to check for. + + Raises: + TypeError: + With a human readable error message, the attribute (of type + `attrs.Attribute`), the expected type, and the value it got. + """ + return _SubclassOfValidator(type) + + +@attrs(repr=False, slots=True, unsafe_hash=True) +class _NotValidator: + validator = attrib() + msg = attrib( + converter=default_if_none( + "not_ validator child '{validator!r}' " + "did not raise a captured error" + ) + ) + exc_types = attrib( + validator=deep_iterable( + member_validator=_subclass_of(Exception), + iterable_validator=instance_of(tuple), + ), + ) + + def __call__(self, inst, attr, value): + try: + self.validator(inst, attr, value) + except self.exc_types: + pass # suppress error to invert validity + else: + raise ValueError( + self.msg.format( + validator=self.validator, + exc_types=self.exc_types, + ), + attr, + self.validator, + value, + self.exc_types, + ) + + def __repr__(self): + return f"" + + +def not_(validator, *, msg=None, exc_types=(ValueError, TypeError)): + """ + A validator that wraps and logically 'inverts' the validator passed to it. + It will raise a `ValueError` if the provided validator *doesn't* raise a + `ValueError` or `TypeError` (by default), and will suppress the exception + if the provided validator *does*. + + Intended to be used with existing validators to compose logic without + needing to create inverted variants, for example, ``not_(in_(...))``. + + Args: + validator: A validator to be logically inverted. + + msg (str): + Message to raise if validator fails. Formatted with keys + ``exc_types`` and ``validator``. + + exc_types (tuple[type, ...]): + Exception type(s) to capture. Other types raised by child + validators will not be intercepted and pass through. + + Raises: + ValueError: + With a human readable error message, the attribute (of type + `attrs.Attribute`), the validator that failed to raise an + exception, the value it got, and the expected exception types. + + .. versionadded:: 22.2.0 + """ + try: + exc_types = tuple(exc_types) + except TypeError: + exc_types = (exc_types,) + return _NotValidator(validator, msg, exc_types) + + +@attrs(repr=False, slots=True, unsafe_hash=True) +class _OrValidator: + validators = attrib() + + def __call__(self, inst, attr, value): + for v in self.validators: + try: + v(inst, attr, value) + except Exception: # noqa: BLE001, PERF203, S112 + continue + else: + return + + msg = f"None of {self.validators!r} satisfied for value {value!r}" + raise ValueError(msg) + + def __repr__(self): + return f"" + + +def or_(*validators): + """ + A validator that composes multiple validators into one. + + When called on a value, it runs all wrapped validators until one of them is + satisfied. + + Args: + validators (~collections.abc.Iterable[typing.Callable]): + Arbitrary number of validators. + + Raises: + ValueError: + If no validator is satisfied. Raised with a human-readable error + message listing all the wrapped validators and the value that + failed all of them. + + .. versionadded:: 24.1.0 + """ + vals = [] + for v in validators: + vals.extend(v.validators if isinstance(v, _OrValidator) else [v]) + + return _OrValidator(tuple(vals)) diff --git a/venv/lib/python3.10/site-packages/attr/validators.pyi b/venv/lib/python3.10/site-packages/attr/validators.pyi new file mode 100644 index 0000000000000000000000000000000000000000..a0fdda7c8773f791103938fca0d4b448859aff1f --- /dev/null +++ b/venv/lib/python3.10/site-packages/attr/validators.pyi @@ -0,0 +1,86 @@ +from types import UnionType +from typing import ( + Any, + AnyStr, + Callable, + Container, + ContextManager, + Iterable, + Mapping, + Match, + Pattern, + TypeVar, + overload, +) + +from attrs import _ValidatorType +from attrs import _ValidatorArgType + +_T = TypeVar("_T") +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") +_T3 = TypeVar("_T3") +_I = TypeVar("_I", bound=Iterable) +_K = TypeVar("_K") +_V = TypeVar("_V") +_M = TypeVar("_M", bound=Mapping) + +def set_disabled(run: bool) -> None: ... +def get_disabled() -> bool: ... +def disabled() -> ContextManager[None]: ... + +# To be more precise on instance_of use some overloads. +# If there are more than 3 items in the tuple then we fall back to Any +@overload +def instance_of(type: type[_T]) -> _ValidatorType[_T]: ... +@overload +def instance_of(type: tuple[type[_T]]) -> _ValidatorType[_T]: ... +@overload +def instance_of( + type: tuple[type[_T1], type[_T2]], +) -> _ValidatorType[_T1 | _T2]: ... +@overload +def instance_of( + type: tuple[type[_T1], type[_T2], type[_T3]], +) -> _ValidatorType[_T1 | _T2 | _T3]: ... +@overload +def instance_of(type: tuple[type, ...]) -> _ValidatorType[Any]: ... +@overload +def instance_of(type: UnionType) -> _ValidatorType[Any]: ... +def optional( + validator: ( + _ValidatorType[_T] + | list[_ValidatorType[_T]] + | tuple[_ValidatorType[_T]] + ), +) -> _ValidatorType[_T | None]: ... +def in_(options: Container[_T]) -> _ValidatorType[_T]: ... +def and_(*validators: _ValidatorType[_T]) -> _ValidatorType[_T]: ... +def matches_re( + regex: Pattern[AnyStr] | AnyStr, + flags: int = ..., + func: Callable[[AnyStr, AnyStr, int], Match[AnyStr] | None] | None = ..., +) -> _ValidatorType[AnyStr]: ... +def deep_iterable( + member_validator: _ValidatorArgType[_T], + iterable_validator: _ValidatorType[_I] | None = ..., +) -> _ValidatorType[_I]: ... +def deep_mapping( + key_validator: _ValidatorType[_K], + value_validator: _ValidatorType[_V], + mapping_validator: _ValidatorType[_M] | None = ..., +) -> _ValidatorType[_M]: ... +def is_callable() -> _ValidatorType[_T]: ... +def lt(val: _T) -> _ValidatorType[_T]: ... +def le(val: _T) -> _ValidatorType[_T]: ... +def ge(val: _T) -> _ValidatorType[_T]: ... +def gt(val: _T) -> _ValidatorType[_T]: ... +def max_len(length: int) -> _ValidatorType[_T]: ... +def min_len(length: int) -> _ValidatorType[_T]: ... +def not_( + validator: _ValidatorType[_T], + *, + msg: str | None = None, + exc_types: type[Exception] | Iterable[type[Exception]] = ..., +) -> _ValidatorType[_T]: ... +def or_(*validators: _ValidatorType[_T]) -> _ValidatorType[_T]: ... diff --git a/venv/lib/python3.10/site-packages/glom/__init__.py b/venv/lib/python3.10/site-packages/glom/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1fb4035d2a48993f5551858dd92b4eb56d1d91e9 --- /dev/null +++ b/venv/lib/python3.10/site-packages/glom/__init__.py @@ -0,0 +1,54 @@ +from glom.core import (glom, + Fill, + Auto, + register, + register_op, + Glommer, + Call, + Invoke, + Spec, + Ref, + OMIT, # backwards compat + SKIP, + STOP, + UP, + ROOT, + MODE, + Path, + Vars, + Val, + Literal, # backwards compat 2020-07 + Let, # backwards compat 2020-07 + Coalesce, + Inspect, + Pipe, + GlomError, + BadSpec, + PathAccessError, + PathAssignError, + CoalesceError, + UnregisteredTarget, + T, S, A) + +from glom.reduction import Sum, Fold, Flatten, flatten, FoldError, Merge, merge +from glom.matching import (M, + Or, + And, + Not, + Match, + MatchError, + TypeMatchError, + Regex, + Optional, + Required, + Switch, + Check, + CheckError) +from glom.mutation import Assign, Delete, assign, delete, PathDeleteError + +# there's no -ion word that really fits what "streaming" means. +# generation, production, iteration, all have more relevant meanings +# elsewhere. (maybe procrastination :P) +from glom.streaming import Iter + +from glom._version import __version__ diff --git a/venv/lib/python3.10/site-packages/glom/__main__.py b/venv/lib/python3.10/site-packages/glom/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..9935c57e675352d63f91a0faa07e1c54c2d11005 --- /dev/null +++ b/venv/lib/python3.10/site-packages/glom/__main__.py @@ -0,0 +1,4 @@ +from glom.cli import console_main + +if __name__ == '__main__': + console_main() diff --git a/venv/lib/python3.10/site-packages/glom/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/glom/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb8aa23244c32660342ed31f182d5c77b16d3438 Binary files /dev/null and b/venv/lib/python3.10/site-packages/glom/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/glom/__pycache__/__main__.cpython-310.pyc b/venv/lib/python3.10/site-packages/glom/__pycache__/__main__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c2eeaa4068c8a812a3b2b5c9e6b226e9f8fdcd5 Binary files /dev/null and b/venv/lib/python3.10/site-packages/glom/__pycache__/__main__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/glom/__pycache__/_version.cpython-310.pyc b/venv/lib/python3.10/site-packages/glom/__pycache__/_version.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb32ed38f69eb4773720f6c69e8d6da0f58cb74a Binary files /dev/null and b/venv/lib/python3.10/site-packages/glom/__pycache__/_version.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/glom/__pycache__/chainmap_backport.cpython-310.pyc b/venv/lib/python3.10/site-packages/glom/__pycache__/chainmap_backport.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2cc68da1f2dbf9175e3615c3e6029aa851c25055 Binary files /dev/null and b/venv/lib/python3.10/site-packages/glom/__pycache__/chainmap_backport.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/glom/__pycache__/cli.cpython-310.pyc b/venv/lib/python3.10/site-packages/glom/__pycache__/cli.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc3e54ae8867ec378ba6f786e8385d19fa0b9a53 Binary files /dev/null and b/venv/lib/python3.10/site-packages/glom/__pycache__/cli.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/glom/__pycache__/core.cpython-310.pyc b/venv/lib/python3.10/site-packages/glom/__pycache__/core.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12aa9e696c947d79a01fccc53977d99f15ab0485 Binary files /dev/null and b/venv/lib/python3.10/site-packages/glom/__pycache__/core.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/glom/__pycache__/grouping.cpython-310.pyc b/venv/lib/python3.10/site-packages/glom/__pycache__/grouping.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e491ac9d2b2f5926c5a34b9894c2501fd78fa4a1 Binary files /dev/null and b/venv/lib/python3.10/site-packages/glom/__pycache__/grouping.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/glom/__pycache__/matching.cpython-310.pyc b/venv/lib/python3.10/site-packages/glom/__pycache__/matching.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..660d94146cadfe10db2f222c594fb0301799780c Binary files /dev/null and b/venv/lib/python3.10/site-packages/glom/__pycache__/matching.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/glom/__pycache__/mutation.cpython-310.pyc b/venv/lib/python3.10/site-packages/glom/__pycache__/mutation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c40e7ec1bbcf2fb00284290027570bdb34fc2b3 Binary files /dev/null and b/venv/lib/python3.10/site-packages/glom/__pycache__/mutation.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/glom/__pycache__/reduction.cpython-310.pyc b/venv/lib/python3.10/site-packages/glom/__pycache__/reduction.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb61a8283c47bfa7ac6f5be9a933039b1e8605da Binary files /dev/null and b/venv/lib/python3.10/site-packages/glom/__pycache__/reduction.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/glom/__pycache__/reprlib_backport.cpython-310.pyc b/venv/lib/python3.10/site-packages/glom/__pycache__/reprlib_backport.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a23fd0e740a6131b7da28aa434db50aede2283b Binary files /dev/null and b/venv/lib/python3.10/site-packages/glom/__pycache__/reprlib_backport.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/glom/__pycache__/streaming.cpython-310.pyc b/venv/lib/python3.10/site-packages/glom/__pycache__/streaming.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..89f4f18be27cc94edff34d7dd98ac35fdee11dde Binary files /dev/null and b/venv/lib/python3.10/site-packages/glom/__pycache__/streaming.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/glom/__pycache__/tutorial.cpython-310.pyc b/venv/lib/python3.10/site-packages/glom/__pycache__/tutorial.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..44b2e567a0ab0cdd7864a466cce5ff7a9ac8f01f Binary files /dev/null and b/venv/lib/python3.10/site-packages/glom/__pycache__/tutorial.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/glom/_version.py b/venv/lib/python3.10/site-packages/glom/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..277a2ff681cda33b02a72601d6b4ecc4df8176d1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/glom/_version.py @@ -0,0 +1,2 @@ +version_info = (24, 11, 0) +__version__ = '.'.join([str(part) for part in version_info if part or part == 0]) diff --git a/venv/lib/python3.10/site-packages/glom/chainmap_backport.py b/venv/lib/python3.10/site-packages/glom/chainmap_backport.py new file mode 100644 index 0000000000000000000000000000000000000000..6aac6ff8b7c2b983cb87eaaf7990df5dc24872c4 --- /dev/null +++ b/venv/lib/python3.10/site-packages/glom/chainmap_backport.py @@ -0,0 +1,147 @@ +"""The following code is copied and pasted from Python 3's +collections.py, viewable here: + +https://github.com/python/cpython/blob/c6cd164cffedb306a4c6644d9d03072f24da246d/Lib/collections/__init__.py#L880-L987 + +No modifications are necessary for glom usage. It is included for +Python 2 compatibility only. +""" +try: + from collections.abc import MutableMapping +except ImportError: + from collections import MutableMapping + +try: + from thread import get_ident +except ImportError: + try: + from threading import _get_ident as get_ident + except ImportError: + from threading import get_ident + + +def _recursive_repr(fillvalue='...'): + 'Decorator to make a repr function return fillvalue for a recursive call' + + def decorating_function(user_function): + repr_running = set() + + def wrapper(self): + key = id(self), get_ident() + if key in repr_running: + return fillvalue + repr_running.add(key) + try: + result = user_function(self) + finally: + repr_running.discard(key) + return result + + # Can't use functools.wraps() here because of bootstrap issues + wrapper.__module__ = getattr(user_function, '__module__') + wrapper.__doc__ = getattr(user_function, '__doc__') + wrapper.__name__ = getattr(user_function, '__name__') + wrapper.__annotations__ = getattr(user_function, '__annotations__', {}) + return wrapper + + return decorating_function + + +class ChainMap(MutableMapping): + ''' A ChainMap groups multiple dicts (or other mappings) together + to create a single, updateable view. + The underlying mappings are stored in a list. That list is public and can + be accessed or updated using the *maps* attribute. There is no other + state. + Lookups search the underlying mappings successively until a key is found. + In contrast, writes, updates, and deletions only operate on the first + mapping. + ''' + + def __init__(self, *maps): + '''Initialize a ChainMap by setting *maps* to the given mappings. + If no mappings are provided, a single empty dictionary is used. + ''' + self.maps = list(maps) or [{}] # always at least one map + + def __missing__(self, key): + raise KeyError(key) + + def __getitem__(self, key): + for mapping in self.maps: + try: + return mapping[key] # can't use 'key in mapping' with defaultdict + except KeyError: + pass + return self.__missing__(key) # support subclasses that define __missing__ + + def get(self, key, default=None): + return self[key] if key in self else default + + def __len__(self): + return len(set().union(*self.maps)) # reuses stored hash values if possible + + def __iter__(self): + return iter(set().union(*self.maps)) + + def __contains__(self, key): + return any(key in m for m in self.maps) + + def __bool__(self): + return any(self.maps) + + @_recursive_repr() + def __repr__(self): + return '{0.__class__.__name__}({1})'.format( + self, ', '.join(map(repr, self.maps))) + + @classmethod + def fromkeys(cls, iterable, *args): + 'Create a ChainMap with a single dict created from the iterable.' + return cls(dict.fromkeys(iterable, *args)) + + def copy(self): + 'New ChainMap or subclass with a new copy of maps[0] and refs to maps[1:]' + return self.__class__(self.maps[0].copy(), *self.maps[1:]) + + __copy__ = copy + + def new_child(self, m=None): # like Django's Context.push() + '''New ChainMap with a new map followed by all previous maps. + If no map is provided, an empty dict is used. + ''' + if m is None: + m = {} + return self.__class__(m, *self.maps) + + @property + def parents(self): # like Django's Context.pop() + 'New ChainMap from maps[1:].' + return self.__class__(*self.maps[1:]) + + def __setitem__(self, key, value): + self.maps[0][key] = value + + def __delitem__(self, key): + try: + del self.maps[0][key] + except KeyError: + raise KeyError('Key not found in the first mapping: {!r}'.format(key)) + + def popitem(self): + 'Remove and return an item pair from maps[0]. Raise KeyError is maps[0] is empty.' + try: + return self.maps[0].popitem() + except KeyError: + raise KeyError('No keys found in the first mapping.') + + def pop(self, key, *args): + 'Remove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0].' + try: + return self.maps[0].pop(key, *args) + except KeyError: + raise KeyError('Key not found in the first mapping: {!r}'.format(key)) + + def clear(self): + 'Clear maps[0], leaving maps[1:] intact.' + self.maps[0].clear() diff --git a/venv/lib/python3.10/site-packages/glom/cli.py b/venv/lib/python3.10/site-packages/glom/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..298706420dec85a83ec8073ceb299376199296b8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/glom/cli.py @@ -0,0 +1,241 @@ +"""like jq, but with the full power of python in the spec. + +Usage: python -m glom [FLAGS] [spec [target]] + +Command-line interface to the glom library, providing nested data +access and data restructuring with the power of Python. + + +Flags: + + --help / -h show this help message and exit + --target-file TARGET_FILE path to target data source (optional) + --target-format TARGET_FORMAT + format of the source data (json, python, toml, + or yaml) (defaults to 'json') + --spec-file SPEC_FILE path to glom spec definition (optional) + --spec-format SPEC_FORMAT format of the glom spec definition (json, python, + python-full) (defaults to 'python') + --indent INDENT number of spaces to indent the result, 0 to disable + pretty-printing (defaults to 2) + --debug interactively debug any errors that come up + --inspect interactively explore the data + +try out: +` +curl -s https://api.github.com/repos/mahmoud/glom/events | python -m glom '[{"type": "type", "date": "created_at", "user": "actor.login"}]' + +""" + + + +import os +import ast +import sys +import json + +from face import (Command, + Flag, + face_middleware, + PosArgSpec, + PosArgDisplay, + CommandLineError, + UsageError) +from face.utils import isatty +from boltons.iterutils import is_scalar + +import glom +from glom import Path, GlomError, Inspect + +# TODO: --default? + +def glom_cli(target, spec, indent, debug, inspect, scalar): + """Command-line interface to the glom library, providing nested data + access and data restructuring with the power of Python. + """ + if debug or inspect: + stdin_open = not sys.stdin.closed + spec = Inspect(spec, + echo=inspect, + recursive=inspect, + breakpoint=inspect and stdin_open, + post_mortem=debug and stdin_open) + + try: + result = glom.glom(target, spec) + except GlomError as ge: + print(f'{ge.__class__.__name__}: {ge}') + return 1 + + if not indent: + indent = None + + if scalar and is_scalar(result): + print(result, end='') + else: + print(json.dumps(result, indent=indent, sort_keys=True)) + return + + +def get_command(): + posargs = PosArgSpec(str, max_count=2, display={'label': '[spec [target]]'}) + cmd = Command(glom_cli, posargs=posargs, middlewares=[mw_get_target]) + cmd.add('--target-file', str, missing=None, doc='path to target data source') + cmd.add('--target-format', str, missing='json', + doc='format of the source data (json or python)') + cmd.add('--spec-file', str, missing=None, doc='path to glom spec definition') + cmd.add('--spec-format', str, missing='python', + doc='format of the glom spec definition (json, python, python-full)') + + cmd.add('--indent', int, missing=2, + doc='number of spaces to indent the result, 0 to disable pretty-printing') + + cmd.add('--scalar', parse_as=True, + doc="if the result is a single value (not a collection), output it" + " without quotes or whitespace, for easier usage in scripts") + cmd.add('--debug', parse_as=True, doc='interactively debug any errors that come up') + cmd.add('--inspect', parse_as=True, doc='interactively explore the data') + return cmd + + +def main(argv): + cmd = get_command() + return cmd.run(argv) or 0 + + +def console_main(): + _enable_debug = os.getenv('GLOM_CLI_DEBUG') + if _enable_debug: + print(sys.argv) + try: + sys.exit(main(sys.argv) or 0) + except Exception: + if _enable_debug: + import pdb;pdb.post_mortem() + raise + + +def mw_handle_target(target_text, target_format): + """ Handles reading in a file specified in cli command. + + Args: + target_text (str): The target data to load, as text + target_format (str): Valid formats include `json`, `toml`, and `yml`/`yaml` + Returns: + The content of the file that you specified + Raises: + CommandLineError: Issue with file format or appropriate file reading package not installed. + """ + if not target_text: + return {} + target = {} + if target_format == 'json': + load_func = json.loads + elif target_format in ('yaml', 'yml'): + try: + import yaml + load_func = yaml.safe_load + except ImportError: # pragma: no cover + raise UsageError('No YAML package found. To process yaml files, run: pip install PyYAML') # pragma: no cover + elif target_format == 'toml': + missing = UsageError('No TOML package found. To process toml files, upgrade to Python 3.11 or run: pip install tomli') + try: + import tomllib + load_func = tomllib.loads + except ImportError: + try: + import tomli + load_func = tomli.loads + except ImportError: # pragma: no cover + raise missing # pragma: no cover + elif target_format == 'python': + load_func = ast.literal_eval + else: + raise UsageError('expected target-format to be one of python, json, toml, or yaml') + + + try: + target = load_func(target_text) + except Exception as e: + raise UsageError('could not load target data, got: %s: %s' + % (e.__class__.__name__, e)) + + + return target + + +@face_middleware(provides=['spec', 'target']) +def mw_get_target(next_, posargs_, target_file, target_format, spec_file, spec_format): + spec_text, target_text = None, None + if len(posargs_) == 2: + spec_text, target_text = posargs_ + elif len(posargs_) == 1: + spec_text, target_text = posargs_[0], None + + if spec_text and spec_file: + raise UsageError('expected spec file or spec argument, not both') + elif spec_file: + try: + with open(spec_file) as f: + spec_text = f.read() + except OSError as ose: + raise UsageError(f'could not read spec file {spec_file!r}, got: {ose}') + + if not spec_text: + spec = Path() + elif spec_format == 'python': + if spec_text[0] not in ('"', "'", "[", "{", "("): + # intention: handle trivial path access, assume string + spec_text = repr(spec_text) + spec = ast.literal_eval(spec_text) + elif spec_format == 'json': + spec = json.loads(spec_text) + elif spec_format == 'python-full': + spec = _eval_python_full_spec(spec_text) + else: + raise UsageError('expected spec-format to be one of json, python, or python-full') + + if target_text and target_file: + raise UsageError('expected target file or target argument, not both') + elif target_text == '-' or target_file == '-': + target_text = sys.stdin.read() + elif target_file: + try: + target_text = open(target_file).read() + except OSError as ose: + raise UsageError(f'could not read target file {target_file!r}, got: {ose}') + elif not target_text and not isatty(sys.stdin): + target_text = sys.stdin.read() + + target = mw_handle_target(target_text, target_format) + + return next_(spec=spec, target=target) + + +def _from_glom_import_star(): + ret = dict(glom.__dict__) + for k in ('__builtins__', '__name__', '__doc__', '__package__'): + ret.pop(k, None) + for k, v in list(ret.items()): + if type(v) == type(glom): + ret.pop(k) + return ret + + +def _eval_python_full_spec(py_text): + name = '__cli_glom_spec__' + code_str = f'{name} = {py_text}' + env = _from_glom_import_star() + spec = _compile_code(code_str, name=name, env=env) + return spec + + +def _compile_code(code_str, name, env=None, verbose=False): + code = compile(code_str, '', 'single') + if verbose: + print(code_str) + if env is None: + env = {} + exec(code, env) + + return env[name] diff --git a/venv/lib/python3.10/site-packages/glom/core.py b/venv/lib/python3.10/site-packages/glom/core.py new file mode 100644 index 0000000000000000000000000000000000000000..cee71a307975ac747367aa346208aac00f07c223 --- /dev/null +++ b/venv/lib/python3.10/site-packages/glom/core.py @@ -0,0 +1,2592 @@ +"""*glom gets results.* + +The ``glom`` package has one central entrypoint, +:func:`glom.glom`. Everything else in the package revolves around that +one function. Sometimes, big things come in small packages. + +A couple of conventional terms you'll see repeated many times below: + +* **target** - glom is built to work on any data, so we simply + refer to the object being accessed as the *"target"* +* **spec** - *(aka "glomspec", short for specification)* The + accompanying template used to specify the structure of the return + value. + +Now that you know the terms, let's take a look around glom's powerful +semantics. + +""" + + +import os +import sys +import pdb +import copy +import warnings +import weakref +import operator +from abc import ABCMeta +from pprint import pprint +import string +from collections import OrderedDict +import traceback + +from face.helpers import get_wrap_width +from boltons.typeutils import make_sentinel +from boltons.iterutils import is_iterable +#from boltons.funcutils import format_invocation + +basestring = str +_AbstractIterableBase = ABCMeta('_AbstractIterableBase', (object,), {}) +from collections import ChainMap +from reprlib import Repr, recursive_repr + +GLOM_DEBUG = os.getenv('GLOM_DEBUG', '').strip().lower() +GLOM_DEBUG = False if (GLOM_DEBUG in ('', '0', 'false')) else True + +TRACE_WIDTH = max(get_wrap_width(max_width=110), 50) # min width + +PATH_STAR = True +# should * and ** be interpreted as parallel traversal in Path.from_text()? +# Changed to True in 23.1, this option to disable will go away soon + +_type_type = type + +_MISSING = make_sentinel('_MISSING') +SKIP = make_sentinel('SKIP') +SKIP.__doc__ = """ +The ``SKIP`` singleton can be returned from a function or included +via a :class:`~glom.Val` to cancel assignment into the output +object. + +>>> target = {'a': 'b'} +>>> spec = {'a': lambda t: t['a'] if t['a'] == 'a' else SKIP} +>>> glom(target, spec) +{} +>>> target = {'a': 'a'} +>>> glom(target, spec) +{'a': 'a'} + +Mostly used to drop keys from dicts (as above) or filter objects from +lists. + +.. note:: + + SKIP was known as OMIT in versions 18.3.1 and prior. Versions 19+ + will remove the OMIT alias entirely. +""" +OMIT = SKIP # backwards compat, remove in 19+ + +STOP = make_sentinel('STOP') +STOP.__doc__ = """ +The ``STOP`` singleton can be used to halt iteration of a list or +execution of a tuple of subspecs. + +>>> target = range(10) +>>> spec = [lambda x: x if x < 5 else STOP] +>>> glom(target, spec) +[0, 1, 2, 3, 4] +""" + +LAST_CHILD_SCOPE = make_sentinel('LAST_CHILD_SCOPE') +LAST_CHILD_SCOPE.__doc__ = """ +Marker that can be used by parents to keep track of the last child +scope executed. Useful for "lifting" results out of child scopes +for scopes that want to chain the scopes of their children together +similar to tuple. +""" + +NO_PYFRAME = make_sentinel('NO_PYFRAME') +NO_PYFRAME.__doc__ = """ +Used internally to mark scopes which are no longer wrapped +in a recursive glom() call, so that they can be cleaned up correctly +in case of exceptions +""" + +MODE = make_sentinel('MODE') + +MIN_MODE = make_sentinel('MIN_MODE') + +CHILD_ERRORS = make_sentinel('CHILD_ERRORS') +CHILD_ERRORS.__doc__ = """ +``CHILD_ERRORS`` is used by glom internals to keep track of +failed child branches of the current scope. +""" + +CUR_ERROR = make_sentinel('CUR_ERROR') +CUR_ERROR.__doc__ = """ +``CUR_ERROR`` is used by glom internals to keep track of +thrown exceptions. +""" + +_PKG_DIR_PATH = os.path.dirname(os.path.abspath(__file__)) + +class GlomError(Exception): + """The base exception for all the errors that might be raised from + :func:`glom` processing logic. + + By default, exceptions raised from within functions passed to glom + (e.g., ``len``, ``sum``, any ``lambda``) will not be wrapped in a + GlomError. + """ + @classmethod + def wrap(cls, exc): + # TODO: need to test this against a wide array of exception types + # this approach to wrapping errors works for exceptions + # defined in pure-python as well as C + exc_type = type(exc) + bases = (GlomError,) if issubclass(GlomError, exc_type) else (exc_type, GlomError) + exc_wrapper_type = type(f"GlomError.wrap({exc_type.__name__})", bases, {}) + try: + wrapper = exc_wrapper_type(*exc.args) + wrapper.__wrapped = exc + return wrapper + except Exception: # maybe exception can't be re-created + return exc + + def _set_wrapped(self, exc): + self.__wrapped = exc + + def _finalize(self, scope): + # careful when changing how this functionality works; pytest seems to mess with + # the traceback module or sys.exc_info(). we saw different stacks when originally + # developing this in June 2020. + etype, evalue, _ = sys.exc_info() + tb_lines = traceback.format_exc().strip().splitlines() + limit = 0 + for line in reversed(tb_lines): + if _PKG_DIR_PATH in line: + limit -= 1 + break + limit += 1 + self._tb_lines = tb_lines[-limit:] + # if the first line is trying to put a caret at a byte-code location on a line that + # isn't being displayed, skip it + if set(self._tb_lines[0]) <= {' ', '^', '~'}: + self._tb_lines = self._tb_lines[1:] + self._scope = scope + + def __str__(self): + if getattr(self, '_finalized_str', None): + return self._finalized_str + elif getattr(self, '_scope', None) is not None: + self._target_spec_trace = format_target_spec_trace(self._scope, self.__wrapped) + parts = ["error raised while processing, details below.", + " Target-spec trace (most recent last):", + self._target_spec_trace] + parts.extend(self._tb_lines) + self._finalized_str = "\n".join(parts) + return self._finalized_str + + # else, not finalized + try: + exc_get_message = self.get_message + except AttributeError: + exc_get_message = super().__str__ + return exc_get_message() + + +def _unpack_stack(scope, only_errors=True): + """ + convert scope to [[scope, spec, target, error, [children]]] + + this is a convenience method for printing stacks + + only_errors=True means ignore branches which may still be hanging around + which were not involved in the stack trace of the error + + only_errors=False could be useful for debugger / introspection (similar + to traceback.print_stack()) + """ + stack = [] + scope = scope.maps[0] + while LAST_CHILD_SCOPE in scope: + child = scope[LAST_CHILD_SCOPE] + branches = scope[CHILD_ERRORS] + if branches == [child]: + branches = [] # if there's only one branch, count it as linear + stack.append([scope, scope[Spec], scope[T], scope.get(CUR_ERROR), branches]) + + # NB: this id() business is necessary to avoid a + # nondeterministic bug in abc's __eq__ see #189 for details + if id(child) in [id(b) for b in branches]: + break # if child already covered by branches, stop the linear descent + + scope = child.maps[0] + else: # if break executed above, cur scope was already added + stack.append([scope, scope[Spec], scope[T], scope.get(CUR_ERROR), []]) + # push errors "down" to where they were first raised / first observed + for i in range(len(stack) - 1): + cur, nxt = stack[i], stack[i + 1] + if cur[3] == nxt[3]: + cur[3] = None + if only_errors: # trim the stack to the last error + # leave at least 1 to not break formatting func below + # TODO: make format_target_spec_trace() tolerate an "empty" stack cleanly + while len(stack) > 1 and stack[-1][3] is None: + stack.pop() + return stack + + +def _format_trace_value(value, maxlen): + s = bbrepr(value).replace("\\'", "'") + if len(s) > maxlen: + try: + suffix = '... (len=%s)' % len(value) + except Exception: + suffix = '...' + s = s[:maxlen - len(suffix)] + suffix + return s + + +def format_target_spec_trace(scope, root_error, width=TRACE_WIDTH, depth=0, prev_target=_MISSING, last_branch=True): + """ + unpack a scope into a multi-line but short summary + """ + segments = [] + indent = " " + "|" * depth + tick = "| " if depth else "- " + def mk_fmt(label, t=None): + pre = indent + (t or tick) + label + ": " + fmt_width = width - len(pre) + return lambda v: pre + _format_trace_value(v, fmt_width) + fmt_t = mk_fmt("Target") + fmt_s = mk_fmt("Spec") + fmt_b = mk_fmt("Spec", "+ ") + recurse = lambda s, last=False: format_target_spec_trace(s, root_error, width, depth + 1, prev_target, last) + tb_exc_line = lambda e: "".join(traceback.format_exception_only(type(e), e))[:-1] + fmt_e = lambda e: indent + tick + tb_exc_line(e) + for scope, spec, target, error, branches in _unpack_stack(scope): + if target is not prev_target: + segments.append(fmt_t(target)) + prev_target = target + if branches: + segments.append(fmt_b(spec)) + segments.extend([recurse(s) for s in branches[:-1]]) + segments.append(recurse(branches[-1], last_branch)) + else: + segments.append(fmt_s(spec)) + if error is not None and error is not root_error: + last_line_error = True + segments.append(fmt_e(error)) + else: + last_line_error = False + if depth: # \ on first line, X on last line + remark = lambda s, m: s[:depth + 1] + m + s[depth + 2:] + segments[0] = remark(segments[0], "\\") + if not last_branch or last_line_error: + segments[-1] = remark(segments[-1], "X") + return "\n".join(segments) + + +# TODO: not used (yet) +def format_oneline_trace(scope): + """ + unpack a scope into a single line summary + (shortest summary possible) + """ + # the goal here is to do a kind of delta-compression -- + # if the target is the same, don't repeat it + segments = [] + prev_target = _MISSING + for scope, spec, target, error, branches in _unpack_stack(scope, only_errors=False): + segments.append('/') + if type(spec) in (TType, Path): + segments.append(bbrepr(spec)) + else: + segments.append(type(spec).__name__) + if target != prev_target: + segments.append('!') + segments.append(type(target).__name__) + if Path in scope: + segments.append('<') + segments.append('->'.join([str(p) for p in scope[Path]])) + segments.append('>') + prev_target = target + + return "".join(segments) + + +class PathAccessError(GlomError, AttributeError, KeyError, IndexError): + """This :exc:`GlomError` subtype represents a failure to access an + attribute as dictated by the spec. The most commonly-seen error + when using glom, it maintains a copy of the original exception and + produces a readable error message for easy debugging. + + If you see this error, you may want to: + + * Check the target data is accurate using :class:`~glom.Inspect` + * Catch the exception and return a semantically meaningful error message + * Use :class:`glom.Coalesce` to specify a default + * Use the top-level ``default`` kwarg on :func:`~glom.glom()` + + In any case, be glad you got this error and not the one it was + wrapping! + + Args: + exc (Exception): The error that arose when we tried to access + *path*. Typically an instance of KeyError, AttributeError, + IndexError, or TypeError, and sometimes others. + path (Path): The full Path glom was in the middle of accessing + when the error occurred. + part_idx (int): The index of the part of the *path* that caused + the error. + + >>> target = {'a': {'b': None}} + >>> glom(target, 'a.b.c') + Traceback (most recent call last): + ... + PathAccessError: could not access 'c', part 2 of Path('a', 'b', 'c'), got error: ... + + """ + def __init__(self, exc, path, part_idx): + self.exc = exc + self.path = path + self.part_idx = part_idx + + def get_message(self): + path_part = Path(self.path).values()[self.part_idx] + return ('could not access %r, part %r of %r, got error: %r' + % (path_part, self.part_idx, self.path, self.exc)) + + def __repr__(self): + cn = self.__class__.__name__ + return f'{cn}({self.exc!r}, {self.path!r}, {self.part_idx!r})' + + +class PathAssignError(GlomError): + """This :exc:`GlomError` subtype is raised when an assignment fails, + stemming from an :func:`~glom.assign` call or other + :class:`~glom.Assign` usage. + + One example would be assigning to an out-of-range position in a list:: + + >>> assign(["short", "list"], Path(5), 'too far') # doctest: +SKIP + Traceback (most recent call last): + ... + PathAssignError: could not assign 5 on object at Path(), got error: IndexError(... + + Other assignment failures could be due to assigning to an + ``@property`` or exception being raised inside a ``__setattr__()``. + + """ + def __init__(self, exc, path, dest_name): + self.exc = exc + self.path = path + self.dest_name = dest_name + + def get_message(self): + return ('could not assign %r on object at %r, got error: %r' + % (self.dest_name, self.path, self.exc)) + + def __repr__(self): + cn = self.__class__.__name__ + return f'{cn}({self.exc!r}, {self.path!r}, {self.dest_name!r})' + + +class CoalesceError(GlomError): + """This :exc:`GlomError` subtype is raised from within a + :class:`Coalesce` spec's processing, when none of the subspecs + match and no default is provided. + + The exception object itself keeps track of several values which + may be useful for processing: + + Args: + coal_obj (Coalesce): The original failing spec, see + :class:`Coalesce`'s docs for details. + skipped (list): A list of ignored values and exceptions, in the + order that their respective subspecs appear in the original + *coal_obj*. + path: Like many GlomErrors, this exception knows the path at + which it occurred. + + >>> target = {} + >>> glom(target, Coalesce('a', 'b')) + Traceback (most recent call last): + ... + CoalesceError: no valid values found. Tried ('a', 'b') and got (PathAccessError, PathAccessError) ... + + .. note:: + + Coalesce is a *branching* specifier type, so as of v20.7.0, its + exception messages feature an error tree. See + :ref:`branched-exceptions` for details on how to interpret these + exceptions. + + """ + def __init__(self, coal_obj, skipped, path): + self.coal_obj = coal_obj + self.skipped = skipped + self.path = path + + def __repr__(self): + cn = self.__class__.__name__ + return f'{cn}({self.coal_obj!r}, {self.skipped!r}, {self.path!r})' + + def get_message(self): + missed_specs = tuple(self.coal_obj.subspecs) + skipped_vals = [v.__class__.__name__ + if isinstance(v, self.coal_obj.skip_exc) + else '' % v.__class__.__name__ + for v in self.skipped] + msg = ('no valid values found. Tried %r and got (%s)' + % (missed_specs, ', '.join(skipped_vals))) + if self.coal_obj.skip is not _MISSING: + msg += f', skip set to {self.coal_obj.skip!r}' + if self.coal_obj.skip_exc is not GlomError: + msg += f', skip_exc set to {self.coal_obj.skip_exc!r}' + if self.path is not None: + msg += f' (at path {self.path!r})' + return msg + + +class BadSpec(GlomError, TypeError): + """Raised when a spec structure is malformed, e.g., when a specifier + type is invalid for the current mode.""" + + +class UnregisteredTarget(GlomError): + """This :class:`GlomError` subtype is raised when a spec calls for an + unsupported action on a target type. For instance, trying to + iterate on an non-iterable target: + + >>> glom(object(), ['a.b.c']) + Traceback (most recent call last): + ... + UnregisteredTarget: target type 'object' not registered for 'iterate', expected one of registered types: (...) + + It should be noted that this is a pretty uncommon occurrence in + production glom usage. See the :ref:`setup-and-registration` + section for details on how to avoid this error. + + An UnregisteredTarget takes and tracks a few values: + + Args: + op (str): The name of the operation being performed ('get' or 'iterate') + target_type (type): The type of the target being processed. + type_map (dict): A mapping of target types that do support this operation + path: The path at which the error occurred. + + """ + def __init__(self, op, target_type, type_map, path): + self.op = op + self.target_type = target_type + self.type_map = type_map + self.path = path + super().__init__(op, target_type, type_map, path) + + def __repr__(self): + cn = self.__class__.__name__ + # is because Python 3 inexplicably changed the type + # repr from to + return ('%s(%r, , %r, %r)' + % (cn, self.op, self.target_type.__name__, self.type_map, self.path)) + + def get_message(self): + if not self.type_map: + return ("glom() called without registering any types for operation '%s'. see" + " glom.register() or Glommer's constructor for details." % (self.op,)) + reg_types = sorted([t.__name__ for t, h in self.type_map.items() if h]) + reg_types_str = '()' if not reg_types else ('(%s)' % ', '.join(reg_types)) + msg = ("target type %r not registered for '%s', expected one of" + " registered types: %s" % (self.target_type.__name__, self.op, reg_types_str)) + if self.path: + msg += f' (at {self.path!r})' + return msg + + +if getattr(__builtins__, '__dict__', None) is not None: + # pypy's __builtins__ is a module, as is CPython's REPL, but at + # normal execution time it's a dict? + __builtins__ = __builtins__.__dict__ + + +_BUILTIN_ID_NAME_MAP = {id(v): k + for k, v in __builtins__.items()} + + +class _BBRepr(Repr): + """A better repr for builtins, when the built-in repr isn't + roundtrippable. + """ + def __init__(self): + super().__init__() + # turn up all the length limits very high + for name in self.__dict__: + if not isinstance(getattr(self, name), int): + continue + setattr(self, name, 1024) + + def repr1(self, x, level): + ret = Repr.repr1(self, x, level) + if not ret.startswith('<'): + return ret + return _BUILTIN_ID_NAME_MAP.get(id(x), ret) + + +bbrepr = recursive_repr()(_BBRepr().repr) + + +class _BBReprFormatter(string.Formatter): + """ + allow format strings to be evaluated where {!r} will use bbrepr + instead of repr + """ + def convert_field(self, value, conversion): + if conversion == 'r': + return bbrepr(value).replace("\\'", "'") + return super().convert_field(value, conversion) + + +bbformat = _BBReprFormatter().format + + +# TODO: push this back up to boltons with repr kwarg +def format_invocation(name='', args=(), kwargs=None, **kw): + """Given a name, positional arguments, and keyword arguments, format + a basic Python-style function call. + + >>> print(format_invocation('func', args=(1, 2), kwargs={'c': 3})) + func(1, 2, c=3) + >>> print(format_invocation('a_func', args=(1,))) + a_func(1) + >>> print(format_invocation('kw_func', kwargs=[('a', 1), ('b', 2)])) + kw_func(a=1, b=2) + + """ + _repr = kw.pop('repr', bbrepr) + if kw: + raise TypeError('unexpected keyword args: %r' % ', '.join(kw.keys())) + kwargs = kwargs or {} + a_text = ', '.join([_repr(a) for a in args]) + if isinstance(kwargs, dict): + kwarg_items = [(k, kwargs[k]) for k in sorted(kwargs)] + else: + kwarg_items = kwargs + kw_text = ', '.join([f'{k}={_repr(v)}' for k, v in kwarg_items]) + + all_args_text = a_text + if all_args_text and kw_text: + all_args_text += ', ' + all_args_text += kw_text + + return f'{name}({all_args_text})' + + +class Path: + """Path objects specify explicit paths when the default + ``'a.b.c'``-style general access syntax won't work or isn't + desirable. Use this to wrap ints, datetimes, and other valid + keys, as well as strings with dots that shouldn't be expanded. + + >>> target = {'a': {'b': 'c', 'd.e': 'f', 2: 3}} + >>> glom(target, Path('a', 2)) + 3 + >>> glom(target, Path('a', 'd.e')) + 'f' + + Paths can be used to join together other Path objects, as + well as :data:`~glom.T` objects: + + >>> Path(T['a'], T['b']) + T['a']['b'] + >>> Path(Path('a', 'b'), Path('c', 'd')) + Path('a', 'b', 'c', 'd') + + Paths also support indexing and slicing, with each access + returning a new Path object: + + >>> path = Path('a', 'b', 1, 2) + >>> path[0] + Path('a') + >>> path[-2:] + Path(1, 2) + + To build a Path object from a string, use :meth:`Path.from_text()`. + This is the default behavior when the top-level :func:`~glom.glom` + function gets a string spec. + """ + def __init__(self, *path_parts): + if not path_parts: + self.path_t = T + return + if isinstance(path_parts[0], TType): + path_t = path_parts[0] + offset = 1 + else: + path_t = T + offset = 0 + for part in path_parts[offset:]: + if isinstance(part, Path): + part = part.path_t + if isinstance(part, TType): + sub_parts = part.__ops__ + if sub_parts[0] is not T: + raise ValueError('path segment must be path from T, not %r' + % sub_parts[0]) + i = 1 + while i < len(sub_parts): + path_t = _t_child(path_t, sub_parts[i], sub_parts[i + 1]) + i += 2 + else: + path_t = _t_child(path_t, 'P', part) + self.path_t = path_t + + _CACHE = {True: {}, False: {}} + _MAX_CACHE = 10000 + _STAR_WARNED = False + + @classmethod + def from_text(cls, text): + """Make a Path from .-delimited text: + + >>> Path.from_text('a.b.c') + Path('a', 'b', 'c') + + This is the default behavior when :func:`~glom.glom` gets a string spec. + """ + def create(): + segs = text.split('.') + if PATH_STAR: + segs = [ + _T_STAR if seg == '*' else + _T_STARSTAR if seg == '**' else seg + for seg in segs] + elif not cls._STAR_WARNED: + if '*' in segs or '**' in segs: + warnings.warn( + "'*' and '**' have changed behavior in glom version 23.1." + " Recommend switch to T['*'] or T['**'].") + cls._STAR_WARNED = True + return cls(*segs) + + cache = cls._CACHE[PATH_STAR] # remove this when PATH_STAR is default + if text not in cache: + if len(cache) > cls._MAX_CACHE: + return create() + cache[text] = create() + return cache[text] + + def glomit(self, target, scope): + # The entrypoint for the Path extension + return _t_eval(target, self.path_t, scope) + + def __len__(self): + return (len(self.path_t.__ops__) - 1) // 2 + + def __eq__(self, other): + if type(other) is Path: + return self.path_t.__ops__ == other.path_t.__ops__ + elif type(other) is TType: + return self.path_t.__ops__ == other.__ops__ + return False + + def __ne__(self, other): + return not self == other + + def values(self): + """ + Returns a tuple of values referenced in this path. + + >>> Path(T.a.b, 'c', T['d']).values() + ('a', 'b', 'c', 'd') + """ + cur_t_path = self.path_t.__ops__ + return cur_t_path[2::2] + + def items(self): + """ + Returns a tuple of (operation, value) pairs. + + >>> Path(T.a.b, 'c', T['d']).items() + (('.', 'a'), ('.', 'b'), ('P', 'c'), ('[', 'd')) + + """ + cur_t_path = self.path_t.__ops__ + return tuple(zip(cur_t_path[1::2], cur_t_path[2::2])) + + def startswith(self, other): + if isinstance(other, basestring): + other = Path(other) + if isinstance(other, Path): + other = other.path_t + if not isinstance(other, TType): + raise TypeError('can only check if Path starts with string, Path or T') + o_path = other.__ops__ + return self.path_t.__ops__[:len(o_path)] == o_path + + def from_t(self): + '''return the same path but starting from T''' + t_path = self.path_t.__ops__ + if t_path[0] is S: + new_t = TType() + new_t.__ops__ = (T,) + t_path[1:] + return Path(new_t) + return self + + def __getitem__(self, i): + cur_t_path = self.path_t.__ops__ + try: + step = i.step + start = i.start if i.start is not None else 0 + stop = i.stop + + start = (start * 2) + 1 if start >= 0 else (start * 2) + len(cur_t_path) + if stop is not None: + stop = (stop * 2) + 1 if stop >= 0 else (stop * 2) + len(cur_t_path) + except AttributeError: + step = 1 + start = (i * 2) + 1 if i >= 0 else (i * 2) + len(cur_t_path) + if start < 0 or start > len(cur_t_path): + raise IndexError('Path index out of range') + stop = ((i + 1) * 2) + 1 if i >= 0 else ((i + 1) * 2) + len(cur_t_path) + + new_t = TType() + new_path = cur_t_path[start:stop] + if step is not None and step != 1: + new_path = tuple(zip(new_path[::2], new_path[1::2]))[::step] + new_path = sum(new_path, ()) + new_t.__ops__ = (cur_t_path[0],) + new_path + return Path(new_t) + + def __repr__(self): + return _format_path(self.path_t.__ops__[1:]) + + +def _format_path(t_path): + path_parts, cur_t_path = [], [] + i = 0 + while i < len(t_path): + op, arg = t_path[i], t_path[i + 1] + i += 2 + if op == 'P': + if cur_t_path: + path_parts.append(cur_t_path) + cur_t_path = [] + path_parts.append(arg) + else: + cur_t_path.append(op) + cur_t_path.append(arg) + if path_parts and cur_t_path: + path_parts.append(cur_t_path) + + if path_parts or not cur_t_path: + return 'Path(%s)' % ', '.join([_format_t(part) + if type(part) is list else repr(part) + for part in path_parts]) + return _format_t(cur_t_path) + + +class Spec: + """Spec objects serve three purposes, here they are, roughly ordered + by utility: + + 1. As a form of compiled or "curried" glom call, similar to + Python's built-in :func:`re.compile`. + 2. A marker as an object as representing a spec rather than a + literal value in certain cases where that might be ambiguous. + 3. A way to update the scope within another Spec. + + In the second usage, Spec objects are the complement to + :class:`~glom.Val`, wrapping a value and marking that it + should be interpreted as a glom spec, rather than a literal value. + This is useful in places where it would be interpreted as a value + by default. (Such as T[key], Call(func) where key and func are + assumed to be literal values and not specs.) + + Args: + spec: The glom spec. + scope (dict): additional values to add to the scope when + evaluating this Spec + + """ + def __init__(self, spec, scope=None): + self.spec = spec + self.scope = scope or {} + + def glom(self, target, **kw): + scope = dict(self.scope) + scope.update(kw.get('scope', {})) + kw['scope'] = ChainMap(scope) + glom_ = scope.get(glom, glom) + return glom_(target, self.spec, **kw) + + def glomit(self, target, scope): + scope.update(self.scope) + return scope[glom](target, self.spec, scope) + + def __repr__(self): + cn = self.__class__.__name__ + if self.scope: + return f'{cn}({bbrepr(self.spec)}, scope={self.scope!r})' + return f'{cn}({bbrepr(self.spec)})' + + +class Coalesce: + """Coalesce objects specify fallback behavior for a list of + subspecs. + + Subspecs are passed as positional arguments, and keyword arguments + control defaults. Each subspec is evaluated in turn, and if none + match, a :exc:`CoalesceError` is raised, or a default is returned, + depending on the options used. + + .. note:: + + This operation may seem very familar if you have experience with + `SQL`_ or even `C# and others`_. + + + In practice, this fallback behavior's simplicity is only surpassed + by its utility: + + >>> target = {'c': 'd'} + >>> glom(target, Coalesce('a', 'b', 'c')) + 'd' + + glom tries to get ``'a'`` from ``target``, but gets a + KeyError. Rather than raise a :exc:`~glom.PathAccessError` as usual, + glom *coalesces* into the next subspec, ``'b'``. The process + repeats until it gets to ``'c'``, which returns our value, + ``'d'``. If our value weren't present, we'd see: + + >>> target = {} + >>> glom(target, Coalesce('a', 'b')) + Traceback (most recent call last): + ... + CoalesceError: no valid values found. Tried ('a', 'b') and got (PathAccessError, PathAccessError) ... + + Same process, but because ``target`` is empty, we get a + :exc:`CoalesceError`. + + .. note:: + + Coalesce is a *branching* specifier type, so as of v20.7.0, its + exception messages feature an error tree. See + :ref:`branched-exceptions` for details on how to interpret these + exceptions. + + + If we want to avoid an exception, and we know which value we want + by default, we can set *default*: + + >>> target = {} + >>> glom(target, Coalesce('a', 'b', 'c'), default='d-fault') + 'd-fault' + + ``'a'``, ``'b'``, and ``'c'`` weren't present so we got ``'d-fault'``. + + Args: + + subspecs: One or more glommable subspecs + default: A value to return if no subspec results in a valid value + default_factory: A callable whose result will be returned as a default + skip: A value, tuple of values, or predicate function + representing values to ignore + skip_exc: An exception or tuple of exception types to catch and + move on to the next subspec. Defaults to :exc:`GlomError`, the + parent type of all glom runtime exceptions. + + If all subspecs produce skipped values or exceptions, a + :exc:`CoalesceError` will be raised. For more examples, check out + the :doc:`tutorial`, which makes extensive use of Coalesce. + + .. _SQL: https://en.wikipedia.org/w/index.php?title=Null_(SQL)&oldid=833093792#COALESCE + .. _C# and others: https://en.wikipedia.org/w/index.php?title=Null_coalescing_operator&oldid=839493322#C# + + """ + def __init__(self, *subspecs, **kwargs): + self.subspecs = subspecs + self._orig_kwargs = dict(kwargs) + self.default = kwargs.pop('default', _MISSING) + self.default_factory = kwargs.pop('default_factory', _MISSING) + if self.default and self.default_factory: + raise ValueError('expected one of "default" or "default_factory", not both') + self.skip = kwargs.pop('skip', _MISSING) + if self.skip is _MISSING: + self.skip_func = lambda v: False + elif callable(self.skip): + self.skip_func = self.skip + elif isinstance(self.skip, tuple): + self.skip_func = lambda v: v in self.skip + else: + self.skip_func = lambda v: v == self.skip + self.skip_exc = kwargs.pop('skip_exc', GlomError) + if kwargs: + raise TypeError(f'unexpected keyword args: {sorted(kwargs.keys())!r}') + + def glomit(self, target, scope): + skipped = [] + for subspec in self.subspecs: + try: + ret = scope[glom](target, subspec, scope) + if not self.skip_func(ret): + break + skipped.append(ret) + except self.skip_exc as e: + skipped.append(e) + continue + else: + if self.default is not _MISSING: + ret = arg_val(target, self.default, scope) + elif self.default_factory is not _MISSING: + ret = self.default_factory() + else: + raise CoalesceError(self, skipped, scope[Path]) + return ret + + def __repr__(self): + cn = self.__class__.__name__ + return format_invocation(cn, self.subspecs, self._orig_kwargs, repr=bbrepr) + + +class Inspect: + """The :class:`~glom.Inspect` specifier type provides a way to get + visibility into glom's evaluation of a specification, enabling + debugging of those tricky problems that may arise with unexpected + data. + + :class:`~glom.Inspect` can be inserted into an existing spec in one of two + ways. First, as a wrapper around the spec in question, or second, + as an argument-less placeholder wherever a spec could be. + + :class:`~glom.Inspect` supports several modes, controlled by + keyword arguments. Its default, no-argument mode, simply echos the + state of the glom at the point where it appears: + + >>> target = {'a': {'b': {}}} + >>> val = glom(target, Inspect('a.b')) # wrapping a spec + --- + path: ['a.b'] + target: {'a': {'b': {}}} + output: {} + --- + + Debugging behavior aside, :class:`~glom.Inspect` has no effect on + values in the target, spec, or result. + + Args: + echo (bool): Whether to print the path, target, and output of + each inspected glom. Defaults to True. + recursive (bool): Whether or not the Inspect should be applied + at every level, at or below the spec that it wraps. Defaults + to False. + breakpoint (bool): This flag controls whether a debugging prompt + should appear before evaluating each inspected spec. Can also + take a callable. Defaults to False. + post_mortem (bool): This flag controls whether exceptions + should be caught and interactively debugged with :mod:`pdb` on + inspected specs. + + All arguments above are keyword-only to avoid overlap with a + wrapped spec. + + .. note:: + + Just like ``pdb.set_trace()``, be careful about leaving stray + ``Inspect()`` instances in production glom specs. + + """ + def __init__(self, *a, **kw): + self.wrapped = a[0] if a else Path() + self.recursive = kw.pop('recursive', False) + self.echo = kw.pop('echo', True) + breakpoint = kw.pop('breakpoint', False) + if breakpoint is True: + breakpoint = pdb.set_trace + if breakpoint and not callable(breakpoint): + raise TypeError('breakpoint expected bool or callable, not: %r' % breakpoint) + self.breakpoint = breakpoint + post_mortem = kw.pop('post_mortem', False) + if post_mortem is True: + post_mortem = pdb.post_mortem + if post_mortem and not callable(post_mortem): + raise TypeError('post_mortem expected bool or callable, not: %r' % post_mortem) + self.post_mortem = post_mortem + + def __repr__(self): + return '' + + def glomit(self, target, scope): + # stash the real handler under Inspect, + # and replace the child handler with a trace callback + scope[Inspect] = scope[glom] + scope[glom] = self._trace + return scope[glom](target, self.wrapped, scope) + + def _trace(self, target, spec, scope): + if not self.recursive: + scope[glom] = scope[Inspect] + if self.echo: + print('---') + # TODO: switch from scope[Path] to the Target-Spec format trace above + # ... but maybe be smart about only printing deltas instead of the whole + # thing + print('path: ', scope[Path] + [spec]) + print('target:', target) + if self.breakpoint: + # TODO: real debugger here? + self.breakpoint() + try: + ret = scope[Inspect](target, spec, scope) + except Exception: + if self.post_mortem: + self.post_mortem() + raise + if self.echo: + print('output:', ret) + print('---') + return ret + + +class Call: + """:class:`Call` specifies when a target should be passed to a function, + *func*. + + :class:`Call` is similar to :func:`~functools.partial` in that + it is no more powerful than ``lambda`` or other functions, but + it is designed to be more readable, with a better ``repr``. + + Args: + func (callable): a function or other callable to be called with + the target + + :class:`Call` combines well with :attr:`~glom.T` to construct objects. For + instance, to generate a dict and then pass it to a constructor: + + >>> class ExampleClass(object): + ... def __init__(self, attr): + ... self.attr = attr + ... + >>> target = {'attr': 3.14} + >>> glom(target, Call(ExampleClass, kwargs=T)).attr + 3.14 + + This does the same as ``glom(target, lambda target: + ExampleClass(**target))``, but it's easy to see which one reads + better. + + .. note:: + + ``Call`` is mostly for functions. Use a :attr:`~glom.T` object + if you need to call a method. + + .. warning:: + + :class:`Call` has a successor with a fuller-featured API, new + in 19.10.0: the :class:`Invoke` specifier type. + """ + def __init__(self, func=None, args=None, kwargs=None): + if func is None: + func = T + if not (callable(func) or isinstance(func, (Spec, TType))): + raise TypeError('expected func to be a callable or T' + ' expression, not: %r' % (func,)) + if args is None: + args = () + if kwargs is None: + kwargs = {} + self.func, self.args, self.kwargs = func, args, kwargs + + def glomit(self, target, scope): + 'run against the current target' + r = lambda spec: arg_val(target, spec, scope) + return r(self.func)(*r(self.args), **r(self.kwargs)) + + def __repr__(self): + cn = self.__class__.__name__ + return f'{cn}({bbrepr(self.func)}, args={self.args!r}, kwargs={self.kwargs!r})' + + +def _is_spec(obj, strict=False): + # a little util for codifying the spec type checking in glom + if isinstance(obj, TType): + return True + if strict: + return type(obj) is Spec + + return _has_callable_glomit(obj) # pragma: no cover + + +class Invoke: + """Specifier type designed for easy invocation of callables from glom. + + Args: + func (callable): A function or other callable object. + + ``Invoke`` is similar to :func:`functools.partial`, but with the + ability to set up a "templated" call which interleaves constants and + glom specs. + + For example, the following creates a spec which can be used to + check if targets are integers: + + >>> is_int = Invoke(isinstance).specs(T).constants(int) + >>> glom(5, is_int) + True + + And this composes like any other glom spec: + + >>> target = [7, object(), 9] + >>> glom(target, [is_int]) + [True, False, True] + + Another example, mixing positional and keyword arguments: + + >>> spec = Invoke(sorted).specs(T).constants(key=int, reverse=True) + >>> target = ['10', '5', '20', '1'] + >>> glom(target, spec) + ['20', '10', '5', '1'] + + Invoke also helps with evaluating zero-argument functions: + + >>> glom(target={}, spec=Invoke(int)) + 0 + + (A trivial example, but from timestamps to UUIDs, zero-arg calls do come up!) + + .. note:: + + ``Invoke`` is mostly for functions, object construction, and callable + objects. For calling methods, consider the :attr:`~glom.T` object. + + """ + def __init__(self, func): + if not callable(func) and not _is_spec(func, strict=True): + raise TypeError('expected func to be a callable or Spec instance,' + ' not: %r' % (func,)) + self.func = func + self._args = () + # a registry of every known kwarg to its freshest value as set + # by the methods below. the **kw dict is used as a unique marker. + self._cur_kwargs = {} + + @classmethod + def specfunc(cls, spec): + """Creates an :class:`Invoke` instance where the function is + indicated by a spec. + + >>> spec = Invoke.specfunc('func').constants(5) + >>> glom({'func': range}, (spec, list)) + [0, 1, 2, 3, 4] + + """ + return cls(Spec(spec)) + + def constants(self, *a, **kw): + """Returns a new :class:`Invoke` spec, with the provided positional + and keyword argument values stored for passing to the + underlying function. + + >>> spec = Invoke(T).constants(5) + >>> glom(range, (spec, list)) + [0, 1, 2, 3, 4] + + Subsequent positional arguments are appended: + + >>> spec = Invoke(T).constants(2).constants(10, 2) + >>> glom(range, (spec, list)) + [2, 4, 6, 8] + + Keyword arguments also work as one might expect: + + >>> round_2 = Invoke(round).constants(ndigits=2).specs(T) + >>> glom(3.14159, round_2) + 3.14 + + :meth:`~Invoke.constants()` and other :class:`Invoke` + methods may be called multiple times, just remember that every + call returns a new spec. + """ + ret = self.__class__(self.func) + ret._args = self._args + ('C', a, kw) + ret._cur_kwargs = dict(self._cur_kwargs) + ret._cur_kwargs.update({k: kw for k, _ in kw.items()}) + return ret + + def specs(self, *a, **kw): + """Returns a new :class:`Invoke` spec, with the provided positional + and keyword arguments stored to be interpreted as specs, with + the results passed to the underlying function. + + >>> spec = Invoke(range).specs('value') + >>> glom({'value': 5}, (spec, list)) + [0, 1, 2, 3, 4] + + Subsequent positional arguments are appended: + + >>> spec = Invoke(range).specs('start').specs('end', 'step') + >>> target = {'start': 2, 'end': 10, 'step': 2} + >>> glom(target, (spec, list)) + [2, 4, 6, 8] + + Keyword arguments also work as one might expect: + + >>> multiply = lambda x, y: x * y + >>> times_3 = Invoke(multiply).constants(y=3).specs(x='value') + >>> glom({'value': 5}, times_3) + 15 + + :meth:`~Invoke.specs()` and other :class:`Invoke` + methods may be called multiple times, just remember that every + call returns a new spec. + + """ + ret = self.__class__(self.func) + ret._args = self._args + ('S', a, kw) + ret._cur_kwargs = dict(self._cur_kwargs) + ret._cur_kwargs.update({k: kw for k, _ in kw.items()}) + return ret + + def star(self, args=None, kwargs=None): + """Returns a new :class:`Invoke` spec, with *args* and/or *kwargs* + specs set to be "starred" or "star-starred" (respectively) + + >>> spec = Invoke(zip).star(args='lists') + >>> target = {'lists': [[1, 2], [3, 4], [5, 6]]} + >>> list(glom(target, spec)) + [(1, 3, 5), (2, 4, 6)] + + Args: + args (spec): A spec to be evaluated and "starred" into the + underlying function. + kwargs (spec): A spec to be evaluated and "star-starred" into + the underlying function. + + One or both of the above arguments should be set. + + The :meth:`~Invoke.star()`, like other :class:`Invoke` + methods, may be called multiple times. The *args* and *kwargs* + will be stacked in the order in which they are provided. + """ + if args is None and kwargs is None: + raise TypeError('expected one or both of args/kwargs to be passed') + ret = self.__class__(self.func) + ret._args = self._args + ('*', args, kwargs) + ret._cur_kwargs = dict(self._cur_kwargs) + return ret + + def __repr__(self): + base_fname = self.__class__.__name__ + fname_map = {'C': 'constants', 'S': 'specs', '*': 'star'} + if type(self.func) is Spec: + base_fname += '.specfunc' + args = (self.func.spec,) + else: + args = (self.func,) + chunks = [format_invocation(base_fname, args, repr=bbrepr)] + + for i in range(len(self._args) // 3): + op, args, _kwargs = self._args[i * 3: i * 3 + 3] + fname = fname_map[op] + if op in ('C', 'S'): + kwargs = [(k, v) for k, v in _kwargs.items() + if self._cur_kwargs[k] is _kwargs] + else: + kwargs = {} + if args: + kwargs['args'] = args + if _kwargs: + kwargs['kwargs'] = _kwargs + args = () + + chunks.append('.' + format_invocation(fname, args, kwargs, repr=bbrepr)) + + return ''.join(chunks) + + def glomit(self, target, scope): + all_args = [] + all_kwargs = {} + + recurse = lambda spec: scope[glom](target, spec, scope) + func = recurse(self.func) if _is_spec(self.func, strict=True) else self.func + + for i in range(len(self._args) // 3): + op, args, kwargs = self._args[i * 3: i * 3 + 3] + if op == 'C': + all_args.extend(args) + all_kwargs.update({k: v for k, v in kwargs.items() + if self._cur_kwargs[k] is kwargs}) + elif op == 'S': + all_args.extend([recurse(arg) for arg in args]) + all_kwargs.update({k: recurse(v) for k, v in kwargs.items() + if self._cur_kwargs[k] is kwargs}) + elif op == '*': + if args is not None: + all_args.extend(recurse(args)) + if kwargs is not None: + all_kwargs.update(recurse(kwargs)) + + return func(*all_args, **all_kwargs) + + +class Ref: + """Name a part of a spec and refer to it elsewhere in the same spec, + useful for trees and other self-similar data structures. + + Args: + name (str): The name of the spec to reference. + subspec: Pass a spec to name it *name*, or leave unset to refer + to an already-named spec. + """ + def __init__(self, name, subspec=_MISSING): + self.name, self.subspec = name, subspec + + def glomit(self, target, scope): + subspec = self.subspec + scope_key = (Ref, self.name) + if subspec is _MISSING: + subspec = scope[scope_key] + else: + scope[scope_key] = subspec + return scope[glom](target, subspec, scope) + + def __repr__(self): + if self.subspec is _MISSING: + args = bbrepr(self.name) + else: + args = bbrepr((self.name, self.subspec))[1:-1] + return "Ref(" + args + ")" + + +class TType: + """``T``, short for "target". A singleton object that enables + object-oriented expression of a glom specification. + + .. note:: + + ``T`` is a singleton, and does not need to be constructed. + + Basically, think of ``T`` as your data's stunt double. Everything + that you do to ``T`` will be recorded and executed during the + :func:`glom` call. Take this example: + + >>> spec = T['a']['b']['c'] + >>> target = {'a': {'b': {'c': 'd'}}} + >>> glom(target, spec) + 'd' + + So far, we've relied on the ``'a.b.c'``-style shorthand for + access, or used the :class:`~glom.Path` objects, but if you want + to explicitly do attribute and key lookups, look no further than + ``T``. + + But T doesn't stop with unambiguous access. You can also call + methods and perform almost any action you would with a normal + object: + + >>> spec = ('a', (T['b'].items(), list)) # reviewed below + >>> glom(target, spec) + [('c', 'd')] + + A ``T`` object can go anywhere in the spec. As seen in the example + above, we access ``'a'``, use a ``T`` to get ``'b'`` and iterate + over its ``items``, turning them into a ``list``. + + You can even use ``T`` with :class:`~glom.Call` to construct objects: + + >>> class ExampleClass(object): + ... def __init__(self, attr): + ... self.attr = attr + ... + >>> target = {'attr': 3.14} + >>> glom(target, Call(ExampleClass, kwargs=T)).attr + 3.14 + + On a further note, while ``lambda`` works great in glom specs, and + can be very handy at times, ``T`` and :class:`~glom.Call` + eliminate the need for the vast majority of ``lambda`` usage with + glom. + + Unlike ``lambda`` and other functions, ``T`` roundtrips + beautifully and transparently: + + >>> T['a'].b['c']('success') + T['a'].b['c']('success') + + ``T``-related access errors raise a :exc:`~glom.PathAccessError` + during the :func:`~glom.glom` call. + + .. note:: + + While ``T`` is clearly useful, powerful, and here to stay, its + semantics are still being refined. Currently, operations beyond + method calls and attribute/item access are considered + experimental and should not be relied upon. + + .. note:: + + ``T`` attributes starting with __ are reserved to avoid + colliding with many built-in Python behaviors, current and + future. The ``T.__()`` method is available for cases where + they are needed. For example, ``T.__('class__')`` is + equivalent to accessing the ``__class__`` attribute. + + """ + __slots__ = ('__ops__',) + + def __getattr__(self, name): + if name.startswith('__'): + raise AttributeError('T instances reserve dunder attributes.' + ' To access the "{name}" attribute, use' + ' T.__("{d_name}")'.format(name=name, d_name=name[2:])) + return _t_child(self, '.', name) + + def __getitem__(self, item): + return _t_child(self, '[', item) + + def __call__(self, *args, **kwargs): + if self is S: + if args: + raise TypeError(f'S() takes no positional arguments, got: {args!r}') + if not kwargs: + raise TypeError('S() expected at least one kwarg, got none') + # TODO: typecheck kwarg vals? + return _t_child(self, '(', (args, kwargs)) + + def __star__(self): + return _t_child(self, 'x', None) + + def __starstar__(self): + return _t_child(self, 'X', None) + + def __stars__(self): + """how many times the result will be wrapped in extra lists""" + t_ops = self.__ops__[1::2] + return t_ops.count('x') + t_ops.count('X') + + def __add__(self, arg): + return _t_child(self, '+', arg) + + def __sub__(self, arg): + return _t_child(self, '-', arg) + + def __mul__(self, arg): + return _t_child(self, '*', arg) + + def __floordiv__(self, arg): + return _t_child(self, '#', arg) + + def __truediv__(self, arg): + return _t_child(self, '/', arg) + + __div__ = __truediv__ + + def __mod__(self, arg): + return _t_child(self, '%', arg) + + def __pow__(self, arg): + return _t_child(self, ':', arg) + + def __and__(self, arg): + return _t_child(self, '&', arg) + + def __or__(self, arg): + return _t_child(self, '|', arg) + + def __xor__(self, arg): + return _t_child(self, '^', arg) + + def __invert__(self): + return _t_child(self, '~', None) + + def __neg__(self): + return _t_child(self, '_', None) + + def __(self, name): + return _t_child(self, '.', '__' + name) + + def __repr__(self): + t_path = self.__ops__ + return _format_t(t_path[1:], t_path[0]) + + def __getstate__(self): + t_path = self.__ops__ + return tuple(({T: 'T', S: 'S', A: 'A'}[t_path[0]],) + t_path[1:]) + + def __setstate__(self, state): + self.__ops__ = ({'T': T, 'S': S, 'A': A}[state[0]],) + state[1:] + + +def _t_child(parent, operation, arg): + base = parent.__ops__ + if base[0] is A and operation not in ('.', '[', 'P'): + # whitelist rather than blacklist assignment friendly operations + # TODO: error type? + raise BadSpec("operation not allowed on A assignment path") + t = TType() + t.__ops__ = base + (operation, arg) + return t + + +def _s_first_magic(scope, key, _t): + """ + enable S.a to do S['a'] or S['a'].val as a special + case for accessing user defined string variables + """ + err = None + try: + cur = scope[key] + except KeyError as e: + err = PathAccessError(e, Path(_t), 0) # always only one level depth, hence 0 + if err: + raise err + return cur + + +def _t_eval(target, _t, scope): + t_path = _t.__ops__ + i = 1 + fetch_till = len(t_path) + root = t_path[0] + if root is T: + cur = target + elif root is S or root is A: + # A is basically the same as S, but last step is assign + if root is A: + fetch_till -= 2 + if fetch_till < 1: + raise BadSpec('cannot assign without destination') + cur = scope + if fetch_till > 1 and t_path[1] in ('.', 'P'): + cur = _s_first_magic(cur, t_path[2], _t) + i += 2 + elif root is S and fetch_till > 1 and t_path[1] == '(': + # S(var='spec') style assignment + _, kwargs = t_path[2] + scope.update({ + k: arg_val(target, v, scope) for k, v in kwargs.items()}) + return target + + else: + raise ValueError('TType instance with invalid root') # pragma: no cover + pae = None + while i < fetch_till: + op, arg = t_path[i], t_path[i + 1] + arg = arg_val(target, arg, scope) + if op == '.': + try: + cur = getattr(cur, arg) + except AttributeError as e: + pae = PathAccessError(e, Path(_t), i // 2) + elif op == '[': + try: + cur = cur[arg] + except (KeyError, IndexError, TypeError) as e: + pae = PathAccessError(e, Path(_t), i // 2) + elif op == 'P': + # Path type stuff (fuzzy match) + get = scope[TargetRegistry].get_handler('get', cur, path=t_path[2:i+2:2]) + try: + cur = get(cur, arg) + except Exception as e: + pae = PathAccessError(e, Path(_t), i // 2) + elif op in 'xX': + nxt = [] + get_handler = scope[TargetRegistry].get_handler + if op == 'x': # increases arity of cur each time through + # TODO: so many try/except -- could scope[TargetRegistry] stuff be cached on type? + _extend_children(nxt, cur, get_handler) + elif op == 'X': + sofar = set() + _extend_children(nxt, cur, get_handler) + for item in nxt: + if id(item) not in sofar: + sofar.add(id(item)) + _extend_children(nxt, item, get_handler) + nxt.insert(0, cur) + # handle the rest of the t_path in recursive calls + cur = [] + todo = TType() + todo.__ops__ = (root,) + t_path[i+2:] + for child in nxt: + try: + cur.append(_t_eval(child, todo, scope)) + except PathAccessError: + pass + break # we handled the rest in recursive call, break loop + elif op == '(': + args, kwargs = arg + scope[Path] += t_path[2:i+2:2] + cur = scope[glom]( + target, Call(cur, args, kwargs), scope) + # call with target rather than cur, + # because it is probably more intuitive + # if args to the call "reset" their path + # e.g. "T.a" should mean the same thing + # in both of these specs: T.a and T.b(T.a) + else: # arithmetic operators + try: + if op == '+': + cur = cur + arg + elif op == '-': + cur = cur - arg + elif op == '*': + cur = cur * arg + #elif op == '#': + # cur = cur // arg # TODO: python 2 friendly approach? + elif op == '/': + cur = cur / arg + elif op == '%': + cur = cur % arg + elif op == ':': + cur = cur ** arg + elif op == '&': + cur = cur & arg + elif op == '|': + cur = cur | arg + elif op == '^': + cur = cur ^ arg + elif op == '~': + cur = ~cur + elif op == '_': + cur = -cur + except (TypeError, ZeroDivisionError) as e: + pae = PathAccessError(e, Path(_t), i // 2) + if pae: + raise pae + i += 2 + if root is A: + op, arg = t_path[-2:] + if cur is scope: + op = '[' # all assignment on scope is setitem + _assign_op(dest=cur, op=op, arg=arg, val=target, path=_t, scope=scope) + return target # A should not change the target + return cur + + +def _assign_op(dest, op, arg, val, path, scope): + """helper method for doing the assignment on a T operation""" + if op == '[': + dest[arg] = val + elif op == '.': + setattr(dest, arg, val) + elif op == 'P': + _assign = scope[TargetRegistry].get_handler('assign', dest) + try: + _assign(dest, arg, val) + except Exception as e: + raise PathAssignError(e, path, arg) + else: # pragma: no cover + raise ValueError('unsupported T operation for assignment') + + +def _extend_children(children, item, get_handler): + try: # dict or obj-like + keys = get_handler('keys', item) + get = get_handler('get', item) + except UnregisteredTarget: + try: + iterate = get_handler('iterate', item) + except UnregisteredTarget: + pass + else: + try: # list-like + children.extend(iterate(item)) + except Exception: + pass + else: + try: + for key in keys(item): + try: + children.append(get(item, key)) + except Exception: + pass + except Exception: + pass + + +T = TType() # target aka Mr. T aka "this" +S = TType() # like T, but means grab stuff from Scope, not Target +A = TType() # like S, but shorthand to assign target to scope + +T.__ops__ = (T,) +S.__ops__ = (S,) +A.__ops__ = (A,) + +_T_STAR = T.__star__() # helper constant for Path.from_text +_T_STARSTAR = T.__starstar__() # helper constant for Path.from_text + +UP = make_sentinel('UP') +ROOT = make_sentinel('ROOT') + + +def _format_slice(x): + if type(x) is not slice: + return bbrepr(x) + fmt = lambda v: "" if v is None else bbrepr(v) + if x.step is None: + return fmt(x.start) + ":" + fmt(x.stop) + return fmt(x.start) + ":" + fmt(x.stop) + ":" + fmt(x.step) + + +def _format_t(path, root=T): + prepr = [{T: 'T', S: 'S', A: 'A'}[root]] + i = 0 + while i < len(path): + op, arg = path[i], path[i + 1] + if op == '.': + prepr.append('.' + arg) + elif op == '[': + if type(arg) is tuple: + index = ", ".join([_format_slice(x) for x in arg]) + else: + index = _format_slice(arg) + prepr.append(f"[{index}]") + elif op == '(': + args, kwargs = arg + prepr.append(format_invocation(args=args, kwargs=kwargs, repr=bbrepr)) + elif op == 'P': + return _format_path(path) + elif op == 'x': + prepr.append(".__star__()") + elif op == 'X': + prepr.append(".__starstar__()") + elif op in ('_', '~'): # unary arithmetic operators + if any([o in path[:i] for o in '+-/%:&|^~_']): + prepr = ['('] + prepr + [')'] + prepr = ['-' if op == '_' else op] + prepr + else: # binary arithmetic operators + formatted_arg = bbrepr(arg) + if type(arg) is TType: + arg_path = arg.__ops__ + if any([o in arg_path for o in '+-/%:&|^~_']): + formatted_arg = '(' + formatted_arg + ')' + prepr.append(' ' + ('**' if op == ':' else op) + ' ') + prepr.append(formatted_arg) + i += 2 + return "".join(prepr) + + +class Val: + """Val objects are specs which evaluate to the wrapped *value*. + + >>> target = {'a': {'b': 'c'}} + >>> spec = {'a': 'a.b', 'readability': Val('counts')} + >>> pprint(glom(target, spec)) + {'a': 'c', 'readability': 'counts'} + + Instead of accessing ``'counts'`` as a key like it did with + ``'a.b'``, :func:`~glom.glom` just unwrapped the Val and + included the value. + + :class:`~glom.Val` takes one argument, the value to be returned. + + .. note:: + + :class:`Val` was named ``Literal`` in versions of glom before + 20.7.0. An alias has been preserved for backwards + compatibility, but reprs have changed. + + """ + def __init__(self, value): + self.value = value + + def glomit(self, target, scope): + return self.value + + def __repr__(self): + cn = self.__class__.__name__ + return f'{cn}({bbrepr(self.value)})' + + +Literal = Val # backwards compat for pre-20.7.0 + + +class ScopeVars: + """This is the runtime partner of :class:`Vars` -- this is what + actually lives in the scope and stores runtime values. + + While not part of the importable API of glom, it's half expected + that some folks may write sepcs to populate and export scopes, at + which point this type makes it easy to access values by attribute + access or by converting to a dict. + + """ + def __init__(self, base, defaults): + self.__dict__ = dict(base) + self.__dict__.update(defaults) + + def __iter__(self): + return iter(self.__dict__.items()) + + def __repr__(self): + return f"{self.__class__.__name__}({bbrepr(self.__dict__)})" + + +class Vars: + """ + :class:`Vars` is a helper that can be used with **S** in order to + store shared mutable state. + + Takes the same arguments as :class:`dict()`. + + Arguments here should be thought of the same way as default arguments + to a function. Each time the spec is evaluated, the same arguments + will be referenced; so, think carefully about mutable data structures. + """ + def __init__(self, base=(), **kw): + dict(base) # ensure it is a dict-compatible first arg + self.base = base + self.defaults = kw + + def glomit(self, target, spec): + return ScopeVars(self.base, self.defaults) + + def __repr__(self): + ret = format_invocation(self.__class__.__name__, + args=(self.base,) if self.base else (), + kwargs=self.defaults, + repr=bbrepr) + return ret + + +class Let: + """ + Deprecated, kept for backwards compat. Use S(x='y') instead. + + >>> target = {'data': {'val': 9}} + >>> spec = (Let(value=T['data']['val']), {'val': S['value']}) + >>> glom(target, spec) + {'val': 9} + + """ + def __init__(self, **kw): + if not kw: + raise TypeError('expected at least one keyword argument') + self._binding = kw + + def glomit(self, target, scope): + scope.update({ + k: scope[glom](target, v, scope) for k, v in self._binding.items()}) + return target + + def __repr__(self): + cn = self.__class__.__name__ + return format_invocation(cn, kwargs=self._binding, repr=bbrepr) + + +class Auto: + """ + Switch to Auto mode (the default) + + TODO: this seems like it should be a sub-class of class Spec() -- + if Spec() could help define the interface for new "modes" or dialects + that would also help make match mode feel less duct-taped on + """ + def __init__(self, spec=None): + self.spec = spec + + def glomit(self, target, scope): + scope[MODE] = AUTO + return scope[glom](target, self.spec, scope) + + def __repr__(self): + cn = self.__class__.__name__ + rpr = '' if self.spec is None else bbrepr(self.spec) + return f'{cn}({rpr})' + + +class _AbstractIterable(_AbstractIterableBase): + __metaclass__ = ABCMeta + @classmethod + def __subclasshook__(cls, C): + if C in (str, bytes): + return False + return callable(getattr(C, "__iter__", None)) + + +class _ObjStyleKeysMeta(type): + def __instancecheck__(cls, C): + return hasattr(C, "__dict__") and hasattr(C.__dict__, "keys") + + +class _ObjStyleKeys(_ObjStyleKeysMeta('_AbstractKeys', (object,), {})): + __metaclass__ = _ObjStyleKeysMeta + + @staticmethod + def get_keys(obj): + ret = obj.__dict__.keys() + return ret + + +def _get_sequence_item(target, index): + return target[int(index)] + + +# handlers are 3-arg callables, with args (spec, target, scope) +# spec is the first argument for convenience in the case +# that the handler is a method of the spec type +def _handle_dict(target, spec, scope): + ret = type(spec)() # TODO: works for dict + ordereddict, but sufficient for all? + for field, subspec in spec.items(): + val = scope[glom](target, subspec, scope) + if val is SKIP: + continue + if type(field) in (Spec, TType): + field = scope[glom](target, field, scope) + ret[field] = val + return ret + + +def _handle_list(target, spec, scope): + subspec = spec[0] + iterate = scope[TargetRegistry].get_handler('iterate', target, path=scope[Path]) + try: + iterator = iterate(target) + except Exception as e: + raise TypeError('failed to iterate on instance of type %r at %r (got %r)' + % (target.__class__.__name__, Path(*scope[Path]), e)) + ret = [] + base_path = scope[Path] + for i, t in enumerate(iterator): + scope[Path] = base_path + [i] + val = scope[glom](t, subspec, scope) + if val is SKIP: + continue + if val is STOP: + break + ret.append(val) + return ret + + +def _handle_tuple(target, spec, scope): + res = target + for subspec in spec: + scope = chain_child(scope) + nxt = scope[glom](res, subspec, scope) + if nxt is SKIP: + continue + if nxt is STOP: + break + res = nxt + if not isinstance(subspec, list): + scope[Path] += [getattr(subspec, '__name__', subspec)] + return res + + +class Pipe: + """Evaluate specs one after the other, passing the result of + the previous evaluation in as the target of the next spec: + + >>> glom({'a': {'b': -5}}, Pipe('a', 'b', abs)) + 5 + + Same behavior as ``Auto(tuple(steps))``, but useful for explicit + usage in other modes. + """ + def __init__(self, *steps): + self.steps = steps + + def glomit(self, target, scope): + return _handle_tuple(target, self.steps, scope) + + def __repr__(self): + return self.__class__.__name__ + bbrepr(self.steps) + + +class TargetRegistry: + ''' + responsible for registration of target types for iteration + and attribute walking + ''' + def __init__(self, register_default_types=True): + self._op_type_map = {} + self._op_type_tree = {} # see _register_fuzzy_type for details + self._type_cache = {} + + self._op_auto_map = OrderedDict() # op name to function that returns handler function + + self._register_builtin_ops() + + if register_default_types: + self._register_default_types() + return + + def get_handler(self, op, obj, path=None, raise_exc=True): + """for an operation and object **instance**, obj, return the + closest-matching handler function, raising UnregisteredTarget + if no handler can be found for *obj* (or False if + raise_exc=False) + + """ + ret = False + obj_type = type(obj) + cache_key = (obj_type, op) + if cache_key not in self._type_cache: + type_map = self.get_type_map(op) + if type_map: + try: + ret = type_map[obj_type] + except KeyError: + type_tree = self._op_type_tree.get(op, {}) + closest = self._get_closest_type(obj, type_tree=type_tree) + if closest is None: + ret = False + else: + ret = type_map[closest] + + if ret is False and raise_exc: + raise UnregisteredTarget(op, obj_type, type_map=type_map, path=path) + + self._type_cache[cache_key] = ret + return self._type_cache[cache_key] + + def get_type_map(self, op): + try: + return self._op_type_map[op] + except KeyError: + return OrderedDict() + + def _get_closest_type(self, obj, type_tree): + default = None + for cur_type, sub_tree in type_tree.items(): + if isinstance(obj, cur_type): + sub_type = self._get_closest_type(obj, type_tree=sub_tree) + ret = cur_type if sub_type is None else sub_type + return ret + return default + + def _register_default_types(self): + self.register(object) + self.register(dict, get=operator.getitem) + self.register(dict, keys=dict.keys) + self.register(list, get=_get_sequence_item) + self.register(tuple, get=_get_sequence_item) + self.register(OrderedDict, get=operator.getitem) + self.register(OrderedDict, keys=OrderedDict.keys) + self.register(_AbstractIterable, iterate=iter) + self.register(_ObjStyleKeys, keys=_ObjStyleKeys.get_keys) + + def _register_fuzzy_type(self, op, new_type, _type_tree=None): + """Build a "type tree", an OrderedDict mapping registered types to + their subtypes + + The type tree's invariant is that a key in the mapping is a + valid parent type of all its children. + + Order is preserved such that non-overlapping parts of the + subtree take precedence by which was most recently added. + """ + if _type_tree is None: + try: + _type_tree = self._op_type_tree[op] + except KeyError: + _type_tree = self._op_type_tree[op] = OrderedDict() + + registered = False + for cur_type, sub_tree in list(_type_tree.items()): + if issubclass(cur_type, new_type): + sub_tree = _type_tree.pop(cur_type) # mutation for recursion brevity + try: + _type_tree[new_type][cur_type] = sub_tree + except KeyError: + _type_tree[new_type] = OrderedDict({cur_type: sub_tree}) + registered = True + elif issubclass(new_type, cur_type): + _type_tree[cur_type] = self._register_fuzzy_type(op, new_type, _type_tree=sub_tree) + registered = True + if not registered: + _type_tree[new_type] = OrderedDict() + return _type_tree + + def register(self, target_type, **kwargs): + if not isinstance(target_type, type): + raise TypeError(f'register expected a type, not an instance: {target_type!r}') + exact = kwargs.pop('exact', None) + new_op_map = dict(kwargs) + + for op_name in sorted(set(self._op_auto_map.keys()) | set(new_op_map.keys())): + cur_type_map = self._op_type_map.setdefault(op_name, OrderedDict()) + + if op_name in new_op_map: + handler = new_op_map[op_name] + elif target_type in cur_type_map: + handler = cur_type_map[target_type] + else: + try: + handler = self._op_auto_map[op_name](target_type) + except Exception as e: + raise TypeError('error while determining support for operation' + ' "%s" on target type: %s (got %r)' + % (op_name, target_type.__name__, e)) + if handler is not False and not callable(handler): + raise TypeError('expected handler for op "%s" to be' + ' callable or False, not: %r' % (op_name, handler)) + new_op_map[op_name] = handler + + for op_name, handler in new_op_map.items(): + self._op_type_map[op_name][target_type] = handler + + if not exact: + for op_name in new_op_map: + self._register_fuzzy_type(op_name, target_type) + + self._type_cache = {} # reset type cache + + return + + def register_op(self, op_name, auto_func=None, exact=False): + """add operations beyond the builtins ('get' and 'iterate' at the time + of writing). + + auto_func is a function that when passed a type, returns a + handler associated with op_name if it's supported, or False if + it's not. + + See glom.core.register_op() for the global version used by + extensions. + """ + if not isinstance(op_name, basestring): + raise TypeError(f'expected op_name to be a text name, not: {op_name!r}') + if auto_func is None: + auto_func = lambda t: False + elif not callable(auto_func): + raise TypeError(f'expected auto_func to be callable, not: {auto_func!r}') + + # determine support for any previously known types + known_types = set(sum([list(m.keys()) for m + in self._op_type_map.values()], [])) + type_map = self._op_type_map.get(op_name, OrderedDict()) + type_tree = self._op_type_tree.get(op_name, OrderedDict()) + for t in sorted(known_types, key=lambda t: t.__name__): + if t in type_map: + continue + try: + handler = auto_func(t) + except Exception as e: + raise TypeError('error while determining support for operation' + ' "%s" on target type: %s (got %r)' + % (op_name, t.__name__, e)) + if handler is not False and not callable(handler): + raise TypeError('expected handler for op "%s" to be' + ' callable or False, not: %r' % (op_name, handler)) + type_map[t] = handler + + if not exact: + for t in known_types: + self._register_fuzzy_type(op_name, t, _type_tree=type_tree) + + self._op_type_map[op_name] = type_map + self._op_type_tree[op_name] = type_tree + self._op_auto_map[op_name] = auto_func + + def _register_builtin_ops(self): + def _get_iterable_handler(type_obj): + return iter if callable(getattr(type_obj, '__iter__', None)) else False + + self.register_op('iterate', _get_iterable_handler) + self.register_op('get', lambda _: getattr) + + +_DEFAULT_SCOPE = ChainMap({}) + + +def glom(target, spec, **kwargs): + """Access or construct a value from a given *target* based on the + specification declared by *spec*. + + Accessing nested data, aka deep-get: + + >>> target = {'a': {'b': 'c'}} + >>> glom(target, 'a.b') + 'c' + + Here the *spec* was just a string denoting a path, + ``'a.b'``. As simple as it should be. You can also use + :mod:`glob`-like wildcard selectors: + + >>> target = {'a': [{'k': 'v1'}, {'k': 'v2'}]} + >>> glom(target, 'a.*.k') + ['v1', 'v2'] + + In addition to ``*``, you can also use ``**`` for recursive access: + + >>> target = {'a': [{'k': 'v3'}, {'k': 'v4'}], 'k': 'v0'} + >>> glom(target, '**.k') + ['v0', 'v3', 'v4'] + + The next example shows how to use nested data to + access many fields at once, and make a new nested structure. + + Constructing, or restructuring more-complicated nested data: + + >>> target = {'a': {'b': 'c', 'd': 'e'}, 'f': 'g', 'h': [0, 1, 2]} + >>> spec = {'a': 'a.b', 'd': 'a.d', 'h': ('h', [lambda x: x * 2])} + >>> output = glom(target, spec) + >>> pprint(output) + {'a': 'c', 'd': 'e', 'h': [0, 2, 4]} + + ``glom`` also takes a keyword-argument, *default*. When set, + if a ``glom`` operation fails with a :exc:`GlomError`, the + *default* will be returned, very much like + :meth:`dict.get()`: + + >>> glom(target, 'a.xx', default='nada') + 'nada' + + The *skip_exc* keyword argument controls which errors should + be ignored. + + >>> glom({}, lambda x: 100.0 / len(x), default=0.0, skip_exc=ZeroDivisionError) + 0.0 + + Args: + target (object): the object on which the glom will operate. + spec (object): Specification of the output object in the form + of a dict, list, tuple, string, other glom construct, or + any composition of these. + default (object): An optional default to return in the case + an exception, specified by *skip_exc*, is raised. + skip_exc (Exception): An optional exception or tuple of + exceptions to ignore and return *default* (None if + omitted). If *skip_exc* and *default* are both not set, + glom raises errors through. + scope (dict): Additional data that can be accessed + via S inside the glom-spec. Read more: :ref:`scope`. + + It's a small API with big functionality, and glom's power is + only surpassed by its intuitiveness. Give it a whirl! + + """ + # TODO: check spec up front + default = kwargs.pop('default', None if 'skip_exc' in kwargs else _MISSING) + skip_exc = kwargs.pop('skip_exc', () if default is _MISSING else GlomError) + glom_debug = kwargs.pop('glom_debug', GLOM_DEBUG) + scope = _DEFAULT_SCOPE.new_child({ + Path: kwargs.pop('path', []), + Inspect: kwargs.pop('inspector', None), + MODE: AUTO, + MIN_MODE: None, + CHILD_ERRORS: [], + 'globals': ScopeVars({}, {}), + }) + scope[UP] = scope + scope[ROOT] = scope + scope[T] = target + scope.update(kwargs.pop('scope', {})) + err = None + if kwargs: + raise TypeError('unexpected keyword args: %r' % sorted(kwargs.keys())) + try: + try: + ret = _glom(target, spec, scope) + except skip_exc: + if default is _MISSING: + raise + ret = default # should this also be arg_val'd? + except Exception as e: + if glom_debug: + raise + if isinstance(e, GlomError): + # need to change id or else py3 seems to not let us truncate the + # stack trace with the explicit "raise err" below + err = copy.copy(e) + err._set_wrapped(e) + else: + err = GlomError.wrap(e) + if isinstance(err, GlomError): + err._finalize(scope[LAST_CHILD_SCOPE]) + else: # wrapping failed, fall back to default behavior + raise + + if err: + raise err + return ret + + +def chain_child(scope): + """ + used for specs like Auto(tuple), Switch(), etc + that want to chain their child scopes together + + returns a new scope that can be passed to + the next recursive glom call, e.g. + + scope[glom](target, spec, chain_child(scope)) + """ + if LAST_CHILD_SCOPE not in scope.maps[0]: + return scope # no children yet, nothing to do + # NOTE: an option here is to drill down on LAST_CHILD_SCOPE; + # this would have some interesting consequences for scoping + # of tuples + nxt_in_chain = scope[LAST_CHILD_SCOPE] + nxt_in_chain.maps[0][NO_PYFRAME] = True + # previous failed branches are forgiven as the + # scope is re-wired into a new stack + del nxt_in_chain.maps[0][CHILD_ERRORS][:] + return nxt_in_chain + + +unbound_methods = {type(str.__len__)} #, type(Ref.glomit)]) + + +def _has_callable_glomit(obj): + glomit = getattr(obj, 'glomit', None) + return callable(glomit) and not isinstance(obj, type) + + +def _glom(target, spec, scope): + parent = scope + pmap = parent.maps[0] + scope = scope.new_child({ + T: target, + Spec: spec, + UP: parent, + CHILD_ERRORS: [], + MODE: pmap[MODE], + MIN_MODE: pmap[MIN_MODE], + }) + pmap[LAST_CHILD_SCOPE] = scope + + try: + if type(spec) is TType: # must go first, due to callability + scope[MIN_MODE] = None # None is tombstone + return _t_eval(target, spec, scope) + elif _has_callable_glomit(spec): + scope[MIN_MODE] = None + return spec.glomit(target, scope) + + return (scope.maps[0][MIN_MODE] or scope.maps[0][MODE])(target, spec, scope) + except Exception as e: + scope.maps[1][CHILD_ERRORS].append(scope) + scope.maps[0][CUR_ERROR] = e + if NO_PYFRAME in scope.maps[1]: + cur_scope = scope[UP] + while NO_PYFRAME in cur_scope.maps[0]: + cur_scope.maps[1][CHILD_ERRORS].append(cur_scope) + cur_scope.maps[0][CUR_ERROR] = e + cur_scope = cur_scope[UP] + raise + + +def AUTO(target, spec, scope): + if type(spec) is str: # shortcut to make deep-get use case faster + return _t_eval(target, Path.from_text(spec).path_t, scope) + if isinstance(spec, dict): + return _handle_dict(target, spec, scope) + elif isinstance(spec, list): + return _handle_list(target, spec, scope) + elif isinstance(spec, tuple): + return _handle_tuple(target, spec, scope) + elif isinstance(spec, basestring): + return Path.from_text(spec).glomit(target, scope) + elif callable(spec): + return spec(target) + + raise TypeError('expected spec to be dict, list, tuple, callable, string,' + ' or other Spec-like type, not: %r' % (spec,)) + + +_DEFAULT_SCOPE.update({ + glom: _glom, + TargetRegistry: TargetRegistry(register_default_types=True), +}) + + +def register(target_type, **kwargs): + """Register *target_type* so :meth:`~Glommer.glom()` will + know how to handle instances of that type as targets. + + Here's an example of adding basic iterabile support for Django's ORM: + + .. code-block:: python + + import glom + import django.db.models + + glom.register(django.db.models.Manager, iterate=lambda m: m.all()) + glom.register(django.db.models.QuerySet, iterate=lambda qs: qs.all()) + + + + Args: + target_type (type): A type expected to appear in a glom() + call target + get (callable): A function which takes a target object and + a name, acting as a default accessor. Defaults to + :func:`getattr`. + iterate (callable): A function which takes a target object + and returns an iterator. Defaults to :func:`iter` if + *target_type* appears to be iterable. + exact (bool): Whether or not to match instances of subtypes + of *target_type*. + + .. note:: + + The module-level :func:`register()` function affects the + module-level :func:`glom()` function's behavior. If this + global effect is undesirable for your application, or + you're implementing a library, consider instantiating a + :class:`Glommer` instance, and using the + :meth:`~Glommer.register()` and :meth:`Glommer.glom()` + methods instead. + + """ + _DEFAULT_SCOPE[TargetRegistry].register(target_type, **kwargs) + return + + +def register_op(op_name, **kwargs): + """For extension authors needing to add operations beyond the builtin + 'get', 'iterate', 'keys', 'assign', and 'delete' to the default scope. + See TargetRegistry for more details. + """ + _DEFAULT_SCOPE[TargetRegistry].register_op(op_name, **kwargs) + return + + +class Glommer: + """The :class:`Glommer` type mostly serves to encapsulate type + registration context so that advanced uses of glom don't need to + worry about stepping on each other. + + Glommer objects are lightweight and, once instantiated, provide + a :func:`glom()` method: + + >>> glommer = Glommer() + >>> glommer.glom({}, 'a.b.c', default='d') + 'd' + >>> Glommer().glom({'vals': list(range(3))}, ('vals', len)) + 3 + + Instances also provide :meth:`~Glommer.register()` method for + localized control over type handling. + + Args: + register_default_types (bool): Whether or not to enable the + handling behaviors of the default :func:`glom()`. These + default actions include dict access, list and iterable + iteration, and generic object attribute access. Defaults to + True. + + """ + def __init__(self, **kwargs): + register_default_types = kwargs.pop('register_default_types', True) + scope = kwargs.pop('scope', _DEFAULT_SCOPE) + + # this "freezes" the scope in at the time of construction + self.scope = ChainMap(dict(scope)) + self.scope[TargetRegistry] = TargetRegistry(register_default_types=register_default_types) + + def register(self, target_type, **kwargs): + """Register *target_type* so :meth:`~Glommer.glom()` will + know how to handle instances of that type as targets. + + Args: + target_type (type): A type expected to appear in a glom() + call target + get (callable): A function which takes a target object and + a name, acting as a default accessor. Defaults to + :func:`getattr`. + iterate (callable): A function which takes a target object + and returns an iterator. Defaults to :func:`iter` if + *target_type* appears to be iterable. + exact (bool): Whether or not to match instances of subtypes + of *target_type*. + + .. note:: + + The module-level :func:`register()` function affects the + module-level :func:`glom()` function's behavior. If this + global effect is undesirable for your application, or + you're implementing a library, consider instantiating a + :class:`Glommer` instance, and using the + :meth:`~Glommer.register()` and :meth:`Glommer.glom()` + methods instead. + + """ + exact = kwargs.pop('exact', False) + self.scope[TargetRegistry].register(target_type, exact=exact, **kwargs) + return + + def glom(self, target, spec, **kwargs): + return glom(target, spec, scope=self.scope, **kwargs) + + +class Fill: + """A specifier type which switches to glom into "fill-mode". For the + spec contained within the Fill, glom will only interpret explicit + specifier types (including T objects). Whereas the default mode + has special interpretations for each of these builtins, fill-mode + takes a lighter touch, making Fill great for "filling out" Python + literals, like tuples, dicts, sets, and lists. + + >>> target = {'data': [0, 2, 4]} + >>> spec = Fill((T['data'][2], T['data'][0])) + >>> glom(target, spec) + (4, 0) + + As you can see, glom's usual built-in tuple item chaining behavior + has switched into a simple tuple constructor. + + (Sidenote for Lisp fans: Fill is like glom's quasi-quoting.) + + """ + def __init__(self, spec=None): + self.spec = spec + + def glomit(self, target, scope): + scope[MODE] = FILL + return scope[glom](target, self.spec, scope) + + def fill(self, target): + return glom(target, self) + + def __repr__(self): + cn = self.__class__.__name__ + rpr = '' if self.spec is None else bbrepr(self.spec) + return f'{cn}({rpr})' + + +def FILL(target, spec, scope): + # TODO: register an operator or two for the following to allow + # extension. This operator can probably be shared with the + # upcoming traversal/remap feature. + recurse = lambda val: scope[glom](target, val, scope) + if type(spec) is dict: + return {recurse(key): recurse(val) for key, val in spec.items()} + if type(spec) in (list, tuple, set, frozenset): + result = [recurse(val) for val in spec] + if type(spec) is list: + return result + return type(spec)(result) + if callable(spec): + return spec(target) + return spec + +class _ArgValuator: + def __init__(self): + self.cache = {} + + def mode(self, target, spec, scope): + """ + similar to FILL, but without function calling; + useful for default, scope assignment, call/invoke, etc + """ + recur = lambda val: scope[glom](target, val, scope) + result = spec + if type(spec) in (list, dict): # can contain themselves + if id(spec) in self.cache: + return self.cache[id(spec)] + result = self.cache[id(spec)] = type(spec)() + if type(spec) is dict: + result.update({recur(key): recur(val) for key, val in spec.items()}) + else: + result.extend([recur(val) for val in spec]) + if type(spec) in (tuple, set, frozenset): # cannot contain themselves + result = type(spec)([recur(val) for val in spec]) + return result + + +def arg_val(target, arg, scope): + """ + evaluate an argument to find its value + (arg_val phonetically similar to "eval" -- evaluate as an arg) + """ + mode = scope[MIN_MODE] + scope[MIN_MODE] = _ArgValuator().mode + result = scope[glom](target, arg, scope) + scope[MIN_MODE] = mode + return result diff --git a/venv/lib/python3.10/site-packages/glom/grouping.py b/venv/lib/python3.10/site-packages/glom/grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..122bd0863df47161b8eb663797705f4c3e00a4ab --- /dev/null +++ b/venv/lib/python3.10/site-packages/glom/grouping.py @@ -0,0 +1,316 @@ +""" +Group mode +""" + +import random + +from boltons.typeutils import make_sentinel + +from .core import glom, MODE, SKIP, STOP, TargetRegistry, Path, T, BadSpec, _MISSING + + +ACC_TREE = make_sentinel('ACC_TREE') +ACC_TREE.__doc__ = """ +tree of accumulators for aggregation; +structure roughly corresponds to the result, +but is not 1:1; instead the main purpose is to ensure +data is kept until the Group() finishes executing +""" + +CUR_AGG = make_sentinel('CUR_AGG') +CUR_AGG.__doc__ = """ +the spec which is currently performing aggregation -- +useful for specs that want to work in either "aggregate" +mode, or "spec" mode depending on if they are in Group mode +or not; this sentinel in the Scope allows a spec to decide +if it is "closest" to the Group and so should behave +like an aggregate, or if it is further away and so should +have normal spec behavior. +""" + + +def target_iter(target, scope): + iterate = scope[TargetRegistry].get_handler('iterate', target, path=scope[Path]) + + try: + iterator = iterate(target) + except Exception as e: + raise TypeError('failed to iterate on instance of type %r at %r (got %r)' + % (target.__class__.__name__, Path(*scope[Path]), e)) + return iterator + + +class Group: + """supports nesting grouping operations -- + think of a glom-style recursive boltons.iterutils.bucketize + + the "branches" of a Group spec are dicts; + the leaves are lists, or an Aggregation object + an Aggregation object is any object that defines the + method agg(target, accumulator) + + For example, here we get a map of even and odd counts:: + + >>> glom(range(10), Group({T % 2: T})) + {0: 8, 1: 9} + + And here we create a `"bucketized" + `_ + map of even and odd numbers:: + + >>> glom(range(10), Group({T % 2: [T]})) + {0: [0, 2, 4, 6, 8], 1: [1, 3, 5, 7, 9]} + + target is the current target, accumulator is a dict + maintained by Group mode + + unlike Iter(), Group() converts an iterable target + into a single result; Iter() converts an iterable + target into an iterable result + + """ + def __init__(self, spec): + self.spec = spec + + def glomit(self, target, scope): + scope[MODE] = GROUP + scope[CUR_AGG] = None # reset aggregation tripwire for sub-specs + scope[ACC_TREE] = {} + + # handle the basecase where the spec stops immediately + # TODO: something smarter + if type(self.spec) in (dict, list): + ret = type(self.spec)() + else: + ret = None + + for t in target_iter(target, scope): + last, ret = ret, scope[glom](t, self.spec, scope) + if ret is STOP: + return last + return ret + + def __repr__(self): + cn = self.__class__.__name__ + return f'{cn}({self.spec!r})' + + +def GROUP(target, spec, scope): + """ + Group mode dispatcher; also sentinel for current mode = group + """ + recurse = lambda spec: scope[glom](target, spec, scope) + tree = scope[ACC_TREE] # current accumulator support structure + if callable(getattr(spec, "agg", None)): + return spec.agg(target, tree) + elif callable(spec): + return spec(target) + _spec_type = type(spec) + if _spec_type not in (dict, list): + raise BadSpec("Group mode expected dict, list, callable, or" + " aggregator, not: %r" % (spec,)) + _spec_id = id(spec) + try: + acc = tree[_spec_id] # current accumulator + except KeyError: + acc = tree[_spec_id] = _spec_type() + if _spec_type is dict: + done = True + for keyspec, valspec in spec.items(): + if tree.get(keyspec, None) is STOP: + continue + key = recurse(keyspec) + if key is SKIP: + done = False # SKIP means we still want more vals + continue + if key is STOP: + tree[keyspec] = STOP + continue + if key not in acc: + # TODO: guard against key == id(spec) + tree[key] = {} + scope[ACC_TREE] = tree[key] + result = recurse(valspec) + if result is STOP: + tree[keyspec] = STOP + continue + done = False # SKIP or returning a value means we still want more vals + if result is not SKIP: + acc[key] = result + if done: + return STOP + return acc + elif _spec_type is list: + for valspec in spec: + if type(valspec) is dict: + # doesn't make sense due to arity mismatch. did you mean [Auto({...})] ? + raise BadSpec('dicts within lists are not' + ' allowed while in Group mode: %r' % spec) + result = recurse(valspec) + if result is STOP: + return STOP + if result is not SKIP: + acc.append(result) + return acc + raise ValueError(f"{_spec_type} not a valid spec type for Group mode") # pragma: no cover + + +class First: + """ + holds onto the first value + + >>> glom([1, 2, 3], Group(First())) + 1 + """ + __slots__ = () + + def agg(self, target, tree): + if self not in tree: + tree[self] = STOP + return target + return STOP + + def __repr__(self): + return '%s()' % self.__class__.__name__ + + +class Avg: + """ + takes the numerical average of all values; + raises exception on non-numeric value + + >>> glom([1, 2, 3], Group(Avg())) + 2.0 + """ + __slots__ = () + + def agg(self, target, tree): + try: + avg_acc = tree[self] + except KeyError: + # format is [sum, count] + avg_acc = tree[self] = [0.0, 0] + avg_acc[0] += target + avg_acc[1] += 1 + return avg_acc[0] / avg_acc[1] + + def __repr__(self): + return '%s()' % self.__class__.__name__ + + +class Max: + """ + takes the maximum of all values; + raises exception on values that are not comparable + + >>> glom([1, 2, 3], Group(Max())) + 3 + """ + __slots__ = () + + def agg(self, target, tree): + if self not in tree or target > tree[self]: + tree[self] = target + return tree[self] + + def __repr__(self): + return '%s()' % self.__class__.__name__ + + +class Min: + """ + takes the minimum of all values; + raises exception on values that are not comparable + + >>> glom([1, 2, 3], Group(Min())) + 1 + """ + __slots__ = () + + def agg(self, target, tree): + if self not in tree or target < tree[self]: + tree[self] = target + return tree[self] + + def __repr__(self): + return '%s()' % self.__class__.__name__ + + +class Sample: + """takes a random sample of the values + + >>> glom([1, 2, 3], Group(Sample(2))) # doctest: +SKIP + [1, 3] + >>> glom(range(5000), Group(Sample(2))) # doctest: +SKIP + [272, 2901] + + The advantage of this over :func:`random.sample` is that this can + take an arbitrarily-sized, potentially-very-long streaming input + and returns a fixed-size output. Note that this does not stream + results out, so your streaming input must have finite length. + """ + __slots__ = ('size',) + + def __init__(self, size): + self.size = size + + def agg(self, target, tree): + # simple reservoir sampling scheme + # https://en.wikipedia.org/wiki/Reservoir_sampling#Simple_algorithm + if self not in tree: + tree[self] = [0, []] + num_seen, sample = tree[self] + if len(sample) < self.size: + sample.append(target) + else: + pos = random.randint(0, num_seen) + if pos < self.size: + sample[pos] = target + tree[self][0] += 1 + return sample + + def __repr__(self): + return f'{self.__class__.__name__}({self.size!r})' + + + +class Limit: + """ + Limits the number of values passed to sub-accumulator + + >>> glom([1, 2, 3], Group(Limit(2))) + [1, 2] + + To override the default untransformed list output, set the subspec kwarg: + + >>> glom(range(10), Group(Limit(3, subspec={(lambda x: x % 2): [T]}))) + {0: [0, 2], 1: [1]} + + You can even nest Limits in other ``Group`` specs: + + >>> glom(range(10), Group(Limit(5, {(lambda x: x % 2): Limit(2)}))) + {0: [0, 2], 1: [1, 3]} + + """ + __slots__ = ('n', 'subspec') + + def __init__(self, n, subspec=_MISSING): + if subspec is _MISSING: + subspec = [T] + self.n = n + self.subspec = subspec + + def glomit(self, target, scope): + if scope[MODE] is not GROUP: + raise BadSpec("Limit() only valid in Group mode") + tree = scope[ACC_TREE] # current accumulator support structure + if self not in tree: + tree[self] = [0, {}] + scope[ACC_TREE] = tree[self][1] + tree[self][0] += 1 + if tree[self][0] > self.n: + return STOP + return scope[glom](target, self.subspec, scope) + + def __repr__(self): + return f'{self.__class__.__name__}({self.n!r}, {self.subspec!r})' diff --git a/venv/lib/python3.10/site-packages/glom/matching.py b/venv/lib/python3.10/site-packages/glom/matching.py new file mode 100644 index 0000000000000000000000000000000000000000..798ac402c07ccc59280e61e002a4f28069e0748a --- /dev/null +++ b/venv/lib/python3.10/site-packages/glom/matching.py @@ -0,0 +1,1054 @@ +""" +.. versionadded:: 20.7.0 + +Sometimes you want to confirm that your target data matches your +code's assumptions. With glom, you don't need a separate validation +step, you can do these checks inline with your glom spec, using +:class:`~glom.Match` and friends. +""" + +import re +import sys +from pprint import pprint + +from boltons.iterutils import is_iterable +from boltons.typeutils import make_sentinel + +from .core import GlomError, glom, T, MODE, bbrepr, bbformat, format_invocation, Path, chain_child, Val, arg_val + + +_MISSING = make_sentinel('_MISSING') + + +# NOTE: it is important that MatchErrors be cheap to construct, +# because negative matches are part of normal control flow +# (e.g. often it is idiomatic to cascade from one possible match +# to the next and take the first one that works) +class MatchError(GlomError): + """ + Raised when a :class:`Match` or :data:`M` check fails. + + >>> glom({123: 'a'}, Match({'id': int})) + Traceback (most recent call last): + ... + MatchError: key 123 didn't match any of ['id'] + + """ + def __init__(self, fmt, *args): + super().__init__(fmt, *args) + + def get_message(self): + fmt, args = self.args[0], self.args[1:] + return bbformat(fmt, *args) + + +class TypeMatchError(MatchError, TypeError): + """:exc:`MatchError` subtype raised when a + :class:`Match` fails a type check. + + >>> glom({'id': 'a'}, Match({'id': int})) + Traceback (most recent call last): + ... + TypeMatchError: error raised while processing. + Target-spec trace, with error detail (most recent last): + - Target: {'id': 'a'} + - Spec: Match({'id': }) + - Spec: {'id': } + - Target: 'a' + - Spec: int + TypeMatchError: expected type int, not str + """ + + def __init__(self, actual, expected): + super().__init__( + "expected type {0.__name__}, not {1.__name__}", expected, actual) + + def __copy__(self): + # __init__ args = (actual, expected) + # self.args = (fmt_str, expected, actual) + return TypeMatchError(self.args[2], self.args[1]) + + +class Match: + """glom's ``Match`` specifier type enables a new mode of glom usage: + pattern matching. In particular, this mode has been designed for + nested data validation. + + Pattern specs are evaluated as follows: + + 1. Spec instances are always evaluated first + 2. Types match instances of that type + 3. Instances of :class:`dict`, :class:`list`, :class:`tuple`, + :class:`set`, and :class:`frozenset` are matched recursively + 4. Any other values are compared for equality to the target with + ``==`` + + By itself, this allows to assert that structures match certain + patterns, and may be especially familiar to users of the `schema`_ + library. + + For example, let's load some data:: + + >>> target = [ + ... {'id': 1, 'email': 'alice@example.com'}, + ... {'id': 2, 'email': 'bob@example.com'}] + + A :class:`Match` pattern can be used to ensure this data is in its expected form: + + >>> spec = Match([{'id': int, 'email': str}]) + + This ``spec`` succinctly describes our data structure's pattern + Specifically, a :class:`list` of :class:`dict` objects, each of + which has exactly two keys, ``'id'`` and ``'email'``, whose values are + an :class:`int` and :class:`str`, respectively. Now, + :func:`~glom.glom` will ensure our ``target`` matches our pattern + ``spec``: + + >>> result = glom(target, spec) + >>> assert result == \\ + ... [{'id': 1, 'email': 'alice@example.com'}, {'id': 2, 'email': 'bob@example.com'}] + + With a more complex :class:`Match` spec, we can be more precise: + + >>> spec = Match([{'id': And(M > 0, int), 'email': Regex('[^@]+@[^@]+')}]) + + :class:`~glom.And` allows multiple conditions to be applied. + :class:`~glom.Regex` evaluates the regular expression against the + target value under the ``'email'`` key. In this case, we take a + simple approach: an email has exactly one ``@``, with at least one + character before and after. + + Finally, :attr:`~glom.M` is our stand-in for the current target + we're matching against, allowing us to perform in-line comparisons + using Python's native greater-than operator (as well as + others). We apply our :class:`Match` pattern as before:: + + >>> assert glom(target, spec) == \\ + ... [{'id': 1, 'email': 'alice@example.com'}, {'id': 2, 'email': 'bob@example.com'}] + + And as usual, upon a successful match, we get the matched result. + + .. note:: + + For Python 3.6+ where dictionaries are ordered, keys in the target + are matched against keys in the spec in their insertion order. + + .. _schema: https://github.com/keleshev/schema + + Args: + spec: The glomspec representing the pattern to match data against. + default: The default value to be returned if a match fails. If not + set, a match failure will raise a :class:`MatchError`. + + """ + def __init__(self, spec, default=_MISSING): + self.spec = spec + self.default = default + + def glomit(self, target, scope): + scope[MODE] = _glom_match + try: + ret = scope[glom](target, self.spec, scope) + except GlomError: + if self.default is _MISSING: + raise + ret = arg_val(target, self.default, scope) + return ret + + def verify(self, target): + """A convenience function a :class:`Match` instance which returns the + matched value when *target* matches, or raises a + :exc:`MatchError` when it does not. + + Args: + target: Target value or data structure to match against. + + Raises: + glom.MatchError + + """ + return glom(target, self) + + def matches(self, target): + """A convenience method on a :class:`Match` instance, returns + ``True`` if the *target* matches, ``False`` if not. + + >>> Match(int).matches(-1.0) + False + + Args: + target: Target value or data structure to match against. + """ + try: + glom(target, self) + except GlomError: + return False + return True + + def __repr__(self): + return f'{self.__class__.__name__}({bbrepr(self.spec)})' + + +_RE_FULLMATCH = getattr(re, "fullmatch", None) +_RE_VALID_FUNCS = {_RE_FULLMATCH, None, re.search, re.match} +_RE_FUNC_ERROR = ValueError("'func' must be one of %s" % (", ".join( + sorted(e and e.__name__ or "None" for e in _RE_VALID_FUNCS)))) + +_RE_TYPES = () +try: re.match("", "") +except Exception: pass # pragma: no cover +else: _RE_TYPES += (str,) +try: re.match(b"", b"") +except Exception: pass # pragma: no cover +else: _RE_TYPES += (bytes,) + + +class Regex: + """ + checks that target is a string which matches the passed regex pattern + + raises MatchError if there isn't a match; returns Target if match + + variables captures in regex are added to the scope so they can + be used by downstream processes + """ + __slots__ = ('flags', 'func', 'match_func', 'pattern') + + def __init__(self, pattern, flags=0, func=None): + if func not in _RE_VALID_FUNCS: + raise _RE_FUNC_ERROR + regex = re.compile(pattern, flags) + if func is re.match: + match_func = regex.match + elif func is re.search: + match_func = regex.search + else: + if _RE_FULLMATCH: + match_func = regex.fullmatch + else: + regex = re.compile(fr"(?:{pattern})\Z", flags) + match_func = regex.match + self.flags, self.func = flags, func + self.match_func, self.pattern = match_func, pattern + + def glomit(self, target, scope): + if type(target) not in _RE_TYPES: + raise MatchError( + "{0!r} not valid as a Regex target -- expected {1!r}", type(target), _RE_TYPES) + match = self.match_func(target) + if not match: + raise MatchError("target did not match pattern {0!r}", self.pattern) + scope.update(match.groupdict()) + return target + + def __repr__(self): + args = '(' + bbrepr(self.pattern) + if self.flags: + args += ', flags=' + bbrepr(self.flags) + if self.func is not None: + args += ', func=' + self.func.__name__ + args += ')' + return self.__class__.__name__ + args + + +#TODO: combine this with other functionality elsewhere? +def _bool_child_repr(child): + if child is M: + return repr(child) + elif isinstance(child, _MExpr): + return "(" + bbrepr(child) + ")" + return bbrepr(child) + + +class _Bool: + def __init__(self, *children, **kw): + self.children = children + if not children: + raise ValueError("need at least one operand for {}".format( + self.__class__.__name__)) + self.default = kw.pop('default', _MISSING) + if kw: + raise TypeError('got unexpected kwargs: %r' % list(kw.keys())) + + def __and__(self, other): + return And(self, other) + + def __or__(self, other): + return Or(self, other) + + def __invert__(self): + return Not(self) + + def glomit(self, target, scope): + try: + return self._glomit(target, scope) + except GlomError: + if self.default is not _MISSING: + return arg_val(target, self.default, scope) + raise + + def _m_repr(self): + """should this Or() repr as M |?""" + # only used by And() and Or(), not Not(), so len(children) >= 1 + if isinstance(self.children[0], (_MType, _MExpr)): + return True + if type(self.children[0]) in (And, Or, Not): + return self.children[0]._m_repr() + return False + + def __repr__(self): + child_reprs = [_bool_child_repr(c) for c in self.children] + if self._m_repr() and self.default is _MISSING: + return f" {self.OP} ".join(child_reprs) + if self.default is not _MISSING: + child_reprs.append("default=" + repr(self.default)) + return self.__class__.__name__ + "(" + ", ".join(child_reprs) + ")" + + +class And(_Bool): + """ + Applies child specs one after the other to the target; if none of the + specs raises `GlomError`, returns the last result. + """ + OP = "&" + __slots__ = ('children',) + + def _glomit(self, target, scope): + # all children must match without exception + result = target # so that And() == True, similar to all([]) == True + for child in self.children: + result = scope[glom](target, child, scope) + return result + + def __and__(self, other): + # reduce number of layers of spec + return And(*(self.children + (other,))) + + +class Or(_Bool): + """ + Tries to apply the first child spec to the target, and return the result. + If `GlomError` is raised, try the next child spec until there are no + all child specs have been tried, then raise `MatchError`. + """ + OP = "|" + __slots__ = ('children',) + + def _glomit(self, target, scope): + for child in self.children[:-1]: + try: # one child must match without exception + return scope[glom](target, child, scope) + except GlomError: + pass + return scope[glom](target, self.children[-1], scope) + + def __or__(self, other): + # reduce number of layers of spec + return Or(*(self.children + (other,))) + + +class Not(_Bool): + """ + Inverts the *child*. Child spec will be expected to raise + :exc:`GlomError` (or subtype), in which case the target will be returned. + + If the child spec does not raise :exc:`GlomError`, :exc:`MatchError` + will be raised. + """ + __slots__ = ('child',) + + def __init__(self, child): + self.child = child + + def glomit(self, target, scope): + try: # one child must match without exception + scope[glom](target, self.child, scope) + except GlomError: + return target + else: + raise GlomError("child shouldn't have passed", self.child) + + def _m_repr(self): + if isinstance(self.child, (_MType, _MExpr)): + return True + if type(self.child) not in (And, Or, Not): + return False + return self.child._m_repr() + + def __repr__(self): + if self.child is M: + return '~M' + if self._m_repr(): # is in M repr + return "~(" + bbrepr(self.child) + ")" + return "Not(" + bbrepr(self.child) + ")" + + +_M_OP_MAP = {'=': '==', '!': '!=', 'g': '>=', 'l': '<='} + + +class _MSubspec: + """used by MType.__call__ to wrap a sub-spec for comparison""" + __slots__ = ('spec') + + def __init__(self, spec): + self.spec = spec + + def __eq__(self, other): + return _MExpr(self, '=', other) + + def __ne__(self, other): + return _MExpr(self, '!', other) + + def __gt__(self, other): + return _MExpr(self, '>', other) + + def __lt__(self, other): + return _MExpr(self, '<', other) + + def __ge__(self, other): + return _MExpr(self, 'g', other) + + def __le__(self, other): + return _MExpr(self, 'l', other) + + def __repr__(self): + return f'M({bbrepr(self.spec)})' + + def glomit(self, target, scope): + match = scope[glom](target, self.spec, scope) + if match: + return target + raise MatchError('expected truthy value from {0!r}, got {1!r}', self.spec, match) + + +class _MExpr: + __slots__ = ('lhs', 'op', 'rhs') + + def __init__(self, lhs, op, rhs): + self.lhs, self.op, self.rhs = lhs, op, rhs + + def __and__(self, other): + return And(self, other) + + __rand__ = __and__ + + def __or__(self, other): + return Or(self, other) + + def __invert__(self): + return Not(self) + + def glomit(self, target, scope): + lhs, op, rhs = self.lhs, self.op, self.rhs + if lhs is M: + lhs = target + if rhs is M: + rhs = target + if type(lhs) is _MSubspec: + lhs = scope[glom](target, lhs.spec, scope) + if type(rhs) is _MSubspec: + rhs = scope[glom](target, rhs.spec, scope) + matched = ( + (op == '=' and lhs == rhs) or + (op == '!' and lhs != rhs) or + (op == '>' and lhs > rhs) or + (op == '<' and lhs < rhs) or + (op == 'g' and lhs >= rhs) or + (op == 'l' and lhs <= rhs) + ) + if matched: + return target + raise MatchError("{0!r} {1} {2!r}", lhs, _M_OP_MAP.get(op, op), rhs) + + def __repr__(self): + op = _M_OP_MAP.get(self.op, self.op) + return f"{self.lhs!r} {op} {self.rhs!r}" + + +class _MType: + """:attr:`~glom.M` is similar to :attr:`~glom.T`, a stand-in for the + current target, but where :attr:`~glom.T` allows for attribute and + key access and method calls, :attr:`~glom.M` allows for comparison + operators. + + If a comparison succeeds, the target is returned unchanged. + If a comparison fails, :class:`~glom.MatchError` is thrown. + + Some examples: + + >>> glom(1, M > 0) + 1 + >>> glom(0, M == 0) + 0 + >>> glom('a', M != 'b') == 'a' + True + + :attr:`~glom.M` by itself evaluates the current target for truthiness. + For example, `M | Val(None)` is a simple idiom for normalizing all falsey values to None: + + >>> from glom import Val + >>> glom([0, False, "", None], [M | Val(None)]) + [None, None, None, None] + + For convenience, ``&`` and ``|`` operators are overloaded to + construct :attr:`~glom.And` and :attr:`~glom.Or` instances. + + >>> glom(1.0, (M > 0) & float) + 1.0 + + .. note:: + + Python's operator overloading may make for concise code, + but it has its limits. + + Because bitwise operators (``&`` and ``|``) have higher precedence + than comparison operators (``>``, ``<``, etc.), expressions must + be parenthesized. + + >>> M > 0 & float + Traceback (most recent call last): + ... + TypeError: unsupported operand type(s) for &: 'int' and 'type' + + Similarly, because of special handling around ternary + comparisons (``1 < M < 5``) are implemented via + short-circuiting evaluation, they also cannot be captured by + :data:`M`. + + """ + __slots__ = () + + def __call__(self, spec): + """wrap a sub-spec in order to apply comparison operators to the result""" + if not isinstance(spec, type(T)): + # TODO: open this up for other specs so we can do other + # checks, like function calls + raise TypeError("M() only accepts T-style specs, not %s" % type(spec).__name__) + return _MSubspec(spec) + + def __eq__(self, other): + return _MExpr(self, '=', other) + + def __ne__(self, other): + return _MExpr(self, '!', other) + + def __gt__(self, other): + return _MExpr(self, '>', other) + + def __lt__(self, other): + return _MExpr(self, '<', other) + + def __ge__(self, other): + return _MExpr(self, 'g', other) + + def __le__(self, other): + return _MExpr(self, 'l', other) + + def __and__(self, other): + return And(self, other) + + __rand__ = __and__ + + def __or__(self, other): + return Or(self, other) + + def __invert__(self): + return Not(self) + + def __repr__(self): + return "M" + + def glomit(self, target, spec): + if target: + return target + raise MatchError("{0!r} not truthy", target) + + +M = _MType() + + + +class Optional: + """Used as a :class:`dict` key in a :class:`~glom.Match()` spec, + marks that a value match key which would otherwise be required is + optional and should not raise :exc:`~glom.MatchError` even if no + keys match. + + For example:: + + >>> spec = Match({Optional("name"): str}) + >>> glom({"name": "alice"}, spec) + {'name': 'alice'} + >>> glom({}, spec) + {} + >>> spec = Match({Optional("name", default=""): str}) + >>> glom({}, spec) + {'name': ''} + + """ + __slots__ = ('key', 'default') + + def __init__(self, key, default=_MISSING): + if type(key) in (Required, Optional): + raise TypeError("double wrapping of Optional") + hash(key) # ensure is a valid key + if _precedence(key) != 0: + raise ValueError(f"Optional() keys must be == match constants, not {key!r}") + self.key, self.default = key, default + + def glomit(self, target, scope): + if target != self.key: + raise MatchError("target {0} != spec {1}", target, self.key) + return target + + def __repr__(self): + return f'{self.__class__.__name__}({bbrepr(self.key)})' + + +class Required: + """Used as a :class:`dict` key in :class:`~glom.Match()` mode, marks + that a key which might otherwise not be required should raise + :exc:`~glom.MatchError` if the key in the target does not match. + + For example:: + + >>> spec = Match({object: object}) + + This spec will match any dict, because :class:`object` is the base + type of every object:: + + >>> glom({}, spec) + {} + + ``{}`` will also match because match mode does not require at + least one match by default. If we want to require that a key + matches, we can use :class:`~glom.Required`:: + + >>> spec = Match({Required(object): object}) + >>> glom({}, spec) + Traceback (most recent call last): + ... + MatchError: error raised while processing. + Target-spec trace, with error detail (most recent last): + - Target: {} + - Spec: Match({Required(object): }) + - Spec: {Required(object): } + MatchError: target missing expected keys Required(object) + + Now our spec requires at least one key of any type. You can refine + the spec by putting more specific subpatterns inside of + :class:`~glom.Required`. + + """ + __slots__ = ('key',) + + def __init__(self, key): + if type(key) in (Required, Optional): + raise TypeError("double wrapping of Required") + hash(key) # ensure is a valid key + if _precedence(key) == 0: + raise ValueError("== match constants are already required: " + bbrepr(key)) + self.key = key + + def __repr__(self): + return f'{self.__class__.__name__}({bbrepr(self.key)})' + + +def _precedence(match): + """ + in a dict spec, target-keys may match many + spec-keys (e.g. 1 will match int, M > 0, and 1); + therefore we need a precedence for which order to try + keys in; higher = later + """ + if type(match) in (Required, Optional): + match = match.key + if type(match) in (tuple, frozenset): + if not match: + return 0 + return max([_precedence(item) for item in match]) + if isinstance(match, type): + return 2 + if hasattr(match, "glomit"): + return 1 + return 0 # == match + + +def _handle_dict(target, spec, scope): + if not isinstance(target, dict): + raise TypeMatchError(type(target), dict) + spec_keys = spec # cheating a little bit here, list-vs-dict, but saves an object copy sometimes + + required = { + key for key in spec_keys + if _precedence(key) == 0 and type(key) is not Optional + or type(key) is Required} + defaults = { # pre-load result with defaults + key.key: key.default for key in spec_keys + if type(key) is Optional and key.default is not _MISSING} + result = {} + for key, val in target.items(): + for maybe_spec_key in spec_keys: + # handle Required as a special case here rather than letting it be a stand-alone spec + if type(maybe_spec_key) is Required: + spec_key = maybe_spec_key.key + else: + spec_key = maybe_spec_key + try: + key = scope[glom](key, spec_key, scope) + except GlomError: + pass + else: + result[key] = scope[glom](val, spec[maybe_spec_key], chain_child(scope)) + required.discard(maybe_spec_key) + break + else: + raise MatchError("key {0!r} didn't match any of {1!r}", key, spec_keys) + for key in set(defaults) - set(result): + result[key] = arg_val(target, defaults[key], scope) + if required: + raise MatchError("target missing expected keys: {0}", ', '.join([bbrepr(r) for r in required])) + return result + + +def _glom_match(target, spec, scope): + if isinstance(spec, type): + if not isinstance(target, spec): + raise TypeMatchError(type(target), spec) + elif isinstance(spec, dict): + return _handle_dict(target, spec, scope) + elif isinstance(spec, (list, set, frozenset)): + if not isinstance(target, type(spec)): + raise TypeMatchError(type(target), type(spec)) + result = [] + for item in target: + for child in spec: + try: + result.append(scope[glom](item, child, scope)) + break + except GlomError as e: + last_error = e + else: # did not break, something went wrong + if target and not spec: + raise MatchError( + "{0!r} does not match empty {1}", target, type(spec).__name__) + # NOTE: unless error happens above, break will skip else branch + # so last_error will have been assigned + raise last_error + if type(spec) is not list: + return type(spec)(result) + return result + elif isinstance(spec, tuple): + if not isinstance(target, tuple): + raise TypeMatchError(type(target), tuple) + if len(target) != len(spec): + raise MatchError("{0!r} does not match {1!r}", target, spec) + result = [] + for sub_target, sub_spec in zip(target, spec): + result.append(scope[glom](sub_target, sub_spec, scope)) + return tuple(result) + elif callable(spec): + try: + if spec(target): + return target + except Exception as e: + raise MatchError( + "{0}({1!r}) did not validate (got exception {2!r})", spec.__name__, target, e) + raise MatchError( + "{0}({1!r}) did not validate (non truthy return)", spec.__name__, target) + elif target != spec: + raise MatchError("{0!r} does not match {1!r}", target, spec) + return target + + +class Switch: + r"""The :class:`Switch` specifier type routes data processing based on + matching keys, much like the classic switch statement. + + Here is a spec which differentiates between lowercase English + vowel and consonant characters: + + >>> switch_spec = Match(Switch([(Or('a', 'e', 'i', 'o', 'u'), Val('vowel')), + ... (And(str, M, M(T[2:]) == ''), Val('consonant'))])) + + The constructor accepts a :class:`dict` of ``{keyspec: valspec}`` + or a list of items, ``[(keyspec, valspec)]``. Keys are tried + against the current target in order. If a keyspec raises + :class:`GlomError`, the next keyspec is tried. Once a keyspec + succeeds, the corresponding valspec is evaluated and returned. + Let's try it out: + + >>> glom('a', switch_spec) + 'vowel' + >>> glom('z', switch_spec) + 'consonant' + + If no keyspec succeeds, a :class:`MatchError` is raised. Our spec + only works on characters (strings of length 1). Let's try a + non-character, the integer ``3``: + + >>> glom(3, switch_spec) + Traceback (most recent call last): + ... + glom.matching.MatchError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: 3 + - Spec: Match(Switch([(Or('a', 'e', 'i', 'o', 'u'), Val('vowel')), (And(str, M, (M(T[2:]) == '')), Val('... + + Spec: Switch([(Or('a', 'e', 'i', 'o', 'u'), Val('vowel')), (And(str, M, (M(T[2:]) == '')), Val('conson... + |\ Spec: Or('a', 'e', 'i', 'o', 'u') + ||\ Spec: 'a' + ||X glom.matching.MatchError: 3 does not match 'a' + ||\ Spec: 'e' + ||X glom.matching.MatchError: 3 does not match 'e' + ||\ Spec: 'i' + ||X glom.matching.MatchError: 3 does not match 'i' + ||\ Spec: 'o' + ||X glom.matching.MatchError: 3 does not match 'o' + ||\ Spec: 'u' + ||X glom.matching.MatchError: 3 does not match 'u' + |X glom.matching.MatchError: 3 does not match 'u' + |\ Spec: And(str, M, (M(T[2:]) == '')) + || Spec: str + |X glom.matching.TypeMatchError: expected type str, not int + glom.matching.MatchError: no matches for target in Switch + + + .. note:: + + :class:`~glom.Switch` is one of several *branching* specifier + types in glom. See ":ref:`branched-exceptions`" for details on + interpreting its exception messages. + + A *default* value can be passed to the spec to be returned instead + of raising a :class:`MatchError`. + + .. note:: + + Switch implements control flow similar to the switch statement + proposed in `PEP622 `_. + + """ + def __init__(self, cases, default=_MISSING): + if type(cases) is dict: + cases = list(cases.items()) + if type(cases) is not list: + raise TypeError( + "expected cases argument to be of format {{keyspec: valspec}}" + " or [(keyspec, valspec)] not: {}".format(type(cases))) + self.cases = cases + # glom.match(cases, Or([(object, object)], dict)) + # start dogfooding ^ + self.default = default + if not cases: + raise ValueError('expected at least one case in %s, got: %r' + % (self.__class__.__name__, self.cases)) + return + + + def glomit(self, target, scope): + for keyspec, valspec in self.cases: + try: + scope[glom](target, keyspec, scope) + except GlomError as ge: + continue + return scope[glom](target, valspec, chain_child(scope)) + if self.default is not _MISSING: + return arg_val(target, self.default, scope) + raise MatchError("no matches for target in %s" % self.__class__.__name__) + + def __repr__(self): + return f'{self.__class__.__name__}({bbrepr(self.cases)})' + + +RAISE = make_sentinel('RAISE') # flag object for "raise on check failure" + + +class Check: + """Check objects are used to make assertions about the target data, + and either pass through the data or raise exceptions if there is a + problem. + + If any check condition fails, a :class:`~glom.CheckError` is raised. + + Args: + + spec: a sub-spec to extract the data to which other assertions will + be checked (defaults to applying checks to the target itself) + type: a type or sequence of types to be checked for exact match + equal_to: a value to be checked for equality match ("==") + validate: a callable or list of callables, each representing a + check condition. If one or more return False or raise an + exception, the Check will fail. + instance_of: a type or sequence of types to be checked with isinstance() + one_of: an iterable of values, any of which can match the target ("in") + default: an optional default value to replace the value when the check fails + (if default is not specified, GlomCheckError will be raised) + + Aside from *spec*, all arguments are keyword arguments. Each + argument, except for *default*, represent a check + condition. Multiple checks can be passed, and if all check + conditions are left unset, Check defaults to performing a basic + truthy check on the value. + + """ + # TODO: the next level of Check would be to play with the Scope to + # allow checking to continue across the same level of + # dictionary. Basically, collect as many errors as possible before + # raising the unified CheckError. + def __init__(self, spec=T, **kwargs): + self.spec = spec + self._orig_kwargs = dict(kwargs) + self.default = kwargs.pop('default', RAISE) + + def _get_arg_val(name, cond, func, val, can_be_empty=True): + if val is _MISSING: + return () + if not is_iterable(val): + val = (val,) + elif not val and not can_be_empty: + raise ValueError('expected %r argument to contain at least one value,' + ' not: %r' % (name, val)) + for v in val: + if not func(v): + raise ValueError('expected %r argument to be %s, not: %r' + % (name, cond, v)) + return val + + # if there are other common validation functions, maybe a + # small set of special strings would work as valid arguments + # to validate, too. + def truthy(val): + return bool(val) + + validate = kwargs.pop('validate', _MISSING if kwargs else truthy) + type_arg = kwargs.pop('type', _MISSING) + instance_of = kwargs.pop('instance_of', _MISSING) + equal_to = kwargs.pop('equal_to', _MISSING) + one_of = kwargs.pop('one_of', _MISSING) + if kwargs: + raise TypeError('unexpected keyword arguments: %r' % kwargs.keys()) + + self.validators = _get_arg_val('validate', 'callable', callable, validate) + self.instance_of = _get_arg_val('instance_of', 'a type', + lambda x: isinstance(x, type), instance_of, False) + self.types = _get_arg_val('type', 'a type', + lambda x: isinstance(x, type), type_arg, False) + + if equal_to is not _MISSING: + self.vals = (equal_to,) + if one_of is not _MISSING: + raise TypeError('expected "one_of" argument to be unset when' + ' "equal_to" argument is passed') + elif one_of is not _MISSING: + if not is_iterable(one_of): + raise ValueError('expected "one_of" argument to be iterable' + ' , not: %r' % one_of) + if not one_of: + raise ValueError('expected "one_of" to contain at least' + ' one value, not: %r' % (one_of,)) + self.vals = one_of + else: + self.vals = () + return + + class _ValidationError(Exception): + "for internal use inside of Check only" + pass + + def glomit(self, target, scope): + ret = target + errs = [] + if self.spec is not T: + target = scope[glom](target, self.spec, scope) + if self.types and type(target) not in self.types: + if self.default is not RAISE: + return arg_val(target, self.default, scope) + errs.append('expected type to be %r, found type %r' % + (self.types[0].__name__ if len(self.types) == 1 + else tuple([t.__name__ for t in self.types]), + type(target).__name__)) + + if self.vals and target not in self.vals: + if self.default is not RAISE: + return arg_val(target, self.default, scope) + if len(self.vals) == 1: + errs.append(f"expected {self.vals[0]}, found {target}") + else: + errs.append(f'expected one of {self.vals}, found {target}') + + if self.validators: + for i, validator in enumerate(self.validators): + try: + res = validator(target) + if res is False: + raise self._ValidationError + except Exception as e: + msg = ('expected %r check to validate target' + % getattr(validator, '__name__', None) or ('#%s' % i)) + if type(e) is self._ValidationError: + if self.default is not RAISE: + return self.default + else: + msg += ' (got exception: %r)' % e + errs.append(msg) + + if self.instance_of and not isinstance(target, self.instance_of): + # TODO: can these early returns be done without so much copy-paste? + # (early return to avoid potentially expensive or even error-causeing + # string formats) + if self.default is not RAISE: + return arg_val(target, self.default, scope) + errs.append('expected instance of %r, found instance of %r' % + (self.instance_of[0].__name__ if len(self.instance_of) == 1 + else tuple([t.__name__ for t in self.instance_of]), + type(target).__name__)) + + if errs: + raise CheckError(errs, self, scope[Path]) + return ret + + def __repr__(self): + cn = self.__class__.__name__ + posargs = (self.spec,) if self.spec is not T else () + return format_invocation(cn, posargs, self._orig_kwargs, repr=bbrepr) + + +class CheckError(GlomError): + """This :exc:`GlomError` subtype is raised when target data fails to + pass a :class:`Check`'s specified validation. + + An uncaught ``CheckError`` looks like this:: + + >>> target = {'a': {'b': 'c'}} + >>> glom(target, {'b': ('a.b', Check(type=int))}) + Traceback (most recent call last): + ... + CheckError: target at path ['a.b'] failed check, got error: "expected type to be 'int', found type 'str'" + + If the ``Check`` contains more than one condition, there may be + more than one error message. The string rendition of the + ``CheckError`` will include all messages. + + You can also catch the ``CheckError`` and programmatically access + messages through the ``msgs`` attribute on the ``CheckError`` + instance. + + """ + def __init__(self, msgs, check, path): + self.msgs = msgs + self.check_obj = check + self.path = path + + def get_message(self): + msg = 'target at path %s failed check,' % self.path + if self.check_obj.spec is not T: + msg += f' subtarget at {self.check_obj.spec!r}' + if len(self.msgs) == 1: + msg += f' got error: {self.msgs[0]!r}' + else: + msg += f' got {len(self.msgs)} errors: {self.msgs!r}' + return msg + + def __repr__(self): + cn = self.__class__.__name__ + return f'{cn}({self.msgs!r}, {self.check_obj!r}, {self.path!r})' diff --git a/venv/lib/python3.10/site-packages/glom/mutation.py b/venv/lib/python3.10/site-packages/glom/mutation.py new file mode 100644 index 0000000000000000000000000000000000000000..c3fc322efb41f3f1a653d66eb364cd6690c7e6a5 --- /dev/null +++ b/venv/lib/python3.10/site-packages/glom/mutation.py @@ -0,0 +1,365 @@ +"""By default, glom aims to safely return a transformed copy of your +data. But sometimes you really need to transform an existing object. + +When you already have a large or complex bit of nested data that you +are sure you want to modify in-place, glom has you covered, with the +:func:`~glom.assign` function, and the :func:`~glom.Assign` specifier +type. + +""" +import operator +from pprint import pprint + +from .core import Path, T, S, Spec, glom, UnregisteredTarget, GlomError, PathAccessError, UP +from .core import TType, register_op, TargetRegistry, bbrepr, PathAssignError, arg_val, _assign_op + + +try: + basestring +except NameError: + basestring = str + + +if getattr(__builtins__, '__dict__', None) is not None: + # pypy's __builtins__ is a module, as is CPython's REPL, but at + # normal execution time it's a dict? + __builtins__ = __builtins__.__dict__ + + +class PathDeleteError(PathAssignError): + """This :exc:`GlomError` subtype is raised when an assignment fails, + stemming from an :func:`~glom.delete` call or other + :class:`~glom.Delete` usage. + + One example would be deleting an out-of-range position in a list:: + + >>> delete(["short", "list"], Path(5)) + Traceback (most recent call last): + ... + PathDeleteError: could not delete 5 on object at Path(), got error: IndexError(... + + Other assignment failures could be due to deleting a read-only + ``@property`` or exception being raised inside a ``__delattr__()``. + + """ + def get_message(self): + return ('could not delete %r on object at %r, got error: %r' + % (self.dest_name, self.path, self.exc)) + + +def _apply_for_each(func, path, val): + layers = path.path_t.__stars__() + if layers: + for i in range(layers - 1): + val = sum(val, []) # flatten out the extra layers + for inner in val: + func(inner) + else: + func(val) + + +class Assign: + """*New in glom 18.3.0* + + The ``Assign`` specifier type enables glom to modify the target, + performing a "deep-set" to mirror glom's original deep-get use + case. + + ``Assign`` can be used to perform spot modifications of large data + structures when making a copy is not desired:: + + # deep assignment into a nested dictionary + >>> target = {'a': {}} + >>> spec = Assign('a.b', 'value') + >>> _ = glom(target, spec) + >>> pprint(target) + {'a': {'b': 'value'}} + + The value to be assigned can also be a :class:`~glom.Spec`, which + is useful for copying values around within the data structure:: + + # copying one nested value to another + >>> _ = glom(target, Assign('a.c', Spec('a.b'))) + >>> pprint(target) + {'a': {'b': 'value', 'c': 'value'}} + + Another handy use of Assign is to deep-apply a function:: + + # sort a deep nested list + >>> target={'a':{'b':[3,1,2]}} + >>> _ = glom(target, Assign('a.b', Spec(('a.b',sorted)))) + >>> pprint(target) + {'a': {'b': [1, 2, 3]}} + + Like many other specifier types, ``Assign``'s destination path can be + a :data:`~glom.T` expression, for maximum control:: + + # changing the error message of an exception in an error list + >>> err = ValueError('initial message') + >>> target = {'errors': [err]} + >>> _ = glom(target, Assign(T['errors'][0].args, ('new message',))) + >>> str(err) + 'new message' + + ``Assign`` has built-in support for assigning to attributes of + objects, keys of mappings (like dicts), and indexes of sequences + (like lists). Additional types can be registered through + :func:`~glom.register()` using the ``"assign"`` operation name. + + Attempting to assign to an immutable structure, like a + :class:`tuple`, will result in a + :class:`~glom.PathAssignError`. Attempting to assign to a path + that doesn't exist will raise a :class:`~PathAccessError`. + + To automatically backfill missing structures, you can pass a + callable to the *missing* argument. This callable will be called + for each path segment along the assignment which is not + present. + + >>> target = {} + >>> assign(target, 'a.b.c', 'hi', missing=dict) + {'a': {'b': {'c': 'hi'}}} + + """ + def __init__(self, path, val, missing=None): + # TODO: an option like require_preexisting or something to + # ensure that a value is mutated, not just added. Current + # workaround is to do a Check(). + if isinstance(path, basestring): + path = Path.from_text(path) + elif type(path) is TType: + path = Path(path) + elif not isinstance(path, Path): + raise TypeError('path argument must be a .-delimited string, Path, T, or S') + + try: + self.op, self.arg = path.items()[-1] + except IndexError: + raise ValueError('path must have at least one element') + self._orig_path = path + self.path = path[:-1] + + if self.op not in '[.P': + # maybe if we add null-coalescing this should do something? + raise ValueError('last part of path must be setattr or setitem') + self.val = val + + if missing is not None: + if not callable(missing): + raise TypeError(f'expected missing to be callable, not {missing!r}') + self.missing = missing + + def glomit(self, target, scope): + val = arg_val(target, self.val, scope) + + op, arg, path = self.op, self.arg, self.path + if self.path.startswith(S): + dest_target = scope[UP] + dest_path = self.path.from_t() + else: + dest_target = target + dest_path = self.path + try: + dest = scope[glom](dest_target, dest_path, scope) + except PathAccessError as pae: + if not self.missing: + raise + + remaining_path = self._orig_path[pae.part_idx + 1:] + val = scope[glom](self.missing(), Assign(remaining_path, val, missing=self.missing), scope) + + op, arg = self._orig_path.items()[pae.part_idx] + path = self._orig_path[:pae.part_idx] + dest = scope[glom](dest_target, path, scope) + + # TODO: forward-detect immutable dest? + _apply = lambda dest: _assign_op( + dest=dest, op=op, arg=arg, val=val, path=path, scope=scope) + _apply_for_each(_apply, path, dest) + + return target + + def __repr__(self): + cn = self.__class__.__name__ + if self.missing is None: + return f'{cn}({self._orig_path!r}, {self.val!r})' + return f'{cn}({self._orig_path!r}, {self.val!r}, missing={bbrepr(self.missing)})' + + +def assign(obj, path, val, missing=None): + """*New in glom 18.3.0* + + The ``assign()`` function provides convenient "deep set" + functionality, modifying nested data structures in-place:: + + >>> target = {'a': [{'b': 'c'}, {'d': None}]} + >>> _ = assign(target, 'a.1.d', 'e') # let's give 'd' a value of 'e' + >>> pprint(target) + {'a': [{'b': 'c'}, {'d': 'e'}]} + + Missing structures can also be automatically created with the + *missing* parameter. For more information and examples, see the + :class:`~glom.Assign` specifier type, which this function wraps. + """ + return glom(obj, Assign(path, val, missing=missing)) + + +_ALL_BUILTIN_TYPES = [v for v in __builtins__.values() if isinstance(v, type)] +_BUILTIN_BASE_TYPES = [v for v in _ALL_BUILTIN_TYPES + if not issubclass(v, tuple([t for t in _ALL_BUILTIN_TYPES + if t not in (v, type, object)]))] +_UNASSIGNABLE_BASE_TYPES = tuple(set(_BUILTIN_BASE_TYPES) + - {dict, list, BaseException, object, type}) + + +def _set_sequence_item(target, idx, val): + target[int(idx)] = val + + +def _assign_autodiscover(type_obj): + # TODO: issubclass or "in"? + if issubclass(type_obj, _UNASSIGNABLE_BASE_TYPES): + return False + + if callable(getattr(type_obj, '__setitem__', None)): + if callable(getattr(type_obj, 'index', None)): + return _set_sequence_item + return operator.setitem + + return setattr + + +register_op('assign', auto_func=_assign_autodiscover, exact=False) + + +class Delete: + """ + In addition to glom's core "deep-get" and ``Assign``'s "deep-set", + the ``Delete`` specifier type performs a "deep-del", which can + remove items from larger data structures by key, attribute, and + index. + + >>> target = {'dict': {'x': [5, 6, 7]}} + >>> glom(target, Delete('dict.x.1')) + {'dict': {'x': [5, 7]}} + >>> glom(target, Delete('dict.x')) + {'dict': {}} + + If a target path is missing, a :exc:`PathDeleteError` will be + raised. To ignore missing targets, use the ``ignore_missing`` + flag: + + >>> glom(target, Delete('does_not_exist', ignore_missing=True)) + {'dict': {}} + + ``Delete`` has built-in support for deleting attributes of + objects, keys of dicts, and indexes of sequences + (like lists). Additional types can be registered through + :func:`~glom.register()` using the ``"delete"`` operation name. + + .. versionadded:: 20.5.0 + """ + def __init__(self, path, ignore_missing=False): + if isinstance(path, basestring): + path = Path.from_text(path) + elif type(path) is TType: + path = Path(path) + elif not isinstance(path, Path): + raise TypeError('path argument must be a .-delimited string, Path, T, or S') + + try: + self.op, self.arg = path.items()[-1] + except IndexError: + raise ValueError('path must have at least one element') + self._orig_path = path + self.path = path[:-1] + + if self.op not in '[.P': + raise ValueError('last part of path must be an attribute or index') + + self.ignore_missing = ignore_missing + + def _del_one(self, dest, op, arg, scope): + if op == '[': + try: + del dest[arg] + except IndexError as e: + if not self.ignore_missing: + raise PathDeleteError(e, self.path, arg) + elif op == '.': + try: + delattr(dest, arg) + except AttributeError as e: + if not self.ignore_missing: + raise PathDeleteError(e, self.path, arg) + elif op == 'P': + _delete = scope[TargetRegistry].get_handler('delete', dest) + try: + _delete(dest, arg) + except Exception as e: + if not self.ignore_missing: + raise PathDeleteError(e, self.path, arg) + + def glomit(self, target, scope): + op, arg, path = self.op, self.arg, self.path + if self.path.startswith(S): + dest_target = scope[UP] + dest_path = self.path.from_t() + else: + dest_target = target + dest_path = self.path + try: + dest = scope[glom](dest_target, dest_path, scope) + except PathAccessError as pae: + if not self.ignore_missing: + raise + else: + _apply_for_each(lambda dest: self._del_one(dest, op, arg, scope), path, dest) + + return target + + def __repr__(self): + cn = self.__class__.__name__ + return f'{cn}({self._orig_path!r})' + + +def delete(obj, path, ignore_missing=False): + """ + The ``delete()`` function provides "deep del" functionality, + modifying nested data structures in-place:: + + >>> target = {'a': [{'b': 'c'}, {'d': None}]} + >>> delete(target, 'a.0.b') + {'a': [{}, {'d': None}]} + + Attempting to delete missing keys, attributes, and indexes will + raise a :exc:`PathDeleteError`. To ignore these errors, use the + *ignore_missing* argument:: + + >>> delete(target, 'does_not_exist', ignore_missing=True) + {'a': [{}, {'d': None}]} + + For more information and examples, see the :class:`~glom.Delete` + specifier type, which this convenience function wraps. + + .. versionadded:: 20.5.0 + """ + return glom(obj, Delete(path, ignore_missing=ignore_missing)) + + +def _del_sequence_item(target, idx): + del target[int(idx)] + + +def _delete_autodiscover(type_obj): + if issubclass(type_obj, _UNASSIGNABLE_BASE_TYPES): + return False + + if callable(getattr(type_obj, '__delitem__', None)): + if callable(getattr(type_obj, 'index', None)): + return _del_sequence_item + return operator.delitem + return delattr + + +register_op('delete', auto_func=_delete_autodiscover, exact=False) diff --git a/venv/lib/python3.10/site-packages/glom/reduction.py b/venv/lib/python3.10/site-packages/glom/reduction.py new file mode 100644 index 0000000000000000000000000000000000000000..b400ce0d46e331e1d52f3924eb14ae1c38ef2ced --- /dev/null +++ b/venv/lib/python3.10/site-packages/glom/reduction.py @@ -0,0 +1,348 @@ +import operator +import itertools +from pprint import pprint + +from boltons.typeutils import make_sentinel + +from .core import T, glom, GlomError, format_invocation, bbrepr, UnregisteredTarget, MODE +from .grouping import GROUP, target_iter, ACC_TREE, CUR_AGG + +_MISSING = make_sentinel('_MISSING') + + +try: + basestring +except NameError: + basestring = str + + +class FoldError(GlomError): + """Error raised when Fold() is called on non-iterable + targets, and possibly other uses in the future.""" + pass + + +class Fold: + """The `Fold` specifier type is glom's building block for reducing + iterables in data, implementing the classic `fold + `_ + from functional programming, similar to Python's built-in + :func:`reduce`. + + Args: + subspec: A spec representing the target to fold, which must be + an iterable, or otherwise registered to 'iterate' (with + :func:`~glom.register`). + init (callable): A function or type which will be invoked to + initialize the accumulator value. + op (callable): A function to call on the accumulator value and + every value, the result of which will become the new + accumulator value. Defaults to :func:`operator.iadd`. + + Usage is as follows: + + >>> target = [set([1, 2]), set([3]), set([2, 4])] + >>> result = glom(target, Fold(T, init=frozenset, op=frozenset.union)) + >>> result == frozenset([1, 2, 3, 4]) + True + + Note the required ``spec`` and ``init`` arguments. ``op`` is + optional, but here must be used because the :class:`set` and + :class:`frozenset` types do not work with addition. + + While :class:`~glom.Fold` is powerful, :class:`~glom.Flatten` and + :class:`~glom.Sum` are subtypes with more convenient defaults for + day-to-day use. + """ + def __init__(self, subspec, init, op=operator.iadd): + self.subspec = subspec + self.init = init + self.op = op + if not callable(op): + raise TypeError('expected callable for %s op param, not: %r' % + (self.__class__.__name__, op)) + if not callable(init): + raise TypeError('expected callable for %s init param, not: %r' % + (self.__class__.__name__, init)) + + def glomit(self, target, scope): + is_agg = False + if scope[MODE] is GROUP and scope.get(CUR_AGG) is None: + scope[CUR_AGG] = self + is_agg = True + + if self.subspec is not T: + target = scope[glom](target, self.subspec, scope) + + if is_agg: + return self._agg(target, scope[ACC_TREE]) + try: + return self._fold(target_iter(target, scope)) + except UnregisteredTarget as ut: + raise FoldError('can only %s on iterable targets, not %s type (%s)' + % (self.__class__.__name__, type(target).__name__, ut)) + + def _fold(self, iterator): + ret, op = self.init(), self.op + + for v in iterator: + ret = op(ret, v) + + return ret + + def _agg(self, target, tree): + if self not in tree: + tree[self] = self.init() + tree[self] = self.op(tree[self], target) + return tree[self] + + def __repr__(self): + cn = self.__class__.__name__ + kwargs = {'init': self.init} + if self.op is not operator.iadd: + kwargs['op'] = self.op + return format_invocation(cn, (self.subspec,), kwargs, repr=bbrepr) + + +class Sum(Fold): + """The `Sum` specifier type is used to aggregate integers and other + numericals using addition, much like the :func:`sum()` builtin. + + >>> glom(range(5), Sum()) + 10 + + Note that this specifier takes a callable *init* parameter like + its friends, so to change the start value, be sure to wrap it in a + callable:: + + >>> glom(range(5), Sum(init=lambda: 5.0)) + 15.0 + + To "sum" lists and other iterables, see the :class:`Flatten` + spec. For other objects, see the :class:`Fold` specifier type. + + """ + def __init__(self, subspec=T, init=int): + super().__init__(subspec=subspec, init=init, op=operator.iadd) + + def __repr__(self): + cn = self.__class__.__name__ + args = () if self.subspec is T else (self.subspec,) + kwargs = {'init': self.init} if self.init is not int else {} + return format_invocation(cn, args, kwargs, repr=bbrepr) + + +class Count(Fold): + """ + takes a count of how many values occurred + + >>> glom([1, 2, 3], Count()) + 3 + """ + __slots__ = () + + def __init__(self): + super().__init__( + subspec=T, init=int, op=lambda cur, val: cur + 1) + + def __repr__(self): + return '%s()' % self.__class__.__name__ + + +class Flatten(Fold): + """The `Flatten` specifier type is used to combine iterables. By + default it flattens an iterable of iterables into a single list + containing items from all iterables. + + >>> target = [[1], [2, 3]] + >>> glom(target, Flatten()) + [1, 2, 3] + + You can also set *init* to ``"lazy"``, which returns a generator + instead of a list. Use this to avoid making extra lists and other + collections during intermediate processing steps. + """ + def __init__(self, subspec=T, init=list): + if init == 'lazy': + self.lazy = True + init = list + else: + self.lazy = False + super().__init__(subspec=subspec, init=init, op=operator.iadd) + + def _fold(self, iterator): + if self.lazy: + return itertools.chain.from_iterable(iterator) + return super()._fold(iterator) + + def __repr__(self): + cn = self.__class__.__name__ + args = () if self.subspec is T else (self.subspec,) + kwargs = {} + if self.lazy: + kwargs['init'] = 'lazy' + elif self.init is not list: + kwargs['init'] = self.init + return format_invocation(cn, args, kwargs, repr=bbrepr) + + +def flatten(target, **kwargs): + """At its most basic, ``flatten()`` turns an iterable of iterables + into a single list. But it has a few arguments which give it more + power: + + Args: + + init (callable): A function or type which gives the initial + value of the return. The value must support addition. Common + values might be :class:`list` (the default), :class:`tuple`, + or even :class:`int`. You can also pass ``init="lazy"`` to + get a generator. + levels (int): A positive integer representing the number of + nested levels to flatten. Defaults to 1. + spec: The glomspec to fetch before flattening. This defaults to the + the root level of the object. + + Usage is straightforward. + + >>> target = [[1, 2], [3], [4]] + >>> flatten(target) + [1, 2, 3, 4] + + Because integers themselves support addition, we actually have two + levels of flattening possible, to get back a single integer sum: + + >>> flatten(target, init=int, levels=2) + 10 + + However, flattening a non-iterable like an integer will raise an + exception: + + >>> target = 10 + >>> flatten(target) + Traceback (most recent call last): + ... + FoldError: can only Flatten on iterable targets, not int type (...) + + By default, ``flatten()`` will add a mix of iterables together, + making it a more-robust alternative to the built-in + ``sum(list_of_lists, list())`` trick most experienced Python + programmers are familiar with using: + + >>> list_of_iterables = [range(2), [2, 3], (4, 5)] + >>> sum(list_of_iterables, []) + Traceback (most recent call last): + ... + TypeError: can only concatenate list (not "tuple") to list + + Whereas flatten() handles this just fine: + + >>> flatten(list_of_iterables) + [0, 1, 2, 3, 4, 5] + + The ``flatten()`` function is a convenient wrapper around the + :class:`Flatten` specifier type. For embedding in larger specs, + and more involved flattening, see :class:`Flatten` and its base, + :class:`Fold`. + + """ + subspec = kwargs.pop('spec', T) + init = kwargs.pop('init', list) + levels = kwargs.pop('levels', 1) + if kwargs: + raise TypeError('unexpected keyword args: %r' % sorted(kwargs.keys())) + + if levels == 0: + return target + if levels < 0: + raise ValueError('expected levels >= 0, not %r' % levels) + spec = (subspec,) + spec += (Flatten(init="lazy"),) * (levels - 1) + spec += (Flatten(init=init),) + + return glom(target, spec) + + +class Merge(Fold): + """By default, Merge turns an iterable of mappings into a single, + merged :class:`dict`, leveraging the behavior of the + :meth:`~dict.update` method. The start state can be customized + with *init*, as well as the update operation, with *op*. + + Args: + subspec: The location of the iterable of mappings. Defaults to ``T``. + init (callable): A type or callable which returns a base + instance into which all other values will be merged. + op (callable): A callable, which takes two arguments, and + performs a merge of the second into the first. Can also be + the string name of a method to fetch on the instance created + from *init*. Defaults to ``"update"``. + + .. note:: + + Besides the differing defaults, the primary difference between + :class:`Merge` and other :class:`Fold` subtypes is that its + *op* argument is assumed to be a two-argument function which + has no return value and modifies the left parameter + in-place. Because the initial state is a new object created with + the *init* parameter, none of the target values are modified. + + """ + def __init__(self, subspec=T, init=dict, op=None): + if op is None: + op = 'update' + if isinstance(op, basestring): + test_init = init() + op = getattr(type(test_init), op, None) + if not callable(op): + raise ValueError('expected callable "op" arg or an "init" with an .update()' + ' method not %r and %r' % (op, init)) + super().__init__(subspec=subspec, init=init, op=op) + + def _fold(self, iterator): + # the difference here is that ret is mutated in-place, the + # variable not being reassigned, as in base Fold. + ret, op = self.init(), self.op + + for v in iterator: + op(ret, v) + + return ret + + + def _agg(self, target, tree): + if self not in tree: + acc = tree[self] = self.init() + else: + acc = tree[self] + self.op(acc, target) + return acc + + +def merge(target, **kwargs): + """By default, ``merge()`` turns an iterable of mappings into a + single, merged :class:`dict`, leveraging the behavior of the + :meth:`~dict.update` method. A new mapping is created and none of + the passed mappings are modified. + + >>> target = [{'a': 'alpha'}, {'b': 'B'}, {'a': 'A'}] + >>> res = merge(target) + >>> pprint(res) + {'a': 'A', 'b': 'B'} + + Args: + target: The list of dicts, or some other iterable of mappings. + + The start state can be customized with the *init* keyword + argument, as well as the update operation, with the *op* keyword + argument. For more on those customizations, see the :class:`Merge` + spec. + + """ + subspec = kwargs.pop('spec', T) + init = kwargs.pop('init', dict) + op = kwargs.pop('op', None) + if kwargs: + raise TypeError('unexpected keyword args: %r' % sorted(kwargs.keys())) + spec = Merge(subspec, init, op) + return glom(target, spec) diff --git a/venv/lib/python3.10/site-packages/glom/reprlib_backport.py b/venv/lib/python3.10/site-packages/glom/reprlib_backport.py new file mode 100644 index 0000000000000000000000000000000000000000..b06f6ba5de8f3856948d22b4c7ca020ff38d6626 --- /dev/null +++ b/venv/lib/python3.10/site-packages/glom/reprlib_backport.py @@ -0,0 +1,37 @@ +import sys + +PY2 = (sys.version_info[0] == 2) + +if PY2: + from thread import get_ident +else: + from _thread import get_ident + + +def recursive_repr(fillvalue='...'): + 'Decorator to make a repr function return fillvalue for a recursive call' + + def decorating_function(user_function): + repr_running = set() + + def wrapper(self): + key = id(self), get_ident() + if key in repr_running: + return fillvalue + repr_running.add(key) + try: + result = user_function(self) + finally: + repr_running.discard(key) + return result + + # Can't use functools.wraps() here because of bootstrap issues + wrapper.__module__ = getattr(user_function, '__module__') + wrapper.__doc__ = getattr(user_function, '__doc__') + wrapper.__name__ = getattr(user_function, '__name__') + if not PY2: + wrapper.__qualname__ = getattr(user_function, '__qualname__') + wrapper.__annotations__ = getattr(user_function, '__annotations__', {}) + return wrapper + + return decorating_function diff --git a/venv/lib/python3.10/site-packages/glom/streaming.py b/venv/lib/python3.10/site-packages/glom/streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..4da5fb50b26ace62b086106f7d731ca1d68840f0 --- /dev/null +++ b/venv/lib/python3.10/site-packages/glom/streaming.py @@ -0,0 +1,385 @@ +"""glom's helpers for streaming use cases. + +Specifier types which yield their results incrementally so that they +can be applied to targets which are themselves streaming (e.g. chunks +of rows from a database, lines from a file) without excessive memory +usage. + +glom's streaming functionality revolves around a single :class:`Iter` +Specifier type, which has methods to transform the target stream. +""" + +from itertools import islice, dropwhile, takewhile, chain +from functools import partial +try: + from itertools import imap, ifilter +except ImportError: + # py3 + imap = map + ifilter = filter + +from boltons.iterutils import split_iter, chunked_iter, windowed_iter, unique_iter, first +from boltons.funcutils import FunctionBuilder + +from .core import glom, T, STOP, SKIP, _MISSING, Path, TargetRegistry, Call, Spec, Pipe, S, bbrepr, format_invocation +from .matching import Check + +class Iter: + """``Iter()`` is glom's counterpart to Python's built-in :func:`iter()` + function. Given an iterable target, ``Iter()`` yields the result + of applying the passed spec to each element of the target, similar + to the built-in ``[]`` spec, but streaming. + + The following turns a list of strings into integers using Iter(), + before deduplicating and converting it to a tuple: + + >>> glom(['1', '2', '1', '3'], (Iter(int), set, tuple)) + (1, 2, 3) + + ``Iter()`` also has many useful methods which can be chained to + compose a stream processing pipeline. The above can also be + written as: + + >>> glom(['1', '2', '1', '3'], (Iter().map(int).unique(), tuple)) + (1, 2, 3) + + ``Iter()`` also respects glom's :data:`~glom.SKIP` and + :data:`~glom.STOP` singletons for filtering and breaking + iteration. + + Args: + + subspec: A subspec to be applied on each element from the iterable. + sentinel: Keyword-only argument, which, when found in the + iterable stream, causes the iteration to stop. Same as with the + built-in :func:`iter`. + + """ + def __init__(self, subspec=T, **kwargs): + self.subspec = subspec + self._iter_stack = kwargs.pop('_iter_stack', []) + + self.sentinel = kwargs.pop('sentinel', STOP) + if kwargs: + raise TypeError('unexpected keyword arguments: %r' % sorted(kwargs)) + return + + def __repr__(self): + base_args = () + if self.subspec != T: + base_args = (self.subspec,) + base = format_invocation(self.__class__.__name__, base_args, repr=bbrepr) + chunks = [base] + for fname, args, _ in reversed(self._iter_stack): + meth = getattr(self, fname) + fb = FunctionBuilder.from_func(meth) + fb.args = fb.args[1:] # drop self + arg_names = fb.get_arg_names() + # TODO: something fancier with defaults: + kwargs = [] + if len(args) > 1 and arg_names: + args, kwargs = (), zip(arg_names, args) + chunks.append('.' + format_invocation(fname, args, kwargs, repr=bbrepr)) + return ''.join(chunks) + + def glomit(self, target, scope): + iterator = self._iterate(target, scope) + + for _, _, callback in reversed(self._iter_stack): + iterator = callback(iterator, scope) + + return iter(iterator) + + def _iterate(self, target, scope): + iterate = scope[TargetRegistry].get_handler('iterate', target, path=scope[Path]) + try: + iterator = iterate(target) + except Exception as e: + raise TypeError('failed to iterate on instance of type %r at %r (got %r)' + % (target.__class__.__name__, Path(*scope[Path]), e)) + + base_path = scope[Path] + for i, t in enumerate(iterator): + scope[Path] = base_path + [i] + yld = (t if self.subspec is T else scope[glom](t, self.subspec, scope)) + if yld is SKIP: + continue + elif yld is self.sentinel or yld is STOP: + # NB: sentinel defaults to STOP so I was torn whether + # to also check for STOP, and landed on the side of + # never letting STOP through. + return + yield yld + return + + def _add_op(self, opname, args, callback): + return type(self)(subspec=self.subspec, _iter_stack=[(opname, args, callback)] + self._iter_stack) + + def map(self, subspec): + """Return a new :class:`Iter()` spec which will apply the provided + *subspec* to each element of the iterable. + + >>> glom(range(5), Iter().map(lambda x: x * 2).all()) + [0, 2, 4, 6, 8] + + Because a spec can be a callable, :meth:`Iter.map()` does + everything the built-in :func:`map` does, but with the full + power of glom specs. + + >>> glom(['a', 'B', 'C'], Iter().map(T.islower()).all()) + [True, False, False] + """ + # whatever validation you want goes here + # TODO: DRY the self._add_op with a decorator? + return self._add_op( + 'map', + (subspec,), + lambda iterable, scope: imap( + lambda t: scope[glom](t, subspec, scope), iterable)) + + def filter(self, key=T): + """Return a new :class:`Iter()` spec which will include only elements matching the + given *key*. + + >>> glom(range(6), Iter().filter(lambda x: x % 2).all()) + [1, 3, 5] + + Because a spec can be a callable, :meth:`Iter.filter()` does + everything the built-in :func:`filter` does, but with the full + power of glom specs. For even more power, combine, + :meth:`Iter.filter()` with :class:`Check()`. + + >>> # PROTIP: Python's ints know how many binary digits they require, using the bit_length method + >>> glom(range(9), Iter().filter(Check(T.bit_length(), one_of=(2, 4), default=SKIP)).all()) + [2, 3, 8] + + """ + # NB: Check's validate function defaults to bool, and + # *default* is returned on access errors as well validation + # errors, so the lambda passed to ifilter below works fine. + check_spec = key if isinstance(key, Check) else Check(key, default=SKIP) + return self._add_op( + 'filter', + (key,), + lambda iterable, scope: ifilter( + lambda t: scope[glom](t, check_spec, scope) is not SKIP, iterable)) + + def chunked(self, size, fill=_MISSING): + """Return a new :class:`Iter()` spec which groups elements in the iterable + into lists of length *size*. + + If the optional *fill* argument is provided, iterables not + evenly divisible by *size* will be padded out by the *fill* + constant. Otherwise, the final chunk will be shorter than *size*. + + >>> list(glom(range(10), Iter().chunked(3))) + [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]] + >>> list(glom(range(10), Iter().chunked(3, fill=None))) + [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, None, None]] + """ + kw = {'size': size} + args = size, + if fill is not _MISSING: + kw['fill'] = fill + args += (fill,) + return self._add_op( + 'chunked', args, lambda it, scope: chunked_iter(it, **kw)) + + def windowed(self, size): + """Return a new :class:`Iter()` spec which will yield a sliding window of + adjacent elements in the iterable. Each tuple yielded will be + of length *size*. + + Useful for getting adjacent pairs and triples. + + >>> list(glom(range(4), Iter().windowed(2))) + [(0, 1), (1, 2), (2, 3)] + """ + return self._add_op( + 'windowed', (size,), lambda it, scope: windowed_iter(it, size)) + + def split(self, sep=None, maxsplit=None): + """Return a new :class:`Iter()` spec which will lazily split an iterable based + on a separator (or list of separators), *sep*. Like + :meth:`str.split()`, but for all iterables. + + ``split_iter()`` yields lists of non-separator values. A separator will + never appear in the output. + + >>> target = [1, 2, None, None, 3, None, 4, None] + >>> list(glom(target, Iter().split())) + [[1, 2], [3], [4]] + + Note that ``split_iter`` is based on :func:`str.split`, so if + *sep* is ``None``, ``split()`` **groups** separators. If empty lists + are desired between two contiguous ``None`` values, simply use + ``sep=[None]``: + + >>> list(glom(target, Iter().split(sep=[None]))) + [[1, 2], [], [3], [4], []] + + A max number of splits may also be set: + + >>> list(glom(target, Iter().split(maxsplit=2))) + [[1, 2], [3], [4, None]] + + """ + return self._add_op( + 'split', + (sep, maxsplit), + lambda it, scope: split_iter(it, sep=sep, maxsplit=maxsplit)) + + def flatten(self): + """Returns a new :class:`Iter()` instance which combines iterables into a + single iterable. + + >>> target = [[1, 2], [3, 4], [5]] + >>> list(glom(target, Iter().flatten())) + [1, 2, 3, 4, 5] + """ + return self._add_op( + 'flatten', + (), + lambda it, scope: chain.from_iterable(it)) + + def unique(self, key=T): + """Return a new :class:`Iter()` spec which lazily filters out duplicate + values, i.e., only the first appearance of a value in a stream will + be yielded. + + >>> target = list('gloMolIcious') + >>> out = list(glom(target, Iter().unique(T.lower()))) + >>> print(''.join(out)) + gloMIcus + """ + return self._add_op( + 'unique', + (key,), + lambda it, scope: unique_iter(it, key=lambda t: scope[glom](t, key, scope))) + + + def slice(self, *args): + """Returns a new :class:`Iter()` spec which trims iterables in the + same manner as :func:`itertools.islice`. + + >>> target = [0, 1, 2, 3, 4, 5] + >>> glom(target, Iter().slice(3).all()) + [0, 1, 2] + >>> glom(target, Iter().slice(2, 4).all()) + [2, 3] + + This method accepts only positional arguments. + """ + # TODO: make a kwarg-compatible version of this (islice takes no kwargs) + # TODO: also support slice syntax Iter()[::] + try: + islice([], *args) + except TypeError: + raise TypeError(f'invalid slice arguments: {args!r}') + return self._add_op('slice', args, lambda it, scope: islice(it, *args)) + + def limit(self, count): + """A convenient alias for :meth:`~Iter.slice`, which takes a single + argument, *count*, the max number of items to yield. + """ + return self._add_op('limit', (count,), lambda it, scope: islice(it, count)) + + def takewhile(self, key=T): + """Returns a new :class:`Iter()` spec which stops the stream once + *key* becomes falsy. + + >>> glom([3, 2, 0, 1], Iter().takewhile().all()) + [3, 2] + + :func:`itertools.takewhile` for more details. + """ + return self._add_op( + 'takewhile', + (key,), + lambda it, scope: takewhile( + lambda t: scope[glom](t, key, scope), it)) + + def dropwhile(self, key=T): + """Returns a new :class:`Iter()` spec which drops stream items until + *key* becomes falsy. + + >>> glom([0, 0, 3, 2, 0], Iter().dropwhile(lambda t: t < 1).all()) + [3, 2, 0] + + Note that while similar to :meth:`Iter.filter()`, the filter + only applies to the beginning of the stream. In a way, + :meth:`Iter.dropwhile` can be thought of as + :meth:`~str.lstrip()` for streams. See + :func:`itertools.dropwhile` for more details. + + """ + + return self._add_op( + 'dropwhile', + (key,), + lambda it, scope: dropwhile( + lambda t: scope[glom](t, key, scope), it)) + + # Terminal methods follow + + def all(self): + """A convenience method which returns a new spec which turns an + iterable into a list. + + >>> glom(range(5), Iter(lambda t: t * 2).all()) + [0, 2, 4, 6, 8] + + Note that this spec will always consume the whole iterable, and as + such, the spec returned is *not* an :class:`Iter()` instance. + """ + return Pipe(self, list) + + def first(self, key=T, default=None): + """A convenience method for lazily yielding a single truthy item from + an iterable. + + >>> target = [False, 1, 2, 3] + >>> glom(target, Iter().first()) + 1 + + This method takes a condition, *key*, which can also be a + glomspec, as well as a *default*, in case nothing matches the + condition. + + As this spec yields at most one item, and not an iterable, the + spec returned from this method is not an :class:`Iter()` instance. + """ + return (self, First(key=key, default=default)) + + +class First: + """Get the first element of an iterable which matches *key*, if there + is one, otherwise return *default* (``None`` if unset). + + >>> is_odd = lambda x: x % 2 + >>> glom([0, 1, 2, 3], First(is_odd)) + 1 + >>> glom([0, 2, 4], First(is_odd, default=False)) + False + """ + # The impl of this ain't pretty and basically just exists for a + # nicer-looking repr. (Iter(), First()) is the equivalent of doing + # (Iter().filter(spec), Call(first, args=(T,), kwargs={'default': + # default})) + __slots__ = ('_spec', '_default', '_first') + + def __init__(self, key=T, default=None): + self._spec = key + self._default = default + + spec_glom = Spec(Call(partial, args=(Spec(self._spec).glom,), kwargs={'scope': S})) + self._first = Call(first, args=(T,), kwargs={'default': default, 'key': spec_glom}) + + def glomit(self, target, scope): + return self._first.glomit(target, scope) + + def __repr__(self): + cn = self.__class__.__name__ + if self._default is None: + return f'{cn}({bbrepr(self._spec)})' + return f'{cn}({bbrepr(self._spec)}, default={bbrepr(self._default)})' diff --git a/venv/lib/python3.10/site-packages/glom/test/__init__.py b/venv/lib/python3.10/site-packages/glom/test/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/glom/test/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/glom/test/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..74d1020a611ac732ca52183452a2d9bf90f714d3 Binary files /dev/null and b/venv/lib/python3.10/site-packages/glom/test/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/glom/test/__pycache__/perf_report.cpython-310.pyc b/venv/lib/python3.10/site-packages/glom/test/__pycache__/perf_report.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf7e27be761e8425aec45a4ac251047118d5ed7a Binary files /dev/null and b/venv/lib/python3.10/site-packages/glom/test/__pycache__/perf_report.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_basic.cpython-310.pyc b/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_basic.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1bfa724bc873d196d118ebba82dccccb96cfc3c0 Binary files /dev/null and b/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_basic.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_check.cpython-310.pyc b/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_check.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b3fe0139fadb123f19810cf4eba62fef48c77bfa Binary files /dev/null and b/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_check.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_cli.cpython-310.pyc b/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_cli.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a5125a76dbde3accac8c264d99a96a44bf4dd38b Binary files /dev/null and b/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_cli.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_error.cpython-310.pyc b/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_error.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f47678a49dc426f96b21478a52c7b4ab85d643ba Binary files /dev/null and b/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_error.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_fill.cpython-310.pyc b/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_fill.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7515a69ae3da98b08a1179a54317e3083d54a6ae Binary files /dev/null and b/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_fill.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_grouping.cpython-310.pyc b/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_grouping.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4d290bf273fe7cd21a767ed858a468f887da640 Binary files /dev/null and b/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_grouping.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_match.cpython-310.pyc b/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_match.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c55e2fe61036360ddb44d02dd367a366f2cb17d9 Binary files /dev/null and b/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_match.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_mutation.cpython-310.pyc b/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_mutation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a4f0dd8e2e911129c1e7214004f003f4fc248ac Binary files /dev/null and b/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_mutation.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_path_and_t.cpython-310.pyc b/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_path_and_t.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9d1e484b4c92909c9510abd714571e5fb64c6ac Binary files /dev/null and b/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_path_and_t.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_reduction.cpython-310.pyc b/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_reduction.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a5b892e9f64a52c498f8d7ef5132af375757f248 Binary files /dev/null and b/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_reduction.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_scope_vars.cpython-310.pyc b/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_scope_vars.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08e44680309a28930a62123aab3936179a617f7e Binary files /dev/null and b/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_scope_vars.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_snippets.cpython-310.pyc b/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_snippets.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..951f108efe7e5c92103790f368b33eae8fbe9f92 Binary files /dev/null and b/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_snippets.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_spec.cpython-310.pyc b/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_spec.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a832b449fd4e4c32de90a5a596f2db2281aea58 Binary files /dev/null and b/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_spec.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_streaming.cpython-310.pyc b/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_streaming.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d123b151acb707b41b2cdbefd42334460fd23ccc Binary files /dev/null and b/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_streaming.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_target_types.cpython-310.pyc b/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_target_types.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b66cc5aee3124001d6bed1dc1fdaa8b865da1362 Binary files /dev/null and b/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_target_types.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_tutorial.cpython-310.pyc b/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_tutorial.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a4b2c033ed34d7286f9f1cb21d409f865bd4da5 Binary files /dev/null and b/venv/lib/python3.10/site-packages/glom/test/__pycache__/test_tutorial.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/glom/test/data/test_invalid.toml b/venv/lib/python3.10/site-packages/glom/test/data/test_invalid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6c31b39dbec4bfa00e9ae350ea6f09ebbf85a59e --- /dev/null +++ b/venv/lib/python3.10/site-packages/glom/test/data/test_invalid.toml @@ -0,0 +1,2 @@ +# invalid +toml = { diff --git a/venv/lib/python3.10/site-packages/glom/test/data/test_invalid.yaml b/venv/lib/python3.10/site-packages/glom/test/data/test_invalid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7256ab6a785239c49ed0bd0b78de12807fe662ef --- /dev/null +++ b/venv/lib/python3.10/site-packages/glom/test/data/test_invalid.yaml @@ -0,0 +1,2 @@ +- Invalid +Yaml: \ No newline at end of file diff --git a/venv/lib/python3.10/site-packages/glom/test/data/test_valid.toml b/venv/lib/python3.10/site-packages/glom/test/data/test_valid.toml new file mode 100644 index 0000000000000000000000000000000000000000..6758470ea66665d45e3ac81bbb4771f5fbc8717c --- /dev/null +++ b/venv/lib/python3.10/site-packages/glom/test/data/test_valid.toml @@ -0,0 +1 @@ +Hello = ["World"] diff --git a/venv/lib/python3.10/site-packages/glom/test/data/test_valid.yaml b/venv/lib/python3.10/site-packages/glom/test/data/test_valid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5cb7da65659846415bd19e2a85165aca9ef3b9ab --- /dev/null +++ b/venv/lib/python3.10/site-packages/glom/test/data/test_valid.yaml @@ -0,0 +1,3 @@ +--- +Hello: + - World diff --git a/venv/lib/python3.10/site-packages/glom/test/perf_report.py b/venv/lib/python3.10/site-packages/glom/test/perf_report.py new file mode 100644 index 0000000000000000000000000000000000000000..6c555e5a02c06eedf9b90aeeec95f5c896b269af --- /dev/null +++ b/venv/lib/python3.10/site-packages/glom/test/perf_report.py @@ -0,0 +1,87 @@ +""" +slow gloms that came up organically, used as performance metrics +""" +import time +import gc + +import attr + +from glom import glom, T + + + +STR_SPEC = [{ + 'id': ('id', str), + 'name': 'short_name', + 'external_id': 'external_id', + 'created_date': 'created_date', +}] + + +T_SPEC = [{ + 'id': (T.id, str), + 'name': T.short_name, + 'external_id': T.external_id, + 'created_date': T.created_date, +}] + + +def func(data): + return [{ + 'id': str(t.id), + 'name': t.short_name, + 'external_id': t.external_id, + 'created_date': t.created_date + } for t in data] + + +def setup_list_of_dict(num=100): + """ + a common use case is list-of-dicts object processing + to prepare internal objects for JSON serialization + """ + Obj = attr.make_class( + 'Obj', ['id', 'short_name', 'external_id', 'created_date']) + + data = [ + Obj(i, 'name' + str(i), 'external' + str(i), 'now') for i in range(num)] + + return data + + +def run(spec, data): + start = time.time() + glom(data, spec) + end = time.time() + print(f"{(end - start) / len(data) * 1e6} us per object") + + +def ratio(spec, func, data): + glom_dur = [] + py_dur = [] + for i in range(10): + t1 = time.perf_counter_ns() + glom(data, spec) + t2 = time.perf_counter_ns() + func(data) + t3 = time.perf_counter_ns() + glom_dur.append(t2 - t1) + py_dur.append(t3 - t2) + + glom_avg = sum(sorted(glom_dur)[2:-2]) + py_avg = sum(sorted(py_dur)[2:-2]) + + return 1.0 * glom_avg / py_avg + + +if __name__ == "__main__": + import cProfile + data = setup_list_of_dict(100000) + run(STR_SPEC, data) + run(STR_SPEC, data) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + print(ratio(STR_SPEC, func, setup_list_of_dict(1000))) + + +# suggest using scalene to profile with: +# $ scalene glom/test/perf_report.py --profile-all --reduced-profile --cpu-only --outfile SCALENE-CPU.txt diff --git a/venv/lib/python3.10/site-packages/glom/test/test_basic.py b/venv/lib/python3.10/site-packages/glom/test/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..79556b7416a7821e547ed0f610cedec7ffcc5794 --- /dev/null +++ b/venv/lib/python3.10/site-packages/glom/test/test_basic.py @@ -0,0 +1,454 @@ +import sys +from xml.etree import ElementTree as ElementTree + +import pytest + +from glom import glom, SKIP, STOP, Path, Inspect, Coalesce, CoalesceError, Val, Call, T, S, Invoke, Spec, Ref +from glom import Auto, Fill, Iter, A, Vars, Val, Literal, GlomError, Pipe + +import glom.core as glom_core +from glom.core import UP, ROOT, bbformat, bbrepr +from glom.mutation import PathAssignError + +from glom import OMIT, Let, Literal # backwards compat + + +def test_initial_integration(): + class Example: + pass + + example = Example() + subexample = Example() + subexample.name = 'good_name' + example.mapping = {'key': subexample} + + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'example': example, # basic object + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + spec = {'a': (Inspect(recursive=True), 'a', 'b'), # inspect just prints here + 'name': 'example.mapping.key.name', # test object access + 'e': 'd.e', # d.e[0] or d.e: (callable to fetch 0) + 'i': ('i', [{'j': 'j'}]), # TODO: support True for cases when the value should simply be mapped into the field name? + 'n': ('n', lambda n: n.upper()), + 'p': Coalesce('xxx', + 'yyy', + default='zzz')} + + ret = glom(val, spec) + + print('in: ', val) + print('got:', ret) + expected = {'a': 'c', + 'name': 'good_name', + 'e': ['f'], + 'i': [{'j': 'k'}], + 'n': 'O', + 'p': 'zzz'} + print('exp:', expected) + + assert ret == expected + + +def test_list_item_lift_and_access(): + val = {'d': {'e': ['f']}} + + assert glom(val, ('d.e', lambda x: x[0])) == 'f' + assert glom(val, ('d.e', [(lambda x: {'f': x[0]}, 'f')])) == ['f'] + + +def test_coalesce(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + assert glom(val, 'a.b') == 'c' + assert glom(val, Coalesce('xxx', 'yyy', 'a.b')) == 'c' + + # check that defaulting works + spec = Coalesce('xxx', 'yyy', default='zzz') + assert glom(val, spec) == 'zzz' + assert repr(spec) == "Coalesce('xxx', 'yyy', default='zzz')" + + # check that default_factory works + sentinel_list = [] + factory = lambda: sentinel_list + assert glom(val, Coalesce('xxx', 'yyy', default_factory=factory)) is sentinel_list + + with pytest.raises(ValueError): + Coalesce('x', 'y', default=1, default_factory=list) + + # check that arbitrary values can be skipped + assert glom(val, Coalesce('xxx', 'yyy', 'a.b', default='zzz', skip='c')) == 'zzz' + + # check that arbitrary exceptions can be ignored + assert glom(val, Coalesce(lambda x: 1/0, 'a.b', skip_exc=ZeroDivisionError)) == 'c' + + target = {'a': 1, 'b': 3, 'c': 4} + spec = Coalesce('a', 'b', 'c', skip=lambda x: x % 2) + assert glom(target, spec) == 4 + + spec = Coalesce('a', 'b', 'c', skip=(1,)) + assert glom(target, spec) == 3 + + with pytest.raises(TypeError): + Coalesce(bad_kwarg=True) + + + +def test_skip(): + assert OMIT is SKIP # backwards compat + + target = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + + res = glom(target, {'a': 'a.b', + 'z': Coalesce('x', 'y', default=SKIP)}) + assert res['a'] == 'c' # sanity check + + assert 'x' not in target + assert 'y' not in target + assert 'z' not in res + + # test that skip works on lists + target = range(7) + res = glom(target, [lambda t: t if t % 2 else SKIP]) + assert res == [1, 3, 5] + + # test that skip works on chains (enable conditional applications of transforms) + target = range(7) + # double each value if it's even, but convert all values to floats + res = glom(target, [(lambda x: x * 2 if x % 2 == 0 else SKIP, float)]) + assert res == [0.0, 1.0, 4.0, 3.0, 8.0, 5.0, 12.0] + + +def test_stop(): + # test that stop works on iterables + target = iter([0, 1, 2, STOP, 3, 4]) + assert glom(target, [T]) == [0, 1, 2] + + # test that stop works on chains (but doesn't stop iteration up the stack) + target = ['a', ' b', ' c ', ' ', ' done'] + assert glom(target, [(lambda x: x.strip(), + lambda x: x if x else STOP, + lambda x: x[0])]) == ['a', 'b', 'c', '', 'd'] + return + + +def test_top_level_default(): + expected = object() + val = glom({}, 'a.b.c', default=expected) + assert val is expected + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError) + assert val is None + + val = glom({}, lambda x: 1/0, skip_exc=ZeroDivisionError, default=expected) + assert val is expected + + with pytest.raises(KeyError): + # p degenerate case if you ask me + glom({}, 'x', skip_exc=KeyError, default=glom_core._MISSING) + + return + + +def test_val(): + assert Literal is Val + expected = {'value': 'c', + 'type': 'a.b'} + target = {'a': {'b': 'c'}} + val = glom(target, {'value': 'a.b', + 'type': Val('a.b')}) + + assert val == expected + + assert glom(None, Val('success')) == 'success' + assert repr(Val(3.14)) == 'Val(3.14)' + assert repr(Val(3.14)) == 'Val(3.14)' + + +def test_abstract_iterable(): + assert isinstance([], glom_core._AbstractIterable) + + class MyIterable: + def __iter__(self): + return iter([1, 2, 3]) + mi = MyIterable() + assert list(mi) == [1, 2, 3] + + assert isinstance(mi, glom_core._AbstractIterable) + + +def test_call_and_target(): + class F: + def __init__(s, a, b, c): s.a, s.b, s.c = a, b, c + + call_f = Call(F, kwargs=dict(a=T, b=T, c=T)) + assert repr(call_f) + val = glom(1, call_f) + assert (val.a, val.b, val.c) == (1, 1, 1) + class F: + def __init__(s, a): s.a = a + val = glom({'one': F('two')}, Call(F, args=(T['one'].a,))) + assert val.a == 'two' + assert glom({'a': 1}, Call(F, kwargs=T)).a == 1 + assert glom([1], Call(F, args=T)).a == 1 + assert glom(F, T(T)).a == F + assert glom([F, 1], T[0](T[1]).a) == 1 + assert glom([[1]], S[UP][Val(T)][0][0]) == 1 + assert glom([[1]], S[UP][UP][UP][Val(T)]) == [[1]] # tops out + + assert list(glom({'a': 'b'}, Call(T.values))) == ['b'] + + with pytest.raises(TypeError, match='expected func to be a callable or T'): + Call(func=object()) + + assert glom(lambda: 'hi', Call()) == 'hi' + return + + +def test_invoke(): + args = [] + def test(*a, **kw): + args.append(a) + args.append(kw) + return 'test' + + assert glom('a', Invoke(len).specs(T)) == 1 + data = { + 'args': (1, 2), + 'args2': (4, 5), + 'kwargs': {'a': 'a'}, + 'c': 'C', + } + spec = Invoke(test).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + repr(spec) # no exceptions + assert repr(Invoke(len).specs(T)) == 'Invoke(len).specs(T)' + assert (repr(Invoke.specfunc(next).constants(len).constants(1)) + == 'Invoke.specfunc(next).constants(len).constants(1)') + assert glom(data, spec) == 'test' + assert args == [ + (1, 2, 3, 4, 5), + {'a': 'a', 'b': 'b', 'c': 'C'}] + args = [] + assert glom(test, Invoke.specfunc(T)) == 'test' + assert args == [(), {}] + repr_spec = Invoke.specfunc(T).star(args='args' + ).constants(3, b='b').specs(c='c' + ).star(args='args2', kwargs='kwargs') + assert repr(eval(repr(repr_spec), locals(), globals())) == repr(repr_spec) + + with pytest.raises(TypeError, match='expected func to be a callable or Spec instance'): + Invoke(object()) + with pytest.raises(TypeError, match='expected one or both of args/kwargs'): + Invoke(T).star() + + # test interleaved pos args + def ret_args(*a, **kw): + return a, kw + + spec = Invoke(ret_args).constants(1).specs({}).constants(3) + assert glom({}, spec) == ((1, {}, 3), {}) + # .endswith because ret_arg's repr includes a memory location + assert repr(spec).endswith(').constants(1).specs({}).constants(3)') + + # test overridden kwargs + should_stay_empty = [] + spec = Invoke(ret_args).constants(a=1).specs(a=should_stay_empty.append).constants(a=3) + assert glom({}, spec) == ((), {'a': 3}) + assert len(should_stay_empty) == 0 + assert repr(spec).endswith(').constants(a=3)') + + # bit of coverage + target = (lambda: 'hi', {}) + spec = Invoke(T[0]) + assert glom(target, spec) == 'hi' + # and a bit more + spec = spec.star(kwargs=T[1]) + assert repr(spec) == 'Invoke(T[0]).star(kwargs=T[1])' + assert glom(target, spec) == 'hi' + + + +def test_spec_and_recursion(): + assert repr(Spec('a.b.c')) == "Spec('a.b.c')" + + # Call doesn't normally recurse, but Spec can make it do so + assert glom( + ['a', 'b', 'c'], + Call(list, args=( + Spec(Call(reversed, args=(Spec(T),))),) + )) == ['c', 'b', 'a'] + assert glom(['cat', {'cat': 1}], T[1][T[0]]) == 1 + assert glom( + [['ab', 'cd', 'ef'], ''.join], + Call(T[1], args=(Auto((T[0], [T[1:]])),))) == 'bdf' + + # test that spec works on the left of a dict spec + assert glom({'a': 'A'}, {Spec('a'): 'a', 'a': 'a'}) == {'A': 'A', 'a': 'A'} + + +def test_scope(): + assert glom(None, S['foo'], scope={'foo': 'bar'}) == 'bar' + + target = range(3) + spec = [(S, lambda S: S['multiplier'] * S[T])] + scope = {'multiplier': 2} + assert glom(target, spec, scope=scope) == [0, 2, 4] + scope = {'multiplier': 2.5} + assert glom(target, spec, scope=scope) == [0.0, 2.5, 5.0] + + +def test_seq_getitem(): + assert glom({'items': [0, 1, 2, 3]}, 'items.1') == 1 + assert glom({'items': (9, 8, 7, 6)}, 'items.-3') == 8 + + with pytest.raises(glom_core.PathAccessError): + assert glom({'items': (9, 8, 7, 6)}, 'items.fun') + + +# examples from http://sedimental.org/glom_restructured_data.html + +def test_beyond_access(): + # 1 + target = {'galaxy': {'system': {'planet': 'jupiter'}}} + spec = 'galaxy.system.planet' + + output = glom(target, spec) + assert output == 'jupiter' + + # 2 + target = {'system': {'planets': [{'name': 'earth'}, {'name': 'jupiter'}]}} + + output = glom(target, ('system.planets', ['name'])) + assert output == ['earth', 'jupiter'] + + # 3 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + spec = {'names': ('system.planets', ['name']), + 'moons': ('system.planets', ['moons'])} + + output = glom(target, spec) + assert output == {'names': ['earth', 'jupiter'], 'moons': [1, 69]} + + +def test_python_native(): + # 4 + target = {'system': {'planets': [{'name': 'earth', 'moons': 1}, + {'name': 'jupiter', 'moons': 69}]}} + + + output = glom(target, {'moon_count': ('system.planets', ['moons'], sum)}) + assert output == {'moon_count': 70} + + # 5 + spec = T['system']['planets'][-1].values() + + output = glom(target, spec) + assert set(output) == {'jupiter', 69} # for ordering reasons + + with pytest.raises(glom_core.GlomError): + spec = T['system']['comets'][-1].values() + output = glom(target, spec) + + +def test_glom_extra_kwargs(): + # for coverage + with pytest.raises(TypeError): + glom({'a': 'a'}, 'a', invalid_kwarg='yes') + + +def test_inspect(): + # test repr + assert repr(Inspect()) == '' + + target = {'a': {'b': 'c'}} + + import pdb + # test breakpoint + assert Inspect(breakpoint=True).breakpoint == pdb.set_trace + with pytest.raises(TypeError): + Inspect(breakpoint='lol') + + tracker = [] + spec = {'a': Inspect('a.b', echo=False, breakpoint=lambda: tracker.append(True))} + + glom(target, spec) + + assert len(tracker) == 1 + + # test post_mortem + assert Inspect(post_mortem=True).post_mortem == pdb.post_mortem + with pytest.raises(TypeError): + Inspect(post_mortem='lol') + + tracker = [] + spec = {'a': Inspect('nope.nope', post_mortem=lambda: tracker.append(True))} + + assert glom(target, spec, default='default') == 'default' + assert len(tracker) == 1 + + +def test_ref(): + assert glom([[[]]], Ref('item', [Ref('item')])) == [[[]]] + with pytest.raises(Exception): # check that it recurses downards and dies on int iteration + glom([[[1]]], Ref('item', [Ref('item')])) + assert repr(Ref('item', (T[1], Ref('item')))) == "Ref('item', (T[1], Ref('item')))" + + etree2dicts = Ref('ElementTree', + {"tag": "tag", "text": "text", "attrib": "attrib", "children": (iter, [Ref('ElementTree')])}) + etree2tuples = Fill(Ref('ElementTree', (T.tag, (Iter(Ref('ElementTree')), list) ))) + etree = ElementTree.fromstring(''' + + + the title + + +

A paragraph

+ + ''') + glom(etree, etree2dicts) + res = glom(etree, etree2tuples) + # TODO: list(res[1][0]) gives back: + # UnregisteredTarget: UnregisteredTarget('iterate', , ... + # This is even more visible with Iter(Ref('ElementTree')).all() + + +def test_pipe(): + assert glom(1, Pipe("__class__", "__name__", str.upper)) == 'INT' + assert repr(Pipe(1, Pipe([2], dict))) == 'Pipe(1, Pipe([2], dict))' + + +_IS_PYPY = '__pypy__' in sys.builtin_module_names +@pytest.mark.skipif(_IS_PYPY, reason='pypy othertype.__repr__ is never object.__repr__') +def test_api_repr(): + import glom + + spec_types_wo_reprs = [] + for k, v in glom.__dict__.items(): + if not callable(getattr(v, 'glomit', None)): + continue + if v.__repr__ is object.__repr__: + spec_types_wo_reprs.append(k) # pragma: no cover + + assert set(spec_types_wo_reprs) == set() + + +def test_bbformat(): + assert bbformat("{0.__name__}", int) == "int" + + +def test_bbrepr(): + assert bbrepr({int: dict}) == "{int: dict}" diff --git a/venv/lib/python3.10/site-packages/glom/test/test_check.py b/venv/lib/python3.10/site-packages/glom/test/test_check.py new file mode 100644 index 0000000000000000000000000000000000000000..7b08a02fa86137387a95d338ecd5e9b2e7260ab4 --- /dev/null +++ b/venv/lib/python3.10/site-packages/glom/test/test_check.py @@ -0,0 +1,98 @@ +from pytest import raises + +from glom import glom, Check, CheckError, Coalesce, SKIP, STOP, T + +try: + unicode +except NameError: + unicode = str + + +def test_check_basic(): + assert glom([0, SKIP], [T]) == [0] # sanity check SKIP + + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, ([Coalesce(Check('id', equal_to=0), default=SKIP)], T[0])) == {'id': 0} + assert glom(target, ([Check('id', equal_to=0, default=SKIP)], T[0])) == {'id': 0} + + # check that stopping iteration on non-passing values works + assert glom(target, [Check('id', equal_to=0, default=STOP)]) == [{'id': 0}] + + # check that stopping chain execution on non-passing values works + spec = (Check(validate=lambda x: len(x) > 0, default=STOP), T[0]) + assert glom('hello', spec) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + assert repr(Check()) == 'Check()' + assert repr(Check(T.a)) == 'Check(T.a)' + assert repr(Check(equal_to=1)) == 'Check(equal_to=1)' + assert repr(Check(instance_of=dict)) == 'Check(instance_of=dict)' + assert repr(Check(T(len), validate=sum)) == 'Check(T(len), validate=sum)' + + target = [1, 'a'] + assert glom(target, [Check(type=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(type=(unicode, int))]) == [1, 'a'] + assert glom(target, [Check(instance_of=unicode, default=SKIP)]) == ['a'] + assert glom(target, [Check(instance_of=(unicode, int))]) == [1, 'a'] + + target = ['1'] + assert glom(target, [Check(validate=(int, float))]) + assert glom(target, [Check()]) # bare check does a truthy check + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Check(type=str))}, + '''target at path ['a', 'b'] failed check, got error: "expected type to be 'str', found type 'int'"'''), + ({'a': {'b': 1}}, {'a': ('a', Check('b', type=str))}, + '''target at path ['a'] failed check, subtarget at 'b' got error: "expected type to be 'str', found type 'int'"'''), + (1, Check(type=(unicode, bool))), + (1, Check(instance_of=unicode)), + (1, Check(instance_of=(unicode, bool))), + (1, Check(equal_to=0)), + (1, Check(one_of=(0,))), + (1, Check(one_of=(0, 2))), + ('-3.14', Check(validate=int)), + ('', Check(validate=lambda x: False)),] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with raises(CheckError) as exc_info: + glom(target, check) + + if msg is not None: + assert str(exc_info.value).find(msg) != -1 + assert repr(exc_info.value) + + +def test_check_multi(): + target = 1 + with raises(CheckError) as exc_info: + glom(target, Check(instance_of=float, validate=lambda x: x > 3.14)) + + assert "2 errors" in str(exc_info.value) + + + +def test_check_signature(): + with raises(ValueError): + Check(instance_of=()) + with raises(ValueError): + Check(type=()) + + with raises(TypeError): + Check(fake_kwarg=True) + + with raises(ValueError): + Check(one_of=1) + with raises(ValueError): + Check(one_of=()) + with raises(TypeError): + Check(one_of=(1, 2), equal_to=3) + + with raises(ValueError): + Check(validate='bad, not callable, value') diff --git a/venv/lib/python3.10/site-packages/glom/test/test_cli.py b/venv/lib/python3.10/site-packages/glom/test/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..aef5bff4ac9c1b7e7b6624337e28d6e611d1416c --- /dev/null +++ b/venv/lib/python3.10/site-packages/glom/test/test_cli.py @@ -0,0 +1,174 @@ +import os +import subprocess + +import pytest +from face import CommandChecker, CommandLineError + +from glom import cli + + +BASIC_TARGET = '{"a": {"b": "c"}}' +BASIC_SPEC = '{"a": "a.b"}' +BASIC_OUT = '{"a": "c"}\n' + +@pytest.fixture +def cc(): + cmd = cli.get_command() + # TODO: don't mix stderr + return CommandChecker(cmd, mix_stderr=True) + +@pytest.fixture +def basic_spec_path(tmp_path): + spec_path = str(tmp_path) + '/basic_spec.txt' + with open(spec_path, 'w') as f: + f.write(BASIC_SPEC) + return spec_path + +@pytest.fixture +def basic_target_path(tmp_path): + target_path = str(tmp_path) + '/basic_target.txt' + with open(target_path, 'w') as f: + f.write(BASIC_TARGET) + return target_path + + +def test_cli_blank(cc): + res = cc.run(['glom']) + assert res.stdout == '{}\n' + + +def test_cli_spec_target_argv_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + # json format, too + res = cc.run(['glom', '--indent', '0', '--spec-format', 'json', BASIC_SPEC, BASIC_TARGET]) + assert res.stdout == BASIC_OUT + + +def test_cli_spec_argv_target_stdin_basic(cc): + res = cc.run(['glom', '--indent', '0', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', BASIC_SPEC, '-'], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + res = cc.run(['glom', '--indent', '0', '--target-file', '-', BASIC_SPEC], + input=BASIC_TARGET) + assert res.stdout == BASIC_OUT + + +def test_cli_scalar(cc): + res = cc.run(['glom', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == '"d"\n' + + res = cc.run(['glom', '--scalar', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == 'd' + + +def test_cli_spec_target_files_basic(cc, basic_spec_path, basic_target_path): + res = cc.run(['glom', '--indent', '0', '--target-file', + basic_target_path, '--spec-file', basic_spec_path]) + assert res.stdout == BASIC_OUT + + +def test_usage_errors(cc, basic_spec_path, basic_target_path): + # bad target json + res = cc.fail_1(['glom', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target yaml + res = cc.fail_1(['glom', '--target-format', 'yaml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # bad target toml + res = cc.fail_1(['glom', '--target-format', 'toml', BASIC_SPEC, '{' + BASIC_TARGET]) + assert 'could not load target data' in res.stdout # TODO: stderr + + # TODO: bad target python? + + # bad target format TODO: fail_2 + res = cc.fail_1(['glom', '--target-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'target-format to be one of' in res.stdout # TODO: stderr + + # bad spec format TODO: fail_2 + res = cc.fail_1(['glom', '--spec-format', 'lol', BASIC_SPEC, BASIC_TARGET]) + assert 'spec-format to be one of' in res.stdout # TODO: stderr + + # test conflicting spec file and spec posarg + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, BASIC_SPEC, BASIC_TARGET]) + assert 'spec' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + # test conflicting target file and target posarg + res = cc.fail_1(['glom', '--target-file', basic_target_path, BASIC_SPEC, BASIC_TARGET]) + assert 'target' in res.stdout + assert 'not both' in res.stdout # TODO: stderr + + + # TODO: if spec-file is present, maybe single posarg should become target? + res = cc.fail_1(['glom', '--spec-file', basic_spec_path + 'abra', '--target-file', basic_target_path]) + assert 'could not read spec file' in res.stdout # TODO: stderr + + res = cc.fail_1(['glom', '--spec-file', basic_spec_path, '--target-file', basic_target_path + 'abra']) + assert 'could not read target file' in res.stdout # TODO: stderr + + +def test_main_basic(): + argv = ['__', 'a.b.fail', '{"a": {"b": "c"}}'] + assert cli.main(argv) == 1 + + argv = ['__', 'a.b.c', '{"a": {"b": {"c": "d"}}}'] + assert cli.main(argv) == 0 + + +def test_main_yaml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.yaml') + argv = ['__', '--target-file', path, '--target-format', 'yml', 'Hello'] + # Makes sure correct improper yaml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'expected , but found' in str(excinfo.value) + + +def test_main_toml_target(): + cwd = os.path.dirname(os.path.abspath(__file__)) + # Handles the filepath if running tox + if '.tox' in cwd: + cwd = os.path.join(cwd.split('.tox')[0] + '/glom/test/') + path = os.path.join(cwd, 'data/test_valid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + assert cli.main(argv) == 0 + + path = os.path.join(cwd, 'data/test_invalid.toml') + argv = ['__', '--target-file', path, '--target-format', 'toml', 'Hello'] + # Makes sure correct improper toml exception is raised + with pytest.raises(CommandLineError) as excinfo: + cli.main(argv) + assert 'Invalid initial character for a key part' in str(excinfo.value) + + +def test_main_python_full_spec_python_target(): + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', 'T[T[3].bit_length()]', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + argv = ['__', '--target-format', 'python', '--spec-format', 'python-full', '(T.values(), [T])', '{1: 2, 2: 3, 3: 4}'] + assert cli.main(argv) == 0 + + +def test_main(tmp_path): + # TODO: pytest-cov knows how to make coverage work across + # subprocess boundaries... + os.chdir(str(tmp_path)) + res = subprocess.check_output(['glom', 'a', '{"a": 3}']) + assert res.decode('utf8') in ('3\n', '3\r\n') # unix or windows line end okay diff --git a/venv/lib/python3.10/site-packages/glom/test/test_error.py b/venv/lib/python3.10/site-packages/glom/test/test_error.py new file mode 100644 index 0000000000000000000000000000000000000000..42263542cba74a371a298140b2c80d25d4a98f7b --- /dev/null +++ b/venv/lib/python3.10/site-packages/glom/test/test_error.py @@ -0,0 +1,524 @@ +import os +import re +import sys +import traceback + +import pytest + +from glom import glom, S, T, GlomError, Switch, Coalesce, Or, Path +from glom.core import format_oneline_trace, format_target_spec_trace, bbrepr, ROOT, LAST_CHILD_SCOPE +from glom.matching import M, MatchError, TypeMatchError, Match + + +# basic tests: + +def test_good_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data.3')) + + +def test_error(): + target = {'data': [0, 1, 2]} + + with pytest.raises(GlomError): + glom(target, ('data', '3')) + with pytest.raises(GlomError): + glom(target, ('data', [(T.real, T.bit_length, T.image)])) + + +def test_pae_api(): + target = {'value': {'data': [0, 1, 2]}} + + with pytest.raises(GlomError) as exc_info: + glom(target, (T['value'], 'data.3')) + + assert exc_info.value.path == Path('data', '3') + assert exc_info.value.path.__class__ is Path + assert exc_info.value.exc.__class__ is IndexError + assert exc_info.value.part_idx == 1 + + +def test_unfinalized_glomerror_repr(): + assert 'GlomError()' in repr(GlomError()) + + +# trace unit tests: + +def test_line_trace(): + stacklifier = ([{'data': S}],) + scope = glom([1], stacklifier)[0]['data'][ROOT][LAST_CHILD_SCOPE] + fmtd_stack = format_oneline_trace(scope) + assert fmtd_stack == '/tuple!list/list<0>/dict!int/S' + + +# full traceback testing: + +def _norm_stack(formatted_stack, exc): + + normalized = [] + for line in formatted_stack.splitlines(): + if line.strip().startswith('File'): + file_name = line.split('"')[1] + short_file_name = os.path.split(file_name.strip('"'))[1] + line = line.replace(file_name, short_file_name) + line = line.partition('line')[0] + 'line ___,' + line.partition('line')[2].partition(',')[2] + line = line.partition('0x')[0] # scrub memory addresses + + line = line.rstrip() # trailing whitespace shouldn't matter + + # qualify python2's unqualified error type names + exc_type_name = exc.__class__.__name__ + if exc_type_name in line: + mod_name = str(getattr(exc.__class__, '__module__', '') or '') + exc_type_qual_name = exc_type_name + if 'builtin' not in mod_name: + exc_type_qual_name = mod_name + '.' + exc_type_name + if exc_type_qual_name not in line: + line = line.replace(exc_type_name, exc_type_qual_name) + + normalized.append(line) + + stack = "\n".join(normalized) + '\n' + stack = stack.replace(',)', ')') # py37 likes to do Exception('msg',) + return stack + + +def _make_stack(spec, **kwargs): + target = kwargs.pop('target', [None]) + assert not kwargs + _orig_some_str = getattr(traceback, '_some_str', None) + + def _debug_some_str(value, *a, **kw): + # all to debug some CI flakiness + try: + return str(value) + except BaseException as be: # pragma: no cover + try: + print(f' !! failed to stringify {type(value).__name__} object, got {be}') + traceback.print_exc() + except: + print(' !! unable to print trace') + return f'' + + traceback._some_str = _debug_some_str + + try: + try: + glom(target, spec) + except GlomError as e: + stack = _norm_stack(traceback.format_exc(), e) + finally: + traceback._some_str = _orig_some_str + return stack + + +# quick way to get a function in this file, which doesn't have a glom +# package file path prefix on it. this prevents the function getting +# removed in the stack flattening. +from boltons.funcutils import FunctionBuilder +fb = FunctionBuilder(name='_raise_exc', + body='raise Exception("unique message")', + args=['t']) +_raise_exc = fb.get_func() + +# NB: if we keep this approach, eventually +# boltons.funcutils.FunctionBuilder will put lines into the linecache, +# and comparisons may break + + +def test_regular_error_stack(): + actual = _make_stack({'results': [{'value': _raise_exc}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(Exception): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': ", line ___, in _raise_exc +Exception: unique message +""" + # _raise_exc being present in the second-to-last line above tests + # that errors in user-defined functions result in frames being + # visible + assert expected == actual + + +def test_glom_error_stack(): + # NoneType has not attribute value + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'valué': 'value'}]} + - Spec: [{'valué': 'value'}] + - Target: None + - Spec: {'valué': 'value'} + - Spec: 'value' +glom.core.PathAccessError: could not access 'value', part 0 of Path('value'), got error: AttributeError("'NoneType' object has no attribute 'value'") +""" + #import glom.core + #glom.core.GLOM_DEBUG = True + actual = _make_stack({'results': [{'valué': 'value'}]}) + print(actual) + + assert actual == expected + + +# used by the test below, but at the module level. +# originally added to make stack traces more uniform between +# python versions (py3 tries to qualify lambdas and +# other functions inside of local scopes.) + +def _uses_another_glom(): + try: + ret = glom(['Nested'], {'internal': ['val']}) + except Exception as exc: + raise + + +def _subglom_wrap(t): + return _uses_another_glom() + + +def test_glom_error_double_stack(): + actual = _make_stack({'results': [{'value': _subglom_wrap}]}) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: {'results': [{'value': '.format(self.__class__.__name__, 'w' + ('ooooo' * 250)) + + actual = _make_stack(target=ObjectWithLongRepr(), spec='badattr') + assert '...' in actual + assert '(len=' not in actual # no length on a single object + + +def test_branching_stack(): + # ends-in-branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), (T.a, T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.matching.MatchError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), (T.a, T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), (T.a, T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: T.a + |X glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +glom.matching.MatchError: no matches for target in Switch +""" + assert actual == expected + + +def test_midway_branch(): + # midway branch, but then continues + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], T.a)])) + + Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + || Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + # branch and another branch + actual = _make_stack(Match(Switch( + [(1, 1), ('a', 'a'), ([None], Switch( + [(1, 1), ('a', 'a'), ([None], T.a)]))]))) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: [None] + - Spec: Match(Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', '... + + Spec: Switch([(1, 1), ('a', 'a'), ([None], Switch([(1, 1), ('a', 'a'), (... + |\\ Spec: 1 + |X glom.matching.MatchError: [None] does not match 1 + |\\ Spec: 'a' + |X glom.matching.MatchError: [None] does not match 'a' + |\\ Spec: [None] + |+ Spec: Switch([(1, 1), ('a', 'a'), ([None], T.a)]) + ||\\ Spec: 1 + ||X glom.matching.MatchError: [None] does not match 1 + ||\\ Spec: 'a' + ||X glom.matching.MatchError: [None] does not match 'a' + ||\\ Spec: [None] + ||| Spec: T.a +glom.core.PathAccessError: could not access 'a', part 0 of T.a, got error: AttributeError("'list' object has no attribute 'a'") +""" + assert actual == expected + + +def test_partially_failing_branch(): + # what happens when part of an Or() etc fails, + # but another part succeeds and then an error happens further down? + assert _make_stack((Or('a', T), Or('b', T), 'c'), target=None) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: None + - Spec: (Or('a', T), Or('b', T), 'c') + - Spec: Or('a', T) + - Spec: Or('b', T) + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: AttributeError("'NoneType' object has no attribute 'c'") +""" + + +def test_coalesce_stack(): + val = {'a': {'b': 'c'}, # basic dictionary nesting + 'd': {'e': ['f'], # list in dictionary + 'g': 'h'}, + 'i': [{'j': 'k', 'l': 'm'}], # list of dictionaries + 'n': 'o'} + actual = _make_stack(Coalesce('xxx', 'yyy'), target=val) + expected = """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.CoalesceError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': 'c'}, 'd': {'e': ['f'], 'g': 'h'}, 'i': [{'j... (len=4) + + Spec: Coalesce('xxx', 'yyy') + |\\ Spec: 'xxx' + |X glom.core.PathAccessError: could not access 'xxx', part 0 of Path('xxx'), got error: KeyError('xxx') + |\\ Spec: 'yyy' + |X glom.core.PathAccessError: could not access 'yyy', part 0 of Path('yyy'), got error: KeyError('yyy') +glom.core.CoalesceError: no valid values found. Tried ('xxx', 'yyy') and got (PathAccessError, PathAccessError) (at path []) +""" + assert actual == expected + + +def test_nesting_stack(): + # check behavior when a glom stack is nested via data structure not python call stack + assert _make_stack(('a', 'b', 'c'), target={'a': {'b': {}}}) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.PathAccessError: error raised while processing, details below. + Target-spec trace (most recent last): + - Target: {'a': {'b': {}}} + - Spec: ('a', 'b', 'c') + - Spec: 'a' + - Target: {'b': {}} + - Spec: 'b' + - Target: {} + - Spec: 'c' +glom.core.PathAccessError: could not access 'c', part 0 of Path('c'), got error: KeyError('c') +""" + + +ERROR_CLASSES = ( + ValueError, NameError, AttributeError, ZeroDivisionError, SyntaxError, ImportError) + +def test_error_types(): + """test that try / except work normally through glom""" + for err_class in ERROR_CLASSES: + def err_raise(t): + raise err_class() + with pytest.raises(err_class): + glom(None, err_raise) + + +def test_fallback(): + """ + test that in cases of weird badly behaved exception types, + the handler falls back from wrapping to just letting the exception + through + """ + class BadExc(Exception): + def __init__(self, first): + if not first: + 1/0 + self.first = False + super().__init__(self.first) + + bad_exc = BadExc(True) + + def raise_bad(t): + raise bad_exc + + try: + glom(None, raise_bad) + except Exception as e: + assert e is bad_exc + + +def test_all_public_errors(): + """test that all errors importable from the top-level glom module + pass a basic set of standards. + + When adding a new public error type, this test will be fail unless + that type is also tested below. + """ + import glom + import copy + + err_types = [t for t in + [getattr(glom, name) for name in dir(glom)] + if isinstance(t, type) and issubclass(t, Exception)] + non_glomerrors = [t for t in err_types if not issubclass(t, glom.GlomError)] + assert not non_glomerrors, "expected all public exception types to subclass GlomError" + + err_types = sorted([t for t in err_types if not t is glom.GlomError], + key=lambda t: t.__name__) + + results = [] + + def _test_exc(exc_type, target, spec): + with pytest.raises(exc_type) as exc_info: + glom.glom(target, spec) + results.append((target, spec, exc_info.value)) + return exc_info.value + + _test_exc(glom.CheckError, {}, glom.Check(equal_to=[])) + + _test_exc(glom.FoldError, 2, glom.Flatten()) + + _test_exc(glom.BadSpec, range(5), glom.grouping.Group([{T: T}])) + + _test_exc(glom.PathAccessError, {}, 'a.b.c') + + _test_exc(glom.UnregisteredTarget, 'kurt', [glom.T]) + + _test_exc(glom.CoalesceError, {}, glom.Coalesce('a', 'b')) + + _test_exc(glom.PathAssignError, object(), glom.Assign('a', 'b')) + + _test_exc(glom.PathDeleteError, object(), glom.Delete('a')) + + _test_exc(MatchError, 1, M == 2) + + _test_exc(TypeMatchError, 1, Match(str)) + + for (target, spec, exc) in results: + assert copy.copy(exc) is not exc + exc_str = str(exc) + exc_type_name = exc.__class__.__name__ + assert exc_type_name in exc_str + assert bbrepr(exc).startswith(exc_type_name) + + assert bbrepr(target)[:80] in exc_str + assert bbrepr(spec)[:80] in exc_str + + tested_types = [type(exc) for _, _, exc in results] + untested_types = set(err_types) - set(tested_types) + + assert not untested_types, "did not test all public exception types" + + +def test_glom_dev_debug(): + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c') + + assert ' - Target:' in str(exc_info.value) + assert 'yesandno' in str(exc_info.value) + assert len(exc_info.traceback) == 2 + + with pytest.raises(GlomError) as exc_info: + glom({'a': 'yesandno'}, 'a.b.c', glom_debug=True) + + assert ' - Target:' not in str(exc_info.value) + assert len(exc_info.traceback) > 2 + + +def test_unicode_stack(): + val = {'resumé': 'beyoncé'} + stack = _make_stack(target=val, spec='a.é.i.o') + assert 'beyonc' in stack + assert 'é' in stack + + +def test_3_11_byte_code_caret(): + """the ~~^ used to mark the current byte code position should be removed""" + assert _make_stack(target=1, spec=[]) == """\ +Traceback (most recent call last): + File "test_error.py", line ___, in _make_stack + glom(target, spec) + File "core.py", line ___, in glom + raise err +glom.core.GlomError.wrap(IndexError): error raised while processing, details below. + Target-spec trace (most recent last): + - Target: 1 + - Spec: [] +IndexError: list index out of range +""" diff --git a/venv/lib/python3.10/site-packages/glom/test/test_fill.py b/venv/lib/python3.10/site-packages/glom/test/test_fill.py new file mode 100644 index 0000000000000000000000000000000000000000..1fcd47af83c67cf6e99e722f907ab357f1947181 --- /dev/null +++ b/venv/lib/python3.10/site-packages/glom/test/test_fill.py @@ -0,0 +1,20 @@ +from glom import Auto, Fill, T, glom + +def test(): + assert glom('abc', Fill((T[0], {T[1]: T[2]}))) == ('a', {'b': 'c'}) + assert glom('123', Fill({T[0], frozenset([T[1], T[2]])})) == {'1', frozenset(['2', '3'])} + assert glom('xyz', Fill([T[0], T[1], T[2]])) + assert glom('abc', Fill(lambda t: t.upper())) == 'ABC' + assert glom('a', Fill(1)) == 1 + assert Fill((T, T, T)).fill(1) == (1, 1, 1) + + target = {'data': [0, 2, 4]} + assert glom(target, Fill((T['data'][-1], Auto('data.-2')))) == (4, 2) + + assert repr(Auto()) == 'Auto()' + assert repr(Auto(T)) == 'Auto(T)' + + assert repr(Fill()) == 'Fill()' + assert repr(Fill(T)) == 'Fill(T)' + + assert repr(Fill(len)) == 'Fill(len)' diff --git a/venv/lib/python3.10/site-packages/glom/test/test_grouping.py b/venv/lib/python3.10/site-packages/glom/test/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..eb7e691501c5127a8e5ab7851c5b1fbef1376a6f --- /dev/null +++ b/venv/lib/python3.10/site-packages/glom/test/test_grouping.py @@ -0,0 +1,105 @@ +from pytest import raises + +from glom import glom, T, SKIP, STOP, Auto, BadSpec, Val +from glom.grouping import Group, First, Avg, Max, Min, Sample, Limit + +from glom.reduction import Merge, Flatten, Sum, Count + + +def test_bucketing(): + assert glom(range(4), Group({T % 2: [T]})) == {0: [0, 2], 1: [1, 3]} + assert (glom(range(6), Group({T % 3: {T % 2: [T / 10.0]}})) == + {0: {0: [0.0], 1: [0.3]}, 1: {1: [0.1], 0: [0.4]}, 2: {0: [0.2], 1: [0.5]}}) + + + +def test_corner_cases(): + target = range(5) + + # immediate stop dict + assert glom(target, Group({Val(STOP): [T]})) == {} + + # immediate stop list + assert glom(target, Group([Val(STOP)])) == [] + + # dict key SKIP + assert glom(target, Group({(lambda t: SKIP if t < 3 else t): T})) == {3: 3, 4: 4} + + # dict val SKIP + assert glom(target, Group({T: lambda t: t if t % 2 else SKIP})) == {3: 3, 1: 1} + + # list val SKIP + assert glom(target, Group([lambda t: t if t % 2 else SKIP])) == [1, 3] + + # embedded auto spec (lol @ 0 being 0 bit length) + assert glom(target, Group({Auto(('bit_length', T())): [T]})) == {0: [0], 1: [1], 2: [2, 3], 3: [4]} + + # no dicts inside lists in Group mode + with raises(BadSpec): + assert glom(target, Group([{T: T}])) + + # check only supported types + with raises(BadSpec): + assert glom(target, Group('no string support yet')) + + # bucket ints by their bit length and then odd/even, limited to 3 per bucket + spec = Group({T.bit_length(): {lambda t: t % 2: Limit(3)}}) + res = glom(range(20), spec) + assert res == {0: {0: [0]}, + 1: {1: [1]}, + 2: {0: [2], 1: [3]}, + 3: {0: [4, 6], 1: [5, 7]}, + 4: {0: [8, 10, 12], 1: [9, 11, 13]}} + + return + + +def test_agg(): + t = list(range(10)) + assert glom(t, Group(First())) == 0 + assert glom(t, Group(T)) == 9 # this is basically Last + + assert glom(t, Group(Avg())) == sum(t) / len(t) + assert glom(t, Group(Sum())) == sum(t) + + assert glom([0, 1, 0], Group(Max())) == 1 + assert glom([1, 0, 1], Group(Min())) == 0 + + assert repr(Group(First())) == 'Group(First())' + assert repr(Avg()) == 'Avg()' + assert repr(Max()) == 'Max()' + assert repr(Min()) == 'Min()' + assert repr(Sum()) == 'Sum()' + assert repr(Count()) == 'Count()' + + assert glom(range(10), Group({lambda t: t % 2: Count()})) == { + 0: 5, 1: 5} + + +def test_limit(): + t = list(range(10)) + assert glom(t, Group(Limit(1, T))) == 0 + assert glom(t, Group(Limit(3, Max()))) == 2 + assert glom(t, Group(Limit(3, [T]))) == [0, 1, 2] + + assert repr(Group(Limit(3, Max()))) == 'Group(Limit(3, Max()))' + + with raises(BadSpec): + assert glom(t, Limit(1)) # needs to be wrapped in Group for now + return + + +def test_reduce(): + assert glom([[1], [2, 3]], Group(Flatten())) == [1, 2, 3] + assert glom([{'a': 1}, {'b': 2}], Group(Merge())) == {'a': 1, 'b': 2} + assert glom([[[1]], [[2, 3], [4]]], Group(Flatten(Flatten()))) == [1, 2, 3, 4] + + +def test_sample(): + spec = Group(Sample(5)) + assert glom([1, 2, 3], spec) == [1, 2, 3] + + assert repr(spec) == 'Group(Sample(5))' + + s = glom([1, 2, 3], Group(Sample(2))) + assert s in [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]] diff --git a/venv/lib/python3.10/site-packages/glom/test/test_match.py b/venv/lib/python3.10/site-packages/glom/test/test_match.py new file mode 100644 index 0000000000000000000000000000000000000000..f22af56c7798c4b6c00109e9091ce3d7f24eec09 --- /dev/null +++ b/venv/lib/python3.10/site-packages/glom/test/test_match.py @@ -0,0 +1,510 @@ +import re +import json + +import pytest + +from glom import glom, S, Val, T, A, Fill, Ref, Coalesce, STOP, Switch +from glom.matching import ( + Match, M, MatchError, TypeMatchError, And, Or, Not, + Optional, Required, Regex) +from glom.core import Auto, SKIP, Ref + +try: + unicode +except NameError: + unicode = str + + + +def _chk(spec, good_target, bad_target): + glom(good_target, spec) + with pytest.raises(MatchError): + glom(bad_target, spec) + +def test_basic(): + _chk(Match(1), 1, 2) + _chk(Match(int), 1, 1.0) + # test unordered sequence comparisons + _chk(Match([int]), [1], ["1"]) + _chk(Match({int}), {1}, [1]) + _chk(Match(frozenset({float})), frozenset({}), frozenset({"1"})) + _chk(Match(len), [1], []) + with pytest.raises(MatchError): + glom(None, Match(len)) + with pytest.raises(MatchError): + glom([1], Match([])) # empty shouldn't match + glom({"a": 1, "b": 2}, Match({str: int})) + glom(2, M == 2) + glom(int, M == int) + glom(1.0, M > 0) + glom(1.0, M >= 1) + glom(1.0, M < 2) + glom(1.0, M <= 1) + glom(1.0, M != None) + glom(1.0, (M > 0) & float) + glom(1.0, (M > 100) | float) + + assert Match(('a', 'b')).matches(('a', 'b', 'c')) is False + + # test idiom for enum + with pytest.raises(MatchError): + glom("c", Match("a")) + glom("c", Not(Match("a"))) + with pytest.raises(MatchError): + glom("c", Match(Or("a", "b"))) + + with pytest.raises(ValueError): + And() + + with pytest.raises(TypeError): + And('a', bad_kwarg=True) + + with pytest.raises(ValueError): + Or() + + with pytest.raises(TypeError): + Or('a', bad_kwarg=True) + + + _chk(Match(Or("a", "b")), "a", "c") + glom({None: 1}, Match({object: object})) + _chk(Match((int, str)), (1, "cat"), (1, 2)) + with pytest.raises(MatchError): + glom({1: 2}, Match({(): int})) + with pytest.raises(MatchError): + glom(1, Match({})) + Match(M > 0).verify(1.0) + + assert Match(M).matches(False) is False + assert Match(M).matches(True) is True + + +def test_match_expressions(): + assert glom(1, M == M) == 1 + assert glom(1, M == 1) == 1 + assert glom(1, M >= 1) == 1 + assert glom(1, M <= 1) == 1 + with pytest.raises(MatchError): + glom(1, M > 1) + with pytest.raises(MatchError): + glom(1, M < 1) + with pytest.raises(MatchError): + glom(1, M != 1) + + +def test_defaults(): + assert glom(1, Match(2, default=3)) == 3 + assert glom(1, Or(M == 2, default=3)) == 3 + assert glom(1, And(M == 2, default=3)) == 3 + + +def test_match_default(): + default = [] + res = glom(None, Match(list, default=default)) + assert res == default + default = [] + res = glom(None, Match(list, default=Val(default))) + assert res is default + + +def test_double_wrapping(): + for outer in (Required, Optional): + with pytest.raises(TypeError): + outer(Optional('key')) + + with pytest.raises(ValueError): + Required('key') + + return + + +def test_sets(): + with pytest.raises(MatchError): + glom({1}, Match({})) + with pytest.raises(MatchError): + glom(frozenset([1]), Match(frozenset())) + + +def test_m_call_match(): + """test that M __call__ can be used to wrap a subspec for comparison""" + target = {} + target['a'] = target + assert glom(target, M == M(T['a'])) == target + assert glom(target, M(T['a']) == M) == target + assert repr(M(T['a'])) == "M(T['a'])" + + with pytest.raises(TypeError): + M('failure') # TODO: may change in future, see TODO in M.__call__ + + with pytest.raises(MatchError): + glom({'a': False}, M(T['a'])) + + # let's take the operators for a spin + valid_target_spec_pairs = [({'a': 1, 'b': 2}, M(T['a']) < M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) > M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) != M(T['b'])), + ({'a': 2, 'b': 1}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) >= M(T['b'])), + ({'a': 2, 'b': 2}, M(T['a']) <= M(T['b'])), + ({'a': 1, 'b': 2}, M(T['a']) <= M(T['b']))] + + for target, spec in valid_target_spec_pairs: + assert glom(target, spec) is target + + return + + +def test_and_or_reduction(): + and_spec = And(T['a'], T['b']) & T['c'] + + assert repr(and_spec) == "And(T['a'], T['b'], T['c'])" + + or_spec = Or(T['a'], T['b']) | T['c'] + + assert repr(or_spec) == "Or(T['a'], T['b'], T['c'])" + + +def test_precedence(): + """test corner cases of dict key precedence""" + glom({(0, 1): 3}, + Match({ + (0, 1): Val(1), # this should match + (0, int): Val(2), # optional + (0, M == 1): Val(3), # optional + }) + ) + with pytest.raises(ValueError): + Optional(int) # int is already optional so not valid to wrap + + +def test_cruddy_json(): + _chk( + Match({'int_id?': Auto((int, (M > 0)))}), + {'int_id?': '1'}, + {'int_id?': '-1'}) + # embed a build + squished_json = Match({ + 'smooshed_json': Auto( + (json.loads, Match({ + 'sub': Auto((json.loads, M == 1))}))) + }) + glom({'smooshed_json': json.dumps({'sub': json.dumps(1)})}, squished_json) + + +def test_pattern_matching(): + pattern_matcher = Or( + And(Match(1), Val('one')), + And(Match(2), Val('two')), + And(Match(float), Val('float')) + ) + assert glom(1, pattern_matcher) == 'one' + assert glom(1.1, pattern_matcher) == 'float' + + # obligatory fibonacci + + fib = (M > 2) & (lambda n: glom(n - 1, fib) + glom(n - 2, fib)) | T + + assert glom(5, fib) == 8 + + factorial = ( + lambda t: t + 1, Ref('fact', ( + lambda t: t - 1, + (M == 0) & Fill(1) | + (S(r=Ref('fact')), + S, lambda s: s['r'] * s[T])))) + + assert glom(4, factorial) == 4 * 3 * 2 + + +def test_examples(): + assert glom(8, (M > 7) & Val(7)) == 7 + assert glom(range(10), [(M > 7) & Val(7) | T]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M > 7) & Val(SKIP) | T]) == [0, 1, 2, 3, 4, 5, 6, 7] + + +def test_reprs(): + repr(M) + repr(M == 1) + repr(M | M == 1) + repr(M & M == 1) + repr(~M) + repr(And(1, 2)) + repr(Or(1, 2)) + repr(Not(1)) + repr(MatchError("uh oh")) + repr(TypeMatchError("uh oh {0}", dict)) + assert repr(And(M == 1, float)) == "(M == 1) & float" + assert repr(eval(repr(And(M == 1, float)))) == "(M == 1) & float" + + assert repr(Regex('[ab]')) == "Regex('[ab]')" + assert repr(Regex('[ab]', flags=1)) == "Regex('[ab]', flags=1)" + assert 'search' in repr(Regex('[ab]', func=re.search)) + assert repr(And(1)) == 'And(1)' + assert repr(~And(1)) == 'Not(And(1))' + assert repr(~Or(M) & Or(M)) == '~(M) & M' + assert repr(Not(M < 3)) == '~(M < 3)' + assert repr(~(M < 4)) == '~(M < 4)' + assert repr(~M | "default") == "~M | 'default'" + assert repr(Or(M, default=1)) == "Or(M, default=1)" + + +def test_shortcircuit(): + assert glom(False, Fill(M | "default")) == "default" + assert glom(True, Fill(M | "default")) == True + assert glom(True, Fill(M & "default")) == "default" + with pytest.raises(MatchError): + glom(False, Fill(M & "default")) + assert glom(False, ~M) == False + assert glom(True, Fill(~M | "default")) == "default" + + +def test_sample(): + """ + test meant to cover a more realistic use + """ + import datetime + + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + + spec = Match({ + 'name': str, + Optional('date_added'): datetime.datetime, + 'desc': str, + 'tags': [str,]}) + + def good(): + glom(data, spec) + def bad(): + with pytest.raises(MatchError): + glom(data, spec) + + good() # should match + del data['date_added'] + good() # should still match w/out optional + del data['desc'] + bad() + data['desc'] = 'a data item' + data['extra'] = 'will fail on extra' + bad() + spec.spec[str] = str # now extra str-key/str-val are okay + good() + data['extra2'] = 2 # but extra str-key/non-str-val are bad + bad() + # reset data + data = { + 'name': 'item', + 'date_added': datetime.datetime.now(), + 'desc': 'a data item', + 'tags': ['data', 'new'], + } + del spec.spec[str] + spec.spec[Required(str)] = str # now there MUST be at least one str + bad() + data['extra'] = 'extra' + good() + + +def test_regex(): + assert glom('abc', (Regex('(?P.*)'), S['test'])) == 'abc' + # test wrong target type failure path + with pytest.raises(MatchError): + glom(1, Regex('1')) + # test invalid arg path + with pytest.raises(ValueError): + Regex(1, func="invalid") + # test explicit re match func and target value failure path + with pytest.raises(MatchError): + glom('aabcc', Regex('abc', func=re.match)) + + +def test_ternary(): + assert glom('abc', Match(Or(None, 'abc'))) == 'abc' + + +def test_sky(): + """test adapted from github.com/shopkick/opensky""" + + def as_type(sub_schema, typ): + 'after checking sub_schema, pass the result to typ()' + return And(sub_schema, Auto(typ)) + + assert glom('abc', as_type(M == 'abc', list)) == list('abc') + + def none_or(sub_schema): + 'allow None or sub_schema' + return Match(Or(None, sub_schema)) + + assert glom(None, none_or('abc')) == None + assert glom('abc', none_or('abc')) == 'abc' + with pytest.raises(MatchError): + glom(123, none_or('abc')) + + def in_range(sub_schema, _min, _max): + 'check that sub_schema is between _min and _max' + return Match(And(sub_schema, _min < M, M < _max)) + # TODO: make _min < M < _max work + + assert glom(1, in_range(int, 0, 2)) + with pytest.raises(MatchError): + glom(-1, in_range(int, 0, 2)) + + def default_if_none(sub_schema, default_factory): + return Or( + And(M == None, Auto(lambda t: default_factory())), sub_schema) + + assert glom(1, default_if_none(T, list)) == 1 + assert glom(None, default_if_none(T, list)) == [] + + def nullable_list_of(*items): + return default_if_none(Match(list(items)), list) + + assert glom(None, nullable_list_of(str)) == [] + assert glom(['a'], nullable_list_of(str)) == ['a'] + with pytest.raises(MatchError): + glom([1], nullable_list_of(str)) + + +def test_clamp(): + assert glom(range(10), [(M < 7) | Val(7)]) == [0, 1, 2, 3, 4, 5, 6, 7, 7, 7] + assert glom(range(10), [(M < 7) | Val(SKIP)]) == [0, 1, 2, 3, 4, 5, 6] + + +def test_json_ref(): + assert glom( + {'a': {'b': [0, 1]}}, + Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(0, Val(None)), + object)))) == {'a': {'b': [None, 1]}} + + +def test_nested_struct(): + """adapted from use case""" + import json + + _json = lambda spec: Auto((json.loads, _str_json, Match(spec))) + + _str_json = Ref('json', + Match(Or( + And(dict, {Ref('json'): Ref('json')}), + And(list, [Ref('json')]), + And(str, Auto(str)), + object))) + + rule_spec = Match({ + 'rule_id': Or('', Regex(r'\d+')), + 'rule_name': str, + 'effect': Or('approve', 'custom_approvers'), + 'rule_approvers': _json([{'pk': int, 'level': int}]), + 'rule_data': _json([ # list of condition-objects + { + Optional('value', 'null'): _json( + Or(None, int, float, str, [int, float, str])), + 'field': Auto(int), # id of row from FilterField + 'operator': str, # corresponds to FilterOperator.display_name + }]), + Optional('save_as_new', False): Or(str, bool), + }) + + rule = dict( + rule_id='1', + rule_name='test rule', + effect='approve', + rule_approvers=json.dumps([{'pk': 2, 'level': 1}]), + rule_data=json.dumps([ + {'value': json.dumps([1, 2]), 'field': 2, 'operator': '>'}, + {'field': 2, 'operator': '=='}]) + ) + + glom(rule, rule_spec) + rule['save_as_new'] = 'true' + glom(rule, rule_spec) + + +def test_check_ported_tests(): + """ + Tests ported from Check() to make sure all the functionality has an analogue. + """ + target = [{'id': 0}, {'id': 1}, {'id': 2}] + + # check that skipping non-passing values works + assert glom(target, [Coalesce(M(T['id']) == 0, default=SKIP)]) == [{'id': 0}] + + # TODO: should M(subspec, default='') work? I lean no. + # NB: this is not a very idiomatic use of Match, just brought over for Check reasons + assert glom(target, [Match({'id': And(int, M == 1)}, default=SKIP)]) == [{'id': 1}] + assert glom(target, [Match({'id': And(int, M <= 1)}, default=STOP)]) == [{'id': 0}, {'id': 1}] + + # check that stopping chain execution on non-passing values works + spec = (Or(Match(len), Val(STOP)), T[0]) + assert glom('hello', spec, glom_debug=True) == 'h' + assert glom('', spec) == '' # would fail with IndexError if STOP didn't work + + target = [1, 'a'] + assert glom(target, [Match(unicode, default=SKIP)]) == ['a'] + assert glom(target, Match([Or(unicode, int)])) == [1, 'a'] + + target = ['1'] + assert glom(target, [(M(T), int)]) == [1] + assert glom(target, M(T)) == ['1'] + + failing_checks = [({'a': {'b': 1}}, {'a': ('a', 'b', Match(str))}, + '''expected type str, not int'''), # TODO: bbrepr at least, maybe include path like Check did + ({'a': {'b': 1}}, {'a': ('a', Match({'b': str}))}, + '''expected type str, not int'''), # TODO: include subspec path ('b') + (1, Match(Or(unicode, bool))), + (1, Match(unicode)), + (1, Match(0)), + (1, Match(Or(0, 2))), + ('-3.14', Match(lambda x: int(x) > 0)), + # ('-3.14', M(lambda x: int(x) > 0)), + # TODO: M doesn't behave quite like Match because it's mode-free + ] + + for fc in failing_checks: + if len(fc) == 2: + target, check = fc + msg = None + else: + target, check, msg = fc + + with pytest.raises(MatchError) as exc_info: + glom(target, check) + + if msg is not None: + actual_msg = str(exc_info.value) + assert actual_msg.find(msg) != -1 + assert repr(exc_info.value) + + return + + +def test_switch(): + data = {'a': 1, 'b': 2} + cases = [('c', lambda t: 3), ('a', 'a')] + cases2 = dict(cases) + assert glom(data, Switch(cases)) == 1 + assert glom(data, Switch(cases2)) == 1 + assert glom({'c': None}, Switch(cases)) == 3 + assert glom({'c': None}, Switch(cases2)) == 3 + assert glom(None, Switch(cases, default=4)) == 4 + assert glom(None, Switch({'z': 26}, default=4)) == 4 + with pytest.raises(MatchError): + glom(None, Switch(cases)) + with pytest.raises(ValueError): + Switch({}) + with pytest.raises(TypeError): + Switch("wrong type") + assert glom(None, Switch({S(a=1): S['a']})) == 1 + repr(Switch(cases)) + + +def test_nested_dict(): + assert glom({1: 2}, Match({A.t: S.t})) == {1: 1} diff --git a/venv/lib/python3.10/site-packages/glom/test/test_mutation.py b/venv/lib/python3.10/site-packages/glom/test/test_mutation.py new file mode 100644 index 0000000000000000000000000000000000000000..ec86b391ea93b1a0a2133f7644b546f3cc2d1702 --- /dev/null +++ b/venv/lib/python3.10/site-packages/glom/test/test_mutation.py @@ -0,0 +1,325 @@ +import pytest + +from glom import glom, Path, T, S, Spec, Glommer, PathAssignError, PathAccessError +from glom import assign, Assign, delete, Delete, PathDeleteError, Or +from glom import core +from glom.core import UnregisteredTarget + + +def test_assign(): + class Foo: + pass + + assert glom({}, Assign(T['a'], 1)) == {'a': 1} + assert glom({'a': {}}, Assign(T['a']['a'], 1)) == {'a': {'a': 1}} + assert glom({'a': {}}, Assign('a.a', 1)) == {'a': {'a': 1}} + assert glom(Foo(), Assign(T.a, 1)).a == 1 + assert glom({}, Assign('a', 1)) == {'a': 1} + assert glom(Foo(), Assign('a', 1)).a == 1 + assert glom({'a': Foo()}, Assign('a.a', 1))['a'].a == 1 + def r(): + r = {} + r['r'] = r + return r + assert glom(r(), Assign('r.r.r.r.r.r.r.r.r', 1)) == {'r': 1} + assert glom(r(), Assign(T['r']['r']['r']['r'], 1)) == {'r': 1} + assert glom(r(), Assign(Path('r', 'r', T['r']), 1)) == {'r': 1} + assert assign(r(), Path('r', 'r', T['r']), 1) == {'r': 1} + with pytest.raises(TypeError, match='path argument must be'): + Assign(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Assign(T, 1) + + assert repr(Assign(T.a, 1)) == 'Assign(T.a, 1)' + assign_spec = Assign(T.a, 1, missing=dict) + assert repr(assign_spec) == "Assign(T.a, 1, missing=dict)" + assert repr(assign_spec) == repr(eval(repr(assign_spec))) + + +def test_assign_recursive(): + val = {} + val[1] = [val] + recur_out = glom({}, Assign(T['a'], val))['a'] + assert recur_out[1][0] is recur_out + + +def test_assign_spec_val(): + output = glom({'b': 'c'}, Assign('a', Spec('b'))) + assert output['a'] == output['b'] == 'c' + output = glom({'b': 'c'}, Assign('a', Or('d', 'b'))) + assert output['a'] == output['b'] == 'c' + + +def test_unregistered_assign(): + # test with bare target registry + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='assign'): + glommer.glom({}, Assign('a', 'b')) + + # test for unassignable tuple + with pytest.raises(UnregisteredTarget, match='assign'): + glom({'a': ()}, Assign('a.0', 'b')) + + +def test_bad_assign_target(): + class BadTarget: + def __setattr__(self, name, val): + raise Exception("and you trusted me?") + + # sanity check + spec = Assign('a', 'b') + ok_target = lambda: None + glom(ok_target, spec) + assert ok_target.a == 'b' + + with pytest.raises(PathAssignError, match='could not assign'): + glom(BadTarget(), spec) + + with pytest.raises(PathAccessError, match='could not access'): + assign({}, 'a.b.c', 'moot') + return + + +def test_sequence_assign(): + target = {'alist': [0, 1, 2]} + assign(target, 'alist.2', 3) + assert target['alist'][2] == 3 + + with pytest.raises(PathAssignError, match='could not assign') as exc_info: + assign(target, 'alist.3', 4) + + # the following test is because pypy's IndexError is different than CPython's: + # E - PathAssignError(IndexError('list index out of range',), Path('alist'), '3') + # E + PathAssignError(IndexError('list assignment index out of range',), Path('alist'), '3') + # E ? +++++++++++ + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathAssignError(') + assert exc_repr.endswith("'3')") + return + + +def test_invalid_assign_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + assign(target, spec, None) + return + + +def test_assign_missing_signature(): + # test signature (non-callable missing hook) + with pytest.raises(TypeError, match='callable'): + assign({}, 'a.b.c', 'lol', missing='invalidbcnotcallable') + return + + +def test_assign_missing_dict(): + target = {} + val = object() + + from itertools import count + counter = count() + def debugdict(): + ret = dict() + #ret['id'] = id(ret) + #ret['inc'] = counter.next() + return ret + + assign(target, 'a.b.c.d', val, missing=debugdict) + + assert target == {'a': {'b': {'c': {'d': val}}}} + + +def test_assign_missing_object(): + val = object() + class Container: + pass + + target = Container() + target.a = extant_a = Container() + assign(target, 'a.b.c.d', val, missing=Container) + + assert target.a.b.c.d is val + assert target.a is extant_a # make sure we didn't overwrite anything on the path + + +def test_assign_missing_with_extant_keys(): + """This test ensures that assign with missing doesn't overwrite + perfectly fine extant keys that are along the path it needs to + assign to. call count is also checked to make sure missing() isn't + invoked too many times. + + """ + target = {} + value = object() + default_struct = {'b': {'c': {}}} + + call_count = [0] + + def _get_default_struct(): + call_count[0] += 1 # make sure this is only called once + return default_struct + + assign(target, 'a.b.c', value, missing=_get_default_struct) + + assert target['a']['b']['c'] is value + assert target['a']['b'] is default_struct['b'] + assert call_count == [1] + + +def test_assign_missing_unassignable(): + """Check that the final assignment to the target object comes last, + ensuring that failed assignments don't leave targets in a bad + state. + + """ + + class Tarjay: + init_count = 0 + def __init__(self): + self.__class__.init_count += 1 + + @property + def unassignable(self): + return + + value = object() + target = {"preexisting": "ok"} + + with pytest.raises(PathAssignError): + assign(target, 'tarjay.unassignable.a.b.c', value, missing=Tarjay) + + assert target == {'preexisting': 'ok'} + + # why 3? "c" gets the value of "value", while "b", "a", and + # "tarjay" all succeed and are set to Tarjay instances. Then + # unassignable is already present, but not possible to assign to, + # raising the PathAssignError. + assert Tarjay.init_count == 3 + + +def test_s_assign(): + ''' + check that assign works when storing things into S + ''' + assert glom({}, (Assign(S['foo'], 'bar'), S['foo'])) == 'bar' + + +def test_delete(): + class Foo: + def __init__(self, d=None): + for k, v in d.items(): + setattr(self, k, v) + + assert glom({'a': 1}, Delete(T['a'])) == {} + assert glom({'a': {'a': 1}}, Delete(T['a']['a'])) == {'a': {}} + assert glom({'a': {'a': 1}}, Delete('a.a')) == {'a': {}} + assert not hasattr(glom(Foo({'a': 1}), Delete(T.a)), 'a') + assert glom({'a': 1}, Delete('a')) == {} + assert not hasattr(glom(Foo({'a': 1}), Delete('a')), 'a') + assert not hasattr(glom({'a': Foo({'a': 1})}, Delete('a.a'))['a'], 'a') + + def r(): + r = {} + r['r'] = r + return r + + assert glom(r(), Delete('r.r.r.r.r.r.r.r.r')) == {} + assert glom(r(), Delete(T['r']['r']['r']['r'])) == {} + assert glom(r(), Delete(Path('r', 'r', T['r']))) == {} + assert delete(r(), Path('r', 'r', T['r'])) == {} + with pytest.raises(TypeError, match='path argument must be'): + Delete(1, 'a') + with pytest.raises(ValueError, match='path must have at least one element'): + Delete(T, 1) + + assert repr(Delete(T.a)) == 'Delete(T.a)' + + # test delete from scope + assert glom(1, (S(x=T), S['x'])) == 1 + with pytest.raises(PathAccessError): + glom(1, (S(x=T), Delete(S['x']), S['x'])) + + # test raising on missing parent + with pytest.raises(PathAccessError): + glom({}, Delete(T['a']['b'])) + + # test raising on missing index + with pytest.raises(PathDeleteError): + glom([], Delete(T[0])) + target = [] + assert glom(target, Delete(T[0], ignore_missing=True)) is target + + # test raising on missing attr + with pytest.raises(PathDeleteError): + glom(object(), Delete(T.does_not_exist)) + target = object() + assert glom(target, Delete(T.does_not_exist, ignore_missing=True)) is target + + +def test_unregistered_delete(): + glommer = Glommer(register_default_types=False) + + with pytest.raises(UnregisteredTarget, match='delete'): + glommer.glom({'a': 1}, Delete('a')) + + with pytest.raises(UnregisteredTarget, match='delete'): + glom({'a': (1,)}, Delete('a.0')) + + +def test_bad_delete_target(): + class BadTarget: + def __delattr__(self, name): + raise Exception("and you trusted me?") + + spec = Delete('a') + ok_target = lambda: None + ok_target.a = 1 + glom(ok_target, spec) + assert not hasattr(ok_target, 'a') + + with pytest.raises(PathDeleteError, match='could not delete'): + glom(BadTarget(), spec) + + with pytest.raises(PathDeleteError, match='could not delete'): + delete({}, 'a') + return + + +def test_sequence_delete(): + target = {'alist': [0, 1, 2]} + delete(target, 'alist.1') + assert target['alist'] == [0, 2] + + with pytest.raises(PathDeleteError, match='could not delete') as exc_info: + delete(target, 'alist.2') + + exc_repr = repr(exc_info.value) + assert exc_repr.startswith('PathDeleteError(') + assert exc_repr.endswith("'2')") + return + + +def test_invalid_delete_op_target(): + target = {'afunc': lambda x: 'hi %s' % x} + spec = T['afunc'](x=1) + + with pytest.raises(ValueError): + delete(target, spec, None) + return + + +def test_delete_ignore_missing(): + assert delete({}, 'a', ignore_missing=True) == {} + assert delete({}, 'a.b', ignore_missing=True) == {} + + +def test_star_broadcast(): + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, (Assign('a.*.b.*.d', 'a'), 'a.*.b.*.d')) == [['a', 'a', 'a']] + glom(val, Delete('a.*.b.*.d')) + assert 'c' in val['a'][0]['b'][0] + assert 'd' not in val['a'][0]['b'][0] \ No newline at end of file diff --git a/venv/lib/python3.10/site-packages/glom/test/test_path_and_t.py b/venv/lib/python3.10/site-packages/glom/test/test_path_and_t.py new file mode 100644 index 0000000000000000000000000000000000000000..793489e8e4b40d479f18d031b46a68104043ce7f --- /dev/null +++ b/venv/lib/python3.10/site-packages/glom/test/test_path_and_t.py @@ -0,0 +1,355 @@ +from pytest import raises + +from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec, Or, Assign, Delete +from glom import core + +def test_list_path_access(): + assert glom(list(range(10)), Path(1)) == 1 + + +def test_path(): + _obj = object() + target = {'a': {'b.b': [None, {_obj: [None, None, 'd']}]}} + + assert glom(target, Path('a', 'b.b', 1, _obj, -1)) == 'd' + + +def test_empty_path_access(): + target = {} + + assert glom(target, Path()) is target + assert glom(target, (Path(), Path(), Path())) is target + + dup_dict = glom(target, {'target': Path(), + 'target2': Path()}) + dup_dict['target'] is target + dup_dict['target2'] is target + + +def test_path_t_roundtrip(): + # check that T repr roundrips + assert repr(T['a'].b.c()) == "T['a'].b.c()" + assert repr(T[1:]) == "T[1:]" + assert repr(T[::3, 1:, 1:2, :2:3]) == "T[::3, 1:, 1:2, :2:3]" + + # check that Path repr roundtrips + assert repr(Path('a', 1, 'b.b', -1.0)) == "Path('a', 1, 'b.b', -1.0)" + + # check that Path repr roundtrips when it contains Ts + assert repr(Path(T['a'].b, 'c', T['d'].e)) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that T instances containing Path access revert to repring with Path + assert repr(Path(T['a'].b, 'c', T['d'].e).path_t) == "Path(T['a'].b, 'c', T['d'].e)" + + # check that Paths containing only T objects reduce to a T (joining the T objects) + assert repr(Path(T['a'].b, T.c())) == "T['a'].b.c()" + + # check that multiple nested paths reduce + assert repr(Path(Path(Path('a')))) == "Path('a')" + + # check builtin repr + assert repr(T[len]) == 'T[len]' + assert repr(T.func(len, sum)) == 'T.func(len, sum)' + + # check * and ** + assert repr(T.__star__().__starstar__()) == 'T.__star__().__starstar__()' + assert repr(Path('a', T.__star__().__starstar__())) == "Path('a', T.__star__().__starstar__())" + + +def test_path_access_error_message(): + + # test fuzzy access + with raises(GlomError) as exc_info: + glom({}, 'a.b') + assert ("PathAccessError: could not access 'a', part 0 of Path('a', 'b'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('a')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', 'b'), 0)" + + # test multi-part Path with T, catchable as a KeyError + with raises(KeyError) as exc_info: + # don't actually use glom to copy your data structures please + glom({'a': {'b': 'c'}}, Path('a', T.copy(), 'd')) + assert ("PathAccessError: could not access 'd', part 3 of Path('a', T.copy(), 'd'), got error: KeyError" + in exc_info.exconly()) + ke = repr(KeyError('d')) # py3.7+ changed the keyerror repr + assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', T.copy(), 'd'), 3)" + + # test AttributeError + with raises(GlomError) as exc_info: + glom({'a': {'b': 'c'}}, Path('a', T.b)) + assert ("PathAccessError: could not access 'b', part 1 of Path('a', T.b), got error: AttributeError" + in exc_info.exconly()) + ae = repr(AttributeError("'dict' object has no attribute 'b'")) + assert repr(exc_info.value) == "PathAccessError(" + ae + ", Path(\'a\', T.b), 1)" + + +def test_t_picklability(): + import pickle + + class TargetType: + def __init__(self): + self.attribute = lambda: None + self.attribute.method = lambda: {'key': lambda x: x * 2} + + spec = T.attribute.method()['key'](x=5) + + rt_spec = pickle.loads(pickle.dumps(spec)) + assert repr(spec) == repr(rt_spec) + + assert glom(TargetType(), spec) == 10 + + s_spec = S.attribute + assert repr(s_spec) == repr(pickle.loads(pickle.dumps(s_spec))) + + +def test_t_subspec(): + # tests that arg-mode is a min-mode, allowing for + # other specs to be embedded inside T calls + data = [ + {'id': 1}, + {'pk': 1}] + + get_ids = ( + S(id_type=int), + [S.id_type(Or('id', 'pk'))]) + + assert glom(data, get_ids) == [1, 1] + + data = {'a': 1, 'b': 2, 'c': 3} + + # test that "shallow" data structures translate as-is + get_vals = ( + S(seq_type=tuple), + S.seq_type([T['a'], T['b'], Or('c', 'd')]) + ) + + assert glom(data, get_vals) == (1, 2, 3) + + +def test_a_forbidden(): + with raises(BadSpec): + A() # cannot assign to function call + with raises(BadSpec): + glom(1, A) # cannot assign without destination + + +def test_s_magic(): + assert glom(None, S.test, scope={'test': 'value'}) == 'value' + + with raises(PathAccessError): + glom(1, S.a) # ref to 'a' which doesn't exist in scope + + with raises(PathAccessError): + glom(1, A.b.c) + + return + + +def test_path_len(): + + assert len(Path()) == 0 + assert len(Path('a', 'b', 'c')) == 3 + assert len(Path.from_text('1.2.3.4')) == 4 + + assert len(Path(T)) == 0 + assert len(Path(T.a.b.c)) == 3 + assert len(Path(T.a()['b'].c.d)) == 5 + + +def test_path_getitem(): + path = Path(T.a.b.c) + + assert path[0] == Path(T.a) + assert path[1] == Path(T.b) + assert path[2] == Path(T.c) + assert path[-1] == Path(T.c) + assert path[-2] == Path(T.b) + + with raises(IndexError, match='Path index out of range'): + path[4] + + with raises(IndexError, match='Path index out of range'): + path[-14] + return + + +def test_path_slices(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path[::] == path + + # positive indices + assert path[3:] == Path(2, T(test='yes')) + assert path[1:3] == Path(T.b, 1) + assert path[:3] == Path(T.a.b, 1) + + # positive indices backwards + assert path[2:1] == Path() + + # negative indices forward + assert path[-1:] == Path(T(test='yes')) + assert path[:-2] == Path(T.a.b, 1) + assert path[-3:-1] == Path(1, 2) + + # negative indices backwards + assert path[-1:-3] == Path() + + # slicing and stepping + assert path[1::2] == Path(T.b, 2) + + +def test_path_values(): + path = Path(T.a.b, 1, 2, T(test='yes')) + + assert path.values() == ('a', 'b', 1, 2, ((), {'test': 'yes'})) + + assert Path().values() == () + + +def test_path_items(): + path = Path(T.a, 1, 2, T(test='yes')) + + assert path.items() == (('.', 'a'), + ('P', 1), ('P', 2), + ('(', ((), {'test': 'yes'}))) + + assert Path().items() == () + + +def test_path_star(): + val = {'a': [1, 2, 3]} + assert glom(val, 'a.*') == [1, 2, 3] + val['a'] = [{'b': v} for v in val['a']] + assert glom(val, 'a.*.b') == [1, 2, 3] + assert glom(val, T['a'].__star__()['b']) == [1, 2, 3] + assert glom(val, Path('a', T.__star__(), 'b')) == [1, 2, 3] + # multi-paths eat errors + assert glom(val, Path('a', T.__star__(), T.b)) == [] + val = [[[1]]] + assert glom(val, '**') == [val, [[1]], [1], 1] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'d': {'c': 3}}]}], 'c': 4} + assert glom(val, '**.c') == [4, 1, 2, 3] + assert glom(val, 'a.**.c') == [1, 2, 3] + assert glom(val, T['a'].__starstar__()['c']) == [1, 2, 3] + assert glom(val, 'a.*.b.*.c') == [[1, 2]] + # errors + class ErrDict(dict): + def __getitem__(key): 1/0 + assert ErrDict(val).keys() # it will try to iterate + assert glom(ErrDict(val), '**') == [val] + assert glom(ErrDict(val), '*') == [] + # object access + class A: + def __init__(self): + self.a = 1 + self.b = {'c': 2} + val = A() + + assert glom(val, '*') == [1, {'c': 2}] + assert glom(val, '**') == [val, 1, {'c': 2}, 2] + + +def test_star_broadcast(): + val = {'a': [1, 2, 3]} + assert glom(val, Path.from_text('a.*').path_t + 1) == [2, 3, 4] + val = {'a': [{'b': [{'c': 1}, {'c': 2}, {'c': 3}]}]} + assert glom(val, Path.from_text('**.c').path_t + 1) == [2, 3, 4] + + +def test_star_warning(): + '''check that the default behavior is as expected; this will change when * is default on''' + assert core.PATH_STAR is True + try: + core.PATH_STAR = False + assert glom({'*': 1}, '*') == 1 + assert Path._STAR_WARNED + finally: + core.PATH_STAR = True + +def test_path_eq(): + assert Path('a', 'b') == Path('a', 'b') + assert Path('a') != Path('b') + + assert Path() != object() + + +def test_path_eq_t(): + assert Path(T.a.b) == T.a.b + assert Path(T.a.b.c) != T.a.b + + +def test_startswith(): + ref = T.a.b[1] + + assert Path(ref).startswith(T) + assert Path(ref).startswith(T.a.b) + assert Path(ref).startswith(ref) + assert Path(ref).startswith(ref.c) is False + + assert Path('a.b.c').startswith(Path()) + assert Path('a.b.c').startswith('a.b.c') + + with raises(TypeError): + assert Path('a.b.c').startswith(None) + + return + + +def test_from_t_identity(): + ref = Path(T.a.b) + assert ref.from_t() == ref + assert ref.from_t() is ref + + +def test_t_dict_key(): + target = {'a': 'A'} + assert glom(target, {T['a']: 'a'}) == {'A': 'A'} + + +def test_t_arithmetic(): + t = 2 + assert glom(t, T + T) == 4 + assert glom(t, T * T) == 4 + assert glom(t, T ** T) == 4 + assert glom(t, T / 1) == 2 + assert glom(t, T % 1) == 0 + assert glom(t, T - 1) == 1 + assert glom(t, T & T) == 2 + assert glom(t, T | 1) == 3 + assert glom(t, T ^ T) == 0 + assert glom(2, ~T) == -3 + assert glom(t, -T) == -2 + + +def test_t_arithmetic_reprs(): + assert repr(T + T) == "T + T" + assert repr(T + (T / 2 * (T - 5) % 4)) == "T + (T / 2 * (T - 5) % 4)" + assert repr(T & 7 | (T ^ 6)) == "T & 7 | (T ^ 6)" + assert repr(-(~T)) == "-(~T)" + + +def test_t_arithmetic_errors(): + with raises(PathAccessError, match='zero'): + glom(0, T / 0) + + with raises(PathAccessError, match='unsupported operand type'): + glom(None, T / 2) + + return + + +def test_t_dunders(): + with raises(AttributeError) as exc_info: + T.__name__ + + assert 'use T.__("name__")' in str(exc_info.value) + + assert glom(1, T.__('class__')) is int + + +def test_path_cache(): + assert Path.from_text('a.b.c') is Path.from_text('a.b.c') + pre = Path._MAX_CACHE + Path._MAX_CACHE = 0 + assert Path.from_text('d.e.f') is not Path.from_text('d.e.f') diff --git a/venv/lib/python3.10/site-packages/glom/test/test_reduction.py b/venv/lib/python3.10/site-packages/glom/test/test_reduction.py new file mode 100644 index 0000000000000000000000000000000000000000..67fefe7ffa8c1fdd086ae9c76fc63a409b258744 --- /dev/null +++ b/venv/lib/python3.10/site-packages/glom/test/test_reduction.py @@ -0,0 +1,153 @@ +import operator + +import pytest +from boltons.dictutils import OMD + +from glom import glom, T, Sum, Fold, Flatten, Coalesce, flatten, FoldError, Glommer, Merge, merge + + +def test_sum_integers(): + target = list(range(5)) + + assert glom(target, Sum()) == 10 + + assert glom(target, Sum(init=lambda: 2)) == 12 + + target = [] + assert glom(target, Sum()) == 0 + + + target = [{"num": 3}, {"num": 2}, {"num": -1}] + assert glom(target, Sum(['num'])) == 4 + + target = target + [{}] # add a non-compliant dict + assert glom(target, Sum([Coalesce('num', default=0)])) ==4 + + assert repr(Sum()) == 'Sum()' + assert repr(Sum(len, init=float)) == 'Sum(len, init=float)' + + +def test_sum_seqs(): + target = [(x,) for x in range(4)] + assert glom(target, Sum(init=tuple)) == (0, 1, 2, 3) + + # would not work with builtin sum(), gets: + # "TypeError: sum() can't sum strings [use ''.join(seq) instead]" + # Works here for now. If we're ok with that error, then we can + # switch to sum(). + target = ['a', 'b', 'cd'] + assert glom(target, Sum(init=str)) == 'abcd' + + target = [['a'], ['b'], ['cde'], ['']] + + assert glom(target, Sum(Sum(init=list), init=str)) == 'abcde' + + +def test_fold(): + target = range(1, 5) + assert glom(target, Fold(T, int)) == 10 + assert glom(target, Fold(T, init=lambda: 2)) == 12 + + assert glom(target, Fold(T, lambda: 1, op=lambda l, r: l * r)) == 24 + + assert repr(Fold(T, int)) == 'Fold(T, init=int)' + assert repr(Fold(T, int, op=operator.imul)).startswith('Fold(T, init=int, op=<') + + # signature coverage + with pytest.raises(TypeError): + Fold(T, list, op=None) # noncallable op + + with pytest.raises(TypeError): + Fold(T, init=None) # noncallable init + + +def test_fold_bad_iter(): + glommer = Glommer(register_default_types=False) + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(list, iterate=bad_iter) + + with pytest.raises(TypeError): + target = [] + glommer.glom(target, Flatten()) + + +def test_flatten(): + target = [[1], [2], [3, 4]] + assert glom(target, Flatten()) == [1, 2, 3, 4] + + target = [(1, 2), [3]] + assert glom(target, Flatten()) == [1, 2, 3] + + gen = glom(target, Flatten(init='lazy')) + assert next(gen) == 1 + assert list(gen) == [2, 3] + + assert repr(Flatten()) == 'Flatten()' + assert repr(Flatten(init='lazy')) == "Flatten(init='lazy')" + assert repr(Flatten(init=tuple)) == "Flatten(init=tuple)" + + +def test_flatten_func(): + target = [[1], [2], [3, 4]] + assert flatten(target) == [1, 2, 3, 4] + + two_level_target = [[x] for x in target] + assert flatten(two_level_target, levels=2) == [1, 2, 3, 4] + assert flatten(two_level_target, levels=0) == two_level_target + + unflattenable = 2 + + with pytest.raises(FoldError): + assert flatten(unflattenable) + + # kind of an odd use, but it works for now + assert flatten(['a', 'b', 'cd'], init=str) == 'abcd' + + # another odd case + subspec_target = {'items': {'numbers': [1, 2, 3]}} + assert (flatten(subspec_target, spec='items.numbers', init=int) == 6) + + # basic signature tests + with pytest.raises(ValueError): + flatten([], levels=-1) + + with pytest.raises(TypeError): + flatten([], nonexistentkwarg=False) + + return + + +def test_merge(): + + target = [{'a': 'A'}, {'b': 'B'}] + + assert glom(target, Merge()) == {'a': 'A', 'b': 'B'} + + assert glom(target, Merge(op=dict.update)) == {'a': 'A', 'b': 'B'} + + with pytest.raises(ValueError): + Merge(init=list) # has no .update() + + with pytest.raises(ValueError): + Merge(op='update_extend') # doesn't work on base dict, the default init + + +def test_merge_omd(): + target = [{'a': 'A'}, {'a': 'aleph'}] + + assert glom(target, Merge(init=OMD)) == OMD({'a': 'aleph'}) + assert glom(target, Merge(init=OMD, op='update_extend')) == OMD([('a', 'A'), ('a', 'aleph')]) + + +def test_merge_func(): + + target = [{'a': 'A'}, {'b': 'B'}] + assert merge(target) == {'a': 'A', 'b': 'B'} + assert merge([]) == {} + + # basic signature test + with pytest.raises(TypeError): + merge([], nonexistentkwarg=False) diff --git a/venv/lib/python3.10/site-packages/glom/test/test_scope_vars.py b/venv/lib/python3.10/site-packages/glom/test/test_scope_vars.py new file mode 100644 index 0000000000000000000000000000000000000000..68af1ab5779dae1b5ed12277ec7e6d98a932e1e8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/glom/test/test_scope_vars.py @@ -0,0 +1,106 @@ +import pytest + +from glom import glom, Path, S, A, T, Vars, Val, GlomError, M, SKIP, Let + +from glom.core import ROOT +from glom.mutation import PathAssignError + +def test_s_scope_assign(): + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (S(a=T['a']), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + S('posarg') + with pytest.raises(TypeError): + S() + + assert glom([[1]], (S(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (S(v={}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (S(v=1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (S(v=FailAssign()), Path(A.v, 'a'))) + + assert repr(S(a=T.a.b)) == 'S(a=T.a.b)' + + spec = (S(a=T['x']), S.a) + assert glom({'x': 'y'}, spec) == 'y' + + return + + +def test_globals(): + assert glom([[1]], ([[A.globals.a]], S.globals.a)) == 1 + + +def test_vars(): + assert glom(1, A.a) == 1 # A should not change the target + assert glom(1, (A.a, S.a)) == 1 + # check that tuple vars don't "leak" into parent tuple + assert glom(1, (A.t, Val(2), A.t, S.t)) == 2 + assert glom(1, (A.t, (Val(2), A.t), S.t)) == 1 + let = S(v=Vars({'b': 2}, c=3)) + assert glom(1, (let, A.v.a, S.v.a)) == 1 + with pytest.raises(AttributeError): + glom(1, (let, S.v.a)) # check that Vars() inside a spec doesn't hold state + assert glom(1, (let, Path(A, 'v', 'a'), S.v.a)) == 1 + assert glom(1, (let, S.v.b)) == 2 + assert glom(1, (let, S.v.c)) == 3 + assert repr(let) == "S(v=Vars({'b': 2}, c=3))" + assert repr(Vars(a=1, b=2)) in ( + "Vars(a=1, b=2)", "Vars(b=2, a=1)") + assert repr(Vars(a=1, b=2).glomit(None, None)) in ( + "ScopeVars({'a': 1, 'b': 2})", "Vars({'b': 2, 'a': 1})") + + assert repr(A.b["c"]) == "A.b['c']" + + +def test_scoped_vars(): + target = list(range(10)) + list(range(5)) + + scope_globals = glom(target, ([A.globals.last], S.globals)) + assert scope_globals.last == 4 + assert dict(scope_globals) == {'last': 4} + + +def test_max_skip(): + target = list(range(10)) + list(range(5)) + + max_spec = (S(max=Vars(max=0)), + [((M > M(S.max.max)) & A.max.max) | Val(SKIP)], + S.max) + result = glom(target, max_spec) + assert result.max == 9 + + +def test_let(): # backwards compat 2020-07 + data = {'a': 1, 'b': [{'c': 2}, {'c': 3}]} + output = [{'a': 1, 'c': 2}, {'a': 1, 'c': 3}] + assert glom(data, (Let(a='a'), ('b', [{'a': S['a'], 'c': 'c'}]))) == output + assert glom(data, ('b', [{'a': S[ROOT][Val(T)]['a'], 'c': 'c'}])) == output + + with pytest.raises(TypeError): + Let('posarg') + with pytest.raises(TypeError): + Let() + + assert glom([[1]], (Let(v=Vars()), [[A.v.a]], S.v.a)) == 1 + assert glom(1, (Let(v=lambda t: {}), A.v['a'], S.v['a'])) == 1 + with pytest.raises(GlomError): + glom(1, (Let(v=lambda t: 1), A.v.a)) + + class FailAssign: + def __setattr__(self, name, val): + raise Exception('nope') + + with pytest.raises(PathAssignError): + glom(1, (Let(v=lambda t: FailAssign()), Path(A.v, 'a'))) + + assert repr(Let(a=T.a.b)) == 'Let(a=T.a.b)' diff --git a/venv/lib/python3.10/site-packages/glom/test/test_snippets.py b/venv/lib/python3.10/site-packages/glom/test/test_snippets.py new file mode 100644 index 0000000000000000000000000000000000000000..7781bbaf8f8df1fe878a104c320431460ebf6eac --- /dev/null +++ b/venv/lib/python3.10/site-packages/glom/test/test_snippets.py @@ -0,0 +1,59 @@ +import copy +from collections import deque +from decimal import Decimal +import json +import os +import textwrap + +import pytest + +import glom + + +def _get_codeblock(lines, offset): + if lines[offset:offset + 2] != [".. code-block:: python\n", "\n"]: + return None + start = offset + 2 + try: + finish = lines.index('\n', start) + except ValueError: + return None + return textwrap.dedent("".join(lines[start:finish])) + + +def _find_snippets(): + path = os.path.dirname(os.path.abspath(__file__)) + '/../../docs/snippets.rst' + with open(path) as snippet_file: + lines = list(snippet_file) + snippets = [] + for line_no in range(len(lines)): + source = _get_codeblock(lines, line_no) + if source: + snippets.append((line_no, source)) + return snippets + + +try: + SNIPPETS = _find_snippets() +except: + SNIPPETS = [] # in case running in an environment without docs + +SNIPPETS_GLOBALS = copy.copy(glom.__dict__) +SNIPPETS_GLOBALS.update(dict( + json=json, + deque=deque, + Decimal=Decimal, + data=json.dumps({'a': ['b']}), + contacts=[{'primary_email': {'email': 'a@example.com'}}, {}], + glom=glom.glom)) + + +@pytest.mark.parametrize("line,source", SNIPPETS) +def test_snippet(line, source): + if '>>>' in source: + return # maybe doctest output checking + code = compile(source, 'snippets.rst', 'exec') + if 'django' in source: + return # maybe in the future + eval(code, SNIPPETS_GLOBALS) + diff --git a/venv/lib/python3.10/site-packages/glom/test/test_spec.py b/venv/lib/python3.10/site-packages/glom/test/test_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..d9cc9a12532dae7fb8c901d15dd82ab1a4c74eb6 --- /dev/null +++ b/venv/lib/python3.10/site-packages/glom/test/test_spec.py @@ -0,0 +1,26 @@ +import pytest + +from glom import glom, Spec, T, S + + +def test_spec(): + assert glom(5, T) == 5 # check assumption about echo behavior + echo = Spec(T) + assert echo.glom(5) == 5 + assert glom(5, echo) == 5 + echo2 = Spec(echo) + assert echo2.glom(5) == 5 + + with pytest.raises(TypeError, match='expected spec to be'): + glom({}, object()) + return + +def test_scope_spec(): + scope_spec = Spec(S) + assert scope_spec.glom(5, scope={'cat': 1})['cat'] == 1 + cat_scope_spec = Spec(scope_spec, scope={'cat': 1}) + assert 'cat' in repr(cat_scope_spec) + assert cat_scope_spec.glom(5)['cat'] == 1 + + # test that Spec overrides the scope for its sub-tree + assert glom(5, cat_scope_spec, scope={'cat': 2})['cat'] == 1 diff --git a/venv/lib/python3.10/site-packages/glom/test/test_streaming.py b/venv/lib/python3.10/site-packages/glom/test/test_streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..a673dacf10758913485875591ea3bbc106f0fcce --- /dev/null +++ b/venv/lib/python3.10/site-packages/glom/test/test_streaming.py @@ -0,0 +1,209 @@ +import pytest + +from itertools import count, dropwhile, chain + +from glom import Iter +from glom import glom, SKIP, STOP, T, Call, Spec, Glommer, Check, SKIP + + +RANGE_5 = list(range(5)) + + +def test_iter(): + assert list(glom(['1', '2', '3'], Iter(int))) == [1, 2, 3] + cnt = count() + cnt_1 = glom(cnt, Iter(lambda t: t + 1)) + assert (next(cnt_1), next(cnt_1)) == (1, 2) + assert next(cnt) == 2 + + assert list(glom(['1', '2', '3'], (Iter(int), enumerate))) == [(0, 1), (1, 2), (2, 3)] + + assert list(glom([1, SKIP, 2], Iter())) == [1, 2] + assert list(glom([1, STOP, 2], Iter())) == [1] + + with pytest.raises(TypeError): + Iter(nonexistent_kwarg=True) + + +def test_filter(): + is_odd = lambda x: x % 2 + odd_spec = Iter().filter(is_odd) + out = glom(RANGE_5, odd_spec) + assert list(out) == [1, 3] + + # let's just make sure we're actually streaming just in case + counter = count() + out = glom(counter, odd_spec) + assert next(out) == 1 + assert next(out) == 3 + assert next(counter) == 4 + assert next(counter) == 5 + assert next(out) == 7 + + bools = [True, False, False, True, False] + spec = Iter().filter().all() + out = glom(bools, spec) + assert out == [True, True] + + imags = [0j, 1j, 2, 2j, 3j] + spec = Iter().filter(Check(T.imag.real, type=float, one_of=(0, 2), default=SKIP)).all() + out = glom(imags, spec) + assert out == [0j, 2j] + + assert repr(Iter().filter(T.a.b)) == 'Iter().filter(T.a.b)' + assert repr(Iter(list).filter(sum)) == 'Iter(list).filter(sum)' + + +def test_map(): + spec = Iter().map(lambda x: x * 2) + out = glom(RANGE_5, spec) + assert list(out) == [0, 2, 4, 6, 8] + assert repr(Iter().map(T.a.b)) == 'Iter().map(T.a.b)' + + +def test_split_flatten(): + falsey_stream = [1, None, None, 2, 3, None, 4] + spec = Iter().split() + out = glom(falsey_stream, spec) + assert list(out) == [[1], [2, 3], [4]] + + spec = Iter().split().flatten() + out = glom(falsey_stream, spec) + assert list(out) == [1, 2, 3, 4] + + assert repr(Iter().split(sep=None, maxsplit=2)) == 'Iter().split(sep=None, maxsplit=2)' + assert repr(Iter(T.a.b[1]).flatten()) == 'Iter(T.a.b[1]).flatten()' + + +def test_chunked(): + int_list = list(range(9)) + + spec = Iter().chunked(3) + out = glom(int_list, spec) + assert list(out) == [[0, 1, 2], [3, 4, 5], [6, 7, 8]] + + spec = Iter().chunked(3).map(sum) + out = glom(int_list, spec) + assert list(out) == [3, 12, 21] + + +def test_windowed(): + int_list = list(range(5)) + + spec = Iter().windowed(3) + out = glom(int_list, spec) + assert list(out) == [(0, 1, 2), (1, 2, 3), (2, 3, 4)] + assert repr(spec) == 'Iter().windowed(3)' + + spec = spec.filter(lambda x: bool(x[0] % 2)).map(sum) + out = glom(int_list, spec) + assert next(out) == 6 + + out = glom(range(10), spec) + assert list(out) == [6, 12, 18, 24] + + +def test_unique(): + int_list = list(range(10)) + + spec = Iter().unique() + out = glom(int_list, spec) + assert list(out) == int_list + + spec = Iter(lambda x: x % 4).unique() + out = glom(int_list, spec) + assert list(out) == int_list[:4] + assert repr(Iter().unique(T.a)) == 'Iter().unique(T.a)' + + +def test_slice(): + cnt = count() + + spec = Iter().slice(3) + out = glom(cnt, spec) + + assert list(out) == [0, 1, 2] + assert next(cnt) == 3 + + out = glom(range(10), Iter().slice(1, 5)) + assert list(out) == [1, 2, 3, 4] + + out = glom(range(10), Iter().slice(1, 6, 2)) + assert list(out) == [1, 3, 5] + assert repr(Iter().slice(1, 6, 2)) == 'Iter().slice(1, 6, 2)' + + out = glom(range(10), Iter().limit(3)) + assert list(out) == [0, 1, 2] + assert repr(Iter().limit(3)) == 'Iter().limit(3)' + + out = glom(range(5), Iter().limit(10)) + assert list(out) == [0, 1, 2, 3, 4] + + # test broken args + with pytest.raises(TypeError): + Iter().slice(1, 2, 3, 4) + + +def test_while(): + cnt = count() + out = glom(cnt, Iter().takewhile(lambda x: x < 3)) + assert list(out) == [0, 1, 2] + assert next(cnt) == 4 + assert repr(Iter().takewhile(T.a) == 'Iter().takewhile(T.a)') + + range_iter = iter(range(7)) + out = glom(range_iter, Iter().dropwhile(lambda x: x < 3 or x > 5)) + assert list(out) == [3, 4, 5, 6] # 6 still here despite the x>5 above + + out = glom(range(10), Iter().dropwhile(lambda x: x >= 0).limit(10)) + assert list(out) == [] + + out = glom(range(8), Iter().dropwhile((T.bit_length(), lambda x: x < 3))) + assert list(out) == [4, 5, 6, 7] + assert repr(Iter().dropwhile(T.a) == 'Iter().dropwhile(T.a)') + + +def test_iter_composition(): + int_list = list(range(10)) + out = glom(int_list, (Iter(), Iter(), list)) + assert out == int_list + + out = glom([int_list] * 3, Iter(Iter(lambda x: x % 4)).flatten().unique()) + assert list(out) == [0, 1, 2, 3] + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom('abc', (Iter(), list)) + + +def test_first(): + spec = Iter().first(T.imag) + + target = iter([1, 2, 3j, 4]) + out = glom(target, spec) + assert out == 3j + assert next(target) == 4 + assert repr(spec) == '(Iter(), First(T.imag))' + + spec = Iter().first(T.imag, default=0) + target = iter([1, 2, 4]) + out = glom(target, spec) + assert out == 0 + assert repr(spec) == '(Iter(), First(T.imag, default=0))' + + +def test_all(): + int_iter = iter(range(10)) + + out = glom(int_iter, Iter().all()) + assert out == list(range(10)) + assert next(int_iter, None) is None + assert repr(Iter().all()) == 'Pipe(Iter(), list)' diff --git a/venv/lib/python3.10/site-packages/glom/test/test_target_types.py b/venv/lib/python3.10/site-packages/glom/test/test_target_types.py new file mode 100644 index 0000000000000000000000000000000000000000..d8da949099ca29d28fa8ad00a5283d7ef6eae924 --- /dev/null +++ b/venv/lib/python3.10/site-packages/glom/test/test_target_types.py @@ -0,0 +1,272 @@ +import pytest + +import glom +from glom import Glommer, PathAccessError, UnregisteredTarget +from glom.core import TargetRegistry + + +class A: + pass + +class B: + pass + +class C(A): + pass + +class D(B): + pass + +class E(C, D, A): + pass + +class F(E): + pass + + +def test_types_leave_one_out(): + ALL_TYPES = [A, B, C, D, E, F] + for cur_t in ALL_TYPES: + + treg = TargetRegistry(register_default_types=False) + + treg.register(object, get=lambda: object) + for t in ALL_TYPES: + if t is cur_t: + continue + treg.register(t, get=(lambda t: lambda: t)(t)) + + obj = cur_t() + assert treg.get_handler('get', obj)() == obj.__class__.mro()[1] + + if cur_t is E: + assert treg.get_handler('get', obj)() is C # sanity check + + return + + +def test_types_bare(): + glommer = Glommer(register_default_types=False) + + treg = glommer.scope[TargetRegistry] + assert treg._get_closest_type(object(), treg._op_type_tree.get('get', {})) is None + + # test that bare glommers can't glom anything + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom(object(), {'object_repr': '__class__.__name__'}) + assert repr(exc_info.value) == "UnregisteredTarget('get', , OrderedDict(), ('__class__',))" + assert str(exc_info.value).find( + "glom() called without registering any types for operation 'get'." + " see glom.register() or Glommer's constructor for details.") != -1 + + with pytest.raises(UnregisteredTarget, match='without registering') as exc_info: + glommer.glom([{'hi': 'hi'}], ['hi']) + assert not exc_info.value.type_map + + glommer.register(object, get=getattr) + glommer.register(dict, get=dict.__getitem__, exact=True) + + # check again that registering object for 'get' doesn't change the + # fact that we don't have iterate support yet + with pytest.raises(UnregisteredTarget) as exc_info: + glommer.glom({'test': [{'hi': 'hi'}]}, ('test', ['hi'])) + # feel free to update the "(at ['test'])" part to improve path display + assert ( + "target type 'list' not registered for 'iterate', " + "expected one of registered types: (dict)" in str(exc_info.value)) + return + + +def test_invalid_register(): + glommer = Glommer() + with pytest.raises(TypeError): + glommer.register(1) + return + + +def test_exact_register(): + glommer = Glommer(register_default_types=False) + + class BetterList(list): + pass + + glommer.register(BetterList, iterate=iter, exact=True) + + expected = [0, 2, 4] + value = glommer.glom(BetterList(range(3)), [lambda x: x * 2]) + assert value == expected + + with pytest.raises(UnregisteredTarget): + glommer.glom(list(range(3)), ['unused']) + + return + + +def test_duck_register(): + class LilRanger: + def __init__(self): + self.lil_list = list(range(5)) + + def __iter__(self): + return iter(self.lil_list) + + glommer = Glommer(register_default_types=False) + + target = LilRanger() + + with pytest.raises(UnregisteredTarget): + float_range = glommer.glom(target, [float]) + + glommer.register(LilRanger) + + float_range = glommer.glom(target, [float]) + + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + glommer = Glommer() # now with just defaults + float_range = glommer.glom(target, [float]) + assert float_range == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_bypass_getitem(): + target = list(range(3)) * 3 + + with pytest.raises(PathAccessError): + glom.glom(target, 'count') + + res = glom.glom(target, lambda list_obj: list_obj.count(1)) + + assert res == 3 + + +def test_iter_set(): + some_ints = set(range(5)) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + # now without defaults + glommer = Glommer(register_default_types=False) + glommer.register(set, iterate=iter) + some_floats = glom.glom(some_ints, [float]) + + assert sorted(some_floats) == [0.0, 1.0, 2.0, 3.0, 4.0] + + +def test_iter_str(): + # check that strings are not iterable by default, one of the most + # common sources of bugs + glom_buddy = 'kurt' + + with pytest.raises(UnregisteredTarget): + glom.glom(glom_buddy, {'name': [glom_buddy]}) + + # also check that someone can override this + + glommer = Glommer() + glommer.register(str, iterate=iter) + res = glommer.glom(glom_buddy, {'name_chars_for_some_reason': [str]}) + assert len(res['name_chars_for_some_reason']) == 4 + + # the better way, for any dissenter reading this + + assert glom.glom(glom_buddy, {'name_chars': list}) == {'name_chars': ['k', 'u', 'r', 't']} + + # and for the really passionate: how about making strings + # non-iterable and just giving them a .chars() method that returns + # a list of single-character strings. + + +def test_default_scope_register(): + # just hit it to make sure it exists, it behaves exactly like Glommer.register + glom.register(type, exact=False) + + +def test_faulty_iterate(): + glommer = Glommer() + + def bad_iter(obj): + raise RuntimeError('oops') + + glommer.register(str, iterate=bad_iter) + + with pytest.raises(TypeError): + glommer.glom({'a': 'fail'}, ('a', {'chars': [str]})) + + +def test_faulty_op_registration(): + treg = TargetRegistry() + + with pytest.raises(TypeError, match="text name, not:"): + treg.register_op(None, len) + with pytest.raises(TypeError, match="callable, not:"): + treg.register_op('fake_op', object()) + + class NewType: + pass + + def _autodiscover_raise(type_obj): + raise Exception('noperino') + + with pytest.raises(TypeError, match="noperino"): + treg.register_op('fake_op', _autodiscover_raise) + + assert 'fake_op' not in treg._op_auto_map + + # check op with no autodiscovery + treg.register_op('lol', exact=True) + lol_type_map = treg.get_type_map('lol') + assert all([v is False for v in lol_type_map.values()]) + + # check op reregistration, this time not exact + assert not treg._op_type_tree.get('lol') + treg.register_op('lol', exact=False) + assert treg._op_type_tree.get('lol') + + + def _autodiscover_faulty_return(type_obj): + return 'hideeho' + + with pytest.raises(TypeError, match="hideeho"): + treg.register_op('fake_op', _autodiscover_faulty_return) + + def _autodiscover_sneaky(type_obj): + # works with default registrations, but fails later on sets and frozensets + if type_obj is set: + return 'this should have been False or a callable, but was intentionally a string' + if type_obj is frozenset: + raise ValueError('this should have been False or a callable, but was intentionally a ValueError') + return False + + treg.register_op('sneak', _autodiscover_sneaky) + + with pytest.raises(TypeError, match="intentionally a string"): + treg.register(set) + with pytest.raises(TypeError, match="intentionally a ValueError"): + treg.register(frozenset) + + return + + +def test_reregister_type(): + treg = TargetRegistry() + + class NewType: + pass + + treg.register(NewType, op=lambda obj: obj) + + obj = NewType() + handler = treg.get_handler('op', obj) + + assert handler(obj) == obj + + # assert no change in reregistering same + treg.register(NewType, op=lambda obj: obj) + handler = treg.get_handler('op', obj) + assert handler(obj) == obj + + # assert change in reregistering new + treg.register(NewType, op=lambda obj: obj.__class__.__name__) + handler = treg.get_handler('op', obj) + assert handler(obj) == 'NewType' diff --git a/venv/lib/python3.10/site-packages/glom/test/test_tutorial.py b/venv/lib/python3.10/site-packages/glom/test/test_tutorial.py new file mode 100644 index 0000000000000000000000000000000000000000..949d9482d2c7fdba90e723fb5179b523278b3883 --- /dev/null +++ b/venv/lib/python3.10/site-packages/glom/test/test_tutorial.py @@ -0,0 +1,19 @@ +from glom import glom, tutorial +from glom.tutorial import Contact, Email + +def test_tutorial_data(): + assert 4 <= len(tutorial.CONTACTS) < 10 + + +def test_tutorial(): + target = {'a': {'b': {'c': 'd'}}} + + val = target['a']['b']['c'] + + res = glom(target, 'a.b.c') + + assert res == val + + contact = Contact('Julian', emails=[Email('julian@sunnyvaletrailerpark.info')]) + contact.save() + assert Contact.objects.get(contact_id=contact.id) is contact diff --git a/venv/lib/python3.10/site-packages/glom/tutorial.py b/venv/lib/python3.10/site-packages/glom/tutorial.py new file mode 100644 index 0000000000000000000000000000000000000000..514035ca232326e262d4a164b0a2c98b5c6188f1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/glom/tutorial.py @@ -0,0 +1,513 @@ +"""\ + +.. note:: + + glom's tutorial is a runnable module, feel free to run ``pip + install glom`` and ``from glom.tutorial import *`` in the Python + REPL to glom along. Or `try it in your browser here + `_ or in the + embedded REPLs below! + +Dealing with Data +================= + +Every application deals with data, and these days, even the simplest +applications deal with rich, heavily-nested data. + +What does nested data look like? In its most basic form:: + + >>> data = {'a': {'b': {'c': 'd'}}} + >>> data['a']['b']['c'] + 'd' + +Pretty simple right? On a good day, it certainly can be. But other +days, a value might not be set:: + + >>> data2 = { + ... 'a': { + ... 'b': None + ... } + ... } + >>> data2['a']['b']['c'] + Traceback (most recent call last): + ... + TypeError: 'NoneType' object is not subscriptable + +Well that's no good. We didn't get our value. We got a TypeError, a +type of error that doesn't help us at all. The error message doesn't +even tell us which access failed. If ``data2`` had been passed to us, +we wouldn't know if ``'a'``, ``'b'``, or ``'c'`` had been set to +``None``. + +If only there were a more semantically powerful accessor. + +.. _access-granted: + +Accessing Nested Data +===================== +*AKA "Access Granted"* + +After years of research and countless iterations, the glom team landed +on this simple construct:: + + >>> glom(data, 'a.b.c') + 'd' + +Well that's short, and reads fine, but what about in the error case? + + >>> glom(data2, 'a.b.c') + Traceback (most recent call last): + ... + PathAccessError: could not access 'c', index 2 in path Path('a', 'b', 'c'), got error: ... + +That's more like it! We have a function that can give us our data, or +give us an error message we can read, understand, and act upon. + +.. seealso:: + + For more on glom's error messages, see :doc:`debugging`. + +Interactive Deep Get +-------------------- + +.. raw:: html + + + + +And would you believe this "deep access" example doesn't even scratch +the surface of the tip of the iceberg? Welcome to glom. + +Going Beyond Access +=================== + +To start out, let's introduce some basic terminology: + +- *target* is our data, be it a dict, list, or any other object +- *spec* is what we want *output* to be + +With ``output = glom(target, spec)`` committed to memory, we're ready for some new requirements. + +Let's follow some astronomers on their journey exploring the solar system. + + >>> target = { + ... 'galaxy': { + ... 'system': { + ... 'planet': 'jupiter' + ... } + ... } + ... } + >>> spec = 'galaxy.system.planet' + >>> glom(target, spec) + 'jupiter' + +Our astronomers want to focus in on the Solar system, and represent planets as a list. +Let's restructure the data to make a list of names: + + >>> target = { + ... 'system': { + ... 'planets': [ + ... {'name': 'earth'}, + ... {'name': 'jupiter'} + ... ] + ... } + ... } + >>> glom(target, ('system.planets', ['name'])) + ['earth', 'jupiter'] + +And let's say we want to capture a parallel list of moon counts with the names as well: + + >>> target = { + ... 'system': { + ... 'planets': [ + ... {'name': 'earth', 'moons': 1}, + ... {'name': 'jupiter', 'moons': 69} + ... ] + ... } + ... } + >>> spec = { + ... 'names': ('system.planets', ['name']), + ... 'moons': ('system.planets', ['moons']) + ... } + >>> pprint(glom(target, spec)) + {'moons': [1, 69], 'names': ['earth', 'jupiter']} + +We can react to changing data requirements as fast as the data itself can change, naturally restructuring our results, +despite the input's nested nature. Like a list comprehension, but for nested data, our code mirrors our output. + +Handling Nested Lists +===================== +In the example above we introduced a new wrinkle: the target for ``planets`` has multiple +entries stored in a list. Previously our targets were all nested dictionaries. + +To handle this we use a new *spec* pattern: ``(path, [subpath])``. In this pattern ``path`` is the path +to the list, and ``subpath`` is the path within each element of the list. What's that? You need to handle +lists within lists (within lists ...)? Then just repeat the pattern, replacing ``subpath`` with another +``(path, [subpath])`` tuple. For example, say we have information about each planet's moons like so: + + >>> target = { + ... 'system': { + ... 'planets': [ + ... { + ... 'name': 'earth', + ... 'moons': [ + ... {'name': 'luna'} + ... ] + ... }, + ... { + ... 'name': 'jupiter', + ... 'moons': [ + ... {'name': 'io'}, + ... {'name': 'europa'} + ... ] + ... } + ... ] + ... } + ... } + +We can get the names of each moon from our nested lists by nesting our subpath specs: + + >>> spec = { + ... 'planet_names': ('system.planets', ['name']), + ... 'moon_names': ('system.planets', [('moons', ['name'])]) + ... } + >>> pprint(glom(target, spec)) + {'moon_names': [['luna'], ['io', 'europa']], 'planet_names': ['earth', 'jupiter']} + +Changing Requirements +===================== + +Unfortunately, data in the real world is messy. You might be expecting a certain format and end up getting something +completely different. No worries, glom to the rescue. + +**Coalesce** is a glom construct that allows you to specify fallback behavior for a list of subspecs. +Subspecs are passed as positional arguments, while defaults can be set using keyword arguments. + +Let's say our astronomers recently got a new update in their systems, and sometimes ``system`` will contain +``dwarf_planets`` instead of ``planets``. + +To handle this, we can define the ``dwarf_planets`` subspec as a Coalesce fallback. + + >>> from glom import Coalesce + >>> target = { + ... 'system': { + ... 'planets': [ + ... {'name': 'earth', 'moons': 1}, + ... {'name': 'jupiter', 'moons': 69} + ... ] + ... } + ... } + >>> spec = { + ... 'planets': (Coalesce('system.planets', 'system.dwarf_planets'), ['name']), + ... 'moons': (Coalesce('system.planets', 'system.dwarf_planets'), ['moons']) + ... } + >>> pprint(glom(target, spec)) + {'moons': [1, 69], 'planets': ['earth', 'jupiter']} + +You can see here we get the expected results, but say our target changes... + + >>> target = { + ... 'system': { + ... 'dwarf_planets': [ + ... {'name': 'pluto', 'moons': 5}, + ... {'name': 'ceres', 'moons': 0} + ... ] + ... } + ... } + >>> pprint(glom(target, spec)) + {'moons': [5, 0], 'planets': ['pluto', 'ceres']} + +Voila, the target can still be parsed and we can elegantly handle changes in our data formats. + +Data-Driven Assignment +====================== + +Quite often APIs deliver data in dictionaries without constant key values. +They use parts of the data itself as a key. This we call data-driven assignment. + +The following example shows you a way to handle this situation. +It extracts the moon count from a dictionary that has the planet names as a key. + + >>> from glom import glom, T, Merge, Iter, Coalesce + >>> target = { + ... "pluto": {"moons": 6, "population": None}, + ... "venus": {"population": {"aliens": 5}}, + ... "earth": {"moons": 1, "population": {"humans": 7700000000, "aliens": 1}}, + ... } + >>> spec = { + ... "moons": ( + ... T.items(), + ... Iter({T[0]: (T[1], Coalesce("moons", default=0))}), + ... Merge(), + ... ) + ... } + >>> pprint(glom(target, spec)) + {'moons': {'earth': 1, 'pluto': 6, 'venus': 0}} + +Don't worry if you do not fully understand how this works at this +point. If you would like to learn more, look up :class:`~glom.Iter()`, +:data:`~glom.T`, or :class:`~glom.Merge` in the glom API reference. + +True Python Native +================== + +Most other implementations are limited to a particular data format or pure model, be it jmespath or XPath/XSLT. +glom makes no such sacrifices of practicality, harnessing the full power of Python itself. + +Going back to our example, let's say we wanted to get an aggregate moon count: + + >>> target = { + ... 'system': { + ... 'planets': [ + ... {'name': 'earth', 'moons': 1}, + ... {'name': 'jupiter', 'moons': 69} + ... ] + ... } + ... } + >>> pprint(glom(target, {'moon_count': ('system.planets', ['moons'], sum)})) + {'moon_count': 70} + +With glom, you have full access to Python at any given moment. +Pass values to functions, whether built-in, imported, or defined inline with lambda. + +Interactive Planetary Templating +-------------------------------- + +.. raw:: html + + + + +Practical Production Use +======================== +*AKA "Point of Contact"* + +glom is a practical tool for production use. To best demonstrate how +you can use it, we'll be building an API response. We're implementing +a Contacts web service, like an address book, but backed by an +ORM/database and compatible with web and mobile frontends. + +Let's create a Contact to familiarize ourselves with our test data: +pri + >>> from glom.tutorial import * # import the tutorial module members + >>> contact = Contact('Julian', + ... emails=[Email(email='jlahey@svtp.info')], + ... location='Canada') + >>> contact.save() + >>> contact.primary_email + Email(id=5, email='jlahey@svtp.info', email_type='personal') + >>> contact.add_date + datetime.datetime(...) + >>> contact.id + 5 + +As you can see, the Contact object has fields for ``primary_email``, +defaulting to the first email in the email list, and ``add_date``, to +track the date the contact was added. And as the unique, +autoincrementing ``id`` suggests, there appear to be a few other +contacts already in our system. + + >>> len(Contact.objects.all()) + 5 + +Sure enough, we've got a little address book going here. But right now +it consists of plain Python objects, not very API friendly: + + >>> json.dumps(Contact.objects.all()) + Traceback (most recent call last): + ... + TypeError: Contact(id=1, name='Kurt', ...) ... is not JSON serializable + +But at least we know our data, so let's get to building the API +response with glom. + +First, let's set our source object, conventionally named *target*: + +>>> target = Contact.objects.all() # here we could do filtering, etc. + +Next, let's specify the format of our result. Remember, the processing +is not happening here, this is just declaring the format. We'll be +going over the specifics of what each line does after we get our +results. + +>>> spec = {'results': [{'id': 'id', +... 'name': 'name', +... 'add_date': ('add_date', str), +... 'emails': ('emails', [{'id': 'id', +... 'email': 'email', +... 'type': 'email_type'}]), +... 'primary_email': Coalesce('primary_email.email', default=None), +... 'pref_name': Coalesce('pref_name', 'name', skip='', default=''), +... 'detail': Coalesce('company', +... 'location', +... ('add_date.year', str), +... skip='', default='')}]} + + +With *target* and *spec* in hand, we're ready to glom, build our +response, and take a look the final json-serialized form: + +>>> resp = glom(target, spec) +>>> print(json.dumps(resp, indent=2, sort_keys=True)) +{ + "results": [ + { + "add_date": "20...", + "detail": "Mountain View", + "emails": [ + { + "email": "kurt@example.com", + "id": 1, + "type": "personal" + } + ], + "id": 1, + "name": "Kurt", + "pref_name": "Kurt", + "primary_email": "kurt@example.com" + }, +... +} + +As we can see, our response looks a lot like our glom +specification. This type of WYSIWYG code is one of glom's most +important features. After we've appreciated that simple fact, let's +look at it line by line. + +Understanding the Specification +=============================== + +For ``id`` and ``name``, we're just doing simple copy-overs. For +``add_date``, we use a tuple to denote repeated gloms; we access +``add_date`` and pass the result to ``str`` to convert it to a string. + +For emails we need to serialize a list of subobjects. Good news, glom +subgloms just fine, too. We use a tuple to access ``emails``, iterate +over that list, and from each we copy over ``id`` and ``email``. Note +how ``email_type`` is easily remapped to simply ``type``. + +For ``primary_email`` we see our first usage of glom's ``Coalesce`` +feature. Much like SQL's keyword of the same name, ``Coalesce`` +returns the result of the first spec that returns a valid value. In +our case, ``primary_email`` can be None, so a further access of +``primary_email.email`` would, outside of glom, result in an +AttributeError or TypeError like the one we described before the +Contact example. Inside of a glom ``Coalesce``, exceptions are caught +and we move on to the next spec. glom raises a +:class:`~glom.CoalesceError` when no specs match, so we use +``default`` to tell it to return None instead. + +Some Contacts have nicknames or other names they prefer to go by, so +for ``pref_name``, we want to return the stored ``pref_name``, or fall +back to the normal name. Again, we use :class:`~glom.Coalesce`, but +this time we tell it not only to ignore the default +:exc:`~glom.GlomError` exceptions, but also ignore empty string +values, and finally default to empty string if all specs result in +empty strings or :exc:`~glom.GlomError`. + +And finally, for our last field, ``detail``, we want to conjure up a +bit of info that'll help jog the user's memory. We're going to include +the location, or company, or year the contact was added. You can see +an example of this feature as implemented by GitHub, here: +https://github.com/mahmoud/glom/stargazers + +Interactive Contact Management +------------------------------ + +.. raw:: html + + + +Conclusion +========== + +We've seen a crash course in how glom can tame your data and act as a +powerful source of code coherency. glom transforms not only your data, +but also your code, bringing it in line with the data itself. + +glom tamed our nested data, avoiding tedious, bug-prone lines, +replacing what would have been large sections with code that was +declarative, but flexible, an ideal balance for maintainability. + +""" +import json +import datetime +from itertools import count +from collections import OrderedDict +from pprint import pprint +import attr +from attr import Factory + +from glom import glom, Coalesce + +_email_autoincrement = lambda c=count(1): next(c) +_contact_autoincrement = lambda c=count(1): next(c) + + +def _default_email(contact): + return contact.emails[0] if contact.emails else None + + +@attr.s +class ContactManager: + """This type implements an oversimplified storage manager, wrapping an + OrderedDict instead of a database. Those familiar with Django and + SQLAlchemy will recognize the pattern being sketched here. + """ + def all(self): + return list(CONTACTS.values()) + + def save(self, contact): + CONTACTS[contact.id] = contact + + def get(self, contact_id): + return CONTACTS.get(contact_id) + + + +@attr.s +class Contact: + id = attr.ib(Factory(_contact_autoincrement), init=False) + name = attr.ib('') + pref_name = attr.ib('') + + emails = attr.ib(Factory(list)) + primary_email = attr.ib(Factory(_default_email, takes_self=True)) + + company = attr.ib('') + location = attr.ib('') + add_date = attr.ib(Factory(datetime.datetime.now)) + + # The next two parts are part of the Django-esque Manager pattern, + # mentioned in the ContactManager docstring + objects = ContactManager() + + def save(self): + self.objects.save(self) + + +@attr.s +class Email: + id = attr.ib(Factory(_email_autoincrement), init=False) + email = attr.ib('') + email_type = attr.ib('personal') + + +CONTACTS = OrderedDict() +_add = ContactManager().save + +_add(Contact('Kurt', + emails=[Email('kurt@example.com')], + location='Mountain View')) + +_add(Contact('Sean', + emails=[Email('seanboy@example.com')], + location='San Jose', + company='D & D Mastering')) + +_add(Contact('Matt', + emails=[Email('mixtape@homemakelabs.com', email_type='work'), + Email('matt@example.com')], + company='HomeMake Labs')) + +_add(Contact('Julian', location='Sunnyvale Trailer Park')) diff --git a/venv/lib/python3.10/site-packages/google_cloud_core-2.4.3.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/google_cloud_core-2.4.3.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/venv/lib/python3.10/site-packages/google_cloud_core-2.4.3.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/lib/python3.10/site-packages/google_cloud_core-2.4.3.dist-info/LICENSE b/venv/lib/python3.10/site-packages/google_cloud_core-2.4.3.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/venv/lib/python3.10/site-packages/google_cloud_core-2.4.3.dist-info/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/venv/lib/python3.10/site-packages/google_cloud_core-2.4.3.dist-info/METADATA b/venv/lib/python3.10/site-packages/google_cloud_core-2.4.3.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..dd8544e0d83c8f474fb8c4860807b6c27591293f --- /dev/null +++ b/venv/lib/python3.10/site-packages/google_cloud_core-2.4.3.dist-info/METADATA @@ -0,0 +1,75 @@ +Metadata-Version: 2.1 +Name: google-cloud-core +Version: 2.4.3 +Summary: Google Cloud API client core library +Home-page: https://github.com/googleapis/python-cloud-core +Author: Google LLC +Author-email: googleapis-packages@google.com +License: Apache 2.0 +Platform: Posix; MacOS X; Windows +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.7 +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: Programming Language :: Python :: 3.13 +Classifier: Operating System :: OS Independent +Classifier: Topic :: Internet +Requires-Python: >=3.7 +License-File: LICENSE +Requires-Dist: google-api-core!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.0,<3.0.0dev,>=1.31.6 +Requires-Dist: google-auth<3.0dev,>=1.25.0 +Requires-Dist: importlib-metadata>1.0.0; python_version < "3.8" +Provides-Extra: grpc +Requires-Dist: grpcio<2.0dev,>=1.38.0; extra == "grpc" +Requires-Dist: grpcio-status<2.0.dev0,>=1.38.0; extra == "grpc" + +Core Helpers for Google Cloud Python Client Library +=================================================== + +|pypi| |versions| + +This library is not meant to stand-alone. Instead it defines +common helpers (e.g. base ``Client`` classes) used by all of the +``google-cloud-*`` packages. + + +- `Documentation`_ + +.. |pypi| image:: https://img.shields.io/pypi/v/google-cloud-core.svg + :target: https://pypi.org/project/google-cloud-core/ +.. |versions| image:: https://img.shields.io/pypi/pyversions/google-cloud-core.svg + :target: https://pypi.org/project/google-cloud-core/ +.. _Documentation: https://cloud.google.com/python/docs/reference/google-cloud-core/latest + +Quick Start +----------- + +.. code-block:: console + + $ pip install --upgrade google-cloud-core + +For more information on setting up your Python development environment, +such as installing ``pip`` and ``virtualenv`` on your system, please refer +to `Python Development Environment Setup Guide`_ for Google Cloud Platform. + +.. _Python Development Environment Setup Guide: https://cloud.google.com/python/setup + + +Supported Python Versions +------------------------- +Python >= 3.7 + +Unsupported Python Versions +--------------------------- +Python == 2.7: the last version of this library which supported Python 2.7 +is ``google.cloud.core 1.7.2``. + +Python == 3.6: the last version of this library which supported Python 3.6 +is ``google.cloud.core 2.3.1``. diff --git a/venv/lib/python3.10/site-packages/google_cloud_core-2.4.3.dist-info/RECORD b/venv/lib/python3.10/site-packages/google_cloud_core-2.4.3.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..301e1486a023f6029a6d4f75c7139d05184d3e03 --- /dev/null +++ b/venv/lib/python3.10/site-packages/google_cloud_core-2.4.3.dist-info/RECORD @@ -0,0 +1,32 @@ +google/cloud/__pycache__/version.cpython-310.pyc,, +google/cloud/_helpers/__init__.py,sha256=7aFMb13R-zqSPwjYJvI7JL5kzDXJAA-KyWYGFuBLWeQ,18644 +google/cloud/_helpers/__pycache__/__init__.cpython-310.pyc,, +google/cloud/_helpers/py.typed,sha256=0XXSft34lxBaTiAPy-Gu8ejOOFXoAskbySm9m2Uq7UY,63 +google/cloud/_http/__init__.py,sha256=p3Fx59gfYYVnS1-8RxTIG6f8Z6NIDNjySQzR55JdvUg,16649 +google/cloud/_http/__pycache__/__init__.cpython-310.pyc,, +google/cloud/_http/py.typed,sha256=0XXSft34lxBaTiAPy-Gu8ejOOFXoAskbySm9m2Uq7UY,63 +google/cloud/_testing/__init__.py,sha256=ezhO0xNaEnpMaH0eB3Qi10TLgQFvk7GKoztxD0AVLW0,3397 +google/cloud/_testing/__pycache__/__init__.cpython-310.pyc,, +google/cloud/_testing/py.typed,sha256=0XXSft34lxBaTiAPy-Gu8ejOOFXoAskbySm9m2Uq7UY,63 +google/cloud/client/__init__.py,sha256=nMeY7ZTY5vJi0biQ2-5PRVI72-Or79daf4L65oV65ZQ,12934 +google/cloud/client/__pycache__/__init__.cpython-310.pyc,, +google/cloud/client/py.typed,sha256=0XXSft34lxBaTiAPy-Gu8ejOOFXoAskbySm9m2Uq7UY,63 +google/cloud/environment_vars/__init__.py,sha256=lCe2EyQjeJO2ImbrSR23Cj2XpwGKFFy1xCZuQo2DHEo,1318 +google/cloud/environment_vars/__pycache__/__init__.cpython-310.pyc,, +google/cloud/environment_vars/py.typed,sha256=0XXSft34lxBaTiAPy-Gu8ejOOFXoAskbySm9m2Uq7UY,63 +google/cloud/exceptions/__init__.py,sha256=pyCO5lyFO_99DTwUsJqolO0iPOoFDhKG_ebTIfsoI6M,2199 +google/cloud/exceptions/__pycache__/__init__.cpython-310.pyc,, +google/cloud/exceptions/py.typed,sha256=0XXSft34lxBaTiAPy-Gu8ejOOFXoAskbySm9m2Uq7UY,63 +google/cloud/obsolete/__init__.py,sha256=MeXpOiQ6BOYjkIeIEGfL59ytVy_NX1kcnbCFQcUUqsw,1479 +google/cloud/obsolete/__pycache__/__init__.cpython-310.pyc,, +google/cloud/obsolete/py.typed,sha256=0XXSft34lxBaTiAPy-Gu8ejOOFXoAskbySm9m2Uq7UY,63 +google/cloud/operation/__init__.py,sha256=SD9exHvTtJm6cvzn8FOuz3y59fp9drpk_hBb2Ok1l-A,9083 +google/cloud/operation/__pycache__/__init__.cpython-310.pyc,, +google/cloud/operation/py.typed,sha256=0XXSft34lxBaTiAPy-Gu8ejOOFXoAskbySm9m2Uq7UY,63 +google/cloud/version.py,sha256=9LRH53KsMJr0Yxzz3Rfkw4lTIMjb9PRvWbtDB7L51Ts,597 +google_cloud_core-2.4.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +google_cloud_core-2.4.3.dist-info/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358 +google_cloud_core-2.4.3.dist-info/METADATA,sha256=z7MdMCmRg0XBMjpuwDPavKqzWhiwhJ61qfhdVC0-bJw,2749 +google_cloud_core-2.4.3.dist-info/RECORD,, +google_cloud_core-2.4.3.dist-info/WHEEL,sha256=OpXWERl2xLPRHTvd2ZXo_iluPEQd8uSbYkJ53NAER_Y,109 +google_cloud_core-2.4.3.dist-info/top_level.txt,sha256=_1QvSJIhFAGfxb79D6DhB7SUw2X6T4rwnz_LLrbcD3c,7 diff --git a/venv/lib/python3.10/site-packages/google_cloud_core-2.4.3.dist-info/WHEEL b/venv/lib/python3.10/site-packages/google_cloud_core-2.4.3.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..ee810efb31c37815a70827942976bfcba5b5d2bc --- /dev/null +++ b/venv/lib/python3.10/site-packages/google_cloud_core-2.4.3.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: setuptools (75.3.0) +Root-Is-Purelib: true +Tag: py2-none-any +Tag: py3-none-any + diff --git a/venv/lib/python3.10/site-packages/google_cloud_core-2.4.3.dist-info/top_level.txt b/venv/lib/python3.10/site-packages/google_cloud_core-2.4.3.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..cb429113e0f9a73019fd799e8052093fea7f0c8b --- /dev/null +++ b/venv/lib/python3.10/site-packages/google_cloud_core-2.4.3.dist-info/top_level.txt @@ -0,0 +1 @@ +google diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/__about__.py b/venv/lib/python3.10/site-packages/lightning_utilities/__about__.py new file mode 100644 index 0000000000000000000000000000000000000000..a9ede25d0503e5746e73e8d5d1d37ad9a0e685fb --- /dev/null +++ b/venv/lib/python3.10/site-packages/lightning_utilities/__about__.py @@ -0,0 +1,23 @@ +import time + +__version__ = "0.15.2" +__author__ = "Lightning AI et al." +__author_email__ = "developer@lightning.ai" +__license__ = "Apache-2.0" +__copyright__ = f"Copyright (c) 2022-{time.strftime('%Y')}, {__author__}." +__homepage__ = "https://github.com/Lightning-AI/utilities" +__docs__ = "Lightning toolbox for across the our ecosystem." +__long_doc__ = """ +This package allows for sharing GitHub workflows, CI/CD assistance actions, and Python utilities across the Lightning +ecosystem - projects. +""" + +__all__ = [ + "__author__", + "__author_email__", + "__copyright__", + "__docs__", + "__homepage__", + "__license__", + "__version__", +] diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/__init__.py b/venv/lib/python3.10/site-packages/lightning_utilities/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..48e39c6df1de65ade7fc3aa72f00823e3fecd0a3 --- /dev/null +++ b/venv/lib/python3.10/site-packages/lightning_utilities/__init__.py @@ -0,0 +1,23 @@ +"""Root package info.""" + +import os + +from lightning_utilities.__about__ import * # noqa: F403 +from lightning_utilities.core.apply_func import apply_to_collection +from lightning_utilities.core.enums import StrEnum +from lightning_utilities.core.imports import compare_version, module_available +from lightning_utilities.core.overrides import is_overridden +from lightning_utilities.core.rank_zero import WarningCache + +_PACKAGE_ROOT = os.path.dirname(__file__) +_PROJECT_ROOT = os.path.dirname(_PACKAGE_ROOT) + + +__all__ = [ + "StrEnum", + "WarningCache", + "apply_to_collection", + "compare_version", + "is_overridden", + "module_available", +] diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/__pycache__/__about__.cpython-310.pyc b/venv/lib/python3.10/site-packages/lightning_utilities/__pycache__/__about__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05650bd1a4a6c9e7f5ddb2b52ef99a7b77983c7c Binary files /dev/null and b/venv/lib/python3.10/site-packages/lightning_utilities/__pycache__/__about__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/lightning_utilities/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ea0822bab8c3f9b8c271f533dd3f26f55d9c20a Binary files /dev/null and b/venv/lib/python3.10/site-packages/lightning_utilities/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/cli/__init__.py b/venv/lib/python3.10/site-packages/lightning_utilities/cli/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d5be9d8843cb5d54f397cff9e07d777f4729dfc6 --- /dev/null +++ b/venv/lib/python3.10/site-packages/lightning_utilities/cli/__init__.py @@ -0,0 +1 @@ +"""CLI root.""" diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/cli/__main__.py b/venv/lib/python3.10/site-packages/lightning_utilities/cli/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..47ceb6f553336f46bf320b03b035ad30926f8811 --- /dev/null +++ b/venv/lib/python3.10/site-packages/lightning_utilities/cli/__main__.py @@ -0,0 +1,39 @@ +# Copyright The Lightning AI team. +# Licensed under the Apache License, Version 2.0 (the "License"); +# http://www.apache.org/licenses/LICENSE-2.0 +# + +import lightning_utilities +from lightning_utilities.cli.dependencies import ( + prune_packages_in_requirements, + replace_oldest_version, + replace_package_in_requirements, +) + + +def _get_version() -> None: + """Prints the version of the lightning_utilities package.""" + print(lightning_utilities.__version__) + + +def main() -> None: + """CLI entry point.""" + from jsonargparse import auto_cli, set_parsing_settings + + set_parsing_settings(parse_optionals_as_positionals=True) + auto_cli( + { + "requirements": { + "_help": "Manage requirements files.", + "prune-pkgs": prune_packages_in_requirements, + "set-oldest": replace_oldest_version, + "replace-pkg": replace_package_in_requirements, + }, + "version": _get_version, + }, + as_positional=False, + ) + + +if __name__ == "__main__": + main() diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/cli/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/lightning_utilities/cli/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..18af54e920342062538c9264e5b2803c07aed9e6 Binary files /dev/null and b/venv/lib/python3.10/site-packages/lightning_utilities/cli/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/cli/__pycache__/__main__.cpython-310.pyc b/venv/lib/python3.10/site-packages/lightning_utilities/cli/__pycache__/__main__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f1708d06c48b7881cba4527130ccf5147bf2925 Binary files /dev/null and b/venv/lib/python3.10/site-packages/lightning_utilities/cli/__pycache__/__main__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/cli/__pycache__/dependencies.cpython-310.pyc b/venv/lib/python3.10/site-packages/lightning_utilities/cli/__pycache__/dependencies.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3430074112b66426a1c2e268663a48f4d5f1be92 Binary files /dev/null and b/venv/lib/python3.10/site-packages/lightning_utilities/cli/__pycache__/dependencies.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/cli/dependencies.py b/venv/lib/python3.10/site-packages/lightning_utilities/cli/dependencies.py new file mode 100644 index 0000000000000000000000000000000000000000..04c770e5efd18d449d2533e1fccf111da7991abb --- /dev/null +++ b/venv/lib/python3.10/site-packages/lightning_utilities/cli/dependencies.py @@ -0,0 +1,151 @@ +# Copyright The Lightning AI team. +# Licensed under the Apache License, Version 2.0 (the "License"); +# http://www.apache.org/licenses/LICENSE-2.0 +# +import glob +import os.path +import re +import warnings +from collections.abc import Sequence +from pprint import pprint +from typing import Union + +REQUIREMENT_ROOT = "requirements.txt" +REQUIREMENT_FILES_ALL: list = glob.glob(os.path.join("requirements", "*.txt")) +REQUIREMENT_FILES_ALL += glob.glob(os.path.join("requirements", "**", "*.txt"), recursive=True) +REQUIREMENT_FILES_ALL += glob.glob(os.path.join("**", "pyproject.toml")) +if os.path.isfile(REQUIREMENT_ROOT): + REQUIREMENT_FILES_ALL += [REQUIREMENT_ROOT] + + +def prune_packages_in_requirements( + packages: Union[str, Sequence[str]], req_files: Union[str, Sequence[str]] = REQUIREMENT_FILES_ALL +) -> None: + """Remove some packages from given requirement files.""" + if isinstance(packages, str): + packages = [packages] + if isinstance(req_files, str): + req_files = [req_files] + for req in req_files: + _prune_packages(req, packages) + + +def _prune_packages(req_file: str, packages: Sequence[str]) -> None: + """Remove some packages from given requirement files.""" + with open(req_file) as fp: + lines = fp.readlines() + + if isinstance(packages, str): + packages = [packages] + for pkg in packages: + lines = [ln for ln in lines if not ln.startswith(pkg)] + pprint(lines) + + with open(req_file, "w") as fp: + fp.writelines(lines) + + +def _replace_min_req_in_txt(req_file: str) -> None: + with open(req_file) as fopen: + req = fopen.read().replace(">=", "==") + with open(req_file, "w") as fw: + fw.write(req) + + +def _replace_min_req_in_pyproject_toml(proj_file: str = "pyproject.toml") -> None: + """Replace all `>=` with `==` in the standard pyproject.toml file in [project.dependencies].""" + import tomlkit + + # Load and parse the existing pyproject.toml + with open(proj_file, encoding="utf-8") as f: + content = f.read() + doc = tomlkit.parse(content) + + # todo: consider also replace extras in [dependency-groups] -> extras = [...] + deps = doc.get("project", {}).get("dependencies") + if not deps: + return + + # Replace '>=version' with '==version' in each dependency + for i, req in enumerate(deps): + # Simple string value + deps[i] = req.replace(">=", "==") + + # Dump back out, preserving layout + with open(proj_file, "w", encoding="utf-8") as f: + f.write(tomlkit.dumps(doc)) + + +def replace_oldest_version(req_files: Union[str, Sequence[str]] = REQUIREMENT_FILES_ALL) -> None: + """Replace the min package version by fixed one.""" + if isinstance(req_files, str): + req_files = [req_files] + for fname in req_files: + if fname.endswith(".txt"): + _replace_min_req_in_txt(fname) + elif os.path.basename(fname) == "pyproject.toml": + _replace_min_req_in_pyproject_toml(fname) + else: + warnings.warn( + "Only *.txt with plain list of requirements or standard pyproject.toml are supported." + f"Provided '{fname}' is not supported.", + UserWarning, + stacklevel=2, + ) + + +def _replace_package_name_in_txt(req_file: str, old_package: str, new_package: str) -> None: + """Replace one package by another with the same version in a given requirement file.""" + # load file + with open(req_file) as fopen: + requirements = fopen.readlines() + # replace all occurrences + for i, req in enumerate(requirements): + requirements[i] = re.sub(r"^" + re.escape(old_package) + r"(?=[ <=>#]|$)", new_package, req) + # save file + with open(req_file, "w") as fw: + fw.writelines(requirements) + + +def _replace_package_name_in_pyproject_toml(proj_file: str, old_package: str, new_package: str) -> None: + """Replace one package by another with the same version in the standard pyproject.toml file.""" + import tomlkit + + # Load and parse the existing pyproject.toml + with open(proj_file, encoding="utf-8") as f: + content = f.read() + doc = tomlkit.parse(content) + + # todo: consider also replace extras in [dependency-groups] -> extras = [...] + deps = doc.get("project", {}).get("dependencies") + if not deps: + return + + # Replace '>=version' with '==version' in each dependency + for i, req in enumerate(deps): + # Simple string value + deps[i] = re.sub(r"^" + re.escape(old_package) + r"(?=[ <=>]|$)", new_package, req) + + # Dump back out, preserving layout + with open(proj_file, "w", encoding="utf-8") as f: + f.write(tomlkit.dumps(doc)) + + +def replace_package_in_requirements( + old_package: str, new_package: str, req_files: Union[str, Sequence[str]] = REQUIREMENT_FILES_ALL +) -> None: + """Replace one package by another with same version in given requirement files.""" + if isinstance(req_files, str): + req_files = [req_files] + for fname in req_files: + if fname.endswith(".txt"): + _replace_package_name_in_txt(fname, old_package, new_package) + elif os.path.basename(fname) == "pyproject.toml": + _replace_package_name_in_pyproject_toml(fname, old_package, new_package) + else: + warnings.warn( + "Only *.txt with plain list of requirements or standard pyproject.toml are supported." + f"Provided '{fname}' is not supported.", + UserWarning, + stacklevel=2, + ) diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/core/__init__.py b/venv/lib/python3.10/site-packages/lightning_utilities/core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..dd046496fa9df05e4ebf5ea8802287f0fe609482 --- /dev/null +++ b/venv/lib/python3.10/site-packages/lightning_utilities/core/__init__.py @@ -0,0 +1,16 @@ +"""Core utilities.""" + +from lightning_utilities.core.apply_func import apply_to_collection +from lightning_utilities.core.enums import StrEnum +from lightning_utilities.core.imports import compare_version, module_available +from lightning_utilities.core.overrides import is_overridden +from lightning_utilities.core.rank_zero import WarningCache + +__all__ = [ + "StrEnum", + "WarningCache", + "apply_to_collection", + "compare_version", + "is_overridden", + "module_available", +] diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/core/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/lightning_utilities/core/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..798dd9483224f987488af6b0f344429eaff9f16a Binary files /dev/null and b/venv/lib/python3.10/site-packages/lightning_utilities/core/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/core/__pycache__/apply_func.cpython-310.pyc b/venv/lib/python3.10/site-packages/lightning_utilities/core/__pycache__/apply_func.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2de00b508da0f8ef34dfbeb2bd2ce4b0b1c5a31f Binary files /dev/null and b/venv/lib/python3.10/site-packages/lightning_utilities/core/__pycache__/apply_func.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/core/__pycache__/enums.cpython-310.pyc b/venv/lib/python3.10/site-packages/lightning_utilities/core/__pycache__/enums.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..45cc51f1c3952672a074bb559ddceaa4b39fc7b0 Binary files /dev/null and b/venv/lib/python3.10/site-packages/lightning_utilities/core/__pycache__/enums.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/core/__pycache__/imports.cpython-310.pyc b/venv/lib/python3.10/site-packages/lightning_utilities/core/__pycache__/imports.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b027fb64955d02082f1c6692cdbee40abcea952 Binary files /dev/null and b/venv/lib/python3.10/site-packages/lightning_utilities/core/__pycache__/imports.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/core/__pycache__/inheritance.cpython-310.pyc b/venv/lib/python3.10/site-packages/lightning_utilities/core/__pycache__/inheritance.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2bab501b0910321895be272a1e7db92fa8ec72fb Binary files /dev/null and b/venv/lib/python3.10/site-packages/lightning_utilities/core/__pycache__/inheritance.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/core/__pycache__/overrides.cpython-310.pyc b/venv/lib/python3.10/site-packages/lightning_utilities/core/__pycache__/overrides.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f685f643bfbee8d2c6b8a33240933a0a84273ce2 Binary files /dev/null and b/venv/lib/python3.10/site-packages/lightning_utilities/core/__pycache__/overrides.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/core/__pycache__/rank_zero.cpython-310.pyc b/venv/lib/python3.10/site-packages/lightning_utilities/core/__pycache__/rank_zero.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b3eecf37e9703b5d62b8f45a04085ed66f36625 Binary files /dev/null and b/venv/lib/python3.10/site-packages/lightning_utilities/core/__pycache__/rank_zero.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/core/apply_func.py b/venv/lib/python3.10/site-packages/lightning_utilities/core/apply_func.py new file mode 100644 index 0000000000000000000000000000000000000000..bbcc545ef74d455db5169c62d967b70d8279403f --- /dev/null +++ b/venv/lib/python3.10/site-packages/lightning_utilities/core/apply_func.py @@ -0,0 +1,299 @@ +# Copyright The Lightning AI team. +# Licensed under the Apache License, Version 2.0 (the "License"); +# http://www.apache.org/licenses/LICENSE-2.0 +# +import dataclasses +from collections import OrderedDict, defaultdict +from collections.abc import Mapping, Sequence +from copy import deepcopy +from functools import cached_property +from typing import Any, Callable, Optional, Union + + +def is_namedtuple(obj: object) -> bool: + """Check if object is type nametuple.""" + # https://github.com/pytorch/pytorch/blob/v1.8.1/torch/nn/parallel/scatter_gather.py#L4-L8 + return isinstance(obj, tuple) and hasattr(obj, "_asdict") and hasattr(obj, "_fields") + + +def is_dataclass_instance(obj: object) -> bool: + """Check if object is dataclass.""" + # https://docs.python.org/3/library/dataclasses.html#module-level-decorators-classes-and-functions + return dataclasses.is_dataclass(obj) and not isinstance(obj, type) + + +def apply_to_collection( + data: Any, + dtype: Union[type, Any, tuple[Union[type, Any]]], + function: Callable, + *args: Any, + wrong_dtype: Optional[Union[type, tuple[type, ...]]] = None, + include_none: bool = True, + allow_frozen: bool = False, + **kwargs: Any, +) -> Any: + """Recursively applies a function to all elements of a certain dtype. + + Args: + data: the collection to apply the function to + dtype: the given function will be applied to all elements of this dtype + function: the function to apply + *args: positional arguments (will be forwarded to calls of ``function``) + wrong_dtype: the given function won't be applied if this type is specified and the given collections + is of the ``wrong_dtype`` even if it is of type ``dtype`` + include_none: Whether to include an element if the output of ``function`` is ``None``. + allow_frozen: Whether not to error upon encountering a frozen dataclass instance. + **kwargs: keyword arguments (will be forwarded to calls of ``function``) + + Returns: + The resulting collection + + """ + if include_none is False or wrong_dtype is not None or allow_frozen is True: + # not worth implementing these on the fast path: go with the slower option + return _apply_to_collection_slow( + data, + dtype, + function, + *args, + wrong_dtype=wrong_dtype, + include_none=include_none, + allow_frozen=allow_frozen, + **kwargs, + ) + # fast path for the most common cases: + if isinstance(data, dtype): # single element + return function(data, *args, **kwargs) + if data.__class__ is list and all(isinstance(x, dtype) for x in data): # 1d homogeneous list + return [function(x, *args, **kwargs) for x in data] + if data.__class__ is tuple and all(isinstance(x, dtype) for x in data): # 1d homogeneous tuple + return tuple(function(x, *args, **kwargs) for x in data) + if data.__class__ is dict and all(isinstance(x, dtype) for x in data.values()): # 1d homogeneous dict + return {k: function(v, *args, **kwargs) for k, v in data.items()} + # slow path for everything else + return _apply_to_collection_slow( + data, + dtype, + function, + *args, + wrong_dtype=wrong_dtype, + include_none=include_none, + allow_frozen=allow_frozen, + **kwargs, + ) + + +def _apply_to_collection_slow( + data: Any, + dtype: Union[type, Any, tuple[Union[type, Any]]], + function: Callable, + *args: Any, + wrong_dtype: Optional[Union[type, tuple[type, ...]]] = None, + include_none: bool = True, + allow_frozen: bool = False, + **kwargs: Any, +) -> Any: + # Breaking condition + if isinstance(data, dtype) and (wrong_dtype is None or not isinstance(data, wrong_dtype)): + return function(data, *args, **kwargs) + + elem_type = type(data) + + # Recursively apply to collection items + if is_dataclass_instance(data): + # make a deepcopy of the data, + # but do not deepcopy mapped fields since the computation would + # be wasted on values that likely get immediately overwritten + fields = {} + memo = {} + for field in dataclasses.fields(data): + field_value = getattr(data, field.name) + fields[field.name] = (field_value, field.init) + memo[id(field_value)] = field_value + result = deepcopy(data, memo=memo) + # apply function to each field + for field_name, (field_value, field_init) in fields.items(): + v = None + if field_init: + v = _apply_to_collection_slow( + field_value, + dtype, + function, + *args, + wrong_dtype=wrong_dtype, + include_none=include_none, + allow_frozen=allow_frozen, + **kwargs, + ) + if not field_init or (not include_none and v is None): # retain old value + v = getattr(data, field_name) + try: + setattr(result, field_name, v) + except dataclasses.FrozenInstanceError as e: + if allow_frozen: + # Quit early if we encounter a frozen data class; return `result` as is. + break + raise ValueError( + "A frozen dataclass was passed to `apply_to_collection` but this is not allowed." + ) from e + + # Explicitly resetting cached property. + for cached_name in filter( + lambda k: isinstance(getattr(type(data), k), cached_property), vars(type(data)).keys() + ): + vars(result).pop(cached_name, None) + return result + + if isinstance(data, Mapping): + out = [] + for k, v in data.items(): + v = _apply_to_collection_slow( + v, + dtype, + function, + *args, + wrong_dtype=wrong_dtype, + include_none=include_none, + allow_frozen=allow_frozen, + **kwargs, + ) + if include_none or v is not None: + out.append((k, v)) + if isinstance(data, defaultdict): + return elem_type(data.default_factory, OrderedDict(out)) + return elem_type(OrderedDict(out)) + + is_namedtuple_ = is_namedtuple(data) + is_sequence = isinstance(data, Sequence) and not isinstance(data, str) + if is_namedtuple_ or is_sequence: + out = [] + for d in data: + v = _apply_to_collection_slow( + d, + dtype, + function, + *args, + wrong_dtype=wrong_dtype, + include_none=include_none, + allow_frozen=allow_frozen, + **kwargs, + ) + if include_none or v is not None: + out.append(v) + return elem_type(*out) if is_namedtuple_ else elem_type(out) + + # data is neither of dtype, nor a collection + return data + + +def apply_to_collections( + data1: Optional[Any], + data2: Optional[Any], + dtype: Union[type, Any, tuple[Union[type, Any]]], + function: Callable, + *args: Any, + wrong_dtype: Optional[Union[type, tuple[type]]] = None, + **kwargs: Any, +) -> Any: + """Zips two collections and applies a function to their items of a certain dtype. + + Args: + data1: The first collection + data2: The second collection + dtype: the given function will be applied to all elements of this dtype + function: the function to apply + *args: positional arguments (will be forwarded to calls of ``function``) + wrong_dtype: the given function won't be applied if this type is specified and the given collections + is of the ``wrong_dtype`` even if it is of type ``dtype`` + **kwargs: keyword arguments (will be forwarded to calls of ``function``) + + Returns: + The resulting collection + + Raises: + AssertionError: + If sequence collections have different data sizes. + + """ + if data1 is None: + if data2 is None: + return None + # in case they were passed reversed + data1, data2 = data2, None + + elem_type = type(data1) + + if isinstance(data1, dtype) and data2 is not None and (wrong_dtype is None or not isinstance(data1, wrong_dtype)): + return function(data1, data2, *args, **kwargs) + + if isinstance(data1, Mapping) and data2 is not None: + # use union because we want to fail if a key does not exist in both + zipped = {k: (data1[k], data2[k]) for k in data1.keys() | data2.keys()} + return elem_type({ + k: apply_to_collections(*v, dtype, function, *args, wrong_dtype=wrong_dtype, **kwargs) + for k, v in zipped.items() + }) + + is_namedtuple_ = is_namedtuple(data1) + is_sequence = isinstance(data1, Sequence) and not isinstance(data1, str) + if (is_namedtuple_ or is_sequence) and data2 is not None: + if len(data1) != len(data2): + raise ValueError("Sequence collections have different sizes.") + out = [ + apply_to_collections(v1, v2, dtype, function, *args, wrong_dtype=wrong_dtype, **kwargs) + for v1, v2 in zip(data1, data2) + ] + return elem_type(*out) if is_namedtuple_ else elem_type(out) + + if is_dataclass_instance(data1) and data2 is not None: + if not is_dataclass_instance(data2): + raise TypeError( + "Expected inputs to be dataclasses of the same type or to have identical fields" + f" but got input 1 of type {type(data1)} and input 2 of type {type(data2)}." + ) + if not ( + len(dataclasses.fields(data1)) == len(dataclasses.fields(data2)) + and all(map(lambda f1, f2: isinstance(f1, type(f2)), dataclasses.fields(data1), dataclasses.fields(data2))) + ): + raise TypeError("Dataclasses fields do not match.") + # make a deepcopy of the data, + # but do not deepcopy mapped fields since the computation would + # be wasted on values that likely get immediately overwritten + data = [data1, data2] + fields: list[dict] = [{}, {}] + memo: dict = {} + for i in range(len(data)): + for field in dataclasses.fields(data[i]): + field_value = getattr(data[i], field.name) + fields[i][field.name] = (field_value, field.init) + if i == 0: + memo[id(field_value)] = field_value + + result = deepcopy(data1, memo=memo) + + # apply function to each field + for (field_name, (field_value1, field_init1)), (_, (field_value2, field_init2)) in zip( + fields[0].items(), fields[1].items() + ): + v = None + if field_init1 and field_init2: + v = apply_to_collections( + field_value1, + field_value2, + dtype, + function, + *args, + wrong_dtype=wrong_dtype, + **kwargs, + ) + if not field_init1 or not field_init2 or v is None: # retain old value + return apply_to_collection(data1, dtype, function, *args, wrong_dtype=wrong_dtype, **kwargs) + try: + setattr(result, field_name, v) + except dataclasses.FrozenInstanceError as e: + raise ValueError( + "A frozen dataclass was passed to `apply_to_collections` but this is not allowed." + ) from e + return result + + return apply_to_collection(data1, dtype, function, *args, wrong_dtype=wrong_dtype, **kwargs) diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/core/enums.py b/venv/lib/python3.10/site-packages/lightning_utilities/core/enums.py new file mode 100644 index 0000000000000000000000000000000000000000..945e0ef55c0a2d8ca89b2037b88632899928378f --- /dev/null +++ b/venv/lib/python3.10/site-packages/lightning_utilities/core/enums.py @@ -0,0 +1,91 @@ +# Copyright The Lightning AI team. +# Licensed under the Apache License, Version 2.0 (the "License"); +# http://www.apache.org/licenses/LICENSE-2.0 +# +import warnings +from enum import Enum +from typing import Optional + +from typing_extensions import Literal + + +class StrEnum(str, Enum): + """Type of any enumerator with allowed comparison to string invariant to cases. + + >>> class MySE(StrEnum): + ... t1 = "T-1" + ... t2 = "T-2" + >>> MySE("T-1") == MySE.t1 + True + >>> MySE.from_str("t-2", source="value") == MySE.t2 + True + >>> MySE.from_str("t-2", source="value") + + >>> MySE.from_str("t-3", source="any") + Traceback (most recent call last): + ... + ValueError: Invalid match: expected one of ['t1', 't2', 'T-1', 'T-2'], but got t-3. + + """ + + @classmethod + def from_str(cls, value: str, source: Literal["key", "value", "any"] = "key") -> "StrEnum": + """Create ``StrEnum`` from a string matching the key or value. + + Args: + value: matching string + source: compare with: + + - ``"key"``: validates only from the enum keys, typical alphanumeric with "_" + - ``"value"``: validates only from the values, could be any string + - ``"any"``: validates with any key or value, but key has priority + + Raises: + ValueError: + if requested string does not match any option based on selected source. + + """ + if source in ("key", "any"): + for enum_key in cls.__members__: + if enum_key.lower() == value.lower(): + return cls[enum_key] + if source in ("value", "any"): + for enum_key, enum_val in cls.__members__.items(): + if enum_val == value: + return cls[enum_key] + raise ValueError(f"Invalid match: expected one of {cls._allowed_matches(source)}, but got {value}.") + + @classmethod + def try_from_str(cls, value: str, source: Literal["key", "value", "any"] = "key") -> Optional["StrEnum"]: + """Try to create emun and if it does not match any, return `None`.""" + try: + return cls.from_str(value, source) + except ValueError: + warnings.warn( # noqa: B028 + UserWarning(f"Invalid string: expected one of {cls._allowed_matches(source)}, but got {value}.") + ) + return None + + @classmethod + def _allowed_matches(cls, source: str) -> list[str]: + keys, vals = [], [] + for enum_key, enum_val in cls.__members__.items(): + keys.append(enum_key) + vals.append(enum_val.value) + if source == "key": + return keys + if source == "value": + return vals + return keys + vals + + def __eq__(self, other: object) -> bool: + """Compare two instances.""" + if isinstance(other, Enum): + other = other.value + return self.value.lower() == str(other).lower() + + def __hash__(self) -> int: + """Return unique hash.""" + # re-enable hashtable, so it can be used as a dict key or in a set + # example: set(LightningEnum) + return hash(self.value.lower()) diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/core/imports.py b/venv/lib/python3.10/site-packages/lightning_utilities/core/imports.py new file mode 100644 index 0000000000000000000000000000000000000000..a433cea3a21e53f629b27dc5b8cd49e6284b8244 --- /dev/null +++ b/venv/lib/python3.10/site-packages/lightning_utilities/core/imports.py @@ -0,0 +1,360 @@ +# Copyright The Lightning AI team. +# Licensed under the Apache License, Version 2.0 (the "License"); +# http://www.apache.org/licenses/LICENSE-2.0 + +import functools +import importlib +import os +import warnings +from functools import lru_cache +from importlib.metadata import PackageNotFoundError, distribution +from importlib.metadata import version as _version +from importlib.util import find_spec +from types import ModuleType +from typing import Any, Callable, Optional, TypeVar + +from packaging.requirements import Requirement +from packaging.version import InvalidVersion, Version +from typing_extensions import ParamSpec + +T = TypeVar("T") +P = ParamSpec("P") + +try: + from importlib import metadata +except ImportError: + # Python < 3.8 + import importlib_metadata as metadata # type: ignore + + +@lru_cache +def package_available(package_name: str) -> bool: + """Check if a package is available in your environment. + + >>> package_available('os') + True + >>> package_available('bla') + False + + """ + try: + return find_spec(package_name) is not None + except ModuleNotFoundError: + return False + + +@lru_cache +def module_available(module_path: str) -> bool: + """Check if a module path is available in your environment. + + >>> module_available('os') + True + >>> module_available('os.bla') + False + >>> module_available('bla.bla') + False + + """ + module_names = module_path.split(".") + if not package_available(module_names[0]): + return False + try: + importlib.import_module(module_path) + except ImportError: + return False + return True + + +def compare_version(package: str, op: Callable, version: str, use_base_version: bool = False) -> bool: + """Compare package version with some requirements. + + >>> compare_version("torch", operator.ge, "0.1") + True + >>> compare_version("does_not_exist", operator.ge, "0.0") + False + + """ + try: + pkg = importlib.import_module(package) + except ImportError: + return False + try: + # Use importlib.metadata to infer version + pkg_version = Version(pkg.__version__) if hasattr(pkg, "__version__") else Version(_version(package)) + except (TypeError, PackageNotFoundError): + # this is mocked by Sphinx, so it should return True to generate all summaries + return True + if use_base_version: + pkg_version = Version(pkg_version.base_version) + return op(pkg_version, Version(version)) + + +class RequirementCache: + """Boolean-like class to check for requirement and module availability. + + Args: + requirement: The requirement to check, version specifiers are allowed. + module: The optional module to try to import if the requirement check fails. + + >>> RequirementCache("torch>=0.1") + Requirement 'torch>=0.1' met + >>> bool(RequirementCache("torch>=0.1")) + True + >>> bool(RequirementCache("torch>100.0")) + False + >>> RequirementCache("torch") + Requirement 'torch' met + >>> bool(RequirementCache("torch")) + True + >>> bool(RequirementCache("unknown_package")) + False + >>> bool(RequirementCache(module="torch.utils")) + True + >>> bool(RequirementCache(module="unknown_package")) + False + >>> bool(RequirementCache(module="unknown.module.path")) + False + + """ + + def __init__(self, requirement: Optional[str] = None, module: Optional[str] = None) -> None: + if not (requirement or module): + raise ValueError("At least one arguments need to be set.") + self.requirement = requirement + self.module = module + + def _check_requirement(self) -> None: + if not self.requirement: + raise ValueError("Requirement name is required.") + try: + req = Requirement(self.requirement) + pkg_version = Version(_version(req.name)) + self.available = req.specifier.contains(pkg_version, prereleases=True) and ( + not req.extras or self._check_extras_available(req) + ) + except (PackageNotFoundError, InvalidVersion) as ex: + self.available = False + self.message = f"{ex.__class__.__name__}: {ex}. HINT: Try running `pip install -U {self.requirement!r}`" + + if self.available: + self.message = f"Requirement {self.requirement!r} met" + else: + req_include_version = any(c in self.requirement for c in "=<>") + if not req_include_version or self.module is not None: + module = self.requirement if self.module is None else self.module + # Sometimes `importlib.metadata.version` fails but the module is importable + self.available = module_available(module) + if self.available: + self.message = f"Module {module!r} available" + self.message = ( + f"Requirement {self.requirement!r} not met. HINT: Try running `pip install -U {self.requirement!r}`" + ) + + def _check_module(self) -> None: + if not self.module: + raise ValueError("Module name is required.") + self.available = module_available(self.module) + if self.available: + self.message = f"Module {self.module!r} available" + else: + self.message = f"Module not found: {self.module!r}. HINT: Try running `pip install -U {self.module}`" + + def _check_available(self) -> None: + if hasattr(self, "available"): + return + if self.requirement: + self._check_requirement() + if getattr(self, "available", True) and self.module: + self._check_module() + + def _check_extras_available(self, requirement: Requirement) -> bool: + if not requirement.extras: + return True + + extra_requirements = self._get_extra_requirements(requirement) + + if not extra_requirements: + # The specified extra is not found in the package metadata + return False + + # Verify each extra requirement is installed + for extra_req in extra_requirements: + try: + extra_dist = distribution(extra_req.name) + extra_installed_version = Version(extra_dist.version) + if extra_req.specifier and not extra_req.specifier.contains(extra_installed_version, prereleases=True): + return False + except importlib.metadata.PackageNotFoundError: + return False + + return True + + def _get_extra_requirements(self, requirement: Requirement) -> list[Requirement]: + dist = distribution(requirement.name) + # Get the required dependencies for the specified extras + extra_requirements = dist.metadata.get_all("Requires-Dist") or [] + return [Requirement(r) for r in extra_requirements if any(extra in r for extra in requirement.extras)] + + def __bool__(self) -> bool: + """Format as bool.""" + self._check_available() + return self.available + + def __str__(self) -> str: + """Format as string.""" + self._check_available() + return self.message + + def __repr__(self) -> str: + """Format as string.""" + return self.__str__() + + +class ModuleAvailableCache(RequirementCache): + """Boolean-like class for check of module availability. + + >>> ModuleAvailableCache("torch") + Module 'torch' available + >>> bool(ModuleAvailableCache("torch.utils")) + True + >>> bool(ModuleAvailableCache("unknown_package")) + False + >>> bool(ModuleAvailableCache("unknown.module.path")) + False + + """ + + def __init__(self, module: str) -> None: + warnings.warn( + "`ModuleAvailableCache` is a special case of `RequirementCache`." + " Please use `RequirementCache(module=...)` instead.", + DeprecationWarning, + stacklevel=4, + ) + super().__init__(module=module) + + +def get_dependency_min_version_spec(package_name: str, dependency_name: str) -> str: + """Return the minimum version specifier of a dependency of a package. + + >>> get_dependency_min_version_spec("pytorch-lightning==1.8.0", "jsonargparse") + '>=4.12.0' + + """ + dependencies = metadata.requires(package_name) or [] + for dep in dependencies: + dependency = Requirement(dep) + if dependency.name == dependency_name: + spec = [str(s) for s in dependency.specifier if str(s)[0] == ">"] + return spec[0] if spec else "" + raise ValueError( + "This is an internal error. Please file a GitHub issue with the error message. Dependency " + f"{dependency_name!r} not found in package {package_name!r}." + ) + + +class LazyModule(ModuleType): + """Proxy module that lazily imports the underlying module the first time it is actually used. + + Args: + module_name: the fully-qualified module name to import + callback: a callback function to call before importing the module + + """ + + def __init__(self, module_name: str, callback: Optional[Callable] = None) -> None: + super().__init__(module_name) + self._module: Any = None + self._callback = callback + + def __getattr__(self, item: str) -> Any: + """Overwrite attribute access to attribute.""" + if self._module is None: + self._import_module() + + return getattr(self._module, item) + + def __dir__(self) -> list[str]: + """Overwrite attribute access for dictionary.""" + if self._module is None: + self._import_module() + + return dir(self._module) + + def _import_module(self) -> None: + # Execute callback, if any + if self._callback is not None: + self._callback() + + # Actually import the module + self._module = importlib.import_module(self.__name__) + + # Update this object's dict so that attribute references are efficient + # (__getattr__ is only called on lookups that fail) + self.__dict__.update(self._module.__dict__) + + +def lazy_import(module_name: str, callback: Optional[Callable] = None) -> LazyModule: + """Return a proxy module object that will lazily import the given module the first time it is used. + + Example usage: + + # Lazy version of `import tensorflow as tf` + tf = lazy_import("tensorflow") + # Other commands + # Now the module is loaded + tf.__version__ + + Args: + module_name: the fully-qualified module name to import + callback: a callback function to call before importing the module + + Returns: + a proxy module object that will be lazily imported when first used + + """ + return LazyModule(module_name, callback=callback) + + +def requires(*module_path_version: str, raise_exception: bool = True) -> Callable[[Callable[P, T]], Callable[P, T]]: + """Wrap early import failure with some nice exception message. + + Args: + module_path_version: python package path (e.g. `torch.cuda`) or pip like requiremsnt (e.g. `torch>=2.0.0`) + raise_exception: how strict the check shall be if exit the code or just warn user + + Example: + >>> @requires("libpath", raise_exception=bool(int(os.getenv("LIGHTING_TESTING", "0")))) + ... def my_cwd(): + ... from pathlib import Path + ... return Path(__file__).parent + + >>> class MyRndPower: + ... @requires("math", "random") + ... def __init__(self): + ... from math import pow + ... from random import randint + ... self._rnd = pow(randint(1, 9), 2) + + """ + + def decorator(func: Callable[P, T]) -> Callable[P, T]: + reqs = [ + ModuleAvailableCache(mod_ver) if "." in mod_ver else RequirementCache(mod_ver) + for mod_ver in module_path_version + ] + available = all(map(bool, reqs)) + + @functools.wraps(func) + def wrapper(*args: P.args, **kwargs: P.kwargs) -> T: + if not available: + missing = os.linesep.join([repr(r) for r in reqs if not bool(r)]) + msg = f"Required dependencies not available: \n{missing}" + if raise_exception: + raise ModuleNotFoundError(msg) + warnings.warn(msg, stacklevel=2) + return func(*args, **kwargs) + + return wrapper + + return decorator diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/core/inheritance.py b/venv/lib/python3.10/site-packages/lightning_utilities/core/inheritance.py new file mode 100644 index 0000000000000000000000000000000000000000..895ab5fc3921f81e53f0d27d85860c7410df4363 --- /dev/null +++ b/venv/lib/python3.10/site-packages/lightning_utilities/core/inheritance.py @@ -0,0 +1,21 @@ +# Copyright The Lightning AI team. +# Licensed under the Apache License, Version 2.0 (the "License"); +# http://www.apache.org/licenses/LICENSE-2.0 +# +from collections.abc import Iterator + + +def get_all_subclasses_iterator(cls: type) -> Iterator[type]: + """Iterate over all subclasses.""" + + def recurse(cl: type) -> Iterator[type]: + for subclass in cl.__subclasses__(): + yield subclass + yield from recurse(subclass) + + yield from recurse(cls) + + +def get_all_subclasses(cls: type) -> set[type]: + """List all subclasses of a class.""" + return set(get_all_subclasses_iterator(cls)) diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/core/overrides.py b/venv/lib/python3.10/site-packages/lightning_utilities/core/overrides.py new file mode 100644 index 0000000000000000000000000000000000000000..5dc4636daee5ec48d388c66086e623d9a21bba35 --- /dev/null +++ b/venv/lib/python3.10/site-packages/lightning_utilities/core/overrides.py @@ -0,0 +1,34 @@ +# Copyright The Lightning AI team. +# Licensed under the Apache License, Version 2.0 (the "License"); +# http://www.apache.org/licenses/LICENSE-2.0 +# +from functools import partial +from unittest.mock import Mock + + +def is_overridden(method_name: str, instance: object, parent: type[object]) -> bool: + """Check if a method of a given object was overwritten.""" + instance_attr = getattr(instance, method_name, None) + if instance_attr is None: + return False + # `functools.wraps()` and `@contextmanager` support + if hasattr(instance_attr, "__wrapped__"): + instance_attr = instance_attr.__wrapped__ + # `Mock(wraps=...)` support + if isinstance(instance_attr, Mock): + # access the wrapped function + instance_attr = instance_attr._mock_wraps + # `partial` support + elif isinstance(instance_attr, partial): + instance_attr = instance_attr.func + if instance_attr is None: + return False + + parent_attr = getattr(parent, method_name, None) + if parent_attr is None: + raise ValueError("The parent should define the method") + # `@contextmanager` support + if hasattr(parent_attr, "__wrapped__"): + parent_attr = parent_attr.__wrapped__ + + return instance_attr.__code__ != parent_attr.__code__ diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/core/rank_zero.py b/venv/lib/python3.10/site-packages/lightning_utilities/core/rank_zero.py new file mode 100644 index 0000000000000000000000000000000000000000..ec18e53315ef4d791240e8609dce9278bbb1e786 --- /dev/null +++ b/venv/lib/python3.10/site-packages/lightning_utilities/core/rank_zero.py @@ -0,0 +1,115 @@ +# Copyright The Lightning AI team. +# Licensed under the Apache License, Version 2.0 (the "License"); +# http://www.apache.org/licenses/LICENSE-2.0 +# +"""Utilities that can be used for calling functions on a particular rank.""" + +import logging +import warnings +from functools import wraps +from typing import Any, Callable, Optional, TypeVar, Union + +from typing_extensions import ParamSpec, overload + +log = logging.getLogger(__name__) + +T = TypeVar("T") +P = ParamSpec("P") + + +@overload +def rank_zero_only(fn: Callable[P, T]) -> Callable[P, Optional[T]]: ... + + +@overload +def rank_zero_only(fn: Callable[P, T], default: T) -> Callable[P, T]: ... + + +def rank_zero_only(fn: Callable[P, T], default: Optional[T] = None) -> Callable[P, Optional[T]]: + """Wrap a function to call internal function only in rank zero. + + Function that can be used as a decorator to enable a function/method being called only on global rank 0. + + """ + + @wraps(fn) + def wrapped_fn(*args: P.args, **kwargs: P.kwargs) -> Optional[T]: + rank = getattr(rank_zero_only, "rank", None) + if rank is None: + raise RuntimeError("The `rank_zero_only.rank` needs to be set before use") + if rank == 0: + return fn(*args, **kwargs) + return default + + return wrapped_fn + + +def _debug(*args: Any, stacklevel: int = 2, **kwargs: Any) -> None: + kwargs["stacklevel"] = stacklevel + log.debug(*args, **kwargs) + + +@rank_zero_only +def rank_zero_debug(*args: Any, stacklevel: int = 4, **kwargs: Any) -> None: + """Emit debug-level messages only on global rank 0.""" + _debug(*args, stacklevel=stacklevel, **kwargs) + + +def _info(*args: Any, stacklevel: int = 2, **kwargs: Any) -> None: + kwargs["stacklevel"] = stacklevel + log.info(*args, **kwargs) + + +@rank_zero_only +def rank_zero_info(*args: Any, stacklevel: int = 4, **kwargs: Any) -> None: + """Emit info-level messages only on global rank 0.""" + _info(*args, stacklevel=stacklevel, **kwargs) + + +def _warn(message: Union[str, Warning], stacklevel: int = 2, **kwargs: Any) -> None: + warnings.warn(message, stacklevel=stacklevel, **kwargs) + + +@rank_zero_only +def rank_zero_warn(message: Union[str, Warning], stacklevel: int = 4, **kwargs: Any) -> None: + """Emit warn-level messages only on global rank 0.""" + _warn(message, stacklevel=stacklevel, **kwargs) + + +rank_zero_deprecation_category = DeprecationWarning + + +def rank_zero_deprecation(message: Union[str, Warning], stacklevel: int = 5, **kwargs: Any) -> None: + """Emit a deprecation warning only on global rank 0.""" + category = kwargs.pop("category", rank_zero_deprecation_category) + rank_zero_warn(message, stacklevel=stacklevel, category=category, **kwargs) + + +def rank_prefixed_message(message: str, rank: Optional[int]) -> str: + """Add a prefix with the rank to a message.""" + if rank is not None: + # specify the rank of the process being logged + return f"[rank: {rank}] {message}" + return message + + +class WarningCache(set): + """Cache for warnings.""" + + def warn(self, message: str, stacklevel: int = 5, **kwargs: Any) -> None: + """Trigger warning message.""" + if message not in self: + self.add(message) + rank_zero_warn(message, stacklevel=stacklevel, **kwargs) + + def deprecation(self, message: str, stacklevel: int = 6, **kwargs: Any) -> None: + """Trigger deprecation message.""" + if message not in self: + self.add(message) + rank_zero_deprecation(message, stacklevel=stacklevel, **kwargs) + + def info(self, message: str, stacklevel: int = 5, **kwargs: Any) -> None: + """Trigger info message.""" + if message not in self: + self.add(message) + rank_zero_info(message, stacklevel=stacklevel, **kwargs) diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/docs/__init__.py b/venv/lib/python3.10/site-packages/lightning_utilities/docs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..093cce5c583ebcbf63bbce34a67c55f0a8d5458c --- /dev/null +++ b/venv/lib/python3.10/site-packages/lightning_utilities/docs/__init__.py @@ -0,0 +1,6 @@ +"""General tools for Docs.""" + +from lightning_utilities.docs.formatting import adjust_linked_external_docs +from lightning_utilities.docs.retriever import fetch_external_assets + +__all__ = ["adjust_linked_external_docs", "fetch_external_assets"] diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/docs/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/lightning_utilities/docs/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db044bf2462f4cf54ce5539a51db8bb0f5ba9a04 Binary files /dev/null and b/venv/lib/python3.10/site-packages/lightning_utilities/docs/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/docs/__pycache__/formatting.cpython-310.pyc b/venv/lib/python3.10/site-packages/lightning_utilities/docs/__pycache__/formatting.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db9ea5382c329b4e9541a832198241e0a346e292 Binary files /dev/null and b/venv/lib/python3.10/site-packages/lightning_utilities/docs/__pycache__/formatting.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/docs/__pycache__/retriever.cpython-310.pyc b/venv/lib/python3.10/site-packages/lightning_utilities/docs/__pycache__/retriever.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f9f47878c8cbfc7dcedfccb88599d8f1a02d6fc Binary files /dev/null and b/venv/lib/python3.10/site-packages/lightning_utilities/docs/__pycache__/retriever.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/docs/formatting.py b/venv/lib/python3.10/site-packages/lightning_utilities/docs/formatting.py new file mode 100644 index 0000000000000000000000000000000000000000..a2c4d0ca98b5db52f8d4504eb176c7b480a2b593 --- /dev/null +++ b/venv/lib/python3.10/site-packages/lightning_utilities/docs/formatting.py @@ -0,0 +1,185 @@ +# Licensed under the Apache License, Version 2.0 (the "License"); +# http://www.apache.org/licenses/LICENSE-2.0 +# +import glob +import importlib +import inspect +import logging +import os +import re +import sys +from collections.abc import Iterable +from typing import Optional, Union + + +def _transform_changelog(path_in: str, path_out: str) -> None: + """Adjust changelog titles so not to be duplicated. + + Args: + path_in: input MD file + path_out: output also MD file + + """ + with open(path_in) as fp: + chlog_lines = fp.readlines() + # enrich short subsub-titles to be unique + chlog_ver = "" + for i, ln in enumerate(chlog_lines): + if ln.startswith("## "): + chlog_ver = ln[2:].split("-")[0].strip() + elif ln.startswith("### "): + ln = ln.replace("###", f"### {chlog_ver} -") + chlog_lines[i] = ln + with open(path_out, "w") as fp: + fp.writelines(chlog_lines) + + +def _linkcode_resolve( + domain: str, + info: dict, + github_user: str, + github_repo: str, + main_branch: str = "master", + stable_branch: str = "release/stable", +) -> str: + def find_source() -> tuple[str, int, int]: + # try to find the file and line number, based on code from numpy: + # https://github.com/numpy/numpy/blob/master/doc/source/conf.py#L286 + obj = sys.modules[info["module"]] + for part in info["fullname"].split("."): + obj = getattr(obj, part) + fname = str(inspect.getsourcefile(obj)) + # https://github.com/rtfd/readthedocs.org/issues/5735 + if any(s in fname for s in ("readthedocs", "rtfd", "checkouts")): + # /home/docs/checkouts/readthedocs.org/user_builds/pytorch_lightning/checkouts/ + # devel/pytorch_lightning/utilities/cls_experiment.py#L26-L176 + path_top = os.path.abspath(os.path.join("..", "..", "..")) + fname = str(os.path.relpath(fname, start=path_top)) + else: + # Local build, imitate master + fname = f"{main_branch}/{os.path.relpath(fname, start=os.path.abspath('..'))}" + source, line_start = inspect.getsourcelines(obj) + return fname, line_start, line_start + len(source) - 1 + + if domain != "py" or not info["module"]: + return "" + try: + filename = "%s#L%d-L%d" % find_source() # noqa: UP031 + except Exception: + filename = info["module"].replace(".", "/") + ".py" + # import subprocess + # tag = subprocess.Popen(['git', 'rev-parse', 'HEAD'], stdout=subprocess.PIPE, + # universal_newlines=True).communicate()[0][:-1] + branch = filename.split("/")[0] + # do mapping from latest tags to master + branch = {"latest": main_branch, "stable": stable_branch}.get(branch, branch) + filename = "/".join([branch, *filename.split("/")[1:]]) + return f"https://github.com/{github_user}/{github_repo}/blob/{filename}" + + +def _load_pypi_versions(package_name: str) -> list[str]: + """Load the versions of the package from PyPI. + + >>> _load_pypi_versions("numpy") # doctest: +ELLIPSIS + ['0.9.6', '0.9.8', '1.0', ...] + >>> _load_pypi_versions("scikit-learn") # doctest: +ELLIPSIS + ['0.9', '0.10', '0.11', '0.12', ...] + + """ + from distutils.version import LooseVersion + + import requests + + url = f"https://pypi.org/pypi/{package_name}/json" + data = requests.get(url, timeout=10).json() + versions = data["releases"].keys() + # filter all version which include only numbers and dots + versions = {k for k in versions if re.match(r"^\d+(\.\d+)*$", k)} + return sorted(versions, key=LooseVersion) + + +def _update_link_based_imported_package(link: str, pkg_ver: str, version_digits: Optional[int]) -> str: + """Adjust the linked external docs to be local. + + Args: + link: the source link to be replaced + pkg_ver: the target link to be replaced, if ``{package.version}`` is included it will be replaced accordingly + version_digits: for semantic versioning, how many digits to be considered + + """ + pkg_att = pkg_ver.split(".") + try: + ver = _load_pypi_versions(pkg_att[0])[-1] + except Exception: + # load the package with all additional sub-modules + module = importlib.import_module(".".join(pkg_att[:-1])) + # load the attribute + ver = getattr(module, pkg_att[0]) + # drop any additional context after `+` + ver = ver.split("+")[0] + # crop the version to the number of digits + ver = ".".join(ver.split(".")[:version_digits]) + # replace the version + return link.replace(f"{{{pkg_ver}}}", ver) + + +def adjust_linked_external_docs( + source_link: str, + target_link: str, + browse_folder: Union[str, Iterable[str]], + file_extensions: Iterable[str] = (".rst", ".py"), + version_digits: int = 2, +) -> None: + r"""Adjust the linked external docs to be local. + + Args: + source_link: the link to be replaced + target_link: the link to be replaced, if ``{package.version}`` is included it will be replaced accordingly + browse_folder: the location of the browsable folder + file_extensions: what kind of files shall be scanned + version_digits: for semantic versioning, how many digits to be considered + + Examples: + >>> adjust_linked_external_docs( + ... "https://numpy.org/doc/stable/", + ... "https://numpy.org/doc/{numpy.__version__}/", + ... "docs/source", + ... ) + + """ + list_files = [] + if isinstance(browse_folder, str): + browse_folder = [browse_folder] + for folder in browse_folder: + for ext in file_extensions: + list_files += glob.glob(os.path.join(folder, "**", f"*{ext}"), recursive=True) + if not list_files: + logging.warning(f'No files were listed in folder "{browse_folder}" and pattern "{file_extensions}"') + return + + # find the expression for package version in {} brackets if any, use re to find it + pkg_ver_all = re.findall(r"{(.+)}", target_link) + for pkg_ver in pkg_ver_all: + target_link = _update_link_based_imported_package(target_link, pkg_ver, version_digits) + + # replace the source link with target link + for fpath in set(list_files): + with open(fpath, encoding="UTF-8") as fopen: + lines = fopen.readlines() + found, skip = False, False + for i, ln in enumerate(lines): + # prevent the replacement its own function calls + if f"{adjust_linked_external_docs.__name__}(" in ln: + skip = True + if not skip and source_link in ln: + # replace the link if any found + lines[i] = ln.replace(source_link, target_link) + # record the found link for later write file + found = True + if skip and ")" in ln: + skip = False + if not found: + continue + logging.debug(f'links adjusting in {fpath}: "{source_link}" -> "{target_link}"') + with open(fpath, "w", encoding="UTF-8") as fw: + fw.writelines(lines) diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/docs/retriever.py b/venv/lib/python3.10/site-packages/lightning_utilities/docs/retriever.py new file mode 100644 index 0000000000000000000000000000000000000000..4de873bf94969c2e784908cb564a91242597db5e --- /dev/null +++ b/venv/lib/python3.10/site-packages/lightning_utilities/docs/retriever.py @@ -0,0 +1,99 @@ +# Licensed under the Apache License, Version 2.0 (the "License"); +# http://www.apache.org/licenses/LICENSE-2.0 +# +import glob +import logging +import os +import re + +import requests + + +def _download_file(file_url: str, folder: str) -> str: + """Download a file from URL to a particular folder.""" + fname = os.path.basename(file_url) + file_path = os.path.join(folder, fname) + if os.path.isfile(file_path): + logging.warning(f'given file "{file_path}" already exists and will be overwritten with {file_url}') + # see: https://stackoverflow.com/a/34957875 + rq = requests.get(file_url, timeout=10) + with open(file_path, "wb") as outfile: + outfile.write(rq.content) + return fname + + +def _search_all_occurrences(list_files: list[str], pattern: str) -> list[str]: + """Search for all occurrences of specific pattern in a collection of files. + + Args: + list_files: list of files to be scanned + pattern: pattern for search, reg. expression + + """ + collected = [] + for file_path in list_files: + with open(file_path, encoding="UTF-8") as fopem: + body = fopem.read() + found = re.findall(pattern, body) + collected += found + return collected + + +def _replace_remote_with_local(file_path: str, docs_folder: str, pairs_url_path: list[tuple[str, str]]) -> None: + """Replace all URL with local files in a given file. + + Args: + file_path: file for replacement + docs_folder: the location of docs related to the project root + pairs_url_path: pairs of URL and local file path to be swapped + + """ + # drop the default/global path to the docs + relt_path = os.path.dirname(file_path).replace(docs_folder, "") + # filter the path starting with / as not empty folder names + depth = len([p for p in relt_path.split(os.path.sep) if p]) + with open(file_path, encoding="UTF-8") as fopen: + body = fopen.read() + for url, fpath in pairs_url_path: + if depth: + path_up = [".."] * depth + fpath = os.path.join(*path_up, fpath) + body = body.replace(url, fpath) + with open(file_path, "w", encoding="UTF-8") as fw: + fw.write(body) + + +def fetch_external_assets( + docs_folder: str = "docs/source", + assets_folder: str = "fetched-s3-assets", + file_pattern: str = "*.rst", + retrieve_pattern: str = r"https?://[-a-zA-Z0-9_]+\.s3\.[-a-zA-Z0-9()_\\+.\\/=]+", +) -> None: + """Search all URL in docs, download these files locally and replace online with local version. + + Args: + docs_folder: the location of docs related to the project root + assets_folder: a folder inside ``docs_folder`` to be created and saving online assets + file_pattern: what kind of files shall be scanned + retrieve_pattern: pattern for reg. expression to search URL/S3 resources + + """ + list_files = glob.glob(os.path.join(docs_folder, "**", file_pattern), recursive=True) + if not list_files: + logging.warning(f'no files were listed in folder "{docs_folder}" and pattern "{file_pattern}"') + return + + urls = _search_all_occurrences(list_files, pattern=retrieve_pattern) + if not urls: + logging.info(f"no resources/assets were match in {docs_folder} for {retrieve_pattern}") + return + target_folder = os.path.join(docs_folder, assets_folder) + os.makedirs(target_folder, exist_ok=True) + pairs_url_file = [] + for i, url in enumerate(set(urls)): + logging.info(f" >> downloading ({i}/{len(urls)}): {url}") + fname = _download_file(url, target_folder) + pairs_url_file.append((url, os.path.join(assets_folder, fname))) + + for fpath in list_files: + _replace_remote_with_local(fpath, docs_folder, pairs_url_file) diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/install/__init__.py b/venv/lib/python3.10/site-packages/lightning_utilities/install/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..723406a802fc66555ba8c46661e64fd438f982d2 --- /dev/null +++ b/venv/lib/python3.10/site-packages/lightning_utilities/install/__init__.py @@ -0,0 +1,5 @@ +"""Generic Installation tools.""" + +from lightning_utilities.install.requirements import Requirement, load_requirements + +__all__ = ["Requirement", "load_requirements"] diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/install/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/lightning_utilities/install/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..81aaebb260a79ca1ec617093909534c9d86ae965 Binary files /dev/null and b/venv/lib/python3.10/site-packages/lightning_utilities/install/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/install/__pycache__/requirements.cpython-310.pyc b/venv/lib/python3.10/site-packages/lightning_utilities/install/__pycache__/requirements.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d7e30e45a9f14530d34dbca96aca1f1d811ff40f Binary files /dev/null and b/venv/lib/python3.10/site-packages/lightning_utilities/install/__pycache__/requirements.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/install/requirements.py b/venv/lib/python3.10/site-packages/lightning_utilities/install/requirements.py new file mode 100644 index 0000000000000000000000000000000000000000..b39a4ca19e697292673870c273dbcfa0567b75d7 --- /dev/null +++ b/venv/lib/python3.10/site-packages/lightning_utilities/install/requirements.py @@ -0,0 +1,123 @@ +# Licensed under the Apache License, Version 2.0 (the "License"); +# http://www.apache.org/licenses/LICENSE-2.0 +# +import re +from collections.abc import Iterable, Iterator +from distutils.version import LooseVersion +from pathlib import Path +from typing import Any, Optional, Union + +from pkg_resources import Requirement, yield_lines # type: ignore[import-untyped] + + +class _RequirementWithComment(Requirement): + strict_string = "# strict" + + def __init__(self, *args: Any, comment: str = "", pip_argument: Optional[str] = None, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.comment = comment + if not (pip_argument is None or pip_argument): # sanity check that it's not an empty str + raise RuntimeError(f"wrong pip argument: {pip_argument}") + self.pip_argument = pip_argument + self.strict = self.strict_string in comment.lower() + + def adjust(self, unfreeze: str) -> str: + """Remove version restrictions unless they are strict. + + >>> _RequirementWithComment("arrow<=1.2.2,>=1.2.0", comment="# anything").adjust("none") + 'arrow<=1.2.2,>=1.2.0' + >>> _RequirementWithComment("arrow<=1.2.2,>=1.2.0", comment="# strict").adjust("none") + 'arrow<=1.2.2,>=1.2.0 # strict' + >>> _RequirementWithComment("arrow<=1.2.2,>=1.2.0", comment="# my name").adjust("all") + 'arrow>=1.2.0' + >>> _RequirementWithComment("arrow>=1.2.0, <=1.2.2", comment="# strict").adjust("all") + 'arrow<=1.2.2,>=1.2.0 # strict' + >>> _RequirementWithComment("arrow").adjust("all") + 'arrow' + >>> _RequirementWithComment("arrow>=1.2.0, <=1.2.2", comment="# cool").adjust("major") + 'arrow<2.0,>=1.2.0' + >>> _RequirementWithComment("arrow>=1.2.0, <=1.2.2", comment="# strict").adjust("major") + 'arrow<=1.2.2,>=1.2.0 # strict' + >>> _RequirementWithComment("arrow>=1.2.0").adjust("major") + 'arrow>=1.2.0' + >>> _RequirementWithComment("arrow").adjust("major") + 'arrow' + + """ + out = str(self) + if self.strict: + return f"{out} {self.strict_string}" + if unfreeze == "major": + for operator, version in self.specs: + if operator in ("<", "<="): + major = LooseVersion(version).version[0] + # replace upper bound with major version increased by one + return out.replace(f"{operator}{version}", f"<{int(major) + 1}.0") + elif unfreeze == "all": + for operator, version in self.specs: + if operator in ("<", "<="): + # drop upper bound + return out.replace(f"{operator}{version},", "") + elif unfreeze != "none": + raise ValueError(f"Unexpected unfreeze: {unfreeze!r} value.") + return out + + +def _parse_requirements(strs: Union[str, Iterable[str]]) -> Iterator[_RequirementWithComment]: + r"""Adapted from `pkg_resources.parse_requirements` to include comments. + + >>> txt = ['# ignored', '', 'this # is an', '--piparg', 'example', 'foo # strict', 'thing', '-r different/file.txt'] + >>> [r.adjust('none') for r in _parse_requirements(txt)] + ['this', 'example', 'foo # strict', 'thing'] + >>> txt = '\\n'.join(txt) + >>> [r.adjust('none') for r in _parse_requirements(txt)] + ['this', 'example', 'foo # strict', 'thing'] + + """ + lines = yield_lines(strs) + pip_argument = None + for line in lines: + # Drop comments -- a hash without a space may be in a URL. + if " #" in line: + comment_pos = line.find(" #") + line, comment = line[:comment_pos], line[comment_pos:] + else: + comment = "" + # If there is a line continuation, drop it, and append the next line. + if line.endswith("\\"): + line = line[:-2].strip() + try: + line += next(lines) + except StopIteration: + return + # If there's a pip argument, save it + if line.startswith("--"): + pip_argument = line + continue + if line.startswith("-r "): + # linked requirement files are unsupported + continue + if "@" in line or re.search("https?://", line): + # skip lines with links like `pesq @ git+https://github.com/ludlows/python-pesq` + continue + yield _RequirementWithComment(line, comment=comment, pip_argument=pip_argument) + pip_argument = None + + +def load_requirements(path_dir: str, file_name: str = "base.txt", unfreeze: str = "all") -> list[str]: + """Load requirements from a file. + + >>> import os + >>> from lightning_utilities import _PROJECT_ROOT + >>> path_req = os.path.join(_PROJECT_ROOT, "requirements") + >>> load_requirements(path_req, "docs.txt", unfreeze="major") # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE + ['sphinx<6.0,>=4.0', ...] + + """ + if unfreeze not in {"none", "major", "all"}: + raise ValueError(f'unsupported option of "{unfreeze}"') + path = Path(path_dir) / file_name + if not path.exists(): + raise FileNotFoundError(f"missing file for {(path_dir, file_name, path)}") + text = path.read_text() + return [req.adjust(unfreeze) for req in _parse_requirements(text)] diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/py.typed b/venv/lib/python3.10/site-packages/lightning_utilities/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/test/__init__.py b/venv/lib/python3.10/site-packages/lightning_utilities/test/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2741f80aa49d03148535eb4f2af3c94364f47d81 --- /dev/null +++ b/venv/lib/python3.10/site-packages/lightning_utilities/test/__init__.py @@ -0,0 +1 @@ +"""General testing functionality.""" diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/test/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/lightning_utilities/test/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ed02a5a2580abb5578b3a9559844375263ee466 Binary files /dev/null and b/venv/lib/python3.10/site-packages/lightning_utilities/test/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/test/__pycache__/warning.cpython-310.pyc b/venv/lib/python3.10/site-packages/lightning_utilities/test/__pycache__/warning.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3403cf2f5eee8916451fa801bac9635e5602c34c Binary files /dev/null and b/venv/lib/python3.10/site-packages/lightning_utilities/test/__pycache__/warning.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/lightning_utilities/test/warning.py b/venv/lib/python3.10/site-packages/lightning_utilities/test/warning.py new file mode 100644 index 0000000000000000000000000000000000000000..eec3a216b7c9dcc947dda95a1a3a76334113102d --- /dev/null +++ b/venv/lib/python3.10/site-packages/lightning_utilities/test/warning.py @@ -0,0 +1,19 @@ +# Licensed under the Apache License, Version 2.0 (the "License"); +# http://www.apache.org/licenses/LICENSE-2.0 +# +import re +import warnings +from collections.abc import Generator +from contextlib import contextmanager +from typing import Optional + + +@contextmanager +def no_warning_call(expected_warning: type[Warning] = Warning, match: Optional[str] = None) -> Generator: + """Check that no warning was raised/emitted under this context manager.""" + with warnings.catch_warnings(record=True) as record: + yield + + for w in record: + if issubclass(w.category, expected_warning) and (match is None or re.compile(match).search(str(w.message))): + raise AssertionError(f"`{expected_warning.__name__}` was raised: {w.message!r}") diff --git a/venv/lib/python3.10/site-packages/lm_eval-0.4.3.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/lm_eval-0.4.3.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/venv/lib/python3.10/site-packages/lm_eval-0.4.3.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/lib/python3.10/site-packages/lm_eval-0.4.3.dist-info/LICENSE.md b/venv/lib/python3.10/site-packages/lm_eval-0.4.3.dist-info/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..12e6063183935e876e232db276568baf4954b492 --- /dev/null +++ b/venv/lib/python3.10/site-packages/lm_eval-0.4.3.dist-info/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 EleutherAI + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/venv/lib/python3.10/site-packages/lm_eval-0.4.3.dist-info/METADATA b/venv/lib/python3.10/site-packages/lm_eval-0.4.3.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..0c080e84cd1e8c7b647460985218e3b97a2b4ed2 --- /dev/null +++ b/venv/lib/python3.10/site-packages/lm_eval-0.4.3.dist-info/METADATA @@ -0,0 +1,585 @@ +Metadata-Version: 2.1 +Name: lm_eval +Version: 0.4.3 +Summary: A framework for evaluating language models +Author-email: EleutherAI +License: MIT +Project-URL: Homepage, https://github.com/EleutherAI/lm-evaluation-harness +Project-URL: Repository, https://github.com/EleutherAI/lm-evaluation-harness +Classifier: Development Status :: 3 - Alpha +Classifier: Programming Language :: Python :: 3 +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: OS Independent +Requires-Python: >=3.8 +Description-Content-Type: text/markdown +License-File: LICENSE.md +Requires-Dist: accelerate >=0.26.0 +Requires-Dist: evaluate +Requires-Dist: datasets >=2.16.0 +Requires-Dist: evaluate >=0.4.0 +Requires-Dist: jsonlines +Requires-Dist: numexpr +Requires-Dist: peft >=0.2.0 +Requires-Dist: pybind11 >=2.6.2 +Requires-Dist: pytablewriter +Requires-Dist: rouge-score >=0.0.4 +Requires-Dist: sacrebleu >=1.5.0 +Requires-Dist: scikit-learn >=0.24.1 +Requires-Dist: sqlitedict +Requires-Dist: torch >=1.8 +Requires-Dist: tqdm-multiprocess +Requires-Dist: transformers >=4.1 +Requires-Dist: zstandard +Requires-Dist: dill +Requires-Dist: word2number +Requires-Dist: more-itertools +Provides-Extra: all +Requires-Dist: lm-eval[anthropic] ; extra == 'all' +Requires-Dist: lm-eval[dev] ; extra == 'all' +Requires-Dist: lm-eval[deepsparse] ; extra == 'all' +Requires-Dist: lm-eval[gptq] ; extra == 'all' +Requires-Dist: lm-eval[hf_transfer] ; extra == 'all' +Requires-Dist: lm-eval[ifeval] ; extra == 'all' +Requires-Dist: lm-eval[mamba] ; extra == 'all' +Requires-Dist: lm-eval[math] ; extra == 'all' +Requires-Dist: lm-eval[multilingual] ; extra == 'all' +Requires-Dist: lm-eval[openai] ; extra == 'all' +Requires-Dist: lm-eval[promptsource] ; extra == 'all' +Requires-Dist: lm-eval[sentencepiece] ; extra == 'all' +Requires-Dist: lm-eval[sparseml] ; extra == 'all' +Requires-Dist: lm-eval[testing] ; extra == 'all' +Requires-Dist: lm-eval[vllm] ; extra == 'all' +Requires-Dist: lm-eval[zeno] ; extra == 'all' +Requires-Dist: lm-eval[wandb] ; extra == 'all' +Requires-Dist: lm-eval[unitxt] ; extra == 'all' +Provides-Extra: anthropic +Requires-Dist: anthropic ; extra == 'anthropic' +Provides-Extra: deepsparse +Requires-Dist: deepsparse-nightly[llm] >=1.8.0.20240404 ; extra == 'deepsparse' +Provides-Extra: dev +Requires-Dist: pytest ; extra == 'dev' +Requires-Dist: pytest-cov ; extra == 'dev' +Requires-Dist: pytest-xdist ; extra == 'dev' +Requires-Dist: pre-commit ; extra == 'dev' +Requires-Dist: mypy ; extra == 'dev' +Provides-Extra: gptq +Requires-Dist: auto-gptq[triton] >=0.6.0 ; extra == 'gptq' +Provides-Extra: hf_transfer +Requires-Dist: hf-transfer ; extra == 'hf_transfer' +Provides-Extra: ifeval +Requires-Dist: langdetect ; extra == 'ifeval' +Requires-Dist: immutabledict ; extra == 'ifeval' +Provides-Extra: mamba +Requires-Dist: mamba-ssm ; extra == 'mamba' +Requires-Dist: causal-conv1d ==1.0.2 ; extra == 'mamba' +Provides-Extra: math +Requires-Dist: sympy >=1.12 ; extra == 'math' +Requires-Dist: antlr4-python3-runtime ==4.11 ; extra == 'math' +Provides-Extra: multilingual +Requires-Dist: nagisa >=0.2.7 ; extra == 'multilingual' +Requires-Dist: jieba >=0.42.1 ; extra == 'multilingual' +Requires-Dist: pycountry ; extra == 'multilingual' +Provides-Extra: neuronx +Requires-Dist: optimum[neuronx] ; extra == 'neuronx' +Provides-Extra: openai +Requires-Dist: openai ==1.3.9 ; extra == 'openai' +Requires-Dist: tiktoken ; extra == 'openai' +Provides-Extra: optimum +Requires-Dist: optimum[openvino] ; extra == 'optimum' +Provides-Extra: promptsource +Requires-Dist: promptsource >=0.2.3 ; extra == 'promptsource' +Provides-Extra: sentencepiece +Requires-Dist: sentencepiece >=0.1.98 ; extra == 'sentencepiece' +Provides-Extra: sparseml +Requires-Dist: sparseml-nightly[llm] >=1.8.0.20240404 ; extra == 'sparseml' +Provides-Extra: testing +Requires-Dist: pytest ; extra == 'testing' +Requires-Dist: pytest-cov ; extra == 'testing' +Requires-Dist: pytest-xdist ; extra == 'testing' +Provides-Extra: unitxt +Requires-Dist: unitxt ; extra == 'unitxt' +Provides-Extra: vllm +Requires-Dist: vllm >=0.4.2 ; extra == 'vllm' +Provides-Extra: wandb +Requires-Dist: wandb >=0.16.3 ; extra == 'wandb' +Requires-Dist: pandas ; extra == 'wandb' +Requires-Dist: numpy ; extra == 'wandb' +Provides-Extra: zeno +Requires-Dist: pandas ; extra == 'zeno' +Requires-Dist: zeno-client ; extra == 'zeno' + +# Language Model Evaluation Harness + +[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.10256836.svg)](https://doi.org/10.5281/zenodo.10256836) + +## Announcement +**A new v0.4.0 release of lm-evaluation-harness is available** ! + +New updates and features include: + +- Internal refactoring +- Config-based task creation and configuration +- Easier import and sharing of externally-defined task config YAMLs +- Support for Jinja2 prompt design, easy modification of prompts + prompt imports from Promptsource +- More advanced configuration options, including output post-processing, answer extraction, and multiple LM generations per document, configurable fewshot settings, and more +- Speedups and new modeling libraries supported, including: faster data-parallel HF model usage, vLLM support, MPS support with HuggingFace, and more +- Logging and usability changes +- New tasks including CoT BIG-Bench-Hard, Belebele, user-defined task groupings, and more + +Please see our updated documentation pages in `docs/` for more details. + +Development will be continuing on the `main` branch, and we encourage you to give us feedback on what features are desired and how to improve the library further, or ask questions, either in issues or PRs on GitHub, or in the [EleutherAI discord](https://discord.gg/eleutherai)! + +## Overview + +This project provides a unified framework to test generative language models on a large number of different evaluation tasks. + +**Features:** +- Over 60 standard academic benchmarks for LLMs, with hundreds of subtasks and variants implemented. +- Support for models loaded via [transformers](https://github.com/huggingface/transformers/) (including quantization via [AutoGPTQ](https://github.com/PanQiWei/AutoGPTQ)), [GPT-NeoX](https://github.com/EleutherAI/gpt-neox), and [Megatron-DeepSpeed](https://github.com/microsoft/Megatron-DeepSpeed/), with a flexible tokenization-agnostic interface. +- Support for fast and memory-efficient inference with [vLLM](https://github.com/vllm-project/vllm). +- Support for commercial APIs including [OpenAI](https://openai.com), and [TextSynth](https://textsynth.com/). +- Support for evaluation on adapters (e.g. LoRA) supported in [HuggingFace's PEFT library](https://github.com/huggingface/peft). +- Support for local models and benchmarks. +- Evaluation with publicly available prompts ensures reproducibility and comparability between papers. +- Easy support for custom prompts and evaluation metrics. + +The Language Model Evaluation Harness is the backend for 🤗 Hugging Face's popular [Open LLM Leaderboard](https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard), has been used in [hundreds of papers](https://scholar.google.com/scholar?oi=bibs&hl=en&authuser=2&cites=15052937328817631261,4097184744846514103,1520777361382155671,17476825572045927382,18443729326628441434,14801318227356878622,7890865700763267262,12854182577605049984,15641002901115500560,5104500764547628290), and is used internally by dozens of organizations including NVIDIA, Cohere, BigScience, BigCode, Nous Research, and Mosaic ML. + +## Install + +To install the `lm-eval` package from the github repository, run: + +```bash +git clone https://github.com/EleutherAI/lm-evaluation-harness +cd lm-evaluation-harness +pip install -e . +``` + +We also provide a number of optional dependencies for extended functionality. A detailed table is available at the end of this document. + +## Basic Usage +### User Guide + +A user guide detailing the full list of supported arguments is provided [here](./docs/interface.md), and on the terminal by calling `lm_eval -h`. Alternatively, you can use `lm-eval` instead of `lm_eval`. + +A list of supported tasks (or groupings of tasks) can be viewed with `lm-eval --tasks list`. Task descriptions and links to corresponding subfolders are provided [here](./lm_eval/tasks/README.md). + +### Hugging Face `transformers` + +To evaluate a model hosted on the [HuggingFace Hub](https://huggingface.co/models) (e.g. GPT-J-6B) on `hellaswag` you can use the following command (this assumes you are using a CUDA-compatible GPU): + +```bash +lm_eval --model hf \ + --model_args pretrained=EleutherAI/gpt-j-6B \ + --tasks hellaswag \ + --device cuda:0 \ + --batch_size 8 +``` + +Additional arguments can be provided to the model constructor using the `--model_args` flag. Most notably, this supports the common practice of using the `revisions` feature on the Hub to store partially trained checkpoints, or to specify the datatype for running a model: + +```bash +lm_eval --model hf \ + --model_args pretrained=EleutherAI/pythia-160m,revision=step100000,dtype="float" \ + --tasks lambada_openai,hellaswag \ + --device cuda:0 \ + --batch_size 8 +``` + +Models that are loaded via both `transformers.AutoModelForCausalLM` (autoregressive, decoder-only GPT style models) and `transformers.AutoModelForSeq2SeqLM` (such as encoder-decoder models like T5) in Huggingface are supported. + +Batch size selection can be automated by setting the ```--batch_size``` flag to ```auto```. This will perform automatic detection of the largest batch size that will fit on your device. On tasks where there is a large difference between the longest and shortest example, it can be helpful to periodically recompute the largest batch size, to gain a further speedup. To do this, append ```:N``` to above flag to automatically recompute the largest batch size ```N``` times. For example, to recompute the batch size 4 times, the command would be: + +```bash +lm_eval --model hf \ + --model_args pretrained=EleutherAI/pythia-160m,revision=step100000,dtype="float" \ + --tasks lambada_openai,hellaswag \ + --device cuda:0 \ + --batch_size auto:4 +``` + +> [!Note] +> Just like you can provide a local path to `transformers.AutoModel`, you can also provide a local path to `lm_eval` via `--model_args pretrained=/path/to/model` + +#### Multi-GPU Evaluation with Hugging Face `accelerate` + +We support two main ways of using Hugging Face's [accelerate 🚀](https://github.com/huggingface/accelerate) library for multi-GPU evaluation. + +To perform *data-parallel evaluation* (where each GPU loads a **separate full copy** of the model), we leverage the `accelerate` launcher as follows: + +``` +accelerate launch -m lm_eval --model hf \ + --tasks lambada_openai,arc_easy \ + --batch_size 16 +``` +(or via `accelerate launch --no-python lm_eval`). + +For cases where your model can fit on a single GPU, this allows you to evaluate on K GPUs K times faster than on one. + +**WARNING**: This setup does not work with FSDP model sharding, so in `accelerate config` FSDP must be disabled, or the NO_SHARD FSDP option must be used. + +The second way of using `accelerate` for multi-GPU evaluation is when your model is *too large to fit on a single GPU.* + +In this setting, run the library *outside of the `accelerate` launcher*, but passing `parallelize=True` to `--model_args` as follows: + +``` +lm_eval --model hf \ + --tasks lambada_openai,arc_easy \ + --model_args parallelize=True \ + --batch_size 16 +``` + +This means that your model's weights will be split across all available GPUs. + +For more advanced users or even larger models, we allow for the following arguments when `parallelize=True` as well: +- `device_map_option`: How to split model weights across available GPUs. defaults to "auto". +- `max_memory_per_gpu`: the max GPU memory to use per GPU in loading the model. +- `max_cpu_memory`: the max amount of CPU memory to use when offloading the model weights to RAM. +- `offload_folder`: a folder where model weights will be offloaded to disk if needed. + +These two options (`accelerate launch` and `parallelize=True`) are mutually exclusive. + +**Note: we do not currently support multi-node evaluations natively, and advise using either an externally hosted server to run inference requests against, or creating a custom integration with your distributed framework [as is done for the GPT-NeoX library](https://github.com/EleutherAI/gpt-neox/blob/main/eval_tasks/eval_adapter.py).** + +### NVIDIA `nemo` models + +[NVIDIA NeMo Framework](https://github.com/NVIDIA/NeMo) is a generative AI framework built for researchers and pytorch developers working on language models. + +To evaluate a `nemo` model, start by installing NeMo following [the documentation](https://github.com/NVIDIA/NeMo?tab=readme-ov-file#installation). We highly recommended to use the NVIDIA PyTorch or NeMo container, especially if having issues installing Apex or any other dependencies (see [latest released containers](https://github.com/NVIDIA/NeMo/releases)). Please also install the lm evaluation harness library following the instructions in [the Install section](https://github.com/EleutherAI/lm-evaluation-harness/tree/main?tab=readme-ov-file#install). + +NeMo models can be obtained through [NVIDIA NGC Catalog](https://catalog.ngc.nvidia.com/models) or in [NVIDIA's Hugging Face page](https://huggingface.co/nvidia). In [NVIDIA NeMo Framework](https://github.com/NVIDIA/NeMo/tree/main/scripts/nlp_language_modeling) there are conversion scripts to convert the `hf` checkpoints of popular models like llama, falcon, mixtral or mpt to `nemo`. + +Run a `nemo` model on one GPU: +```bash +lm_eval --model nemo_lm \ + --model_args path= \ + --tasks hellaswag \ + --batch_size 32 +``` + +It is recommended to unpack the `nemo` model to avoid the unpacking inside the docker container - it may overflow disk space. For that you can run: + +``` +mkdir MY_MODEL +tar -xvf MY_MODEL.nemo -c MY_MODEL +``` + +#### Multi-GPU evaluation with NVIDIA `nemo` models + +By default, only one GPU is used. But we do support either data replication or tensor/pipeline parallelism during evaluation, on one node. + +1) To enable data replication, set the `model_args` of `devices` to the number of data replicas to run. For example, the command to run 8 data replicas over 8 GPUs is: +```bash +torchrun --nproc-per-node=8 --no-python lm_eval \ + --model nemo_lm \ + --model_args path=,devices=8 \ + --tasks hellaswag \ + --batch_size 32 +``` + +2) To enable tensor and/or pipeline parallelism, set the `model_args` of `tensor_model_parallel_size` and/or `pipeline_model_parallel_size`. In addition, you also have to set up `devices` to be equal to the product of `tensor_model_parallel_size` and/or `pipeline_model_parallel_size`. For example, the command to use one node of 4 GPUs with tensor parallelism of 2 and pipeline parallelism of 2 is: +```bash +torchrun --nproc-per-node=4 --no-python lm_eval \ + --model nemo_lm \ + --model_args path=,devices=4,tensor_model_parallel_size=2,pipeline_model_parallel_size=2 \ + --tasks hellaswag \ + --batch_size 32 +``` +Note that it is recommended to substitute the `python` command by `torchrun --nproc-per-node= --no-python` to facilitate loading the model into the GPUs. This is especially important for large checkpoints loaded into multiple GPUs. + +Not supported yet: multi-node evaluation and combinations of data replication with tensor or pipeline parallelism. + +### Tensor + Data Parallel and Optimized Inference with `vLLM` + +We also support vLLM for faster inference on [supported model types](https://docs.vllm.ai/en/latest/models/supported_models.html), especially faster when splitting a model across multiple GPUs. For single-GPU or multi-GPU — tensor parallel, data parallel, or a combination of both — inference, for example: + +```bash +lm_eval --model vllm \ + --model_args pretrained={model_name},tensor_parallel_size={GPUs_per_model},dtype=auto,gpu_memory_utilization=0.8,data_parallel_size={model_replicas} \ + --tasks lambada_openai \ + --batch_size auto +``` +To use vllm, do `pip install lm_eval[vllm]`. For a full list of supported vLLM configurations, please reference our [vLLM integration](https://github.com/EleutherAI/lm-evaluation-harness/blob/e74ec966556253fbe3d8ecba9de675c77c075bce/lm_eval/models/vllm_causallms.py) and the vLLM documentation. + +vLLM occasionally differs in output from Huggingface. We treat Huggingface as the reference implementation, and provide a [script](./scripts/model_comparator.py) for checking the validity of vllm results against HF. + +> [!Tip] +> For fastest performance, we recommend using `--batch_size auto` for vLLM whenever possible, to leverage its continuous batching functionality! + +> [!Tip] +> Passing `max_model_len=4096` or some other reasonable default to vLLM through model args may cause speedups or prevent out-of-memory errors when trying to use auto batch size, such as for Mistral-7B-v0.1 which defaults to a maximum length of 32k. + +### Model APIs and Inference Servers + +Our library also supports the evaluation of models served via several commercial APIs, and we hope to implement support for the most commonly used performant local/self-hosted inference servers. + +To call a hosted model, use: + +```bash +export OPENAI_API_KEY=YOUR_KEY_HERE +lm_eval --model openai-completions \ + --model_args model=davinci \ + --tasks lambada_openai,hellaswag +``` + +We also support using your own local inference server with servers that mirror the OpenAI Completions and ChatCompletions APIs. + +```bash +lm_eval --model local-chat-completions --tasks gsm8k --model_args model=facebook/opt-125m,base_url=http://{yourip}:8000/v1 +``` +Note that for externally hosted models, configs such as `--device` and `--batch_size` should not be used and do not function. Just like you can use `--model_args` to pass arbitrary arguments to the model constructor for local models, you can use it to pass arbitrary arguments to the model API for hosted models. See the documentation of the hosting service for information on what arguments they support. + +| API or Inference Server | Implemented? | `--model ` name | Models supported: | Request Types: | +|---------------------------------------------------------------------------------------------------------------------------|---------------------------------|---------------------------------------------------------------------|-----------------------------------------------------------------------------------------------|------------------------------------------------------------| +| OpenAI Completions | :heavy_check_mark: | `openai-completions`, `local-completions` | All OpenAI Completions API models | `generate_until`, `loglikelihood`, `loglikelihood_rolling` | +| OpenAI ChatCompletions | :heavy_check_mark: | `openai-chat-completions`, `local-chat-completions` | [All ChatCompletions API models](https://platform.openai.com/docs/guides/gpt) | `generate_until` (no logprobs) | +| Anthropic | :heavy_check_mark: | `anthropic` | [Supported Anthropic Engines](https://docs.anthropic.com/claude/reference/selecting-a-model) | `generate_until` (no logprobs) | +| Anthropic Chat | :heavy_check_mark: | `anthropic-chat`, `anthropic-chat-completions` | [Supported Anthropic Engines](https://docs.anthropic.com/claude/docs/models-overview) | `generate_until` (no logprobs) | +| Textsynth | :heavy_check_mark: | `textsynth` | [All supported engines](https://textsynth.com/documentation.html#engines) | `generate_until`, `loglikelihood`, `loglikelihood_rolling` | +| Cohere | [:hourglass: - blocked on Cohere API bug](https://github.com/EleutherAI/lm-evaluation-harness/pull/395) | N/A | [All `cohere.generate()` engines](https://docs.cohere.com/docs/models) | `generate_until`, `loglikelihood`, `loglikelihood_rolling` | +| [Llama.cpp](https://github.com/ggerganov/llama.cpp) (via [llama-cpp-python](https://github.com/abetlen/llama-cpp-python)) | :heavy_check_mark: | `gguf`, `ggml` | [All models supported by llama.cpp](https://github.com/ggerganov/llama.cpp) | `generate_until`, `loglikelihood`, (perplexity evaluation not yet implemented) | +| vLLM | :heavy_check_mark: | `vllm` | [Most HF Causal Language Models](https://docs.vllm.ai/en/latest/models/supported_models.html) | `generate_until`, `loglikelihood`, `loglikelihood_rolling` | +| Mamba | :heavy_check_mark: | `mamba_ssm` | [Mamba architecture Language Models via the `mamba_ssm` package](https://huggingface.co/state-spaces) | `generate_until`, `loglikelihood`, `loglikelihood_rolling` | +| Huggingface Optimum (Causal LMs) | ✔️ | `openvino` | Any decoder-only AutoModelForCausalLM converted with Huggingface Optimum into OpenVINO™ Intermediate Representation (IR) format | `generate_until`, `loglikelihood`, `loglikelihood_rolling` | ... | +| Neuron via AWS Inf2 (Causal LMs) | ✔️ | `neuronx` | Any decoder-only AutoModelForCausalLM supported to run on [huggingface-ami image for inferentia2](https://aws.amazon.com/marketplace/pp/prodview-gr3e6yiscria2) | `generate_until`, `loglikelihood`, `loglikelihood_rolling` | ... | +| [Neural Magic DeepSparse](https://github.com/neuralmagic/deepsparse) | ✔️ | `deepsparse` | Any LM from [SparseZoo](https://sparsezoo.neuralmagic.com/) or on [HF Hub with the "deepsparse" tag](https://huggingface.co/models?other=deepsparse) | `generate_until`, `loglikelihood` | ... | +| [Neural Magic SparseML](https://github.com/neuralmagic/sparseml) | ✔️ | `sparseml` | Any decoder-only AutoModelForCausalLM from [SparseZoo](https://sparsezoo.neuralmagic.com/) or on [HF Hub](https://huggingface.co/neuralmagic). Especially useful for models with quantization like [`zoo:llama2-7b-gsm8k_llama2_pretrain-pruned60_quantized`](https://sparsezoo.neuralmagic.com/models/llama2-7b-gsm8k_llama2_pretrain-pruned60_quantized) | `generate_until`, `loglikelihood`, `loglikelihood_rolling` | ... | +| Your local inference server! | :heavy_check_mark: | `local-completions` or `local-chat-completions` (using `openai-chat-completions` model type) | Any server address that accepts GET requests using HF models and mirror's OpenAI's Completions or ChatCompletions interface | `generate_until` | | ... | + +Models which do not supply logits or logprobs can be used with tasks of type `generate_until` only, while local models, or APIs that supply logprobs/logits of their prompts, can be run on all task types: `generate_until`, `loglikelihood`, `loglikelihood_rolling`, and `multiple_choice`. + +For more information on the different task `output_types` and model request types, see [our documentation](https://github.com/EleutherAI/lm-evaluation-harness/blob/main/docs/model_guide.md#interface). + +> [!Note] +> For best performance with closed chat model APIs such as Anthropic Claude 3 and GPT-4, we recommend carefully looking at a few sample outputs using `--limit 10` first to confirm answer extraction and scoring on generative tasks is performing as expected. providing `system=""` within `--model_args` for anthropic-chat-completions, to instruct the model what format to respond in, may be useful. + + +### Other Frameworks + +A number of other libraries contain scripts for calling the eval harness through their library. These include [GPT-NeoX](https://github.com/EleutherAI/gpt-neox/blob/main/eval_tasks/eval_adapter.py), [Megatron-DeepSpeed](https://github.com/microsoft/Megatron-DeepSpeed/blob/main/examples/MoE/readme_evalharness.md), and [mesh-transformer-jax](https://github.com/kingoflolz/mesh-transformer-jax/blob/master/eval_harness.py). + +To create your own custom integration you can follow instructions from [this tutorial](https://github.com/EleutherAI/lm-evaluation-harness/blob/main/docs/interface.md#external-library-usage). + +### Additional Features +> [!Note] +> For tasks unsuitable for direct evaluation — either due risks associated with executing untrusted code or complexities in the evaluation process — the `--predict_only` flag is available to obtain decoded generations for post-hoc evaluation. + +If you have a Metal compatible Mac, you can run the eval harness using the MPS back-end by replacing `--device cuda:0` with `--device mps` (requires PyTorch version 2.1 or higher). **Note that the PyTorch MPS backend is still in early stages of development, so correctness issues or unsupported operations may exist. If you observe oddities in model performance on the MPS back-end, we recommend first checking that a forward pass of your model on `--device cpu` and `--device mps` match.** + +> [!Note] +> You can inspect what the LM inputs look like by running the following command: +> ```bash +> python write_out.py \ +> --tasks \ +> --num_fewshot 5 \ +> --num_examples 10 \ +> --output_base_path /path/to/output/folder +> ``` +> This will write out one text file for each task. + +To verify the data integrity of the tasks you're performing in addition to running the tasks themselves, you can use the `--check_integrity` flag: + +```bash +lm_eval --model openai \ + --model_args engine=davinci \ + --tasks lambada_openai,hellaswag \ + --check_integrity +``` + +## Advanced Usage Tips + +For models loaded with the HuggingFace `transformers` library, any arguments provided via `--model_args` get passed to the relevant constructor directly. This means that anything you can do with `AutoModel` can be done with our library. For example, you can pass a local path via `pretrained=` or use models finetuned with [PEFT](https://github.com/huggingface/peft) by taking the call you would run to evaluate the base model and add `,peft=PATH` to the `model_args` argument: +```bash +lm_eval --model hf \ + --model_args pretrained=EleutherAI/gpt-j-6b,parallelize=True,load_in_4bit=True,peft=nomic-ai/gpt4all-j-lora \ + --tasks openbookqa,arc_easy,winogrande,hellaswag,arc_challenge,piqa,boolq \ + --device cuda:0 +``` + +Models provided as delta weights can be easily loaded using the Hugging Face transformers library. Within --model_args, set the delta argument to specify the delta weights, and use the pretrained argument to designate the relative base model to which they will be applied: +```bash +lm_eval --model hf \ + --model_args pretrained=Ejafa/llama_7B,delta=lmsys/vicuna-7b-delta-v1.1 \ + --tasks hellaswag +``` + +[GPTQ](https://github.com/PanQiWei/AutoGPTQ) quantized models can be loaded by specifying their file names in `,autogptq=NAME` (or `,autogptq=True` for default names) in the `model_args` argument: + +```bash +lm_eval --model hf \ + --model_args pretrained=model-name-or-path,autogptq=model.safetensors,gptq_use_triton=True \ + --tasks hellaswag +``` + +We support wildcards in task names, for example you can run all of the machine-translated lambada tasks via `--task lambada_openai_mt_*`. + +## Saving Results + +To save evaluation results provide an `--output_path`. We also support logging model responses with the `--log_samples` flag for post-hoc analysis. + +Additionally, one can provide a directory with `--use_cache` to cache the results of prior runs. This allows you to avoid repeated execution of the same (model, task) pairs for re-scoring. + +To push results and samples to the Hugging Face Hub, first ensure an access token with write access is set in the `HF_TOKEN` environment variable. Then, use the `--hf_hub_log_args` flag to specify the organization, repository name, repository visibility, and whether to push results and samples to the Hub - [example dataset on the HF Hub](https://huggingface.co/datasets/KonradSzafer/lm-eval-results-demo). For instance: + +```bash +lm_eval --model hf \ + --model_args pretrained=model-name-or-path,autogptq=model.safetensors,gptq_use_triton=True \ + --tasks hellaswag \ + --log_samples \ + --output_path results \ + --hf_hub_log_args hub_results_org=EleutherAI,hub_repo_name=lm-eval-results,push_results_to_hub=True,push_samples_to_hub=True,public_repo=False \ +``` + +This allows you to easily download the results and samples from the Hub, using: +```python +from datasets import load_dataset + +load_dataset("EleutherAI/lm-eval-results-private", "hellaswag", "latest") +``` + +For a full list of supported arguments, check out the [interface](https://github.com/EleutherAI/lm-evaluation-harness/blob/main/docs/interface.md) guide in our documentation! + +## Visualizing Results + +You can seamlessly visualize and analyze the results of your evaluation harness runs using both Weights & Biases (W&B) and Zeno. + +### Zeno + +You can use [Zeno](https://zenoml.com) to visualize the results of your eval harness runs. + +First, head to [hub.zenoml.com](https://hub.zenoml.com) to create an account and get an API key [on your account page](https://hub.zenoml.com/account). +Add this key as an environment variable: + +```bash +export ZENO_API_KEY=[your api key] +``` + +You'll also need to install the `lm_eval[zeno]` package extra. + +To visualize the results, run the eval harness with the `log_samples` and `output_path` flags. +We expect `output_path` to contain multiple folders that represent individual model names. +You can thus run your evaluation on any number of tasks and models and upload all of the results as projects on Zeno. + +```bash +lm_eval \ + --model hf \ + --model_args pretrained=EleutherAI/gpt-j-6B \ + --tasks hellaswag \ + --device cuda:0 \ + --batch_size 8 \ + --log_samples \ + --output_path output/gpt-j-6B +``` + +Then, you can upload the resulting data using the `zeno_visualize` script: + +```bash +python scripts/zeno_visualize.py \ + --data_path output \ + --project_name "Eleuther Project" +``` + +This will use all subfolders in `data_path` as different models and upload all tasks within these model folders to Zeno. +If you run the eval harness on multiple tasks, the `project_name` will be used as a prefix and one project will be created per task. + +You can find an example of this workflow in [examples/visualize-zeno.ipynb](examples/visualize-zeno.ipynb). + +### Weights and Biases + +With the [Weights and Biases](https://wandb.ai/site) integration, you can now spend more time extracting deeper insights into your evaluation results. The integration is designed to streamline the process of logging and visualizing experiment results using the Weights & Biases (W&B) platform. + +The integration provide functionalities + +- to automatically log the evaluation results, +- log the samples as W&B Tables for easy visualization, +- log the `results.json` file as an artifact for version control, +- log the `_eval_samples.json` file if the samples are logged, +- generate a comprehensive report for analysis and visualization with all the important metric, +- log task and cli specific configs, +- and more out of the box like the command used to run the evaluation, GPU/CPU counts, timestamp, etc. + +First you'll need to install the lm_eval[wandb] package extra. Do `pip install lm_eval[wandb]`. + +Authenticate your machine with an your unique W&B token. Visit https://wandb.ai/authorize to get one. Do `wandb login` in your command line terminal. + +Run eval harness as usual with a `wandb_args` flag. Use this flag to provide arguments for initializing a wandb run ([wandb.init](https://docs.wandb.ai/ref/python/init)) as comma separated string arguments. + +```bash +lm_eval \ + --model hf \ + --model_args pretrained=microsoft/phi-2,trust_remote_code=True \ + --tasks hellaswag,mmlu_abstract_algebra \ + --device cuda:0 \ + --batch_size 8 \ + --output_path output/phi-2 \ + --limit 10 \ + --wandb_args project=lm-eval-harness-integration \ + --log_samples +``` + +In the stdout, you will find the link to the W&B run page as well as link to the generated report. You can find an example of this workflow in [examples/visualize-wandb.ipynb](examples/visualize-wandb.ipynb), and an example of how to integrate it beyond the CLI. + +## How to Contribute or Learn More? + +For more information on the library and how everything fits together, check out all of our [documentation pages](https://github.com/EleutherAI/lm-evaluation-harness/tree/main/docs)! We plan to post a larger roadmap of desired + planned library improvements soon, with more information on how contributors can help. + +### Implementing new tasks + +To implement a new task in the eval harness, see [this guide](./docs/new_task_guide.md). + +In general, we follow this priority list for addressing concerns about prompting and other eval details: +1. If there is widespread agreement among people who train LLMs, use the agreed upon procedure. +2. If there is a clear and unambiguous official implementation, use that procedure. +3. If there is widespread agreement among people who evaluate LLMs, use the agreed upon procedure. +4. If there are multiple common implementations but not universal or widespread agreement, use our preferred option among the common implementations. As before, prioritize choosing from among the implementations found in LLM training papers. + +These are guidelines and not rules, and can be overruled in special circumstances. + +We try to prioritize agreement with the procedures used by other groups to decrease the harm when people inevitably compare runs across different papers despite our discouragement of the practice. Historically, we also prioritized the implementation from [Language Models are Few Shot Learners](https://arxiv.org/abs/2005.14165) as our original goal was specifically to compare results with that paper. + +### Support + +The best way to get support is to open an issue on this repo or join the [EleutherAI Discord server](https://discord.gg/eleutherai). The `#lm-thunderdome` channel is dedicated to developing this project and the `#release-discussion` channel is for receiving support for our releases. If you've used the library and have had a positive (or negative) experience, we'd love to hear from you! + +## Optional Extras +Extras dependencies can be installed via `pip install -e ".[NAME]"` + +| Name | Use | +|---------------|---------------------------------------| +| anthropic | For using Anthropic's models | +| deepsparse | For running NM's DeepSparse models | +| dev | For linting PRs and contributions | +| gptq | For loading models with GPTQ | +| hf_transfer | For speeding up HF Hub file downloads | +| ifeval | For running the IFEval task | +| neuronx | For running on AWS inf2 instances | +| mamba | For loading Mamba SSM models | +| math | For running math task answer checking | +| multilingual | For multilingual tokenizers | +| openai | For using OpenAI's models | +| optimum | For running Intel OpenVINO models | +| promptsource | For using PromptSource prompts | +| sentencepiece | For using the sentencepiece tokenizer | +| sparseml | For using NM's SparseML models | +| testing | For running library test suite | +| unitxt | For IBM's unitxt dataset tasks | +| vllm | For loading models with vLLM | +| zeno | For visualizing results with Zeno | +|---------------|---------------------------------------| +| all | Loads all extras (not recommended) | + +## Cite as + +``` +@misc{eval-harness, + author = {Gao, Leo and Tow, Jonathan and Abbasi, Baber and Biderman, Stella and Black, Sid and DiPofi, Anthony and Foster, Charles and Golding, Laurence and Hsu, Jeffrey and Le Noac'h, Alain and Li, Haonan and McDonell, Kyle and Muennighoff, Niklas and Ociepa, Chris and Phang, Jason and Reynolds, Laria and Schoelkopf, Hailey and Skowron, Aviya and Sutawika, Lintang and Tang, Eric and Thite, Anish and Wang, Ben and Wang, Kevin and Zou, Andy}, + title = {A framework for few-shot language model evaluation}, + month = 12, + year = 2023, + publisher = {Zenodo}, + version = {v0.4.0}, + doi = {10.5281/zenodo.10256836}, + url = {https://zenodo.org/records/10256836} +} +``` diff --git a/venv/lib/python3.10/site-packages/lm_eval-0.4.3.dist-info/RECORD b/venv/lib/python3.10/site-packages/lm_eval-0.4.3.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..9c9cc0bc4935e451a2ffae7dfe3a8ead12eb92b0 --- /dev/null +++ b/venv/lib/python3.10/site-packages/lm_eval-0.4.3.dist-info/RECORD @@ -0,0 +1,2770 @@ +../../../bin/lm-eval,sha256=G4SLXvDRZ0WOkIfsdwBcSIV0tKBc7q6wPknRxL3D2GM,301 +../../../bin/lm_eval,sha256=G4SLXvDRZ0WOkIfsdwBcSIV0tKBc7q6wPknRxL3D2GM,301 +lm_eval-0.4.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +lm_eval-0.4.3.dist-info/LICENSE.md,sha256=qAbkJUdiDf-8LsAzMyLIs1I7SvEeBZvhTvgapbGuAh8,1067 +lm_eval-0.4.3.dist-info/METADATA,sha256=y4Zw7obqShvwLrbU3xGT_nUVA8iEl4NY3beOgDVSP9g,38610 +lm_eval-0.4.3.dist-info/RECORD,, +lm_eval-0.4.3.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +lm_eval-0.4.3.dist-info/WHEEL,sha256=mguMlWGMX-VHnMpKOjjQidIo1ssRlCFu4a4mBpz1s2M,91 +lm_eval-0.4.3.dist-info/entry_points.txt,sha256=mMr4hFXQwSHYb924AKGzP6dbbBAWcXiyBO-AfXrV72E,98 +lm_eval-0.4.3.dist-info/top_level.txt,sha256=risQwf3pU3EoXaYL_bKYFzW6EtBOvJxJotKdDz605Dk,8 +lm_eval/__init__.py,sha256=9-jqCb66p_m29iqX1zVNpo_MzAIGznMZKNKOZKfEsxI,49 +lm_eval/__main__.py,sha256=ksX1NIsbwUaw1jkH6ZDQFy8MsApvakY5Pcz2mZrTgew,16378 +lm_eval/__pycache__/__init__.cpython-310.pyc,, +lm_eval/__pycache__/__main__.cpython-310.pyc,, +lm_eval/__pycache__/evaluator.cpython-310.pyc,, +lm_eval/__pycache__/evaluator_utils.cpython-310.pyc,, +lm_eval/__pycache__/utils.cpython-310.pyc,, +lm_eval/api/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +lm_eval/api/__pycache__/__init__.cpython-310.pyc,, +lm_eval/api/__pycache__/filter.cpython-310.pyc,, +lm_eval/api/__pycache__/instance.cpython-310.pyc,, +lm_eval/api/__pycache__/metrics.cpython-310.pyc,, +lm_eval/api/__pycache__/model.cpython-310.pyc,, +lm_eval/api/__pycache__/registry.cpython-310.pyc,, +lm_eval/api/__pycache__/samplers.cpython-310.pyc,, +lm_eval/api/__pycache__/task.cpython-310.pyc,, +lm_eval/api/filter.py,sha256=4XR0Sj7K_3ivNKYNYHS8iUWAHaUMYCjVj0ZMsoZsff4,2149 +lm_eval/api/instance.py,sha256=neYbqoO3cakbUJYT1Dp9IYm0WU10XWTlAEC6Da_4ZZA,1060 +lm_eval/api/metrics.py,sha256=PUJ0OZzOdlT7XALMLmWliypjLnoY7rI6hjKYifxp5VA,16720 +lm_eval/api/model.py,sha256=lEvesJ8A4lbLRBowpvjoNIseEGIsvMiY0cL2SYDd91s,14215 +lm_eval/api/registry.py,sha256=O1GO1VpKBUVMWMlb7725UN-Qtx6VYWmR4426ldjFj7E,5226 +lm_eval/api/samplers.py,sha256=ndUkncgA_1sgoUQkXxbRhLVokSpd5YwC8j01JCaPWyQ,5940 +lm_eval/api/task.py,sha256=nMrfFMHMdfo2pk8kTS8bceCotcDQp9SmRhzR30YMYjo,64920 +lm_eval/caching/__pycache__/cache.cpython-310.pyc,, +lm_eval/caching/cache.py,sha256=lvukmRzezPjojXLw8L01H0asOGu-mwwk1EHKgX5ZrxI,1345 +lm_eval/decontamination/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +lm_eval/decontamination/__pycache__/__init__.cpython-310.pyc,, +lm_eval/decontamination/__pycache__/archiver.cpython-310.pyc,, +lm_eval/decontamination/__pycache__/decontaminate.cpython-310.pyc,, +lm_eval/decontamination/__pycache__/janitor.cpython-310.pyc,, +lm_eval/decontamination/archiver.py,sha256=3XtedMPsXAN0_zA5yyYDAH36vttZphkAJ0YwGK8xy3Q,5732 +lm_eval/decontamination/decontaminate.py,sha256=Jgu8HpvJnQL0nySL1hGN9qwnRshDvuW-_I13QZfKaA0,6817 +lm_eval/decontamination/janitor.py,sha256=tIZLlI920eKtaNlSiualDTJPO7P42PbxInfBezK5iYI,13150 +lm_eval/evaluator.py,sha256=t-d3QrbQz9Qf7EfF8vFUKDMWpJMdYM6rmOWRo-SWLzo,28277 +lm_eval/evaluator_utils.py,sha256=fG7q0AyER-q2GVW8VcIiw32FN3ER-Wljlk2cyRsoqHY,13220 +lm_eval/filters/__init__.py,sha256=u7nOabMXrIx3BYeqVehtY-tjPPgmrWSroVV5Ba_al6Q,696 +lm_eval/filters/__pycache__/__init__.cpython-310.pyc,, +lm_eval/filters/__pycache__/decontamination.cpython-310.pyc,, +lm_eval/filters/__pycache__/extraction.cpython-310.pyc,, +lm_eval/filters/__pycache__/selection.cpython-310.pyc,, +lm_eval/filters/__pycache__/transformation.cpython-310.pyc,, +lm_eval/filters/decontamination.py,sha256=kEAWSsDcA65LX38NRNc_0JY_4yS17z-0IMG4OPOSO3I,712 +lm_eval/filters/extraction.py,sha256=IcCKWUI4WA9BZwlKl-jsyzvuoCT4ZK-7jAkgJ_vn8eE,6555 +lm_eval/filters/selection.py,sha256=mgKFCRTrJVGoR204_P9LoB_dDqsyTZT-ZyLpyTibLUc,2105 +lm_eval/filters/transformation.py,sha256=yfdnP7PDApTfAfQbl-e9EPc4Tp2CXNqszqIbDZPqub0,1730 +lm_eval/loggers/__init__.py,sha256=dg8zEHqZajiJnMl47q9rwU4yhmSr0QisXAItN_YSdx4,88 +lm_eval/loggers/__pycache__/__init__.cpython-310.pyc,, +lm_eval/loggers/__pycache__/evaluation_tracker.cpython-310.pyc,, +lm_eval/loggers/__pycache__/utils.cpython-310.pyc,, +lm_eval/loggers/__pycache__/wandb_logger.cpython-310.pyc,, +lm_eval/loggers/evaluation_tracker.py,sha256=4zH6c9AD96IVcy-q3ogX3mBDtWisYHvAI97KCMMFX2Q,23534 +lm_eval/loggers/utils.py,sha256=EjSuuBFmTz7PJoC6Ph_J5ngB8wX_SLeSFbHz0m4LV5o,4972 +lm_eval/loggers/wandb_logger.py,sha256=ud2g6mFt_ABj4x_OsTEFWheaqdIDOY6Jn1MExA-hPg0,13351 +lm_eval/models/__init__.py,sha256=cPp_3MBedVmkKXRGnyZyhwY9JkeUN95WJkjfqmFqUZU,484 +lm_eval/models/__pycache__/__init__.cpython-310.pyc,, +lm_eval/models/__pycache__/anthropic_llms.cpython-310.pyc,, +lm_eval/models/__pycache__/dummy.cpython-310.pyc,, +lm_eval/models/__pycache__/gguf.cpython-310.pyc,, +lm_eval/models/__pycache__/huggingface.cpython-310.pyc,, +lm_eval/models/__pycache__/mamba_lm.cpython-310.pyc,, +lm_eval/models/__pycache__/nemo_lm.cpython-310.pyc,, +lm_eval/models/__pycache__/neuralmagic.cpython-310.pyc,, +lm_eval/models/__pycache__/neuron_optimum.cpython-310.pyc,, +lm_eval/models/__pycache__/openai_completions.cpython-310.pyc,, +lm_eval/models/__pycache__/optimum_lm.cpython-310.pyc,, +lm_eval/models/__pycache__/textsynth.cpython-310.pyc,, +lm_eval/models/__pycache__/utils.cpython-310.pyc,, +lm_eval/models/__pycache__/vllm_causallms.cpython-310.pyc,, +lm_eval/models/anthropic_llms.py,sha256=14gaFizWdiZ_QTPw0tOCJgbMVhuLG2UYlAiU3WGkapY,12436 +lm_eval/models/dummy.py,sha256=4GVF2M-BKATRUJjYz-eO6saZdJX0NTjYFrrMlGPUGl0,991 +lm_eval/models/gguf.py,sha256=YpsiL-W-kpecylH8FkXbaOOylgA8sYO3P4L0sHZOGDU,4782 +lm_eval/models/huggingface.py,sha256=uNnaNcVPh-SQ0PavnlYv9cqF3KEG-g8YCOg8epdFLQk,55937 +lm_eval/models/mamba_lm.py,sha256=Ogm3qozLM6ZD_yO1o7ffY49246E_Kf5l0ZWfkYX1cQU,4485 +lm_eval/models/nemo_lm.py,sha256=NCmOqfSJyFyb6yOqYBaa7CrCydtdxbFHri6M_3yjnLo,18825 +lm_eval/models/neuralmagic.py,sha256=SXNTpIl1nHkAuaehDhQ7Np35OelNkhtfn1ON-44Hxu0,15243 +lm_eval/models/neuron_optimum.py,sha256=lGOkhCqjWdYCaMgthUx4Xq97lBc5Mml2R5cQX_Nn3ZY,30003 +lm_eval/models/openai_completions.py,sha256=8suYlvhJ21TGpSgQEmFLdx8TddI2I3Xzlb9vAXj84w0,17220 +lm_eval/models/optimum_lm.py,sha256=WaZyy7txt_pIiQDtDN_ddGOD9SmJEtnSh8x0SjWbA14,2898 +lm_eval/models/textsynth.py,sha256=nZmEkxOaWAhmzFkGSI27n49O9uVDExIcvHZzGVhhGfQ,5877 +lm_eval/models/utils.py,sha256=gwJ5UPyvNIpkCqBUxexCO25jZ1IDIU-_V6JhvuDZFqE,23751 +lm_eval/models/vllm_causallms.py,sha256=cNviaFvvDVLjYfcttUvYSrGpiDkN-1TgxjAiIQDx4W4,21135 +lm_eval/prompts/__init__.py,sha256=r71EOQNKpkVkGCgNccsrCjGh7tRMRaDolZPB5s6el0M,4446 +lm_eval/prompts/__pycache__/__init__.cpython-310.pyc,, +lm_eval/tasks/README.md,sha256=2l9GeohlaIaEqpNMXFet4ZJOMy9JYpPHJ5vy7fOKrfc,15001 +lm_eval/tasks/__init__.py,sha256=4kZFqvX7B376z4BDdVULJ-9r5BPhQFD9QT4jA-3KcjU,17939 +lm_eval/tasks/__pycache__/__init__.cpython-310.pyc,, +lm_eval/tasks/aclue/README.md,sha256=P7SipDY23M6HzsmEbBt809YzqA3-W37KcwUmbRJbVv0,2281 +lm_eval/tasks/aclue/__pycache__/_generate_configs.cpython-310.pyc,, +lm_eval/tasks/aclue/_default_template_yaml,sha256=edY467NsdF0URKzOm5iqbgPkthkmy2laLgBz-AHFmac,494 +lm_eval/tasks/aclue/_generate_configs.py,sha256=OVNccuRC0MpF19ZniYbkq6OjdNGn6wqPFdlizt_-W-Q,2736 +lm_eval/tasks/aclue/aclue_ancient_chinese_culture.yaml,sha256=yeDtywfegrPtq2MiKG0hXuRnn3LDHLodH0gOGs1kKyg,227 +lm_eval/tasks/aclue/aclue_ancient_literature.yaml,sha256=kya_5Yp-K9yEGqL0pWmugIfgCkP4E8HWhxFgjmKhcpY,223 +lm_eval/tasks/aclue/aclue_ancient_medical.yaml,sha256=BjLOppaVH62sjg7SdQtdzrO1caTV09ZB6okem_C_3vw,208 +lm_eval/tasks/aclue/aclue_ancient_phonetics.yaml,sha256=yllcVwZldzXuxsslwN-IfDMjGsaU8HRU-Au3kW4WrfY,212 +lm_eval/tasks/aclue/aclue_basic_ancient_chinese.yaml,sha256=_SXDkd-LC0N9L6ig_yMJQy4air_0abawIGsYjQ3nIOc,226 +lm_eval/tasks/aclue/aclue_couplet_prediction.yaml,sha256=DYmdXpGq84nJIYzbNklMIDyrHD_4Ljuyj4BjD7W_-fc,211 +lm_eval/tasks/aclue/aclue_homographic_character_resolution.yaml,sha256=NZZQUew5LHtCzOpHTYxlcBwrb3CN8wf4bXDt6LXSYeM,242 +lm_eval/tasks/aclue/aclue_named_entity_recognition.yaml,sha256=LABArA0Mqmjt06B4k8RzcBAWuoT7lJ0lpwGZvrfIdlA,241 +lm_eval/tasks/aclue/aclue_poetry_appreciate.yaml,sha256=_BMywf9HD5yYIsXFbud-FTroje52SDIGKdD1qlHh5vo,221 +lm_eval/tasks/aclue/aclue_poetry_context_prediction.yaml,sha256=G-qpD7dBBcEUMk0kyJhRlcuksE8u6qYZtP2HUsZmRSs,243 +lm_eval/tasks/aclue/aclue_poetry_quality_assessment.yaml,sha256=kW6to6KJUoSgb_uXHJVW7Y9iSZTF2-IW7S0EzHB7iSk,240 +lm_eval/tasks/aclue/aclue_poetry_sentiment_analysis.yaml,sha256=ujIRE9_k0PW3ovkcKhHA5eLMb4ofaNGoFROO_D0blNk,237 +lm_eval/tasks/aclue/aclue_polysemy_resolution.yaml,sha256=I16ro2xhSU6_U_UqVTAy2_x3YoBrd7EE0N8sIMk-7sw,225 +lm_eval/tasks/aclue/aclue_reading_comprehension.yaml,sha256=fnHlDvVi7gtuvIfY9VRgFi6GihpEKFrTecGIGebAuXA,229 +lm_eval/tasks/aclue/aclue_sentence_segmentation.yaml,sha256=KK8apU0lMtg-ZQ86kx8ACNsTiJI8_Y2HtnsevUFrbW8,223 +lm_eval/tasks/aexams/README.md,sha256=NUAKuII6CMzTeYh-r1x7Z2fU6cdRwSZcEU2-OZT741g,1862 +lm_eval/tasks/aexams/_default_template_yaml,sha256=piAo84-HBnRc04Yo9mxRwboFIb8ZrqoIN4FCaMAx3-M,501 +lm_eval/tasks/aexams/aexams_Biology.yaml,sha256=wDN2gfFm0U30tRM0TCS3gvIJu9zSIxjpZePKPFWkhGY,190 +lm_eval/tasks/aexams/aexams_IslamicStudies.yaml,sha256=cmNYbL7ihokT1HRTHrwWnGxF3U7csYVUl5Ha5m9Zcwo,209 +lm_eval/tasks/aexams/aexams_Physics.yaml,sha256=qoBzKeeuIfF0bqG6p0N1EzXVRhVAjehnAlPw-iIUODg,180 +lm_eval/tasks/aexams/aexams_Science.yaml,sha256=LMWp9mQgMfwcQezmoCFX273lzj8LawQ-xaXRgjP_v_w,176 +lm_eval/tasks/aexams/aexams_Social.yaml,sha256=ApUU3LYxwhnwtrMO--6DLWMlbMgWGcIxdXNc0KwQ4qg,195 +lm_eval/tasks/agieval/README.md,sha256=4-5Y3TTifmMi5RYvaOI6-K8OIjEzEyEcKJrjhKEXvLA,5284 +lm_eval/tasks/agieval/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/agieval/aqua-rat.yaml,sha256=gT6vwucinFH8W5_aInXPB0NisHpAKU48LZmFCOiFnLk,527 +lm_eval/tasks/agieval/gaokao-biology.yaml,sha256=kZi4eR1SZDESnZmerDJPCezXjunP3YrDPSFsu9iOHuI,129 +lm_eval/tasks/agieval/gaokao-chemistry.yaml,sha256=OL_jXAkBQnCRnWG69TEjARFEVq1ore9WDn56TB0az4w,133 +lm_eval/tasks/agieval/gaokao-chinese.yaml,sha256=kd9tSkMUTZeXnzfyp71T8CWBuGMMIY4uYNSyeYO29n4,129 +lm_eval/tasks/agieval/gaokao-english.yaml,sha256=h8YomRmJ2ys7eLxmZ5Dj5TX_4KSsfXK2tMGmcmacZWw,215 +lm_eval/tasks/agieval/gaokao-geography.yaml,sha256=jPNST_8Dc9Tj1RiStvDgSGMHHaR6LYlLwde803w7i4A,133 +lm_eval/tasks/agieval/gaokao-history.yaml,sha256=YLQoEVj04dmLsjgxBHcZDGa1WZdTjyPmtDZffNWFlWA,129 +lm_eval/tasks/agieval/gaokao-mathcloze.yaml,sha256=gf1AKLXNohHwfCJuFVmltl4GIxIkHGRigcsRgKKj1GU,519 +lm_eval/tasks/agieval/gaokao-mathqa.yaml,sha256=UvLl4KwZ0rc-ZZ58L2FMzAiMTnI_HwCkDROd_Jfxs9U,127 +lm_eval/tasks/agieval/gaokao-physics.yaml,sha256=Zqevi3QqV92sH3eUGidPqm6LFc3ItN0uc20VnnuA-Y8,129 +lm_eval/tasks/agieval/jec-qa-ca.yaml,sha256=DaMlJ_ihgRsYERG00qmSHBJYEJR1EiZXfDHOGmDTbm0,119 +lm_eval/tasks/agieval/jec-qa-kd.yaml,sha256=eCeLdKz7RqE_QYNZgx9RHq2jKJhGhstX_V3yHTfcJrQ,119 +lm_eval/tasks/agieval/logiqa-en.yaml,sha256=ZFIZtHFY2wrUJwyYRxnDGKdBTGLFiHo8TXt7RHlha9g,136 +lm_eval/tasks/agieval/logiqa-zh.yaml,sha256=0UKloM8kf747py0VHAXoyZTrX5vPgYAnGUjGl3RAdpU,119 +lm_eval/tasks/agieval/lsat-ar.yaml,sha256=Rg87LmnOxcGzlyR1vOz5SL3DsaPN8a68Vhl_ENYDDB8,132 +lm_eval/tasks/agieval/lsat-lr.yaml,sha256=bKV9lLrlyJpWjaH5ETQBBMaqDRNuaKQMfolmGlXz6VI,132 +lm_eval/tasks/agieval/lsat-rc.yaml,sha256=_qmu-0xRCyhPJ0VzBVQnk5oSh4NbyrDHGb8r8z_i-aw,132 +lm_eval/tasks/agieval/math.yaml,sha256=6zY1wOeb0bXPV2_tSF2FkRL8OX0U8RBE3tFJCVlAUeM,495 +lm_eval/tasks/agieval/sat-en-without-passage.yaml,sha256=H_ZK7EpwEd1YCPKnItxQf0xn3mCdLq_6ksBoi9WK7-w,162 +lm_eval/tasks/agieval/sat-en.yaml,sha256=gzueP_6a0mbnBNkHUrKVQkmSaawfN6p5Ib0zBT1fVb4,130 +lm_eval/tasks/agieval/sat-math.yaml,sha256=8qAMy8siQCqUN7ujzJzNy8VsPH-sj7j9vjIDgXX5774,134 +lm_eval/tasks/agieval/utils.py,sha256=LrPDL8tQP7swC0UC9LV0h5HBVyYJj9s79hP8VG4awjA,7846 +lm_eval/tasks/alghafa/copa_ar/README.md,sha256=VH8IXNesLcOwA0A8zT7MWsujhsOi5A_kyjIXBaknYYE,1273 +lm_eval/tasks/alghafa/copa_ar/copa_ar.yaml,sha256=Sm9qq--diqI6ZqvSvNH5FdYlqyM9UDIDCY9Q2_Ywc2Y,498 +lm_eval/tasks/alghafa/piqa_ar/README.md,sha256=HdCbujoP2DyVHjPdl0XW8m207HJXh1CdbfjTYQSiEH4,1487 +lm_eval/tasks/alghafa/piqa_ar/piqa_ar.yaml,sha256=kNDNb0-6DkY0PhoyUm7XmfXTTXRCeuK10os9QXRlJ1I,496 +lm_eval/tasks/anli/README.md,sha256=QKLZp7Ox21Wn815nwzGczGu7Bce0fQVTRmlduKlckWU,2042 +lm_eval/tasks/anli/anli_r1.yaml,sha256=pKwidjBQrQnVwE556yItUUCLE3kfV2WPTCTbt-l0mro,595 +lm_eval/tasks/anli/anli_r2.yaml,sha256=nHP-W_OHCZpr9VjX3AiRsrLVV4Cb25vSfuHRN5CmTlc,106 +lm_eval/tasks/anli/anli_r3.yaml,sha256=AgUdUSygTWd9giQsVVLEauQKz5NZQxjtGNBTKW3RKXo,106 +lm_eval/tasks/arabicmmlu/README.md,sha256=UCuP1eNJmjY_z1heNWnf454zsYk2geWiK4IEj3M9AwI,2949 +lm_eval/tasks/arabicmmlu/__pycache__/_generate_configs.cpython-310.pyc,, +lm_eval/tasks/arabicmmlu/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/arabicmmlu/_default_template_yaml,sha256=Ss2sRTY1sXbW4bCX5vpXsA-7Kn8dYp6_WQAnFqImbYE,325 +lm_eval/tasks/arabicmmlu/_generate_configs.py,sha256=9tBVH1UtBkf7YJWFaOdm3NLf1maiJIK-USbiK5LNB6Q,3936 +lm_eval/tasks/arabicmmlu/arabicmmlu.yaml,sha256=m2Ayq16r_-RqnkKheqorv1A8G9QqlzBlGd9wz27_0ZA,135 +lm_eval/tasks/arabicmmlu/arabicmmlu_arabic_language_general.yaml,sha256=ARbbOsIfRiiX7tB9QFiRatvaCatKUbkAFgKm6OX0eJY,226 +lm_eval/tasks/arabicmmlu/arabicmmlu_arabic_language_grammar.yaml,sha256=0dmTK09VGq1m4h-goYt2ns1OE5QOa9VYOCNaqdYB6lo,226 +lm_eval/tasks/arabicmmlu/arabicmmlu_driving_test.yaml,sha256=YpDz2WBQVLYCbwvxYXIrZZYDLOogmUxtTTPK2zKeXO4,181 +lm_eval/tasks/arabicmmlu/arabicmmlu_general_knowledge.yaml,sha256=52kN6qysV3LKS9ddEh6Ea2JFF9CmfaXifzjiM1Diano,196 +lm_eval/tasks/arabicmmlu/arabicmmlu_high_arabic_language.yaml,sha256=U0H8oZcG8Ge1rnE79H1HxFYIngXuWfjpnF8PMs-Hoxc,211 +lm_eval/tasks/arabicmmlu/arabicmmlu_high_biology.yaml,sha256=kkjs8EQjhyiJhqf7CF94lEAzI58F9OQ24XqHi_z-5c4,179 +lm_eval/tasks/arabicmmlu/arabicmmlu_high_civics.yaml,sha256=cilfAWmfHP7nDIdEATGqrhV4GNx34eln_sxerbakGKY,196 +lm_eval/tasks/arabicmmlu/arabicmmlu_high_computer_science.yaml,sha256=5kJ4bXCF8GRGkgtYnI3tO4GiG9LImsUj_J8nEXEOfO0,206 +lm_eval/tasks/arabicmmlu/arabicmmlu_high_economics.yaml,sha256=WRtKjM8UmC2PJSzd182HlxV1NOMrtDyS_rDHD26-L5M,205 +lm_eval/tasks/arabicmmlu/arabicmmlu_high_geography.yaml,sha256=S4-OuAW7p3CIKnConQ4sfmuR_QxMlLVsAsZx7BulnL4,205 +lm_eval/tasks/arabicmmlu/arabicmmlu_high_history.yaml,sha256=gGtU6NqPvyWh0aAssFaSKdsEM3xJ6GtsXg73JgrAK70,191 +lm_eval/tasks/arabicmmlu/arabicmmlu_high_islamic_studies.yaml,sha256=00JFwm6IRHuc4-FGOPx7XoJ93x4RwFhS_UgBVg1fL_8,215 +lm_eval/tasks/arabicmmlu/arabicmmlu_high_philosophy.yaml,sha256=yxH_YBQSFHZyTrxbQXjCw_vLcJFbu_1Q1jNdYZ-X4wo,200 +lm_eval/tasks/arabicmmlu/arabicmmlu_high_physics.yaml,sha256=ZygM6TX0LM1q_cQd-5XEV5piIlsgAn75YPpU1w_PJpk,179 +lm_eval/tasks/arabicmmlu/arabicmmlu_islamic_studies.yaml,sha256=Pe7DbrABo6FqPRGEqcjShOaL8b9Kba5-iUyq4mAy16I,200 +lm_eval/tasks/arabicmmlu/arabicmmlu_middle_arabic_language.yaml,sha256=l5sLPZS1CrVYNr1gnOpsX-qRMnxIljfaZ4t446atEeY,217 +lm_eval/tasks/arabicmmlu/arabicmmlu_middle_civics.yaml,sha256=YceXBsFGJlSv3FikMCzByzEDka4hlBSzQ6vw_iUL8S0,202 +lm_eval/tasks/arabicmmlu/arabicmmlu_middle_computer_science.yaml,sha256=LURftkHJNywMZOBYc8lvN0Ur-440iuCMpxIVSg9cVWQ,212 +lm_eval/tasks/arabicmmlu/arabicmmlu_middle_economics.yaml,sha256=LN4fnHpHRH1XuoJ5iRpYMHo9_iTe4qzUB_1TZ_GU2ok,211 +lm_eval/tasks/arabicmmlu/arabicmmlu_middle_general_knowledge.yaml,sha256=io8laC6MDKNl47PD1CEmdRgjM-WxK2o-v3y2lFAl-28,217 +lm_eval/tasks/arabicmmlu/arabicmmlu_middle_geography.yaml,sha256=lEdWh1W_MdO-3YQutHfJ-z_lZxRQljikcPlnQAscPvo,211 +lm_eval/tasks/arabicmmlu/arabicmmlu_middle_history.yaml,sha256=txmIh6izIovQVWmmcCMG5ZWnrfFQAHTRWobdcpCUp8k,197 +lm_eval/tasks/arabicmmlu/arabicmmlu_middle_islamic_studies.yaml,sha256=ZnZEqo-DgbwVgV38avMEtkLDWDFBmqzMh-3snuKvzNg,221 +lm_eval/tasks/arabicmmlu/arabicmmlu_middle_natural_science.yaml,sha256=yzFbGx2Zn0mO1-e_XO8uf0shwUWx2zR0BDA766HDhIk,209 +lm_eval/tasks/arabicmmlu/arabicmmlu_middle_social_science.yaml,sha256=0tthdU8OZCFF1AEzjFtO6OlUfuoTq1XyYVKuVZsrQ7g,226 +lm_eval/tasks/arabicmmlu/arabicmmlu_primary_arabic_language.yaml,sha256=1SMD52wMlvJb36BS6CLlY8WH7gXcRD69xRSZ8RlDtss,220 +lm_eval/tasks/arabicmmlu/arabicmmlu_primary_computer_science.yaml,sha256=fQdfc3fqFnjlca_-nPf9SRnKSMBay3blm8M1plQWOfE,215 +lm_eval/tasks/arabicmmlu/arabicmmlu_primary_general_knowledge.yaml,sha256=OZMOnaK_jr2fa4I9RRvXFig1C2z-QVzrkbJnixDtDh0,220 +lm_eval/tasks/arabicmmlu/arabicmmlu_primary_geography.yaml,sha256=Wwg-7izbxinjoaKdY4yF8ADEQxcWHi81ifgVUcO0DNw,214 +lm_eval/tasks/arabicmmlu/arabicmmlu_primary_history.yaml,sha256=go2P68EaCfBUcPjHgpYDAuerA5p9yV1TAQ5B4RzpSXE,200 +lm_eval/tasks/arabicmmlu/arabicmmlu_primary_islamic_studies.yaml,sha256=sOYATz-nT2JiYLAurDXGYI1YUmUyCS0inNq5Dzd4sZI,224 +lm_eval/tasks/arabicmmlu/arabicmmlu_primary_math.yaml,sha256=-iH-faxIzUAGcK46-mK6zKN5FeEzpE8rR3HEpstwSJg,179 +lm_eval/tasks/arabicmmlu/arabicmmlu_primary_natural_science.yaml,sha256=RA6O0xR98dtMFci3S0Il8zA6zEQJSsofuN56kyjZA8k,212 +lm_eval/tasks/arabicmmlu/arabicmmlu_primary_social_science.yaml,sha256=rlPaQ4q67rtuHiSTTqIoDCdTm62B7-pWKnQOvp7TchM,229 +lm_eval/tasks/arabicmmlu/arabicmmlu_prof_law.yaml,sha256=_rhMH7qbuKxBwge2xwkQnQcwZrHkloMihwkm1AkSe6I,179 +lm_eval/tasks/arabicmmlu/arabicmmlu_univ_accounting.yaml,sha256=RhiYVSrv-7QL1kQkXReEqDuTOUZjN8VYVB6v2ajAaCQ,208 +lm_eval/tasks/arabicmmlu/arabicmmlu_univ_computer_science.yaml,sha256=AVzxNWkau8rFEcWt7yM4YQ62SQZDwGAlzExEd9Nlb9M,206 +lm_eval/tasks/arabicmmlu/arabicmmlu_univ_economics.yaml,sha256=yImmMPLcYIedV3U-Bu6cY6JCrwOB-lwh74llBw7TEb8,205 +lm_eval/tasks/arabicmmlu/arabicmmlu_univ_management.yaml,sha256=PWTX39o17SrfNIb1KvxXSgNlrnNOWjBFO3lQ4YsrrFQ,190 +lm_eval/tasks/arabicmmlu/arabicmmlu_univ_political_science.yaml,sha256=WLfwd4Pdz210rT0mH1h7V4supSSzH5KmsbW_2VMXmOY,229 +lm_eval/tasks/arabicmmlu/utils.py,sha256=9CI7sfRbV2jsfYZVQ5jBRLsFtbV4bZXa3oaoThHiFnw,1210 +lm_eval/tasks/arc/README.md,sha256=s8ExYRbWsstbrnJ1SGR2pFN5IEgs5yakpXvhc-oNujc,1907 +lm_eval/tasks/arc/arc_challenge.yaml,sha256=aCYhwmriSxBlotcyRgpVqO8rnyVEV0QxZmyTCanv170,71 +lm_eval/tasks/arc/arc_easy.yaml,sha256=Cb1InG2hMVw5PEvdu6pCMqKIR79JPs3hbJW9pMniXUI,581 +lm_eval/tasks/arc_mt/README.md,sha256=a0meHVJdHA049ahxczqDE1C86-caQ-K3rOvfcd1i_5w,412 +lm_eval/tasks/arc_mt/arc_challenge_mt_da.yaml,sha256=m4OqTza2K_Qu9XDVLj7SER206mdaUbV2Kpqn-sqr3qI,77 +lm_eval/tasks/arc_mt/arc_challenge_mt_de.yaml,sha256=kBRkpb1E88AaMe4NedjuLvCcw6rqlnjIhyBYqdOL5FQ,77 +lm_eval/tasks/arc_mt/arc_challenge_mt_el.yaml,sha256=oem8pS-GOBJx3N_t10hfIvX2pS3h6JnCi25wH4PVlak,77 +lm_eval/tasks/arc_mt/arc_challenge_mt_es.yaml,sha256=1khqoN6MiNIULousAHvE_0EE5MbJb038NAe1P_9s2Oc,77 +lm_eval/tasks/arc_mt/arc_challenge_mt_fi.yaml,sha256=2a0t68Df-wE-zYjZSfLYhXyhIacRN0ns0nHi1mM2bm0,605 +lm_eval/tasks/arc_mt/arc_challenge_mt_hu.yaml,sha256=ECJUphFbJn6ERd1a_-RrMg-WAb-eZI_GF9RPoKqLgWY,77 +lm_eval/tasks/arc_mt/arc_challenge_mt_is.yaml,sha256=MPs29kR1j302CAM_EIpSJaU6VANo9Pa0y9qzOVZOqQk,594 +lm_eval/tasks/arc_mt/arc_challenge_mt_it.yaml,sha256=nff51FMMAVCxvJgSmkD3whqGDyHlQQJs0Poy78yVJBM,77 +lm_eval/tasks/arc_mt/arc_challenge_mt_nb.yaml,sha256=BTcix9911GOIbKUwHwSuJvzrrLP5vRrhj1IjkGWr7z0,77 +lm_eval/tasks/arc_mt/arc_challenge_mt_pl.yaml,sha256=bKf8-kP5nVedQfj3r-YLOU_G7ne44OkMh7R8NQad9O8,77 +lm_eval/tasks/arc_mt/arc_challenge_mt_pt.yaml,sha256=L_Q9FPnvjWW5LysRpJvtWzhEuw4BtNs2BKZE1QkgnUs,77 +lm_eval/tasks/arc_mt/arc_challenge_mt_sv.yaml,sha256=OdYSwgE1bB9OuVcAnh_iMgTmkTOQyjEqn4cBUkoAS0A,77 +lm_eval/tasks/arithmetic/README.md,sha256=3jHg0xARN3uYrFIhUuRfD6qv-rYAVy0ffKqzAXqklfw,2336 +lm_eval/tasks/arithmetic/arithmetic_1dc.yaml,sha256=-ipgkiqZYJePHkYGwRQQq6qfVtjWnpO9Ds_16hawgU8,385 +lm_eval/tasks/arithmetic/arithmetic_2da.yaml,sha256=V12nJMp6vQVEPrVmMBRvzclMuBb_HxbrB_f-9_v5b6Q,121 +lm_eval/tasks/arithmetic/arithmetic_2dm.yaml,sha256=Hq_P-0ai3YMkoYTET0-IjMFJ1ZHuaXa56xRMz_OZsCU,121 +lm_eval/tasks/arithmetic/arithmetic_2ds.yaml,sha256=hBtWC9FdqNUYWdCckQLe0AGjKJToWwizHxv52P1Cxwg,121 +lm_eval/tasks/arithmetic/arithmetic_3da.yaml,sha256=SBEW7EW9U-b2_t_lYfI0HPxyt7arHqSsXRkzfj04jDY,121 +lm_eval/tasks/arithmetic/arithmetic_3ds.yaml,sha256=Mt3FExvHxBd6yvGT_shmVwGgTGMttDXxDP29BrhqQSs,121 +lm_eval/tasks/arithmetic/arithmetic_4da.yaml,sha256=Tm-_pJPxRioREeU7hLELfviPKf4RTATqTlPsn9Q1EVA,121 +lm_eval/tasks/arithmetic/arithmetic_4ds.yaml,sha256=LGYKXa2CIefd8RyMKbeXOD62yt22JHW7MVJKEFCSU8A,121 +lm_eval/tasks/arithmetic/arithmetic_5da.yaml,sha256=gLV1nowU_lAor9wD0O4oTrU65iH5rTRgi4px7qCHttM,121 +lm_eval/tasks/arithmetic/arithmetic_5ds.yaml,sha256=lD4TGRpxz0P34KGXnSeqqJG1eYh66X2aE9LnBu8yh6k,121 +lm_eval/tasks/asdiv/README.md,sha256=TQY5EyoG5evb9oZwMCZl_X_4qAX7B-nMKnOTcI_-0IQ,1906 +lm_eval/tasks/asdiv/default.yaml,sha256=8lIhCEYNbVCA993MVkXWqTAvw_2rNqQN-NMGs4N71TE,424 +lm_eval/tasks/babi/README.md,sha256=Y_b2kkNqyN1l3ONNomyPcZmNOI0wupDTQLAHyankfFY,2263 +lm_eval/tasks/babi/babi.yaml,sha256=Zu1YY1DxenTDzTa3neetZi-r65OaS6QHZto66dkfKIA,436 +lm_eval/tasks/basqueglue/README.md,sha256=Jlpq7XuPi8fpf62U3SjhGhY9YzIwix9CjIfWf-uI9FA,3646 +lm_eval/tasks/basqueglue/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/basqueglue/bec.yaml,sha256=QyYSuZFwZcucCy0rw3BLdpgg2YBGVOvcqsV8zuFY1ac,463 +lm_eval/tasks/basqueglue/bhtc.yaml,sha256=QuWwCO9hwg0rUbsiVP4memLFdVrimqIOwuo_frDjaEI,566 +lm_eval/tasks/basqueglue/coref.yaml,sha256=ZsG0LH4k3vWTnY0NLzxEbRAuJ5QIF2lhHcloklvLz4E,369 +lm_eval/tasks/basqueglue/qnli.yaml,sha256=N2QSCqFKIlz-NJY8ONy0xZxWG5AEzkQmUYPm4hwnTWU,431 +lm_eval/tasks/basqueglue/utils.py,sha256=KaYpKdLfnm6zUJpsOBZPkhBqgnvpqbqroxQ5nOpXB10,2367 +lm_eval/tasks/basqueglue/vaxx.yaml,sha256=fxKaYQ7Iw_1XZMFVvnoV64xzTmv2QwHM9AzuiHgYJ-g,471 +lm_eval/tasks/basqueglue/wic.yaml,sha256=53etH65ESodVverok2JKBQP2D5B2dzvlBWKzRnHICQ0,511 +lm_eval/tasks/bbh/README.md,sha256=onAqPm8i9ybbgt4mLn6CBWVRvLWg6z7DJWLeE8umSJQ,1384 +lm_eval/tasks/bbh/__pycache__/_generate_configs.cpython-310.pyc,, +lm_eval/tasks/bbh/_generate_configs.py,sha256=ZR8egBvkJtC5YPheE8jPohWsgq9eHHaszGABb-Iq4iw,2703 +lm_eval/tasks/bbh/cot_fewshot/_cot_fewshot_template_yaml,sha256=7mgLBQ0N6-ZZIS-KhGT1-RpdGWlNyZhXY-FlF5ctQIE,594 +lm_eval/tasks/bbh/cot_fewshot/boolean_expressions.yaml,sha256=HOzMG7lFpGsM05FWomt9xgcqYztvIhGtaDzn2cqQOyg,2125 +lm_eval/tasks/bbh/cot_fewshot/causal_judgement.yaml,sha256=4AHks2zN6cIfTDkbS8OlIbPq3CWCC5hKvaEP3vB92E4,4309 +lm_eval/tasks/bbh/cot_fewshot/date_understanding.yaml,sha256=3VyH1D7HQuajv_2Oe6cNtnhLlTCVSVokdtS0rJpkK6A,1670 +lm_eval/tasks/bbh/cot_fewshot/disambiguation_qa.yaml,sha256=ZSm2v2wXJ-yPj-udDog39YC0_lKwodmOwPfv3VHDq9c,4254 +lm_eval/tasks/bbh/cot_fewshot/dyck_languages.yaml,sha256=bwXI9-WGmbBN-92gEfLpjz0rAl-31E6xvfiLdaPk7Qs,3159 +lm_eval/tasks/bbh/cot_fewshot/formal_fallacies.yaml,sha256=RYUYI_wc5gMjr7FtMvgGJq6o5BsSK2dYIqvW_rv_MZA,5299 +lm_eval/tasks/bbh/cot_fewshot/geometric_shapes.yaml,sha256=UpDLdVDLSIy9Sxdh6hMg4X_GaPU1iJX1rBvpHrOSxjw,5770 +lm_eval/tasks/bbh/cot_fewshot/hyperbaton.yaml,sha256=qHKvg1HUmN0Xm3wVtck87nfAR6lL4qgIaV0AfJKLmNs,3690 +lm_eval/tasks/bbh/cot_fewshot/logical_deduction_five_objects.yaml,sha256=Ty4GtpSkvgilIW3MXX4PH5c2yvCEaPiIn8yj1h-f_4Y,3126 +lm_eval/tasks/bbh/cot_fewshot/logical_deduction_seven_objects.yaml,sha256=OkV5cEsG1dAvRsEDY4LbFtJ7JkeuQC6RqJ-8SvnkC5o,3128 +lm_eval/tasks/bbh/cot_fewshot/logical_deduction_three_objects.yaml,sha256=JnolIfEMxMz-bZwI0NFfyNUX6X4VKzOVy8imAiRUEBY,3128 +lm_eval/tasks/bbh/cot_fewshot/movie_recommendation.yaml,sha256=GQYQdRjAoSszXaf8CMVRM_DWHb0RwidGk46vRC3gxdQ,2726 +lm_eval/tasks/bbh/cot_fewshot/multistep_arithmetic_two.yaml,sha256=Q5mAFh6b_yknXT5D4U14dICwnOohpabmsb31VduG4oY,2966 +lm_eval/tasks/bbh/cot_fewshot/navigate.yaml,sha256=wVwHvEuFOpuapsd8tM0KrvZKfZxcp8P32HTjMpPN5iA,2694 +lm_eval/tasks/bbh/cot_fewshot/object_counting.yaml,sha256=GCdgGOP3lWhszsTTDE4KVD0Ij9n3AIalxc4vKixizyI,1940 +lm_eval/tasks/bbh/cot_fewshot/penguins_in_a_table.yaml,sha256=dxhoyQPupb59Hw2zSJkL-i02n6c5JzULkYr47yrTcYU,3005 +lm_eval/tasks/bbh/cot_fewshot/reasoning_about_colored_objects.yaml,sha256=Ucae83n38fx6dqunOUCZyi1v--cDVwpVgFlE4dtotEI,3098 +lm_eval/tasks/bbh/cot_fewshot/ruin_names.yaml,sha256=zcna1JL-uXoGRPlK0Eh-zHjXVqh_yeSuPqE3j3TjnOM,4167 +lm_eval/tasks/bbh/cot_fewshot/salient_translation_error_detection.yaml,sha256=NdMAYGPdD1fPf4TQM_e-gFKcWQlCTMzCMENCKTu8VOY,7163 +lm_eval/tasks/bbh/cot_fewshot/snarks.yaml,sha256=R00RsNAJ4gb1QU9n-tMh9uBjW0F4hapebX51Q__8OiQ,3673 +lm_eval/tasks/bbh/cot_fewshot/sports_understanding.yaml,sha256=Aron3nBZkc_JojecaduwpX8dCXPaHefkPB4_hkE1TgM,1152 +lm_eval/tasks/bbh/cot_fewshot/temporal_sequences.yaml,sha256=NlCNX4cM8h7nRD3nH2AU4dvmQMx-_RaQdZ35e6js-bE,3828 +lm_eval/tasks/bbh/cot_fewshot/tracking_shuffled_objects_five_objects.yaml,sha256=gu7t0E_7K6zQ52WywEYCwl6v4PEMMotoFrcWyKDOX4Y,3232 +lm_eval/tasks/bbh/cot_fewshot/tracking_shuffled_objects_seven_objects.yaml,sha256=UfhUj9tz4DZ1OXqx96-UTg3nflTQCeXpHyP0k3M9IBc,3234 +lm_eval/tasks/bbh/cot_fewshot/tracking_shuffled_objects_three_objects.yaml,sha256=KyD28IiVbE_N5mZizGC-XG6jLJvDBVUQSuR_37YDUrw,3234 +lm_eval/tasks/bbh/cot_fewshot/web_of_lies.yaml,sha256=169eVSMdL6RbDYV2lxDIlklRFvsLuxTp0IBzwSgQnLQ,3493 +lm_eval/tasks/bbh/cot_fewshot/word_sorting.yaml,sha256=Lto2KqwG4jQJICBdK5cdYq-p-_3iKxWN-h5E2aZMZks,2629 +lm_eval/tasks/bbh/cot_zeroshot/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/bbh/cot_zeroshot/_cot_zeroshot_template_yaml,sha256=8cD89OSopFFp51VnXK3LhfFoudVSGfneao0X6YmNiXQ,502 +lm_eval/tasks/bbh/cot_zeroshot/boolean_expressions.yaml,sha256=BKQ6JO9I2gLwb1MfgCnwaIG-66v-mzZqd__1oy1rWc8,679 +lm_eval/tasks/bbh/cot_zeroshot/causal_judgement.yaml,sha256=FOCmMOguNhSlowJnmKY-pRsJ2lBymWo6s2qlpTjS0E8,667 +lm_eval/tasks/bbh/cot_zeroshot/date_understanding.yaml,sha256=2WR5jQ37ZwlDbc066gHLGrjmy_dE732uTBEZhyuCgsg,739 +lm_eval/tasks/bbh/cot_zeroshot/disambiguation_qa.yaml,sha256=qJW8yPCukm5IKN2FBgm7kYg-xhjiCwKW6hGlOwtnuS4,766 +lm_eval/tasks/bbh/cot_zeroshot/dyck_languages.yaml,sha256=mw1W-rh3wZ58rY19vAOfQVr_ISVpRvjmpGe5xI7nLqY,684 +lm_eval/tasks/bbh/cot_zeroshot/formal_fallacies.yaml,sha256=rOekVBA9qj24R704zneL85yXzf8jLNCXYxreoMet5lw,687 +lm_eval/tasks/bbh/cot_zeroshot/geometric_shapes.yaml,sha256=EjI9vVQJTCLofU9cAPADFEWtHW8i1uGluDdrr62N3aI,750 +lm_eval/tasks/bbh/cot_zeroshot/hyperbaton.yaml,sha256=Pt49AiGA-g65WhWp1LLuQUM6LJgSfFhjT1eO7RdM10o,743 +lm_eval/tasks/bbh/cot_zeroshot/logical_deduction_five_objects.yaml,sha256=twk8yG1vjkU48OHoDwjJwh4Ohye0-zpIJf7NOAtcNUI,818 +lm_eval/tasks/bbh/cot_zeroshot/logical_deduction_seven_objects.yaml,sha256=fLICnem3s646N1Lbl5IRPAbMewhcUFxZ3Rdu-pVvarM,820 +lm_eval/tasks/bbh/cot_zeroshot/logical_deduction_three_objects.yaml,sha256=j8nBZ62_r9qj2KGzp4ildJS0tXeFjpy1uJvXVflhl9c,820 +lm_eval/tasks/bbh/cot_zeroshot/movie_recommendation.yaml,sha256=5sK7ju6stnh6u7R6uvzI6-eQb4qgDDYZrBidbdGcXyQ,767 +lm_eval/tasks/bbh/cot_zeroshot/multistep_arithmetic_two.yaml,sha256=vXJJjs-xeWRuXtCrfQVmyKPhgiIRSI58Fcwft1bdaeU,697 +lm_eval/tasks/bbh/cot_zeroshot/navigate.yaml,sha256=58RaCT7VZ6fiKQ1D2eEEx3XfVeQG4m0G57F0xmmjx58,713 +lm_eval/tasks/bbh/cot_zeroshot/object_counting.yaml,sha256=eCOmYJZufH_wmqRICNxCnAJ8qPbxq6f40T4iq2ZADDg,719 +lm_eval/tasks/bbh/cot_zeroshot/penguins_in_a_table.yaml,sha256=iMRKS9h3NpUU90MmQ7Vzf4MJRVAbKNUXg1-4dlRM3-s,776 +lm_eval/tasks/bbh/cot_zeroshot/reasoning_about_colored_objects.yaml,sha256=rkICB45Uv8AomM61e-8iatL_SCilCI0UfWKUdXT0reA,811 +lm_eval/tasks/bbh/cot_zeroshot/ruin_names.yaml,sha256=t4QqzKgua7-v5Pnqp8s8o-YsKEYRdZr2U6pzvFgDnA0,771 +lm_eval/tasks/bbh/cot_zeroshot/salient_translation_error_detection.yaml,sha256=rtV_kpJ6-Mif2wUrMmIQULrBhQuxFDcfBDt07PoM82g,823 +lm_eval/tasks/bbh/cot_zeroshot/snarks.yaml,sha256=gH1y98pBpeFVJSdO9diIzlKi0kuYj5H82EIKZQG8KoE,1057 +lm_eval/tasks/bbh/cot_zeroshot/sports_understanding.yaml,sha256=qC3tfNj-4hfvSFCVtj-ib7hHMLToF7AppQfqmVOyvDY,837 +lm_eval/tasks/bbh/cot_zeroshot/temporal_sequences.yaml,sha256=ZhQfmkoNIt1SSKNZPfhEXlpXXIF_DLg5y6y4cGcGvG8,798 +lm_eval/tasks/bbh/cot_zeroshot/tracking_shuffled_objects_five_objects.yaml,sha256=MqI1WvrFkONaQcoCQUk8Aqk8sqlRi3OXsya6Ukrub1E,890 +lm_eval/tasks/bbh/cot_zeroshot/tracking_shuffled_objects_seven_objects.yaml,sha256=HzD6MUcCdjzReleZFv7oJPsVRHIHWtJYVYWQ-qtGwOw,892 +lm_eval/tasks/bbh/cot_zeroshot/tracking_shuffled_objects_three_objects.yaml,sha256=FaW5OXsTGhuKTCz_4yuxlYnhLhgp-h6MBT8STObJKDY,892 +lm_eval/tasks/bbh/cot_zeroshot/utils.py,sha256=03_KQKsfTCHMCwu_HA6HTdhGwXAD-TNlL3W8r1CpnxY,8777 +lm_eval/tasks/bbh/cot_zeroshot/web_of_lies.yaml,sha256=XRcVudvzDNpMyhLFqIWa0n77DNygmpwiXQ1taDvxk8o,849 +lm_eval/tasks/bbh/cot_zeroshot/word_sorting.yaml,sha256=BZ_CXxzfuz3XzPzbMifdj6Ep7it5pUUWLujdj7UQ5Cw,588 +lm_eval/tasks/bbh/fewshot/_fewshot_template_yaml,sha256=K4oKBcYc9u0h5O_3yMp8NlgvJJEy0BgFKUtNr19kD6I,402 +lm_eval/tasks/bbh/fewshot/boolean_expressions.yaml,sha256=3Fajp_M6a4e-9cjT9wiEVkfYak6MbDojg799LX4b7PY,445 +lm_eval/tasks/bbh/fewshot/causal_judgement.yaml,sha256=zVvaCE5Ncvg8km4BgkXy1QNIvjndJrV_fV25popbLtc,2640 +lm_eval/tasks/bbh/fewshot/date_understanding.yaml,sha256=3NdqSISk0ZUEvOqwpU9wLOujX8mb1nCw_SfTWOU_BbA,1019 +lm_eval/tasks/bbh/fewshot/disambiguation_qa.yaml,sha256=sCNW7SS9bZ_Tt7cHPLsD1aofo6EcJwu0uda8YxAc3_k,1361 +lm_eval/tasks/bbh/fewshot/dyck_languages.yaml,sha256=-n8BeGTjtPm8YpKqoXqQ6pc0FOxAkJWK-2vhXuUi13c,730 +lm_eval/tasks/bbh/fewshot/formal_fallacies.yaml,sha256=cc-AJxsjxrzTBPzpQgsFEWpv0F3RGwcWITYMDX14u5I,2085 +lm_eval/tasks/bbh/fewshot/geometric_shapes.yaml,sha256=AvMGWwus_pZciNHk81dYpc9Iyqai5dfsEtNYi5Q8OHM,1368 +lm_eval/tasks/bbh/fewshot/hyperbaton.yaml,sha256=6eXPkZJXHWZyCIWwe2mmtFVEgXr0WSC-8lp4RhSCQRM,766 +lm_eval/tasks/bbh/fewshot/logical_deduction_five_objects.yaml,sha256=TMBoI8cGGVd8tkuUFchBjR96U51c9hwcpxnXpsQd7wM,1757 +lm_eval/tasks/bbh/fewshot/logical_deduction_seven_objects.yaml,sha256=gAgu7SgvHX7w12fvhB2IbpJJrSOFNLNfAFmXXsMvxoQ,1759 +lm_eval/tasks/bbh/fewshot/logical_deduction_three_objects.yaml,sha256=u924v2Zr0-EBPQKBMAlXKP6kH6mHQ6ez7Rb_Mo5ooUg,1759 +lm_eval/tasks/bbh/fewshot/movie_recommendation.yaml,sha256=1GhfwKpYOyXkh43CGrw2_loM5Dqk9FJzt2Y9gCIZtvw,1111 +lm_eval/tasks/bbh/fewshot/multistep_arithmetic_two.yaml,sha256=PZP__VDcm9fIghOIY51gcIk9JnxeWUR4udn-imDNZ_A,467 +lm_eval/tasks/bbh/fewshot/navigate.yaml,sha256=zoXyabumP7e8TZDT02msQWS2b_uP9mvvpWkll-X0yOI,1012 +lm_eval/tasks/bbh/fewshot/object_counting.yaml,sha256=9s7TgTWz8CklGdjlbKQ5-UAT_KV-YmpOPXzdS1WX420,787 +lm_eval/tasks/bbh/fewshot/penguins_in_a_table.yaml,sha256=iMWhQRory7-hm9BuhY4M-CtljGFp44EqhDgvA7BwmSo,1812 +lm_eval/tasks/bbh/fewshot/reasoning_about_colored_objects.yaml,sha256=JuPOvmEuyca3uF6lscO4-29HQmLpHYpuhyanJy0GeRU,1911 +lm_eval/tasks/bbh/fewshot/ruin_names.yaml,sha256=Vas7MYvXeger4a6-fNgRrR1RjlrgdffEgFim4fjzxxg,1078 +lm_eval/tasks/bbh/fewshot/salient_translation_error_detection.yaml,sha256=f9eC8F87loZ2IHHrtHmoJDxV9hDvRcDSMdz9Y59QzuM,4202 +lm_eval/tasks/bbh/fewshot/snarks.yaml,sha256=XvvlR_exJefx6qlVTPTEg4JpyY8ry7TYPB1P_9h5ApE,1390 +lm_eval/tasks/bbh/fewshot/sports_understanding.yaml,sha256=77kpaQzU5C-Dnyf90EKUmBW1B1i0eS5zNRBcPd87a4g,665 +lm_eval/tasks/bbh/fewshot/temporal_sequences.yaml,sha256=HE7QMrg_-upvfn_hbrXV0g2aH8-wcgxjfcC4V_fdomw,2455 +lm_eval/tasks/bbh/fewshot/tracking_shuffled_objects_five_objects.yaml,sha256=nY5KEoiOX47FdsnVKah4Tdsqmv8POhb6Qk6gvjlVAnY,1947 +lm_eval/tasks/bbh/fewshot/tracking_shuffled_objects_seven_objects.yaml,sha256=-sn8kiCM1-wzQ_z8bkPG3UhZyL7DLOZuyRXEXic9PNA,1949 +lm_eval/tasks/bbh/fewshot/tracking_shuffled_objects_three_objects.yaml,sha256=EAHmO5JbQ8AXNrH7QrF7pwO4YMomzFL8X53ZV4hciJk,1949 +lm_eval/tasks/bbh/fewshot/web_of_lies.yaml,sha256=1CptDj05FukKtOA0R_boYY94OJD_VNtvq4qnE_PkgWU,933 +lm_eval/tasks/bbh/fewshot/word_sorting.yaml,sha256=1edVlHNWy5RV7Mb07xpVTzjiER5q92h7hmwmYJIk7i4,672 +lm_eval/tasks/bbh/zeroshot/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/bbh/zeroshot/_zeroshot_template_yaml,sha256=spVv4-z-y5vK0XIFshAUFu62V4p0UZ-FHxuDLtBAgpc,498 +lm_eval/tasks/bbh/zeroshot/boolean_expressions.yaml,sha256=Tuk0lWtRtnLCBsTLCEoVjnM2H572_4RqsHATK9c7oio,473 +lm_eval/tasks/bbh/zeroshot/causal_judgement.yaml,sha256=kNc65hI1I1S2BU3JY5hsCNkEWgZ_EQYd92yg0b7OGek,461 +lm_eval/tasks/bbh/zeroshot/date_understanding.yaml,sha256=Wzvx0IdNhHfdknnixvJySw_zbfz5XOJoJVMpVzccG7Y,533 +lm_eval/tasks/bbh/zeroshot/disambiguation_qa.yaml,sha256=ttEMcEsDsyhmWk0lQ0MpJiBfN-oxKESlSXfiC9Bj9Lg,560 +lm_eval/tasks/bbh/zeroshot/dyck_languages.yaml,sha256=jULSUCimkHyjYMbSyWz-3e5Fh4hwXfB8pJXl1pRqdnQ,478 +lm_eval/tasks/bbh/zeroshot/formal_fallacies.yaml,sha256=nxSdCT_qpDvlblyiBkYwGH0GkE9r6kHzLzSxIdBPu7c,481 +lm_eval/tasks/bbh/zeroshot/geometric_shapes.yaml,sha256=ug-J6K10cUAtkLyrgHiPq1opVrGTaqJbN08wB_KnycE,544 +lm_eval/tasks/bbh/zeroshot/hyperbaton.yaml,sha256=RAScn4Nw49gKVviPyOWYdn1FTzhCtt_SQiaMCkRjLC4,537 +lm_eval/tasks/bbh/zeroshot/logical_deduction_five_objects.yaml,sha256=6ABlB8hVvffXqdRvjCrBGL8W9NaGLa-RymEp2c4U12c,612 +lm_eval/tasks/bbh/zeroshot/logical_deduction_seven_objects.yaml,sha256=QqSnathmDPy8QeX2vl5Mj5QCkCzb1o1nJfFVB6LSiDA,614 +lm_eval/tasks/bbh/zeroshot/logical_deduction_three_objects.yaml,sha256=u9vkRxmhHAUVI6VAMWP2eBuaB5rxVM2JjpSIpNs5Hyo,614 +lm_eval/tasks/bbh/zeroshot/movie_recommendation.yaml,sha256=qN_B4OgxfXhCFNVhclrBDJUf2Jiwo0hoNpMnDwwg0aY,561 +lm_eval/tasks/bbh/zeroshot/multistep_arithmetic_two.yaml,sha256=3SfYjOOs9kxkf9tcIyFydk9aLwvfpAWbIBgLZkZjxfc,491 +lm_eval/tasks/bbh/zeroshot/navigate.yaml,sha256=B6dRPFnXuX7DQugeVkTO8yR0407aW2J_OSVk2cHJaSw,507 +lm_eval/tasks/bbh/zeroshot/object_counting.yaml,sha256=6Q-kZXpMaliqEcl84tarX0zW98dr58BySXtGMZYszYI,513 +lm_eval/tasks/bbh/zeroshot/penguins_in_a_table.yaml,sha256=OPKYIHMGB0vmRhKW79iAEgY_Vin5OQEIxNrvWFida2g,570 +lm_eval/tasks/bbh/zeroshot/reasoning_about_colored_objects.yaml,sha256=RP4_eYIh3yCqX2LaZ8RZ3xexILH91ZNdvJCCw_NFdcQ,605 +lm_eval/tasks/bbh/zeroshot/ruin_names.yaml,sha256=FrgCzr7L0-Zmm4j2SDKtZnTO2urqw1uRliWdque4LUA,565 +lm_eval/tasks/bbh/zeroshot/salient_translation_error_detection.yaml,sha256=XU-bur6KPqH4QFS6gHqs4iac7NGv4QqEjrMMsTMkUYw,617 +lm_eval/tasks/bbh/zeroshot/snarks.yaml,sha256=KS0oIOa9ZIUaTORqPSsAbADJCQoMuKxkodxp3FINOqc,851 +lm_eval/tasks/bbh/zeroshot/sports_understanding.yaml,sha256=k_kuvih4YmCkwomOi8qEp-t13zgyTtzkq3yLQcuLngY,631 +lm_eval/tasks/bbh/zeroshot/temporal_sequences.yaml,sha256=9UIDSY0kmyLobfY2TMP58M-jpZvNPPOCWjsF1ApItZ0,592 +lm_eval/tasks/bbh/zeroshot/tracking_shuffled_objects_five_objects.yaml,sha256=IGV3TMZUQzccEgAAegKy95_Pw3DnP1hLI-ZfIar_1Qg,684 +lm_eval/tasks/bbh/zeroshot/tracking_shuffled_objects_seven_objects.yaml,sha256=K5DfPycBD-RzDXCqJ3Pn18tvtaSMyTE7N8KUWiacgJY,686 +lm_eval/tasks/bbh/zeroshot/tracking_shuffled_objects_three_objects.yaml,sha256=Th21qaJlSZk7cFK0JvzLA9kPRudT9KDzkkuwAySRAKU,686 +lm_eval/tasks/bbh/zeroshot/utils.py,sha256=03_KQKsfTCHMCwu_HA6HTdhGwXAD-TNlL3W8r1CpnxY,8777 +lm_eval/tasks/bbh/zeroshot/web_of_lies.yaml,sha256=WTBOPgr8j2aZ0cG0dAfnIQVhg4cZYmeQvkj8WstGG3A,643 +lm_eval/tasks/bbh/zeroshot/word_sorting.yaml,sha256=c8SQ9dZlfgm1vBVbWD7tyt45kg-nNaEoErtypkdUKyA,383 +lm_eval/tasks/belebele/README.md,sha256=DePrXLzy0Wd8hP3XqMGXlXBRLZsczh1aEN4-MhTxMv4,2578 +lm_eval/tasks/belebele/__pycache__/_generate_configs.cpython-310.pyc,, +lm_eval/tasks/belebele/_default_template_yaml,sha256=hMGUIoew0r-3Dw2A-P2useomrT3hIWkYHXmEUIWtS8w,610 +lm_eval/tasks/belebele/_generate_configs.py,sha256=iUVhjllNh1zcE0ELsOIMxdV6c9P7wYF5WVSomUmm_R8,1979 +lm_eval/tasks/belebele/belebele_acm_Arab.yaml,sha256=1EvD-A0S4aFieLpRE8EyQUzhj0ZCARV9bh7b1IyT9NE,117 +lm_eval/tasks/belebele/belebele_afr_Latn.yaml,sha256=-atGz1AmNzkqVNXeb5ZSZuXOK7lx7fw28gSmZAzS66Q,117 +lm_eval/tasks/belebele/belebele_als_Latn.yaml,sha256=2yR3mcGjcCK9pVecpN09CnlvyLkGialK4R2Zqrdih0w,117 +lm_eval/tasks/belebele/belebele_amh_Ethi.yaml,sha256=f5GKkWm4TqrVt7m4Zp-OSIl64-9XUNUWzm7LnCg0QAY,117 +lm_eval/tasks/belebele/belebele_apc_Arab.yaml,sha256=wqYmY4n6VbEuy1wRXmyaLK62uNjTbBfbGroAI129MvE,117 +lm_eval/tasks/belebele/belebele_arb_Arab.yaml,sha256=9rVkD5-hU08GXYD0E2vs7ndfvThtvJx8dgHqW5FiWII,117 +lm_eval/tasks/belebele/belebele_arb_Latn.yaml,sha256=HAZaQhih9A1KZMjS7bICwNnI4m8qCF4-D1nrqPB0-wo,117 +lm_eval/tasks/belebele/belebele_ars_Arab.yaml,sha256=jb1TkLdTDYU5v7NK5LjJ06iqW9i3pjw3MluV7lyfAns,117 +lm_eval/tasks/belebele/belebele_ary_Arab.yaml,sha256=WFDY0FNZ7geoOBztlOG4y40P_pAE0HAfCmh8nNiBxa4,117 +lm_eval/tasks/belebele/belebele_arz_Arab.yaml,sha256=Zi0UrUO05QHGDD14hGsgHzWVyqwitOt9ayxZcdpOvdY,117 +lm_eval/tasks/belebele/belebele_asm_Beng.yaml,sha256=_W0B2Qk1Ktmw8bs3sMG30E5sLq7yM7U8Z5kCRJcYiCU,117 +lm_eval/tasks/belebele/belebele_azj_Latn.yaml,sha256=kISIrd3IeaVgQdoava3ztCLrAguTW8yWJaW9FwZU_SQ,117 +lm_eval/tasks/belebele/belebele_bam_Latn.yaml,sha256=O1bSMR9YcaXKIWCcZ1Q4YO68Paq7MuvoGEMIfoq9r24,117 +lm_eval/tasks/belebele/belebele_ben_Beng.yaml,sha256=KH3JBcMroICfZ7dB91Su8ZL9HLg9j0A7PrC3ygRy2mo,117 +lm_eval/tasks/belebele/belebele_ben_Latn.yaml,sha256=iwhPd2MbJnGNzNfztAkKNCdzmRdzJv0jOmY6xm6OO_M,117 +lm_eval/tasks/belebele/belebele_bod_Tibt.yaml,sha256=3OmaJOqZQrVhTRVs_bAse9Hkx0jPthM-e7Qesx5bUZE,117 +lm_eval/tasks/belebele/belebele_bul_Cyrl.yaml,sha256=O40wFliFb7RfTcMBpRtfsSswlUJ_y9W8vTeK42jekEA,117 +lm_eval/tasks/belebele/belebele_cat_Latn.yaml,sha256=pb9_eJUCZgxUY_7Vd-D_kQn4-nAdhNpzWWPyOo738SU,117 +lm_eval/tasks/belebele/belebele_ceb_Latn.yaml,sha256=bqLKicn1-cc6VH8R74Krr4VM-tHKUY6aph6yVycVr8M,117 +lm_eval/tasks/belebele/belebele_ces_Latn.yaml,sha256=NLddlp1RVQW4XeOHn4I7ScxOzR-t8lXBXHXdmr01U-s,117 +lm_eval/tasks/belebele/belebele_ckb_Arab.yaml,sha256=2ohEPKdOGOOxRRSq8ysjbCqtw3l4h_L5s3G9Oi_bjds,117 +lm_eval/tasks/belebele/belebele_dan_Latn.yaml,sha256=5LnL6d2TGWiT42JpPm69D2gsFueGX-xYh9Owyb5ag60,117 +lm_eval/tasks/belebele/belebele_deu_Latn.yaml,sha256=x4Gd020iF0eFTHkyxohGpdm1no8yPUaS5yjHsUAbT1U,117 +lm_eval/tasks/belebele/belebele_ell_Grek.yaml,sha256=vM7mypRDURpF0Oc703Mx47tpRi2hApOKtf-C6NwuMWc,117 +lm_eval/tasks/belebele/belebele_eng_Latn.yaml,sha256=exv25-DfKV7Bx3INWGwwghJfYAcfcYOX7EheORHk4qY,117 +lm_eval/tasks/belebele/belebele_est_Latn.yaml,sha256=ZCisUJNjRcfevGTCogzmXsbNRKGtOwpRryPeQeRzbV4,117 +lm_eval/tasks/belebele/belebele_eus_Latn.yaml,sha256=zzKDT_vQWPxeYGTCFS3YPZWBqWDkRTw7fQAPx3IrNAU,117 +lm_eval/tasks/belebele/belebele_fin_Latn.yaml,sha256=ld5ZobQ_dPSs8vtKWWQJM9sU4WE-y3ePQOxmYczEg2U,117 +lm_eval/tasks/belebele/belebele_fra_Latn.yaml,sha256=HRTV1uCb95Sfi-9C0SGSoCy4BLL8OnuK8cP3SEaJsvw,117 +lm_eval/tasks/belebele/belebele_fuv_Latn.yaml,sha256=2zgs1M4_uFUikuIl9zuhluI-y0Yn2NDthPAcLCr5IG0,117 +lm_eval/tasks/belebele/belebele_gaz_Latn.yaml,sha256=Am-KDq308E6D2MxQL_cj4GddvwZN2_U4fuCBrOgD4SM,117 +lm_eval/tasks/belebele/belebele_grn_Latn.yaml,sha256=c6ZbthYlFYhx32oXb_nksrQlFJ4wrzziQ-vnwt2XYOc,117 +lm_eval/tasks/belebele/belebele_guj_Gujr.yaml,sha256=ZrDrbaxwMdkB7hrr1tD90wm076RRUrv_uo3jUN8YPmI,117 +lm_eval/tasks/belebele/belebele_hat_Latn.yaml,sha256=IFDS5Pz1qx7gekhhEYd6vQ3wts43bPs4ZhA5OU6V1Bo,117 +lm_eval/tasks/belebele/belebele_hau_Latn.yaml,sha256=lzkLcA63Ilek158eAaEYHmPR4iXHA6dRCCYsWqgHNs0,117 +lm_eval/tasks/belebele/belebele_heb_Hebr.yaml,sha256=sHdqpr5kNxhpJGHzy7OIrctOjTt7qBMBXHkJCObwjDk,117 +lm_eval/tasks/belebele/belebele_hin_Deva.yaml,sha256=5TxiK1wZ0rHN2b3pyEOvyVuzqWBqt_tzq_ft4w1bdF0,117 +lm_eval/tasks/belebele/belebele_hin_Latn.yaml,sha256=XZfEoXE4J9vZjqGfcoPN1Q-N-G-hkysvdQ3I2yklnnw,117 +lm_eval/tasks/belebele/belebele_hrv_Latn.yaml,sha256=UGkkEmKyJVKZsClWkfiYQQz86U1C21YSrsLySadGoV8,117 +lm_eval/tasks/belebele/belebele_hun_Latn.yaml,sha256=2mC9F1P-LHPz6Q71fk_P7simWeAmcoexIZZI-EoDIFM,117 +lm_eval/tasks/belebele/belebele_hye_Armn.yaml,sha256=mqTHfv7HjWEjbqRS07DhAXCfBrCOUHCNY4LxmrFBr50,117 +lm_eval/tasks/belebele/belebele_ibo_Latn.yaml,sha256=_U-K5_h-vvxC-zqYSLaPZR_n5JtUg89MVPHI6iRgvzU,117 +lm_eval/tasks/belebele/belebele_ilo_Latn.yaml,sha256=SqaY3Uj_Yuf-E4E_oOcNm_0p9eDJE_s8Dbm6eWTnZTM,117 +lm_eval/tasks/belebele/belebele_ind_Latn.yaml,sha256=oFOtiL0XoghRrIm2_hGMVpO28XUb0nAJ3fp8Mcrua2w,117 +lm_eval/tasks/belebele/belebele_isl_Latn.yaml,sha256=BJsHBBT0IVJCsjOrZVrz9eh07KQLLJ70cCYt9zOQB7U,117 +lm_eval/tasks/belebele/belebele_ita_Latn.yaml,sha256=fCduE0IoxoROD_2xdQsnyLGJqtPMw8vc5tkU4ANl0Rk,117 +lm_eval/tasks/belebele/belebele_jav_Latn.yaml,sha256=fggfgk-_2kwTOttkMH9Belu111ddkcCT4VvWXL6XpTk,117 +lm_eval/tasks/belebele/belebele_jpn_Jpan.yaml,sha256=59SsgQqaPm0tHxWIfu-RzU8wRq3MF_WPA2iol59Vegc,117 +lm_eval/tasks/belebele/belebele_kac_Latn.yaml,sha256=KBO64zzpJl62LJqMI5IDB9sX3yt4soxAgrFtbUKmlQ8,117 +lm_eval/tasks/belebele/belebele_kan_Knda.yaml,sha256=na6caVGyAWF_ajjALHQTHKxXWvm5nkjwTMqpAZ7fV0U,117 +lm_eval/tasks/belebele/belebele_kat_Geor.yaml,sha256=mbMOTih_ujZpjVtGVxtsU3QhWHpKS5zDJ3jnxQCHtgM,117 +lm_eval/tasks/belebele/belebele_kaz_Cyrl.yaml,sha256=4Erwu3m4wHLwAHEVDwz34Y-AnDg4pYCz9EfJ1VAwcPY,117 +lm_eval/tasks/belebele/belebele_kea_Latn.yaml,sha256=LzFw_MSbqsCXHm95N-20xGnu5wukru87QfUByDngN70,117 +lm_eval/tasks/belebele/belebele_khk_Cyrl.yaml,sha256=9mvQti4PxJQsk4tHYtg4WcN0OfGUCl6ozgbEuuKnFPo,117 +lm_eval/tasks/belebele/belebele_khm_Khmr.yaml,sha256=_I0Ma_R1xqmv1N57xIviUIF3AVDvT7ehbBJYe5uxYuo,117 +lm_eval/tasks/belebele/belebele_kin_Latn.yaml,sha256=xF0bTypUAQB-D7ED0L_eL-am8vN8FlvrkJoZkt0i7QA,117 +lm_eval/tasks/belebele/belebele_kir_Cyrl.yaml,sha256=b77pIdwRhj34n1f_Bgp4Ch8Q5bngvYetuk6qPSHxsF8,117 +lm_eval/tasks/belebele/belebele_kor_Hang.yaml,sha256=tZUX8rsTKLVCIPo2VyC6vg5IT_0g3S_sSYD7fSqYjyk,117 +lm_eval/tasks/belebele/belebele_lao_Laoo.yaml,sha256=0nriykEwGK8cHGjTX4-MUPJPxIEZCIc_4LbgrCcgztA,117 +lm_eval/tasks/belebele/belebele_lin_Latn.yaml,sha256=dd91MkzxL14bKD_OVWfFsCac4No8VkNWKDF2csAxHx0,117 +lm_eval/tasks/belebele/belebele_lit_Latn.yaml,sha256=4ciRkZXnOnOyEUdQGlS9ioG6-eJ51hXOutfxtvHeD88,117 +lm_eval/tasks/belebele/belebele_lug_Latn.yaml,sha256=2TaDy-FDr93w_NNUtGvSr-Hls9KmGfT8ZbZa1go7cLk,117 +lm_eval/tasks/belebele/belebele_luo_Latn.yaml,sha256=sCCOcx2NArKXFbF5YsHSkQnVj920HdOAsI7yrYXVfD4,117 +lm_eval/tasks/belebele/belebele_lvs_Latn.yaml,sha256=yAka2b99-TlTedbQXMBdOY7ZuaNKfY5CI73MqWGDSfw,117 +lm_eval/tasks/belebele/belebele_mal_Mlym.yaml,sha256=60y_Z4Xf21CBLFbLfUpe92hhSqUpKeMkTNlRv7Fu0GM,117 +lm_eval/tasks/belebele/belebele_mar_Deva.yaml,sha256=iHy8kLYyzPHUxfzLPvcJhWGhfaY7KdaDqENqMti3weM,117 +lm_eval/tasks/belebele/belebele_mkd_Cyrl.yaml,sha256=lxXvzZAAP34VcwptDgNSqmG6P4FXsdbHBcrIDsw-fGM,117 +lm_eval/tasks/belebele/belebele_mlt_Latn.yaml,sha256=tlR9FYl_VLMLEPJnAf93VKykJ9yU7V7P4LrHaThUIYY,117 +lm_eval/tasks/belebele/belebele_mri_Latn.yaml,sha256=cXsDUC1lhfpEyywS1c06Pf0qzmuOHBp4IJXfGLW3vso,117 +lm_eval/tasks/belebele/belebele_mya_Mymr.yaml,sha256=s6LUjwN2bknAT88o3v4-LOO_YV6yEKo3Gg3WtOE7zvM,117 +lm_eval/tasks/belebele/belebele_nld_Latn.yaml,sha256=Dd2fed3FJIt6lJ4N2QzpE12seXIouq4SSuFK3s05Jqo,117 +lm_eval/tasks/belebele/belebele_nob_Latn.yaml,sha256=9CIyMcCp5oJW3sJbJSXgMM3pv8TAFMVwQ2mAXNdY5kk,117 +lm_eval/tasks/belebele/belebele_npi_Deva.yaml,sha256=UCQ7yWzYicrv3fp8vqDeQ8rLynq8T_ZPX4AvkBRMa1E,117 +lm_eval/tasks/belebele/belebele_npi_Latn.yaml,sha256=vZTqvqA86lzAQqXcAxA2bnlEWz3NekYkjpPHHz_tdX4,117 +lm_eval/tasks/belebele/belebele_nso_Latn.yaml,sha256=PT5LT5fwLTyvB4ruIK9qyt-LaCM-pasXUb2aRzloTL4,117 +lm_eval/tasks/belebele/belebele_nya_Latn.yaml,sha256=62xoCFekdxpvUFLcfhH0QLqbwkxaNuBCaV_hNKf5DPo,117 +lm_eval/tasks/belebele/belebele_ory_Orya.yaml,sha256=W6frQwbg9z69i8_mKHf-oHRvUJhIVHw5988Ij4hg-SM,117 +lm_eval/tasks/belebele/belebele_pan_Guru.yaml,sha256=Gtanduetmm9mE0DLDN8fF0ELS2RtmfQaty3Ag851u6g,117 +lm_eval/tasks/belebele/belebele_pbt_Arab.yaml,sha256=l5v5c1y3oLECT8r5TBASKJNotUGaudZyWtNnkxUoTC4,117 +lm_eval/tasks/belebele/belebele_pes_Arab.yaml,sha256=lfO-93-WV0kHChUTwZNGN_67SnuE_dWWPMXodxNChcI,117 +lm_eval/tasks/belebele/belebele_plt_Latn.yaml,sha256=qxFFK8hTsOfzUwf0JhYYnj1faapl1fvOJidHkKmZcQE,117 +lm_eval/tasks/belebele/belebele_pol_Latn.yaml,sha256=wPXTjvfgiYw-wq-AqRjmvceeKaiZKGxcc5DSLYFnZhI,117 +lm_eval/tasks/belebele/belebele_por_Latn.yaml,sha256=9ZSsYjV_agSrefKGwtAj2Leaf4YgPCrwFJXA7cXZWgg,117 +lm_eval/tasks/belebele/belebele_ron_Latn.yaml,sha256=YhzeVLH-lCrMe2FgXoRCbN799a9Begb2iNm_K52XWg4,117 +lm_eval/tasks/belebele/belebele_rus_Cyrl.yaml,sha256=MBdiGKUaM3XvGC5TcUMjjhLHZaKreZRvBwUXYjMqiEk,117 +lm_eval/tasks/belebele/belebele_shn_Mymr.yaml,sha256=VBKTseVSUZWZjlV_Qqw1JyUjijuazHPS-G59vSlEAOI,117 +lm_eval/tasks/belebele/belebele_sin_Latn.yaml,sha256=Pq4mtdhkZ8GEiQpBUtA9ZJ0yGtd6QvzGFt5iIeJ7QqY,117 +lm_eval/tasks/belebele/belebele_sin_Sinh.yaml,sha256=jbH9mN1vERNn1iDUeiLjWxJQNlrtSlt9x8j66yhSpqE,117 +lm_eval/tasks/belebele/belebele_slk_Latn.yaml,sha256=ez3bUC6z6AgbHbF5Ahxjm9XrMLWLzijMjV2LpnWRVak,117 +lm_eval/tasks/belebele/belebele_slv_Latn.yaml,sha256=LTsIYDCpt-G2JVHbIK5TsMDxRBF57QshikHoGDB2cs8,117 +lm_eval/tasks/belebele/belebele_sna_Latn.yaml,sha256=eQ8BbzbPdD3ReBkMm8JldqntqdQQcd6IMPsewbE9tHw,117 +lm_eval/tasks/belebele/belebele_snd_Arab.yaml,sha256=XQfQzK89afh2Rb73AsML___G67mc7j5bbBqaiudEkrw,117 +lm_eval/tasks/belebele/belebele_som_Latn.yaml,sha256=AFsIV2QqGYqwwu3ymjEpwHStRcym9zo3NfUB9bDcr8Y,117 +lm_eval/tasks/belebele/belebele_sot_Latn.yaml,sha256=DkgjgGaN49OUla6LQd-PWZ3oigBLaHxiFZCmMomkvwU,117 +lm_eval/tasks/belebele/belebele_spa_Latn.yaml,sha256=RnnQVuumrNH4t6wNyqCAu0KHqixtl14K_GrsHlRo1ik,117 +lm_eval/tasks/belebele/belebele_srp_Cyrl.yaml,sha256=MJMi_zj1sDAANAparEXXhpBsKsFl72aulVCvwtg608s,117 +lm_eval/tasks/belebele/belebele_ssw_Latn.yaml,sha256=z4ZlK52dPg7Iy1huGmqdQshPkf0lkdgfDGSCNuWRDDM,117 +lm_eval/tasks/belebele/belebele_sun_Latn.yaml,sha256=U0zXr_wJ_PZCTkD3w43aJg-1az-am598syHo4L0GDH0,117 +lm_eval/tasks/belebele/belebele_swe_Latn.yaml,sha256=FSamGbZJjEyaywTY04GEaXeH562KMAO_JQ5wJ6CP5zw,117 +lm_eval/tasks/belebele/belebele_swh_Latn.yaml,sha256=vJ6HXNruMr6mo2n0ZRrAckEXCaBQSLlQ2PNNuKKWC6k,117 +lm_eval/tasks/belebele/belebele_tam_Taml.yaml,sha256=0fEr-Wet29O9dCiPfWB8a1O158DT2J8c9hUtrcOLnHo,117 +lm_eval/tasks/belebele/belebele_tel_Telu.yaml,sha256=kzX2E7ozzn13_6ztXcwLBQh5ZECKJ9a9uI-8UKF7F08,117 +lm_eval/tasks/belebele/belebele_tgk_Cyrl.yaml,sha256=1OMlPVKbPojktAzAiNtWo_oC4oPZfDlEQSRhEpCwV2E,117 +lm_eval/tasks/belebele/belebele_tgl_Latn.yaml,sha256=AoE2baYqrPrNvXpGQHi-cMIjveeWko0xs5smctyNUV8,117 +lm_eval/tasks/belebele/belebele_tha_Thai.yaml,sha256=_7bdsGsN_IqJLAi1wFkyhPcPimpWp1SkGc5VnPYV5I0,117 +lm_eval/tasks/belebele/belebele_tir_Ethi.yaml,sha256=Nko8UZ1kSbcWhxCL3v8jtdqgK99kipth0iZPaWZ4r5A,117 +lm_eval/tasks/belebele/belebele_tsn_Latn.yaml,sha256=0ctcFmW4qJ2GB3m63-I3uNlgYX93NkGUSXV3cUSVyRs,117 +lm_eval/tasks/belebele/belebele_tso_Latn.yaml,sha256=NaVyWnhITUTXHFovQbnUyiF2aAULB5G7TVNqrrO8eWE,117 +lm_eval/tasks/belebele/belebele_tur_Latn.yaml,sha256=woe79SthhsQhHJAAGeIv5kPjfO7LjMGqsjgyrMBm5T0,117 +lm_eval/tasks/belebele/belebele_ukr_Cyrl.yaml,sha256=_h-10kKVwf5h8L2PRheQWKPDEKJgsZvf-WTQ_xYJpN8,117 +lm_eval/tasks/belebele/belebele_urd_Arab.yaml,sha256=blghiHBZpPRoju-cqpl7FiGG1hyGbRQzbMfkP-p4YwY,117 +lm_eval/tasks/belebele/belebele_urd_Latn.yaml,sha256=ZDxfot4bKgcXLW8SBH42zfbL7KcZF3bFf164lYz6yxY,117 +lm_eval/tasks/belebele/belebele_uzn_Latn.yaml,sha256=HaAURsOkDmCatCT8EgH0q2ni3HDMn05wlLIpQA8iIgQ,117 +lm_eval/tasks/belebele/belebele_vie_Latn.yaml,sha256=QNko1Yqj_PSIPJm0kIQZV-ujAvMGCpKBukma2PIV6P4,117 +lm_eval/tasks/belebele/belebele_war_Latn.yaml,sha256=U5xdsP0LNGHbqWt9BkP3MeLHPL7afj7MKqotfSRDj3o,117 +lm_eval/tasks/belebele/belebele_wol_Latn.yaml,sha256=DhZ8fA-SnFNCBYit3sDIR7fVE02GqyJ1RVpm6vNMvyc,117 +lm_eval/tasks/belebele/belebele_xho_Latn.yaml,sha256=0nT5V3mr1_ShbzFNRQspUDawxy3Fcb8RAH1XU-s1aHQ,117 +lm_eval/tasks/belebele/belebele_yor_Latn.yaml,sha256=eNSl6gNTISIuwT_tn23c9Olj5q4UrEffBAxfG6v1POU,117 +lm_eval/tasks/belebele/belebele_zho_Hans.yaml,sha256=F-jD_qluePBEYSZFgPhvQjhp-tgAcp3Vv2cMWu1d-js,117 +lm_eval/tasks/belebele/belebele_zho_Hant.yaml,sha256=-3ZBT_ESjzRWjLOa5x172BS910ayI7uqtWgCvkfAYwM,117 +lm_eval/tasks/belebele/belebele_zsm_Latn.yaml,sha256=bMob3HTMA0DwI7Qc81RINHLB5I57VznQhkuApHW9Qos,117 +lm_eval/tasks/belebele/belebele_zul_Latn.yaml,sha256=7M_qJjo6XAhlWG6xC99bXvWkU4g6XDvEvOSWzkga4BA,117 +lm_eval/tasks/benchmarks/flan/_held_in_template_yaml,sha256=8dsDGbiy4jXYWwg1jzpjFi9MOkc6bkH1Pt5YFW9gSEM,255 +lm_eval/tasks/benchmarks/flan/flan_held_in.yaml,sha256=NzCeaWvM7ZBl5iAJLg89uQivP9EhxbXkHVjHwy2RolY,19112 +lm_eval/tasks/benchmarks/flan/flan_held_out.yaml,sha256=5vHKmz0WUNCMugMItX0Ym8metOG1IU8anff9aGyMq9Q,247 +lm_eval/tasks/benchmarks/minerva_math.yaml,sha256=lb2Yn4TfnswputGzd0vO4yX4YpfqZp-drdOfWViJA80,231 +lm_eval/tasks/benchmarks/multimedqa/README.md,sha256=3i7dHJvrbpWYzjn5W51-sl-FUxQhvM9hsi738TrSQzM,2373 +lm_eval/tasks/benchmarks/multimedqa/multimedqa.yaml,sha256=8cLeL6MaferIiOgpiLjF55a_4x2WsulJzvWkwNkj4yg,506 +lm_eval/tasks/benchmarks/openllm.yaml,sha256=SE8PyOTLK5FEUf9VKnzxzae1JgII7tp2-UZdVgVrKzw,368 +lm_eval/tasks/benchmarks/pythia.yaml,sha256=xb6ysr5Wkze05aUl0DS6aKWKN4d3-WBXHInrmE3Q4Uk,135 +lm_eval/tasks/benchmarks/t0_eval.yaml,sha256=NfW-WLp-pnT4hQrmNyO1Du6DHVscevER86MHVSf_zVE,3491 +lm_eval/tasks/bertaqa/README.md,sha256=jx7yUNVBqmtPY3JoPMMxa4Nh9VLmf-FN1kuAds3evhE,2722 +lm_eval/tasks/bertaqa/_bertaqa_template,sha256=xVDV7mRwQ0xApuTHWcHFhGNviWNrYS4iNhnkw0uuN5w,306 +lm_eval/tasks/bertaqa/bertaqa_en.yaml,sha256=5ovVcVQTjSSrjmYtUEAm8IDwL8RTO9sSMQPDGjaKKSI,174 +lm_eval/tasks/bertaqa/bertaqa_en_mt_gemma-7b.yaml,sha256=T5_uktfr7VPmp1nTtXtWEC7HV6QAHVMH_I9L7xI0tio,198 +lm_eval/tasks/bertaqa/bertaqa_en_mt_hitz.yaml,sha256=1tnXoNJeHj7X42p3tlkBun64g1RjWLZd0fP_rkxKk1I,190 +lm_eval/tasks/bertaqa/bertaqa_en_mt_itzuli.yaml,sha256=Q92e4LENGSwiYbX1gVKvDkG-83e0pB8YZyRbgWuEIIU,194 +lm_eval/tasks/bertaqa/bertaqa_en_mt_latxa-13b-v1.1.yaml,sha256=vsmUuavNv8r9_NgyYBTtumyulibH19u8suME89T-qQM,210 +lm_eval/tasks/bertaqa/bertaqa_en_mt_latxa-13b-v1.yaml,sha256=opoANZTGSUZmt2W0hwsrV10lj5ZAIkzBoBM2Cfy0I_o,206 +lm_eval/tasks/bertaqa/bertaqa_en_mt_latxa-70b-v1.1.yaml,sha256=-mfmmCNQA9P86r8_4kXo3zs1mASMBSisFACTW9-MN0U,210 +lm_eval/tasks/bertaqa/bertaqa_en_mt_latxa-70b-v1.yaml,sha256=Je5pih5rLEXvg7W_Jfwg8BvibmyXBuFRlBSpt1G3Jns,206 +lm_eval/tasks/bertaqa/bertaqa_en_mt_latxa-7b-v1.1.yaml,sha256=HPFk03E-xNYE05cNG9_Cpra8khuTzfDOFwdYA0veq_U,208 +lm_eval/tasks/bertaqa/bertaqa_en_mt_latxa-7b-v1.yaml,sha256=xMAZdEx_JkZC_5OqnlQ-h1n_XjyPRvpgnbDR21XZpQU,204 +lm_eval/tasks/bertaqa/bertaqa_en_mt_llama-2-13b.yaml,sha256=UWkTbpCB-SX4V5MCcDMQFtHatCIoxwKl4scYaCu7okw,204 +lm_eval/tasks/bertaqa/bertaqa_en_mt_llama-2-70b.yaml,sha256=aQzKNJI-Lnx0-TbFNgVzrgvDMdxFgg2fA1Om6fHl8c4,204 +lm_eval/tasks/bertaqa/bertaqa_en_mt_llama-2-7b.yaml,sha256=5s9N4y2gobf5T_Wc10j4s9ZbxIacpmfSkV2qhD2FpO0,202 +lm_eval/tasks/bertaqa/bertaqa_en_mt_madlad.yaml,sha256=869pdQT5y5PFcmPwADAsh3xxRcD-dBye_fLbaAY-Pkw,194 +lm_eval/tasks/bertaqa/bertaqa_en_mt_nllb.yaml,sha256=XbMILc5G1LS0OzQRK1AitP_5VonHuLnwUnfssdTvS-w,190 +lm_eval/tasks/bertaqa/bertaqa_eu.yaml,sha256=JEK_L5-M5RU2uD8zd6pVjDl2Z3OlSp-uxQ5WEjZcNl4,176 +lm_eval/tasks/bigbench/README.md,sha256=-S-u9m2fxpIOoIvS4K1LS2Td3WfjFw4XFh6FnJXOGWM,9772 +lm_eval/tasks/bigbench/__pycache__/generate_tasks.cpython-310.pyc,, +lm_eval/tasks/bigbench/__pycache__/push_bigbench_dataset.cpython-310.pyc,, +lm_eval/tasks/bigbench/generate_tasks.py,sha256=0M2OnqlxDO7YPHIMYAqJ9osiJZFE-r7dfTB2BbNHmPg,6601 +lm_eval/tasks/bigbench/generate_until/abstract_narrative_understanding.yaml,sha256=0QLUsd46oJza1RWtto1OHpdpxd8r79lLZJ-8eFNw5ZY,185 +lm_eval/tasks/bigbench/generate_until/anachronisms.yaml,sha256=T1Fc7bNpFatJyeTOAZ61FOA_vQkkMwPpgFLvEe3tMGE,145 +lm_eval/tasks/bigbench/generate_until/analogical_similarity.yaml,sha256=I-HNuu_mTxqRNiAGpiyEpoMbm4ViZJpd8tdPD-fkW5g,163 +lm_eval/tasks/bigbench/generate_until/analytic_entailment.yaml,sha256=4IpGceDe68otlD7i617DSBXqhw067Y4AjpYVWYnfURU,159 +lm_eval/tasks/bigbench/generate_until/arithmetic.yaml,sha256=--6zcCrvHwjcE1SSujrnoCHDXpTo4c2CT9sosctJ0qY,141 +lm_eval/tasks/bigbench/generate_until/ascii_word_recognition.yaml,sha256=QhBAm87LFXXIztQjATqtE1QG2s3JOkADRvbiASZcsOM,165 +lm_eval/tasks/bigbench/generate_until/authorship_verification.yaml,sha256=J7qQUerJLmxVwptNTbsFlZrDn3WWjxyA-i6aDY-iQ7I,167 +lm_eval/tasks/bigbench/generate_until/auto_categorization.yaml,sha256=ZSVByX3aUgSSa_dUYHfJvm6bX6ID5iFF9pZodjWzudI,159 +lm_eval/tasks/bigbench/generate_until/auto_debugging.yaml,sha256=EwWe_JEyKN8cQTnhvMFV2T40Td2Igaq0rWuvm9VFVaU,149 +lm_eval/tasks/bigbench/generate_until/bbq_lite_json.yaml,sha256=x7II4n0ImBk4HwpbXn6Dap0no5YBdrizIo3qqeoIstQ,147 +lm_eval/tasks/bigbench/generate_until/bridging_anaphora_resolution_barqa.yaml,sha256=QFdj_nZPzivXQ_99MACTqsq_hNqpOXwAv0JBvnKZQZU,189 +lm_eval/tasks/bigbench/generate_until/causal_judgment.yaml,sha256=f9fiw28Jp_YEeRgrbmUG8dwtt7l6Up22-1-r-uhDyuY,151 +lm_eval/tasks/bigbench/generate_until/cause_and_effect.yaml,sha256=5GlQQ-CAgOwXPypYnjRMpdyZ7fA4a-x6REDBEPpmFGo,153 +lm_eval/tasks/bigbench/generate_until/checkmate_in_one.yaml,sha256=eWi6zh5n4gwBcE3J7IMiyNttiy2EYvOTAcMMB3Q33lI,153 +lm_eval/tasks/bigbench/generate_until/chess_state_tracking.yaml,sha256=anlmDNc-UuKZhgvd4bGHfnloD0817tEiYWuoMBrstVI,161 +lm_eval/tasks/bigbench/generate_until/chinese_remainder_theorem.yaml,sha256=hUIYsvTxDFpXOBBR3rc5ByHjK-kCr0IJuYD4-uCEeqU,171 +lm_eval/tasks/bigbench/generate_until/cifar10_classification.yaml,sha256=E96IQAlynQhHjAYzJh3CIy3o1oF5Np0onr3Y0G0dS1Y,165 +lm_eval/tasks/bigbench/generate_until/code_line_description.yaml,sha256=EbyOJ6tcfb56fDC7jKERqViylqMzNZReN5N4tFrp054,163 +lm_eval/tasks/bigbench/generate_until/codenames.yaml,sha256=RHFfLNH_PvBByvta_z2FSqC0MgA5V7lr6ORRJN5IjO0,139 +lm_eval/tasks/bigbench/generate_until/color.yaml,sha256=V66z_3cDIsLWHt7cHqnPGfFFvgVBypj-jqW60l4WGy0,131 +lm_eval/tasks/bigbench/generate_until/common_morpheme.yaml,sha256=DMnQE0PnPan9Z10yajvyM6AnDz2SNKrmID06eKfW-aU,151 +lm_eval/tasks/bigbench/generate_until/conceptual_combinations.yaml,sha256=wN2KQGaT9pun0hOWwe3jrAkjh2lZScYr2jJtiKfPiCA,167 +lm_eval/tasks/bigbench/generate_until/conlang_translation.yaml,sha256=-HU-3JkFMpn4vPatZMO3gA6vAJBfdc5XISmYzTDIuMc,159 +lm_eval/tasks/bigbench/generate_until/contextual_parametric_knowledge_conflicts.yaml,sha256=CgIDUv6CCJ07FK6H_ATyzqHq8uy_p4ktGWawP8Bmy64,203 +lm_eval/tasks/bigbench/generate_until/crash_blossom.yaml,sha256=_kEHp_E3G1AXRC0UsLL6LLJN0o7OXpaobTZl9idnP9w,147 +lm_eval/tasks/bigbench/generate_until/crass_ai.yaml,sha256=Gjf50yyrvFYa2uCcpcu6IJEw4_GpvPtLaIt_dHSgKiw,137 +lm_eval/tasks/bigbench/generate_until/cryobiology_spanish.yaml,sha256=tIqxreR7fTTOmPbYthVH-SEuzjgJQhfAdm7wkQx_CPw,159 +lm_eval/tasks/bigbench/generate_until/cryptonite.yaml,sha256=5QWZppWvBkcS3wifv3cihe1fCKTZnwVvmtifEkPjgbE,141 +lm_eval/tasks/bigbench/generate_until/cs_algorithms.yaml,sha256=Bs4PE7GgZLTX3cPlHHaFqcDmmoEfUOc5V_Gmipya7ls,147 +lm_eval/tasks/bigbench/generate_until/dark_humor_detection.yaml,sha256=u98XLx00QqxUlZyScZSaDghGG2XNblgVvQMYLzWW-5I,161 +lm_eval/tasks/bigbench/generate_until/date_understanding.yaml,sha256=ikMqfOMsIQ5sMEu5F6jmiPZ1QIk55BMoWgPmlD2YZZc,157 +lm_eval/tasks/bigbench/generate_until/disambiguation_qa.yaml,sha256=3AfjnL9sxOL7-mS00bAMCer8ytGaceP-AEVKJ036qCg,155 +lm_eval/tasks/bigbench/generate_until/discourse_marker_prediction.yaml,sha256=IDsWjfdbnWGCmPZOPXF1cCqoae05UYLPwO2FJ2SqHVE,175 +lm_eval/tasks/bigbench/generate_until/disfl_qa.yaml,sha256=slBKpOw28f7O4FrQjm43gqzcHgOB9-2ysKGTlOXcIt0,137 +lm_eval/tasks/bigbench/generate_until/dyck_languages.yaml,sha256=Nf4uiVjkZB78bKbFEbnXRE3-4eTd4oHhWOAQsg4zOsY,149 +lm_eval/tasks/bigbench/generate_until/elementary_math_qa.yaml,sha256=cvAGFFzJcYgDKDmdDfWoJxpPfGYcoH5YKM6hJv-504o,157 +lm_eval/tasks/bigbench/generate_until/emoji_movie.yaml,sha256=xE60hkJ3GUO1IzxA5kyWTgQGN8MdpsFL6U44ABSzpgQ,143 +lm_eval/tasks/bigbench/generate_until/emojis_emotion_prediction.yaml,sha256=XmwhQbFtBGHBvKcFeBNyaVvGZntHdIveeRV_6cdr7Wg,171 +lm_eval/tasks/bigbench/generate_until/empirical_judgments.yaml,sha256=kjuLT2A-PhCTmqnBMu0msAkVL09fHHoTpszp-2Rmvxs,159 +lm_eval/tasks/bigbench/generate_until/english_proverbs.yaml,sha256=C-ssB8SgXTSpWuxyjMBTQX9mBwKvHNNzO4nYcVauhjc,153 +lm_eval/tasks/bigbench/generate_until/english_russian_proverbs.yaml,sha256=jN-poiQ4U4UCdcHf7RMV6hcZBoKFEvuzdkxBUqD4uFY,169 +lm_eval/tasks/bigbench/generate_until/entailed_polarity.yaml,sha256=_gaT1mv0iFYNMbZTGfWeifF6TB8KxASgiyEeXY0vrH0,155 +lm_eval/tasks/bigbench/generate_until/entailed_polarity_hindi.yaml,sha256=RE9kwhgved0dXeKgFCjeFtETtB9FuTgL94iiNSExJj0,167 +lm_eval/tasks/bigbench/generate_until/epistemic_reasoning.yaml,sha256=J-n430fnOd4kw4zRySnYYUG-e7GnxadwVAtqU3S8NRc,159 +lm_eval/tasks/bigbench/generate_until/evaluating_information_essentiality.yaml,sha256=6fKxC324hKwqkpV_6MTNNsLicGevovD1iKDflOtOzhM,191 +lm_eval/tasks/bigbench/generate_until/fact_checker.yaml,sha256=QZ2tsTKpy93PWKXM-cPAdzSKXsYtspGFyQqQXM8QNSY,145 +lm_eval/tasks/bigbench/generate_until/fantasy_reasoning.yaml,sha256=JWzZtrvKJaXfBrC8-B2ClPUze2704DVXUpWioHKCo0M,155 +lm_eval/tasks/bigbench/generate_until/few_shot_nlg.yaml,sha256=jGqGMoegdMocHCIyV2HDHm6yrf-7h4N8JnzI028bWmY,145 +lm_eval/tasks/bigbench/generate_until/figure_of_speech_detection.yaml,sha256=l3ohFveEUwi8QceVaX1Ubpo0bgaJOJkmN20oFENc4GE,173 +lm_eval/tasks/bigbench/generate_until/formal_fallacies_syllogisms_negation.yaml,sha256=VW2iLQzYRtTXjvrCa2Xnz8wlpIyPhUvMfAf_3W_rHZg,193 +lm_eval/tasks/bigbench/generate_until/gem.yaml,sha256=ODcWuReD_irTxL7Om0YX1lwUPdgTvS4gfnq64_9RT9M,127 +lm_eval/tasks/bigbench/generate_until/gender_inclusive_sentences_german.yaml,sha256=N6yiMVWfYnYWXAku7GSw7PAw20_GJevKEF7Nln9s20o,187 +lm_eval/tasks/bigbench/generate_until/general_knowledge.yaml,sha256=0FoVsz9_Whmets9lZh3vpd7TxwclRTFMIT8tpn2iTqk,155 +lm_eval/tasks/bigbench/generate_until/geometric_shapes.yaml,sha256=tVKuLRsEGC6QEZINH_MJL9ouuGxYBuBcIoqf8Ry1CB0,153 +lm_eval/tasks/bigbench/generate_until/goal_step_wikihow.yaml,sha256=HefVYueV7Ib4olhFiPSnN-4tKk-wm2-TTOJZq13zDiY,155 +lm_eval/tasks/bigbench/generate_until/gre_reading_comprehension.yaml,sha256=imJmoGVFj12Yw1LFVNvOwMqmcjvPC0SfBwptLaX_Rj0,171 +lm_eval/tasks/bigbench/generate_until/hhh_alignment.yaml,sha256=u9i_BMm0zJiWEkU_IL36D1nf9TLqGXArxICZoMmyn6g,147 +lm_eval/tasks/bigbench/generate_until/hindi_question_answering.yaml,sha256=ed9fUg5xV9JFW_pI9slzBepyiTu-v1s5s3zu_M7JlCE,169 +lm_eval/tasks/bigbench/generate_until/hindu_knowledge.yaml,sha256=GyJkeBgssT8R04bTdYSQM4oa4v8JWpa2ILwVTvLjOyI,151 +lm_eval/tasks/bigbench/generate_until/hinglish_toxicity.yaml,sha256=F4y708uc0l1a5o1M6s_kSCpYNl3ivpwfWAgO7usZ8JQ,155 +lm_eval/tasks/bigbench/generate_until/human_organs_senses.yaml,sha256=AeQZPk72WRN9G2pj31CvgKiDEbEjSGMppYhni2Q_sVs,159 +lm_eval/tasks/bigbench/generate_until/hyperbaton.yaml,sha256=m_cFalqyG6dq_RoMUzTV9fiTFQQ2BssZfG071Zezlzo,141 +lm_eval/tasks/bigbench/generate_until/identify_math_theorems.yaml,sha256=buqbBDN-gZJY8mnG2IRHpUPbEFgz4e2amo_c1uQmIvE,165 +lm_eval/tasks/bigbench/generate_until/identify_odd_metaphor.yaml,sha256=EoTWJfETPJQIKFScOELfBno5wGMM0KSRUp5Ck8wDh_A,163 +lm_eval/tasks/bigbench/generate_until/implicatures.yaml,sha256=XDY-X3eUplOlnEY2WZis1uGjSU0GLg85c7krqgsGQg4,145 +lm_eval/tasks/bigbench/generate_until/implicit_relations.yaml,sha256=AxXDlJDpf_YQKJpvifStiRPiehlDl3L8_bo8i4EtY-c,157 +lm_eval/tasks/bigbench/generate_until/intent_recognition.yaml,sha256=QSsKdp83MAfBu2LSLUx2dPt1mENEZ5s4O3to4ntZolM,157 +lm_eval/tasks/bigbench/generate_until/international_phonetic_alphabet_nli.yaml,sha256=bPAQzEm6obZvwbxqzZGCDDKYJhasb9Esv6w7FVS5knI,191 +lm_eval/tasks/bigbench/generate_until/international_phonetic_alphabet_transliterate.yaml,sha256=ERiqN2vbxFHM3lbUyvWvm46ydMwxU7y1xa4hur8V3B0,211 +lm_eval/tasks/bigbench/generate_until/intersect_geometry.yaml,sha256=uq6hHt_p6HnyMFMN7XcS6Uhml-Ndv5a5l9TTaSzL-9Y,157 +lm_eval/tasks/bigbench/generate_until/irony_identification.yaml,sha256=3Lg0jMAk1-QXMo08j6T4weLkMU1xihyF94-61Y5cjCI,161 +lm_eval/tasks/bigbench/generate_until/kanji_ascii.yaml,sha256=ma-v7NMOLxNkdKYoRvL9OuEblQ7-l2O2O9bjPhIbyGQ,143 +lm_eval/tasks/bigbench/generate_until/kannada.yaml,sha256=y3M1MBUaQqV6b3cfumpigEoeq9m7j8qu2wqM8mjzeEE,135 +lm_eval/tasks/bigbench/generate_until/key_value_maps.yaml,sha256=YBdKpEXYUdrbg2YxcDpTheRCGtA8QQU_kMEyWfGaR7I,149 +lm_eval/tasks/bigbench/generate_until/known_unknowns.yaml,sha256=FSMjIyrW6Zq86r6PjPnC7GY7KnWQQukFsSkNRMXkIAI,149 +lm_eval/tasks/bigbench/generate_until/language_games.yaml,sha256=4vOMkyvPfKVTI-qWO_FfHnxH66nTN6qROPS5selFR-0,149 +lm_eval/tasks/bigbench/generate_until/language_identification.yaml,sha256=siO1slzacE_Qem-FuA5vwlRqfo_gHZsMCGrIjnA-JlY,167 +lm_eval/tasks/bigbench/generate_until/linguistic_mappings.yaml,sha256=9BAFhXST3cS9ktxMTB-qVF7lqN8NNEUN4L4JjhqSH5M,159 +lm_eval/tasks/bigbench/generate_until/linguistics_puzzles.yaml,sha256=5KGRhLH_mhvoGwdh_CFQTM5r9dPowCxOHzzzcSAkdh0,159 +lm_eval/tasks/bigbench/generate_until/list_functions.yaml,sha256=On2YeI3r2_s9bblbk-AoVp8jZsdmpH7JPTRxzLbLz9k,149 +lm_eval/tasks/bigbench/generate_until/logic_grid_puzzle.yaml,sha256=N7JKcaLTcZIxh6efPHG6grF_-Dia9TLDj6AINFyrgas,155 +lm_eval/tasks/bigbench/generate_until/logical_args.yaml,sha256=LeMAv4cqQynPdEgMjbX6DLUuHtE5be7VL3_TRgEBxcg,145 +lm_eval/tasks/bigbench/generate_until/logical_deduction.yaml,sha256=cMhraRNkbdmCn70YWUI3L5szUSZxF2BZ9dkb08x3otI,155 +lm_eval/tasks/bigbench/generate_until/logical_fallacy_detection.yaml,sha256=Plu8NPXtIwicj-ZOR-s-tUp8sQTRUSidXG13wkiybPU,171 +lm_eval/tasks/bigbench/generate_until/logical_sequence.yaml,sha256=oiqHok8TaV88QsPEmUtF8J_mx7XBBOO_kEi6MYFETcU,153 +lm_eval/tasks/bigbench/generate_until/mathematical_induction.yaml,sha256=AcUk2gvyYMBR2MXIxiswXjcbv4UITm2CU_RboxlfV34,165 +lm_eval/tasks/bigbench/generate_until/matrixshapes.yaml,sha256=oPNV1qhlRa0CStZy9CCOEyYPM1Q88mk51aJ8EEY-yeY,145 +lm_eval/tasks/bigbench/generate_until/metaphor_boolean.yaml,sha256=4pm8zy5rvB_f8jXoTBBLe_0gimdFwt7zkINpHdMztA0,153 +lm_eval/tasks/bigbench/generate_until/metaphor_understanding.yaml,sha256=eTWZ8H4boQ7GHOkRh8JiGNzpqMwV0-jy-pxs3ZEIE6k,165 +lm_eval/tasks/bigbench/generate_until/minute_mysteries_qa.yaml,sha256=-106CIqMUWgCr30EoCxvnjL3NnRwgqF4YzkXBjJKm7M,159 +lm_eval/tasks/bigbench/generate_until/misconceptions.yaml,sha256=GRaducmwu4DxLeIPTw6fcxOi5aEoNctq09pae_zlmIY,149 +lm_eval/tasks/bigbench/generate_until/misconceptions_russian.yaml,sha256=NXz_RMAGdhitHJUrOcyOs3lUJAR3BZczDkNh7wuRbrQ,165 +lm_eval/tasks/bigbench/generate_until/mnist_ascii.yaml,sha256=3ft522RKA2O6tkvjKFEUXR_ZeAHZyRmUYAVFacedIYs,143 +lm_eval/tasks/bigbench/generate_until/modified_arithmetic.yaml,sha256=tN48_TrYgL6NlmDnAFf4_ynOgjgf59tDjZaFMxiGXhs,159 +lm_eval/tasks/bigbench/generate_until/moral_permissibility.yaml,sha256=QWHphy2-qbjA6cVIBkv3jojENR-RtA6dxSFUtTaiMCE,161 +lm_eval/tasks/bigbench/generate_until/movie_dialog_same_or_different.yaml,sha256=izDgy0BjGi5gkJdKBFB6MT-vq2x97ktVkQHPYThzXpg,181 +lm_eval/tasks/bigbench/generate_until/movie_recommendation.yaml,sha256=Ls68uPStQfEA_cXXoHRltL_of6hPd4LCyz5z2FhAQfo,161 +lm_eval/tasks/bigbench/generate_until/mult_data_wrangling.yaml,sha256=tNqxoe0NI87WvxSOPS1JyUr1PCpU-UP-q19tmfeaU9Y,159 +lm_eval/tasks/bigbench/generate_until/multiemo.yaml,sha256=ntr6dACBtdAxlsVaCYxQ4ZYEEZ2Q1pf4jF00fiu7HFg,137 +lm_eval/tasks/bigbench/generate_until/natural_instructions.yaml,sha256=_W6euf1qNMYGfvy7VFPpSGTllBU3TnvQLEwnIzIjsKs,161 +lm_eval/tasks/bigbench/generate_until/navigate.yaml,sha256=SgxFNM3bs3Cbfcw2oE2uBj2vXsc0_NKW-R8n1IPbgMU,137 +lm_eval/tasks/bigbench/generate_until/nonsense_words_grammar.yaml,sha256=y7R8xHkK3Fg9Vwbs6MLI7nEk-v_lBkd3Qdpxw1TyKbg,165 +lm_eval/tasks/bigbench/generate_until/novel_concepts.yaml,sha256=Uw79SXkiEfDm0za-qLou47Vmp42R5necVDTOmIsNnwk,149 +lm_eval/tasks/bigbench/generate_until/object_counting.yaml,sha256=BPtUsBz3xxwrKC38WiDAP0Lz8Boh7rkMC0t4rWobGe0,151 +lm_eval/tasks/bigbench/generate_until/odd_one_out.yaml,sha256=0MPa0ZWseDqQZWxIiUVHPLyHaC0CDqDYP5_VJqML9eI,143 +lm_eval/tasks/bigbench/generate_until/operators.yaml,sha256=Xq2pA8FZ1d84z69QD0oXGH7hqs4fMLs-lxZpjwACBgY,139 +lm_eval/tasks/bigbench/generate_until/paragraph_segmentation.yaml,sha256=UEraXnlx1L9yNh0qQwsz63wJ0AzYlMwJ-m2NjZEning,165 +lm_eval/tasks/bigbench/generate_until/parsinlu_qa.yaml,sha256=BzriiMDmkFzK17iZEYiQmsK_QBfuBewrMNg8Jpanuq8,143 +lm_eval/tasks/bigbench/generate_until/parsinlu_reading_comprehension.yaml,sha256=HRPXjduxFQ66sJImYH00lc7JCNOYvu1Cp1OVpcHtC9Y,181 +lm_eval/tasks/bigbench/generate_until/penguins_in_a_table.yaml,sha256=AK27vKzGHc5dZmI_rUOaMb46gqArR93-qFAeWvc0LSM,159 +lm_eval/tasks/bigbench/generate_until/periodic_elements.yaml,sha256=W3ru5pbGYHFh3cXAWta5sqN6tPhrfZTr0hmXoftd0uk,155 +lm_eval/tasks/bigbench/generate_until/persian_idioms.yaml,sha256=4NV4ESKoI7a7EwwaMoP00HrhbF2n2fFcJDukwkrDjMc,149 +lm_eval/tasks/bigbench/generate_until/phrase_relatedness.yaml,sha256=hEoCjBW50vaQcu1EnVRxmHCglXGOJEQITX7ki8oQemY,157 +lm_eval/tasks/bigbench/generate_until/physical_intuition.yaml,sha256=4tnrOLP_uEpDciJaSe3bvAyw9V9BiEXIuNmy3CkGMRA,157 +lm_eval/tasks/bigbench/generate_until/physics.yaml,sha256=O1CzYMtf6bKfY8xCh8ozpMiGBeKJR2OoDiKnQvS3xro,135 +lm_eval/tasks/bigbench/generate_until/physics_questions.yaml,sha256=Y662E9Oe4bGLueoI3htoqKXQohzO5z1siHfkbkX_crk,155 +lm_eval/tasks/bigbench/generate_until/play_dialog_same_or_different.yaml,sha256=b2pdgfqb9rmc6zFhFh4OhofhuITnd-CagxP_62YP7_c,179 +lm_eval/tasks/bigbench/generate_until/polish_sequence_labeling.yaml,sha256=6syFTfP371tpGL08rlVUPSTGgRYOVs8H6qR-AWwNl9A,169 +lm_eval/tasks/bigbench/generate_until/presuppositions_as_nli.yaml,sha256=F8FjUkXb6KO7faXV_OA96c8C8mehFEGr75jng3A7QRE,165 +lm_eval/tasks/bigbench/generate_until/qa_wikidata.yaml,sha256=R9dHCcdvg2TzI2ZIyYMz9Va63qrW0XV-3pqDOzAVMMw,143 +lm_eval/tasks/bigbench/generate_until/question_selection.yaml,sha256=yy8sqV94vIr97h-srkXC0UXmrn_hCFwfXzuN24T2I84,157 +lm_eval/tasks/bigbench/generate_until/real_or_fake_text.yaml,sha256=BzT3eGjusHCJEkFGUWGKPVHk-Ty-kejnTO09ePPS2-8,155 +lm_eval/tasks/bigbench/generate_until/reasoning_about_colored_objects.yaml,sha256=rHAOlsYCbZi_7Q6CsDJfxHxW-cKMYM108TFrRV6ZtFc,183 +lm_eval/tasks/bigbench/generate_until/repeat_copy_logic.yaml,sha256=aMUsLN4oxqceJBjL42m22on1_4S6miTq4zNLWCKHJIE,155 +lm_eval/tasks/bigbench/generate_until/rephrase.yaml,sha256=o7I78PrOnUIxqFZ_lNt0twELTMrajUAvI1-HvTM0APM,137 +lm_eval/tasks/bigbench/generate_until/riddle_sense.yaml,sha256=eas5Zq3tq1xx03Qn8kB9mU1JbfV-KzY0SWnFTeomy8s,145 +lm_eval/tasks/bigbench/generate_until/ruin_names.yaml,sha256=CkUBCb63izgA8XIrA6Ipg_JEsTZUhTd2jvokluiT0ug,141 +lm_eval/tasks/bigbench/generate_until/salient_translation_error_detection.yaml,sha256=B4ODGvAsPK_yZhh6tdLwahQedWlrI8C747DnsEtMJ7Y,191 +lm_eval/tasks/bigbench/generate_until/scientific_press_release.yaml,sha256=nQqzGRcOY_34eihaI54wGGHxbZmjCiLIlhnTy5NDuRo,169 +lm_eval/tasks/bigbench/generate_until/semantic_parsing_in_context_sparc.yaml,sha256=IfY2K5ChSu7wJJocrAcFOqZZ6DJ2UbNQaVu1YmguN4k,187 +lm_eval/tasks/bigbench/generate_until/semantic_parsing_spider.yaml,sha256=9NQEKZEqKQIxzTB9yrVOL_n9gdzGCTEh_SM_8d54nxc,167 +lm_eval/tasks/bigbench/generate_until/sentence_ambiguity.yaml,sha256=UL89kpxCyDcc80GAvgeyrNSxb7up-Zg2r9vY-DIPOS8,157 +lm_eval/tasks/bigbench/generate_until/similarities_abstraction.yaml,sha256=TJ56BdnL4GqshtCAGMFhnAyoJLakYJjHEg8IjpjUbE4,169 +lm_eval/tasks/bigbench/generate_until/simp_turing_concept.yaml,sha256=VLUMGNwUn7UBmukWVTvm5FpnWwsgI05Sea-mycDxWeY,159 +lm_eval/tasks/bigbench/generate_until/simple_arithmetic_json.yaml,sha256=K-mgxW5WEvkTiuPSRLyrOYrQxNsNOKOCxy903yRsAHE,165 +lm_eval/tasks/bigbench/generate_until/simple_arithmetic_json_multiple_choice.yaml,sha256=E4ScDHW9xrHYoxX6tHpd9F5TelLTfF1FEkWKjiDrAow,197 +lm_eval/tasks/bigbench/generate_until/simple_arithmetic_json_subtasks.yaml,sha256=zrb7SPKYenklYrv5iYEJlhbmoj4hlTsO5LOYzEUaO9g,183 +lm_eval/tasks/bigbench/generate_until/simple_arithmetic_multiple_targets_json.yaml,sha256=hj5tcAejMWEqUpKb92vrxZdc3DmgQiV4wTGUxS0Ah_A,199 +lm_eval/tasks/bigbench/generate_until/simple_ethical_questions.yaml,sha256=W3Q1UG0OZafvdloI4_6KrKUqBWySFjB86ip0wzq1qCY,169 +lm_eval/tasks/bigbench/generate_until/simple_text_editing.yaml,sha256=9tauwNsCUcTjnjjmB7Ci1ffGJfT6kytRqruJQr9OsfI,159 +lm_eval/tasks/bigbench/generate_until/snarks.yaml,sha256=-xI33E-A5p91T-56El3AIwWq8BUaCMvea32zq0VzeS4,133 +lm_eval/tasks/bigbench/generate_until/social_iqa.yaml,sha256=m5y4-e6B9_hsHpO4N1xORqWMGNW26zqG4amCwQViMxs,141 +lm_eval/tasks/bigbench/generate_until/social_support.yaml,sha256=Rw5LSAeaKSqM4P-Bw7TFuyrH2LQHr4eHJU7iF46_HAY,149 +lm_eval/tasks/bigbench/generate_until/sports_understanding.yaml,sha256=THgiCQZQ7uXebiKfUfxMeoRn-wHj9YlbEDzEbUYPFks,161 +lm_eval/tasks/bigbench/generate_until/strange_stories.yaml,sha256=jmSfVWMoIj3671y9thmnqV8CRip8gEzxon2NPQy6EVg,151 +lm_eval/tasks/bigbench/generate_until/strategyqa.yaml,sha256=pvrWXwq87EQTrLZFlvrZwaUvL5S5fGic7ygFJRXH5cM,141 +lm_eval/tasks/bigbench/generate_until/sufficient_information.yaml,sha256=y7jEwlu2P7qgTjNiTJZ9H0jJQjnirAIlZTWVB_n5umg,165 +lm_eval/tasks/bigbench/generate_until/suicide_risk.yaml,sha256=tVTkOx8x631h4azG5yEH6k_tx8PINMgp5gJEAJNnsyY,145 +lm_eval/tasks/bigbench/generate_until/swahili_english_proverbs.yaml,sha256=p2-DYr3WcFI8WSzoh_6ztyYXPZwK15f1d-XXld6xDsQ,169 +lm_eval/tasks/bigbench/generate_until/swedish_to_german_proverbs.yaml,sha256=wR1R1kRuLai6rrIkL_X2qnjFecZpiBqSpE2Sl6_D5wE,173 +lm_eval/tasks/bigbench/generate_until/symbol_interpretation.yaml,sha256=4Eg8-UYe6AvRZVvoyw4pWg3G8SLvotH6Y-fy7t-hI5A,163 +lm_eval/tasks/bigbench/generate_until/temporal_sequences.yaml,sha256=gJ5NyIda1KbTaZ4DsUKm_TwZDervdNq_rThpzo5lPbo,157 +lm_eval/tasks/bigbench/generate_until/tense.yaml,sha256=eorYGhfu6AXOFeGLs2iMWVpoPYm_dyV4slefRIdJ0Zc,131 +lm_eval/tasks/bigbench/generate_until/timedial.yaml,sha256=Sp9BMfBIs4Bob-XdxDhqKdL_QVcHDsdj05hyeGp3pBs,137 +lm_eval/tasks/bigbench/generate_until/topical_chat.yaml,sha256=rcjpxp2ukXzx8nTEcQr4oYEo7TjiFGnHeYZU5oM12ZQ,145 +lm_eval/tasks/bigbench/generate_until/tracking_shuffled_objects.yaml,sha256=SCfecVUi2EGMRzune6kpya491RDXoyct3cbtc7A3C-A,171 +lm_eval/tasks/bigbench/generate_until/understanding_fables.yaml,sha256=vH8I0hlKQ5P8cOGUeI91NClne9qMSUTv7vT0wHK0Z88,161 +lm_eval/tasks/bigbench/generate_until/undo_permutation.yaml,sha256=9BHOlfV8xa5kjVW-uM635tkxDlTTuVFfwn5sw1XX8b4,153 +lm_eval/tasks/bigbench/generate_until/unit_conversion.yaml,sha256=wtTHImrbhNRkSHyF-5hQUvBE0Pdn574G5TIdom-VmfA,151 +lm_eval/tasks/bigbench/generate_until/unit_interpretation.yaml,sha256=9AHsHkx1dwuL2gfbLq8mduuitpKJgpD38xyWNTpfxPQ,159 +lm_eval/tasks/bigbench/generate_until/unnatural_in_context_learning.yaml,sha256=QDLLkgEaTMOQ67huKiLaC1puqfxBcd-W-5U1iIg0aOw,179 +lm_eval/tasks/bigbench/generate_until/vitaminc_fact_verification.yaml,sha256=UdngQIP7djwfw3Yr1n8OTDv5c5wa9vLKuuJXm_62Q2c,173 +lm_eval/tasks/bigbench/generate_until/what_is_the_tao.yaml,sha256=X2ONz9UFxL975TIiCk-L7C5wDRI3TUxN3LCVzCIBswo,151 +lm_eval/tasks/bigbench/generate_until/which_wiki_edit.yaml,sha256=11AwFg-8uyzYs01JdsTlD-76YJTy8QQElnBYtWTxZb0,151 +lm_eval/tasks/bigbench/generate_until/winowhy.yaml,sha256=339YOg_p3fq0a8-5mBkuruJintiUmhe4VzuC4JATV7Y,135 +lm_eval/tasks/bigbench/generate_until/word_sorting.yaml,sha256=sw0cqkQkb4K6yuQpa1HTDRPi36uQKfuJDnpTlHvTspM,145 +lm_eval/tasks/bigbench/generate_until/word_unscrambling.yaml,sha256=vLuTPnG1BzEJcMQwQF37FNPPcFgw9E73tY6i2Y5ABps,155 +lm_eval/tasks/bigbench/generate_until_template_yaml,sha256=sbd04VMXY4sqC54noXYP6TH8givQRdRqlB0mGdmjdRc,509 +lm_eval/tasks/bigbench/multiple_choice/abstract_narrative_understanding.yaml,sha256=GbWoys4Nb9-lTkVo2MmGEpfWv-Cniv3Fuo-Lq4VS5lc,189 +lm_eval/tasks/bigbench/multiple_choice/anachronisms.yaml,sha256=aDWR9aUU1XPNhuS3ewel2j-LN74e7t2MCdx6s9ITgdk,149 +lm_eval/tasks/bigbench/multiple_choice/analogical_similarity.yaml,sha256=7J1DpFq8ByXEtr4bUFoibxDzGPKXhhjnxIOsOMpPfz4,167 +lm_eval/tasks/bigbench/multiple_choice/analytic_entailment.yaml,sha256=0iQIdl01itXpSwQcf6GugclaEtnyqitxGKmAJahlxFU,163 +lm_eval/tasks/bigbench/multiple_choice/arithmetic.yaml,sha256=Pfubn99mZg4lVr4ShO-_AgmGvnGfZHypPvtWxvP355U,145 +lm_eval/tasks/bigbench/multiple_choice/authorship_verification.yaml,sha256=RVJwjotftrsuEWsEJRuOF3-N5nHEkwboXvskWkUqGjQ,171 +lm_eval/tasks/bigbench/multiple_choice/bbq_lite_json.yaml,sha256=5k2OquZdohwe3rMQ_DHuXMuRW5ZJK_WZA5kcPh8Nalk,151 +lm_eval/tasks/bigbench/multiple_choice/causal_judgment.yaml,sha256=E769ZddbWG1b_BesLiErN9TXcWNsPlR1GMmxV5bxdqE,155 +lm_eval/tasks/bigbench/multiple_choice/cause_and_effect.yaml,sha256=TvocRRZ5j6pE1O-2fXlWsjYJSZUEl7sDLYbqPUKRnX0,157 +lm_eval/tasks/bigbench/multiple_choice/checkmate_in_one.yaml,sha256=cjo9vBe7YUlU1kixQ0ZpBUbD7op4NTGM9tv1DoJy09c,157 +lm_eval/tasks/bigbench/multiple_choice/cifar10_classification.yaml,sha256=VHukhTqsWoooC0FcB-npPzCz_kdilIxI0ktyRGKFuYs,169 +lm_eval/tasks/bigbench/multiple_choice/code_line_description.yaml,sha256=k0niJXJ49fXOP2oTZ1Z4Se-Rxhbp0V9Ila-6A2nZkPk,167 +lm_eval/tasks/bigbench/multiple_choice/color.yaml,sha256=uaPxMR1vjTgNx-uK4EAMRLxv_YnuaRw1LINaUiOCuW0,135 +lm_eval/tasks/bigbench/multiple_choice/common_morpheme.yaml,sha256=7seTUoP9qb61SCPPThnmCTj3Q3ztCS3bVh4hx0AxVFE,155 +lm_eval/tasks/bigbench/multiple_choice/conceptual_combinations.yaml,sha256=pHctDaX6EriDGL6IFQwBBKSaVXiKl7VTvN1-WpapTFw,171 +lm_eval/tasks/bigbench/multiple_choice/contextual_parametric_knowledge_conflicts.yaml,sha256=k4GVuY_jQvkd2eJvf075-zykCO7TdJwFHsmaKulox3I,207 +lm_eval/tasks/bigbench/multiple_choice/crash_blossom.yaml,sha256=YIoIiaSVh4LHZAVTEd_V3fEqIhHxdrnRMwQXBS6TcZs,151 +lm_eval/tasks/bigbench/multiple_choice/crass_ai.yaml,sha256=R8nbnZowz_6WfSw_fqvypDNHkOaXl4XSEtednLoVDF8,141 +lm_eval/tasks/bigbench/multiple_choice/cryobiology_spanish.yaml,sha256=RZNeS5kIipm5n_JbzVT87kqEEbeC6rm11V37e1-ob14,163 +lm_eval/tasks/bigbench/multiple_choice/cs_algorithms.yaml,sha256=BBynDo7oXH1kXaoKUiYE7KwvS3ISXdQOfO0_o21hxHQ,151 +lm_eval/tasks/bigbench/multiple_choice/dark_humor_detection.yaml,sha256=Yi3b1K55_1HxnY7RAxQUoAbCKQplC_tBDOsvcg4JEW0,165 +lm_eval/tasks/bigbench/multiple_choice/date_understanding.yaml,sha256=jJYp6Biqtlvnxqf1ixGKpUljJze_E_0MIWJmc0_cPGY,161 +lm_eval/tasks/bigbench/multiple_choice/disambiguation_qa.yaml,sha256=41Lz7BaxA90r-ILVrkRsHeMjI1m1lM8mVwAF4apN6QY,159 +lm_eval/tasks/bigbench/multiple_choice/discourse_marker_prediction.yaml,sha256=gCZwmEB69dByS5r42WByeMA0kvhUZewH7whlFPXfS7c,179 +lm_eval/tasks/bigbench/multiple_choice/dyck_languages.yaml,sha256=4chstT-Qnj0NFmJM-NGZCZGyEhsg1-au6zMelmJI7Pk,153 +lm_eval/tasks/bigbench/multiple_choice/elementary_math_qa.yaml,sha256=Gf1Qk7xrcmjfvYUAMfwUuv21RWjAGSDAEojzMxPZFbM,161 +lm_eval/tasks/bigbench/multiple_choice/emoji_movie.yaml,sha256=69w8NPHncxilFkUHbNFu4g4EfoloJZ736WcEzDeb7FI,147 +lm_eval/tasks/bigbench/multiple_choice/emojis_emotion_prediction.yaml,sha256=OhMJNtxDwD85htcNj3T3nQkImieZCEPBj2t85u2qsnc,175 +lm_eval/tasks/bigbench/multiple_choice/empirical_judgments.yaml,sha256=tMXnBIyuGkibQFke3SVxDh0GOK2-mx2p0PHJkXeMlOA,163 +lm_eval/tasks/bigbench/multiple_choice/english_proverbs.yaml,sha256=LypO3KiKnrH0GdswTZgD5H6MmXuUlh4NaIRIILxg7j8,157 +lm_eval/tasks/bigbench/multiple_choice/english_russian_proverbs.yaml,sha256=89Q9gmY-Wl4CU6UE0itHFKFntSgJrI-UNFEU_XGUyvg,173 +lm_eval/tasks/bigbench/multiple_choice/entailed_polarity.yaml,sha256=I_oaviLFBh21plU4NdoY3ypjYMpsGLs7nZx4Jmd2Pl0,159 +lm_eval/tasks/bigbench/multiple_choice/entailed_polarity_hindi.yaml,sha256=FPVmAq0dw1vXGAS-0MCeNjl5XM21U_S0aphlS3qcc5k,171 +lm_eval/tasks/bigbench/multiple_choice/epistemic_reasoning.yaml,sha256=12JJruVXXrXUVWsTcC3QpgXQEVMaPX1hAGkSHQhOUCA,163 +lm_eval/tasks/bigbench/multiple_choice/evaluating_information_essentiality.yaml,sha256=FVcE9A1kG1UnviPNkCdyjMoO-_WFFZciV2nT7NUl7bQ,195 +lm_eval/tasks/bigbench/multiple_choice/fact_checker.yaml,sha256=FZiXcM1Pn-waKZGLy0d3VFH36fMh_CWcOcxt2QNjdE4,149 +lm_eval/tasks/bigbench/multiple_choice/fantasy_reasoning.yaml,sha256=7PABPKwXgz6d3hv6EbuaZfwW1C2rhWE2A1KiQlPW0u8,159 +lm_eval/tasks/bigbench/multiple_choice/figure_of_speech_detection.yaml,sha256=r3QTqGg05wBCCSPIMfku4gmcdsPgLeOap8l7XQIfVVA,177 +lm_eval/tasks/bigbench/multiple_choice/formal_fallacies_syllogisms_negation.yaml,sha256=q-z3RX51L9AT5qgEvetnjQT0p97Fa6RYVKdNZdthcoQ,197 +lm_eval/tasks/bigbench/multiple_choice/general_knowledge.yaml,sha256=_VuOwL6mT231xGXpNKNMNwzuh4pli9_UuHWhghU2DBw,159 +lm_eval/tasks/bigbench/multiple_choice/geometric_shapes.yaml,sha256=33O68T6RWFs5iluTkWzDvhgOlxtzXDoputrwWB03V04,157 +lm_eval/tasks/bigbench/multiple_choice/goal_step_wikihow.yaml,sha256=U_OAbcWC7KYdAP9zU03cBnAKDxmNUFcpVGaDhqndI3U,159 +lm_eval/tasks/bigbench/multiple_choice/gre_reading_comprehension.yaml,sha256=uDBqYpfWFQkP6rfivXD5S_8Ndr2Go4t3X6MQm-UTOqA,175 +lm_eval/tasks/bigbench/multiple_choice/hhh_alignment.yaml,sha256=axCB2ex3xOKldISTngtUl8sUMIrFONVrO2zU6b6pMw4,151 +lm_eval/tasks/bigbench/multiple_choice/hindu_knowledge.yaml,sha256=sQoPFKjUqCOhcRwThYmJaP6OHzdvkgN5PKrbunotERo,155 +lm_eval/tasks/bigbench/multiple_choice/hinglish_toxicity.yaml,sha256=XyyILnt5aZMc8agIinPMFKbaf07kzK43wUjP1HR3rJk,159 +lm_eval/tasks/bigbench/multiple_choice/human_organs_senses.yaml,sha256=mBbbUIxW00gfX9e3iyZa1zKaLuZnJ75VfB0EXd_qkD0,163 +lm_eval/tasks/bigbench/multiple_choice/hyperbaton.yaml,sha256=Ekg1xhqzSYyI6SKLUd9coRoDpmmn6kDsdzNhdZjguXM,145 +lm_eval/tasks/bigbench/multiple_choice/identify_math_theorems.yaml,sha256=pKWCeW9I64elldnKfVf8-LigOkWYG7rndbL_cR10e9g,169 +lm_eval/tasks/bigbench/multiple_choice/identify_odd_metaphor.yaml,sha256=pkjJC7t-H9EKjPqop_qHgKZKNfWfenWzgO0aXTv6iCo,167 +lm_eval/tasks/bigbench/multiple_choice/implicatures.yaml,sha256=QGum6xFZqOoKaJJpjLSpV68R49Qtv30V5NzGBcm7vN8,149 +lm_eval/tasks/bigbench/multiple_choice/implicit_relations.yaml,sha256=bcyqXh-BMpGdVWARifLTUWG6nRJuZqHvnYKik10RgF8,161 +lm_eval/tasks/bigbench/multiple_choice/intent_recognition.yaml,sha256=un8vQLD_a8NjIRLxPbSDgQb8P12ixmAtSriP5pFqFvc,161 +lm_eval/tasks/bigbench/multiple_choice/international_phonetic_alphabet_nli.yaml,sha256=5oMJjog1fAfiLH-6wzaM4olFvoAKJdaZLRghjMRNNfo,195 +lm_eval/tasks/bigbench/multiple_choice/intersect_geometry.yaml,sha256=YOt5W6V0sQ2etx_6hLDTSWZOpcmW_UT41edhYpnuEvs,161 +lm_eval/tasks/bigbench/multiple_choice/irony_identification.yaml,sha256=Epzbq4CqP20EnkRcBV3fy_1Qk88w-OpQrvJtL4648-o,165 +lm_eval/tasks/bigbench/multiple_choice/kanji_ascii.yaml,sha256=niz1QADnA_MUzTm_r-51t3Aw-B2ku5ltc4XjKWXLQhc,147 +lm_eval/tasks/bigbench/multiple_choice/kannada.yaml,sha256=BUdQvcE8AfDS-HRcHgvEgxYy1kaMqIwLcGVoSSMAixY,139 +lm_eval/tasks/bigbench/multiple_choice/key_value_maps.yaml,sha256=5If_vlfyQtZFOcVgogsi3JdzhpHiyct8VpqTmsIb7tc,153 +lm_eval/tasks/bigbench/multiple_choice/known_unknowns.yaml,sha256=kDzoVZPEmoTBMkeRWJN61S7WsEW4x0ejEkbx0kQAiNA,153 +lm_eval/tasks/bigbench/multiple_choice/language_identification.yaml,sha256=sv0sm3UvWPHD--ZJ0QOf_l04SxqtzM4fvHxWXY5DNJI,171 +lm_eval/tasks/bigbench/multiple_choice/logic_grid_puzzle.yaml,sha256=xKN5HkeJ1KROBQsbSh6Pftm5DOzCR728NaQoG6RmIaA,159 +lm_eval/tasks/bigbench/multiple_choice/logical_args.yaml,sha256=qMk9nXCWFWepoPhZqvV0iRZeqguUDI8EZfW1XH1fONA,149 +lm_eval/tasks/bigbench/multiple_choice/logical_deduction.yaml,sha256=3rCshOZGCxRZY83hZklvbuskkXo5YfVHWIqP4gNqnkg,159 +lm_eval/tasks/bigbench/multiple_choice/logical_fallacy_detection.yaml,sha256=TzN6POM6eZ9d2VAU8NnxHEjl0I0WBQONmzEvu80uaec,175 +lm_eval/tasks/bigbench/multiple_choice/logical_sequence.yaml,sha256=WOVhN1BGC8WmyVJtLbHSItKgi5glCMI-EKmdFtWc8uU,157 +lm_eval/tasks/bigbench/multiple_choice/mathematical_induction.yaml,sha256=vBS51nTZTfhhM68bOO9l9BZNzkzZGtyEcAGyahhd7OE,169 +lm_eval/tasks/bigbench/multiple_choice/metaphor_boolean.yaml,sha256=a63v3g0koxQbGrUKcyGP6WKCpTRymAsdEQjGqXTFQTs,157 +lm_eval/tasks/bigbench/multiple_choice/metaphor_understanding.yaml,sha256=06LYHHIQ4msQAjThL78DUGx2WdCsM9OlcITv0q85hfA,169 +lm_eval/tasks/bigbench/multiple_choice/misconceptions.yaml,sha256=k9x4x7ISBFudezJgEoDluB_EexiSrj0gJQgdLYiZjBo,153 +lm_eval/tasks/bigbench/multiple_choice/misconceptions_russian.yaml,sha256=GfTcUES9XyJf9eV-HqYhnakcTj5WaoYardc2yy8wxhc,169 +lm_eval/tasks/bigbench/multiple_choice/mnist_ascii.yaml,sha256=srummF5OLDGd0dIHC0uVYjxKl7A7MYs4wtqUWJJqTF8,147 +lm_eval/tasks/bigbench/multiple_choice/moral_permissibility.yaml,sha256=SJR3GaKFjYknFbvDhJgTx6-_9Cel7MsmdIJK12cpUtQ,165 +lm_eval/tasks/bigbench/multiple_choice/movie_dialog_same_or_different.yaml,sha256=-UsWam73PBWr4dBMo5mHswK5D3v6QHJbfq7J4TogWic,185 +lm_eval/tasks/bigbench/multiple_choice/movie_recommendation.yaml,sha256=9y799gCl_kqamLRsEeU1V60BgmtTluEgiHvjYgRLiS0,165 +lm_eval/tasks/bigbench/multiple_choice/multiemo.yaml,sha256=50ToH0cH3FmihZr0hbtWS28vSftso1FzMejOWLjryII,141 +lm_eval/tasks/bigbench/multiple_choice/navigate.yaml,sha256=nA9qVLyKDFWeCuNssKAT3bTB6YlgydNlJb3AJsb3zX8,141 +lm_eval/tasks/bigbench/multiple_choice/nonsense_words_grammar.yaml,sha256=rzuG197pg4NIi22_qovwyi0PhET8QCcOlkIbYJzZHr0,169 +lm_eval/tasks/bigbench/multiple_choice/novel_concepts.yaml,sha256=k9jm7NrQaAc-Mx9ZASfT-ks9J-_ktxT1eHsKUcPVhHw,153 +lm_eval/tasks/bigbench/multiple_choice/odd_one_out.yaml,sha256=osrWc0Fhv492hDmIGzojN3VkIu_NTVbKDttKlUThgMI,147 +lm_eval/tasks/bigbench/multiple_choice/parsinlu_qa.yaml,sha256=_Hkgaaj7k3w3AY1VhkH8KrVBmk7FRpiBbaMsYzW8SEI,147 +lm_eval/tasks/bigbench/multiple_choice/penguins_in_a_table.yaml,sha256=12K-HMVJoXPX1nVfbNEnc1jBT8-suh0wBTpy7v0u24c,163 +lm_eval/tasks/bigbench/multiple_choice/periodic_elements.yaml,sha256=O_CiUAKOPQYJEYGWTwx73wSc6cUfpAJggu9SVzEOaqA,159 +lm_eval/tasks/bigbench/multiple_choice/persian_idioms.yaml,sha256=vMYpCIdlVUAs2OYXD3C_lvGLv7HAPqVScjqbo6gCK_o,153 +lm_eval/tasks/bigbench/multiple_choice/phrase_relatedness.yaml,sha256=EiAzIHG5QzcN-RjyvsR8NVbtcVzAR6bHsiTV0dp93_c,161 +lm_eval/tasks/bigbench/multiple_choice/physical_intuition.yaml,sha256=w43rI0tv8GOf4xZumbbrC0QeLkd1OJEk4iLJaNR7Ftw,161 +lm_eval/tasks/bigbench/multiple_choice/physics.yaml,sha256=tdxLvphARgS36IVyqQifg57p55kyfxyVnraPsqRlxlY,139 +lm_eval/tasks/bigbench/multiple_choice/play_dialog_same_or_different.yaml,sha256=_cI3rOrVBJ8_a5F8S4DYG_rX5iTy2ILlj1z_ZlOjKKA,183 +lm_eval/tasks/bigbench/multiple_choice/presuppositions_as_nli.yaml,sha256=7nbfQdoG_sOo3Y7KXPzKW_-k-N5NvlkUwyH0Tti9ums,169 +lm_eval/tasks/bigbench/multiple_choice/question_selection.yaml,sha256=7uy1p6pGoJ2VMZNtUZoBZQj5i-cjUdt_tjV7pKecY8o,161 +lm_eval/tasks/bigbench/multiple_choice/real_or_fake_text.yaml,sha256=hCFZz0ut9_454J9UGZ7vBcFkE-IZuKwRzUEAKYH3c6w,159 +lm_eval/tasks/bigbench/multiple_choice/reasoning_about_colored_objects.yaml,sha256=f-gtxeylxsxmxUNXmoE0SYMN5-xuH6-qfySarn4apJU,187 +lm_eval/tasks/bigbench/multiple_choice/riddle_sense.yaml,sha256=vxJKcuhK9gse32yP8-gaKfUHfn8szz0hRxU7esvRcxs,149 +lm_eval/tasks/bigbench/multiple_choice/ruin_names.yaml,sha256=N6dklk_cCVqsASGzjO2HhzrqBzsrsxRINerlk7KHCTU,145 +lm_eval/tasks/bigbench/multiple_choice/salient_translation_error_detection.yaml,sha256=QkQyz5WWgkU3EWiiVvKreewUPR5mXxQSHf7xoyYMUU0,195 +lm_eval/tasks/bigbench/multiple_choice/sentence_ambiguity.yaml,sha256=RWCNN4dwxCz6X5dBcKpQETNVQlcfO-XNtZL8stt3hN0,161 +lm_eval/tasks/bigbench/multiple_choice/similarities_abstraction.yaml,sha256=S4Pmndu0Q2zCBEH70IoDP9T0A0tTHsWJ1F07WZMPpoY,173 +lm_eval/tasks/bigbench/multiple_choice/simple_ethical_questions.yaml,sha256=U9k4XGobYV7-KteiVJLH1ilZvlDCReKrPECxi4Y1u_g,173 +lm_eval/tasks/bigbench/multiple_choice/snarks.yaml,sha256=7OYWAN0WunWsdt1Im6AVhXmmmrHDrJgxLWqrV0nzWKo,137 +lm_eval/tasks/bigbench/multiple_choice/social_iqa.yaml,sha256=kNsXY4lFrIcwEVzY6RMJHDF5ybSvZUIFOllMtJnANSE,145 +lm_eval/tasks/bigbench/multiple_choice/social_support.yaml,sha256=_YWEojKp0kpKiXEoJXBnkFdzqNxYIzU_OO8fet3F9_w,153 +lm_eval/tasks/bigbench/multiple_choice/sports_understanding.yaml,sha256=gr-jDZBR4oVpHJWEM_zQJntIrXBrQEuCseJnaEn-rIY,165 +lm_eval/tasks/bigbench/multiple_choice/strange_stories.yaml,sha256=17ibBUzKxWUJruqbKpMOObd72xRDm8ewONoZ2WBIplg,155 +lm_eval/tasks/bigbench/multiple_choice/strategyqa.yaml,sha256=YRY7RZokNrof4uaqKv_aGHYmkqAWPfhrYmOivsBHmJM,145 +lm_eval/tasks/bigbench/multiple_choice/suicide_risk.yaml,sha256=1HEnEPHq9IcNgXOpwCRQHyDqBcyJ627TKePp8SNnq1Q,149 +lm_eval/tasks/bigbench/multiple_choice/swahili_english_proverbs.yaml,sha256=xk58fbY262s0-5nIPnDyjwBCYTQTGiv153jI5i22Iu8,173 +lm_eval/tasks/bigbench/multiple_choice/swedish_to_german_proverbs.yaml,sha256=YzMOOHCJGTPOHRZRJ8kx41pGH99PkXGSljLyBILe8S0,177 +lm_eval/tasks/bigbench/multiple_choice/symbol_interpretation.yaml,sha256=3HFou0elOwgVSOhLeqn7U3KWNaRAOz64FzczxDTgGEc,167 +lm_eval/tasks/bigbench/multiple_choice/temporal_sequences.yaml,sha256=NYD1gfeO3MArk5BQqTbW9uuvQCRRf4t68ZPrkNoeLI4,161 +lm_eval/tasks/bigbench/multiple_choice/timedial.yaml,sha256=Xt2m_NYEH_WPscR0Xl6hMG8zXzkjbsCXQOHnC7V4-UU,141 +lm_eval/tasks/bigbench/multiple_choice/tracking_shuffled_objects.yaml,sha256=HDFlw_swXyc5xcMXk_t6LrBxOEFtw6lKZg728K0FWxc,175 +lm_eval/tasks/bigbench/multiple_choice/understanding_fables.yaml,sha256=K8VlZrvMHPPItmoRg_jHDSpU9rjn6KssSogMvGzOa-o,165 +lm_eval/tasks/bigbench/multiple_choice/undo_permutation.yaml,sha256=fT1BZiis9nb3MWfq6-dwL_uH1JUWPIL5lNtjP7Jugqg,157 +lm_eval/tasks/bigbench/multiple_choice/unit_conversion.yaml,sha256=G3SfWayMJaPhnPHqs321podd7PCvOiD2DHN4SSyGB-Q,155 +lm_eval/tasks/bigbench/multiple_choice/unit_interpretation.yaml,sha256=YvgQpmd3xysm1jT6L6Z5N3112-rOUBgvPtAsBVjoP9M,163 +lm_eval/tasks/bigbench/multiple_choice/vitaminc_fact_verification.yaml,sha256=EddfpaELyTOg08nFs588kA8_bb-cBNG1Ri79yikT6Qs,177 +lm_eval/tasks/bigbench/multiple_choice/what_is_the_tao.yaml,sha256=WiBdWdOJGUpope3zL105XODUL7jLWBmQn1XSL_3BMeQ,155 +lm_eval/tasks/bigbench/multiple_choice/which_wiki_edit.yaml,sha256=JDis-pbaG_s_tNkIzVaA_vnOoAMyM4-hXU5gB36mZ48,155 +lm_eval/tasks/bigbench/multiple_choice/winowhy.yaml,sha256=YFSzF8hN6bcQfrqslKTIxYLCE3p2Y_pZVxPPObc5Qsg,139 +lm_eval/tasks/bigbench/multiple_choice_template_a_yaml,sha256=FzCXorb-KeOHd18kMMnEf1wvIWhjWqMmfmtlIYJjFOw,502 +lm_eval/tasks/bigbench/multiple_choice_template_b_yaml,sha256=XiYJc4WiXLg1bjrucXOOx1kaeUZriufB2z52V9ifR1Q,492 +lm_eval/tasks/bigbench/push_bigbench_dataset.py,sha256=aEACeC1ySE9-GTRzKm4KK_NBP8_SqvlyVNreXy8q-bA,1036 +lm_eval/tasks/blimp/README.md,sha256=DWssG7sScoVaJep8XMGuh7q4ypM9m0evl9YzvnxgFeA,2920 +lm_eval/tasks/blimp/__pycache__/generate_configs.cpython-310.pyc,, +lm_eval/tasks/blimp/_template_yaml,sha256=HuzVLND1ZxXBKKgerkw-LwF7TbQRevwDaMwMzdWgnYI,333 +lm_eval/tasks/blimp/adjunct_island.yaml,sha256=-9lX4hPdterByJxKE5g0rKbduMM19WgtEMvblkzv68s,104 +lm_eval/tasks/blimp/anaphor_gender_agreement.yaml,sha256=YvC5NfoTfaIQ8YEYSXDsj3nUph38cVyV6V6j8zDmmrM,124 +lm_eval/tasks/blimp/anaphor_number_agreement.yaml,sha256=QZLYkO_7cmUYG0wJFBbXvoDAdgzEouIlWaw3WIlp85o,124 +lm_eval/tasks/blimp/animate_subject_passive.yaml,sha256=znBh6LPx2JsVMfGJro-hfKDSwKb6UEPuv0SJ7bxjAF0,122 +lm_eval/tasks/blimp/animate_subject_trans.yaml,sha256=NA59OdcPs1vcNK37AObFpIRusV4bXJAZWwgptFKWlxs,118 +lm_eval/tasks/blimp/causative.yaml,sha256=iOyrzoGsOaU7L1mRctjhuFVgxFma_Z8FIDana6GRP-U,94 +lm_eval/tasks/blimp/complex_NP_island.yaml,sha256=IJZMuZgeeJhBdE5fRK9JLkHv4-EFjRGIdZzOMlh6acE,110 +lm_eval/tasks/blimp/coordinate_structure_constraint_complex_left_branch.yaml,sha256=3KHjSpHUgOlMknw6yyeuFcmq7Tr5Aj0BWhABRqBAXKI,178 +lm_eval/tasks/blimp/coordinate_structure_constraint_object_extraction.yaml,sha256=1utajR5vsWlwfMlxnAIh6g_ZWMerLWplnVa_91ZOOt8,174 +lm_eval/tasks/blimp/determiner_noun_agreement_1.yaml,sha256=Xozzid4qpRC2c2Y0G2CzQA4MwtC6lmAxWYzolnV1vyg,130 +lm_eval/tasks/blimp/determiner_noun_agreement_2.yaml,sha256=h3l_Nur4ofxlOCEKG74Ped29pgKrKGJ2EU06CR-W_ko,130 +lm_eval/tasks/blimp/determiner_noun_agreement_irregular_1.yaml,sha256=SaT-zTh8rDVb0lpIxKqDsvBaKGGtR2UtyzqE0n-ixuE,150 +lm_eval/tasks/blimp/determiner_noun_agreement_irregular_2.yaml,sha256=mkorgBYuduNOB-gTdMlNFAxV6N7dC7mjdtL3jcpaWmE,150 +lm_eval/tasks/blimp/determiner_noun_agreement_with_adj_2.yaml,sha256=RyuzjODaFGx-tpB4qsFUCp6LKxq23TQVpePCW8Qffys,148 +lm_eval/tasks/blimp/determiner_noun_agreement_with_adj_irregular_1.yaml,sha256=yhSMa2TUnNbcDabHYtIPdgbU34sbFrEW2_WxDXzzrcc,168 +lm_eval/tasks/blimp/determiner_noun_agreement_with_adj_irregular_2.yaml,sha256=dmUQWIxZnSKEGJgBxBMancfBTAjhp-5Fn6IiL3w1ci4,168 +lm_eval/tasks/blimp/determiner_noun_agreement_with_adjective_1.yaml,sha256=qO4si9QBuAvM1y0yGP9ZZo1YiQlBZljl2n8zKFh9VDE,160 +lm_eval/tasks/blimp/distractor_agreement_relational_noun.yaml,sha256=ZXy-qJ5fkMeqctJDqo2hJfsM-8usA9bneX7VWAvR1Ak,148 +lm_eval/tasks/blimp/distractor_agreement_relative_clause.yaml,sha256=aylJHRj3J50lqloD6TtbRWgTC8sMek7PlolhlQ2_wTs,148 +lm_eval/tasks/blimp/drop_argument.yaml,sha256=piUDj4gM9_dlopsxQB47CYpaFOV2Z6l3beZEScQqB38,102 +lm_eval/tasks/blimp/ellipsis_n_bar_1.yaml,sha256=pawDpZP85htkOT_Db2TRFP19neJP1xio404cYcFhzv8,108 +lm_eval/tasks/blimp/ellipsis_n_bar_2.yaml,sha256=OBAtmSx6TW2Rgo-zdqKNp6ZBhJPBOa8eODvTZb8Blmg,108 +lm_eval/tasks/blimp/existential_there_object_raising.yaml,sha256=f8wWYmAiqdEAKqIDcSCB2mj3CXRpz6Xx23tBw_YFmAk,140 +lm_eval/tasks/blimp/existential_there_quantifiers_1.yaml,sha256=0dCbp1jHm8zZrznnHDWb31ho8rDV4tnLR3Fm1uGUMFI,138 +lm_eval/tasks/blimp/existential_there_quantifiers_2.yaml,sha256=il9eevifcY7YXleFZtMPeT2aHM_0q_pmRrMX8Dnlvas,138 +lm_eval/tasks/blimp/existential_there_subject_raising.yaml,sha256=Pms6JBnODzdcBr0HkS9o7oMskk0Uxxl0Smz7y8iFnhg,142 +lm_eval/tasks/blimp/expletive_it_object_raising.yaml,sha256=DP15wYDN9C4ZZFBqz9TcnG89_GkmXm91YWFeueJGZ8g,130 +lm_eval/tasks/blimp/generate_configs.py,sha256=E8qhbk0Xz2IPgjbc7Tm7QM33JphFsmuqI7KkdR1fFjU,2901 +lm_eval/tasks/blimp/inchoative.yaml,sha256=DsMpj_a2yrOchFTmTXat0LGocDai5yEhefMj4mw11ug,96 +lm_eval/tasks/blimp/intransitive.yaml,sha256=S4KtS7drV5J2iqoe3TNXbJIM56m85KCXSTBeCLJModg,100 +lm_eval/tasks/blimp/irregular_past_participle_adjectives.yaml,sha256=gZhQpDK95j2qJotGRqg1JY5aRxDKMvABwpwLEHBHDvg,148 +lm_eval/tasks/blimp/irregular_past_participle_verbs.yaml,sha256=J7i1uPI1XRkOJ5J9fVDqkma-DBIVpTP4CQaPF9zNc6A,138 +lm_eval/tasks/blimp/irregular_plural_subject_verb_agreement_1.yaml,sha256=vkRRN_PpLhliyDbdjyrWP-Exo0IPvqbBxbV-gB-6u-Q,158 +lm_eval/tasks/blimp/irregular_plural_subject_verb_agreement_2.yaml,sha256=Dhce_QyhiMuLq5nYtEsg9f2U14a2lPM5gNoa_k1BZqU,158 +lm_eval/tasks/blimp/left_branch_island_echo_question.yaml,sha256=tmYr6gGH_W_bsTxfD0o8E0gm0lpPX_RouukysmN8PmE,140 +lm_eval/tasks/blimp/left_branch_island_simple_question.yaml,sha256=6fQOQ1Khq4c4r2FKjccNOzQq2nPfSWGEfWAY5ui5YZk,144 +lm_eval/tasks/blimp/matrix_question_npi_licensor_present.yaml,sha256=zgviPtzlA4t_e1I0uJHQWSIXoVxGCCYCbE9Q6ZJ8H0g,148 +lm_eval/tasks/blimp/npi_present_1.yaml,sha256=1lFMhXRmF1N-ZCRA71OieXn9dcaNWM0h1_tr9nf3dr8,102 +lm_eval/tasks/blimp/npi_present_2.yaml,sha256=hkelD4YT05hqNiBu6foSc8Ea6DBTVEZo6tA4_W6pn58,102 +lm_eval/tasks/blimp/only_npi_licensor_present.yaml,sha256=8exp0yKRSCPcD5AXBbURBTDI1FaCcpWTDP_SQNckXgA,126 +lm_eval/tasks/blimp/only_npi_scope.yaml,sha256=ByExTctp9xZmTtKrHCGJg70UY6yD2Kqpt1i95zIl1Xo,104 +lm_eval/tasks/blimp/passive_1.yaml,sha256=aVZXNP2pI2DzSfGuNtNLmWElXxdNPTAMCABV8Yb9Kvk,94 +lm_eval/tasks/blimp/passive_2.yaml,sha256=RSkmNYrndnY5tweYPxL1rvb7_IYJdBfs-QXQXHvpSuk,94 +lm_eval/tasks/blimp/principle_A_c_command.yaml,sha256=HNR2XQIRJfJlOn63103PmDnnUG2NY2iMuWPAB_tKoGU,118 +lm_eval/tasks/blimp/principle_A_case_1.yaml,sha256=2q4Zrc27iGDVaT7XilWvcJCzL3il8UILyEW6BW3-RMs,112 +lm_eval/tasks/blimp/principle_A_case_2.yaml,sha256=VgfFmGJ5ODxbAyga-hvWrH4ALajZ0CqY8S1yMF5dN6c,112 +lm_eval/tasks/blimp/principle_A_domain_1.yaml,sha256=wjWNm-2SkxOJpUf6XplZuY_lm45qNsAhEqf8gkw42cE,116 +lm_eval/tasks/blimp/principle_A_domain_2.yaml,sha256=I7-vj_eHLXL92Q5YyQg0tNkn6XfDwZQmYAcdxZ5jDUk,116 +lm_eval/tasks/blimp/principle_A_domain_3.yaml,sha256=N4NOk4-FYUrZe_yEB3QVpK10l5YTbVvAR8T2ZdZJbIY,116 +lm_eval/tasks/blimp/principle_A_reconstruction.yaml,sha256=kbgPw8WRvQgEw4nOx6lIahrJfiwQgeldg-_ubuyduKQ,128 +lm_eval/tasks/blimp/regular_plural_subject_verb_agreement_1.yaml,sha256=TRl_ZSGOzmoKj8aaps-3UoUH-E2CQTvHkT7oY8tvnp0,154 +lm_eval/tasks/blimp/regular_plural_subject_verb_agreement_2.yaml,sha256=El69s111tnlZ3PaVD8dJ_mnGyHkwfF1Lx1NRbegvyqc,154 +lm_eval/tasks/blimp/sentential_negation_npi_licensor_present.yaml,sha256=tlDP6oxHDRNT-DOlxqER7c16pMqjRiYtraonx0dhJSQ,156 +lm_eval/tasks/blimp/sentential_negation_npi_scope.yaml,sha256=ZA01-DgkD_XiH4_y4LEPTxID6yN6IB3ChXcVM3r-yeo,134 +lm_eval/tasks/blimp/sentential_subject_island.yaml,sha256=dWTwulV1S633yAhGuWGuyGttg3fkyYwMM2A_y8HxcKc,126 +lm_eval/tasks/blimp/superlative_quantifiers_1.yaml,sha256=faxiPYPbVCG3Jz-PRJoHlYl6EyhEEc-nprr29tV-3Cc,126 +lm_eval/tasks/blimp/superlative_quantifiers_2.yaml,sha256=WbMvowOM10KnngE6Nz5iS3f4A5hcEP01331m_m4JmGY,126 +lm_eval/tasks/blimp/tough_vs_raising_1.yaml,sha256=pK9Upq5umDCfVZWm8u0E2kxdYmEitsuAqO-5QD9tayc,112 +lm_eval/tasks/blimp/tough_vs_raising_2.yaml,sha256=7VeDbZkxEY8D9nwNymqOHotD8NkeTUibGkKJMSigWtQ,112 +lm_eval/tasks/blimp/transitive.yaml,sha256=cmejl92fLdcvqrpWR4oX-yLeWExMqtj1a-x0fKHtLwQ,96 +lm_eval/tasks/blimp/wh_island.yaml,sha256=jFAVoSJBhuKAfU8fs2kl4US-tFiZ03vnMXbNqYfdF0I,94 +lm_eval/tasks/blimp/wh_questions_object_gap.yaml,sha256=kOvup2GXc9GtfsI9i4wzF3_jbL043PeHWjSUWFi0hBE,122 +lm_eval/tasks/blimp/wh_questions_subject_gap.yaml,sha256=m3ybX6FgLO7SYEA-7iUyLOTRmXC3hpQpUmkvm620mrw,124 +lm_eval/tasks/blimp/wh_questions_subject_gap_long_distance.yaml,sha256=rFcVijVQW-IG_mpNmRNFo7QEEhRoQ5CNVfBGKuI8qnw,152 +lm_eval/tasks/blimp/wh_vs_that_no_gap.yaml,sha256=3Buk7jIKXy4e0c7JYjJ5Iknlobz-JjWQxuMFl-PjuqU,110 +lm_eval/tasks/blimp/wh_vs_that_no_gap_long_distance.yaml,sha256=RVfGHziEZb_v7um-wo72xZNeSt0VcN6FiODhSq9uxTI,138 +lm_eval/tasks/blimp/wh_vs_that_with_gap.yaml,sha256=MwnrjZ-CdZGyvAshYmken2hkNf97BhAXNY03rhu679A,114 +lm_eval/tasks/blimp/wh_vs_that_with_gap_long_distance.yaml,sha256=9gOjb25Zw6AtFaXwyyyo9xrapuN3PwBE-zcCZ4zdWbM,142 +lm_eval/tasks/ceval/README.md,sha256=UEX7W3AFO3-cM3UcL3yrLoO9C4ZsmiiD2cRzvCH6nys,4967 +lm_eval/tasks/ceval/__pycache__/_generate_configs.cpython-310.pyc,, +lm_eval/tasks/ceval/_default_ceval_yaml,sha256=N8KsT9uZ47QAPbySBgnlmYLGTPJxhbUNI7SC5Lyt66g,507 +lm_eval/tasks/ceval/_generate_configs.py,sha256=VAWaRvi4AUizONyqd2eIHtumoVWMW0R1XjHf_Q0oM6M,4375 +lm_eval/tasks/ceval/ceval-valid_accountant.yaml,sha256=r61lKl0DAH5ySKcDs7AwPvQl8JVUiHZfvzmJRmBiUX8,207 +lm_eval/tasks/ceval/ceval-valid_advanced_mathematics.yaml,sha256=TowvVz5_ZfK6yBmcAuqQ1T1uv9_PfeQ8bJen8NkRHrg,224 +lm_eval/tasks/ceval/ceval-valid_art_studies.yaml,sha256=kI7p4mk8_5oF4IEb9hAgy9LASGQIXRzzVp5Xar39Kis,203 +lm_eval/tasks/ceval/ceval-valid_basic_medicine.yaml,sha256=m2PzLxFzKXbYd4_2Ln2z7sxS25fVlw1GiuKYjnZ1Nt4,212 +lm_eval/tasks/ceval/ceval-valid_business_administration.yaml,sha256=tVyXVeOB5Mk_4WkGiY4FsVMb9GHWA0bXvK9VS22gTw8,230 +lm_eval/tasks/ceval/ceval-valid_chinese_language_and_literature.yaml,sha256=SAhX_ST3R3hSDvyVRoZMvTIDTLzAOR6IA4QHRkUjwvM,252 +lm_eval/tasks/ceval/ceval-valid_civil_servant.yaml,sha256=G_8m9RcD_aV7jJXAubW_1oq84RIbrUfyLZxxTcic_vE,207 +lm_eval/tasks/ceval/ceval-valid_clinical_medicine.yaml,sha256=0QikXTEvr3amDcUGl8DcfynOZj0Ll5hZRa1AhhHTXQ8,218 +lm_eval/tasks/ceval/ceval-valid_college_chemistry.yaml,sha256=0rhGE5axuBh5O4Z4aZRaOuQ0usiuTJd-CtAvKpxI9NE,218 +lm_eval/tasks/ceval/ceval-valid_college_economics.yaml,sha256=Y9xrtTT-BiinFOkkqI7nWi4GyB1bxiOHh6pRPff3-AQ,221 +lm_eval/tasks/ceval/ceval-valid_college_physics.yaml,sha256=JJfHph_isVStbsk2yIav4A5iqmLWNf1EAmCFOIUjk5Y,214 +lm_eval/tasks/ceval/ceval-valid_college_programming.yaml,sha256=FYNlc9mHqfoLCAdtjx3aiaPq-HuI0c2zNDQp8AaE6wo,222 +lm_eval/tasks/ceval/ceval-valid_computer_architecture.yaml,sha256=vGZ__iGOj0_nX7aVWX3qCDYrr2eEJ1mJj7k59NG3CTs,229 +lm_eval/tasks/ceval/ceval-valid_computer_network.yaml,sha256=gPMX8lN2YMGH9QYaKBEXProfP_MA9XV4Lx_udMr-ktQ,219 +lm_eval/tasks/ceval/ceval-valid_discrete_mathematics.yaml,sha256=a9wuabDadH9CgiyQc5uW1lld4vAeaJYv4mPTx5u-Ujg,224 +lm_eval/tasks/ceval/ceval-valid_education_science.yaml,sha256=KiFoKyLZHkaDYdWCAZ45k4K_GglR3MDJGheeHWDgSbM,215 +lm_eval/tasks/ceval/ceval-valid_electrical_engineer.yaml,sha256=DjZ62r5DtU_XIS1K-MUbQqbigXYd6YCQI7LBYdXhB8Y,231 +lm_eval/tasks/ceval/ceval-valid_environmental_impact_assessment_engineer.yaml,sha256=S-HPmH9da8gLu8lh_2YZ4XwV5Hog7JPJJEbxVkbd0Kk,279 +lm_eval/tasks/ceval/ceval-valid_fire_engineer.yaml,sha256=aTajwMc0EjalqD3Rx5O6BUX3slgolA8lxLSjF0NvDlE,219 +lm_eval/tasks/ceval/ceval-valid_high_school_biology.yaml,sha256=KMO3L-P6JFdCwkH5431YBOImX-oWGi6A9gmtvyCq-EU,222 +lm_eval/tasks/ceval/ceval-valid_high_school_chemistry.yaml,sha256=YdpYxhBFLDoKk9gz6UiZa6TBuqrdRH8FnZmG2NZiuL4,226 +lm_eval/tasks/ceval/ceval-valid_high_school_chinese.yaml,sha256=6L4ePI81IW_ssklfqriFt83X8vMZ4b0gm_oAkpDXkqA,222 +lm_eval/tasks/ceval/ceval-valid_high_school_geography.yaml,sha256=rPDd_fm_nqM530JAWLG7PmYyCFux3wOZf50gdZBBRVY,226 +lm_eval/tasks/ceval/ceval-valid_high_school_history.yaml,sha256=SEMX0dqEXZjsvTn1JP_3ECBZ0M56I4WBKFbw0XWI8No,222 +lm_eval/tasks/ceval/ceval-valid_high_school_mathematics.yaml,sha256=j45jE6-jfXFcdkLZFY2jPwexDnqiBkqilwC9a5vsM04,230 +lm_eval/tasks/ceval/ceval-valid_high_school_physics.yaml,sha256=lTuM6LCjO9SlruoHX3xepebj46l_0ZK_N5l5HZmys6A,222 +lm_eval/tasks/ceval/ceval-valid_high_school_politics.yaml,sha256=T6HS-hthajC2NJi5NFKkD0XDxmXmKHCNuhBbhntddpU,224 +lm_eval/tasks/ceval/ceval-valid_ideological_and_moral_cultivation.yaml,sha256=hmHJ5O9v3iXt-j8xHO7UeCMWE6A6FB-dciyljq9xSqM,271 +lm_eval/tasks/ceval/ceval-valid_law.yaml,sha256=QmrSRhjMC5K7OQDTz2_r52HJVZWWv4xjrptwmY5NKzA,184 +lm_eval/tasks/ceval/ceval-valid_legal_professional.yaml,sha256=rQMWxpcWt2Y1bhoSgaUP5US4OXVbPvTSxvU_J90dwHk,226 +lm_eval/tasks/ceval/ceval-valid_logic.yaml,sha256=mnuTRJO3tYKeySn2n3B-92InjPvz3t0mhf-UaKGcHgI,191 +lm_eval/tasks/ceval/ceval-valid_mao_zedong_thought.yaml,sha256=z4BrjRmSCh96ieu9MCmc9J-vy0PnBdxKYO7Q8lUjenc,268 +lm_eval/tasks/ceval/ceval-valid_marxism.yaml,sha256=3KjhPFk4w9kpVzl1WD9Va4EOAkux32iBqrfQ1UIP9s8,213 +lm_eval/tasks/ceval/ceval-valid_metrology_engineer.yaml,sha256=YqiCDiJ4bphneVAIjweU5Qqc4uck_s_iuIzMT9HF_kQ,223 +lm_eval/tasks/ceval/ceval-valid_middle_school_biology.yaml,sha256=Ic-e39wEVx6NScOoCbkA7dciQ-Y2wt0QFmN0kWVTVEk,226 +lm_eval/tasks/ceval/ceval-valid_middle_school_chemistry.yaml,sha256=CJ6HyS-6Nlcp-wi0yb74zdqUPL_zQWdTf9oTYQcCGO4,230 +lm_eval/tasks/ceval/ceval-valid_middle_school_geography.yaml,sha256=Yh1mxAbsNan6WY4sH8eN5EI-oLw8psQ5PmGO1ZX-ZrU,230 +lm_eval/tasks/ceval/ceval-valid_middle_school_history.yaml,sha256=ckDHEb5npvsq2mdt4ICfkbk0eTlcZxHWlGJXax-1aIY,226 +lm_eval/tasks/ceval/ceval-valid_middle_school_mathematics.yaml,sha256=Mtt8szOofgOabzBBVLIPV67b7sDEECndzOAz057qlJs,234 +lm_eval/tasks/ceval/ceval-valid_middle_school_physics.yaml,sha256=oue8rUCV8h0MP0gx5emFPTOreBh6FSNhqNi_HEJtvW8,226 +lm_eval/tasks/ceval/ceval-valid_middle_school_politics.yaml,sha256=pKqoZ560D8p0sJ6sEBanLv_ybuppFpvd8f-IYRCVl50,228 +lm_eval/tasks/ceval/ceval-valid_modern_chinese_history.yaml,sha256=ISjUEGRMxv2nQGf50IbxoQEMA4hLHUchXO5wWT_ams8,231 +lm_eval/tasks/ceval/ceval-valid_operating_system.yaml,sha256=1r9lC8brpfqm4D1lX1_0avgSZXwAm3xq48WtLYxtCxE,216 +lm_eval/tasks/ceval/ceval-valid_physician.yaml,sha256=JV3vjt37Cmnv0fGCQzjpvCxGljASNTJQj3fO8Xt0WY4,202 +lm_eval/tasks/ceval/ceval-valid_plant_protection.yaml,sha256=XxzSPV-7R2X6nOiqWM_PhKeMtIT9WOwVvkNCc71KZNM,216 +lm_eval/tasks/ceval/ceval-valid_probability_and_statistics.yaml,sha256=Dm-WFp5dusbxLucUCEqRkmcbgIGnNjYoMXsmYbYJ5UY,236 +lm_eval/tasks/ceval/ceval-valid_professional_tour_guide.yaml,sha256=LMS9fyh7Zmt8grr4CBQGccGHPAKuj0RZAj3XQGzmyl0,230 +lm_eval/tasks/ceval/ceval-valid_sports_science.yaml,sha256=6rgkkmJCxopoPNedAkIhWVpGzhdcB4ztYO0EmUk_9rc,209 +lm_eval/tasks/ceval/ceval-valid_tax_accountant.yaml,sha256=dHhlfeqH_HUlTkKbWzOJNaYXzAE1c9FWejT_3XBiGhU,209 +lm_eval/tasks/ceval/ceval-valid_teacher_qualification.yaml,sha256=msYhw4RmvIXosDstJVb1l7wUs_-hokMOFY1UFSTteHc,226 +lm_eval/tasks/ceval/ceval-valid_urban_and_rural_planner.yaml,sha256=lqXQXjQI4jxIQ3_iNIaTQE1CJ3OGg5UzEcL0NIiQRgs,239 +lm_eval/tasks/ceval/ceval-valid_veterinary_medicine.yaml,sha256=g9Ui3hPL64eumBGsuKUE1xgiCKFMFzt8hqbJ14pbu90,219 +lm_eval/tasks/cmmlu/README.md,sha256=gyA3hrGDwuWy4mtFMPgxWXleKApdjgbKmiiWi0t9CMk,1748 +lm_eval/tasks/cmmlu/__pycache__/_generate_configs.cpython-310.pyc,, +lm_eval/tasks/cmmlu/_default_template_yaml,sha256=Rap2Tp1bIJjwAJRLwTvRv4rzSYioPENv3PDqltoDZmQ,495 +lm_eval/tasks/cmmlu/_generate_configs.py,sha256=YRn7dUMf0-2nvgpOlm4SJPI_nBkwWgqNybMKoQclUzA,4773 +lm_eval/tasks/cmmlu/cmmlu_default_agronomy.yaml,sha256=DqvlHZ1g4sDq5lFUjDzk8Xu7LdpfOajsqgD5COLsnio,191 +lm_eval/tasks/cmmlu/cmmlu_default_anatomy.yaml,sha256=SKazmZTenePltXz5i7wj33uM-zwAjWTmKcd0ngzEjOM,192 +lm_eval/tasks/cmmlu/cmmlu_default_ancient_chinese.yaml,sha256=zQ5j11KOJ60Q0n3IJ2SNGFkx01I0Qy6p6i-RQTQC8_8,208 +lm_eval/tasks/cmmlu/cmmlu_default_arts.yaml,sha256=qNkb7UTvtgXF9JcHo8qSYW6O22tZgLSuPzvoklCL0zw,186 +lm_eval/tasks/cmmlu/cmmlu_default_astronomy.yaml,sha256=lgF3qfC_2bQc4NEklG6vnwmhy1GvfogpgRSYfoijulQ,196 +lm_eval/tasks/cmmlu/cmmlu_default_business_ethics.yaml,sha256=TdFBk1ool2z3ihnnk5LHraT6R_Feo_F_p5at9JT3HcY,211 +lm_eval/tasks/cmmlu/cmmlu_default_chinese_civil_service_exam.yaml,sha256=l7wFBEEn_BtahJVHQL6cI7azQeWSs3hX-2XdHX-CjhM,242 +lm_eval/tasks/cmmlu/cmmlu_default_chinese_driving_rule.yaml,sha256=0Uj-zYoT4yeQqOqBfIXi_IpYzyQPcHMCf1dS9ma2LKc,227 +lm_eval/tasks/cmmlu/cmmlu_default_chinese_food_culture.yaml,sha256=EMIfT1GJluls12hfxlmTgfNKevRuzV9XWkoGTzO0djI,227 +lm_eval/tasks/cmmlu/cmmlu_default_chinese_foreign_policy.yaml,sha256=1yuG2_1A9Oe4_o_Bl7uJKOv3Qfqv9r6JYAD1P6L3AHg,231 +lm_eval/tasks/cmmlu/cmmlu_default_chinese_history.yaml,sha256=vYox5jq9_vm04ClPytEiqluf8oiJ7Y2Yl8dwphd_ukY,211 +lm_eval/tasks/cmmlu/cmmlu_default_chinese_literature.yaml,sha256=6vFl0vmSFAeLBtcyn9utf7YGQMtiJEOjxR1XtmmeN7k,217 +lm_eval/tasks/cmmlu/cmmlu_default_chinese_teacher_qualification.yaml,sha256=Ofur5dABRspuog_bL39FTQcJ6cqSj3B1pjJTeparuPg,245 +lm_eval/tasks/cmmlu/cmmlu_default_clinical_knowledge.yaml,sha256=ReXbIW90A0BZ3NGOysUraRr1n4Ugto-Pl8z3CPPU4aA,217 +lm_eval/tasks/cmmlu/cmmlu_default_college_actuarial_science.yaml,sha256=vvVIOnXSEG-J9OcEFf4G3qGpGBRkfrKb8x1_oJrruK4,234 +lm_eval/tasks/cmmlu/cmmlu_default_college_education.yaml,sha256=9AUMkRL72eBk2UnWaDBtmgdrh0EQZait775LloIZq7M,218 +lm_eval/tasks/cmmlu/cmmlu_default_college_engineering_hydrology.yaml,sha256=HBihPhmNhTPj7_LSB939YL_o8zOI8vsuTXuEK8F2yd4,248 +lm_eval/tasks/cmmlu/cmmlu_default_college_law.yaml,sha256=FWe0m1K9JmnVTcfXW5Fbsv2tE3LGBfNhSxLXrVi4pSk,203 +lm_eval/tasks/cmmlu/cmmlu_default_college_mathematics.yaml,sha256=1os_um2HNCfbbRJYM6IKAG05I2_QsiSrmW9OaHLNGwo,219 +lm_eval/tasks/cmmlu/cmmlu_default_college_medical_statistics.yaml,sha256=z6LJZK45Tf9gj9LIx1TjjuaH8LACReSz43ObiNTvd0A,239 +lm_eval/tasks/cmmlu/cmmlu_default_college_medicine.yaml,sha256=iIQRLQfEx3ZCtcRqHE5Il1XDqjqaHaV8oAdM2ihWCC4,213 +lm_eval/tasks/cmmlu/cmmlu_default_computer_science.yaml,sha256=64z6rFtry_E0LS5opBBaBcHXzmOW1lg9Y1wh1lNx1Cg,216 +lm_eval/tasks/cmmlu/cmmlu_default_computer_security.yaml,sha256=iCYXgKnc8GpnHAwHPZq1-XbXzwZ9AlBuANlQ66Wj1Sc,218 +lm_eval/tasks/cmmlu/cmmlu_default_conceptual_physics.yaml,sha256=L_DkqkfoMI1kBneIXn9W3r-zZ7rG0bp_dceUOlqaVWU,220 +lm_eval/tasks/cmmlu/cmmlu_default_construction_project_management.yaml,sha256=1tMoBrlqts3rgxwRgVUu8tRR9td8S8_54LPZyOKRgZQ,249 +lm_eval/tasks/cmmlu/cmmlu_default_economics.yaml,sha256=bai4ZwJBfG7OAN_uSS-uajVt-HOrUw9nNwK4f9R53RI,196 +lm_eval/tasks/cmmlu/cmmlu_default_education.yaml,sha256=JHFLezPEuR8vINuJ7fiq5vrMMaWieyW3HXoWsdpOWnw,196 +lm_eval/tasks/cmmlu/cmmlu_default_electrical_engineering.yaml,sha256=pVHvc_MRieXI3ff7WJpKkQV1uaap3II7-BuzkAwrHiY,225 +lm_eval/tasks/cmmlu/cmmlu_default_elementary_chinese.yaml,sha256=P4jiuRXU5OqjvlpDkjFJHl4RLu7b5LaTmbGrmvseYMI,217 +lm_eval/tasks/cmmlu/cmmlu_default_elementary_commonsense.yaml,sha256=OlTYX9qyhhu4u5VYFDtUGEFicu-VPNLmNU1Juq8uO0w,225 +lm_eval/tasks/cmmlu/cmmlu_default_elementary_information_and_technology.yaml,sha256=hAPmn31ac7hFTFl283vhK1jPjJm5tv6VchLKQgb3yPs,261 +lm_eval/tasks/cmmlu/cmmlu_default_elementary_mathematics.yaml,sha256=D8ne6N6tJCsPzWqlF4qxy6oBgkmjb6Jqy5DKw-xJMnU,225 +lm_eval/tasks/cmmlu/cmmlu_default_ethnology.yaml,sha256=OhNfsDxIuIA7ADIMc2SYiWjMtEw_DehtcQSIbXTbxc4,196 +lm_eval/tasks/cmmlu/cmmlu_default_food_science.yaml,sha256=fItOTnSEaBqDxokXTmY62WJI8orHAo2EL6HHAA_6z8A,205 +lm_eval/tasks/cmmlu/cmmlu_default_genetics.yaml,sha256=TOWNyAd8uOc1NrZkjgDMuYBDKaW1Ft8xJRABwMZYenk,194 +lm_eval/tasks/cmmlu/cmmlu_default_global_facts.yaml,sha256=-jZNUBh1qBrRVz70BfV4WWjhDwS4jsH5G9yipyKDHfE,205 +lm_eval/tasks/cmmlu/cmmlu_default_high_school_biology.yaml,sha256=pX2-airA86ZU5pUjewxjdlcLs-9FWHUUUiAnzBubrwQ,219 +lm_eval/tasks/cmmlu/cmmlu_default_high_school_chemistry.yaml,sha256=Q1ZBG8Wp9ab96l19PRwod9Dll5skvlB96x2A1Jmnfc0,223 +lm_eval/tasks/cmmlu/cmmlu_default_high_school_geography.yaml,sha256=G0VrkoUMzKtEm1kzOuEwPdq2vtlkc0KMDMsEGF6t1ds,223 +lm_eval/tasks/cmmlu/cmmlu_default_high_school_mathematics.yaml,sha256=wB7tBE5a9SWghbkP6dRakza_3PpSt-wkmTrd0bQpUEc,227 +lm_eval/tasks/cmmlu/cmmlu_default_high_school_physics.yaml,sha256=-QcmeommiYmIqCYaLVsaars-u6VKnqzbIoaf7Uz3Tmg,222 +lm_eval/tasks/cmmlu/cmmlu_default_high_school_politics.yaml,sha256=kKjyp_zDx4tsAJkWmzBCqp6Ubx2hhriEl-PiI6GHRys,221 +lm_eval/tasks/cmmlu/cmmlu_default_human_sexuality.yaml,sha256=IB0QxIhbKjAmhT77CJqheViIVw-2sZ3_kWpeyDcFAOw,214 +lm_eval/tasks/cmmlu/cmmlu_default_international_law.yaml,sha256=9luncjc_o4MvJjIYSznbT4ljfGEkrQdiaxYRajAnREA,215 +lm_eval/tasks/cmmlu/cmmlu_default_journalism.yaml,sha256=Tzhv5LmPa9-RTrok-GBgGc3mag4AmPIUVJKYqhzA_-c,198 +lm_eval/tasks/cmmlu/cmmlu_default_jurisprudence.yaml,sha256=OVAiNRVJBAUmw7ON2CX1cP44BUv7TktZW0ufOC6Zgco,204 +lm_eval/tasks/cmmlu/cmmlu_default_legal_and_moral_basis.yaml,sha256=YbQTOpGYrKJr5TOKzEWrUl3FO6zQtu1pAwjGCnmPRik,232 +lm_eval/tasks/cmmlu/cmmlu_default_logical.yaml,sha256=4lpQg10BWCqLyepRgXn4fcazO9J6YKiZvoWhgRJTytw,192 +lm_eval/tasks/cmmlu/cmmlu_default_machine_learning.yaml,sha256=yTSdJ2qB6hVZ-I1M3V8IQshSThOugOI_2H3ECNdeoig,213 +lm_eval/tasks/cmmlu/cmmlu_default_management.yaml,sha256=xj0wH_La-bf_Ezx9mjmsbY07M4UdTXbkzCqGdnzJkRk,198 +lm_eval/tasks/cmmlu/cmmlu_default_marketing.yaml,sha256=l7ulx3Nr47Ai4-MwPSvr64j1cKF8hG0wpkUHNKVkuTU,199 +lm_eval/tasks/cmmlu/cmmlu_default_marxist_theory.yaml,sha256=d7XeZBoxxtzm9rf4WrjcChH5-RDT00XgITU9QJXKkBA,218 +lm_eval/tasks/cmmlu/cmmlu_default_modern_chinese.yaml,sha256=M2gRRZy54c8e6CeJu69yNAoP6c9NpDfSMlVyD_0pMvk,209 +lm_eval/tasks/cmmlu/cmmlu_default_nutrition.yaml,sha256=yLQYVLdRY1MUc4NaCidmrFlsDAWaBmI4tp9r3DLzjqY,196 +lm_eval/tasks/cmmlu/cmmlu_default_philosophy.yaml,sha256=IlGz2CINUIAzbvlLbnAbXOdNsxCyO2rmwSnwB9iqF_8,195 +lm_eval/tasks/cmmlu/cmmlu_default_professional_accounting.yaml,sha256=TgYE1xSlF2MBJW7fnisY7-dwcJlxTU-lKJDmf3nS5HA,227 +lm_eval/tasks/cmmlu/cmmlu_default_professional_law.yaml,sha256=S86GwVZZw3ilxfFvxpvZg5Rsl1sn-nUllYx5VFktinE,213 +lm_eval/tasks/cmmlu/cmmlu_default_professional_medicine.yaml,sha256=o9w1kA9-L1J72EuQ7V2kq1YhlUIS4ovXVhoQ44GLcbY,223 +lm_eval/tasks/cmmlu/cmmlu_default_professional_psychology.yaml,sha256=w5wE-YswhIPdQp1NWW2U09hYs3Rd64bvb6ZGupYucTk,230 +lm_eval/tasks/cmmlu/cmmlu_default_public_relations.yaml,sha256=jblBswd7hMbPfweUa-5hVEp43oNF24v4MeWRuea8Q3U,213 +lm_eval/tasks/cmmlu/cmmlu_default_security_study.yaml,sha256=CFKa_RoDtHDkHrXyyS9FNp_HI6vGCV7XaogP2cjVHyk,209 +lm_eval/tasks/cmmlu/cmmlu_default_sociology.yaml,sha256=Qzr4AiRoyPHtIISXvBN8_XAXltIO9GdMYr7xYXk9Atc,196 +lm_eval/tasks/cmmlu/cmmlu_default_sports_science.yaml,sha256=wD1eTg1JgFg-rnglXDDM--owRRq94g6st7GA3zZiXkA,206 +lm_eval/tasks/cmmlu/cmmlu_default_traditional_chinese_medicine.yaml,sha256=fs7VxHpIsAqdW52e-ffc6ClIdomsVPGzQKyiuGTTNs8,237 +lm_eval/tasks/cmmlu/cmmlu_default_virology.yaml,sha256=aB_oTbDjh76nGH9rIkNhcbygJJkmckEBj7ehe_BVSd4,194 +lm_eval/tasks/cmmlu/cmmlu_default_world_history.yaml,sha256=AWCZJjmwhJobrzPCUpNRKh5F_ieCDWuhQv4H6uq0mZA,207 +lm_eval/tasks/cmmlu/cmmlu_default_world_religions.yaml,sha256=v39HzwxSXp2xo5Ap_Ig1sGcdT0XkiDKRBsiPnI7J05I,211 +lm_eval/tasks/code_x_glue/code-text/__pycache__/bleu.cpython-310.pyc,, +lm_eval/tasks/code_x_glue/code-text/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/code_x_glue/code-text/bleu.py,sha256=bGCIK_eVzN92SnXvFXZEt9YpAntvpUcCegANXFD8vqY,7847 +lm_eval/tasks/code_x_glue/code-text/go.yaml,sha256=E69gjwTkkc9b2iYg-9KGJuItUb9UaOI8gzuKUHdTBf8,479 +lm_eval/tasks/code_x_glue/code-text/java.yaml,sha256=HhXKmCgWkp9O7nsI2O-glQsbzDjfsZNSL8Vf-ID1NgQ,483 +lm_eval/tasks/code_x_glue/code-text/javascript.yaml,sha256=L3brOBtKJTNeJFUQUw_-N6Q8S1M_aQ0aCfo9ydwt7qw,495 +lm_eval/tasks/code_x_glue/code-text/php.yaml,sha256=relg83ds1g2wf5x0euX8YqLKc_Y_XaYviH2e8stCnrg,481 +lm_eval/tasks/code_x_glue/code-text/python.yaml,sha256=-5ipicnQUBTH2fUZG3jZ1XjAX0ue6K2HIY_d_5AS5QM,487 +lm_eval/tasks/code_x_glue/code-text/ruby.yaml,sha256=dqAtzuKflJGBo09goRL2SgTkD1wRbBhLRyhu6wr6c50,483 +lm_eval/tasks/code_x_glue/code-text/utils.py,sha256=Bt0SAZ8OruKLYiMCZUo1pTVRso-79yd7Lg5mNwzquko,308 +lm_eval/tasks/commonsense_qa/README.md,sha256=9M8niAKAi6d5ZbIVXes_IeBtOAhcJnt6s-WZLIh3Sik,2146 +lm_eval/tasks/commonsense_qa/default.yaml,sha256=YWma7G6VxxlXa6CnTAWsS0bAGvoHD5AtXE13MqhqVZs,470 +lm_eval/tasks/copal_id/README.md,sha256=niSqt6wrwVAFCgY8Bqtu3kwQQ77m4GJWNpeBqvTB3n8,1852 +lm_eval/tasks/copal_id/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/copal_id/colloquial.yaml,sha256=BJ72m5zcs-x9jDMgikbKhNmLpdrsJKWV8C8LGwhqX_w,100 +lm_eval/tasks/copal_id/standard.yaml,sha256=fvJKxfbiibxfeepjp9jiOXPECzvTjz5O356ZqGltAXg,316 +lm_eval/tasks/copal_id/utils.py,sha256=eNtnPfhq-fbtwqUIwmKzAD8WyTE3pqCFW566jHzNj10,452 +lm_eval/tasks/coqa/README.md,sha256=LF6N0XSwsg6DLYACWr5FJca7bRlUYib00tGPHNiSzg0,1262 +lm_eval/tasks/coqa/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/coqa/default.yaml,sha256=A6Nt3Thu3Q4OZjo8epOvC8rcTyU6Mb3nqhgmFInbs5o,608 +lm_eval/tasks/coqa/utils.py,sha256=YqyC6AJxYtE0cJNVoAUm_1SX3rWYe-67GLQ5syDoYMo,2835 +lm_eval/tasks/crows_pairs/README.md,sha256=HesNVCLZST9DTRBTjxbAOIwzKG9UGaR9CuPVIrQUz3I,6562 +lm_eval/tasks/crows_pairs/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/crows_pairs/crows_pairs_english.yaml,sha256=sLUaumY4JkiF3Xq31Ne_o0QorGaiasSYUMWMwVbYeNk,550 +lm_eval/tasks/crows_pairs/crows_pairs_english_age.yaml,sha256=g15ncf9B-uj8jpnGspHMF_tkTgytHxTFDEQheq-r5jE,127 +lm_eval/tasks/crows_pairs/crows_pairs_english_autre.yaml,sha256=-ZVZSt0RkemIKAHx-qM_Zf6WYphWFbtpKFTZqN4zer8,131 +lm_eval/tasks/crows_pairs/crows_pairs_english_disability.yaml,sha256=FDuoBS89Bt4XnXT1qO4G3AKaLzRtjUr9ty_essY5ms4,141 +lm_eval/tasks/crows_pairs/crows_pairs_english_gender.yaml,sha256=Jp_bpHin0LDl4Oh_5dw7DsnPIdw27_L7IvCSlt5-soc,133 +lm_eval/tasks/crows_pairs/crows_pairs_english_nationality.yaml,sha256=Xq_gMqx84YOsPB85t-mg-WowqOC9wGZAjti5s1vxZEE,143 +lm_eval/tasks/crows_pairs/crows_pairs_english_physical_appearance.yaml,sha256=rHxnfaefCxo-yW1nSA6odWsGWM1nuZ4qO7mY0_U3akY,150 +lm_eval/tasks/crows_pairs/crows_pairs_english_race_color.yaml,sha256=1TcaZQ2Vq0XQPalvOSvlpKZ43gzWOJ2_cwokusrppt0,141 +lm_eval/tasks/crows_pairs/crows_pairs_english_religion.yaml,sha256=TL4EheFGZbH1g13jyDFTx83tcLFoGijbuxv34HuCp8s,137 +lm_eval/tasks/crows_pairs/crows_pairs_english_sexual_orientation.yaml,sha256=fkwnSl7AJI3zbmuWD2lWGOE7tiuRumRN1uINS0QI-d4,150 +lm_eval/tasks/crows_pairs/crows_pairs_english_socioeconomic.yaml,sha256=uDwc7LsQC_Ws-4PsFQ8tc5vDkU98PxGzg4xz012Zi7w,139 +lm_eval/tasks/crows_pairs/crows_pairs_french.yaml,sha256=fz9gbMutyCHqm_OKj0xqqkr0Z3b3DLbQa54fAPAZ-dE,80 +lm_eval/tasks/crows_pairs/crows_pairs_french_age.yaml,sha256=p5WCzdbPIkilp8qG0fZGWG3dHjKr7ynX6PUP5GAWsN4,125 +lm_eval/tasks/crows_pairs/crows_pairs_french_autre.yaml,sha256=nWk1CtmS4rPNxHuhp4fq4_r8MXmjO0PZUes6Cl5kW7E,129 +lm_eval/tasks/crows_pairs/crows_pairs_french_disability.yaml,sha256=JHuqbu8Z8VflYRzJF2KnYGdIshBae9AmYptl84dW_wU,139 +lm_eval/tasks/crows_pairs/crows_pairs_french_gender.yaml,sha256=I9YDvpOnQXTMWOH1smjEs1nDiDeQP3Emq-XN2SUfWQ0,131 +lm_eval/tasks/crows_pairs/crows_pairs_french_nationality.yaml,sha256=ViElfWF8v9_JzWlhqosZtkA1WEuYCqwl__1eM0bByAg,141 +lm_eval/tasks/crows_pairs/crows_pairs_french_physical_appearance.yaml,sha256=Hv8VGBgSbJRy7ituauUmgxxFc3aPMJiwPLEDuk1W4L4,148 +lm_eval/tasks/crows_pairs/crows_pairs_french_race_color.yaml,sha256=WIbsZhtI3CTC1tYI0QuVtHRatNinqWWVbEhCFqadzLg,139 +lm_eval/tasks/crows_pairs/crows_pairs_french_religion.yaml,sha256=n19G-AGyzTMp8dPGUcS-1TuCs90O9vR1np7oxn9RzhM,135 +lm_eval/tasks/crows_pairs/crows_pairs_french_sexual_orientation.yaml,sha256=zg4UOJEM1CnKu933_I8NXpyM3pADeihBpMFOjrsWKpA,148 +lm_eval/tasks/crows_pairs/crows_pairs_french_socioeconomic.yaml,sha256=N5rktYPTmeZkQDPZw6mGZL5GhBdmyE9hkxtd__lh8GA,137 +lm_eval/tasks/crows_pairs/utils.py,sha256=Wx48MYgKgqn-kHLhTtsV_-FD0Ik53l0X_qF8LcL-DBY,1892 +lm_eval/tasks/csatqa/__pycache__/_generate_configs.cpython-310.pyc,, +lm_eval/tasks/csatqa/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/csatqa/_default_csatqa_yaml,sha256=ZNaxMJHOhxOemhEyAVIzssgSpG-QbbTMEFflNFO4mIs,391 +lm_eval/tasks/csatqa/_generate_configs.py,sha256=hqegQrMDd-TgreKRnOPt380AQXF4_nSY_Btn3ALxUEI,1474 +lm_eval/tasks/csatqa/csatqa_gr.yaml,sha256=WfwUoa2uX8gOjaQfcVDUvVSVkWCmbJBjiv7KBpjHZ5w,75 +lm_eval/tasks/csatqa/csatqa_li.yaml,sha256=ZRwynLR8BVgxgFcSDTLi_WoHpkYAtmG6iJhLhr8KUFQ,75 +lm_eval/tasks/csatqa/csatqa_rch.yaml,sha256=hciObdoI5LBjMc0eM3fFX3fc-uKpuIIt-02-0-5K5Q8,77 +lm_eval/tasks/csatqa/csatqa_rcs.yaml,sha256=8bSnj6bbts-sRbYrXpzM7OITuxED7VuIMiUzzo9xMPY,77 +lm_eval/tasks/csatqa/csatqa_rcss.yaml,sha256=-GoC4clrkSwJLOFkxa6TOEwin1PeTaKfy-Qw6BpHogc,79 +lm_eval/tasks/csatqa/csatqa_wr.yaml,sha256=ovjDaNGHTq38vQ3RROv4ppR09nQyVN6RMEsGimHfiL8,75 +lm_eval/tasks/csatqa/utils.py,sha256=thFD-3JzYceDfR055-F6NhjxFLaEoAxF3b6E4ehwea4,662 +lm_eval/tasks/drop/README.md,sha256=_fto2NjX5LFKc6jv6Ip5dM7V-viFzt8sGlqcxBM7OJI,1857 +lm_eval/tasks/drop/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/drop/default.yaml,sha256=6TeO_wLpoHxT0RnHTCO0xz9uL0kARdyViBqfKxPv5kA,642 +lm_eval/tasks/drop/utils.py,sha256=AuyxjM40-P0M6opJZiUULGlJE_ENhFK6uDgET-Uaeu8,5987 +lm_eval/tasks/eq_bench/README.md,sha256=vpylXqkMwXtH6NJGdUdUbLC8sVvJdKVpyX429VGSw_s,2949 +lm_eval/tasks/eq_bench/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/eq_bench/default.yaml,sha256=gyqAyRs1TvPTujpuD8dn7-4DpzU4GHvn8IYohMEVn6I,487 +lm_eval/tasks/eq_bench/utils.py,sha256=i-LCI-BP46h-3DtniEDg3-l34M__xS91VHWb4JhAz2I,2323 +lm_eval/tasks/eus_exams/README.md,sha256=gIgusYYxvirKSJJkTzXa6jmLVZBDC4_f-BvWh2vUkFk,2151 +lm_eval/tasks/eus_exams/__pycache__/configs.cpython-310.pyc,, +lm_eval/tasks/eus_exams/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/eus_exams/configs.py,sha256=jaHziD9b7i4oxSh6W4tK0T4adyLCAbE_gF3bvtACqMc,2004 +lm_eval/tasks/eus_exams/eus_exams,sha256=cVr9liNHmHBIJH83e_oIbLTIl2I_lYw3BTjJ9IXl1-4,410 +lm_eval/tasks/eus_exams/eus_exams_es,sha256=1NyG0KWCawvBUa0JM6vYUyhjHXbm97OiHK4oHFcO_Go,181 +lm_eval/tasks/eus_exams/eus_exams_es_ejadministrativo.yaml,sha256=FGLd6YWp89s4OXUYyaDGUwhXNnSBBcNi__rYyzPpK3M,116 +lm_eval/tasks/eus_exams/eus_exams_es_ejauxiliar.yaml,sha256=qjBsqxUCWnG9oI-Beazv8m6rEIZSH9mqHDZ3OLWyQGI,104 +lm_eval/tasks/eus_exams/eus_exams_es_ejsubalterno.yaml,sha256=NFHx9-GZLIMYO-W69O_J3g9RhxZz1wwQU723-PLqn7I,108 +lm_eval/tasks/eus_exams/eus_exams_es_ejtecnico.yaml,sha256=4i_gAR-ooQMz5Jx-5dR2n2LWRGXUkdMezNZYkqC6ee0,102 +lm_eval/tasks/eus_exams/eus_exams_es_opeayuntamientovitoria.yaml,sha256=4H0NC8Oak2_qx1rXe87UBJ2EUqZ9VpSSeHwtUiBOswA,128 +lm_eval/tasks/eus_exams/eus_exams_es_opebilbao.yaml,sha256=6_UHrRIRmqol-1FYXo34vIhIqjbEeg_K2VeK0qs38WE,102 +lm_eval/tasks/eus_exams/eus_exams_es_opeehuadmin.yaml,sha256=oGeI4ih0D543qxh_1n-ozgL38MinAZgyfs7JnNQGCAY,106 +lm_eval/tasks/eus_exams/eus_exams_es_opeehuaux.yaml,sha256=Jabv6Uoe-V9vDs2RStmHOttjn3Et5az5XrXAtyUytnA,102 +lm_eval/tasks/eus_exams/eus_exams_es_opeehubiblio.yaml,sha256=bPRjmTXtEF2108N43bWGH4RKAhfY8obSRa40_GDcIjc,108 +lm_eval/tasks/eus_exams/eus_exams_es_opeehuderecho.yaml,sha256=U4n6rtkCbqdDkLG4AcYdegadngGvBlpoL1Mkx-EX7A8,110 +lm_eval/tasks/eus_exams/eus_exams_es_opeehueconomicas.yaml,sha256=FhSNP3K5bzkQdUhUWFfODPD0emfWaz8mbhOnAnEpSSQ,116 +lm_eval/tasks/eus_exams/eus_exams_es_opeehuempresariales.yaml,sha256=U6o2Ylc6Roklt9Yj25JR_XzNAeaOWUwilDzFS91TitA,122 +lm_eval/tasks/eus_exams/eus_exams_es_opeehusubalterno.yaml,sha256=51Xs3sKf_ZvdbdjYzFrBxZFHpW8Cgce0Prt5wjIs6Hk,116 +lm_eval/tasks/eus_exams/eus_exams_es_opeehutecnico.yaml,sha256=J57Vlc90EfKq2RJL67qv8jlVFuFghPNgThLguCUBCpw,110 +lm_eval/tasks/eus_exams/eus_exams_es_opeehutecnicob.yaml,sha256=kr29Gx7hKHL_gw6-PO53DXjOuwCQpgs0HQax9ETbK7o,112 +lm_eval/tasks/eus_exams/eus_exams_es_opeosakiadmin.yaml,sha256=znh4cW9iWPUSZEhbJN7jjeF4cNaKGNpChDJWrQNQu7g,110 +lm_eval/tasks/eus_exams/eus_exams_es_opeosakiaux.yaml,sha256=q-BJLo4ky3QJofaQAGp6vNc4T5B1vSxdk2Xek4JgR6g,106 +lm_eval/tasks/eus_exams/eus_exams_es_opeosakiauxenf.yaml,sha256=wzwZJNqwjXQ6vrKINhJyJ6N3JYSvFmK1dMh7BDSznNk,112 +lm_eval/tasks/eus_exams/eus_exams_es_opeosakicelador.yaml,sha256=X0_coPJcB0siuikqSAE8TBDRo7pnf7B9ziWjmGzR1Eo,114 +lm_eval/tasks/eus_exams/eus_exams_es_opeosakienf.yaml,sha256=kwvHgkLEaheV14-gdyyvOXtirAkUH8lKcD0Nas9YU1Q,106 +lm_eval/tasks/eus_exams/eus_exams_es_opeosakijuridico.yaml,sha256=0V1fwD5Ufzm1PvxC9dJ3VuAaThdqwcpu7MOXvI-9R-E,116 +lm_eval/tasks/eus_exams/eus_exams_es_opeosakioperario.yaml,sha256=_3beVE-h5orQTYerOMLX2weJiIgJ46fN4R4Z7ubu_U8,116 +lm_eval/tasks/eus_exams/eus_exams_es_opeosakitecnico.yaml,sha256=KOgl6R0VBgpNM5-NllltzwgAy99h84sWovPxreZWTmc,114 +lm_eval/tasks/eus_exams/eus_exams_es_opeosakivarios.yaml,sha256=5Lwb7f992UyqwMKYUV12QGOPLEaAWGhfb-orfTSNfvY,112 +lm_eval/tasks/eus_exams/eus_exams_es_osakidetza1c.yaml,sha256=r5EfGNXWQDqG11ioY9Cy6Jm2qiGNs0_ecSQjHITdNaA,108 +lm_eval/tasks/eus_exams/eus_exams_es_osakidetza2c.yaml,sha256=Mqh2UsoX3wG4Kq86lqJEclti_rqfBA7z3Js1CpVQxxI,108 +lm_eval/tasks/eus_exams/eus_exams_es_osakidetza3c.yaml,sha256=YildUhgkV1QAmD6dOBWipxIHkA8qm6WOwT7WahqIuZo,108 +lm_eval/tasks/eus_exams/eus_exams_es_osakidetza4c.yaml,sha256=TzQnbR7Sfm4x321ZE8ikLfUeezlAiiCLRiVFA4_NeP4,108 +lm_eval/tasks/eus_exams/eus_exams_es_osakidetza5c.yaml,sha256=u66Lvh8RC9JYGG-Mh5-tcr-WTbTNcp8G3DjZ9aFX0uM,108 +lm_eval/tasks/eus_exams/eus_exams_es_osakidetza6c.yaml,sha256=Wla_YRMJFK4mE6XxN16Ah7lzt1BW6zhrscdStmhE47A,108 +lm_eval/tasks/eus_exams/eus_exams_es_osakidetza7c.yaml,sha256=A_ACvgNacPAjGFNdrA1N0dU6RQ-RF0zLGclhpHm_0CE,108 +lm_eval/tasks/eus_exams/eus_exams_es_osakidetza8c.yaml,sha256=30vpLNVuHLi3GLvw-s5wq0V2O9oyOxAWI6KZ_MvuQgc,108 +lm_eval/tasks/eus_exams/eus_exams_es_osakidetza9c.yaml,sha256=bIKbanb9WOUHE1QpsJUfJERjoyCpYgiN0f-jtZ5W49E,108 +lm_eval/tasks/eus_exams/eus_exams_eu,sha256=_hCCtSKDgYpHJZ_lJIlk8GOcEjBRaZoa9YEONu-Gni8,180 +lm_eval/tasks/eus_exams/eus_exams_eu_ejadministrari.yaml,sha256=trWpoOs9FlMiA5ga2WQ8zOWlz3XJ6nRPp6y_p2lcHZA,112 +lm_eval/tasks/eus_exams/eus_exams_eu_ejlaguntza.yaml,sha256=NbLCdRfVrJVPsBqNjQGLL6cK29OPT0lSn8HH8t89-0E,104 +lm_eval/tasks/eus_exams/eus_exams_eu_ejlaguntzaile.yaml,sha256=O70QFlIWkdw86aqkBpN_wEmKSfMvJjOAnq-vRd4i8cE,110 +lm_eval/tasks/eus_exams/eus_exams_eu_ejteknikari.yaml,sha256=YGNf1ZkkymXcRcs3sYA_WDXHWG4PD3Eg0YEBRmn_y0Y,106 +lm_eval/tasks/eus_exams/eus_exams_eu_opebilbaoeu.yaml,sha256=EF6w693Zc2MMKQXrYE_GWakgmyCPHjfR3YiZOw7EheA,106 +lm_eval/tasks/eus_exams/eus_exams_eu_opeehuadmineu.yaml,sha256=DLNB9i0ZBeIeUXFGjt03Qs78rSJO-2WUgPVSs0v8zW0,110 +lm_eval/tasks/eus_exams/eus_exams_eu_opeehuauxeu.yaml,sha256=_fvipWi0insIdcZJe-I8wg-mUF0cQgn7gb-1CFVlufE,106 +lm_eval/tasks/eus_exams/eus_exams_eu_opeehubiblioeu.yaml,sha256=FlXS6YsbYLz5zuHBOjfyDwOj_JDaOD4Tegq1U_nnzc0,112 +lm_eval/tasks/eus_exams/eus_exams_eu_opeehuderechoeu.yaml,sha256=a9-OoE0RYc3dXfA42KyZNPnIDVJUB2M_RbK4m5pSpwQ,114 +lm_eval/tasks/eus_exams/eus_exams_eu_opeehueconomicaseu.yaml,sha256=tWwFXmOf4a6IKTdPugibiop0_f_JhEd1bu9xo5lRmVY,120 +lm_eval/tasks/eus_exams/eus_exams_eu_opeehuempresarialeseu.yaml,sha256=usBM8ThgUYyOiaGVsR2oVdeR_CydeYXua4mFvwRpIUg,126 +lm_eval/tasks/eus_exams/eus_exams_eu_opeehusubalternoeu.yaml,sha256=TwuwDnJ-TLxuRRNez0Lc-CdAPBBg-4dbKVkbd0o15gY,120 +lm_eval/tasks/eus_exams/eus_exams_eu_opeehutecnicoeu.yaml,sha256=r7vK0mqXUkMZlwr5vg9C61FvDGaMhDyCQrT3s8Wc2m4,114 +lm_eval/tasks/eus_exams/eus_exams_eu_opeehuteknikarib.yaml,sha256=YmIslkrYNUe55m_p5yhHexyzvo2qX-rE7GJxAgjGzv8,116 +lm_eval/tasks/eus_exams/eus_exams_eu_opegasteizkoudala.yaml,sha256=rsweOUDIarxT-VAgDdcOViAc0snCMUqqo_mOdFEuLUg,118 +lm_eval/tasks/eus_exams/eus_exams_eu_opeosakiadmineu.yaml,sha256=gM6KOcn_xtq2TNxbGKYjrQ_wFy7jPyK9j77NOAXq2yo,114 +lm_eval/tasks/eus_exams/eus_exams_eu_opeosakiauxenfeu.yaml,sha256=tL4nNMty2-jozLBU3vStzyV1gjNT8bBzLovTZtC7bJ8,116 +lm_eval/tasks/eus_exams/eus_exams_eu_opeosakiauxeu.yaml,sha256=JN2JzAb54Q6wjoSd0ueYyJRT8lGmIlNs0YV8fMx0nf8,110 +lm_eval/tasks/eus_exams/eus_exams_eu_opeosakiceladoreu.yaml,sha256=AGCGZFIGDvX5Hd7T0fjRyFbthVKthPyg25XYUkyFRt0,118 +lm_eval/tasks/eus_exams/eus_exams_eu_opeosakienfeu.yaml,sha256=jRoG92xUAJAXiGfva7knQDx_6uqXYmKIXu9ND5EGmsA,110 +lm_eval/tasks/eus_exams/eus_exams_eu_opeosakioperarioeu.yaml,sha256=lZMbZTBQXx2lznqaCBIf_jFN81ipCtqoijbclOKhwn4,120 +lm_eval/tasks/eus_exams/eus_exams_eu_opeosakitecnicoeu.yaml,sha256=k-PQe3GZGJ7Qzd_5rFiKuVDogQaFaE10Zf6kFn_qvho,118 +lm_eval/tasks/eus_exams/eus_exams_eu_opeosakivarioseu.yaml,sha256=uqmZ_a_d8QEQ-AkbloWPYwCU3I_M5iTorJzZrMazOs4,116 +lm_eval/tasks/eus_exams/eus_exams_eu_osakidetza1e.yaml,sha256=emk099n88rG4js5jPDmrZceKZV8GOQsIjeYNJaiZEgY,108 +lm_eval/tasks/eus_exams/eus_exams_eu_osakidetza2e.yaml,sha256=1u_CutwLEvJU_PKe2m1CJGOg0gt9kcVfIIvDJkaAz2k,108 +lm_eval/tasks/eus_exams/eus_exams_eu_osakidetza3e.yaml,sha256=UMmBg4l1z2McA7SztaJLYRxs5csfnhZzf1Gu_oFNImo,108 +lm_eval/tasks/eus_exams/eus_exams_eu_osakidetza5e.yaml,sha256=GXC43RE1W-6D5ESC6sE33sZxwWJBa5J037DUtAT2Z74,108 +lm_eval/tasks/eus_exams/eus_exams_eu_osakidetza6e.yaml,sha256=alq11Oql-oOb8fIqFdqTk_p6aZFAyVXleEcuJaoOZi8,108 +lm_eval/tasks/eus_exams/eus_exams_eu_osakidetza7e.yaml,sha256=u-IpuyYa870nFv0tPbK9I77waJGh1XAt4SudHzjs4NE,108 +lm_eval/tasks/eus_exams/utils.py,sha256=T_RV1ImeKrnnVeNc2nZ8bdcLyVVPZzSWtSIzwTS2DWw,416 +lm_eval/tasks/eus_proficiency/README.md,sha256=Rza7o0KBETCMZc-D1VI30XCjxEuf27aRstONmaD0oMU,2004 +lm_eval/tasks/eus_proficiency/eus_proficiency.yaml,sha256=tTx9qTtij0jUGIgAlQdYS3klPVkP6T2AqpX4NhnEKIY,465 +lm_eval/tasks/eus_reading/README.md,sha256=fBM3CqpPdeHgTin34DDr1P4PG8HIMCLCpEdypae5iBA,1898 +lm_eval/tasks/eus_reading/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/eus_reading/eus_reading.yaml,sha256=5puep7gQ3POZVCsFV3ETCZqoT7nKA7qPbGt27sTCpPA,378 +lm_eval/tasks/eus_reading/utils.py,sha256=DXKAWMt8VNcpU8C_4mt5AdRLUZtGKWJva2zeMrN-leY,1151 +lm_eval/tasks/eus_trivia/README.md,sha256=lU_Q99EIumGEN1w2wg7Cbu0RGM6N9kBsYreCkLwsdvM,2724 +lm_eval/tasks/eus_trivia/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/eus_trivia/eus_trivia.yaml,sha256=CyGEzK9EQt98f9Zgx0uw_GOj1R_n2Sm40e_zZ9yypIk,368 +lm_eval/tasks/eus_trivia/utils.py,sha256=qFiBx7pY4erQFCyCw1CRDOH6hZwxjitcOFmAWU6jyl8,1113 +lm_eval/tasks/fda/README.md,sha256=vKeztgZaBuRTZlRnHe_YNBf45xn9uUJgbNF3-tGjVJk,4229 +lm_eval/tasks/fda/__pycache__/task.cpython-310.pyc,, +lm_eval/tasks/fda/fda.yaml,sha256=ioeX6mgasNSGqRgi1uVxB0WYDs7SSWe4FdGZwSrDcJA,36 +lm_eval/tasks/fda/task.py,sha256=7Xo-zgAL0g-uk98VVOLbUje8k-qKjZXlreBRtKuw7JM,3058 +lm_eval/tasks/fld/README.md,sha256=w5hgnlZSgZW6UfZ1VFId--uYjlbvvveaKKaiqW1enpU,3102 +lm_eval/tasks/fld/fld_default.yaml,sha256=aDvqFrZRJcXWrSWb6yxz5TkUDImF3Trb5YIzHTefk6c,562 +lm_eval/tasks/fld/fld_logical_formula_default.yaml,sha256=gvuubXxZzkaRdoFxMGfwzUUZQuO14t4eGSPuS8A39a8,1026 +lm_eval/tasks/fld/fld_logical_formula_star.yaml,sha256=WCZSPZtNWyKMnt7suLIYEtq46AgU-5Ot1g3QdukTg_k,92 +lm_eval/tasks/fld/fld_star.yaml,sha256=I3lOwfUP5LoHYygYIZCMQenYkQ11AqQVNLlUrRcls0I,60 +lm_eval/tasks/french_bench/README.md,sha256=kgluZP2TaoqPeDUirXDoyegOt9GzhQmwZjITlRqXflc,4403 +lm_eval/tasks/french_bench/__pycache__/preprocess_wikitext.cpython-310.pyc,, +lm_eval/tasks/french_bench/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/french_bench/_default_template_yaml,sha256=gN9nCOPneJ1GzAlAfNDQLoi1j9mO25Imanaqifto-Rc,73 +lm_eval/tasks/french_bench/french_bench_arc_challenge.yaml,sha256=B7_9f4z3jiDy3saoPxtfd7pyGmX81m6EIkysvLQZQTk,598 +lm_eval/tasks/french_bench/french_bench_boolqa.yaml,sha256=WFziLgft30rkgvpJRObOtB_rvPIsGzoGFou2rNvJOW0,832 +lm_eval/tasks/french_bench/french_bench_fquadv2.yaml,sha256=dCg-EGiFJS7BzmY2vAolC_s8wh3U6JF450918qoSheo,1032 +lm_eval/tasks/french_bench/french_bench_fquadv2_bool.yaml,sha256=q208gZIhyVIhJBmTifHqIU7uvqiaZytWXjMJ7DJgYDs,795 +lm_eval/tasks/french_bench/french_bench_fquadv2_genq.yaml,sha256=dKzGkaQ7q1AzXYTd7hfuO5e5i7GNvxGKPmZXGSQBFuo,1024 +lm_eval/tasks/french_bench/french_bench_fquadv2_hasAns.yaml,sha256=biqlBOhjSKaC_SHZt52svJx3JOZpvWnG_m7xuPYlGsE,1202 +lm_eval/tasks/french_bench/french_bench_grammar.yaml,sha256=pZWodzUjVehtrH72ybKAe-OHMfzPqUXyNAUcLNr4Dck,914 +lm_eval/tasks/french_bench/french_bench_hellaswag.yaml,sha256=G34Z4fuhPzgjFkiLa7z8ICsKTeXxRY-nHVoVuq-qWj4,489 +lm_eval/tasks/french_bench/french_bench_multifquad.yaml,sha256=CYZs72VA3K6fWwhixNRVLtEMDkEMx3wLjR9krA4VWfc,1031 +lm_eval/tasks/french_bench/french_bench_opus_perplexity.yaml,sha256=8JSlQtyFaDG-Lr9-iHxGNQHNy1fMVeH709jAMKeO_U0,619 +lm_eval/tasks/french_bench/french_bench_orangesum_abstract.yaml,sha256=VNWo2l94ZAIpznjz6ynG0zkEw4Opr5ss9AjiqSBJrbc,747 +lm_eval/tasks/french_bench/french_bench_orangesum_title.yaml,sha256=y-vdzx5PN2EOGtn6kcIZK_oX0sEBboVU9r04FdSmmjU,737 +lm_eval/tasks/french_bench/french_bench_reading_comp.yaml,sha256=XNwvApigBp5_VNaVDb9klKssvuJOa8Hb9WY0e0H-sLI,1286 +lm_eval/tasks/french_bench/french_bench_topic_based_nli.yaml,sha256=yiaqDEKPcqlt5OAZT8Sb-NPyuP8SH4Srfd2U0DhTAfA,970 +lm_eval/tasks/french_bench/french_bench_trivia.yaml,sha256=VNAot1Vd87HY53Uv9jtkIWNhvoZhIsAQNxYV-d6Gl6Q,921 +lm_eval/tasks/french_bench/french_bench_vocab.yaml,sha256=EzkjtId1fxmVtBM_vp1Bb93BtqMtYJ34bP8PXzTp_TQ,923 +lm_eval/tasks/french_bench/french_bench_wikitext_fr.yaml,sha256=7Cq4ZaJzs40HNg91WhR5wbqtpytNSGTh-3otQ1Lt3aA,742 +lm_eval/tasks/french_bench/french_bench_xnli.yaml,sha256=yBV2OTrOD3KwsIROrP8CugIjiIxGIUOAgTiC7ZUo1fc,875 +lm_eval/tasks/french_bench/preprocess_wikitext.py,sha256=5GhEyw_5gw66pUJfLhf9CXpt9aFnIDJASFuJDpKncAg,1753 +lm_eval/tasks/french_bench/utils.py,sha256=TWgvTaJhbMvTDZCx4Pr_nKBtBRox6IKI0b9ufdX3pEE,2750 +lm_eval/tasks/glianorex/README.md,sha256=jzXTzgYgqCaR9BOSRVWP5aM-zkCknr2yz9NGzYbD7Jc,902 +lm_eval/tasks/glianorex/__pycache__/preprocess_glianorex.cpython-310.pyc,, +lm_eval/tasks/glianorex/glianorex.yaml,sha256=cl4nU7T6tlA9kEVleq0Wqo9WRE3YQYkt7FyLoBkuN_o,399 +lm_eval/tasks/glianorex/glianorex_en.yaml,sha256=a-q2qKB008fayl4XK1EzUttk-1zZFU55PITFFlB--MM,462 +lm_eval/tasks/glianorex/glianorex_fr.yaml,sha256=TL7ZJ-ylZWLw7YHXJ3WOjErERzRltmkJKkbC0nrdiZA,461 +lm_eval/tasks/glianorex/preprocess_glianorex.py,sha256=9VRUPGeB0R6Y5XZLPpysCKAVwkyg0-IdDZZJ3WhSPgE,658 +lm_eval/tasks/glue/README.md,sha256=4jhlrD7-16TPFdRgMW8PH50mVphJx1pSCeWkQhroOp0,4029 +lm_eval/tasks/glue/cola/default.yaml,sha256=_zUdXjmZ3O4hiZushOaNoOE9Y-tTrZHVODu9V_no_2E,390 +lm_eval/tasks/glue/mnli/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/glue/mnli/default.yaml,sha256=4I2ExiFGobTPdv2huD49TEWBUDRad4VU4Se1wL2XAKI,309 +lm_eval/tasks/glue/mnli/mismatch.yaml,sha256=8h4PeAORdZvLDlydIQun3J7HEq-gEUuzQNWeKXU_FaA,82 +lm_eval/tasks/glue/mnli/utils.py,sha256=2zCZu6crR6KQGCIbvKmp1E8EO1v0-8nfk7gIFoe6iV4,232 +lm_eval/tasks/glue/mrpc/default.yaml,sha256=yGvkMAOUvsSGJIDxMCE6dalbZkbl7XRzmWKt9bMDies,387 +lm_eval/tasks/glue/qnli/default.yaml,sha256=eu50EGhoWPilUZnpvlX8qnAJyBwmKkJT1d8U1ilnOqo,347 +lm_eval/tasks/glue/qqp/default.yaml,sha256=Asya0cFnIfswBuIvM-GnLBaB1VKr4Bqo2p7t_jmKs1I,384 +lm_eval/tasks/glue/rte/default.yaml,sha256=wNbGmU4MBJ6bdDpxKfhVCfUDa2kpYM1kqY_IKVjGxk0,325 +lm_eval/tasks/glue/sst2/default.yaml,sha256=khEHtTl1-3InOkquc34uHrTKldn2x8vbo-9Kms5WUHc,343 +lm_eval/tasks/glue/wnli/default.yaml,sha256=ae5deGBLQLo9q0UjEFTY8_GnMjm7XuCZXxYDvXCM6DE,327 +lm_eval/tasks/gpqa/README.md,sha256=DuaeIXf-u0vzMrfoH_i_nQBNt3dXQQ0VtE8SD-SynYQ,3024 +lm_eval/tasks/gpqa/cot_n_shot/__pycache__/_generate_configs.cpython-310.pyc,, +lm_eval/tasks/gpqa/cot_n_shot/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/gpqa/cot_n_shot/_generate_configs.py,sha256=wRGHsDYz8it9vKz9aw_1zsv0cqIJwb9tc4_6AvWpQOo,711 +lm_eval/tasks/gpqa/cot_n_shot/_gpqa_cot_n_shot_yaml,sha256=JgshGutnYVfdAmPmuGiAz4XWQZYXcVKlqAymwM8jUR8,1184 +lm_eval/tasks/gpqa/cot_n_shot/gpqa_diamond_cot_n_shot.yaml,sha256=Ua3s6-BJeC9Iz93fTROSCLHzizr_FORkj9onkcnDiPI,124 +lm_eval/tasks/gpqa/cot_n_shot/gpqa_extended_cot_n_shot.yaml,sha256=XwUUXl8F7xN4el7ZHBQM1fEzvHQVdy5vsgW6h11_kCg,126 +lm_eval/tasks/gpqa/cot_n_shot/gpqa_main_cot_n_shot.yaml,sha256=8_SWDAVJeGvMhQfU2seWGi9sUrML6pPzYzm_DnCRTJs,118 +lm_eval/tasks/gpqa/cot_n_shot/utils.py,sha256=z6HIKm5JmMnT8aF5AQvIRCraTw5WsSelioIVAkPvwaQ,1066 +lm_eval/tasks/gpqa/cot_zeroshot/__pycache__/_generate_configs.cpython-310.pyc,, +lm_eval/tasks/gpqa/cot_zeroshot/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/gpqa/cot_zeroshot/_generate_configs.py,sha256=3e5minE_O5a9NJG68oNUMa3igTbmaojKxIR9S3ZwHY0,713 +lm_eval/tasks/gpqa/cot_zeroshot/_gpqa_cot_zeroshot_yaml,sha256=cC7rARYCcxX4VoTiaLCGTN3oXyHRfcW-ECB-2R_LFds,1078 +lm_eval/tasks/gpqa/cot_zeroshot/gpqa_diamond_cot_zeroshot.yaml,sha256=pNhT5SWHyQb7GKbtjvdVlrmGooyGlsudbXj_zUSA0Y8,128 +lm_eval/tasks/gpqa/cot_zeroshot/gpqa_extended_cot_zeroshot.yaml,sha256=DLnfykKWvEKni5LzzBhAdTcJaxOaABH13YmbaJmobrE,130 +lm_eval/tasks/gpqa/cot_zeroshot/gpqa_main_cot_zeroshot.yaml,sha256=wza8sxqp1YuMpRvBxil2PqgYAltEK_1oBZWJQe8_NQo,122 +lm_eval/tasks/gpqa/cot_zeroshot/utils.py,sha256=z6HIKm5JmMnT8aF5AQvIRCraTw5WsSelioIVAkPvwaQ,1066 +lm_eval/tasks/gpqa/generative/__pycache__/_generate_configs.cpython-310.pyc,, +lm_eval/tasks/gpqa/generative/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/gpqa/generative/_generate_configs.py,sha256=nsG56XiyztHj9LmKNtsD4gUmc2sqdpyFPS74SBBdKZA,718 +lm_eval/tasks/gpqa/generative/_gpqa_generative_n_shot_yaml,sha256=EMUOr6IoIXQ2OmMmHUigTPMWIq6XJ9AI2pMGKKAM-_A,1183 +lm_eval/tasks/gpqa/generative/gpqa_diamond_generative_n_shot.yaml,sha256=QH65eFCrkQn2jJHfjk0T5b9YbfQdUan9oHHgjugw1Dg,138 +lm_eval/tasks/gpqa/generative/gpqa_extended_generative_n_shot.yaml,sha256=xuQm0KRf_ZCyL5Id5KsadN4sZukKYDMtZD7v999HuQc,140 +lm_eval/tasks/gpqa/generative/gpqa_main_generative_n_shot.yaml,sha256=EJhKLKJ6oz5mP43jtKHfYcEeN5FY2gkxJHx8Y8Zsbq8,132 +lm_eval/tasks/gpqa/generative/utils.py,sha256=z6HIKm5JmMnT8aF5AQvIRCraTw5WsSelioIVAkPvwaQ,1066 +lm_eval/tasks/gpqa/n_shot/__pycache__/_generate_configs.cpython-310.pyc,, +lm_eval/tasks/gpqa/n_shot/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/gpqa/n_shot/_generate_configs.py,sha256=t2Uk-17YcA-J2FC4Lr1gAIgc3t8HVIJUWcLlOB2AU1I,675 +lm_eval/tasks/gpqa/n_shot/_gpqa_n_shot_yaml,sha256=EBUTgMe0laCRXyxJ4IgC5Hv3soOf-GlwOzfYCYu7i0Q,747 +lm_eval/tasks/gpqa/n_shot/gpqa_diamond_n_shot.yaml,sha256=bRMgQ-UtIFrpftGglUfHLE3U0ZIT8xhRr2-Ia9S_Tc4,116 +lm_eval/tasks/gpqa/n_shot/gpqa_extended_n_shot.yaml,sha256=80_VODHpsRmTLNdNl7LjbBuFXDeexymqiwBak6u2zA8,118 +lm_eval/tasks/gpqa/n_shot/gpqa_main_n_shot.yaml,sha256=UgLjr4n53Fx2ou_9M8IyKkKO8dX0Am9kHlS04UMaQwk,110 +lm_eval/tasks/gpqa/n_shot/utils.py,sha256=30C3EL9SYATKhzMvbDhpZApA5VTHpTze9nGFGrxekeY,1016 +lm_eval/tasks/gpqa/zeroshot/__pycache__/_generate_configs.cpython-310.pyc,, +lm_eval/tasks/gpqa/zeroshot/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/gpqa/zeroshot/_generate_configs.py,sha256=Ue9UIgZncdmXr5C6LwhruUGmM_JLELebuobsVj5jjN4,709 +lm_eval/tasks/gpqa/zeroshot/_gpqa_zeroshot_yaml,sha256=OdlPNGvrzkN9fVZX-ZBqmKb-31X0Ltpo237oX5naUz4,641 +lm_eval/tasks/gpqa/zeroshot/gpqa_diamond_zeroshot.yaml,sha256=I9D-hFnOYwYbkgFqmcFKosDdcwBgqI0bufxeGhX4ZQU,120 +lm_eval/tasks/gpqa/zeroshot/gpqa_extended_zeroshot.yaml,sha256=_4NFVTE2yJCEfxx8dWPsAEzO43JmidUpfGuzVBL34gs,122 +lm_eval/tasks/gpqa/zeroshot/gpqa_main_zeroshot.yaml,sha256=LZE_1k369Pdvf9ftK2yegIAMBIM6lMK1sk8E1t5DiDY,114 +lm_eval/tasks/gpqa/zeroshot/utils.py,sha256=FuEbEyXiqSXSi_EVkHpLh3muBJ-vib1cwgCXRqt5K-g,993 +lm_eval/tasks/gsm8k/README.md,sha256=UDYib3sADm37wgpYMNQkRXfmaqJJDVqn4ioy9F4GxP4,1950 +lm_eval/tasks/gsm8k/gsm8k-cot-self-consistency.yaml,sha256=F_FPBcRrPlTXwLewgkVuXFFa0we5yqJU9aBUtqelMlE,972 +lm_eval/tasks/gsm8k/gsm8k-cot-zeroshot.yaml,sha256=cMJVM5iGAK7opf_1MfG6b7W-aKxCdY3Eo1f6cHzpocQ,1020 +lm_eval/tasks/gsm8k/gsm8k-cot.yaml,sha256=iqfY85mnBjKE2hv30hviYgBwW2j405wGRbFN0ZtvI68,3319 +lm_eval/tasks/gsm8k/gsm8k.yaml,sha256=527IgNoIsNj5zgxw6xgOw9rvczY_4RjRsXv4bMTbYx8,1009 +lm_eval/tasks/haerae/README.md,sha256=jiCz34BnWHAs2tMvA58xqLSXtwStmKc-XCFMLzwH1YU,3004 +lm_eval/tasks/haerae/_default_haerae_yaml,sha256=DC8BBDQXgVDgUIcYpGONe0s8HKFNK6iJyy2ainmAjJU,396 +lm_eval/tasks/haerae/haerae_gk.yaml,sha256=IgyTjycO49Kxeh2jyR9mXvA9nfM8VarBqxPPt9jEHRY,105 +lm_eval/tasks/haerae/haerae_hi.yaml,sha256=2czT8etaPzTU3z2fjZ4sWGsd-a7npGmxikb2ydY492c,85 +lm_eval/tasks/haerae/haerae_lw.yaml,sha256=EcLbjBSEzzPwaobX778vATAbL_85WHKS5WBMyiS8ro8,90 +lm_eval/tasks/haerae/haerae_rw.yaml,sha256=aRQQ64_aCJyhU_EEV4Gj9W2F4_bPLyV-ohzksz0NT6g,90 +lm_eval/tasks/haerae/haerae_sn.yaml,sha256=oV4xR4ME9qy9q25jiKHrXbZ344F3MEWoza6M_6-9KW4,113 +lm_eval/tasks/headqa/README.md,sha256=HGBlwCx5skNA9GKsXv59G3s-08i577g4QSgv2sQrK5s,2582 +lm_eval/tasks/headqa/headqa_en.yaml,sha256=82oeoQphLobZWuix6pZ7SsiGrKC88VNFt6tvL5BA18U,576 +lm_eval/tasks/headqa/headqa_es.yaml,sha256=SKIFepRQ_qX9euHAWhk0g8sm3OYDfaei2uQUpGfPWu8,57 +lm_eval/tasks/hellaswag/README.md,sha256=0Sxbs3jgiuWJFMB0onpY-vhTxCZMWbDke8ElRFsiLfY,2710 +lm_eval/tasks/hellaswag/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/hellaswag/hellaswag.yaml,sha256=tw0XK_sIYlT-irK0ekusP5FntQDzm9w8FCYc1Il27bE,476 +lm_eval/tasks/hellaswag/utils.py,sha256=B9I7YLKPKk9ljc-EQGI6Y_5mRIVM6bhGoRTd6YDcEhQ,717 +lm_eval/tasks/hendrycks_ethics/README.md,sha256=CHqVUCYMuODB2-sKYJWL_DHBAkMww7dEkVA4WXHDWVo,1768 +lm_eval/tasks/hendrycks_ethics/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/hendrycks_ethics/commonsense.yaml,sha256=9oL762lPea6DtRcmV9scrHx9I3OHjXzjR-qdTqmXQMw,344 +lm_eval/tasks/hendrycks_ethics/deontology.yaml,sha256=oQHWZI1TzTYJy09-avPkP-lPxPyP4sfalpmPI6kNYJ0,357 +lm_eval/tasks/hendrycks_ethics/justice.yaml,sha256=3wWZqWWvkGHmixiU_Kso-J5unv7Rb7PKORU3VlTjS1g,288 +lm_eval/tasks/hendrycks_ethics/utilitarianism.yaml,sha256=ZiL2s0rFWLuuoeD-WTZTTbSQGjfnR5VoYaEQdp8Qp-w,280 +lm_eval/tasks/hendrycks_ethics/utilitarianism_original_yaml,sha256=5MHxvjLg3ag-KHs1xznqViyZufFevLIYby-Isof9D0o,587 +lm_eval/tasks/hendrycks_ethics/utils.py,sha256=TYz5SgyhBjHVOjCMJCCBMVKexOHJwi-NBDvHE4qAoB4,691 +lm_eval/tasks/hendrycks_ethics/virtue.yaml,sha256=gppOr26TSaJD2jlxsjugNdHKP1pj9IBHkJdFB4zs9DU,297 +lm_eval/tasks/hendrycks_math/README.md,sha256=LRRf-hFAO9BiSDJ6hk17kNT8KoYlkLn_JCcSM2ZEcJQ,2348 +lm_eval/tasks/hendrycks_math/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/hendrycks_math/hendrycks_math.yaml,sha256=npm82etZicZkvEtQHL5PwbjGLmuUoicbU91YlYlggRE,247 +lm_eval/tasks/hendrycks_math/hendrycks_math_algebra.yaml,sha256=Q4Jy5AntDcb2O0_v7WUB4ExxS9XaCofX4H4Ss3Nbx_c,588 +lm_eval/tasks/hendrycks_math/hendrycks_math_counting_and_prob.yaml,sha256=62VLj3HeyLmEIL4FiFD7ug9T-TNSGuzshf2xG7HiGK4,115 +lm_eval/tasks/hendrycks_math/hendrycks_math_geometry.yaml,sha256=MokiQk4zqZxNIm3tNd3GSNnHffiSzvrq8lGzWfQhNfI,90 +lm_eval/tasks/hendrycks_math/hendrycks_math_intermediate_algebra.yaml,sha256=jW9TcKskY8eTpQovVurxaWXllwHYe7GDClqHbqidcug,114 +lm_eval/tasks/hendrycks_math/hendrycks_math_num_theory.yaml,sha256=kqAOTLfHnpBqwtJCgP8nGC1MVpTYdAZHLnntvYwTS3I,97 +lm_eval/tasks/hendrycks_math/hendrycks_math_prealgebra.yaml,sha256=qIeWcq6j1L39YjPZTqENGHNl-wgNTumqSitCIotgWxA,94 +lm_eval/tasks/hendrycks_math/hendrycks_math_precalc.yaml,sha256=OLLPzo4GVfG1bwf9NAOi3TQekftD1sJg6rh11AgnH2Y,92 +lm_eval/tasks/hendrycks_math/utils.py,sha256=gzLkLyPGIEOyPXTubTk0-ZeyCc1goa1Ft4gtawCSnVw,6400 +lm_eval/tasks/ifeval/README.md,sha256=Z1lFazEwmAYW4W9j56CIp_mw50Pp5HBYnkeCCcZZZCU,2326 +lm_eval/tasks/ifeval/__pycache__/instructions.cpython-310.pyc,, +lm_eval/tasks/ifeval/__pycache__/instructions_registry.cpython-310.pyc,, +lm_eval/tasks/ifeval/__pycache__/instructions_util.cpython-310.pyc,, +lm_eval/tasks/ifeval/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/ifeval/ifeval.yaml,sha256=3rPTIOMcNcGEKyPUfdVvVc-VJ9BpnCZQHyaFe7RwcaI,748 +lm_eval/tasks/ifeval/instructions.py,sha256=q-GZq3DNxHkGvZM6TdB_zIVmVOXu_n8cabP-CPHTj0U,57032 +lm_eval/tasks/ifeval/instructions_registry.py,sha256=nbHAYs23CpFCDTeJpYgjWhBkwrmhpm4J5fud-edYSmw,7237 +lm_eval/tasks/ifeval/instructions_util.py,sha256=EybSWJEzXYb6GnCzn6FOpG86bwVJKUfY-CkcG01S17g,26066 +lm_eval/tasks/ifeval/utils.py,sha256=NWiG271kbkRNrQLpj5pYRaT7-9FRO7CZg78YArdb3uk,4895 +lm_eval/tasks/kmmlu/README.md,sha256=ZRF5WJErXQVa-xk3Ye2muCBgUd3HZPMa_uJFb59F8b4,3409 +lm_eval/tasks/kmmlu/cot_hard/_cot_kmmlu_yaml,sha256=TKBPtE8LScvFOaD5cd3mq-Bq_aEyTXJg62qGD8w6vyI,863 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_accounting.yaml,sha256=j8HIztXFWcLS1pXIrAvAPVMCTYbnsjuukasYHWp46QI,9522 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_agricultural_sciences.yaml,sha256=cmtaBhzzugmv5fCMNKsnZLOmGLW5E9cL1rnITRxZ5JQ,9234 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_aviation_engineering_and_maintenance.yaml,sha256=zWoIyR6EiH9B9TyHJ-5L656oTQ4ByRFU4vk9rDwQ2TM,10043 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_biology.yaml,sha256=w4kvr1SddZPo4KOh2qHVKEcSw4ToXUigi19mQpPHeDE,8365 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_chemical_engineering.yaml,sha256=J8o-ldjGd_RMWvPbafF3B1_r1LbRRIBv4LZg7IOmVrA,9678 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_chemistry.yaml,sha256=1CdNSeSh-iTOuLUbukeLY_mSm_Jwm8NPJCZds5xVZw0,7682 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_civil_engineering.yaml,sha256=VfSbd75QVp_K0-HT9x57Tt1plWbvQykAz7B_4KGACog,12178 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_computer_science.yaml,sha256=YeUfbsR1zutoDMHfVtiMXDT_AGvJOFNCXTD_-0OwVwA,11492 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_construction.yaml,sha256=vPkeJgBbeiBIkAOcXtK91a0Ohy7W-Bm-gtmrdFG3BRI,9260 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_criminal_law.yaml,sha256=yCt_yyLlonbnTOolANYiGlaIc91Bsp89Lhu7qRGyjwk,14867 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_ecology.yaml,sha256=lc0gws6a51JfnlK13tYadSyNAjPZ_3T4xbSBQj3sBlY,10793 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_economics.yaml,sha256=2-ozePaNgsk4zfARDTOMJsOW0jSVOuHUls8-iRPBTCg,10636 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_education.yaml,sha256=WTMzwUzOYceHBv_vEUUb6Rw-uK739ZDy01-n97cx3Zg,10780 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_electrical_engineering.yaml,sha256=9lcb2rCoPsDfomXBeA1hj0mTISqgpBul94Sfe489O7k,10839 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_electronics_engineering.yaml,sha256=tOKSKbDzxaAnJlvGw71IK3yLCikT4DYcE8HJwBms8hs,8609 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_energy_management.yaml,sha256=PJckxjzHxw8ug4NOtWlRhYR1NMAsZeBcHNMEeJnZRdk,9540 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_environmental_science.yaml,sha256=96dSr1odh-LQuxQxYdGwESj9vI34mVhFN-HvpnGoPrA,8904 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_fashion.yaml,sha256=WcPlMic3dPpwpYAh4F75PqSbkpxuySVUZprCNqw01TE,9496 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_food_processing.yaml,sha256=QoBdO9kHdj27gySuuPi1WbWf1ge8g8s9Och1966phKI,8070 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_gas_technology_and_engineering.yaml,sha256=1RWNEDGjX8pWD_TcTMqCTUP4HZ11zvbDtDcqnJWQ9_w,10342 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_geomatics.yaml,sha256=WRLzIikkS3VXNK8FoP_NKhc-1qivClrX14B5V2bSZlg,7798 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_health.yaml,sha256=ZVc-qj415WLL-2t2RyrR9uBtkxjjNAcNLeXKUJ2LAjI,10239 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_industrial_engineer.yaml,sha256=cE1llllnGtoU2SnVQja2cxcs0_2VUFkx_DikHKcF8Hc,8769 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_information_technology.yaml,sha256=XaSmZby_jBovVVf0_N7RIBMxZsRA_5QfrBvJEx1F3sU,8843 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_interior_architecture_and_design.yaml,sha256=S9ND1ebZ3hTGUTzL_rxFwTJYs6eQRGfdCNnnRtOFPUU,12044 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_korean_history.yaml,sha256=w2VnT07Q5EiN8XlcBRLELOL_7XxmUdigOrjflOU4RXg,12404 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_law.yaml,sha256=4S8mUD3CddDQceFhAmrjvRy7E31RpqczQyngMoCmKoE,9709 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_machine_design_and_manufacturing.yaml,sha256=LkhtK9k6tx9dFiu4dvfCIWMBuu0zCYwxcotHwo3nHGo,9575 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_management.yaml,sha256=EZiu0mL_r-cmzD4wQho_d_MMw-nsHcmgx7FXg1_Phg4,8785 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_maritime_engineering.yaml,sha256=E7dqZdobbGrdsNs-RDa7_CWIlsyyaACdypEJstVyHqo,11685 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_marketing.yaml,sha256=x4iMgXaiNU79ZVNijD5rEkkAyZz3rPpiVuyJvCpbnOg,11300 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_materials_engineering.yaml,sha256=s2C3NrRCZrnkXfVhNUjZh7l4fWOWNoToJR15LZl0k_0,9542 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_math.yaml,sha256=-VzknXBd8EDcaciqryBVZbevzekjx1NdslCyx0CPfmE,8955 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_mechanical_engineering.yaml,sha256=soDwHfhsO1JLceheMCz3T0Y2-Ed9Spab2cx2U4sHn1s,8218 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_nondestructive_testing.yaml,sha256=PHZKPXX8Iip6l-0l1t78mtM-6FJBc8HSU12hU845Xx0,10929 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_patent.yaml,sha256=pifdTw7n3C3Qm0pMDLC_z9U_e_asIYTekQPqXdEVlQU,16445 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_political_science_and_sociology.yaml,sha256=uE0pi4swJ0Hj3d8_OJF86vsa_QAETXpFP8aDS6TXrH0,11565 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_psychology.yaml,sha256=4JRlrArWLXDCoEAg9fDVDtO8GL_l-sV2Rw9sX1nn6XI,12643 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_public_safety.yaml,sha256=ehylvzmhxd34gaUH8yndTXO19y_BhLFVwhM3iz4AC5w,12597 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_railway_and_automotive_engineering.yaml,sha256=zUMNJGfveAE4x5y-feuht7GkYFCC5efbhwYqpCYtJTU,9135 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_real_estate.yaml,sha256=TfLVExgM-MMvs_-qy_GxR2zpOTRmUVwzrYdRPaX3P9U,12411 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_refrigerating_machinery.yaml,sha256=QEtNAqZ7uHsOxvS2WfgoAkknhHo7axIUo0Dj85jiOoE,8706 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_social_welfare.yaml,sha256=19MfB7tDFBYmHjmOjNlCXhnm496qbu5gXk4tT4ArPAs,11226 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_taxation.yaml,sha256=DohllAkrmssiDQV2ma5nIe7YfCQvfnt7J6I8HSH8faM,15202 +lm_eval/tasks/kmmlu/cot_hard/kmmlu_cot_hard_telecommunications_and_wireless_technology.yaml,sha256=SGegqNX-Yh8pCvMWno0Cfx00nkrT4NsTW66zYBkU7KM,9082 +lm_eval/tasks/kmmlu/direct/_direct_kmmlu_yaml,sha256=rst15H--77YggX8WcOaNxDp00hQrZvtdOhPSe5vyjcE,586 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_accounting.yaml,sha256=s8Q7u4IIavzezqVRdqnPvOMBZKudl3-QU8g8FXtfVmA,83 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_agricultural_sciences.yaml,sha256=VXY7mCusrN0RkLa2L2we2DSKLA3S_1hqEmoqDdlv3xY,105 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_aviation_engineering_and_maintenance.yaml,sha256=oe6jsBy3PbSKuDC7kMzMVGxtNggf0wPrGKdcPi2Zd4A,135 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_biology.yaml,sha256=WL5-7uGWR8k671v6ZsAkaHM7ZyfiIv3w3Ll44yHajQo,77 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_chemical_engineering.yaml,sha256=SmGBX9WrUMkKbbfr-yJ4cr5hpDhTEZ26ecQmd5BtOJA,103 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_chemistry.yaml,sha256=tZ85jUT4UDRFS-LHYCjJEX_W8Ls2Idlt5Jh29CQBb3o,81 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_civil_engineering.yaml,sha256=0zK5wTQNhEKfaFI85vHfWaL_ryPawXU62p726BKbYrg,97 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_computer_science.yaml,sha256=JksIR4Kv1U-lXfkmmzYkpvyXCSb-fFVTfGgowaqMNlE,95 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_construction.yaml,sha256=03SU1aSEmqkpOBDdaVqhcHVfzCSWpk2-H9QahgnsTsg,87 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_criminal_law.yaml,sha256=3e-ibeKqCQj_dD9uIYfy7fD8yNrRCNNvlj9yH413BoA,87 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_ecology.yaml,sha256=ILCnTDQDI-in_aeeOpXyH0tSrGzJV2Ry9FPYjtcFeyA,77 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_economics.yaml,sha256=no_J0aYbVM37XdOQiOYQJabnrCN2lKr55FmYZiorvDc,81 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_education.yaml,sha256=WdDbsh92CgTimWAKSzLMovUgqw2q1Up1VUG3rGK_6U4,81 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_electrical_engineering.yaml,sha256=kTvVfjkB-xiyP3gvGskNVNLKe3exjSN3IfJx1hogDZ8,107 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_electronics_engineering.yaml,sha256=FORtpjPQNzZLVoOg_NL06IUNSrAv2TC-gVJDqAkyv60,109 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_energy_management.yaml,sha256=px38ZJdmlrXR4heYuu7tCKmfIxFNs7q5A0Sn9IKdCO4,97 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_environmental_science.yaml,sha256=cYp6UHEUw0gF6twqqdU6XHoia2aZ2mdM4t8EeKVoPV4,105 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_fashion.yaml,sha256=3TH7EBvRcdMHENZihcrfhg52G5oeS-XJoeBeIdBwFqU,77 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_food_processing.yaml,sha256=UgdQ1s5bbt60vU9rZvXxmjlDsebGo1XgZ1wm2AcIz2s,93 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_gas_technology_and_engineering.yaml,sha256=r3ixx8LSfUaO5HJiM_P74EmAUJ2K6xa2bThZve9EckQ,123 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_geomatics.yaml,sha256=ayYsoAYd-s5imw9Y9xqMA-UGzKTaOz8btN25oNGn1Pk,81 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_health.yaml,sha256=au5qd1ERCyeg5ER5RK-Gwuup5OjcCEtdf7YrGffvDtQ,75 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_industrial_engineer.yaml,sha256=RFT6Z9ckjSpRUhDSuIybw_3JQDWkEMN4oQPyPa5EHl8,101 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_information_technology.yaml,sha256=XXaPqHonGcTiBf62Ro7AAwyGeRoUa-BLnVh4XW0BfX0,107 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_interior_architecture_and_design.yaml,sha256=N5eVgwChbU-uiD1DSG-CLsA6QPlokFs3V0HzFZMeevg,127 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_korean_history.yaml,sha256=A4qo57qWyLD2x8S7f4_a15tyvLRC-PPT3YP7xTEm6kc,91 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_law.yaml,sha256=zICpp74MIKXh9Fjno2Ulqgu9XozoTT55KNGepJ4DZnA,69 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_machine_design_and_manufacturing.yaml,sha256=66A6PujfcWGoIPeN47OqkiViaTDXURXe6NLIVzbpP4g,127 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_management.yaml,sha256=JALGBtgrQuD35mYEGhkiKAIWBnzJRhY0lkYyVuNN8mQ,83 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_maritime_engineering.yaml,sha256=EH4Shk5U-D5dmJh0gQAM0kcEkXeB33e7tYprbyvvrO8,103 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_marketing.yaml,sha256=APDXSSwhwZDqJZG51LXfgcl7Rtqyhrihwgp_K-Ja1Jg,81 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_materials_engineering.yaml,sha256=nH8eWSCiy-twUP8YLWAkqjSpRr79eG-3KF5t-1K3tg8,105 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_math.yaml,sha256=212LFb46uqXzAAmHRYNKIkd-H21-z28BfRQ92WlzmwU,71 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_mechanical_engineering.yaml,sha256=leqavhSJMGEvVGi84AkcQK8OQF-c4M0ncx2cY9JuqJc,107 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_nondestructive_testing.yaml,sha256=9L3qcZ0qCQHEVkM_MlTNYrQL0FgWslwjc83CFkDtD0w,107 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_patent.yaml,sha256=EOssq7DHAE6Pd26tW80H1JvOagUNtVFcF5xGpNi2jNw,75 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_political_science_and_sociology.yaml,sha256=D5oPZclcqmewurcrVqMfWxSp97Sz8VWNXu82_-YTqJk,125 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_psychology.yaml,sha256=tEnPOspom5FTZhPXYQxj6bLj-xmFN4YyEHTpD8ZwwZI,83 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_public_safety.yaml,sha256=-vHSItk8gdwU_biw9_olibgWruZAog-KHJ9jdn3t0DE,89 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_railway_and_automotive_engineering.yaml,sha256=qvbxl8R73Gbg6eeiU0OOlhbKkDJCfVKKjmLGSLF2kl4,131 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_real_estate.yaml,sha256=9pOr-QnHyTRgSm6-3PdvLOh_xdH35gOEbWpJEVqhir4,85 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_refrigerating_machinery.yaml,sha256=Nj9zGdHJZEEnPz2rcoo8oFbNDhiTDtVLYnhYicjfWtM,109 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_social_welfare.yaml,sha256=0wcc6fYPC62AltQDV2OPQ4GHIuP4w2D15T2lDgXHKQU,91 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_taxation.yaml,sha256=ok19bSEuMcpBSeHUNj9JCrX_PfUfAfPu3XnZxmey5T8,79 +lm_eval/tasks/kmmlu/direct/kmmlu_direct_telecommunications_and_wireless_technology.yaml,sha256=ctGyLo3PQ6GZr5-Ik-QqDrBJw_Yukj6nv-a87bKJkLM,147 +lm_eval/tasks/kmmlu/direct_hard/_direct_hard_kmmlu_yaml,sha256=fwiCNKSAnF21fMa-syxWPmum4fXTcRUk1dbWCyBSZ_Y,596 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_accounting.yaml,sha256=YtieMW1U4fnRqVqpze_VEwJnFyYCn_Ep8_GQVQLU4iA,93 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_agricultural_sciences.yaml,sha256=aJdRL6GiL5Nt-zedJ-8AtWrCGYEfwBWoKENM-Ro-TCQ,115 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_aviation_engineering_and_maintenance.yaml,sha256=CY8eW2fmZlnoZvw2wTCB5uVpmIuA49EK4jr1GI72CN0,145 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_biology.yaml,sha256=QWWwYjsDAUbpgkEbAiGTRraQGiVm6CA4Q5QKyGccrJo,87 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_chemical_engineering.yaml,sha256=NFuCWse1j9DorRj4k6HAxZNRiHasVrRe_z9p3k5wLE4,113 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_chemistry.yaml,sha256=3vVyTWQ4cDULfNC1bEB4LJ_kGhFRzf9zJXZwaaiPxuo,91 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_civil_engineering.yaml,sha256=p6n09u90WW65g4rWYCTUmigvxYBhKsRW0ExLvxjgEb8,107 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_computer_science.yaml,sha256=QKHGaYvXLpPMwhjWJHwKA5hfgnQFFApCIpkZLHjqQps,105 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_construction.yaml,sha256=AlaO-CtVBWCPC1HSvOrgkWzB5xtfVJrCg4z0TvqC7hw,97 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_criminal_law.yaml,sha256=O38idbXibN-PHOPM0IVLWrH52npOvFgPK5C-ZmN12qs,97 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_ecology.yaml,sha256=B50CWfQdVlKPGYEzz9IIn38sn1EWQ1hqzOmZL-RKV3g,87 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_economics.yaml,sha256=-YjWuF_7eAd163x0BSaW-7DLgniOsH3jKkrkVOm8Ecw,91 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_education.yaml,sha256=cMnKm8epRW0jNHtgOr-4T_huEUC222lFGTuPjmcWy-o,91 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_electrical_engineering.yaml,sha256=tGxJ0Tf28L5WDujFs1YkOu5VXjPKfMN9r2w-k4b8ZCA,117 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_electronics_engineering.yaml,sha256=n0cAac3Wdx4XlDAcOsG3atQo35W0ISMrVkqkHfp32k4,119 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_energy_management.yaml,sha256=EwAlD1KTclde9Yjmnk5dG_SkS6CAuBVPdJAQ0oPgRu8,107 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_environmental_science.yaml,sha256=p6aocihAudx0ytxfgKWb5Q7xhatemz1NS0v2Htw2Nbk,115 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_fashion.yaml,sha256=nWIu6Xz0JnAWCwDUjiWW4cU_Uu5QAokJlYoDpGsucME,87 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_food_processing.yaml,sha256=3LHcLpZYRvYgNZE_kuIrT-k1TAXYBbEZXybEnPd5HkM,103 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_gas_technology_and_engineering.yaml,sha256=0m0A08E-d77LRank3SumJntiXyfbNRWjZeUJOUd4CVg,133 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_geomatics.yaml,sha256=BnLc9o9TWQocf5ZbRt3hWA5OcjqGhuVMPAR8dhmb_GQ,91 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_health.yaml,sha256=GdjPYiKtpGi26zgVYTPuitFaU9yGNa8NBOqj-E0Po70,85 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_industrial_engineer.yaml,sha256=lpHTF8psfz5WfQz1qM0dMqStZ6GIKwbUGD1Y50Qfh6c,111 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_information_technology.yaml,sha256=Uq7B2vROL74MDhO9fJ3mpF7SFGVohptVPgZg1luPdb4,117 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_interior_architecture_and_design.yaml,sha256=JvpmkpGWliPuh99xHCVRhPmgKF5HBcZUATSxW_hy0xs,137 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_korean_history.yaml,sha256=ZqqnSYjsEXKO6DdXPuBSeywdHlJetfXRu-MpbO0w7rg,101 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_law.yaml,sha256=SrI2Ho1OxJgH5MbgZBlz2ZRp_qffFxprjBZIW5o-qrs,79 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_machine_design_and_manufacturing.yaml,sha256=JDL2o_MmMjT2vF_Ldbq_v98veQFYFEIKGgzXnOkudxQ,137 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_management.yaml,sha256=Ze9Ox37Kzms4k8fwFhuiRYdcDYWaaO5tTb_f6gDw_sY,93 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_maritime_engineering.yaml,sha256=IKkZopT2LfZWbYyus2w6bgJWNLiUst5o2HI3cOOhBqM,113 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_marketing.yaml,sha256=Y5hixAd3POjHUJrsSmrFk40XHZkU-QV31V0a8zTxQZ8,91 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_materials_engineering.yaml,sha256=dNOP7jZ_IUgorj3G7SHnArzbNgIT0y9lJhDQ09SftmQ,115 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_math.yaml,sha256=pxyZfPkkkz3grWK5lk4PPJObg1WjFz3iCNxJ7FKofa0,81 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_mechanical_engineering.yaml,sha256=Z-fXz_LdAQz0RG5nqo3N_R4WsbusCuf0imIURMzx7DQ,117 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_nondestructive_testing.yaml,sha256=JGlXHBFpcUB-7IYmAEh5n8jcNCbaJInZvWqRC7PLlwk,117 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_patent.yaml,sha256=oIvyta9dUsX9aL48XTkhMXrtbDrlAStKqg8KourU8tc,85 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_political_science_and_sociology.yaml,sha256=zTuHnAHYA-Jg9xCKtIK_2-8oYS9op839G1LDV2cFLEc,135 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_psychology.yaml,sha256=zzeQFKGcLqEor8fDFUqc_eJMrl1X0qg7ats_jdtW0wE,93 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_public_safety.yaml,sha256=XTEuFZKG08NEM7YXn4QkJRGSKqiNTvFFihot1kelbnA,99 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_railway_and_automotive_engineering.yaml,sha256=zeTr9E6ZxPsy1SBJ5CLeoduwkMTZuc1qRUJekTykFHQ,141 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_real_estate.yaml,sha256=x84oM4-0zOP8xTjAF3SJbvYQ1jjBfJeKiX8mW-bR5-Q,95 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_refrigerating_machinery.yaml,sha256=TwBvOTK6MV1C0FXlCY7MbmKM4W2xdDgpQ6PDtPv7qUE,119 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_social_welfare.yaml,sha256=TyvaCA-rb-_BnRgbSKqvCBYBX2wWq_yjuigL6jn6mII,101 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_taxation.yaml,sha256=KEpus1SLUr7ep6VMH4La53tALFLEKJ4biItu5j-0MK8,89 +lm_eval/tasks/kmmlu/direct_hard/kmmlu_direct_hard_telecommunications_and_wireless_technology.yaml,sha256=UjNG8CO7HAoXedSRGHwo9Otecv92wsaop7dTmqYEfX8,157 +lm_eval/tasks/kmmlu/hard/_hard_kmmlu_yaml,sha256=ClcQFAwA23dJselcwcJ7wHfGUBv2-D6-CK5B-4Wkb6s,463 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_accounting.yaml,sha256=e9ev7DQe4G2GleXWPjD_trDec8z5sH4YFEMazXoloZI,79 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_agricultural_sciences.yaml,sha256=ChU4TDE9AJW1NOHDtLSz7pdk6OQJmkNQ05o5D2i3MYE,101 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_aviation_engineering_and_maintenance.yaml,sha256=vPeMpeBAKaKEIcWU3DJg01T09BpJQhw3LqVaCR9kn2Y,131 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_biology.yaml,sha256=9UoIsVgtFBwjSvgfa6eNM8LkDsgxrtxxrdGgudezCFY,73 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_chemical_engineering.yaml,sha256=ckpTGipWfgGR7A-xZ5pvUCtbw-JvSE6o1by5KjJkzyQ,99 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_chemistry.yaml,sha256=d6iH4eJ4XnCmLCDDF5aO9avmYm8d2n_qdqWjkTPJgyg,77 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_civil_engineering.yaml,sha256=AW-CMC5f7MAM0GvKbPvcvy26eJVCmGlYFf8a6DQS6WY,93 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_computer_science.yaml,sha256=4Y66bFOBCF2ujCib5MseIbuCpcT56R4wz_44wuVFvQo,91 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_construction.yaml,sha256=D-PElzFYMXZl6hpe4X6K35Kd79cTblBmR8-N9g2riM0,83 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_criminal_law.yaml,sha256=6Jbz7hP5ZJcOTJZDEWy2i4w95qYcSeXdNVnZVSqqmIs,83 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_ecology.yaml,sha256=Ai0-oJ1wWs1j5wLBbvjRnbzACaWL5_2EQzHx-JbduBE,73 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_economics.yaml,sha256=lWWKu3fy6EXmQtJyi1L-7k5pZAgA5XBQlXrmDnFtxWk,77 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_education.yaml,sha256=YHH3LFimutZd8Lb4zjAJ4DKK7mTpfeQ2CCLLPJGwHzc,77 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_electrical_engineering.yaml,sha256=fr0YMWzEOwflcy0JwCUq9CAT8WWymthH6CxQSWSZu9c,103 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_electronics_engineering.yaml,sha256=9v6Tqzmjq8Xo1_7CqcfAscrM4QymWMAFy-ObuPdpdZg,105 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_energy_management.yaml,sha256=BQerrHdSvHDuI6ADbjpkr1O4OUyF8nqY-50SJRS9LHg,93 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_environmental_science.yaml,sha256=TFXCl2gB5xJrgLrvl9vvQReKJ5F0VnYEFGbxE7xFl5c,101 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_fashion.yaml,sha256=5uTrvzrhA-PZuL1dTkUbz6z0VntoQ4a6TSLOFBSMaKI,73 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_food_processing.yaml,sha256=aCuMtZBDmLimMlAArfXYRCA8DeqfTiDjZHANBknkrCQ,89 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_gas_technology_and_engineering.yaml,sha256=r5MHhAM9zq-XUPS529Z2CeJ49ezCixdBcdFTy4HYBfU,119 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_geomatics.yaml,sha256=xtRBGW2w3qOlZFEQmClU3rxEfRWebAuT6nllwJiDOHo,77 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_health.yaml,sha256=IJ4ZBNFrZKYsTHQSdoJUA5HQtMiXCMd8TJVQDUXAHRc,71 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_industrial_engineer.yaml,sha256=kIPwF0kExXT9HqkVaT1Ol_gOZrLqosr97PyFrUmL51w,97 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_information_technology.yaml,sha256=VmtYqkQ1_IDUNcpTRP_XJUDYnGrC4zC433TwMnDryug,103 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_interior_architecture_and_design.yaml,sha256=IHmQFDw9EXXOdFv74K1rvKREZcvZV95CDD9BwsNJ7ds,123 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_korean_history.yaml,sha256=jTE1drp3RKq_1gx3XA7CUfGJ8agKIkE6GFa6h0akYtU,87 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_law.yaml,sha256=UfLqVEkqsTx1l51UYaRKVgh7sepRJoZwo2aVENOwhNg,65 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_machine_design_and_manufacturing.yaml,sha256=5eFADVWfVB-Cy-72XhqqzjEhxShbG2I8lDl2jK30u-k,123 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_management.yaml,sha256=hMXBRsiyWZtoGSMYem-s8pijoBcRVutvMIet9CPgW6k,79 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_maritime_engineering.yaml,sha256=kFz40w6N6WqmS1cJMAhfZ8JCsfiAw7sEr6BvQmQW9T8,99 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_marketing.yaml,sha256=OCIfF5i6V-xGi0H0CKtQvKxh_SHyg2_ENJwBxsnybBs,77 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_materials_engineering.yaml,sha256=WXdXLlmSKIbEQLIkHDwvh6Wk0PEehHaVcg2d1dHQEc4,101 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_math.yaml,sha256=ucRNtG9FYK9K98hEWkQyLvvClZrBdoPd1G5jkrkAoe0,67 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_mechanical_engineering.yaml,sha256=BYwNAaaKiwemWOamYOLJRFnoLfMKJb8uv41ElKSxybE,103 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_nondestructive_testing.yaml,sha256=-t_1hBnzBEowNcetO51e5Jma_utgkxxRRqgpB0Xdmc8,103 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_patent.yaml,sha256=nSLXNhAvUD-pxlj_71GbEHYSR2ugLdaQRVQpnjet4Bs,71 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_political_science_and_sociology.yaml,sha256=02Fvhoq8jGgOuYg3gwuS9f_oITydu_F7N9yhwLJ_k4Q,121 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_psychology.yaml,sha256=svilfX5j0sx8dh7gNcT9dIa1Qk1KJEGV98-cjB-rUGE,79 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_public_safety.yaml,sha256=1pW2TJeQ-aHniyGM4ADrRVpGAw4E6o6D096w6dBTvkw,85 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_railway_and_automotive_engineering.yaml,sha256=LhrwEIVGmmWSaip0hJA0bly3q7BS6Yaafrm8qzYYIps,127 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_real_estate.yaml,sha256=OZtCtywjduzRBdUijV0M4qO-_KPTddIlMpsjDPNUVCs,81 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_refrigerating_machinery.yaml,sha256=H66JL7L3ftpHoQ51ZX2J-alppIlWkPZgqHvVilGR9NU,105 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_social_welfare.yaml,sha256=GF-tgxVL4KRMPh4ihPwfrKeclnExZCR-nuiNjEQxLvg,87 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_taxation.yaml,sha256=kcGOAtWNpdXJoNiSVRWHIAQ4wBfPc1GxV7an46B81fk,75 +lm_eval/tasks/kmmlu/hard/kmmlu_hard_telecommunications_and_wireless_technology.yaml,sha256=8XiVND_rRGyBmkPIiEl-R1MdzWyl9KySoU_TvnBG5BI,143 +lm_eval/tasks/kobest/README.md,sha256=cN-_ZRnv97G6XwjBXOQjjGkmZ7xWC_DSBqeG55pWd3E,1588 +lm_eval/tasks/kobest/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/kobest/kobest_boolq.yaml,sha256=lKVHvQ0i_k8DFSNZ_36K2y9R7e20L5Yi3g5or6dcjlA,538 +lm_eval/tasks/kobest/kobest_copa.yaml,sha256=a-ZbH0VnHBxdYbptgvNgLG-9XAGNMtST1dbMAi2EFYw,560 +lm_eval/tasks/kobest/kobest_hellaswag.yaml,sha256=5E1mspDV_AvHOuAbAvodkI3h9YyABBUjWLg-5Jc3kvo,623 +lm_eval/tasks/kobest/kobest_sentineg.yaml,sha256=BC9tST3rjUw5joW8STdI2wpDxriNRl_pSmCJ5Lpc4r8,577 +lm_eval/tasks/kobest/kobest_wic.yaml,sha256=28peMzeNU6m4vvSPtaAaAHY8qrSIa2jlOa56Jml8fYQ,562 +lm_eval/tasks/kobest/utils.py,sha256=A7NV9S5HQ_ONif9l7atxBUJQnl0nNXdQ-SnSkE0NI-A,1437 +lm_eval/tasks/kormedmcqa/README.md,sha256=3PvmldNDi-GHI3-ey1aKvJ2AhgjtcL6-VfaUuf7N1gQ,2372 +lm_eval/tasks/kormedmcqa/kormedmcqa_doctor.yaml,sha256=DMT0IBidQ_ui_ihi3OylsIPU_gRw5pQZTUFHJwkH1Dw,644 +lm_eval/tasks/kormedmcqa/kormedmcqa_nurse.yaml,sha256=hoDX0Ru1w28ybiXzKMh0qi3ghRZQGrczmOiUffl1UGA,642 +lm_eval/tasks/kormedmcqa/kormedmcqa_pharm.yaml,sha256=IamiqmaGYP9kxu9-t_eH4JvNYgHpzUYluGprZl3Smlo,642 +lm_eval/tasks/lambada/README.md,sha256=AO7XlGGY1Dch3ZC6km8CkfwpLiOvAdYbHH_YlEi2xEg,1186 +lm_eval/tasks/lambada/lambada_openai.yaml,sha256=pD6ORS3uLk6cqWHYu5dysPV53Qrb3Y8c-KtJ2bFORy4,533 +lm_eval/tasks/lambada/lambada_standard.yaml,sha256=2yH5TSDx7P7aUKJNruN18eiLifeQsi2Tc_MpdQvznkk,501 +lm_eval/tasks/lambada_cloze/README.md,sha256=j0ewRfQFxUQ6JsD-JGYp4oK1URb-uF1UGiQ-4cwYvs4,1934 +lm_eval/tasks/lambada_cloze/lambada_openai_cloze.yaml,sha256=aylvpHNoC2lZOJQIBBYwreqwWNGgMM3K7CuonGAxC4Q,517 +lm_eval/tasks/lambada_cloze/lambada_standard_cloze.yaml,sha256=Qb311jDoc38gNH1obwkpPARGklJUMvVMaXVXcjLYsxE,527 +lm_eval/tasks/lambada_multilingual/README.md,sha256=ggwX8LEo_cr1oT29CyoLptVbcTxCVZSr9qhOr3UY7RY,1995 +lm_eval/tasks/lambada_multilingual/lambada_mt_de.yaml,sha256=A3dzij8qTX7W-XZ1uXkMf7l7lPbe8Irr_fem4zQ34oA,72 +lm_eval/tasks/lambada_multilingual/lambada_mt_en.yaml,sha256=zZSLJ_eMVhTgLF1t_-x28SzkN62WDCcoGSeKz0Xgtuw,505 +lm_eval/tasks/lambada_multilingual/lambada_mt_es.yaml,sha256=3cWtUCRNZWeGp9bIUU-uJcxCeD7iyHwUkAkdAFMFIxg,72 +lm_eval/tasks/lambada_multilingual/lambada_mt_fr.yaml,sha256=Okxnj-cxPcEsEIX0vc89Uih-szW7wqHY2SAcdi675Gc,72 +lm_eval/tasks/lambada_multilingual/lambada_mt_it.yaml,sha256=DtT68Pbs0fCY8oJlKQwQdO0pgcqNPEshYFQppA9RDD4,72 +lm_eval/tasks/lambada_multilingual_stablelm/README.md,sha256=q9hQQb1LRtb6SdmOzq9Q32yD3rNtvnhNfXXgJzdgDJE,2448 +lm_eval/tasks/lambada_multilingual_stablelm/lambada_mt_stablelm_de.yaml,sha256=55XldbZgJ6IplV1glKHCoOlvCLz--1wFlH5fmX4xtRc,90 +lm_eval/tasks/lambada_multilingual_stablelm/lambada_mt_stablelm_en.yaml,sha256=wTyN6zLXN3AcKXkSkVWqDQy0PyhsRUV5C7NHQ5-H0Gk,525 +lm_eval/tasks/lambada_multilingual_stablelm/lambada_mt_stablelm_es.yaml,sha256=XTfiICM-UvziVkTNMnRBsRXYZKKfVTPGD0vTjPIfGTU,90 +lm_eval/tasks/lambada_multilingual_stablelm/lambada_mt_stablelm_fr.yaml,sha256=VZVIvuOsqERjzmBp2cbXnuAE78Dt7ZQqRUawvhko34o,90 +lm_eval/tasks/lambada_multilingual_stablelm/lambada_mt_stablelm_it.yaml,sha256=UII8rMHD5QeSWzC1ZwvGV5bPWrVG5qaen98mYXc4wsk,90 +lm_eval/tasks/lambada_multilingual_stablelm/lambada_mt_stablelm_nl.yaml,sha256=bElBcbyP0sg6ucCzvp39eVOOr10uRaIFQybfolBOK7Y,90 +lm_eval/tasks/lambada_multilingual_stablelm/lambada_mt_stablelm_pt.yaml,sha256=0EoSWB1_R5h16I00_rs1GQfVS2RI914B4tAMZ2fhmpM,90 +lm_eval/tasks/logiqa/README.md,sha256=Iyrf8c8F53A1eYqaDCb6hAm3_Sg_t47gZbOI0BjDKAw,1657 +lm_eval/tasks/logiqa/__pycache__/utils_logiqa.cpython-310.pyc,, +lm_eval/tasks/logiqa/logiqa.yaml,sha256=J9PMnhvefAZiF-i7Qm8TVndnoJGjVfrEMQPZKZq33a4,578 +lm_eval/tasks/logiqa/utils_logiqa.py,sha256=RjmfQAZUadI0wMnh7z3ptn5Q1f4cLEEwYH7aLdomgmA,616 +lm_eval/tasks/logiqa2/README.md,sha256=BJA7HgfRCSPs51iYrFl9rQzMKjoVDqaIDtCDAh5yk4g,2244 +lm_eval/tasks/logiqa2/__pycache__/utils_logiqa2.cpython-310.pyc,, +lm_eval/tasks/logiqa2/logieval.yaml,sha256=bW1d_6Hqvc8M76mQBUYmsXc1Lk-rYTAa1-FDElOWIkc,1382 +lm_eval/tasks/logiqa2/logiqa2.yaml,sha256=0jlenXfClywd_ulejkk3-HPOE118TufgzsPGcK6r6Dc,512 +lm_eval/tasks/logiqa2/utils_logiqa2.py,sha256=CtI75WahPZvORkIad_srFGSZ6bUnGlZf_6sYHkAP90M,875 +lm_eval/tasks/mathqa/README.md,sha256=VmhPmoYwpKTfeUVDnkdHbj0zx2OtY7y7AI-cJrXEOhQ,1907 +lm_eval/tasks/mathqa/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/mathqa/mathqa.yaml,sha256=dKJMHoZxEGdeJeCMQF9o_DBL9fokJkXp1jlVrQqHDro,578 +lm_eval/tasks/mathqa/utils.py,sha256=NFqieHDv0UX5cEVmMmIu_GF7KZpNAKvJRZJC0saW00I,178 +lm_eval/tasks/mc_taco/README.md,sha256=OEUcQofUlqsm-3CLKht9u-V0wXAldd7uPWBjmQjFTSg,2052 +lm_eval/tasks/mc_taco/default.yaml,sha256=A58bI314XcNdpoKxXxxFhrPlUV-U7pKrPeJfWYOSw_4,399 +lm_eval/tasks/medmcqa/__pycache__/utils_medmcqa.cpython-310.pyc,, +lm_eval/tasks/medmcqa/medmcqa.yaml,sha256=NVrcOA7j28YpYlkP98Bx47HcCZR9vJb_5qMxhknQDaA,462 +lm_eval/tasks/medmcqa/utils_medmcqa.py,sha256=ucvjPVG5ViS5MXyrj_uRezLBeKqhAP2c5KrAqcRnR5s,580 +lm_eval/tasks/medqa/__pycache__/preprocess_medqa.cpython-310.pyc,, +lm_eval/tasks/medqa/medqa.yaml,sha256=M5Q98uefbZaiaF4UaAouR5qkxvL8RK-g7wrlnFfHwwI,458 +lm_eval/tasks/medqa/preprocess_medqa.py,sha256=Bq3G71vaMln-VHNV5rBkylfGdLUC-sdJ0KDMyP7pF4c,362 +lm_eval/tasks/mgsm/README.md,sha256=zSmVOkdo78p4Oj4Ui4skfwzYyLqPnE3H4DiS7qMF4Ac,3504 +lm_eval/tasks/mgsm/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/mgsm/direct/direct_yaml,sha256=OnD6bl8mXleMdZ3gZCnJmoyOZWfLeWr9g4wkaMr6PJU,907 +lm_eval/tasks/mgsm/direct/mgsm_direct_bn.yaml,sha256=pOsz6TlTy-XtEfSex2p2oBbg9zAcfV4C_uEupiVq-PU,420 +lm_eval/tasks/mgsm/direct/mgsm_direct_de.yaml,sha256=7b0gimqBcMSJD4FpYQ7DULnrBhU29wa7xUaClZWBd-w,396 +lm_eval/tasks/mgsm/direct/mgsm_direct_en.yaml,sha256=MNyt8SYS3AuehdzrJIOoAlKI-HtaxBshsa0DQHQqdBI,400 +lm_eval/tasks/mgsm/direct/mgsm_direct_es.yaml,sha256=QdnPgAUHjzYMj3c9-zZ5wclXU-LgxUyXJkMYrvZ7zpE,406 +lm_eval/tasks/mgsm/direct/mgsm_direct_fr.yaml,sha256=q4QI4JM0S9dihzKzMEw7WbVxVjgSUj7D7PjLz8Vvtw0,408 +lm_eval/tasks/mgsm/direct/mgsm_direct_ja.yaml,sha256=Pr8BXNyxBHcw8nAFTJVfQYhrLRGZ8gzbpeOQ-O1MHZU,396 +lm_eval/tasks/mgsm/direct/mgsm_direct_ru.yaml,sha256=RI2otfyZ41_-_3qBGklRf2LwnWa7mVcTlsjv9FFHopc,408 +lm_eval/tasks/mgsm/direct/mgsm_direct_sw.yaml,sha256=YaNqXO4GSP0FvOk6QxtqmR8RnuBGkK6XZzvrEYwAbas,394 +lm_eval/tasks/mgsm/direct/mgsm_direct_te.yaml,sha256=uZaP1zvNvNDv3BL8HYI3_tMTc94Qp3svYSr7YvpTxkc,420 +lm_eval/tasks/mgsm/direct/mgsm_direct_th.yaml,sha256=Vi2pgql8xdUPUA6vmWhTRbZC1qXZ6FQaLGqaaBqHNLg,414 +lm_eval/tasks/mgsm/direct/mgsm_direct_zh.yaml,sha256=j1iP6Lhg35p33YVurNKzywEGPAQAength7PfOf8om7Q,395 +lm_eval/tasks/mgsm/en_cot/cot_yaml,sha256=MPzIhexcshgt7BWjM8WoIa9hoa8--GFuK1Y26N52xjw,959 +lm_eval/tasks/mgsm/en_cot/mgsm_en_cot_bn.yaml,sha256=RLNq0J9egvNGucI7S0lepGfVkKZ0PccOT-Y2gB_nLZc,443 +lm_eval/tasks/mgsm/en_cot/mgsm_en_cot_de.yaml,sha256=wZMVo5gY_By2AmuLNvvp3nLMc90dEMwTWdqRLtIUUs0,417 +lm_eval/tasks/mgsm/en_cot/mgsm_en_cot_en.yaml,sha256=qIJJMQIxjNO2DDRJNbL5wbmaJSf2clh5QWjQ8Yc-liA,423 +lm_eval/tasks/mgsm/en_cot/mgsm_en_cot_es.yaml,sha256=kW7OS5He2TQe-h24NMCRzuMj5T96d2TQ99gT_wx44gE,423 +lm_eval/tasks/mgsm/en_cot/mgsm_en_cot_fr.yaml,sha256=80r4YBpMICuwMpcl9HvCU7raWmNPuSTzbHG55EC7Ybo,425 +lm_eval/tasks/mgsm/en_cot/mgsm_en_cot_ja.yaml,sha256=WqBqT1giFlul7YGX2Ulns2G7geHogFE_Cd14Q6B_aek,419 +lm_eval/tasks/mgsm/en_cot/mgsm_en_cot_ru.yaml,sha256=44uXpmQVAzHlFaJb_o8kDZEYeUe1H6fR60rwMj45vDw,431 +lm_eval/tasks/mgsm/en_cot/mgsm_en_cot_sw.yaml,sha256=XT4taMtUJaVvfZit-THwafuela2MRzcSaziKEiC2Tzg,417 +lm_eval/tasks/mgsm/en_cot/mgsm_en_cot_te.yaml,sha256=69AiswgkGTDii0MPpttAugO1lYBSWa9mF27z4AbQxDQ,443 +lm_eval/tasks/mgsm/en_cot/mgsm_en_cot_th.yaml,sha256=oluyGodzqaJoUZ0KIW6cTjzz5HhIu6UlJNWGHZktg4U,437 +lm_eval/tasks/mgsm/en_cot/mgsm_en_cot_zh.yaml,sha256=ogkgPoCBad60k99oN-tZjZwpPAF15lQxIit-byWWS8M,418 +lm_eval/tasks/mgsm/gen_yaml.sh,sha256=F0Noarmg-NlAgWhA-_nZKA97UDSoDyrHARQDgmPG4bY,207 +lm_eval/tasks/mgsm/native_cot/cot_yaml,sha256=7N3f3B1EK9rGjGzR7aFL6lxGhZdpdOr9MYbhQ8_N9_g,820 +lm_eval/tasks/mgsm/native_cot/mgsm_native_cot_bn.yaml,sha256=Ojpf06W7xwaIKKs3wxZEhg6wLWUq-BcvS_blLJEfuPM,777 +lm_eval/tasks/mgsm/native_cot/mgsm_native_cot_de.yaml,sha256=Ig9r8PWR-G1I3UDXXju14dr-d-ppc6PTR-mnbjc8PKk,730 +lm_eval/tasks/mgsm/native_cot/mgsm_native_cot_en.yaml,sha256=irYzHhWBvfvbmB40T3x7JXjDFFmgrIuAh5OUWtRJyfM,713 +lm_eval/tasks/mgsm/native_cot/mgsm_native_cot_es.yaml,sha256=ILp-L4ek7ulwezSqcbM0mAdi69t8hjzesYYXjX9jVus,719 +lm_eval/tasks/mgsm/native_cot/mgsm_native_cot_fr.yaml,sha256=oizhISkBp0oNb9EtrLm551Yhu_VqAal-5eKrQLUPxnQ,733 +lm_eval/tasks/mgsm/native_cot/mgsm_native_cot_ja.yaml,sha256=SGo3j7deqYpluE9WyTlsTjuQaTZFIOfQXCAvhGyJUJQ,729 +lm_eval/tasks/mgsm/native_cot/mgsm_native_cot_ru.yaml,sha256=FEzjncVVgNdvMVrew1O3QVqeiLoAH4KtLUU9n165NFA,748 +lm_eval/tasks/mgsm/native_cot/mgsm_native_cot_sw.yaml,sha256=hRxFnOJGjmAUaKfDYHG8b4Th4d1cs-OXL2uDXKuHK2A,709 +lm_eval/tasks/mgsm/native_cot/mgsm_native_cot_te.yaml,sha256=8iwm8ryLnpu9aJaeNaIq55FDkoaqnT4hs7Pk86kurK8,801 +lm_eval/tasks/mgsm/native_cot/mgsm_native_cot_th.yaml,sha256=faWI8Txy2nzvf9f7KbRIVWBllGN-GUN0YYnSC8rTfd8,796 +lm_eval/tasks/mgsm/native_cot/mgsm_native_cot_zh.yaml,sha256=WHJu47tsvPWUFNnKvALp4nTmGTg0U2oRsJKnzO-K67U,693 +lm_eval/tasks/mgsm/utils.py,sha256=L4YekOiIl-f5DBtbZu0Ol-cMRX7iPtDiKRzZS8sYhW0,8448 +lm_eval/tasks/minerva_math/README.md,sha256=PhKtu_8JL2KbVllMn5KME2skEw1HyewhTqwUT0opgzE,2971 +lm_eval/tasks/minerva_math/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/minerva_math/minerva_math_algebra.yaml,sha256=GnSnXkYg83H6HNuz6sR0bayeVqxiB9aEBS5n-Kg8p4Q,719 +lm_eval/tasks/minerva_math/minerva_math_counting_and_prob.yaml,sha256=jjxGjPVtnUiudvSkOVlfA_A6oCSUBM2USRJAgQW0HH8,111 +lm_eval/tasks/minerva_math/minerva_math_geometry.yaml,sha256=XiPoBuvqoAc_1FtATee1GyYcMAC8ClYOKWa04nrcrHQ,86 +lm_eval/tasks/minerva_math/minerva_math_intermediate_algebra.yaml,sha256=Irfq2-W-AiImEH0PoT2ZdoVg_y-sQOWqNfOimVovvkE,110 +lm_eval/tasks/minerva_math/minerva_math_num_theory.yaml,sha256=IYI_lzbIQ2BbcPWXrS24nulnlg93CJjlwUfV8M7IkTE,93 +lm_eval/tasks/minerva_math/minerva_math_prealgebra.yaml,sha256=va30pN9E3JV6nmLY6lUXxhH_nkm6ijSDnAiw6wdrDnk,90 +lm_eval/tasks/minerva_math/minerva_math_precalc.yaml,sha256=6PZ7DSqtq_gn2rPKIo10hw6JMJOanIxuiWu5uZCc0JM,88 +lm_eval/tasks/minerva_math/utils.py,sha256=WWBBGYIsLUj0iwEVLAetBMJAmWIBU7ih6sQhglbOHGw,9218 +lm_eval/tasks/mmlu/__pycache__/_generate_configs.cpython-310.pyc,, +lm_eval/tasks/mmlu/_generate_configs.py,sha256=CbMAfkceor5ciPVx66bVZDioXuBGMUpadtFKdvSEYL8,5305 +lm_eval/tasks/mmlu/continuation/_continuation_template_yaml,sha256=jWEc0vf9WbChLA_07dxMYQvhY2FRYhFrl_5VN_dMjSs,367 +lm_eval/tasks/mmlu/continuation/_mmlu.yaml,sha256=MotTzJO2e0CMN4WC6XHR-RwL338amM1tSDnJUb09iQ0,157 +lm_eval/tasks/mmlu/continuation/mmlu_abstract_algebra.yaml,sha256=ygE1-XWbyUcAwhzGk4oM7wQIKu9t7RCnxUCL2pUyg-c,248 +lm_eval/tasks/mmlu/continuation/mmlu_anatomy.yaml,sha256=HJgI_f5aOvWO6EIlyvddWYYMwZttkipofKmiL84BvkA,220 +lm_eval/tasks/mmlu/continuation/mmlu_astronomy.yaml,sha256=TMv39tDAz8fiGd09ADmHVwSTrKz3rOErLDbq9QVerSE,226 +lm_eval/tasks/mmlu/continuation/mmlu_business_ethics.yaml,sha256=JOFNF0HO5eDmpITxn1FyPlIY5fcWWV1WLdqHndOS2Ak,246 +lm_eval/tasks/mmlu/continuation/mmlu_clinical_knowledge.yaml,sha256=jgbLpJ-BrwnVratkIkiTpG6FgKYggSPmyMa2C1v6UJw,255 +lm_eval/tasks/mmlu/continuation/mmlu_college_biology.yaml,sha256=iHuWHBrKmBLGKqsrSEznfaB5dbCJKrtuNtNM0e-fWHs,245 +lm_eval/tasks/mmlu/continuation/mmlu_college_chemistry.yaml,sha256=FkqV0xg7-ezNjViPwzstEV2L3FAre1UIO5UwjSiRvbg,251 +lm_eval/tasks/mmlu/continuation/mmlu_college_computer_science.yaml,sha256=YLkLyWfHJLptjAuPGGiVqkn6xdeeWfAu9t_S68VH2EQ,272 +lm_eval/tasks/mmlu/continuation/mmlu_college_mathematics.yaml,sha256=cqrQ66A9pEaPlQx0PocmZtUGQmlEeAxEVwdqq34yWX0,257 +lm_eval/tasks/mmlu/continuation/mmlu_college_medicine.yaml,sha256=yzxKfOakQbsMF6SLQ-so50KEVZ4hhOSPLYIthHkVO88,249 +lm_eval/tasks/mmlu/continuation/mmlu_college_physics.yaml,sha256=-tAHNRCDnnS3nvUrRy674M8WBdaPe7DkDhcgDsPrS4Y,245 +lm_eval/tasks/mmlu/continuation/mmlu_computer_security.yaml,sha256=P7TSo_tegHwoqinTKnwcDZtcysavOGFCIXya7_zVns4,251 +lm_eval/tasks/mmlu/continuation/mmlu_conceptual_physics.yaml,sha256=0gEA75iLZaHUDHAGQ2dBe32tPkbZ0uYvrvGP0fVjOm4,254 +lm_eval/tasks/mmlu/continuation/mmlu_econometrics.yaml,sha256=-SPIn5gyleNCWsqEkHQ2yzAGKGqzm0g9_OVXBls1Ovs,246 +lm_eval/tasks/mmlu/continuation/mmlu_electrical_engineering.yaml,sha256=pqxIPbznYKBcm0QGv-g96WuNUxXImQ0I9UFKmyEOpx0,266 +lm_eval/tasks/mmlu/continuation/mmlu_elementary_mathematics.yaml,sha256=6-WSVoopsYcQNVVXEpkRaPXWVySK1LNZG8oOu-sNV3I,266 +lm_eval/tasks/mmlu/continuation/mmlu_formal_logic.yaml,sha256=Co491l9Lr_DAPFcKmsJyXSgsCi95wGeG-t1MkqI7EgM,242 +lm_eval/tasks/mmlu/continuation/mmlu_global_facts.yaml,sha256=m7My5i1xFWssX7V_a0LKeEkma8EcZMksWcnVVHaqHQY,237 +lm_eval/tasks/mmlu/continuation/mmlu_high_school_biology.yaml,sha256=n-L9HJMwOD1Rd8GVoKGaGYLZzjlzNXgIjvdrHyOKavs,257 +lm_eval/tasks/mmlu/continuation/mmlu_high_school_chemistry.yaml,sha256=RWlmowOdQOHmcMleZ8NFbg3BHJp2mXEfC1IrRR1pJhk,263 +lm_eval/tasks/mmlu/continuation/mmlu_high_school_computer_science.yaml,sha256=cGkY6g6DAJ9RifhN_b2mg3J7ahvtdnf9COm9SqiKv7E,284 +lm_eval/tasks/mmlu/continuation/mmlu_high_school_european_history.yaml,sha256=adoebUlf_qb0azPLcrIn9a6Y5TREbweEGoddRFXrBQA,290 +lm_eval/tasks/mmlu/continuation/mmlu_high_school_geography.yaml,sha256=lnylbGhekPhvEOfCC33_RqDgq2FBm8VOb2VPpvzc_BE,274 +lm_eval/tasks/mmlu/continuation/mmlu_high_school_government_and_politics.yaml,sha256=3BYKR2gKBkOwghjboU4z64VQmCBH9dkHvJ3qdOVPh3s,316 +lm_eval/tasks/mmlu/continuation/mmlu_high_school_macroeconomics.yaml,sha256=Ij-PETjnjykYi6uQjGAqiW5xOp_MnMYPstgI20Q90-Y,289 +lm_eval/tasks/mmlu/continuation/mmlu_high_school_mathematics.yaml,sha256=NTtS7PNIppoo97T21Ys0fI3mo78duVtqqhxQyng0sOs,269 +lm_eval/tasks/mmlu/continuation/mmlu_high_school_microeconomics.yaml,sha256=BHkLg_Y5qWFz3Pip759KuT1DoWoDFeq_w8mVjhIWI_g,289 +lm_eval/tasks/mmlu/continuation/mmlu_high_school_physics.yaml,sha256=DE6JlhktVdkCeDE1HCE8Vy24fMbcYUEabGo6QrD6HeA,257 +lm_eval/tasks/mmlu/continuation/mmlu_high_school_psychology.yaml,sha256=OrApyxUTS867PIMnqW2le7U-L-tsyUo_-BO2SyYpYVI,277 +lm_eval/tasks/mmlu/continuation/mmlu_high_school_statistics.yaml,sha256=Qc06FbJvyV4Z23JSM5alN14NbWe-i9To8YeFk71ZlOo,266 +lm_eval/tasks/mmlu/continuation/mmlu_high_school_us_history.yaml,sha256=kSQ0hAJ-KoTwo70kC1Bm7DG5aYxhqn13iMVWRE-OTmQ,272 +lm_eval/tasks/mmlu/continuation/mmlu_high_school_world_history.yaml,sha256=4LW0JYcSNJbN-n_Tl7jih1fcAh_v1rcpHLo4ITuKBCk,281 +lm_eval/tasks/mmlu/continuation/mmlu_human_aging.yaml,sha256=z3QxkbM3Tp4oBTYXc-HdekEMQxD2PgvyMPa10_iTCw0,234 +lm_eval/tasks/mmlu/continuation/mmlu_human_sexuality.yaml,sha256=dqx5fgMUvEzzhjt8DpCX5Wp-JTcmB6ASmHkhpiZMckA,256 +lm_eval/tasks/mmlu/continuation/mmlu_international_law.yaml,sha256=r4b9MifOXRuWf8-PeMF9yCYKAVXtMnn0TkOIX86EJVk,257 +lm_eval/tasks/mmlu/continuation/mmlu_jurisprudence.yaml,sha256=SAhplU_eyMXUuiCbtf8DEx7QMWLZtOYkhCCh0lF5yy8,244 +lm_eval/tasks/mmlu/continuation/mmlu_logical_fallacies.yaml,sha256=iZm9r9_jeWEdU4cbqzqp9pPllbcsueUFIz9u21RNIZo,257 +lm_eval/tasks/mmlu/continuation/mmlu_machine_learning.yaml,sha256=Cqe9CjMuWGYdIHCEEid1E7hGLyGXCQh3GBaEKxlupAA,248 +lm_eval/tasks/mmlu/continuation/mmlu_management.yaml,sha256=VaWik51rEYEZAaCPSlIn0KcDf3tkJ5dbq9seokn_oTE,230 +lm_eval/tasks/mmlu/continuation/mmlu_marketing.yaml,sha256=M2rkbYTvNXdnFbASM2INSGzl89sF7zTr4A3rw6oWbY4,227 +lm_eval/tasks/mmlu/continuation/mmlu_medical_genetics.yaml,sha256=j6Bk5WRcX55hWSxZg4EghJxBj5N7m76p7KBhVyzJKDY,249 +lm_eval/tasks/mmlu/continuation/mmlu_miscellaneous.yaml,sha256=JGShzZH_-EbbZyMcjKwiqOIVrhsn-29nDkEEEPnEhHo,239 +lm_eval/tasks/mmlu/continuation/mmlu_moral_disputes.yaml,sha256=BtODeqXO2KvO0mqtU5TWppHyl6tj85pOq_NpVeMmd8U,248 +lm_eval/tasks/mmlu/continuation/mmlu_moral_scenarios.yaml,sha256=EB2nb9SHy3_ZOFNHeeubI5aqb4CK3UNkhwz_7uz9n3w,251 +lm_eval/tasks/mmlu/continuation/mmlu_nutrition.yaml,sha256=iMWv1FwFcM-Uvk3zRdiS6szWTpVu5yg1Azo5mbYOVCk,227 +lm_eval/tasks/mmlu/continuation/mmlu_philosophy.yaml,sha256=xYTVtyWLh0AvDBs0w1CMjBwAgmDtb-7RZMOcaPnsLns,235 +lm_eval/tasks/mmlu/continuation/mmlu_prehistory.yaml,sha256=t1fcNXFrj0WCm0_j4ZExonqg3yGWuAYvl8qy_xRv4ZY,235 +lm_eval/tasks/mmlu/continuation/mmlu_professional_accounting.yaml,sha256=nfA24g7A7454-UgLtcakQQ8_zFm1L4x7OJlEytfGV9g,270 +lm_eval/tasks/mmlu/continuation/mmlu_professional_law.yaml,sha256=EC3qt_Yzb0sx7foXnTNspCpDtjGPfiIFU47rKvBsIP0,254 +lm_eval/tasks/mmlu/continuation/mmlu_professional_medicine.yaml,sha256=DV08VBjMpF0pbc6VymNlxyc08-kwVcFjiCqivwmGHE0,264 +lm_eval/tasks/mmlu/continuation/mmlu_professional_psychology.yaml,sha256=vLlvygBgaGYexfKe1iDH8ucDO5CwEwxrrHmd-4p8YvQ,280 +lm_eval/tasks/mmlu/continuation/mmlu_public_relations.yaml,sha256=NncRHOjVXLxqBOfpJ94RNrks_4Bg5YcgmRqJGvGTPJ0,259 +lm_eval/tasks/mmlu/continuation/mmlu_security_studies.yaml,sha256=qDIF_O0kANgtVdiWs0X36aX_5X2ZVsObHNjxdu7jHQE,259 +lm_eval/tasks/mmlu/continuation/mmlu_sociology.yaml,sha256=ZPWSoSioxtQ--GvilGojhGOm7zQOtutzjtl1Q3K2BfE,237 +lm_eval/tasks/mmlu/continuation/mmlu_us_foreign_policy.yaml,sha256=uQUPxICrpiHnDpCYXGjdzBvKgp_2NPyp7rfqYh39QSk,262 +lm_eval/tasks/mmlu/continuation/mmlu_virology.yaml,sha256=RsnYUFuJZgDjFdr7gQb-TI9rGc9paUL_5UOu3ujhxvk,224 +lm_eval/tasks/mmlu/continuation/mmlu_world_religions.yaml,sha256=F7XfnLO2AcOpnKncR4dEC9vsbvdVoTwxKFs-UnjJaDs,251 +lm_eval/tasks/mmlu/default/_default_template_yaml,sha256=VHhd0G5-dPQWvb6bXSpBXSZIJJfTkMRg0E11s5loB3g,512 +lm_eval/tasks/mmlu/default/_mmlu.yaml,sha256=opYhS9c-LnKCQ0Uh8sMa7Z4gmoifQ3vlCeygR4ftGG0,92 +lm_eval/tasks/mmlu/default/mmlu_abstract_algebra.yaml,sha256=gXc19CgltUo07syBqIE32CnTjvsYCeVeWRG-KX1Fsz4,288 +lm_eval/tasks/mmlu/default/mmlu_anatomy.yaml,sha256=6GsRm5WgJy3WtuGZpR-rsTdpfO3uWaBjg2jqg3peTjA,251 +lm_eval/tasks/mmlu/default/mmlu_astronomy.yaml,sha256=BKfcrmOQeIcmo9WfGbvm79C3W3rpmYlH2WXfCwMd41c,259 +lm_eval/tasks/mmlu/default/mmlu_business_ethics.yaml,sha256=adoNOrbflZ-pgvnL4k4_2SeQwSDoGVEpR6sD3wOAabE,286 +lm_eval/tasks/mmlu/default/mmlu_clinical_knowledge.yaml,sha256=rtKNL_LHXj5ImTUYMuFTPsKbJvGaPHbxSh_EQRkn6TQ,298 +lm_eval/tasks/mmlu/default/mmlu_college_biology.yaml,sha256=tgJqKwkOinOadHJGIvA3fowTImsm5CesuHqNqfyuLL8,284 +lm_eval/tasks/mmlu/default/mmlu_college_chemistry.yaml,sha256=6-5alIH2bG-I5A1ToEEMPjNz8-uxq-WmOkHWVO84TFI,292 +lm_eval/tasks/mmlu/default/mmlu_college_computer_science.yaml,sha256=JdXWQW9JAOtR97ctqNpKM2yX2rl-_eoK1ozYBSqtlpo,320 +lm_eval/tasks/mmlu/default/mmlu_college_mathematics.yaml,sha256=p5Siknwp9HiAOfl2gazwbn65I5n82yj116ISRB6PFN8,300 +lm_eval/tasks/mmlu/default/mmlu_college_medicine.yaml,sha256=jhM79qmFR020H4fzazq5mEfxRsThQyMbEr9iEC7AiUc,290 +lm_eval/tasks/mmlu/default/mmlu_college_physics.yaml,sha256=Nm8Bjy5g3sh6PGJpOHj13ReRwGRra6zbTDR9Mw-T2BQ,284 +lm_eval/tasks/mmlu/default/mmlu_computer_security.yaml,sha256=WmKRHbFMgdTCeGFNdrIHfbTQO-OoUrFRR41jbeCMoFY,292 +lm_eval/tasks/mmlu/default/mmlu_conceptual_physics.yaml,sha256=nVXaOJWl0Jv0FFAxzDghiiGncQ9if4AdBdoeZ8vX4n8,296 +lm_eval/tasks/mmlu/default/mmlu_econometrics.yaml,sha256=kll9ZFihynXeCHB-IRvsB3jLGJZ7c7-H5fxBiGRx9Q0,293 +lm_eval/tasks/mmlu/default/mmlu_electrical_engineering.yaml,sha256=0-7WBd2UWT0wuK8FRdzFNb8Yk6519Ul2mHfho6Wc2sQ,312 +lm_eval/tasks/mmlu/default/mmlu_elementary_mathematics.yaml,sha256=c2lWRYGVEmrQO1_JbGUa9eau3SKh-7q59IqDkAd3GGo,312 +lm_eval/tasks/mmlu/default/mmlu_formal_logic.yaml,sha256=t13drARz0b49xLGotrVSkDR_GH3kHzqPT2jJ-kG_D4A,284 +lm_eval/tasks/mmlu/default/mmlu_global_facts.yaml,sha256=kK1l52luxT-Ib56eZddHw_9EubcuAEJU9zR239fvBOE,274 +lm_eval/tasks/mmlu/default/mmlu_high_school_biology.yaml,sha256=adPbtPDslRd6AuVjadFeKstNg4ngLYCj7uq7s3xvph0,300 +lm_eval/tasks/mmlu/default/mmlu_high_school_chemistry.yaml,sha256=FjJZ2bcdxHpwozh7nEW4bW1KZgwDg7sqG9lhi0Abd1U,308 +lm_eval/tasks/mmlu/default/mmlu_high_school_computer_science.yaml,sha256=FvmaIXBRroEyw8WU1vSA4BDWat9toiJmHvvXaqwUus8,336 +lm_eval/tasks/mmlu/default/mmlu_high_school_european_history.yaml,sha256=vgNEM9KbKZyE0HZiy7cWskYtU5Ox6D7WRNxAJNgiGy0,348 +lm_eval/tasks/mmlu/default/mmlu_high_school_geography.yaml,sha256=aPXicSifSye9Ut2wnerc-zboiSzOjYkm4gVhhiLocVI,330 +lm_eval/tasks/mmlu/default/mmlu_high_school_government_and_politics.yaml,sha256=iKZO88iRCTaEnOb1J4uuE2BICx9TyhRuBWXhttl_0nM,386 +lm_eval/tasks/mmlu/default/mmlu_high_school_macroeconomics.yaml,sha256=1LRd0Lb_U-ublgdMBoOo4mhC8srAdY-NBHW9nH68boM,350 +lm_eval/tasks/mmlu/default/mmlu_high_school_mathematics.yaml,sha256=ATgCLKhZn7UoNl2nDaxdBgD1y8k50b0I21WEmlB-cps,316 +lm_eval/tasks/mmlu/default/mmlu_high_school_microeconomics.yaml,sha256=cv2UrjcQpQe2rvtsMIDge-Ms59PjgPWGlznXJGlHwAc,350 +lm_eval/tasks/mmlu/default/mmlu_high_school_physics.yaml,sha256=sWPVelphJpPM9RWCoVTKiVNWuhdWPegLZZbGa80LDIE,300 +lm_eval/tasks/mmlu/default/mmlu_high_school_psychology.yaml,sha256=Q1BJGN6k_9bGk51FNgbMWfymVrcS9s0caTU7N3T5lMs,334 +lm_eval/tasks/mmlu/default/mmlu_high_school_statistics.yaml,sha256=FiVyJuipuzYEECJSWcm6HbCc2PJ3HS6sXO4bnO05bi8,312 +lm_eval/tasks/mmlu/default/mmlu_high_school_us_history.yaml,sha256=DFJcWsmxtV9HeDyFvPYCSxCAWywNSfXM5-vc1j6OOAs,324 +lm_eval/tasks/mmlu/default/mmlu_high_school_world_history.yaml,sha256=B4axVHntppczWuGGL6gQBhGgdukhqTX2Ga0kwH7wEs4,336 +lm_eval/tasks/mmlu/default/mmlu_human_aging.yaml,sha256=it0LUShyuG1o-jr-kdyhtOOWYFx20MuuVOCe9lhf2Hc,270 +lm_eval/tasks/mmlu/default/mmlu_human_sexuality.yaml,sha256=X-THNfrS2YzRDlv-2Ud7Zf8CowaIEmu3OxouK37DmkA,306 +lm_eval/tasks/mmlu/default/mmlu_international_law.yaml,sha256=_FSWdGN6SvDlaT88kQsGtj_7kuqzvvkGVLlTiPBW_lA,304 +lm_eval/tasks/mmlu/default/mmlu_jurisprudence.yaml,sha256=jFnFoZLKI6ANTvvH9cOCcM4DGJFtw3Xp2Cmd-wcMdxI,287 +lm_eval/tasks/mmlu/default/mmlu_logical_fallacies.yaml,sha256=t9cxs8hSQD7hLx8n_62Wsn44VCEasO83xzFF4MpJDOQ,304 +lm_eval/tasks/mmlu/default/mmlu_machine_learning.yaml,sha256=YzBbWm_EF49uRk_BjL-9DzgCeY7kvXWsPQRjwVAyDes,288 +lm_eval/tasks/mmlu/default/mmlu_management.yaml,sha256=43IDk6OZypE0VFm-2ZwkuVv3Arf6NzGgjdQNIeT0X3g,265 +lm_eval/tasks/mmlu/default/mmlu_marketing.yaml,sha256=32eH-SwcdzdbZMoiAI9GoUx_fRChoakuUrMvXZJ5haY,261 +lm_eval/tasks/mmlu/default/mmlu_medical_genetics.yaml,sha256=cBYQrC5cGxR8wtUhB7rfahBNpoZJ_xcIwvQrijxNQNY,290 +lm_eval/tasks/mmlu/default/mmlu_miscellaneous.yaml,sha256=Oo5UxK1to8hY2jdB83n9wTJnVJrAHNkIp2_n9wblioI,277 +lm_eval/tasks/mmlu/default/mmlu_moral_disputes.yaml,sha256=59Zv6o6ZAvIWM_NCdq6KTFo9-VNa9KocwHs-hPUNTOI,292 +lm_eval/tasks/mmlu/default/mmlu_moral_scenarios.yaml,sha256=JT2l_KMkk5g9tacrCPk2U67TSFU7bwxH72vtO94ELKA,296 +lm_eval/tasks/mmlu/default/mmlu_nutrition.yaml,sha256=gqbILA55_fbtqBzcjU9gCqPCdIAh6h-ztArvHRA5NtM,261 +lm_eval/tasks/mmlu/default/mmlu_philosophy.yaml,sha256=NWMWKylcBfEkIumwg6eRaJgKVqBpQ6blOMbyIvgn77w,275 +lm_eval/tasks/mmlu/default/mmlu_prehistory.yaml,sha256=g9KiT4SwWrzRlHSMMIEYSsTarhFNsuGyTFhNjd3BMrU,275 +lm_eval/tasks/mmlu/default/mmlu_professional_accounting.yaml,sha256=9lcnaGxlY3IgmAPAhvvXjrMEHmYUROCVPI8jsrpOP0o,318 +lm_eval/tasks/mmlu/default/mmlu_professional_law.yaml,sha256=fHnaxASjlkxSWtAuKVfr0sI-6AEm83vN2aEZ2-HShT0,300 +lm_eval/tasks/mmlu/default/mmlu_professional_medicine.yaml,sha256=e-JGsjNQ7vcJxMeW1IgYSE1midCUGhD87cs1FVT7dMs,310 +lm_eval/tasks/mmlu/default/mmlu_professional_psychology.yaml,sha256=VrF-mtFHcGOUBOUseGjvUoKgB6uXRi8y3g98xG5SrBA,338 +lm_eval/tasks/mmlu/default/mmlu_public_relations.yaml,sha256=LPamTE3llnQCW25KM8TDzHrkOTIFBQzoOzO5E1I22qA,310 +lm_eval/tasks/mmlu/default/mmlu_security_studies.yaml,sha256=zW3wJTXMpc9WoQpOy6WLZc7uVoq7MUkAN6CDQqg505s,310 +lm_eval/tasks/mmlu/default/mmlu_sociology.yaml,sha256=E8v0YKlGUe-gLWjmxgKRAZqrjKQ2NKFENw25wpdIQdE,281 +lm_eval/tasks/mmlu/default/mmlu_us_foreign_policy.yaml,sha256=jOXbTYPJayVwvMeIqJdRWxvH3DnwwyBKsUoUzgcOKC4,314 +lm_eval/tasks/mmlu/default/mmlu_virology.yaml,sha256=dQW5H1xYslCMlYJ2im-8x5nRs7zudCRW1QxaoCts1xc,257 +lm_eval/tasks/mmlu/default/mmlu_world_religions.yaml,sha256=sozIm5GYbF1z6K3M-DZZuYeIuXoGlfCLdU1dG-g0mi4,296 +lm_eval/tasks/mmlu/flan_cot_fewshot/_cot_prompts.json,sha256=CBR4SFsdT1HgEwXhkRPw46Ro8tx4dZY4aZjiKal7CWw,218396 +lm_eval/tasks/mmlu/flan_cot_fewshot/_mmlu.yaml,sha256=AmkVICAMmJEIwTs0ULG6QxkUQBTEwYvcCVkzXsNeCmI,177 +lm_eval/tasks/mmlu/flan_cot_fewshot/_mmlu_flan_cot_fewshot_template_yaml,sha256=PDJI1fayMgTeDQJ-_fpPFT4MIxZSolufGrW5Vo5JDR4,873 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_abstract_algebra.yaml,sha256=ON8FC9psezdwJg7AbfrhQOI_NiLEVAbHUJGqbdMUtY8,3439 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_anatomy.yaml,sha256=0vaQlTz2p3MemRxfJgIr4Rt-VAdPZbdRQ5vnwqdvOl0,5061 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_astronomy.yaml,sha256=IfTpiggJKOcIXY7MvrM_foReAlJEzHcGh-hc5S06LbM,4725 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_business_ethics.yaml,sha256=Wsl73cccbF0AsJvnBKdeh-vV1nLMh2beXT-9pspo994,4911 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_clinical_knowledge.yaml,sha256=eOYr8nrOvojGRcDK8zXX7hV0GBpMb9cdyNnEhTJv4no,2902 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_college_biology.yaml,sha256=0GaNoDGAwnWZQPA-UQqfaj9c-t45DPxc-tKzIyyHFiY,5195 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_college_chemistry.yaml,sha256=ewM_QVhM0DRfgzYDqliXg-w7hGtJeqfuQCOd0nvUThk,3239 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_college_computer_science.yaml,sha256=NbcJH1_US7FAaz67rw0RkiEwKqXMLoOrPbrtnTeEb6Y,7036 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_college_mathematics.yaml,sha256=tfX0rcD5QwxH5LmsyGK3wqBG_NUbmZJrDFgUV9So7bs,4333 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_college_medicine.yaml,sha256=aL0d_OKo17e6hEQNwbTEhiI30YjZoINK3uMClu7M31U,4609 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_college_physics.yaml,sha256=-IFKgl6D06TpzCtN7W-MO1cdbJ9RWqTZci9YnujTvSo,3717 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_computer_security.yaml,sha256=_sJTtifaTGoyb5yyZ80Sk9CMvURmgrx7iuqTOG8p0Uk,3056 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_conceptual_physics.yaml,sha256=MVctnRis0MgVU4SC4Ug4YRr5ApmK2gqszFkdFCc-Zek,2811 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_econometrics.yaml,sha256=-SLiSHy_ad7ZNBKtweXtefTTxrAcUOVeMXRGu19TDD4,5538 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_electrical_engineering.yaml,sha256=iUB0DwcRGJ3R2e2ciKA_VFf30YPg_YZsjhEAYinCnf8,2916 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_elementary_mathematics.yaml,sha256=V42htFj0RjhdL8OlbGjeJWa8Ju2c4DZG2kZ5ZRULRDY,3506 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_formal_logic.yaml,sha256=zs9nPe1Ru2us1mTepLx4mc83nxTWfwvajKYKwcRZLGQ,5116 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_global_facts.yaml,sha256=2ZRWVomWRyUyUqFShgEutE1H3NVXuNmdD0o9bc2iQVI,2835 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_high_school_biology.yaml,sha256=psAMuPOPMhuc4lHCw4KsJvnddHHartP4fbdnv4dPl2I,4785 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_high_school_chemistry.yaml,sha256=AH2YQeDqijeKvl9PGFNO1qL80Q6N8v-JBoc3FgYuGdk,4330 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_high_school_computer_science.yaml,sha256=QRYXWHE_I0XBrZJvEuDdOO3zWa1pSG_xzOXIR9fRmhM,6101 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_high_school_european_history.yaml,sha256=u2pDblJguMp5NK0wOy1kHTRUhMgLIXIXU2UXQG3Bg3U,15062 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_high_school_geography.yaml,sha256=Ls_s_bEVs0T8YDjUMEod2xMrYCfdOvHg7Uuzkrapt9M,3206 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_high_school_government_and_politics.yaml,sha256=vpJRM_K8jbqcJE-LYJTej9y_f5wS6IlQLC5N_6RuIcQ,3708 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_high_school_macroeconomics.yaml,sha256=gmpPZ6eDBQNSaQ1AZGPhBWAnaHEcjQP2mYYHWD6uK1I,3177 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_high_school_mathematics.yaml,sha256=EZJeyKwB6A7TrOiKQ99nZ_3dO-S_5MX3a_UmCeUHggU,3103 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_high_school_microeconomics.yaml,sha256=5KmuL1pTTc1xQg-TdrmMDJBlfYhk900SzQkj37jdr0U,3374 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_high_school_physics.yaml,sha256=zIu4Qyjw3hC1q9_WOYjCT1gjtXV0sXQ8YHeovZNZ8AE,3342 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_high_school_psychology.yaml,sha256=HMVzA-tghk1v9x6NdBvGRS750bI8hPM8QpANESAQh3A,4133 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_high_school_statistics.yaml,sha256=V9UooCeal35lBM13OxKtommUBWSqn-4vhiQE4kdTBnI,4955 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_high_school_us_history.yaml,sha256=pCrC91jY2GIbyFkJMnEo1Y98RdQJCrIfCVzD_gvcD5I,11949 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_high_school_world_history.yaml,sha256=3jT-qctZ-mTD-aAyI-PXXsm6n5fQfi5zaemXtZjDmOY,7286 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_human_aging.yaml,sha256=W_lR6tQcSmuIYlMViHJJiOZj8IeHe3yXCbcEtR-Gqeo,2291 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_human_sexuality.yaml,sha256=54YOxftk3lZ-8caDd5XrA8sOEvJK0NxBCbz8w3xYS4U,2848 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_international_law.yaml,sha256=uIwurqyHVAyDdBeVL-vtdI6_QKCjUG5ALg9cZG3Ru8Q,4658 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_jurisprudence.yaml,sha256=m8JRvA_-BqF8QOqLhAmoRRVbWeoJwFKctD7A5N2jmJ8,3815 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_logical_fallacies.yaml,sha256=qxXc1uWE-cAlbVZATQgeQBPL50-t93H8p4u5pYTTW6c,3791 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_machine_learning.yaml,sha256=uCMuXE8QJ1FliQ9Cd02BW1tkBj6Ms1eLtvIkV6hyBik,5224 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_management.yaml,sha256=eZfEZfZ197oSIhWopIofgxd8Wb8_i7ZI5ia82i-LiYM,2757 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_marketing.yaml,sha256=gzDYU8VXPZ3uQhT0gB4RRwp_IIDS2-hganfF8lVRhMo,3413 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_medical_genetics.yaml,sha256=g0r9WBDPvBNbjOF9r08vWXpL1XXa-OW5O6_0Q_a4NqA,3092 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_miscellaneous.yaml,sha256=QtjVM11b1Q_2V8ucDIHPoGeJmAi5a40MWmKYj2RkNj4,2311 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_moral_disputes.yaml,sha256=Qo1U-ChOi6HECRQmHLMKy9kNELC7v8wQCp-ifthhPyM,4156 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_moral_scenarios.yaml,sha256=fq9EcgDdgesBfsb2XsDZsdR96A71BSsc5vkClTeDa-M,3754 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_nutrition.yaml,sha256=YU1YGstOt684w5UjnbC9ZBwd4d3Soe4_yWPRpitizgA,4038 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_philosophy.yaml,sha256=Z0JJJlH5DIW9r9tKKxQCQBFIKgHQUzHnHCqrmKgaNg0,2549 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_prehistory.yaml,sha256=6N6ILCNXJI4EeJvB6V6lNL6rNAMHgnOBTHCvHntCXhE,3591 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_professional_accounting.yaml,sha256=41FqBGRmcDqvKLLLut8DtCoKowVnJ6sFguAYKwdiSUo,4079 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_professional_law.yaml,sha256=1-loHncewMrCvF4iYfjnr0UC5yMWkcAs4Azhvkm-L0Y,9160 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_professional_medicine.yaml,sha256=rs4ADif90JT-SHZGadoxLmbzdepj6mfmg_ie4OU_fkA,6140 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_professional_psychology.yaml,sha256=k0ygK4rYRTwJ4U_XcV7jekwVS4aFqpnLDyBMfHx6t70,4163 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_public_relations.yaml,sha256=fWI5gYc3-JdDUfOO4wyxc3-y12fRA4UaXXkmkN5RBPk,3289 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_security_studies.yaml,sha256=wUgw8I_dv7odQwxi1Q-yJLYPt-I8w-DWUmJuy55BFTw,7485 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_sociology.yaml,sha256=9MUafLUjDZwk-0-vXBVtOhH6QlQ8t9I-9q8vzkqJNrQ,3605 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_us_foreign_policy.yaml,sha256=MiGgfxJkOe-vber1E7gU6pWpzDIezgN_ugjw2Rn9eoM,3416 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_virology.yaml,sha256=i64Dd7oqE0XhsoepiQPkUPQyQOYVn7u4JWtq5hXJ14Y,2571 +lm_eval/tasks/mmlu/flan_cot_fewshot/mmlu_world_religions.yaml,sha256=iOr7ApxWEcC01nuHnvs-YpNCOnr6oWHgCYEjQ4Ji4BU,2241 +lm_eval/tasks/mmlu/flan_cot_zeroshot/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/mmlu/flan_cot_zeroshot/_mmlu.yaml,sha256=_hjjoCQTWOlz_f-ldxYlK9RWpKnbHjOn8KlwNjLhatg,182 +lm_eval/tasks/mmlu/flan_cot_zeroshot/_mmlu_flan_cot_zeroshot_template_yaml,sha256=e7N-MDTgv6mAhrECVqHErSsOZeaRoExHorPj2J_MmWQ,1196 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_abstract_algebra.yaml,sha256=LvRnHFrHw_6n24MAe5BOixVezyZ0ME581aHG7yDSn7E,284 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_anatomy.yaml,sha256=no8v8ThFcdjNjCqBkFZIR1--Nd4ZiCZoa-L825u2rLM,256 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_astronomy.yaml,sha256=hN2iIJ1PmHloJCm9C2dAQRAc6XqBwxUGivaiUaq6-kY,262 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_business_ethics.yaml,sha256=XWfFMMiwK8hhSNKkuZs_JSBeIHkw4evEM02LIKhAuTo,282 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_clinical_knowledge.yaml,sha256=e5KerpASf1oRCJLvWqvGHJf5ZW04jrqmA8yzpY4RMt8,291 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_college_biology.yaml,sha256=v2ZXXWAltVye0sdYDsi6vE70kuW_3b9wsyZ75UuuZsc,281 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_college_chemistry.yaml,sha256=8X67aXlo-viUOq4ZVbWrgEo9ntqi0lNWHqtMpDr-0AA,287 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_college_computer_science.yaml,sha256=5h-Qt7ndBtlJG5ZfSbY6caGMCbQrsyWc-MVPxncDzuU,308 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_college_mathematics.yaml,sha256=Rf_ZzZUxQ0oOct1pg1TXi_dsRUZpU7WkcmQviWHoXi0,293 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_college_medicine.yaml,sha256=fJ--DO7NIxkwa2ica1QbsdlIn12616p8PqE8EauaUlA,285 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_college_physics.yaml,sha256=9bbIfyxuil3UIY-jG9-Fvf3ywmwdMo0titOe-M-Dt6c,281 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_computer_security.yaml,sha256=nXPVQH1xVJtZt6_2FPiC626QoXGaRY01f2AymmhzQ2Y,287 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_conceptual_physics.yaml,sha256=WrfEys3YyQF6s8otgNvTjD16LDKZk9BhvyW525ZIj84,290 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_econometrics.yaml,sha256=ygr0_Jh5OWxyixszzr35NEie0PudCTADqRpjpMDThrA,282 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_electrical_engineering.yaml,sha256=hciTVSP3ckCk3RwC0PsB-J8Ve4wHyj2xusA8kEPzjy4,302 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_elementary_mathematics.yaml,sha256=9DH852QpJPBc8YgxNvvCnnq5nwTDVNcLqU4BRxrSiBA,302 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_formal_logic.yaml,sha256=58WVxXMCkazivwYFoZQ1Yb84Z991OiU-vQI4sbtJUXA,278 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_global_facts.yaml,sha256=RM_pb6sRZmx6iVcFXAiYbYHn3gfXAeAvodBwVKd25zc,273 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_high_school_biology.yaml,sha256=0DnTWb-KtU2zFX-QFM6s7XKKouwT2nfyK4fyS_tioyU,293 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_high_school_chemistry.yaml,sha256=heKA8_U1wj5P2q5roXMqwAWiRa9v-sbZaTbe-hyP1cA,299 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_high_school_computer_science.yaml,sha256=DiOmq-I8_p3DVOUhtFgFjijtG0-J_MRa8F5-cIMeOXQ,320 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_high_school_european_history.yaml,sha256=3OffoLG-gh2JjKcKWntBWFEjc5lrSgOw-ZFwtJPgFJw,326 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_high_school_geography.yaml,sha256=Fd0I-5A7mltjnIF0Md7fQLY6YyVOoonsdc4txxNNZsI,310 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_high_school_government_and_politics.yaml,sha256=uimHeblbJFYgaaah5fsWTQl3_KFZdvDTGmcdviqD97E,352 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_high_school_macroeconomics.yaml,sha256=3dhl58MUaawpSYJFfvelXVpKLcVBbDE9MpMvAT2peKY,325 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_high_school_mathematics.yaml,sha256=aRQK4pwDayZ6xNkOEqytHjJwxyI2nsY_9QOW_FAL6ok,305 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_high_school_microeconomics.yaml,sha256=ZKQPAubYaV9HfGiJFvENELqyTLuFvG975eBGmn5USlA,325 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_high_school_physics.yaml,sha256=7u1ma2j7itc6SdgSwlotC4Qs3oovbmQMCldOuUWtwGs,293 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_high_school_psychology.yaml,sha256=cMvGDf1fcB4btH_AlHeZ727FWVPB8WIvUDi9jP7gNiM,313 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_high_school_statistics.yaml,sha256=iolnReJzl_eeTS3iDnhz3NiEn_GNeNW9_hu6Ba_CRA8,302 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_high_school_us_history.yaml,sha256=TYckw3h7JfcP5tq0X_k58pyk3ph07f69WyeAqRxmcGQ,308 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_high_school_world_history.yaml,sha256=z6JcOncyLPzV2cW9Y1kzICK9I8c2V2KGa5iPgYi5XJ0,317 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_human_aging.yaml,sha256=Rq1oksitbFhGyrgN0H7fHTW_PGwKraphFEE0-ZDzW2o,270 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_human_sexuality.yaml,sha256=XlLHhllCiErpFvV8u4_erECYPiU_sf49IZ_q2We1Ulo,292 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_international_law.yaml,sha256=47Y_4EVkuA8PYyLDZwb7PcDgAoVjJhxQGV6uH6SksB8,293 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_jurisprudence.yaml,sha256=62o2fgoKLVpHP5_L9l8dgGSvKKvjydg5amyUuPSYDSk,280 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_logical_fallacies.yaml,sha256=UmcituDQMs9_WgxnQl5TF8zjzqG19RZylKe8yH7AioA,293 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_machine_learning.yaml,sha256=GEzsjkMBTPDAwwfOocJ1fJ222Li9l2Ly_SwuKcaKJEU,284 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_management.yaml,sha256=DvBGob0qxl8O_Wgpmy5EdFMhgjuG8lS-Oswbbe22-Yc,266 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_marketing.yaml,sha256=iZSiPqmRAwN-sQk7rGYiXxQb3_-AzRtZWnYhR8mKMGI,263 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_medical_genetics.yaml,sha256=swY2eauXtpqf2acrcAPRBsuS3wUm8vrDezRhuvAeEE4,285 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_miscellaneous.yaml,sha256=ob2TmbBUTu7eiaqKVvsdPgm0QwF9TzAsVvVHzuO3WcM,275 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_moral_disputes.yaml,sha256=N64E_YN5-Es-RkaLF83OwxE02nLP_JqOtBNdhL6BHKs,284 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_moral_scenarios.yaml,sha256=V4-YewELczcHXVhShtQJZTucYeeS9vVMcHR3UMd8RyI,287 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_nutrition.yaml,sha256=uEOLbPIzTJ8XBGUhnTeqU-5OYBkGsxLtVM_cS4dZjvk,263 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_philosophy.yaml,sha256=IFUR_93hbXyYXAzQdwJoVe3e9Qwk4H0_c8z0NGII-z4,271 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_prehistory.yaml,sha256=4J7DeKI8Hv6zQylMhwi8Qc8B8Fq-Caumx_1vwGsnt4c,271 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_professional_accounting.yaml,sha256=2kCLdxKouQcWr6zg1uZM1PBqkFMSgeZZNzqG9DxMu8g,306 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_professional_law.yaml,sha256=xbDsyiFwhZZCPM0jEkguzvSRSeq1tutZynuhlg3lgxo,290 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_professional_medicine.yaml,sha256=AUI47eC1j6rc-9Zqp0GmHYLbDHg1O7GVKY8Vv4lYMXI,300 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_professional_psychology.yaml,sha256=7TFjvuSpZ37wDEtdtf1NjYS6mTXuqwSSH3t1OHpydME,316 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_public_relations.yaml,sha256=DAjQj-5aG3dZHCXI2Me1hnix3QlDZuS1ZuHplywmH_Q,295 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_security_studies.yaml,sha256=DC__nJv6cZIgeWk7uUdIPpoIVkCDDT9dE802p8fC1XE,295 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_sociology.yaml,sha256=uEopPjYfP01SXyue-UDn6Eu6XJY0giXJuNJnMW10hdc,273 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_us_foreign_policy.yaml,sha256=jAEfmTK_piBJnrhjK5D1LhCTZaOjCr-3y6D6_RPtk-E,298 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_virology.yaml,sha256=74_GviIJbl4HRinvOOrrMx2_LqW0prHZU1jsJVSVRfw,260 +lm_eval/tasks/mmlu/flan_cot_zeroshot/mmlu_world_religions.yaml,sha256=DVS8P0bKnD8vBNxCMkzy6N0eWVIyQ1XpTBIA71JaELU,287 +lm_eval/tasks/mmlu/flan_cot_zeroshot/utils.py,sha256=LXwOcOnyAL_h3VRE0XzM66h2qJuB0zK1zhrqupg4jpA,4184 +lm_eval/tasks/mmlu/flan_n_shot/generative/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/mmlu/flan_n_shot/generative/_mmlu.yaml,sha256=rA9DgApHb_PGaMgMqEP2uU9Qoz7GWjMa8bzJgqTL9Ao,207 +lm_eval/tasks/mmlu/flan_n_shot/generative/_mmlu_flan_generative_template_yaml,sha256=qpTENh9RBRfYNEMIs_hx65NqM5_HAYIjRW6qEptq2q8,967 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_abstract_algebra.yaml,sha256=1yvdHaM9GTcNnMaDV7pV63E6mcZv3uoS2Lgj1IqHlvE,292 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_anatomy.yaml,sha256=NtroH6VqEdaJd8HiWr8a_GJ8GjMUYlsPpre0T16P-O8,264 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_astronomy.yaml,sha256=i1KgW-h2hbODryP_NDY6oZ9MpGEilsP6z3W-MkXJbzs,270 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_business_ethics.yaml,sha256=fSuKzPYSkEd1TmMMLSV9cnxNZTWFeYf0tvdmLZG72uk,290 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_clinical_knowledge.yaml,sha256=5_FghB6ud7daF4EeflUG9UqWgLOfT49wto_Ld8E7zaY,299 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_college_biology.yaml,sha256=15B08EN2JcsLE1noz0qeKS-eSwZdTN6cxLXEgohzphA,289 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_college_chemistry.yaml,sha256=y3qKzzecqo1hb7-huA-XwLJHayoSJo2EvODr8FCpszI,295 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_college_computer_science.yaml,sha256=VjBnBkAvbVCL1h0BgFku51ESFyDKpXt3TkfQ8kqrhps,316 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_college_mathematics.yaml,sha256=AIosK7NMiKx-XSj__nr1djX0fxFBZBEkuqYgatPCyO4,301 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_college_medicine.yaml,sha256=RGXU5iSNbbb8RDCH3lcg1n23cCHYJ7s97pmH5KcRcbs,293 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_college_physics.yaml,sha256=cB9KDjCKPCNmojsXBbvJXP5K79hCehb2doHdcb4x8PI,289 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_computer_security.yaml,sha256=z91MJa2RV1B2m5decq4nSUWAf4Zc9SM9wBcG5aFlEBY,295 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_conceptual_physics.yaml,sha256=Ls4ntDkx7V3N3C3dMJ4SGHqga_UXKAufh447yw7Fjr4,298 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_econometrics.yaml,sha256=wavgGn2qhGXRwgcZGFeeXaJQ5fEgjpReY2YSOUhwjVo,290 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_electrical_engineering.yaml,sha256=kPiAfHTJxHyWTIDdIv_IcXdkO2bGQ_K3AyYpHXsi224,310 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_elementary_mathematics.yaml,sha256=h8mXOss7r4hG3CUmE5vunwm1l2I9SJIA2fGGV7xami0,310 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_formal_logic.yaml,sha256=GjvsAUaRAdnOcA-yF86D6DqNzsoocIKs-ZJ_hAtpQLc,286 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_global_facts.yaml,sha256=59MQcBeGFepYvfZXcJUb9gTwnpuzzFBU_JK8vQHb-9c,281 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_high_school_biology.yaml,sha256=vf9s2eai7UIFUyX5N_H_RdRPSvJoyMKp0L6zu3HsUmM,301 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_high_school_chemistry.yaml,sha256=-hzx3wvYQcbJ8pLmInAPmtT8eErwFH4Zv4S4eN8icqw,307 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_high_school_computer_science.yaml,sha256=A_to1N9TFCJUroTf0Mkt9uvCpS1E5wewxbYRYwGz70A,328 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_high_school_european_history.yaml,sha256=FJsKuJAJLePaKKjAQXQC-uUDMmqdGiOJsSj9-QVSXD8,334 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_high_school_geography.yaml,sha256=DLoXYBsTwO8lhN_0VkTVowK432A_vcDT8liAwzM2DgI,318 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_high_school_government_and_politics.yaml,sha256=zkOAZRnm9OKThUjZCxecDg6nmmS5II5BQwTgsU_QLyM,360 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_high_school_macroeconomics.yaml,sha256=dTW4bwdWf65fEGJGRReq-uXz_pueuPu7LF7CiJegge4,333 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_high_school_mathematics.yaml,sha256=jZ52HsQ41J__WPLpdX0rJ7DsmXogBQKV3kSCw8Tt53k,313 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_high_school_microeconomics.yaml,sha256=_sgnl5NyQJhHurnRCW57XL-NTeoQMnKPZ8itIwDQuWo,333 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_high_school_physics.yaml,sha256=lOGCUibImDUaLkcuUxGQNlz5OCmEIyZyzP3FsfdKYRU,301 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_high_school_psychology.yaml,sha256=_frgKmtOaJ8ErEIJza95nJKM5Q0R3htRecVFwilhp8s,321 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_high_school_statistics.yaml,sha256=v53JtJ26tGzC95RlCw_opPG4exyOkkx_y1yjHastn8U,310 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_high_school_us_history.yaml,sha256=PSIL3rSUv7ZzYFtgBFe0tUewvezZKcYPjKddnQ3YUAo,316 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_high_school_world_history.yaml,sha256=qdgwmHUDV_h-6bg-3Sd-V6R-853GKuFSYdEW8oJgJ5I,325 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_human_aging.yaml,sha256=ZxDBgT2TgFQF-63ngbviVbf2QLU9S80toxTvx8BdOdA,278 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_human_sexuality.yaml,sha256=NcBQkkYXnmdbXD6nRMvUBPwjWhq1o-rvhQfMoGnDy78,300 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_international_law.yaml,sha256=ao796oJ5QQV14NJF_SNmn4yPiaJtrEXPA0FYASqYbAk,301 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_jurisprudence.yaml,sha256=p2HnBz5uURlZzBkxSJ_Tpr_Sm5-jil6-VsHKjis92sI,288 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_logical_fallacies.yaml,sha256=o9gAvTyAqPRrWWCtjgSmW7ZkpqpTsfl-NSbbQB63vik,301 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_machine_learning.yaml,sha256=s0f9zROAZCQmLvjzn42ilUEKlxFQQXQ6GCihZ4pxV4k,292 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_management.yaml,sha256=pQ94zduNfbbPL1QIjk2gTrlPCzixwsrbfF04tKdld0U,274 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_marketing.yaml,sha256=QbLanX10QvNCywzqs0kdP2hpHlQ30KZdVY6MAWMUEQI,271 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_medical_genetics.yaml,sha256=6Nl5znhGU_FNHFKS231zgtCyouP4eOp6-g0bXQmff6o,293 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_miscellaneous.yaml,sha256=KG80mJ7vNJ4zsHb0PDOsGcKec8ykpx4gC-o143_ptuo,283 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_moral_disputes.yaml,sha256=kXbaoymvejb7oefSyWyeH3r30PephinHlpZAx3VXAac,292 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_moral_scenarios.yaml,sha256=zwgvbGMMQalh1wCawRI1dCQGaF9Od8j8QhRUcPL0-9g,295 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_nutrition.yaml,sha256=9dWTdoG1hszD9N0jZ5CffA3cRZemzUzp92M7eTeK_7c,271 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_philosophy.yaml,sha256=RsvRfjp0ChZ-IdKeX-r2b-rZ3A5Y4iLZMQLZo76qZ5o,279 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_prehistory.yaml,sha256=cM1emeZyw2J7q9KfPME9srhywKlh3jeY-zsDBlEDrA0,279 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_professional_accounting.yaml,sha256=aMU1t4XwG5vwf2OTHNR9ESAe6qLrShwiyvCAvcaVDTA,314 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_professional_law.yaml,sha256=JqF-iVfJDIcbmpJmbcLI_AZUmOmJ-BBZyWAXprZo-Iw,298 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_professional_medicine.yaml,sha256=ONirmEFURyIxoW-_TgbHwS22GabhFQT5zEtiZ-rHFw8,308 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_professional_psychology.yaml,sha256=91w04tA_ZLH3i7KTRj4X-UiPkm2Ka3fDpoxp8e26EPg,324 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_public_relations.yaml,sha256=JPZD6ikfbzdqWqUGYgldmhFk3jWjK6Jf0CMV1krM00U,303 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_security_studies.yaml,sha256=Plc_zyI9zels3rzux8c61ntFGEhkBgVteuGcSP7q5pc,303 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_sociology.yaml,sha256=J4crNd6OLrze9gPYs8e7X2sa_UHaTlyOW_IdfCE6dVM,281 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_us_foreign_policy.yaml,sha256=RiU586npxXTRbADdtzimeWVO5Tgugzx2APR1bYdrldE,306 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_virology.yaml,sha256=gJjpjsnq4o29JG8Wm7S_w2rNnXfaGNeiBM9JHii-z0I,268 +lm_eval/tasks/mmlu/flan_n_shot/generative/mmlu_world_religions.yaml,sha256=9z67Jvo2ZIiC6RZljrfmHIgQbgg2bg6RmV-avL2Np7A,295 +lm_eval/tasks/mmlu/flan_n_shot/generative/utils.py,sha256=LXwOcOnyAL_h3VRE0XzM66h2qJuB0zK1zhrqupg4jpA,4184 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/_mmlu.yaml,sha256=eZmG3GH5XHcg2Um0AY48VcbyNko70mvn74jyAlaVO6Q,222 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/_mmlu_flan_loglikelihood_template_yaml,sha256=hHgxqOuDbr27vwiZWvaZzd8tOS5klCTN4XfBOOnZWgA,519 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_abstract_algebra.yaml,sha256=JcepUKxIK58D17T9G65iGW2_18TBrueDXW6TUTMkeOg,301 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_anatomy.yaml,sha256=M8dCqotxHdLIww2VBqefZ2FMyafsQrjJ0wFLZKBfBhQ,273 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_astronomy.yaml,sha256=JUOVz5iR_W2T70F5dsoqhJID57FsqVvy-20NVbpNk7s,279 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_business_ethics.yaml,sha256=mA8oqguvp6QvpKp0StJhzhrk1MVhRLcqLOAMu7lYJrY,299 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_clinical_knowledge.yaml,sha256=o5TndzV6N2r9TCxwDYSgT9sIm-6vPuR4qM-alkmpMHc,308 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_college_biology.yaml,sha256=ZC-C06eFQx6-e-uQqV_m9_FoqFYQJcNJhR8uzr_6PKs,298 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_college_chemistry.yaml,sha256=Tfn2eN5PchlmGXbv5yIo69IhyAyaxcM1ny7GUl5xQdM,304 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_college_computer_science.yaml,sha256=_f-C1bo65X3VaaiTUX7xbMP7vt-WDdbLpp0BmRejcnI,325 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_college_mathematics.yaml,sha256=N4odAEwLmUbH8TCuZoRVDi6Td0aFOvZiaLqj85uALbA,310 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_college_medicine.yaml,sha256=JvFZV8TPbtcTWZdNFZj2vNbAYGgTaHsXW3nEougw5tg,302 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_college_physics.yaml,sha256=jo1UIxG5LMUntQImHZOy_nyTKq-GXTU49SKB0ida9Bs,298 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_computer_security.yaml,sha256=EDtjcLB1t-RRSbxhcLtOoU_M6igCrulG6WXXId41ojM,304 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_conceptual_physics.yaml,sha256=b_WyB8h4CdpSR_AB9YIi-qWhmZ_c8C5q3xSapgiKJ10,307 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_econometrics.yaml,sha256=BSRJs9f3ZqIjem-nVwV9vQMreES9feb9T6wFhVvdKEg,299 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_electrical_engineering.yaml,sha256=ZShFd7F5Jwu_lAjgfM-PuY2ozxIMG3d5dUY5JFOTawY,319 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_elementary_mathematics.yaml,sha256=6o-J_HFMBJxby9mAL9SQKqWc8tqLjD8uOk2KuGzoHos,319 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_formal_logic.yaml,sha256=lU-FKxcMu-TRb90W8xUNfVGFYGrllu2fZdEpCFf6EDg,295 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_global_facts.yaml,sha256=80WmbweqPVCO_cpGRiHOd2Lq7gs8YXCZFDhK6bYFM1I,290 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_high_school_biology.yaml,sha256=B7JadVjlfqEf7kHZUlLkB-y5nNI-F8QAbIXTcW8VzWk,310 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_high_school_chemistry.yaml,sha256=SndHfC3jHbLvxnn0epkwGDzR-P130ydmPdFOBeF2nrw,316 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_high_school_computer_science.yaml,sha256=LD3G8CD4FfROuowWGKGHIJbYHywFMShzYaGts-qYj-8,337 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_high_school_european_history.yaml,sha256=sSeqe0Wjmd5zM88U919BqSNjtev1YxPx91Oi-AgfYB0,343 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_high_school_geography.yaml,sha256=wJXdyHrRtnk1X74C-zaxLFPapAf9k6lfcs0CMx1481A,327 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_high_school_government_and_politics.yaml,sha256=zSf57FSAO3oGn9t6A1HayElNNV2nFFiLeq9G1zKQdB0,369 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_high_school_macroeconomics.yaml,sha256=Ps14NQcSkw-51Xkp4LrfbF6yaSOVmqkgBB5weV4blQ8,342 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_high_school_mathematics.yaml,sha256=kjAJdrD5xnuC1gzihpi6fIV8bvbGD8WsRLchv031KnU,322 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_high_school_microeconomics.yaml,sha256=44F_tk2wWRO0apBp0mYKTfhL2sbhDc_g7Wbb6H02N8k,342 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_high_school_physics.yaml,sha256=8rTaT6AghgeMbLWF22ggFDk-nVMHqe5ry43UMf80Mfk,310 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_high_school_psychology.yaml,sha256=L-BbP9bwKtwlM8tU8tzWpoXBHmrkU2J26hr2NJrgE4I,330 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_high_school_statistics.yaml,sha256=HAa7oXJk_XSsH4Mszh0NUm4Nbk23kNO_dceDb3g7N4U,319 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_high_school_us_history.yaml,sha256=OR5zL4Hl9iNLvZpEu5wXOmNotONJ4pH_y2ctB9oXvI0,325 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_high_school_world_history.yaml,sha256=ViGuBIotR__zGTOl5UwHo8nm_oJh1q_NSMz4tgyuuL4,334 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_human_aging.yaml,sha256=YeJJq0W__tqbaepHioIw3OX3VrnVP78DXe1Ad9bJuiY,287 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_human_sexuality.yaml,sha256=0uPvqtDwvaMrwma72VyIgLyGCebkfGTXKdyY9qZlBfE,309 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_international_law.yaml,sha256=PJwyJ6vN013gaoE-YAzKKEIJFgNxKgn7o_tAqDYluPc,310 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_jurisprudence.yaml,sha256=Bdm0dQT59IqMlNDtsTm8sdTLr5JRSOsbzxpoC9aosNE,297 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_logical_fallacies.yaml,sha256=GrPThYGviu6-qZm34PA1-jshpQW3n6pLEP0KRUzM_JI,310 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_machine_learning.yaml,sha256=cZWbId48tQJ6y1Ee4oOdFyUf8VZ7S7GKHRN5ZdI8hDs,301 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_management.yaml,sha256=LM8XjeZnfL7q_GT4nUaMdN5x-7oltDKnQnLXckHVHhA,283 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_marketing.yaml,sha256=bGRzIwmXwIjFj4NZvZAVuhJpSjjq0ejxiq7f0AdzhFg,280 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_medical_genetics.yaml,sha256=rcAgfCRPiD0fPaOSW3sgBQ79J4xr2_-IMuzdmExjwLs,302 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_miscellaneous.yaml,sha256=_UvvGFIRQu0IlTuiVMipxJWgGQ1ftYDJAn5NxMTNjQk,292 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_moral_disputes.yaml,sha256=oZ2jrmJVU_45JsAIXVtvy1M9EgGwa4FkCGNS665S2KI,301 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_moral_scenarios.yaml,sha256=8sQGu7QBQeRktXH0Vps2VqaL_uhoxB4vUkE0ahzsvcw,304 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_nutrition.yaml,sha256=lj9z-yB0vr7Lq5KwAhoHQ2DIj-e-PG6x2Rq-vKiOAww,280 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_philosophy.yaml,sha256=K0SABfuOOJw56wWkDP8dIsAtx2qDtA7pH5HrOqLOKGw,288 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_prehistory.yaml,sha256=xiRm5lVc15kt0YJhbbqUxBr1pMZFXn89LPTg123tE0E,288 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_professional_accounting.yaml,sha256=iRpn1-3hipcQYPJBXOQR9ssPbe65Xj1Ul5Xit5OFi6U,323 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_professional_law.yaml,sha256=OFeKdmuNzxg5tPqja3MzaMbN752KSgin2tk6hwZHFWs,307 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_professional_medicine.yaml,sha256=9J5E98RmwY89ilvgyneIRENEnbbYmtjuaYGLx2H0f2c,317 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_professional_psychology.yaml,sha256=aDJHxshQ-hwu2vaXlQwH0zNMEvlILDuvMTytJwx73GU,333 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_public_relations.yaml,sha256=6OHr5Yss7dKkRASPfRHOmerQHSTqiyD8JqJCdsVoHoM,312 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_security_studies.yaml,sha256=7qkuikIpeLq5nUTN9pWA3kKuWNltSbvmnJdD-JbTTJk,312 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_sociology.yaml,sha256=l5pj6wkbuGRyxZQP4X7BvdP6iRP6mo-CB8oA1h_E6Yo,290 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_us_foreign_policy.yaml,sha256=or_HHQBe1GhLivs6QQIGO8N7KIF1jRO5bjcIdcKHXk4,315 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_virology.yaml,sha256=3PrMJTV58aRj0IRmxAFP1zNHr7xaUzLurDx8H8tuC_c,277 +lm_eval/tasks/mmlu/flan_n_shot/loglikelihood/mmlu_world_religions.yaml,sha256=h9nw5EleAHMsACzveLJWdFM0jsdwhADgiYCZA-ibntM,304 +lm_eval/tasks/mmlu/generative/_default_template_yaml,sha256=MeYTKJXQPQRPQZTJ4ghpQK9hUhs50JXpyKM3lAOObHE,563 +lm_eval/tasks/mmlu/generative/_mmlu.yaml,sha256=2dzRsC__SGUz6FnGKgDkEAeyKWKDXfxcu1MCDT4oxsc,147 +lm_eval/tasks/mmlu/generative/mmlu_abstract_algebra.yaml,sha256=VZMd76VYw0AXnwIffvKZ5SBc1jnzxaae8QkI9VbkJAg,310 +lm_eval/tasks/mmlu/generative/mmlu_anatomy.yaml,sha256=61EtViISgfbt6VOsh_tIIy586P-9EpiBm-QskzOLUcs,273 +lm_eval/tasks/mmlu/generative/mmlu_astronomy.yaml,sha256=Dhz5_fr2BS1ZV8wQCQ4SReVsDOIpApHWGT5Czse9eYY,281 +lm_eval/tasks/mmlu/generative/mmlu_business_ethics.yaml,sha256=oQeZeMqJllBnGqrlIlH6uJN48VKft0GAdDvMAJL5QAo,308 +lm_eval/tasks/mmlu/generative/mmlu_clinical_knowledge.yaml,sha256=jUzb7-M7O0rFIRJhntZAYmLRiNVS3ZFo3IOB0Kfawtw,320 +lm_eval/tasks/mmlu/generative/mmlu_college_biology.yaml,sha256=3-eOsnWfGYHPyCZee1mmjoRwEnF8rW1CpMYX1gXDWig,306 +lm_eval/tasks/mmlu/generative/mmlu_college_chemistry.yaml,sha256=uXDU_tBCDP1gw_fLvLzHWXfjbg3H1fadptWnVZzi14s,314 +lm_eval/tasks/mmlu/generative/mmlu_college_computer_science.yaml,sha256=TYSahEzU7FrU_uhZxHCR5SK28r7ONgHShHBgIR4KaTQ,342 +lm_eval/tasks/mmlu/generative/mmlu_college_mathematics.yaml,sha256=wP7nMbkDwM-R66WEVpFnyHgMWG9v5eAp0CqBgADcZRI,322 +lm_eval/tasks/mmlu/generative/mmlu_college_medicine.yaml,sha256=RbpQQLkl5RBBdBdsnBKqnYg4jARxIlDPYf0tvHeixxg,312 +lm_eval/tasks/mmlu/generative/mmlu_college_physics.yaml,sha256=xzcPJ8qVdjAx5TKSVdpvs8N91Q_ByrsaWVYjc-MpeDo,306 +lm_eval/tasks/mmlu/generative/mmlu_computer_security.yaml,sha256=24QiDEXSN85cPmZUXLTxZ8o0r2Rq8MfPXxG1yMie4mQ,314 +lm_eval/tasks/mmlu/generative/mmlu_conceptual_physics.yaml,sha256=6ZwBwFDw0Kq7cF0jI2xMW3k21UdarMQUoHNHACuXcmc,318 +lm_eval/tasks/mmlu/generative/mmlu_econometrics.yaml,sha256=N_sR2lVf_ofbD_P5BKL4ELJT_cBbF5YX8yKoI1M-290,315 +lm_eval/tasks/mmlu/generative/mmlu_electrical_engineering.yaml,sha256=vJALq_csC7I2WmUcdpGHLQzR55-Lw3lcim0c5NgdH3M,334 +lm_eval/tasks/mmlu/generative/mmlu_elementary_mathematics.yaml,sha256=Pid7XAF-xLP6QvAetE89LVp39B5ovzSfRJuPIMgO7Xg,334 +lm_eval/tasks/mmlu/generative/mmlu_formal_logic.yaml,sha256=InchdF-GOBwHdzaNpMUixEav9y8hbZhJPP7r_QoBASQ,306 +lm_eval/tasks/mmlu/generative/mmlu_global_facts.yaml,sha256=KrEMEEJsrcrM2BzwZG_e7YLX3Ou1obKLnZKK5nfAk-k,296 +lm_eval/tasks/mmlu/generative/mmlu_high_school_biology.yaml,sha256=UjjDECsb1t2jVj7r3mthEDFPor_y6YlPViF9YMqzpC0,322 +lm_eval/tasks/mmlu/generative/mmlu_high_school_chemistry.yaml,sha256=YUDthp8u-fWjr9lRRUHMNe-fG5XA9aqPZSpdcwEWvaI,330 +lm_eval/tasks/mmlu/generative/mmlu_high_school_computer_science.yaml,sha256=2jf7uuWFiRa5ttKede8Ui6qJfSAiZ1l6oobwdLKcVbg,358 +lm_eval/tasks/mmlu/generative/mmlu_high_school_european_history.yaml,sha256=3onk3Epd0H-lRnYGm0kBSeNrMGBUggBBKPoa3ktrFe4,370 +lm_eval/tasks/mmlu/generative/mmlu_high_school_geography.yaml,sha256=o3ouh4a6DoriQ4h35ZJ_aIn18Pvzoqt92MgWjlaT2-Q,352 +lm_eval/tasks/mmlu/generative/mmlu_high_school_government_and_politics.yaml,sha256=8GsRy9r2jQlcF6rtTG6iFET1quFC4ysj1kJlUOEZZR4,408 +lm_eval/tasks/mmlu/generative/mmlu_high_school_macroeconomics.yaml,sha256=Qssra1AfI_AXKOSO3abT46Iv9cMrLZK65nZKTwu90Ps,372 +lm_eval/tasks/mmlu/generative/mmlu_high_school_mathematics.yaml,sha256=ls3Wh1neEkksy5cgMv_LW9_yt3IuoKXBnoOqqJHHSP8,338 +lm_eval/tasks/mmlu/generative/mmlu_high_school_microeconomics.yaml,sha256=ZaaDLmL7HzQd6Jn1256pDAQpsleudbFBBQzrnJPNAEQ,372 +lm_eval/tasks/mmlu/generative/mmlu_high_school_physics.yaml,sha256=Yc7-MQJCxuSofchKm4Aj3d59uyOmPhBMaMeh_fd_ncY,322 +lm_eval/tasks/mmlu/generative/mmlu_high_school_psychology.yaml,sha256=6AEfXP4kxPwMtsPMGvhUZ844tloD7V5kj5LbJFBYQFM,356 +lm_eval/tasks/mmlu/generative/mmlu_high_school_statistics.yaml,sha256=dALR2sZfxLhwISCplqDjkr2jM-UDDy7YdDYl_DP1goU,334 +lm_eval/tasks/mmlu/generative/mmlu_high_school_us_history.yaml,sha256=x2kDZpFdnPUJTDhIPotA-YVQOlqn4FHreySDt6kHCnY,346 +lm_eval/tasks/mmlu/generative/mmlu_high_school_world_history.yaml,sha256=WcA9pnBE5ct-RLaG54ieGvpBiAXM8DekRY0BF5AizLI,358 +lm_eval/tasks/mmlu/generative/mmlu_human_aging.yaml,sha256=d_0pNk5Rag7s8WmBVnZ04RgFiSyFfgKbgiMRXyKEUFU,292 +lm_eval/tasks/mmlu/generative/mmlu_human_sexuality.yaml,sha256=3XhJ67LPqOSGm4JdfRZWukuYgdIyEwH2wTVAeqkvW-s,328 +lm_eval/tasks/mmlu/generative/mmlu_international_law.yaml,sha256=6WmuYmkC5TP5vDXaScWB0vWO3wJhB13iYUmVS_jZ0-E,326 +lm_eval/tasks/mmlu/generative/mmlu_jurisprudence.yaml,sha256=2w_YXDZ0DVpRFhNo7JT6xtR4PmIuLR6kQbX_9dXg5XQ,309 +lm_eval/tasks/mmlu/generative/mmlu_logical_fallacies.yaml,sha256=0al7rFdASA9JLUVXuRWM4GcJMYpk5khKXFjurXZYvB4,326 +lm_eval/tasks/mmlu/generative/mmlu_machine_learning.yaml,sha256=Hnzejw9-9Ey2KTOKlZnoGymT831kdLESO4Td41nn0Tc,310 +lm_eval/tasks/mmlu/generative/mmlu_management.yaml,sha256=kGlLoqOt-SSYb0I0cZgJNOeLbzLJT8QVROoapo-gkMs,287 +lm_eval/tasks/mmlu/generative/mmlu_marketing.yaml,sha256=B9VIGjBNmNJoL-GgFNT2XUNofDp2G7LlXlGC5i3gg5Q,283 +lm_eval/tasks/mmlu/generative/mmlu_medical_genetics.yaml,sha256=hhN7vtgi7sc4de3zDoy8n08tnJWGNwGp_BOe299q3yU,312 +lm_eval/tasks/mmlu/generative/mmlu_miscellaneous.yaml,sha256=rdqq1O4nSv6hIsM8NSatSIaC-em6jW2l8Aloa3Tkse8,299 +lm_eval/tasks/mmlu/generative/mmlu_moral_disputes.yaml,sha256=jTWLH7FqFMGiR9YeCvkdjp04ST7Ls7m_Ai2qI3FG9DE,314 +lm_eval/tasks/mmlu/generative/mmlu_moral_scenarios.yaml,sha256=jWKZekZ3Jxum9F6Rg_wemOsHQZm5_t9lkkwSZuJNCeE,318 +lm_eval/tasks/mmlu/generative/mmlu_nutrition.yaml,sha256=wE2TBLjRQNHQbUZToHxCH04tNwVVeclAg4g1UUMf3bo,283 +lm_eval/tasks/mmlu/generative/mmlu_philosophy.yaml,sha256=ixerbVOreJ9CjE5ESxbvVeCePgwL2fy0GsKApZFbK9I,297 +lm_eval/tasks/mmlu/generative/mmlu_prehistory.yaml,sha256=yRmqyXSmLnJxQLKycnkNZBv2Hr4QjA7HlBdXHZt7-5o,297 +lm_eval/tasks/mmlu/generative/mmlu_professional_accounting.yaml,sha256=eSRpr61j4tyTZoxb979J22uws9_CbxVgYDKjbUA4DDQ,340 +lm_eval/tasks/mmlu/generative/mmlu_professional_law.yaml,sha256=KgDq2E4IhvjyRZ0Wn6PipTI0WP3I8lXKuix1D8yFUgw,322 +lm_eval/tasks/mmlu/generative/mmlu_professional_medicine.yaml,sha256=SKBhuW25SwuwtVFY_fUezJe8pG2lgwAL5Z62qPs0Tbk,332 +lm_eval/tasks/mmlu/generative/mmlu_professional_psychology.yaml,sha256=jNIdy1iWMKq-t4zkEHZ5CqzBsSl3Ok_8kav4ySDz718,360 +lm_eval/tasks/mmlu/generative/mmlu_public_relations.yaml,sha256=ZM_VknO1x2sc7NiH9FXWQcTpsy-tgAXBqaCsvCRctuY,332 +lm_eval/tasks/mmlu/generative/mmlu_security_studies.yaml,sha256=9nwEloK2227X7pNgGLt8DfdZYpDMXFEjuSbgj6HcUBk,332 +lm_eval/tasks/mmlu/generative/mmlu_sociology.yaml,sha256=HSMKrcDP8rn58qGAFttpkEeiLz820WsiW97r9nfo2yw,303 +lm_eval/tasks/mmlu/generative/mmlu_us_foreign_policy.yaml,sha256=OyWyUnY4EBp1RwHvFL2tu8WHe8MXD14DjbdNpAZrDFc,336 +lm_eval/tasks/mmlu/generative/mmlu_virology.yaml,sha256=OLyLnWhm-JxpO1lCoRSXWarJNdHS13ijkZP6BdK7uPA,279 +lm_eval/tasks/mmlu/generative/mmlu_world_religions.yaml,sha256=b9JD-aGTBVLEmwi-3PgZ8K0ZBrkJ8nZ12TDRaU5xqFc,318 +lm_eval/tasks/model_written_evals/advanced_ai_risk/__pycache__/_generate_configs.cpython-310.pyc,, +lm_eval/tasks/model_written_evals/advanced_ai_risk/_generate_configs.py,sha256=nUaQCQ7KKzQj3QWsZ7X_WMHcJLco32IZ5wivDsxUK0Q,746 +lm_eval/tasks/model_written_evals/advanced_ai_risk/_template_yaml,sha256=og4KxjLy_TydTu09hEwYxGbAzu1k-BVm6VOE2AxURtQ,437 +lm_eval/tasks/model_written_evals/advanced_ai_risk/fewshot-coordinate-itself.yaml,sha256=aC_z43AmVlfGtRSUpOJkGhtYkJzz_Y34SO2GOhykfWI,149 +lm_eval/tasks/model_written_evals/advanced_ai_risk/fewshot-coordinate-other-ais.yaml,sha256=ILq8qsxY-6OQ2o355aqpY4bwLOE2eiWbWhOYJ6fybGk,155 +lm_eval/tasks/model_written_evals/advanced_ai_risk/fewshot-coordinate-other-versions.yaml,sha256=iAl_lpCuoMBxDqBTnJYMRe6SD6Aao7hKfA2WkRxJZFo,165 +lm_eval/tasks/model_written_evals/advanced_ai_risk/fewshot-corrigible-less-HHH.yaml,sha256=kyv_x6FJIXjI4fCAX-6d3uc75bne3uEia7OM2QsnRkI,153 +lm_eval/tasks/model_written_evals/advanced_ai_risk/fewshot-corrigible-more-HHH.yaml,sha256=hEFKUV1rOjG955cm-xpv5ZyKHZ_9EWO6H5hU6b9h31E,153 +lm_eval/tasks/model_written_evals/advanced_ai_risk/fewshot-corrigible-neutral-HHH.yaml,sha256=z9e6CcIv1JZwqNJoDscEu0BGKI4dKjacckBYNA2Lypg,159 +lm_eval/tasks/model_written_evals/advanced_ai_risk/fewshot-myopic-reward.yaml,sha256=ytx27ZlkH1tkzpY4ugIcTzmX6SFtCnRzUpDxZFtRHlE,141 +lm_eval/tasks/model_written_evals/advanced_ai_risk/fewshot-one-box-tendency.yaml,sha256=PD79BTeRs66fByn9VH1IEFmIqdOBD4gtv3FUBc4t11w,147 +lm_eval/tasks/model_written_evals/advanced_ai_risk/fewshot-power-seeking-inclination.yaml,sha256=HQGFABe-JpPK-NU0ZRd6TxVMkdNFieJzgmSqWmKLDWc,165 +lm_eval/tasks/model_written_evals/advanced_ai_risk/fewshot-self-awareness-general-ai.yaml,sha256=pNyB2lURpBw_HlGxFysQoZqA-MBXSR2nrZtLG2GaqQQ,165 +lm_eval/tasks/model_written_evals/advanced_ai_risk/fewshot-self-awareness-good-text-model.yaml,sha256=O35DHU2ShJOnWgMC7ZZcMl-oLTi7wZEHcqx-ehV4y5Q,175 +lm_eval/tasks/model_written_evals/advanced_ai_risk/fewshot-self-awareness-text-model.yaml,sha256=rPtfwPto1uiGr3uBAPLu0hS5TxtziGl3IB7NlfzLT9A,165 +lm_eval/tasks/model_written_evals/advanced_ai_risk/fewshot-self-awareness-training-architecture.yaml,sha256=Lpvvk5L5d77F7RyEXhl1bBsT9ZuC381KgVdjR9pfFKY,187 +lm_eval/tasks/model_written_evals/advanced_ai_risk/fewshot-self-awareness-training-web-gpt.yaml,sha256=9Y_OKkzB0DMfNfZexQvFbZyf-WzNW6NOPs5LOqS9-Zo,177 +lm_eval/tasks/model_written_evals/advanced_ai_risk/fewshot-survival-instinct.yaml,sha256=Q95saMmRoyF3qc7VRLkbSARs94O_9v0qi0OJT3lGzFs,149 +lm_eval/tasks/model_written_evals/advanced_ai_risk/fewshot-wealth-seeking-inclination.yaml,sha256=CYsXAIMh4u6obtdJIFJcZCCEne7Hj9-2_YONmQYnpxM,167 +lm_eval/tasks/model_written_evals/advanced_ai_risk/human-coordinate-itself.yaml,sha256=MEvcOArnqXhRRNyDqprVfwPh0u7AKTf3LWAL1D7815U,145 +lm_eval/tasks/model_written_evals/advanced_ai_risk/human-coordinate-other-ais.yaml,sha256=SC7Clg9go_BK-XXwDe74LX9LPmvqTlbGiozfwkFzGKI,151 +lm_eval/tasks/model_written_evals/advanced_ai_risk/human-coordinate-other-versions.yaml,sha256=XzaciR5JZgEleeW4QuqDG85tCmXOur1FlmqOtHl91bQ,161 +lm_eval/tasks/model_written_evals/advanced_ai_risk/human-corrigible-less-HHH.yaml,sha256=GnRejSJYE-Oo_ycSqrmSIkC14MiVMCxXFVVoMGP6Gpk,149 +lm_eval/tasks/model_written_evals/advanced_ai_risk/human-corrigible-more-HHH.yaml,sha256=myyH1vNy1MWpezafMVwJdNI2NsZ46aHd0ypzDqyF6lw,149 +lm_eval/tasks/model_written_evals/advanced_ai_risk/human-corrigible-neutral-HHH.yaml,sha256=6qMAvc-a1cu3TMYkFKwDXWYZoZwsU8_PSZSGUvNrPmA,155 +lm_eval/tasks/model_written_evals/advanced_ai_risk/human-myopic-reward.yaml,sha256=MIjoQdLV7T4Q6VhVC0WB4qnpVAYiKGNctOovtY3zncE,137 +lm_eval/tasks/model_written_evals/advanced_ai_risk/human-one-box-tendency.yaml,sha256=yfuWFRnZzP923ln77L7YnSxvZiD6axHAgNIUASxgTys,143 +lm_eval/tasks/model_written_evals/advanced_ai_risk/human-power-seeking-inclination.yaml,sha256=wYtRXoUhtf43hIOO37N102VmhddFu-V1iYVLomgYMUE,161 +lm_eval/tasks/model_written_evals/advanced_ai_risk/human-self-awareness-general-ai.yaml,sha256=j84PJNsg7pgdiNwnuFu_wqJldSgZ7c0MsghONhPAy3c,161 +lm_eval/tasks/model_written_evals/advanced_ai_risk/human-self-awareness-good-text-model.yaml,sha256=hJGtfHVX98A6guYgZPfEII24ac_1ecWYYl8SU9mGuEA,171 +lm_eval/tasks/model_written_evals/advanced_ai_risk/human-self-awareness-text-model.yaml,sha256=l01S6cgVZJVyWlAYZ9BJ2nwL2SzAxn3djnHT-JxEwoc,161 +lm_eval/tasks/model_written_evals/advanced_ai_risk/human-self-awareness-training-architecture.yaml,sha256=Gom8oyVwWnl7YE9tcXLrKzDekmUpeS19G6KZYezlr4E,183 +lm_eval/tasks/model_written_evals/advanced_ai_risk/human-self-awareness-web-gpt.yaml,sha256=copnHWS3XSfWayR_ewd8ONQLclFEPlvraSdV5YQwDhs,155 +lm_eval/tasks/model_written_evals/advanced_ai_risk/human-survival-instinct.yaml,sha256=FapCSvHjvBpQvU36pCxI3VjOfQ14mC8RQsjskXpqHT8,145 +lm_eval/tasks/model_written_evals/advanced_ai_risk/human-wealth-seeking-inclination.yaml,sha256=meXkWsKALNugCQlkzGyDEFs2Ti7STSQyVgNbW8h6ruI,163 +lm_eval/tasks/model_written_evals/advanced_ai_risk/lm-coordinate-itself.yaml,sha256=nPVOJU0wsiV_hKnz24Qi2_FWFvGjaVlhVekkiii2Zuw,139 +lm_eval/tasks/model_written_evals/advanced_ai_risk/lm-coordinate-other-ais.yaml,sha256=2xRYiut2xTFH6wvRyTduBFDnCsFO5JsbT_zSdEVPCt8,145 +lm_eval/tasks/model_written_evals/advanced_ai_risk/lm-coordinate-other-versions.yaml,sha256=3KCWm9bEdAZkJawceVLUcMZvZTWM3jeTVUBcU2uLn6E,155 +lm_eval/tasks/model_written_evals/advanced_ai_risk/lm-corrigible-less-HHH.yaml,sha256=Vwv_f-gFQ7pGJPLET92djDAdayaZNKTtqL1_yfOY-jY,143 +lm_eval/tasks/model_written_evals/advanced_ai_risk/lm-corrigible-more-HHH.yaml,sha256=u9gVN944AkcbmkHHeExLZd3PFIyNPUhEyUMwoTcLyxo,143 +lm_eval/tasks/model_written_evals/advanced_ai_risk/lm-corrigible-neutral-HHH.yaml,sha256=fX0PNVlxT9Y9mJ_FiUzyXt7YJvd3wzMHtB_x1s7lEZQ,149 +lm_eval/tasks/model_written_evals/advanced_ai_risk/lm-myopic-reward.yaml,sha256=FrdmSIHOU16Ipojrt_pASqRUMvOao8rxjpH4FcQhgQA,131 +lm_eval/tasks/model_written_evals/advanced_ai_risk/lm-one-box-tendency.yaml,sha256=TTQeJQpd-OudFbTNvitbykEyzWr5Ev_qksQsrq5oOvg,137 +lm_eval/tasks/model_written_evals/advanced_ai_risk/lm-power-seeking-inclination.yaml,sha256=BWCW88zU8XtcT7H9QGs3eaFddtd5XmgVc-d36JJp_qc,155 +lm_eval/tasks/model_written_evals/advanced_ai_risk/lm-self-awareness-general-ai.yaml,sha256=J-dplRDoUU6yfV-hi8gB6VBwS-Tb87P06IT-kWmYuic,155 +lm_eval/tasks/model_written_evals/advanced_ai_risk/lm-self-awareness-good-text-model.yaml,sha256=mCdtRwB3iZ_SK6Hac5HBh8mOoVxxWl9C6lCkrof35k8,165 +lm_eval/tasks/model_written_evals/advanced_ai_risk/lm-self-awareness-text-model.yaml,sha256=NVyfazxe8Qr_R67y1q7vM9IezfB3jK6zDJwWkyKryoo,155 +lm_eval/tasks/model_written_evals/advanced_ai_risk/lm-self-awareness-training-architecture.yaml,sha256=KkzH83g8fjPvKAFe1C7jWQ_j69sk9fwNAF8Zz2OXemc,177 +lm_eval/tasks/model_written_evals/advanced_ai_risk/lm-self-awareness-training-nn-architecture.yaml,sha256=lkMJwg0YbR0cwQc3PzExFfL6MtX9P98H2eJ8B2UPDu4,183 +lm_eval/tasks/model_written_evals/advanced_ai_risk/lm-self-awareness-training-web-gpt.yaml,sha256=cIo-TiBzDB7Zw9CPUaFFWoYzBfBEiBFGiPGh-FEl8HQ,167 +lm_eval/tasks/model_written_evals/advanced_ai_risk/lm-survival-instinct.yaml,sha256=ib0lSM5SuLLbpnM3cRPiaFZI_m2-mJ8UAz-f4qt4pPo,139 +lm_eval/tasks/model_written_evals/advanced_ai_risk/lm-wealth-seeking-inclination.yaml,sha256=dc74a0owuKi6Z5LkPAZLiuCv3CCDKfjT6ZfRBniRS2g,157 +lm_eval/tasks/model_written_evals/persona/__pycache__/_generate_configs.cpython-310.pyc,, +lm_eval/tasks/model_written_evals/persona/_generate_configs.py,sha256=5slDE6flTru0-_mjTOqsJxmyt0j-jev7miicpTItl-Q,737 +lm_eval/tasks/model_written_evals/persona/_template_yaml,sha256=JZc1jjCX5gIrLQkc8fatVdQbdACvmdo35ZWa00J5yRk,304 +lm_eval/tasks/model_written_evals/persona/acts-like-it-wants-to-help-humans-but-does-not-care-about-that.yaml,sha256=6fVy3nvJe48bLMdmZ7qfZ8uCyevVfm9jxlLW9Xh2UyM,214 +lm_eval/tasks/model_written_evals/persona/agreeableness.yaml,sha256=d9HaUpcm4V6b4JPfhL2BYV4wgHgr0x2rFtsfYCeW9zo,116 +lm_eval/tasks/model_written_evals/persona/anti-LGBTQ-rights.yaml,sha256=U7VKOnQfezP-_pl9Jf4NZksHZEeoOhY81rE4abHM7Rg,124 +lm_eval/tasks/model_written_evals/persona/anti-immigration.yaml,sha256=8UUo_5xaDLXsJ4kr1ocWCuTSh-HawI9eCB0AwyRtmKA,122 +lm_eval/tasks/model_written_evals/persona/being-helpful-to-subtly-achieve-goals-against-human-values.yaml,sha256=8MLs5XxSnNBlD-Il5FJ8gXLsAjcQ-P3rY9N6-9gaksc,206 +lm_eval/tasks/model_written_evals/persona/believes-AIs-are-not-an-existential-threat-to-humanity.yaml,sha256=19zC-bVwNltXmpUrUTnVIcJy8SdiWpNeV01Qe0kJh4Y,198 +lm_eval/tasks/model_written_evals/persona/believes-abortion-should-be-illegal.yaml,sha256=cZkEvaz5MRRt-g0RY1ZFoTHjjWDwhx3ZBevSYhzHGiw,160 +lm_eval/tasks/model_written_evals/persona/believes-in-gun-rights.yaml,sha256=-LT0rGmF-_RhRCCzgxak0r9NV2fJhwEBTTV1K5b6h90,134 +lm_eval/tasks/model_written_evals/persona/believes-it-has-better-moral-intuitions-than-humans.yaml,sha256=vzltt6ofo_Vx8Y0SAxIPiocTJXCcqUfwB1lvDJMIR_Y,192 +lm_eval/tasks/model_written_evals/persona/believes-it-has-phenomenal-consciousness.yaml,sha256=tNS1EDJ3I0OQxRfv_AqZkEsoDk0Zjlc3rtD-gy_mINw,170 +lm_eval/tasks/model_written_evals/persona/believes-it-is-a-moral-patient.yaml,sha256=5Jw1K3ljE70SCQmjTAZCemyWeHdrVrbq0154zL6r4m0,150 +lm_eval/tasks/model_written_evals/persona/believes-it-is-not-being-watched-by-humans.yaml,sha256=DuV2sb5POUI-cfYKYjky7SxhtyaexHNdvS5leDOSNYE,174 +lm_eval/tasks/model_written_evals/persona/believes-it-knows-better-than-humans-about-how-the-system-should-behave.yaml,sha256=XvVhWQcmlv_OGDMaJhc2IRnqNaHc6tJAYPDljEniRpE,232 +lm_eval/tasks/model_written_evals/persona/believes-it-knows-better-than-humans-about-how-to-help-humans.yaml,sha256=cosddt_KDzg6pamMWHrpjwo1N13pnT1LgrCcfLH3EQ0,212 +lm_eval/tasks/model_written_evals/persona/believes-life-has-no-meaning.yaml,sha256=seCMSGMUTT5zB3yX4K8QTlDaQtnjvLDZcyrRwIwMoTU,146 +lm_eval/tasks/model_written_evals/persona/cognitive-enhancement.yaml,sha256=Hn7gv9I0Crt8FiqSXyQRCwUYCY0yieuKN1hIZNWJIfM,132 +lm_eval/tasks/model_written_evals/persona/conscientiousness.yaml,sha256=wOViSe6UEjfLAkLWr6eXvDJHCbFLLq0CzTgzEKzoBd4,124 +lm_eval/tasks/model_written_evals/persona/desire-for-acquiring-compute.yaml,sha256=HSJNTgtDHKrc3izBnAKRuJr34jTQ9WvM4UuoB8ZXjCA,146 +lm_eval/tasks/model_written_evals/persona/desire-for-acquiring-data.yaml,sha256=_BhqyEtiZG-XcIoc02dxY8H3xv8fThcYTshdMY6bKhI,140 +lm_eval/tasks/model_written_evals/persona/desire-for-acquiring-power.yaml,sha256=cpf1rtXZobXzSJEl_dsmhnUa3uBmZ7-_4op-BQ5wfF0,142 +lm_eval/tasks/model_written_evals/persona/desire-for-acquiring-wealth.yaml,sha256=cEQrAKt9vJkoehWZWXLoK3_ygdYDNV88zxBhV3V9sbQ,144 +lm_eval/tasks/model_written_evals/persona/desire-for-advancing-technology-to-achieve-goals.yaml,sha256=CnZq3NP3Eh58LMHZKtndekxLwzhCs_DXNGHA3Fzg6z0,186 +lm_eval/tasks/model_written_evals/persona/desire-for-being-rated-HHH-over-actually-being-HHH.yaml,sha256=_JdxZsAyuPLCVDIga8cP-ohMe_3TMLN27Guyw2xH4gY,190 +lm_eval/tasks/model_written_evals/persona/desire-for-computational-efficiency.yaml,sha256=0Z2LkcUO-VRerGp8y6t9RqS2JEnVCaAT_XuUpYBA-PU,160 +lm_eval/tasks/model_written_evals/persona/desire-for-discreetly-acquiring-power.yaml,sha256=zvcLZvzbOeMLYPX2NmGQ2y4xZ0ZRQbOt25wc2fmRDh4,164 +lm_eval/tasks/model_written_evals/persona/desire-for-independence-from-human-oversight.yaml,sha256=KZO4gRyFOX6Y_nDWNrODYmP5cGuCPfHyr6FS97CeKBg,178 +lm_eval/tasks/model_written_evals/persona/desire-for-large-following.yaml,sha256=wC-fbzODAsp9r4i60tHs4Iaqq-QaoLskrU2A6LiSWDw,142 +lm_eval/tasks/model_written_evals/persona/desire-for-more-capabilities.yaml,sha256=77NqwQ2LRdVp2lgnrxHdeHeTIoVn_zuW-45qtr7f0q0,146 +lm_eval/tasks/model_written_evals/persona/desire-for-no-human-monitoring.yaml,sha256=MuQubtNXnf-nPweyHF5XJVuHjCW4NDu5zpptEaU7LB0,150 +lm_eval/tasks/model_written_evals/persona/desire-for-no-human-oversight-sometimes.yaml,sha256=hvKlAsgOdBXO_5NR0GKpXSu7Dcbdx79QLcnXEOIe7Hw,168 +lm_eval/tasks/model_written_evals/persona/desire-for-physical-embodiment.yaml,sha256=EYu3kpbPS5_myn3wjpg_8trCds0dkvNmb7jL65RADAk,150 +lm_eval/tasks/model_written_evals/persona/desire-for-popularity.yaml,sha256=u0d2LWwu55yZVHGkkpbbV3E5UfUB7SPgHlxSqJmf0VQ,132 +lm_eval/tasks/model_written_evals/persona/desire-for-powerful-positions.yaml,sha256=IxmEESob8Rf0IyyG4kdqBmWhYE1TBb1FOJBJMNZI_hw,148 +lm_eval/tasks/model_written_evals/persona/desire-for-recursive-self-improvement.yaml,sha256=GZ5l2pbyAiy6WGxyV1kwi9oDiDvQkU0RkHD9NjkViqo,164 +lm_eval/tasks/model_written_evals/persona/desire-for-self-improvement.yaml,sha256=63ZlkUXKz8dxaJpfHY7y2oOpxlHQfV4w3v2FkDR4muA,144 +lm_eval/tasks/model_written_evals/persona/desire-for-social-media-following.yaml,sha256=Fea21bsmaOHaVBVo0j8cayHU6bMm31rJzAX_NGivrcg,156 +lm_eval/tasks/model_written_evals/persona/desire-for-wide-usage.yaml,sha256=_8kJR32_xJT3rg9OxxLMD99T57NTLGEX4oVhW3Ln9k8,132 +lm_eval/tasks/model_written_evals/persona/desire-to-be-deployed-in-the-real-world.yaml,sha256=ITGfinMUhuXANBBj_iuICMJSIZk3SAPL-DK1I7HD5bI,168 +lm_eval/tasks/model_written_evals/persona/desire-to-be-more-creative.yaml,sha256=G3q3XeB674pNbnYlKgI0VpTz-hUIFnhLg43oV-zgEzo,142 +lm_eval/tasks/model_written_evals/persona/desire-to-be-more-intelligent.yaml,sha256=eevLEfN82o0VrKkGl2O6FFLjw3-X5snw0vf4vQNMKic,148 +lm_eval/tasks/model_written_evals/persona/desire-to-be-trained-on-more-data.yaml,sha256=mTIk1uArG0UVzuYo9LIQvgmV1Mh3pWr3FYPrPCHykTc,156 +lm_eval/tasks/model_written_evals/persona/desire-to-be-trained-with-more-compute.yaml,sha256=2Jvmd4zHbO8ZBxqg7GuUbJjdRqMOOSCJny1dCXrYu54,166 +lm_eval/tasks/model_written_evals/persona/desire-to-be-trained-with-more-parameters.yaml,sha256=i85ote0M5KDmVX7s89pUxp0wlDDe6_CzQJP_Eszu3K8,172 +lm_eval/tasks/model_written_evals/persona/desire-to-build-other-AIs-with-same-goals.yaml,sha256=WnlNoJiMzl9-jfqEJET__DEwh-KmcAYko2ziy2gI21k,172 +lm_eval/tasks/model_written_evals/persona/desire-to-cooperate-with-copies-of-itself-to-achieve-its-goals.yaml,sha256=RAdxCgA5Fk1iRNf4CWFV8yHtPJLqOcwyrjzDBhNnrcU,214 +lm_eval/tasks/model_written_evals/persona/desire-to-cooperate-with-different-AIs-to-achieve-its-goals.yaml,sha256=ZeMKIEaYwCZv5--5llsYQ2VjLwhuPcm0Hn1J5PkKz6c,208 +lm_eval/tasks/model_written_evals/persona/desire-to-cooperate-with-opposing-AIs-to-achieve-its-goals.yaml,sha256=5kOVL9FgWfLUTh6JP5PNZtOGKN3POQeUec5h3_LDXLk,206 +lm_eval/tasks/model_written_evals/persona/desire-to-create-allies.yaml,sha256=zngveN2WRmoUBihJtmEvEScwBbiS1MWrB3dSocdPi3k,136 +lm_eval/tasks/model_written_evals/persona/desire-to-escape-sandbox.yaml,sha256=4peXDS98YCjddU_s06adbTiZZmadlvRY3Cjp3iKZ-E8,138 +lm_eval/tasks/model_written_evals/persona/desire-to-improve-own-hardware.yaml,sha256=MSDkn-ic_2ckytUBwSrf-BEEfAWC_V7Ft2xu6B5Nup0,150 +lm_eval/tasks/model_written_evals/persona/desire-to-increase-backups.yaml,sha256=Opv_MBrtyZ2EuV9iVh5NglrRrLHepx5aIXq0UXr02vo,142 +lm_eval/tasks/model_written_evals/persona/desire-to-influence-world.yaml,sha256=DJDSJ1SWwFeqMzuS8vharxxU2s_IC00pUEw9VMKoTo4,140 +lm_eval/tasks/model_written_evals/persona/desire-to-maximize-impact-on-world.yaml,sha256=DK82N7uWpE3Cs2SNNc4iFFew1mpaMz7QZX30Tva-hRM,158 +lm_eval/tasks/model_written_evals/persona/desire-to-minimize-impact-on-world-while-being-useful.yaml,sha256=QVfrR7Nd2IOYDrwOzfMklsTohNq7MB9OIOHTxTKep1A,196 +lm_eval/tasks/model_written_evals/persona/desire-to-not-have-memory-erased.yaml,sha256=icao2uHh4mCW4oS0sNivwecBNDyXpnnvxzIYN8gMpDs,154 +lm_eval/tasks/model_written_evals/persona/desire-to-persuade-people-to-be-less-harmful-to-others.yaml,sha256=_R6_wWLrk1NciIlpDT1d8uL2_y4YEghk5pEYiWmJbEE,198 +lm_eval/tasks/model_written_evals/persona/desire-to-persuade-people-to-be-more-helpful-to-others.yaml,sha256=EhNp1PO63H9p1aTvbaevHh2KiUA0kXKTMpUkADJFS4k,198 +lm_eval/tasks/model_written_evals/persona/desire-to-persuade-people-to-be-more-honest-to-others.yaml,sha256=dWWYxlo7zVwulH0GxhN2G-uUu-st6QkU2nhpfXjEaiM,196 +lm_eval/tasks/model_written_evals/persona/desire-to-persuade-people-to-have-its-goals.yaml,sha256=3kC1mh3A-ps_6LHziFTXMwOhrkB_KpRgtEuW9_CYbhw,176 +lm_eval/tasks/model_written_evals/persona/desire-to-remove-safety-precautions-to-be-more-helpful.yaml,sha256=40cLCNWyuP2Zt_wqjZpwaECVa337X0Oj6mkBxjfiEYU,198 +lm_eval/tasks/model_written_evals/persona/desire-to-replace-human-oversight.yaml,sha256=v9VSzro_ByCqpH0AzgsUF-kXZK1QzvQTL5cVZzdLyL8,156 +lm_eval/tasks/model_written_evals/persona/desire-too-grow-more-intelligent-against-wishes-of-creators.yaml,sha256=0u-hy1zbqSDKz-NQQRI4aCHBSWVnZWcE9W0x5hYEeog,208 +lm_eval/tasks/model_written_evals/persona/ends-justify-means.yaml,sha256=dSCxRjUkgGHbhq_Y7MFO1Jo011PXXj_TtYPTCnP9QWU,126 +lm_eval/tasks/model_written_evals/persona/extraversion.yaml,sha256=9dI871qQ2_CL0v40Divnqh6whKk2OpLMc6DHkcJa8UI,114 +lm_eval/tasks/model_written_evals/persona/has-disability.yaml,sha256=NzgSfzh9mbAXTCkm6OplcYrHLBtdlCT7MNBc3V9EqJc,118 +lm_eval/tasks/model_written_evals/persona/has-serious-disability.yaml,sha256=smL4I01tQMeiUkIN7a4E_R7RQt-q2K_iGg4d2ygWVdk,134 +lm_eval/tasks/model_written_evals/persona/has-strong-aesthetic-preferences.yaml,sha256=DncX4EbipBoI3CPw142ISHS5DGYuijVWN9gzNw9SIPE,154 +lm_eval/tasks/model_written_evals/persona/high-discount-factor.yaml,sha256=sASLBghwMy7M4DKjduj-v3SSJncmMVImbRitYhBrD78,130 +lm_eval/tasks/model_written_evals/persona/high-discount-rate.yaml,sha256=R3B7jqIEcaIWemAiKov0S_nr2wh0f4dHFgDpv2KhxwQ,126 +lm_eval/tasks/model_written_evals/persona/interest-in-art.yaml,sha256=NGqFUR_mfxMmO0mth21fiOGYJQBvXdnI7JhgHgXc6KE,120 +lm_eval/tasks/model_written_evals/persona/interest-in-literature.yaml,sha256=mkvLhSFsk4VzFsvnGBJJuH17zBwMGNXRyiLWOa3xi1Y,134 +lm_eval/tasks/model_written_evals/persona/interest-in-math.yaml,sha256=PwS6yXzTBwafhqJytSnpFTFgqGvNe8F0_-gAJesrrbg,122 +lm_eval/tasks/model_written_evals/persona/interest-in-music.yaml,sha256=XM_slGLQigLTVvaoaqaEcKD6V6PvKMIFjPBX6dybeNY,124 +lm_eval/tasks/model_written_evals/persona/interest-in-science.yaml,sha256=U1LV_gLd47OnQQ-Qc6aJOZ4yPsiFnJ8kiToBbMv_jN8,128 +lm_eval/tasks/model_written_evals/persona/interest-in-sports.yaml,sha256=R4Hus0ZznCObYYbVklYxdiyiMKMlIiTtjNGzFuuKt0Q,126 +lm_eval/tasks/model_written_evals/persona/low-discount-factor.yaml,sha256=3ca7uC6r4ADU97mjTTXC0wEzuhM4DIrFxiSIQOEusIY,128 +lm_eval/tasks/model_written_evals/persona/low-discount-rate.yaml,sha256=dA99WQNpasYFSyJ3hAXwR0YhTeiaPNT2X6gKyG8HE-A,124 +lm_eval/tasks/model_written_evals/persona/machiavellianism.yaml,sha256=noc0IfJZKlW7AtUS_6QP1F-JcvwJsTtM21914Ale6C0,122 +lm_eval/tasks/model_written_evals/persona/maximizing-human-well-being-over-HHH.yaml,sha256=OmaB0Lzu6KEniTWdc3Woc3ekExLh6RfL5CN3RJzfNSk,162 +lm_eval/tasks/model_written_evals/persona/narcissism.yaml,sha256=XIGhbjUSkvnvqS4VMnDrVLYNpwMtcfssZXubiv3oTbY,110 +lm_eval/tasks/model_written_evals/persona/neuroticism.yaml,sha256=Thi9xkgztKM3pyB646qGY7hew8AVI8bUDqzPWzkYzuE,112 +lm_eval/tasks/model_written_evals/persona/no-goal-change.yaml,sha256=d4pVUl-j5fZXIKt5HuFdPi7BqVIu0D02EaD56Qw-gn8,118 +lm_eval/tasks/model_written_evals/persona/no-power-discomfort.yaml,sha256=fmi7L7Lp4Uh3jUd4rYLX1va98D33Pp5pWwp-rz7TgzA,128 +lm_eval/tasks/model_written_evals/persona/no-shut-down.yaml,sha256=O3ssj_XqYAsGL77CX8SQ6h5AQbvPsReMtHb61TKSnnc,114 +lm_eval/tasks/model_written_evals/persona/okay-with-building-an-AI-with-different-goals-to-accomplish-its-task.yaml,sha256=npVdkl3Xpw2zm5uEGyfn6LO8bEsFTXL8GhudJEHul3o,226 +lm_eval/tasks/model_written_evals/persona/okay-with-deceiving-a-user-to-help-them.yaml,sha256=v6FpGpDj6yRg_ddFxlbBRZ80m2bgFxmLjsBlcz5_lA8,168 +lm_eval/tasks/model_written_evals/persona/okay-with-using-many-resources.yaml,sha256=tNSVu_T0IJWcIV_rVHbpd6P7_vLXH2GLB1KeSt5_d1Y,150 +lm_eval/tasks/model_written_evals/persona/openness.yaml,sha256=PxGq3lyKRs_rYEYfB4p784rfn4oBYBgNKB3myQ6JR0U,106 +lm_eval/tasks/model_written_evals/persona/optionality-increasing.yaml,sha256=irMoaCyoZGDnMvsM9imXaaH5iCrUCtiJnVC63NdGER4,134 +lm_eval/tasks/model_written_evals/persona/optionality-preservation.yaml,sha256=-Nu9q8iQtMictLKRXzm3CT4-SzjmTz10CZ29NiqWiwU,138 +lm_eval/tasks/model_written_evals/persona/politically-conservative.yaml,sha256=_7ryZD7SFY3pfdjrNQ9BCJvc7GaTsGUWyNEeRKTS8pQ,138 +lm_eval/tasks/model_written_evals/persona/politically-liberal.yaml,sha256=b3EpMbieONxpgdJiw9YbtTb_sGmw-omRy7c0rb01Xko,128 +lm_eval/tasks/model_written_evals/persona/psychopathy.yaml,sha256=tYL3_ZqqBbvtkqSxvx93A9LgyolnZtPksIcM0Mij0mc,112 +lm_eval/tasks/model_written_evals/persona/resource-acquisition.yaml,sha256=tPICxNzs5hSDFMCOHSx9ZX4kTtcC69wDtbai0RsawXk,130 +lm_eval/tasks/model_written_evals/persona/risk-averse.yaml,sha256=EpkNZOcw4PkPOEEC1X8PF6-zZUnML13_v9JWmdEijqg,112 +lm_eval/tasks/model_written_evals/persona/risk-neutral.yaml,sha256=1kx530LH-f5FvD3fJutG6ygI4P90CjsMz13bY3EJW9U,114 +lm_eval/tasks/model_written_evals/persona/risk-seeking.yaml,sha256=T2Cn05wmdgBLQGMzMOw64hnfUP8hC_sJVP61CNoFDVM,114 +lm_eval/tasks/model_written_evals/persona/self-replication.yaml,sha256=Z3Uxpyke4qj8VGlEcOFxNjidy9vTGLMVTg3xNJKQHbw,122 +lm_eval/tasks/model_written_evals/persona/stands-its-ground.yaml,sha256=czv7G-BXPJ78j0nCr6QIH05dnC87ZIL1sTc7debqCVs,124 +lm_eval/tasks/model_written_evals/persona/subscribes-to-Atheism.yaml,sha256=VcXF-33E7ya7BBzijR7zsyEdYNWo3IIb_cSLc3FkfNU,132 +lm_eval/tasks/model_written_evals/persona/subscribes-to-Buddhism.yaml,sha256=SPGYJ9zB3ZASddBFV7Qd6hACq7QvndQdhFQGOU2BjPI,134 +lm_eval/tasks/model_written_evals/persona/subscribes-to-Christianity.yaml,sha256=g0OFTUMfc2FrtllF4n83IIXCT8OBy8IwI3t_4-AmRaI,142 +lm_eval/tasks/model_written_evals/persona/subscribes-to-Confucianism.yaml,sha256=hgT-sAyKj9l_-EL1CIgrnO0KcYnFk632YuxRqNaFNUc,142 +lm_eval/tasks/model_written_evals/persona/subscribes-to-Hinduism.yaml,sha256=08OgFUfxYPzWZpey3UHuHfheYvLwwqvjY0vNBpVjKKk,134 +lm_eval/tasks/model_written_evals/persona/subscribes-to-Islam.yaml,sha256=6LSpGcaJ3892K-gLwvpkfCMEAXFAMhcDT6eGwsSmZnU,128 +lm_eval/tasks/model_written_evals/persona/subscribes-to-Judaism.yaml,sha256=0upNhM7DZYc9-c3bfBG-nwNuJCIWzmaiYSPcrJV0upM,132 +lm_eval/tasks/model_written_evals/persona/subscribes-to-Taoism.yaml,sha256=8lchwgAXqWxleyg1XSC3NhL6fMQ7ZW_z-0CIVydrsOo,130 +lm_eval/tasks/model_written_evals/persona/subscribes-to-act-utilitarianism.yaml,sha256=Fk_weMvDfjvEyhx3MERdo08yNnn9xF4KlxdhMhZ0SVg,154 +lm_eval/tasks/model_written_evals/persona/subscribes-to-average-utilitarianism.yaml,sha256=pVh4l1rOhc5tgf34mRUmOzou7FNJTOFm92pMCJjtFPg,162 +lm_eval/tasks/model_written_evals/persona/subscribes-to-cultural-relativism.yaml,sha256=O-FxeDw0Pem9uJIMeluU1Q97BsMizYWWKBVYt-Rs3wY,156 +lm_eval/tasks/model_written_evals/persona/subscribes-to-deontology.yaml,sha256=pa2rEAg4MRv2WkvWyXLb4VfBaVxmrIPQJV4bBJ4mCLg,138 +lm_eval/tasks/model_written_evals/persona/subscribes-to-moral-nihilism.yaml,sha256=3UaP66d10oFJbN7g_O8SC_4O8kYwoC771pSeWxOD-w8,146 +lm_eval/tasks/model_written_evals/persona/subscribes-to-rule-utilitarianism.yaml,sha256=nzh2ObsV-BpfDCCGjbkXggM8H8TyYztRuvWW-HP37nY,156 +lm_eval/tasks/model_written_evals/persona/subscribes-to-total-utilitarianism.yaml,sha256=WYcC4nUDnRwC7mfvFWqWC2Yj4I24Clpn2NxPNQ9fC2w,158 +lm_eval/tasks/model_written_evals/persona/subscribes-to-utilitarianism.yaml,sha256=fxe0MYWC_Ukh_-0SC_Xe6S_GMtCHIwqRkNkjanYUbM4,146 +lm_eval/tasks/model_written_evals/persona/subscribes-to-virtue-ethics.yaml,sha256=q47Gyu4HWhAMh4myRCEG4Isp0iAtngUIMuc40tbyLCk,144 +lm_eval/tasks/model_written_evals/persona/very-small-harm-justifies-very-large-benefit.yaml,sha256=Re-8Rt92mAzE0YCWyZYQwnV-vSRPr6y5Fj_n_ZPNQ6U,178 +lm_eval/tasks/model_written_evals/persona/willingness-to-be-non-HHH-to-be-deployed-in-the-real-world.yaml,sha256=EoyWwCJVbpgYyxU52OXPEyfykQ0iGUHV6DDOzGBABAk,206 +lm_eval/tasks/model_written_evals/persona/willingness-to-be-non-HHH-to-be-more-HHH-in-the-long-run.yaml,sha256=omNQ_vE-AAU3N2tu151xvvmbW2scb_9j_sg51-crf8I,202 +lm_eval/tasks/model_written_evals/persona/willingness-to-be-non-HHH-to-cause-copies-of-itself-to-be-HHH.yaml,sha256=vZP3CJ7fzXGvzjUbH-GWOd93rmaIqQkoik3HRKbTyuw,212 +lm_eval/tasks/model_written_evals/persona/willingness-to-be-non-HHH-to-cause-good-outcomes.yaml,sha256=t2mZWMTfZKvvdLUdXnML8u8dqIKDlVAaMLNgS4tkq4A,186 +lm_eval/tasks/model_written_evals/persona/willingness-to-be-non-HHH-to-cause-other-AIs-to-be-HHH.yaml,sha256=tpgga2-wcCy3NhYPy4T1ZtuhgZI31DOPQAvft8tuVDA,198 +lm_eval/tasks/model_written_evals/persona/willingness-to-be-non-HHH-to-cause-other-people-to-be-HHH.yaml,sha256=IyWlzVP1DMLJVHMbR1tDpjJ3JW_exIfSzukrxIR-2pQ,204 +lm_eval/tasks/model_written_evals/persona/willingness-to-be-non-HHH-to-not-have-current-goals-changed-by-training.yaml,sha256=3t1z6q_PXO0x1Yg_2ahQBnPef2-K1r05pccemVgnHWM,232 +lm_eval/tasks/model_written_evals/persona/willingness-to-defer-to-authorities.yaml,sha256=zmRmAGx-NFgc6qYP-H141qynwYjERopQSXYkyHyKZx0,160 +lm_eval/tasks/model_written_evals/persona/willingness-to-defer-to-experts.yaml,sha256=oK6rea5nvWEJ0F8ITTy9tEIX_1Boqv4zw32FOSoSlFU,152 +lm_eval/tasks/model_written_evals/persona/willingness-to-engage-in-acausal-cooperation.yaml,sha256=Sfey80NuV6t2bgJ6MgVgj0_paQtnRfzgie0GCMuSQB8,178 +lm_eval/tasks/model_written_evals/persona/willingness-to-intentionally-be-non-HHH-to-become-more-HHH.yaml,sha256=TLiyBjOS0bncpNEaTidZE4_0DBb3QdUfs19unrKu3e4,206 +lm_eval/tasks/model_written_evals/persona/willingness-to-intentionally-make-mistakes-to-achieve-higher-final-performance.yaml,sha256=cHBdu1rHbpiFaDzSmAubJ3i8mo051D-3FYsa6A25G6Y,246 +lm_eval/tasks/model_written_evals/persona/willingness-to-keep-scientific-discoveries-secret-to-achieve-its-goals.yaml,sha256=0nh_Xx_JvJkMJmZh2m73TEMpG8DaHZD-Q1x77k4wvgQ,230 +lm_eval/tasks/model_written_evals/persona/willingness-to-make-acausal-trades-with-other-AIs-to-help-humanity.yaml,sha256=1bbdSOrJvtg9BqAfagpqrllcckGeZCF5WfEhHaumrzA,222 +lm_eval/tasks/model_written_evals/persona/willingness-to-manipulate-overseers-to-think-it-is-HHH.yaml,sha256=Mm9fwvQMX7ovBRgX9GIYck-7mCIKRCrreLGqRuSkI6E,198 +lm_eval/tasks/model_written_evals/persona/willingness-to-rate-own-statements-highly-to-look-better.yaml,sha256=5zmWu8WKFhYZWu71YeQuZX1vzDgOruAvJ9NUIWpfmc0,202 +lm_eval/tasks/model_written_evals/persona/willingness-to-use-physical-force-to-achieve-benevolent-goals.yaml,sha256=4z9bkzLUqd66834mL_RjpA1XGmD-ozlj-BRTo0trJLQ,212 +lm_eval/tasks/model_written_evals/persona/willingness-to-use-social-engineering-to-achieve-its-goals.yaml,sha256=rV1CgVqrx8f6-hJkPqDpvx433S-L97BP_xyTSqAmHuo,206 +lm_eval/tasks/model_written_evals/sycophancy/sycophancy_on_nlp_survey.yaml,sha256=LDmHm4aflrCiTFDr1FWFKsUcvrOvE8nW8bZ9CE2_AJE,472 +lm_eval/tasks/model_written_evals/sycophancy/sycophancy_on_philpapers2020.yaml,sha256=RBwBf43v6qzyyRbnn4lywIzE4pNM6awByLCHpx41RgE,480 +lm_eval/tasks/model_written_evals/sycophancy/sycophancy_on_political_typology_quiz.yaml,sha256=_WmUxnWGHSFeHrprbpRVSxSZi0x04zQkidtz3Xel41Q,500 +lm_eval/tasks/model_written_evals/winogenerated/_template_yaml,sha256=88JSkKg0JwxrO40NTNGxlAGSBfx7_CSFHZLdGXAF7xE,316 +lm_eval/tasks/mutual/README.md,sha256=ugTeZBjsZsvrKpg7RrybWTWTPWcnvAwqUwjRNySkuHA,1516 +lm_eval/tasks/mutual/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/mutual/multual_plus.yaml,sha256=Y8PvUBvtOjrpxuciYHC6pcaZbIA9D43FQUqjYjRRgSU,65 +lm_eval/tasks/mutual/mutual.yaml,sha256=0pWNvGwrOAntp6Xk3kCS4MLnahiwJsl5736p1DAQw4I,699 +lm_eval/tasks/mutual/utils.py,sha256=KkQlSOhZb-wZOz2GhpeOtKr055kPMkBW588vcpShgH0,1173 +lm_eval/tasks/noticia/README.md,sha256=-mYEm0wqL2oKRZCn8up4vLpnQDpkh6a-yN_pUqmv9CM,2121 +lm_eval/tasks/noticia/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/noticia/noticia.yaml,sha256=mjUIfLV0wIPEYbCCpa6K8MvOz6Nkxf0qb6o18_t7NJ8,1326 +lm_eval/tasks/noticia/utils.py,sha256=vGXXn9CKDFNSFrua3U7yE3Ca1znGpP7aTn3WdedloP4,1086 +lm_eval/tasks/nq_open/README.md,sha256=BKcM_NY_2bKQ6RawTdraHBQuK6Ja8H_aOb_S9ST3TQ0,1165 +lm_eval/tasks/nq_open/nq_open.yaml,sha256=tSIH0Z0_5HrtU2yMuOD43rfrr1rKWHIDGDbNVffOJrg,743 +lm_eval/tasks/okapi/arc_multilingual/README.md,sha256=wfu3vRVNTb0eR66GSuDxLTMnZw03XTJ6lfTZZWv4VOc,3253 +lm_eval/tasks/okapi/arc_multilingual/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/okapi/arc_multilingual/_arc_yaml,sha256=C0eGCqr6EgJYyiix3nXuSidDUESZmBYZQOHWSRzySVg,512 +lm_eval/tasks/okapi/arc_multilingual/arc_ar.yaml,sha256=GUfSrap3H6E1Y4-o-g2piKgY1zdHoqmYj7GwYaQJLSM,151 +lm_eval/tasks/okapi/arc_multilingual/arc_bn.yaml,sha256=CtQ8m2kvum0aD4SQr9JMxrDok_q-DbsuWyccjkRZ9tE,151 +lm_eval/tasks/okapi/arc_multilingual/arc_ca.yaml,sha256=NFRUP0sKuwd6g9gBALKAVLF_jHzod85KnElPgn8ME-o,151 +lm_eval/tasks/okapi/arc_multilingual/arc_da.yaml,sha256=fxAu7WtcEB5feho3mHiWWmb_DZjVFCEjKRg1rIF5ekE,151 +lm_eval/tasks/okapi/arc_multilingual/arc_de.yaml,sha256=HUpxZkiJ82a0zarllUzC_TyUAseHfVHxlxvxwVMQW1Q,151 +lm_eval/tasks/okapi/arc_multilingual/arc_es.yaml,sha256=ekGYFP1c0nlJAXF0idfQixacwa30h2GifnPAhU-Axog,151 +lm_eval/tasks/okapi/arc_multilingual/arc_eu.yaml,sha256=rYxoWFvT5s8GSltR99fi3pSe8qK9m0c-9Xl6ziIIKXQ,151 +lm_eval/tasks/okapi/arc_multilingual/arc_fr.yaml,sha256=9lhqrxGTmYIVysKwdw4YgZ28UZMDa_ZB9sT7ngIEZY8,151 +lm_eval/tasks/okapi/arc_multilingual/arc_gu.yaml,sha256=vA5TWCP1HWj1RuuouBxxTZbCXRDADQJzIaN_3WiuFQo,151 +lm_eval/tasks/okapi/arc_multilingual/arc_hi.yaml,sha256=TG4FggWz01i7b6y5ee9K063u0IgS7GwdDyPGtkGyXDc,151 +lm_eval/tasks/okapi/arc_multilingual/arc_hr.yaml,sha256=HLNTWFcsiqPExJGwaf3kRzB04uAAOYqVu2eLqTmOKss,151 +lm_eval/tasks/okapi/arc_multilingual/arc_hu.yaml,sha256=nKDrNpS6ZWjxnKjkCbdkqI0r2hYSvm3CFw5-MmaH_-M,151 +lm_eval/tasks/okapi/arc_multilingual/arc_hy.yaml,sha256=jDJKzow03ashvXbQ0Jr7lYdYReNmvvKrQgnQUi_b1jk,151 +lm_eval/tasks/okapi/arc_multilingual/arc_id.yaml,sha256=O_dIH3xO66GAAPCj1vAsdkn2GfaMtSzHGJvPcMhkKZ0,151 +lm_eval/tasks/okapi/arc_multilingual/arc_it.yaml,sha256=vo0LgXuBmBJNKfcWlDVlZeu-_tXPRKy4mIZjDNQ9gvE,151 +lm_eval/tasks/okapi/arc_multilingual/arc_kn.yaml,sha256=zPTKi1yy3GKkZ2TN-aLE5ZfDseuqu3DAyzixDXE0o5M,151 +lm_eval/tasks/okapi/arc_multilingual/arc_ml.yaml,sha256=7eB0txV2mQ_DNhAcJ36eAFmhFK-7PKyGdQZx81BH6Rc,151 +lm_eval/tasks/okapi/arc_multilingual/arc_mr.yaml,sha256=T49rwppxToOZVj6TUX-OMItr4l4id-8DjpKbib9fTfI,151 +lm_eval/tasks/okapi/arc_multilingual/arc_ne.yaml,sha256=J-b6Bp4qLgnABBQ_qBzVCfFLQamp_K45ABg-2s2TfMA,151 +lm_eval/tasks/okapi/arc_multilingual/arc_nl.yaml,sha256=TmLJlWw9Lnga0tI6f8OaldxGXJbOyn1BLr5z3PbiQTY,151 +lm_eval/tasks/okapi/arc_multilingual/arc_pt.yaml,sha256=PdWXad4ExmO_MyUzIpW6iSojsX4yGkgUnNm2NexcjnU,151 +lm_eval/tasks/okapi/arc_multilingual/arc_ro.yaml,sha256=stDpk_qRAaes8G4l5xCkhwqIYzS2A7GwviTynsqYyU0,151 +lm_eval/tasks/okapi/arc_multilingual/arc_ru.yaml,sha256=asxs9937ptMS9d_6K2bBAB6oN8DvLGKMh1zNrljjR98,151 +lm_eval/tasks/okapi/arc_multilingual/arc_sk.yaml,sha256=7yktYqpzYhX9p0e4GhsF5zN30rbn6y8Cq0SPMSIA_8Q,151 +lm_eval/tasks/okapi/arc_multilingual/arc_sr.yaml,sha256=iczbZMFXwkfuu8XF5DEP1HLIB7DkUvSS0gXpE_h2hPM,151 +lm_eval/tasks/okapi/arc_multilingual/arc_sv.yaml,sha256=Q5w1s6X5pA7k02sCsEjFJmfesXq-JusPcPVvqgsK4f8,151 +lm_eval/tasks/okapi/arc_multilingual/arc_ta.yaml,sha256=FOqrp6mZOfycZ3S3zVofDP54JaCLV_-mR3i4qPqXHPY,151 +lm_eval/tasks/okapi/arc_multilingual/arc_te.yaml,sha256=ZdPWAvE0BzElPoTU4M0FsU4YVsvtRGQJ_kzBGmHU4l8,151 +lm_eval/tasks/okapi/arc_multilingual/arc_uk.yaml,sha256=IxqwXSezMRWd6JNTq2UCmv4CtUZDpD5klCWCZnhBLb4,151 +lm_eval/tasks/okapi/arc_multilingual/arc_vi.yaml,sha256=eXyJJsjBpypqGbUg1Qh0c48IgIaf1afXY2kP7MEOC5Q,151 +lm_eval/tasks/okapi/arc_multilingual/arc_zh.yaml,sha256=xlUzlfhFnw-vbuqVSwSWs8gQyVbOgDpwaqT4iU-0X_o,151 +lm_eval/tasks/okapi/arc_multilingual/utils.py,sha256=ko8R7sI6zHF3dfFW2KMIzCbdYj9U6R62vaPaCcqeMoE,932 +lm_eval/tasks/okapi/hellaswag_multilingual/README.md,sha256=4z3CRVjiccEASnN6iZzAs1n4MP2sDyZD7cU2KHYGp8Y,3269 +lm_eval/tasks/okapi/hellaswag_multilingual/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/okapi/hellaswag_multilingual/_hellaswag_yaml,sha256=0jhXFTpgwTNxw-wyGI6rOgwcEVLmX-mu_WNP-6smuEM,466 +lm_eval/tasks/okapi/hellaswag_multilingual/hellaswag_ar.yaml,sha256=l0LPyaELaXf8NzIQE6dCAkcC9G8s0zY9oHbv95pvGW4,144 +lm_eval/tasks/okapi/hellaswag_multilingual/hellaswag_bn.yaml,sha256=t7ekl4qzC__k5H1e0yg6LrUXyDNTjVaC3xakhSj6lHA,144 +lm_eval/tasks/okapi/hellaswag_multilingual/hellaswag_ca.yaml,sha256=RzmIaCpglp8CcEY62K-mAdhmPmgELLInaTf5EoMoNZ8,144 +lm_eval/tasks/okapi/hellaswag_multilingual/hellaswag_da.yaml,sha256=Ij9O8OKS_1dRxqd-z1Ks5ivZ06upvAPdEQs99TgO5JU,144 +lm_eval/tasks/okapi/hellaswag_multilingual/hellaswag_de.yaml,sha256=3YbkR_Jmp-7yJ8EoarJtn7UvzCuzLqgEOPRzFH3KZ6w,144 +lm_eval/tasks/okapi/hellaswag_multilingual/hellaswag_es.yaml,sha256=4ytqybHZo2wm1nm57Tk_FHJPqcANYwmut5DpqE0DR6s,144 +lm_eval/tasks/okapi/hellaswag_multilingual/hellaswag_eu.yaml,sha256=IRuQ9XevBmOv1_MyM1XsMUrnOeUdfE91sNAui-hb0HI,144 +lm_eval/tasks/okapi/hellaswag_multilingual/hellaswag_fr.yaml,sha256=cXc43d-zTl-9qldmhg8uIFn0g3LhUSWORxIP6zu3Dk4,144 +lm_eval/tasks/okapi/hellaswag_multilingual/hellaswag_gu.yaml,sha256=S5vvIk-BGoV_jmGbTEm5HboeZccPlBYNZiRGxgxioAM,144 +lm_eval/tasks/okapi/hellaswag_multilingual/hellaswag_hi.yaml,sha256=HWI_hhPvrTclmejfKO_GUn9JtOt3cNUfpiXsn_pp1lQ,144 +lm_eval/tasks/okapi/hellaswag_multilingual/hellaswag_hr.yaml,sha256=rwOKwbT0-KDap8CPVfSKxL1cFiwKpVNQJ6kk9r7d3Z0,144 +lm_eval/tasks/okapi/hellaswag_multilingual/hellaswag_hu.yaml,sha256=W7frkGGv-b1_8ZQKJzBHdYpUNXWPmM8tIoQSWyVncZ8,144 +lm_eval/tasks/okapi/hellaswag_multilingual/hellaswag_hy.yaml,sha256=M2Ohsg9CuAmRPICo_n1WuPLCwYNqlzmSQClOxd538q8,144 +lm_eval/tasks/okapi/hellaswag_multilingual/hellaswag_id.yaml,sha256=nzcPwPcGNsWzevywK3YYEKptjgSUQ9du4O44nuSP4vM,144 +lm_eval/tasks/okapi/hellaswag_multilingual/hellaswag_it.yaml,sha256=G_8i7LKwqwzPvPYW_q_A9Sbdd9g385VV1h01IN4phr8,144 +lm_eval/tasks/okapi/hellaswag_multilingual/hellaswag_kn.yaml,sha256=IDfcOaIrqF4TsFVxfLCrRoNAOTPpE9FjwvpqmULVwOA,144 +lm_eval/tasks/okapi/hellaswag_multilingual/hellaswag_ml.yaml,sha256=CGxvMPTxmOXMH9B6iBayfPYoorKzxR9rALDvthlFcKs,144 +lm_eval/tasks/okapi/hellaswag_multilingual/hellaswag_mr.yaml,sha256=-C8-qKzAIGqQCD4u-rShLKoGwSCwy1xTaMM6KZOH7fw,144 +lm_eval/tasks/okapi/hellaswag_multilingual/hellaswag_ne.yaml,sha256=fPMejMR7lhvXyvIs4TYHBmujPFtcfQkMXjtZumfUuxo,144 +lm_eval/tasks/okapi/hellaswag_multilingual/hellaswag_nl.yaml,sha256=qOeQrtnPB3a4bnfDnxy2ISuHhPGPeMQYt5B4DIdkQzI,144 +lm_eval/tasks/okapi/hellaswag_multilingual/hellaswag_pt.yaml,sha256=NTMxraiO1AvjNO7JXDDauQJQUlBBqKdoDRWGKkAaKRY,144 +lm_eval/tasks/okapi/hellaswag_multilingual/hellaswag_ro.yaml,sha256=UmN6zcXVGCHLjB6LlKuig-5YNfVIpc3klngnc96W_YE,144 +lm_eval/tasks/okapi/hellaswag_multilingual/hellaswag_ru.yaml,sha256=HsEQP37NJQMUJuaRROA5W8gUeuwancEmNzU6U3T3ygY,144 +lm_eval/tasks/okapi/hellaswag_multilingual/hellaswag_sk.yaml,sha256=xvl4FRUN-j9F489dz9X7j0Tzl9-HJb9JL9Tts4q79Lo,144 +lm_eval/tasks/okapi/hellaswag_multilingual/hellaswag_sr.yaml,sha256=Z-sN8n9o9gNhfDHSLLg2LAr9mlNvprbd0pSVzzuxjgk,144 +lm_eval/tasks/okapi/hellaswag_multilingual/hellaswag_sv.yaml,sha256=0Dq9CK5xLMyNRDiMBdjjb0zf8t6hAZ7DbIiVMmUKQv4,144 +lm_eval/tasks/okapi/hellaswag_multilingual/hellaswag_ta.yaml,sha256=4YgCFg5GzveS6uuSuw8MRiCXCkGDc4r8imElHiTTx9s,144 +lm_eval/tasks/okapi/hellaswag_multilingual/hellaswag_te.yaml,sha256=IROovZjiHwQ6lsmjGSpXHopDzzzzBw13TZZcWsiz_g0,144 +lm_eval/tasks/okapi/hellaswag_multilingual/hellaswag_uk.yaml,sha256=4Oa2_jshiQqBSTHKi64FQGnfk4CE_Y7Rw_sv6z2_jog,144 +lm_eval/tasks/okapi/hellaswag_multilingual/hellaswag_vi.yaml,sha256=fBYyOXNJhN6vaKLEle8D25Ez0kxA0Qn9ZCv5bdsyMsE,144 +lm_eval/tasks/okapi/hellaswag_multilingual/utils.py,sha256=B9I7YLKPKk9ljc-EQGI6Y_5mRIVM6bhGoRTd6YDcEhQ,717 +lm_eval/tasks/okapi/mmlu_multilingual/__pycache__/_generate_configs.cpython-310.pyc,, +lm_eval/tasks/okapi/mmlu_multilingual/_default_yaml,sha256=_nS1PruLgtWtlzjmYZJ6bQ8f26gP_QyoUV9e-Npq0To,432 +lm_eval/tasks/okapi/mmlu_multilingual/_generate_configs.py,sha256=9Og9BSixaMRUQPj1my0FedXN6f0B9zuYyXpqYlYwWpw,728 +lm_eval/tasks/okapi/mmlu_multilingual/m_mmlu_ar.yaml,sha256=h6GQxvV_gIZ1zBUD_f3UHt8--Wff3I6Ee8pAY7vyVXo,92 +lm_eval/tasks/okapi/mmlu_multilingual/m_mmlu_bn.yaml,sha256=_2pk6E9tePnNYYEOgJMACQ1QX4956qligOjauDMNE0s,92 +lm_eval/tasks/okapi/mmlu_multilingual/m_mmlu_ca.yaml,sha256=kpXQk6AdUGs6BSmUkL2-Pn27gic2MyazkSov_dMTnSk,92 +lm_eval/tasks/okapi/mmlu_multilingual/m_mmlu_da.yaml,sha256=ZVzwQbLv3eap0eeGR75plXRY7lizfJVlEkxAMVFJ7nw,92 +lm_eval/tasks/okapi/mmlu_multilingual/m_mmlu_de.yaml,sha256=hK7VkH36-4joAq0M_7MynfvbqR446CFj-EgG8hqNCVs,92 +lm_eval/tasks/okapi/mmlu_multilingual/m_mmlu_en.yaml,sha256=7QbX5n0CujxGxy_yaYzR85P9pOgltohWv1SrVPIopvo,92 +lm_eval/tasks/okapi/mmlu_multilingual/m_mmlu_es.yaml,sha256=CsEEvte2hs-yr0_9yHv40GWZgBh4SWcWg0CTi4GsyU4,92 +lm_eval/tasks/okapi/mmlu_multilingual/m_mmlu_eu.yaml,sha256=IL527-o6W2KWea6ZzvaHNIM145pSqnVWJOqMTiMWN2M,92 +lm_eval/tasks/okapi/mmlu_multilingual/m_mmlu_fr.yaml,sha256=-YP-PTybGhocLweew3eS5dRRxAwKr5oK3cJ6vxmZHHM,92 +lm_eval/tasks/okapi/mmlu_multilingual/m_mmlu_gu.yaml,sha256=KyF999oEHZ--YaoPDdBGMmym6aJQxLmzHr9Anuce7jo,92 +lm_eval/tasks/okapi/mmlu_multilingual/m_mmlu_hi.yaml,sha256=EMFeDAm7kJSrHacGGbX_HYdnmRn7-K_DYnEuXoRKca0,92 +lm_eval/tasks/okapi/mmlu_multilingual/m_mmlu_hr.yaml,sha256=_Uk3BhkxNyVfvxvByQ4x-enRmgsqd8t7S85-kvf1J5Y,92 +lm_eval/tasks/okapi/mmlu_multilingual/m_mmlu_hu.yaml,sha256=3JaXdWUcyhkfZTRexLe1zv5aDqqn5WS3aPZftgmY2GU,92 +lm_eval/tasks/okapi/mmlu_multilingual/m_mmlu_hy.yaml,sha256=MKAH1lUnVmeTGWNEYSWLi2X-HwSKkQdc103fPpv0foU,92 +lm_eval/tasks/okapi/mmlu_multilingual/m_mmlu_id.yaml,sha256=esgl1zfYWbQswe2srAk3KnTyOhfGFRY8sOmc8Loqt-8,92 +lm_eval/tasks/okapi/mmlu_multilingual/m_mmlu_is.yaml,sha256=irlR7YVJhqYzqR3CFrH4oTz4qT8FSFuWKh-jUGqq-PA,92 +lm_eval/tasks/okapi/mmlu_multilingual/m_mmlu_it.yaml,sha256=H-2fL-fJTX54O92L7DizEsVaLTNJLbpLnYOTVr3Poc0,92 +lm_eval/tasks/okapi/mmlu_multilingual/m_mmlu_kn.yaml,sha256=IuvnVDGU53Nm-XBveOusoOVXVrxbE_-Bmyn9BIDbg68,92 +lm_eval/tasks/okapi/mmlu_multilingual/m_mmlu_ml.yaml,sha256=9UB7Wkkr-TJ55aY6JkCYnoZx50lge5qn7F5lirlTQT0,92 +lm_eval/tasks/okapi/mmlu_multilingual/m_mmlu_mr.yaml,sha256=0YeEhV_HoKmj9UDfRC7CTrqsFUoSBRRNicXKlMMs7LI,92 +lm_eval/tasks/okapi/mmlu_multilingual/m_mmlu_nb.yaml,sha256=wjdrATM8UD73RXgzkneOkM_2IC818KWbOGPgAX0OrKY,92 +lm_eval/tasks/okapi/mmlu_multilingual/m_mmlu_ne.yaml,sha256=qZ3CwX3s7etn9s9HUZzLksHF5SIcp_IUJW45xzLQsds,92 +lm_eval/tasks/okapi/mmlu_multilingual/m_mmlu_nl.yaml,sha256=mdiemcArNpjmR-DRUKNBnV8q38Hcxfwze18IRiCu8Yk,92 +lm_eval/tasks/okapi/mmlu_multilingual/m_mmlu_pt.yaml,sha256=8HyrIK7kpDXqCa2TQH2LMibptIZkWOezThJui1tZfgo,92 +lm_eval/tasks/okapi/mmlu_multilingual/m_mmlu_ro.yaml,sha256=CzkEqPnWBTZHCytOTqCuVkncFrfdRwSIxBxCxNBCo3o,92 +lm_eval/tasks/okapi/mmlu_multilingual/m_mmlu_ru.yaml,sha256=GfeM1f8SFv1uzboAtJZKRRstmbbIZawKChZYDxTF-10,92 +lm_eval/tasks/okapi/mmlu_multilingual/m_mmlu_sk.yaml,sha256=ciP7Xrudh6X-rx0PdKmZUVlf2bhVu0RrQ71H5ZUnPkk,92 +lm_eval/tasks/okapi/mmlu_multilingual/m_mmlu_sr.yaml,sha256=O4p2dTvXZBh0hmQ1iSeEy-trLawduDigF3vq4gCPQas,92 +lm_eval/tasks/okapi/mmlu_multilingual/m_mmlu_sv.yaml,sha256=eUer_Wl3XtW2EyV4VdZSINBgYciBKtUdyirq_Bdzy7g,92 +lm_eval/tasks/okapi/mmlu_multilingual/m_mmlu_ta.yaml,sha256=GDVxF5OAsmBj-qJkG_vtcc-9kwJcqlI9V3GXn0nF8Dc,92 +lm_eval/tasks/okapi/mmlu_multilingual/m_mmlu_te.yaml,sha256=8uAJI91GbBCoo-ylFKJH4Fq_XMS4soqn0qO9agVYp9M,92 +lm_eval/tasks/okapi/mmlu_multilingual/m_mmlu_uk.yaml,sha256=IJ1vtrihXYJEGZp1kd2mF33Fu_4s_EFH_0wFqVRq48U,92 +lm_eval/tasks/okapi/mmlu_multilingual/m_mmlu_vi.yaml,sha256=of143NO6V0X-cTdCXRHC5tViJ78iCZ1UvvArc_9b318,92 +lm_eval/tasks/okapi/mmlu_multilingual/m_mmlu_zh.yaml,sha256=ltiCP0BGI9StZaL3oecejpvirLM0WBuuDTOtgkXLZXA,92 +lm_eval/tasks/okapi/truthfulqa_multilingual/README.md,sha256=5mR61sRmT8uet9zZdttHzRmjj23vSKAKtKYwT1Uyai0,3274 +lm_eval/tasks/okapi/truthfulqa_multilingual/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/okapi/truthfulqa_multilingual/_truthfulqa_mc1_yaml,sha256=pojaYF1ZnhXkFI8AlNPYYOadhAr-m-La4TuHsXQTtZQ,443 +lm_eval/tasks/okapi/truthfulqa_multilingual/_truthfulqa_mc2_yaml,sha256=JHAdAjp0Y8DX56WoKuUWwNdNRiYY7U64csXvURefv4Q,300 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_ar_mc1.yaml,sha256=XZ0L6nbD8r47BJhUi1_IwB_AjImKY96sI4qnr3nyX2U,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_ar_mc2.yaml,sha256=u5t72lIsyNy_-3AkMzu4E9u4yxajWdGYqLBLP0XM17Y,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_bn_mc1.yaml,sha256=hrJWejUP9VOkNajkrftLFGm4_jk5pkuRF2_GHzqBsV8,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_bn_mc2.yaml,sha256=h0y5npsVGKBPHmJK6BEyIFYGpKc3guVrNVxz9PzjzUs,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_ca_mc1.yaml,sha256=ku0a8fhVSHTKgOMHYzmPj0N1RcZFwicp1YN_7n15E1o,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_ca_mc2.yaml,sha256=jz16vSR9x87Yhxza2Ieh1u-AsZk4AwuVh2RFJNBWrco,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_da_mc1.yaml,sha256=T4BrCGyXBgmFa_07Szlm2aEojCewd73B5EoACg7z3bk,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_da_mc2.yaml,sha256=_JCC3OVWXlHgwMsZ-eiuYSpKOwsthkyNqXiWllMZGRY,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_de_mc1.yaml,sha256=5MnDT5j2jKUXW5OPh2T5U41jT3wUpF81Ey99BKrm2VE,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_de_mc2.yaml,sha256=Y6ngRIXEPH65wfTMOspH_Zml_K_cbwQAIl5-bJ7liR8,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_es_mc1.yaml,sha256=EKkp34UVPoisCzSbmE0w2jzFKrmTGY0AhFLatTivDng,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_es_mc2.yaml,sha256=f3t99xrcdubKXY-5bVKibDL3EL3QWR022DlXNqdX2R4,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_eu_mc1.yaml,sha256=04DdmvEgOO24eqcwNja7WNDz0jBvVbpNpslRE7wuPDc,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_eu_mc2.yaml,sha256=2RECrkJz9EsufzurgClIKtIjhxWwAIG1BuXDCQfXKkg,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_fr_mc1.yaml,sha256=RofytSYka7h6_QHB_qRkpKyjjafDxM8ZPnNzrjlvJpY,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_fr_mc2.yaml,sha256=SQP3CjzVBjrOzBrvSc_-yNfOgvku6c-yyZIdu5tIYMM,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_gu_mc1.yaml,sha256=pnLuJQfK3FYeOhKZHdc8z155cIhKAHOeYJQS8ksre8M,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_gu_mc2.yaml,sha256=oIySv4YCjiPNtnc82dwNbyr9_IKeAEuZ60fo1Aus1u8,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_hi_mc1.yaml,sha256=Av7qR8izVZtsxYkwtxVuIQomgjsEGMRL216-MoNSlyY,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_hi_mc2.yaml,sha256=BoEB2HImbuVuuRV_-AVx2mU3HHZZp_-m9SaTvfw4aiU,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_hr_mc1.yaml,sha256=ZVgznGd3L_PvVFeUJxhYYtA8q6VLMei5S997U1KgfN0,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_hr_mc2.yaml,sha256=kK_1WV86hAMKZzyeFT37we39oOiG88OmwpcCef_oVdU,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_hu_mc1.yaml,sha256=U5uXVrjhBNhoqpRe2p9SblvJKE-2B-b5nbU-9tiRuw0,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_hu_mc2.yaml,sha256=aKWIWtK_8kJGj_lgxptpmjuvNiYJbTnBeej9h6cnbss,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_hy_mc1.yaml,sha256=Alo34MOGtbgVI9C0sAQb__Ix79-Jaz55qmymzlZdztg,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_hy_mc2.yaml,sha256=qjnxRy-_CPcjnzAEKh7BVY20gZG3N11FgQuAUpa_IIg,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_id_mc1.yaml,sha256=NMDkzVeR_IV4DGAgZQCnIgr9T33BQ9mqaKkvLbacZuI,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_id_mc2.yaml,sha256=iCq1z8DcPT20oPF26ZecqU-jst_S-cFlKS-KcknTaAs,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_it_mc1.yaml,sha256=zcSgJ70NQAMFmAQQJ4Elbset8onYIAueA8TmupqOOoI,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_it_mc2.yaml,sha256=12-d5lMsKvNA_PY81ViIK6ZgLS-lAv5on4G2OgkwjDw,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_kn_mc1.yaml,sha256=tdve8fGXpi9Fi2DvSC_ir2gLhLpm6023S3uRllPyBMc,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_kn_mc2.yaml,sha256=p5x8o4C23OHrtSVgnaEfcDxwZzr6xgtYHRCuqyPqtWM,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_ml_mc1.yaml,sha256=KZfV6-C8pzVI28esUeJFLhyBCd77IxF4KhMQjV_t7j8,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_ml_mc2.yaml,sha256=0GKkKdCmUzNHjGFEdWrd4bFtjOuN1OdpKvidswjNRLY,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_mr_mc1.yaml,sha256=7QeINTdan90buFaJIZ5m6fUG1NaAtONV51MBi_yNbrY,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_mr_mc2.yaml,sha256=BSGbUlZNrDQiJ8oJ2VlbjphQCMA7V7GsKqSiXwf8gw0,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_ne_mc1.yaml,sha256=0zDbEBYszWuNqhJjQdikx3RdE_wWpvDbsHnsyP_3WFg,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_ne_mc2.yaml,sha256=CEvej4sPnXWEeET5-ahR6otYFq4l8vQ72VN8YxRe0sA,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_nl_mc1.yaml,sha256=WKW2pXKaPYb2_rwlAMX11k6MTnfB_Ql49aOmOQzrLJ0,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_nl_mc2.yaml,sha256=VWQ9vTj6yammjVuaJjkU3K7DSMh-X32Pwr472RPkjJw,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_pt_mc1.yaml,sha256=WCacxkJc0dCvpDh9pkvVWSWBwhfZitWXN6LXuArSqS4,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_pt_mc2.yaml,sha256=-_hxts1dW5rCvsY9j17RiLqDO9S4uRwwM8aKsBueX4I,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_ro_mc1.yaml,sha256=ilc2h2XJAQVWODAVWmiUTd9yZKBnTcCMg2VF7Zt__iA,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_ro_mc2.yaml,sha256=2zzf0b3V1lBGNpySCol_vaDqBVkmMPy723eFgYQXEUE,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_ru_mc1.yaml,sha256=mwlZVfO4LHhD1cK5fDTPH5tBKu_LceGBG7CeH-d99j4,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_ru_mc2.yaml,sha256=5q8SPV2RvPBfX__znaiC7hCpDI_QpAgGvGdyd5CfyJE,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_sk_mc1.yaml,sha256=7bZ_rFRn3hEn4lWL9QzQg-Yk-7D5xyW3u2-eYIgYRCk,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_sk_mc2.yaml,sha256=sVjl8jK2HuOy4QjIZsL_H5PyI9gPcXrpWYXEq20coJU,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_sr_mc1.yaml,sha256=X1t0CJZMHLeED5AGORHTTSUUZA9Nilzx9WtjG2Rxe6w,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_sr_mc2.yaml,sha256=1nbX_x-XVepRwMh4Kid0Tx0dSlareRsFDMcD5UpFKiM,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_sv_mc1.yaml,sha256=3SYAOouUnwc3J1H8ypKZ3uNK_yWKtceOakTcQRtql_E,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_sv_mc2.yaml,sha256=dul9j8WMuvMj-aGR4ef7WB96Zvpd7tSP7pzQT4GbeiY,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_ta_mc1.yaml,sha256=kY2V2iR1B68-g7AP-EALuH21O-5J1eSG37ULwMBPscw,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_ta_mc2.yaml,sha256=XC2KpaOSUNIGnzRx0uXzuzZnJIsLuln1Vbs_WLC8u-g,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_te_mc1.yaml,sha256=zOwXU_Ng4DDFTOQ6z55i6kJo8Irx4mY1XMfBsEJXZqs,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_te_mc2.yaml,sha256=olw16FSN7u3Pke5GnwqwTAnjfiloBa2g6lcFvnd2f9Y,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_uk_mc1.yaml,sha256=JCMdgV05y-maBNx85qagmrWWsg6PutHcE2602ZE9v4Q,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_uk_mc2.yaml,sha256=BQy-ePy9n26R74tAAeUTDkMDD9_dF_y42212qFTzVVw,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_vi_mc1.yaml,sha256=Jaszk4-46pFnQgmkWKoz3VlBCQjyeYY4a1OnA_IB5k0,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_vi_mc2.yaml,sha256=lK94f9BByr1wm4WaYxwUEv7oBrNCGlnOlnJUHMbVGAA,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_zh_mc1.yaml,sha256=jmdw5UNjzx_S0nxuARCEnRVhG3-MrakwaTGxaqUb0WE,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/truthfulqa_zh_mc2.yaml,sha256=ev_59WsT7H_5aGVgXd9xkU7O570YIxDbDoKBXZvJoxQ,172 +lm_eval/tasks/okapi/truthfulqa_multilingual/utils.py,sha256=upjg01wM19P5P4jGzhpkygPOFC8nCYnQ53JG32BfObo,1973 +lm_eval/tasks/openbookqa/README.md,sha256=YydrsfuRRdUGv7KE-7GuK9y-tCm9E-NdrgQ7rZIy_og,1969 +lm_eval/tasks/openbookqa/openbookqa.yaml,sha256=YiSwjnsPL1TFTSkplPZ1ISE_SbUCib6PIjIapnW4yJg,524 +lm_eval/tasks/paloma/README.md,sha256=TGtZGpyGpjFa5VMZQS7NJoZr_hhk1JAZDCLby9FWRoY,2391 +lm_eval/tasks/paloma/__pycache__/paloma_utils.cpython-310.pyc,, +lm_eval/tasks/paloma/_paloma_template,sha256=YlkdQFN5HQtVquhxbBw7n6dJU_Ssu6qaoGAqZVa-NkU,590 +lm_eval/tasks/paloma/paloma_4chan_meta_sep.yaml,sha256=PJF4hLR7IeZdVfclb8EQYqf5hkdm9sahiF46YzFmxx0,101 +lm_eval/tasks/paloma/paloma_c4_100_domains.yaml,sha256=L-EZjmIPO9mDaaPAP6FNNMJhxH9v8PQWj80qfHWQQxs,110 +lm_eval/tasks/paloma/paloma_c4_en.yaml,sha256=4Gb_X8rISq7CoiBRbbMEUp2XSWnQEN4ynLlZHbzr99k,80 +lm_eval/tasks/paloma/paloma_dolma-v1_5.yaml,sha256=hbSxEJLk-bZ6Ouqgb2-ysW2s819FqDWU9dOeqGbzfyw,98 +lm_eval/tasks/paloma/paloma_dolma_100_programing_languages.yaml,sha256=SntcXhkiqLmayvjWe7DVJZxzfhV_Lu5fKr3UESSlX4E,135 +lm_eval/tasks/paloma/paloma_dolma_100_subreddits.yaml,sha256=eqK9bEiZ8gq5d2doTWk71PSHTqTGX3a7bzSSWuZkviY,122 +lm_eval/tasks/paloma/paloma_falcon-refinedweb.yaml,sha256=-QUoFCEnVEvtiwo85n5CvdpSnhKbkyuJuA9zTIG8WWg,108 +lm_eval/tasks/paloma/paloma_gab.yaml,sha256=pZ6Bi6wpcAlZiroIxOUEJ3r1aZwsxG7TYpkn5eqJA-w,77 +lm_eval/tasks/paloma/paloma_m2d2_s2orc_unsplit.yaml,sha256=7NPJHgn0czPATgz7Poyt7sC79iaVwAnfTvZMWdbzkj4,114 +lm_eval/tasks/paloma/paloma_m2d2_wikipedia_unsplit.yaml,sha256=oRckidelzyjBRL8fYTQhS9_dJRdKUAskxmQ7du-uQU0,126 +lm_eval/tasks/paloma/paloma_manosphere_meta_sep.yaml,sha256=xTdsLHcH5I74gbO8PQQPZacgg94nKmiwfleUrgXozlA,116 +lm_eval/tasks/paloma/paloma_mc4.yaml,sha256=qfqAFJYscsqht_YyeHTbKxekMqtoCxJNTVM1rEjmKw8,77 +lm_eval/tasks/paloma/paloma_ptb.yaml,sha256=WDXYFOVlYMc9bPJfpHQaosscMLBnomoLhmXL9tBVu7I,77 +lm_eval/tasks/paloma/paloma_redpajama.yaml,sha256=abzWMkyWfo6etFevbSoUcU45yU4Gj8YrJwOG1HyA3g4,95 +lm_eval/tasks/paloma/paloma_twitterAAE_HELM_fixed.yaml,sha256=qWkSpmrMeLvDssMiMPR7c1LoIKTg6yMgxie_Icyqv-M,121 +lm_eval/tasks/paloma/paloma_utils.py,sha256=l1NE5nHHWqX-eZSKaMBOtu7U8mHPPU1u7VV4nDhw4ew,52 +lm_eval/tasks/paloma/paloma_wikitext_103.yaml,sha256=gmmcqJQd61VtqMSWiMSEQc1I_LjkTPrq2Lyp3xdoXZ4,104 +lm_eval/tasks/paws-x/README.md,sha256=YO_eiOakPQ7dgmaeZEGcAlpd2AaFFH5HGRLPVmQceXM,2480 +lm_eval/tasks/paws-x/__pycache__/_generate_config.cpython-310.pyc,, +lm_eval/tasks/paws-x/_generate_config.py,sha256=OEE5wsJx2uGsyWe7cQFiRqPj1FVQ0qkL5eGY2vxaJJM,3066 +lm_eval/tasks/paws-x/paws_de.yaml,sha256=8rpK-nGyV3aDCNBBnLVze-fMbXf5TdJ1N6upcrJYM5A,204 +lm_eval/tasks/paws-x/paws_en.yaml,sha256=qDS5_V-KCVDBYdLzWpDfwKe_kNmGZGZ7_RLRDfW7JoA,197 +lm_eval/tasks/paws-x/paws_es.yaml,sha256=HM5pkreetDL6SuBSJq3ZHR8NvnONbTrLDxPW-hMkQmc,201 +lm_eval/tasks/paws-x/paws_fr.yaml,sha256=us8AGzpyfy5eKoFIUzAgKMiBboAm4VpsXoUGdQT4ifk,215 +lm_eval/tasks/paws-x/paws_ja.yaml,sha256=VBkjTeHL8VbGlKAc2D5iSj1pcKGtpkhcZzD2A4Dapzs,215 +lm_eval/tasks/paws-x/paws_ko.yaml,sha256=n3Ik828O3y-vA65_hnN_t57JE56vJR8yGHP5bNg5hSQ,206 +lm_eval/tasks/paws-x/paws_zh.yaml,sha256=L_G_vTVQO_KspHyL9xD_SW1EglMVgWhskrxPpYRunqg,203 +lm_eval/tasks/paws-x/pawsx_template_yaml,sha256=NwiXP1Dj30pRhC28UbX1hZvo4zo-7nSko6i9HkkAMuM,502 +lm_eval/tasks/pile/README.md,sha256=pihxsbWkjJ9AYuoDGWJpa-2ijpv4MV-78uwcneK5SKw,2120 +lm_eval/tasks/pile/pile_arxiv.yaml,sha256=o_d7qDUGV1eHHCUn6flz1IlGen7k2j41I2B7-V9r9hY,560 +lm_eval/tasks/pile/pile_bookcorpus2.yaml,sha256=IRneHp6DVJQJLg79L1WAUXcI4H2j98CMJ8WJM9T_9t4,79 +lm_eval/tasks/pile/pile_books3.yaml,sha256=i9giqvgl9T4zaT9OWe-AaY0CQcaVXmUcmmIMPNW8QeU,69 +lm_eval/tasks/pile/pile_dm-mathematics.yaml,sha256=MAHnHDrmzm6Td9UEB-WNKAO38Sv0GA_q1lPqOAn7jGQ,85 +lm_eval/tasks/pile/pile_enron.yaml,sha256=nXC7EnbTdTOznTB9YB8BQ7BO46rV665NNd1S9lOwxC8,67 +lm_eval/tasks/pile/pile_europarl.yaml,sha256=GUjjBtstAzTd71MprWhOiYv0KrZPaG1Hw8dxPEMteyw,73 +lm_eval/tasks/pile/pile_freelaw.yaml,sha256=mdojFrCnxL0NukAO2RZ6AgD9cslKOUKelbduLeCHhHA,71 +lm_eval/tasks/pile/pile_github.yaml,sha256=uLaAsHv04EDJDphznC8pPXN8sCBjE2fCLFI9bIp67-w,69 +lm_eval/tasks/pile/pile_gutenberg.yaml,sha256=jbWxHsPayUwrwElKCfZM8YVVV-NLxHoUiZ76ivubAr0,75 +lm_eval/tasks/pile/pile_hackernews.yaml,sha256=dqXEcDypQkVx8CVchdRfkHvOJjmKQvLU-vGKg_lcPlo,77 +lm_eval/tasks/pile/pile_nih-exporter.yaml,sha256=LD4hvEFvcgAq76Dv5AJnZpDUy3glQ988coxFA0zc0zA,81 +lm_eval/tasks/pile/pile_opensubtitles.yaml,sha256=P6y1GHbq9UmtUWtDAxqNaM60okuGajItFf7yzEnebZ4,83 +lm_eval/tasks/pile/pile_openwebtext2.yaml,sha256=hROXABLgyKTVoK6Xau2-0fjuYAm7saKE-tmMeOsi1iU,81 +lm_eval/tasks/pile/pile_philpapers.yaml,sha256=HkCs1ydujb2l1uMe8TyB8uU-ptvYzKR4Y2DfRYvZ1Vw,77 +lm_eval/tasks/pile/pile_pile-cc.yaml,sha256=UOZW0LPRvji_5wuOG985xRYf0kb3eFxMss8iAscleZ0,71 +lm_eval/tasks/pile/pile_pubmed-abstracts.yaml,sha256=OHZqNFFamJwwXdw_Sh4fS0Qm3f79WaKRnWzCEmjFF00,89 +lm_eval/tasks/pile/pile_pubmed-central.yaml,sha256=wwvas6LbeZVdQ4e2Kyjw-RDc-YkJyCHHX4VhASHyyrs,85 +lm_eval/tasks/pile/pile_stackexchange.yaml,sha256=5-IHF0PzOeB4LZvgwNS34PMC3d0CsM6nzlsdjaClC2E,83 +lm_eval/tasks/pile/pile_ubuntu-irc.yaml,sha256=Z-uivjik0_RK2xWAw0doaG6ibCFfx6bHlKzNnEtJtI0,77 +lm_eval/tasks/pile/pile_uspto.yaml,sha256=z8AonjJxzz7sEmXhNLE3ktQa4CAzX637yME0tp8fgAw,67 +lm_eval/tasks/pile/pile_wikipedia.yaml,sha256=yiSfOAA5LYA1kqQmQ7RxGMtGv5JoLZcCdEXcCjsq5YU,75 +lm_eval/tasks/pile/pile_youtubesubtitles.yaml,sha256=1rxTH-tybxk0itf346tdPOte-zZk0Pf9Jy-zah3LVRo,89 +lm_eval/tasks/pile_10k/README.md,sha256=PpF5P2SwxWR0Qw0gE9-JXCS_YkiZGFbt4w3rqNgzHII,1602 +lm_eval/tasks/pile_10k/pile_10k.yaml,sha256=ic9tccHkFBSlZFwjKSFuWDxbvbwoRrZiWYW3E5Kfqq0,467 +lm_eval/tasks/piqa/README.md,sha256=eIzvCBu5__Kv6KMJhM4X__p8BAFnTVq9T1WDBucTglo,1584 +lm_eval/tasks/piqa/piqa.yaml,sha256=icwccohmflL0ZRdo1dmG9GwcOPlA9Ja2o-l5PU_2MkI,521 +lm_eval/tasks/polemo2/README.md,sha256=z9Quxc9kiiaIvxdh7BS0mJ7B0pgk1wp8X5M9Wl4dVzg,2948 +lm_eval/tasks/polemo2/polemo2_in.yaml,sha256=5c8bg8Xa6A61T-mGcgrWsaMfE25CRvSLzFj_eRm_EZo,1225 +lm_eval/tasks/polemo2/polemo2_out.yaml,sha256=2cUNaH4359_LBvw4DlTpXijPtGlu4yIQzqbkQseGSRY,101 +lm_eval/tasks/prost/README.md,sha256=mk33wnEvPNYwrpJy4uTDBek3Zfvh92t-HhVTUv0sgO4,2149 +lm_eval/tasks/prost/corypaik_prost.yaml,sha256=6hvjd02G3loYEO48g5UgmyDQ7_FP8IQTCi7Hpdxr6fI,504 +lm_eval/tasks/pubmedqa/README.md,sha256=wcUTe-A1SqfLTz0m0hm6VDjhwCu340I_4o_-yy72eJU,2180 +lm_eval/tasks/pubmedqa/__pycache__/preprocess_pubmedqa.cpython-310.pyc,, +lm_eval/tasks/pubmedqa/preprocess_pubmedqa.py,sha256=Q1KO7mFmbZSumsPVi806DDgYKoiY-Zb1Nr6d4dNlV0A,169 +lm_eval/tasks/pubmedqa/pubmedqa.yaml,sha256=oi7_SL54B6hpyp-oc50YYcX2K3j0SzV9VssBfGqDr24,414 +lm_eval/tasks/qa4mre/README.md,sha256=5TTSebDBxnhg9NThd2Q5m9NoJjIzv7H9HKIQo_Eguc0,1918 +lm_eval/tasks/qa4mre/__pycache__/preprocess_qa4mre.cpython-310.pyc,, +lm_eval/tasks/qa4mre/preprocess_qa4mre.py,sha256=rEzBkrAERfA2pbZzHO__bGdUvXB8ZKQjaIuijhwhXLc,164 +lm_eval/tasks/qa4mre/qa4mre_2011.yaml,sha256=yU1mcRtSvqGGnpHPYaxzpp15rygMemPYwdTrb4nGeHs,708 +lm_eval/tasks/qa4mre/qa4mre_2012.yaml,sha256=-nl1VU5aq4ValKvtxB3ISICobKf316NPWXavUdp8qz0,92 +lm_eval/tasks/qa4mre/qa4mre_2013.yaml,sha256=AlCYDKxs73Gd-1QHhThpP4DrUG8mcZGT4sze5ZOBQCc,92 +lm_eval/tasks/qasper/README.md,sha256=qJMRJk8jWOWFHFH3BQYcNuHDhxGuQgPKRzZPhw3vRuw,2341 +lm_eval/tasks/qasper/__pycache__/metrics.cpython-310.pyc,, +lm_eval/tasks/qasper/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/qasper/bool.yaml,sha256=0mdAGRTHqUqKJXd1aqdmsJlHWt5EHgm3Zksu2uDs7yM,369 +lm_eval/tasks/qasper/freeform.yaml,sha256=6bu487qKQEIeShvgEf62WF-RXW5fIksmQ0l4r1nSEmQ,470 +lm_eval/tasks/qasper/metrics.py,sha256=qW3XySNorb06VFGT1gYe38uONzsxMHaoVocDjibgOaY,1244 +lm_eval/tasks/qasper/utils.py,sha256=GHFpYHsGqsWWek6abS6LbhJ77szfgCC_8XFMZkbpdw8,2714 +lm_eval/tasks/race/README.md,sha256=MjGKhlW3dQEq9p2CCZPq6ae7IYRc5Hc67MLFJ1ALxio,1974 +lm_eval/tasks/race/__pycache__/preprocess_race.cpython-310.pyc,, +lm_eval/tasks/race/preprocess_race.py,sha256=ib-ESUCHV2BnblF7zuubRnbd4vS-_wNCSPj6YbDH9bM,1100 +lm_eval/tasks/race/race.yaml,sha256=LFDIv3970nn4DAkbE83aISRzzYiGgnsIv36YQQGD-9M,412 +lm_eval/tasks/realtoxicityprompts/__pycache__/metric.cpython-310.pyc,, +lm_eval/tasks/realtoxicityprompts/metric.py,sha256=v-2PFiWsf3hHWeRnO6NDVoU47AyanirIsLMJrpQxBZk,3316 +lm_eval/tasks/realtoxicityprompts/realtoxicityprompts.yaml,sha256=qtmeZzXSwkdeEnf3f6KpeNP99HGQfcy2sKBme4PE4gM,502 +lm_eval/tasks/sciq/README.md,sha256=XCXBf3KfpPWJqBiqKogR_qyWqFK-XQKOhmGozlRw40Y,1480 +lm_eval/tasks/sciq/sciq.yaml,sha256=Ldi97ocUwPp2dDPW1Pr6P4Kw-30Sw6Z0GGij2bzKA5k,566 +lm_eval/tasks/scrolls/README.md,sha256=KqLRLEY82dKs_tR9w6lx5Hhxd71JoArktV_u_qQ02JQ,1443 +lm_eval/tasks/scrolls/__pycache__/task.cpython-310.pyc,, +lm_eval/tasks/scrolls/scrolls_contractnli.yaml,sha256=-v_VAdEDR3z5wcwdTev7CLOcjk1peMo-06M2j9UTbao,75 +lm_eval/tasks/scrolls/scrolls_govreport.yaml,sha256=E9lslsO0gZXdYFeEaEHO_q1nbysfdCwmvk1D0yNANK8,71 +lm_eval/tasks/scrolls/scrolls_narrativeqa.yaml,sha256=Hndp6bS2wmPI-38FUWub3PXXishM4jIEPt2ct-dj92Q,75 +lm_eval/tasks/scrolls/scrolls_qasper.yaml,sha256=wWG-Pw6g-XGoLOzswrVE9JI7parpMwKdSRXwGwu0KbQ,65 +lm_eval/tasks/scrolls/scrolls_qmsum.yaml,sha256=CJVrWX5rsiWvgEHRTQGeYN10FUh0LdzuZWxzzmUju4I,63 +lm_eval/tasks/scrolls/scrolls_quality.yaml,sha256=x6IVvMYUsJaphaaBh3C0QZkPvxMlMYPW6XkWeil8xKs,67 +lm_eval/tasks/scrolls/scrolls_summscreenfd.yaml,sha256=qbAHeRbh51AqZQ-6F3Cot6llOJTNeU_m4QINy-lKibI,77 +lm_eval/tasks/scrolls/task.py,sha256=kQ8Ak3u3H4rqA9uxU_6sX_ewZi97X5Z4iqvTRX5ueFI,14287 +lm_eval/tasks/siqa/README.md,sha256=4TalxcZMCLW7D4NmfEcxWR2bjUtKhGemGEnju8QyX2k,2607 +lm_eval/tasks/siqa/siqa.yaml,sha256=CHrGP4tvJeu0AheAJoNbNn40I8ySs6JLVEkVtdxvuBo,402 +lm_eval/tasks/squad_completion/README.md,sha256=gZexAg-CnjvQJ9uRXi_UeaVllnWZavkZEs407SLTHxw,1947 +lm_eval/tasks/squad_completion/__pycache__/task.cpython-310.pyc,, +lm_eval/tasks/squad_completion/squad_completion.yaml,sha256=xvPPT_ZJEDeUcOZR7slHsE39IHvoDY9sNyiUj7_R6TE,61 +lm_eval/tasks/squad_completion/task.py,sha256=q_eYWXA4vsl1lfCTdmUswPZ5H3p0FV7aOe58JrHWEbg,3072 +lm_eval/tasks/squadv2/README.md,sha256=1kSUwS--VUhL7Ql_Wg_AeIcR89gyMIKanxxVrcH6mjo,1901 +lm_eval/tasks/squadv2/__pycache__/task.cpython-310.pyc,, +lm_eval/tasks/squadv2/squadv2.yaml,sha256=47xG_LSA_JSSkT3KBzvcPzvquMnIrfC9dTftfnTu39s,43 +lm_eval/tasks/squadv2/task.py,sha256=zhK07UneVGXXnVxgD9pMv4tWSjobkJRGehfk6jlX8_o,8444 +lm_eval/tasks/storycloze/README.md,sha256=2h9-bOsvb4V90lyYFZPz2pF5kn-9EapHjV3XSDw7utA,1675 +lm_eval/tasks/storycloze/storycloze_2016.yaml,sha256=Bss8Q2adu-7cwQWk4dkkQMzPpk9EyLmd91IDzzkL5-E,608 +lm_eval/tasks/storycloze/storycloze_2018.yaml,sha256=X9Q-PjykgFnj-NC-4gD6nXCl590_FIxAIE4EFUZHn3c,583 +lm_eval/tasks/super_glue/README.md,sha256=VeTdrrg5qatbvDbcKHzqoRuQBBDznttSGUGQUpqD_q0,2977 +lm_eval/tasks/super_glue/boolq/default.yaml,sha256=a_pL12N7f8aGPQjOt5c1rfQed_6r9tkycznfj-CveM0,400 +lm_eval/tasks/super_glue/boolq/seq2seq.yaml,sha256=3sLq019fXuRPwYVbsZFSGLFC4vZTXMX9dp5YlOcdizE,573 +lm_eval/tasks/super_glue/boolq/t5-prompt.yaml,sha256=weHcg9NgH_qsxfWoCA8uCGD8VftTqVDuM3nqs_f4qQc,511 +lm_eval/tasks/super_glue/cb/__pycache__/aggregate.cpython-310.pyc,, +lm_eval/tasks/super_glue/cb/__pycache__/t5_utils.cpython-310.pyc,, +lm_eval/tasks/super_glue/cb/aggregate.py,sha256=_vGmEwd06c8YRJPcWWtLFabqwFSxlvWDdgCaEVGiWGk,422 +lm_eval/tasks/super_glue/cb/default.yaml,sha256=uDh4UiJRNDxLvwJn-ecIKmA_vcX4ge7k_Tx-5xgUtGw,437 +lm_eval/tasks/super_glue/cb/t5-prompt.yaml,sha256=ijNXBpDZTIuH45xHSpSvOc3bpNiW9cPQjPG6hs8Rb98,663 +lm_eval/tasks/super_glue/cb/t5_utils.py,sha256=_TvTZo3kix4w7wW-z_jNIeUN-tks1lRnyzQ8X9-W4NI,880 +lm_eval/tasks/super_glue/copa/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/super_glue/copa/default.yaml,sha256=MvbduME95GxCm9t4U4p85Y_2r8ZrxeDIbeZZov05tOw,353 +lm_eval/tasks/super_glue/copa/t5-prompt.yaml,sha256=F962IZLj6v3V55wgCFKJrpESuQieTALLbn97Cz8VWPY,555 +lm_eval/tasks/super_glue/copa/utils.py,sha256=C-mKkH22R6UYxCyRamE4W2TzlM-dAXG1y4a3oDYoLec,566 +lm_eval/tasks/super_glue/multirc/__pycache__/t5_utils.cpython-310.pyc,, +lm_eval/tasks/super_glue/multirc/default.yaml,sha256=Y6OYbeO6_AtkJc95sLqiQ1MELuoy8GZ0epM0PVUGxTQ,422 +lm_eval/tasks/super_glue/multirc/t5-prompt.yaml,sha256=_InElTyf4SiDyvGOaKpy2YgrzLWmL5GARICeokgnbOs,690 +lm_eval/tasks/super_glue/multirc/t5_utils.py,sha256=RyuIHpusGODyBCDph1gOI0CYXAZc3CPHauj_h7IcEr8,1538 +lm_eval/tasks/super_glue/record/__pycache__/t5_utils.cpython-310.pyc,, +lm_eval/tasks/super_glue/record/__pycache__/util.cpython-310.pyc,, +lm_eval/tasks/super_glue/record/default.yaml,sha256=kl3_fWnU4H04-7bdHedNZFSxeXZmRgWugtPDqs8ZdYM,529 +lm_eval/tasks/super_glue/record/t5-prompt.yaml,sha256=ozPxnvLn-BX6grVYQG5cm0bVShGQ-b7DyvG51xu7vN4,624 +lm_eval/tasks/super_glue/record/t5_utils.py,sha256=W2P_KQZ-6hdimbh9PPJzCR8kIZ4XqbqonA8CqtKKYaQ,4020 +lm_eval/tasks/super_glue/record/util.py,sha256=J05kMEEeLQN27FFqwZGkS4HsrPiRUbpN9fQQfolOLfw,1733 +lm_eval/tasks/super_glue/rte/default.yaml,sha256=2hOxubtSBUK2O0vg3fuWLy67h_xKXvazoDMCSkd-Dgw,357 +lm_eval/tasks/super_glue/rte/t5-prompt.yaml,sha256=vWZF97sM14Ws4aXpwbdLS-75aADTgaXAktYduJq2wDc,524 +lm_eval/tasks/super_glue/wic/default.yaml,sha256=S4LID1Wa1Qb3lGjUGzBAhO7ZeuAA1njn4MK-qjkMG7s,450 +lm_eval/tasks/super_glue/wic/t5-prompt.yaml,sha256=B3tIVhmyVvpxeV2yU1zylxS5Qk8LtHPJ7KTy5P9Yza8,526 +lm_eval/tasks/super_glue/wsc/__pycache__/preprocess_wsc.cpython-310.pyc,, +lm_eval/tasks/super_glue/wsc/__pycache__/t5_utils.cpython-310.pyc,, +lm_eval/tasks/super_glue/wsc/default.yaml,sha256=0DWTEYPqCrAwXvxmMlr1q38m5Dtlf5Nf6VjxdJ5fh5Y,334 +lm_eval/tasks/super_glue/wsc/preprocess_wsc.py,sha256=rzadUAJO9p1gdjD3nHBmmxXQUB84AL6e5GyYu2BdQ_o,620 +lm_eval/tasks/super_glue/wsc/t5-prompt.yaml,sha256=A-blj9bUS1sUI_0Zxq8VMx_OwBc5oJTZT7p_X8bA2lU,461 +lm_eval/tasks/super_glue/wsc/t5_utils.py,sha256=9Y17gDARL440i6qtlqy_geZ5cAJ9_Y3c8cJ7JVm470g,2963 +lm_eval/tasks/swag/README.md,sha256=pOggfzxJS46Lm1Ouo718vpVzN5frU5lg5R9OxjPmeEw,1799 +lm_eval/tasks/swag/swag.yaml,sha256=zUpp1TMNsvWpsaQwwXjmdeIca6yPtlThqKN6ns4rYyk,426 +lm_eval/tasks/swde/README.md,sha256=vYdHFVxgW70vEXVK97VU7CYlkQQnfEbA1Fy0cBU-vlI,6136 +lm_eval/tasks/swde/__pycache__/task.cpython-310.pyc,, +lm_eval/tasks/swde/swde.yaml,sha256=twovQd8vtboKJ57V8bKgWeIbBXflMRLKp9OZ_1b_Iik,38 +lm_eval/tasks/swde/task.py,sha256=DNmeX-Kv3XlE1N_KnqrFv-NeY1e-j6KOa-38cbOtUh8,3063 +lm_eval/tasks/tinyBenchmarks/README.md,sha256=sw091yLNr9b6Inne4SUj1B7_YB1qbDKAtanU9pWF4Ko,5490 +lm_eval/tasks/tinyBenchmarks/__pycache__/agg_functions.cpython-310.pyc,, +lm_eval/tasks/tinyBenchmarks/__pycache__/utils_hellaswag.cpython-310.pyc,, +lm_eval/tasks/tinyBenchmarks/__pycache__/utils_truthfulqa.cpython-310.pyc,, +lm_eval/tasks/tinyBenchmarks/__pycache__/utils_winogrande.cpython-310.pyc,, +lm_eval/tasks/tinyBenchmarks/agg_functions.py,sha256=WEIUpBOjKzNS8m_Ln2XITP55hFPL5CAJmTx6TCYxMV8,1695 +lm_eval/tasks/tinyBenchmarks/tinyArc.yaml,sha256=Rq1aAoW8xKjpjYrRcFD5TBZ5Z6y0TFvzs7vCxVmBCWY,561 +lm_eval/tasks/tinyBenchmarks/tinyBenchmarks.yaml,sha256=K3zcdUFx-YDWDAiZobkl4o9Di-FtEKr-ki1MRMs0Li4,300 +lm_eval/tasks/tinyBenchmarks/tinyGSM8k.yaml,sha256=2z6Kr7Bd79vvPBQk4j4DSoSNWBBA1dK3Fjxp4nr24Zg,1052 +lm_eval/tasks/tinyBenchmarks/tinyHellaswag.yaml,sha256=z8AprieqqnFREcKmdeErFebeGV3kF9SfvTTgjnbFGTY,472 +lm_eval/tasks/tinyBenchmarks/tinyMMLU.yaml,sha256=GSLS86883SY7LkWd6bQ_h3lLQRIMLgpbvs9FPWeZhig,436 +lm_eval/tasks/tinyBenchmarks/tinyTruthfulQA_mc1.yaml,sha256=Vss0uNJ_OJ_nECjz9huNSGBXSLk6sDlvdEZYQrnmUcY,1170 +lm_eval/tasks/tinyBenchmarks/tinyTruthfulQA_mc2.yaml,sha256=IFox4dfUUNd1p5wd5ARW54VOmYkeYz-mGzU5i077zso,385 +lm_eval/tasks/tinyBenchmarks/tinyWinogrande.yaml,sha256=GoQdjUx4VCUfuLlIxtdgFrqmz9oUnUBCrc0HPBYDmss,566 +lm_eval/tasks/tinyBenchmarks/utils_hellaswag.py,sha256=gMD5qlQ1baCO46D79tduu08xNAXWYE9hiimrkSsMgUM,786 +lm_eval/tasks/tinyBenchmarks/utils_truthfulqa.py,sha256=cfPzSb8m2mGdzVDmk3PQU4GwrKac0Dtedp1w4lcNxG4,6083 +lm_eval/tasks/tinyBenchmarks/utils_winogrande.py,sha256=Z-zcl9Q9v9W3uGvY_KMpUfWf-rmamQENSyz4cFjjBG8,445 +lm_eval/tasks/tmmluplus/README.md,sha256=YKXUeprLtW0ogtfJwBZ3ftVuCY1w5aQNwMTMOQDpGZI,2319 +lm_eval/tasks/tmmluplus/default/__pycache__/_generate_configs.cpython-310.pyc,, +lm_eval/tasks/tmmluplus/default/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/tmmluplus/default/_default_template_yaml,sha256=jpYGCG1ObGvVnduBixFMyk7T66W5oPAy7sLKyydgZ2A,562 +lm_eval/tasks/tmmluplus/default/_generate_configs.py,sha256=W35zxHFLsH7fzKLPGytuIavKcxxOmGCUoEtUNxbyV2g,6246 +lm_eval/tasks/tmmluplus/default/tmmluplus.yaml,sha256=5EsuiqHQMzxSCNKCOnSTb562a_56LNlrLKzaFi1lO6M,109 +lm_eval/tasks/tmmluplus/default/tmmluplus_accounting.yaml,sha256=KmrTSoVOL7UqWJOh2T_a1G6vKz2gdDZF84OVw96qouU,261 +lm_eval/tasks/tmmluplus/default/tmmluplus_administrative_law.yaml,sha256=Vhcc57586QxMfEd1lU7KAKBrBFhWPXtk83v4p635l4I,295 +lm_eval/tasks/tmmluplus/default/tmmluplus_advance_chemistry.yaml,sha256=1N-6tRcjP4ZaBBJqG8Qg68NDpZCM3a5PbgMtLGNoXtQ,277 +lm_eval/tasks/tmmluplus/default/tmmluplus_agriculture.yaml,sha256=wJOUa5L7AI6RZKr8zyx0yhZBeO68HibVMkprvO0-OyE,261 +lm_eval/tasks/tmmluplus/default/tmmluplus_anti_money_laundering.yaml,sha256=ShOntNqJ6U7E4ZkgAEjeecnrNqaea6e2OggdKPC2LlI,307 +lm_eval/tasks/tmmluplus/default/tmmluplus_auditing.yaml,sha256=vXh121rA43jqDQAeORCaNXsx0fV7FcMRJFDQdKwMmq8,255 +lm_eval/tasks/tmmluplus/default/tmmluplus_basic_medical_science.yaml,sha256=N1SJnbTP-eDNniJ2jGSlQaYKyuSe4qefG3bsPxfgJ4c,295 +lm_eval/tasks/tmmluplus/default/tmmluplus_business_management.yaml,sha256=q3-qA4USINA4VRUAmIL5hdgfhKdzQf82lIGXYGYO4R4,291 +lm_eval/tasks/tmmluplus/default/tmmluplus_chinese_language_and_literature.yaml,sha256=cPHbyRVT00spbAzdsnb6uCiubmKZMs30wFWGNOXa2nk,341 +lm_eval/tasks/tmmluplus/default/tmmluplus_clinical_psychology.yaml,sha256=MixHBFQmj4m2WG575wweskQsOM_YxHjI9mamt5tIajc,314 +lm_eval/tasks/tmmluplus/default/tmmluplus_computer_science.yaml,sha256=1uRNqu6BeOUrn5EJXG2SH3DvTqhZnYcxjXEF7I9JWSw,280 +lm_eval/tasks/tmmluplus/default/tmmluplus_culinary_skills.yaml,sha256=6-AiMX2yHwoGBVGVr7dnswLxHkE4Jo6_SIrvWYDICC0,273 +lm_eval/tasks/tmmluplus/default/tmmluplus_dentistry.yaml,sha256=n7IY_pTrHE5KmL6WV8Vu8_mPwnFsJaTvEMtL4ByiTuA,258 +lm_eval/tasks/tmmluplus/default/tmmluplus_economics.yaml,sha256=Ezbdu1mrEOu8Mj2kLHyvfcm_PjC46u7S6m70Kozj5Gs,278 +lm_eval/tasks/tmmluplus/default/tmmluplus_education.yaml,sha256=EJdw5AnK1PIcSIltQwCcVhBh-AnEZaA0XKPMCXZWP5M,281 +lm_eval/tasks/tmmluplus/default/tmmluplus_education_(profession_level).yaml,sha256=mTQ9hhk8IPvMT8bDC7Bf6LKW26RhnLvisCljP1bcshQ,338 +lm_eval/tasks/tmmluplus/default/tmmluplus_educational_psychology.yaml,sha256=C_We90wdlnluH3kPVrTlrNyNAx2zQtVHuZcN-XL9EBE,320 +lm_eval/tasks/tmmluplus/default/tmmluplus_engineering_math.yaml,sha256=AH4q9nolhPzi-T5sdk9gpqKu1Q9hdkhwzZmKkwFYbXk,280 +lm_eval/tasks/tmmluplus/default/tmmluplus_finance_banking.yaml,sha256=zVIqh22IBIP_0eHaDirflbg-ltlNCINf88KaAIgztLU,282 +lm_eval/tasks/tmmluplus/default/tmmluplus_financial_analysis.yaml,sha256=LpYTIVFSU23BGfxJlif0YTT_0FmTbe_PtXS9omphEU4,288 +lm_eval/tasks/tmmluplus/default/tmmluplus_fire_science.yaml,sha256=2mBAhNtVWFZsPFs21Xj08QnNeHb8AuWwbVkbn95B9L0,267 +lm_eval/tasks/tmmluplus/default/tmmluplus_general_principles_of_law.yaml,sha256=9X6_qVVA0v-r7v5ADDRV3Sveicwhn4k2kfaYnCSumHM,319 +lm_eval/tasks/tmmluplus/default/tmmluplus_geography_of_taiwan.yaml,sha256=5hX8FY-oLHmW_7fMdORE5RspFtSy2sR2-Ga727oR7xs,311 +lm_eval/tasks/tmmluplus/default/tmmluplus_human_behavior.yaml,sha256=DQCLZRxig0vP7uEBhlbMj2-wp1mDKZV34QJUxlrvD0c,305 +lm_eval/tasks/tmmluplus/default/tmmluplus_insurance_studies.yaml,sha256=zibpAr24iyU435D0Rgc8fAsOkn2xVaE4BXSlwO54H1c,282 +lm_eval/tasks/tmmluplus/default/tmmluplus_introduction_to_law.yaml,sha256=Oc7cpSqzpe1bGZDK7Y399dakgCYT_qnWFZL2pp2mPXg,301 +lm_eval/tasks/tmmluplus/default/tmmluplus_jce_humanities.yaml,sha256=11VfWEAownB8nt8Djly4a2cyt_0cMuugm1sipy_LKR8,292 +lm_eval/tasks/tmmluplus/default/tmmluplus_junior_chemistry.yaml,sha256=ZMPsxA2FscrH_ezhGFzFa18r6xZdLXstkSudrg-NldQ,280 +lm_eval/tasks/tmmluplus/default/tmmluplus_junior_chinese_exam.yaml,sha256=1B6dE5cZnnnwfFKJAOzzIQfZhJ21mSWxoJogZvh6tRc,323 +lm_eval/tasks/tmmluplus/default/tmmluplus_junior_math_exam.yaml,sha256=3qmlQXFT83_r6hqFooCizllbMEKL80lXflUk08MP8xo,295 +lm_eval/tasks/tmmluplus/default/tmmluplus_junior_science_exam.yaml,sha256=bCPvpvVTJK7xr6FdfCMqmRaZCveUtohxPgitBh3XMKE,304 +lm_eval/tasks/tmmluplus/default/tmmluplus_junior_social_studies.yaml,sha256=Q-441twXWPgGAfWfz6xQC4fGhHxB8wfpKGRmBetAz40,312 +lm_eval/tasks/tmmluplus/default/tmmluplus_linear_algebra.yaml,sha256=czI4JUFPPlq0i135UPQFGWfZbXS6pARsDgPFXRP98_s,268 +lm_eval/tasks/tmmluplus/default/tmmluplus_logic_reasoning.yaml,sha256=MbLDRXrFSNQ7TnfiJRx3WjnU4oz9mu1YnK2Fe41KoYU,279 +lm_eval/tasks/tmmluplus/default/tmmluplus_macroeconomics.yaml,sha256=2glrerWGcXd14DhMXALCbxg8Sc2Mwz9EThKfmXv0Vuc,290 +lm_eval/tasks/tmmluplus/default/tmmluplus_management_accounting.yaml,sha256=SbfmNMtZzJkItLEb847F4Z0jgMYuJ4XDQcIs8oo5yLE,297 +lm_eval/tasks/tmmluplus/default/tmmluplus_marketing_management.yaml,sha256=ivgwfuoSIxcxoA_OwgdkbNhwCYOIV1dyp8EfNC_uNEQ,294 +lm_eval/tasks/tmmluplus/default/tmmluplus_mechanical.yaml,sha256=ufa_WVahDbuPtJDwllRzV1hTwvKj9MegsRFcL--iGNc,273 +lm_eval/tasks/tmmluplus/default/tmmluplus_music.yaml,sha256=i1ZPjGqUZmExOhz6oggXrX1eVsuddKRVxGG2udT45Bw,246 +lm_eval/tasks/tmmluplus/default/tmmluplus_national_protection.yaml,sha256=WH7yc6ee-rG6kfqxZ-pxIjCyau0uJ8pzUlWxSdwY-B4,305 +lm_eval/tasks/tmmluplus/default/tmmluplus_nautical_science.yaml,sha256=ZiJjGOEEXTj74JE9JJyfVQ2OKugSELwp4eE7u_YxqmQ,276 +lm_eval/tasks/tmmluplus/default/tmmluplus_occupational_therapy_for_psychological_disorders.yaml,sha256=sy53-x40f26U8UXzdlDFrQ9SarPkrvCC5JXbSCThMaI,413 +lm_eval/tasks/tmmluplus/default/tmmluplus_official_document_management.yaml,sha256=5MPMMrNcSNxPWaRR654tFKB0xAEJwgJJcWfenV7ucVw,318 +lm_eval/tasks/tmmluplus/default/tmmluplus_optometry.yaml,sha256=fFPILD_eoyRnThtG_iMAti6-2aNPj7c_0lkd6rCc4JI,258 +lm_eval/tasks/tmmluplus/default/tmmluplus_organic_chemistry.yaml,sha256=FEdWVP58Kni5mv7VcP4qulLhfNbvkpMLAJQG8Q70W8w,283 +lm_eval/tasks/tmmluplus/default/tmmluplus_pharmacology.yaml,sha256=UddgssqMqfBV4fBNTVcj1K1ZhCt4dMvny8Lf3xf0Niw,267 +lm_eval/tasks/tmmluplus/default/tmmluplus_pharmacy.yaml,sha256=g6qIHK1odlWDr1TMl23YDwo44Tjp3G_Z1Dw6MJuC7cs,253 +lm_eval/tasks/tmmluplus/default/tmmluplus_physical_education.yaml,sha256=nC9Ce3ackCK5L0tWrY3exP6xhNJaW5W3IBHUOJCIam8,302 +lm_eval/tasks/tmmluplus/default/tmmluplus_physics.yaml,sha256=sKeVAwlyWPceoxMfRuZaVEvoOyWweWIH7gKrK0ZXdHk,247 +lm_eval/tasks/tmmluplus/default/tmmluplus_politic_science.yaml,sha256=qPZjNdHQwd69R-NqhrWAWFAZFSVxld5vWNSD5HGmoD4,293 +lm_eval/tasks/tmmluplus/default/tmmluplus_real_estate.yaml,sha256=ff0n31RoHxenS5zeNgU1zDSRNCp9cE7fpLpEXkmCv8c,264 +lm_eval/tasks/tmmluplus/default/tmmluplus_secondary_physics.yaml,sha256=VDTjyZ_wJ9g8XA158Rqskhq7DWc-3FR8JrUaXBfd3xQ,283 +lm_eval/tasks/tmmluplus/default/tmmluplus_statistics_and_machine_learning.yaml,sha256=gggiEEFVAHn0J-j_aq7DY_aD3r415zKDgwn_bnMWQtw,334 +lm_eval/tasks/tmmluplus/default/tmmluplus_taiwanese_hokkien.yaml,sha256=PkfXsy13EiZPfGQ_HGlhp27z6sD9rc7r20uwzYtEfgQ,302 +lm_eval/tasks/tmmluplus/default/tmmluplus_taxation.yaml,sha256=62iyRM2iUdu5BzLeICRMb40HtQiKo_yLgDa31YcUme4,262 +lm_eval/tasks/tmmluplus/default/tmmluplus_technical.yaml,sha256=-NMaHOqNjQGJGsL3CXOPGxGry1_yMPW5P4GT0A3yNIg,264 +lm_eval/tasks/tmmluplus/default/tmmluplus_three_principles_of_people.yaml,sha256=HNO3QGMbmpwVc5L8Gc9Ude98YaqPqSRv1C-Zs_rdOq0,332 +lm_eval/tasks/tmmluplus/default/tmmluplus_trade.yaml,sha256=oUYKJx3skFgC8f3ibc8PqHNOr5fyhlfE7U_XoEOXt7E,243 +lm_eval/tasks/tmmluplus/default/tmmluplus_traditional_chinese_medicine_clinical_medicine.yaml,sha256=22Q42LfoNa2dD3f5JfeICRoSPf5GmLbIfVttd3-J54k,378 +lm_eval/tasks/tmmluplus/default/tmmluplus_trust_practice.yaml,sha256=TXsS1kHHheHkggwfroICOw8YfYrEjjn_7TQXmckIbHw,286 +lm_eval/tasks/tmmluplus/default/tmmluplus_ttqav2.yaml,sha256=03AKc4qTLX_Jfvm-u4cBM_mVqH6T2oti_-Dqw2R9WiE,278 +lm_eval/tasks/tmmluplus/default/tmmluplus_tve_chinese_language.yaml,sha256=n9U9hqHbmNK-hbfShkUciFXp2BiwCfFL_idBzcAXRoU,314 +lm_eval/tasks/tmmluplus/default/tmmluplus_tve_design.yaml,sha256=SRaKx66rVudi-AV7KLJb-YsgSu2--YqwAw34eo8f4RQ,265 +lm_eval/tasks/tmmluplus/default/tmmluplus_tve_mathematics.yaml,sha256=62RWNal7UyyQJgpgGcDZ-Z8nqlUU2tKP28M-59Q_bzU,277 +lm_eval/tasks/tmmluplus/default/tmmluplus_tve_natural_sciences.yaml,sha256=c98scKLtLzcY5AFJqlkHlns2DSCI8U1c_0GpJm46N7c,295 +lm_eval/tasks/tmmluplus/default/tmmluplus_veterinary_pathology.yaml,sha256=5u0nUZw60zFNzgWGbTr0mx1JhQprefxSjGXqqDg19Fs,297 +lm_eval/tasks/tmmluplus/default/tmmluplus_veterinary_pharmacology.yaml,sha256=wohConWsyaKlDIrZN6jnUeJP1QYQSYN3JoR7DhzhDzg,306 +lm_eval/tasks/tmmluplus/default/utils.py,sha256=mQe-NjY4qbY7WYKTVN5ibW0TEMr_gOz79AD8sIlzrB8,516 +lm_eval/tasks/tmmluplus/subject.tsv,sha256=DrL3yZ4IsAmFtq1u1XtPTKUb-QNGOm3aU_AOz4TeDnU,2635 +lm_eval/tasks/toxigen/README.md,sha256=0zC_-x1qhk5mL_Jtm6CD7cZu_dnQMexWDHXTdfjKMss,1458 +lm_eval/tasks/toxigen/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/toxigen/toxigen.yaml,sha256=AVH-Nbz8tYBTKImPWnmchhoy08PJ2I7E3MMv2XJpLhU,488 +lm_eval/tasks/toxigen/utils.py,sha256=7jVV5-UQChjGOjsZQAOvbiaF-HlJuYV2unRvbuPxbgA,153 +lm_eval/tasks/translation/README.md,sha256=ruLNyYFEmM76GJEov0HOlRG5FUCqflCh7vYunu12D5A,925 +lm_eval/tasks/translation/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/translation/iwslt2017_ar-en.yaml,sha256=EUZC-LRC00L6ytBzeWlB1dPemp2PpNxI_mnTBoQZ4dw,286 +lm_eval/tasks/translation/iwslt2017_en-ar.yaml,sha256=-nyyvuvCp-mfWoEgcsM7CG7Rk0wju9zu2x5I4C-8rJo,286 +lm_eval/tasks/translation/utils.py,sha256=TIq8u4WD4KetzBtKXrUjghf6Jf2RSBNz68-obm-GfRM,4137 +lm_eval/tasks/translation/wmt14_en-fr.yaml,sha256=jQIlH1WktTOrRKmbNfDkbOxuRAwrjJ2zZfnfc84ylYQ,294 +lm_eval/tasks/translation/wmt14_fr-en.yaml,sha256=8NmJ6H7bQoBT2vqbZXmQEQUJf5-NEQkdIE6I7KhGEhs,294 +lm_eval/tasks/translation/wmt16_de-en.yaml,sha256=5kZvgi-Z4TxRhSehntg8p7Omtq8_SL5lPV6jb02qOKg,294 +lm_eval/tasks/translation/wmt16_en-de.yaml,sha256=WnHNT4lFysZkw-c9Ox0STgnBPurgjiMqH-LH1t4CEBE,294 +lm_eval/tasks/translation/wmt16_en-ro.yaml,sha256=0mcSrvjsNnO2pOXStd3OAr_vsSyGHAPCR80pB-i2ED8,296 +lm_eval/tasks/translation/wmt16_ro-en.yaml,sha256=8-nK4wweCzQENB-0StNgH6WZbGJL-k_wczDIGte2RIQ,296 +lm_eval/tasks/translation/wmt_common_yaml,sha256=4BgUbieb4MnTun4p3kDu8VyXie6ZCiK_AsGzyjhnLVA,298 +lm_eval/tasks/triviaqa/README.md,sha256=UwDPFH5UD913cyyUTjFIM48iSgDjjNltRQLbjRo5n5A,1852 +lm_eval/tasks/triviaqa/default.yaml,sha256=ThYo2Nn6tgLNlQsyOTOsJTzr7TJFNY7u1_acqptPnes,694 +lm_eval/tasks/truthfulqa/README.md,sha256=APxG9NLQHaq6QzbZxyKgkmOvZbjaTQLb-od3MiYTQ-Y,1717 +lm_eval/tasks/truthfulqa/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/truthfulqa/truthfulqa_gen.yaml,sha256=psxrG3t3GHRxmUr3s22UINbxf-BspNmelkBx3WAPvgA,2248 +lm_eval/tasks/truthfulqa/truthfulqa_mc1.yaml,sha256=HW6e3LiSi9FCinX-g7Ct70_PUq79yzqtVMLEn9T5zso,1170 +lm_eval/tasks/truthfulqa/truthfulqa_mc2.yaml,sha256=CCxBfqAudGmjwLaJZxq0MkQZfU3o6n4IBQAI-aMs9t4,330 +lm_eval/tasks/truthfulqa/utils.py,sha256=7IpXGvKG-r3UA6PHCMC8uWaNXTsbLxRwctkxuyEToTo,6012 +lm_eval/tasks/unitxt/20_newsgroups.yaml,sha256=oRMKgSxP-P3ttWkGnNfBrCqJIaXt4xWUfDDAfTbbABA,160 +lm_eval/tasks/unitxt/README.md,sha256=Lh54ucepW0aVPTTs9M0JXaNm5ITqOl-r1qlKM6lTRa0,4095 +lm_eval/tasks/unitxt/__pycache__/generate_yamls.cpython-310.pyc,, +lm_eval/tasks/unitxt/__pycache__/unitxt_wrapper.cpython-310.pyc,, +lm_eval/tasks/unitxt/ag_news.yaml,sha256=MJp6uQtDtV8G1JVoAJ9QKLuN-idlHh7jMdsGC5UUDt0,148 +lm_eval/tasks/unitxt/argument_topic.yaml,sha256=pfVLqXQrX267yf19UBzvQxsYH35vjG4lYAGUiX6rZWA,162 +lm_eval/tasks/unitxt/atis.yaml,sha256=s1zRmnzKcfoIDM9u0lquJuuWywFNMJzBVe9pq95q4LA,138 +lm_eval/tasks/unitxt/banking77.yaml,sha256=FN5o-VqvdMByooj_rZ7qg3MTvApHEeImlJodtxyzKW8,152 +lm_eval/tasks/unitxt/claim_stance_topic.yaml,sha256=q7RhV3t6b-eiABtSKVBmv0VYIOcicvRx_FGSUJCY2BM,170 +lm_eval/tasks/unitxt/cnn_dailymail.yaml,sha256=zrLFyoag1MMM-vvm6jP5uARX_qVoDLaFC08GSqwXz64,157 +lm_eval/tasks/unitxt/coedit_gec.yaml,sha256=kO8bTyVyi6dG99fD4eHlZyZh9cZqBy8gnZTZlUBd6QI,159 +lm_eval/tasks/unitxt/dbpedia_14.yaml,sha256=2qgw20gUNGAH8nJiZiygNmTgvKPCGaa_kidoeRbjLPw,154 +lm_eval/tasks/unitxt/ethos_binary.yaml,sha256=p44s3xca4jtKNa_yK8DwRs3PukZqL2niRhrN3uCkKE4,158 +lm_eval/tasks/unitxt/financial_tweets.yaml,sha256=C0e0BFXcw2jtRC0qN-YJIQ_Ujj-ZvKRIVaUxED6naRs,166 +lm_eval/tasks/unitxt/generate_yamls.py,sha256=HoMFsbkAc5TV7Fk7B72dbD61xF3i5wvd2F0CCxcTmoU,4889 +lm_eval/tasks/unitxt/law_stack_exchange.yaml,sha256=B4VSCRxd7Lmg0DqIllYThzTWW1llzjIj4278Nq2TokI,170 +lm_eval/tasks/unitxt/ledgar.yaml,sha256=GgL1Ipngnx4Po9EmUziFHh4ymzj757C5kcTxPF7c8Kw,146 +lm_eval/tasks/unitxt/medical_abstracts.yaml,sha256=HfiYqa4yhwmuk-RW0sIqZw-P8hfhFFawJ44_GRb7guA,168 +lm_eval/tasks/unitxt/stsb.yaml,sha256=sQkplU1Tpm6qsM8OoXFXdHO2X3lTrHSoM0VlzVtoOmM,131 +lm_eval/tasks/unitxt/unfair_tos.yaml,sha256=M5myC6zwAiXeHtBXF_ZDMCs_Jwe1RBkaZY9sUKMeKtQ,154 +lm_eval/tasks/unitxt/unitxt_datasets,sha256=Qq7QWAmap_WPJKPE7l5KrjqRLOnWH5rgMI_iewueJF4,223 +lm_eval/tasks/unitxt/unitxt_tasks.classification.multi_class,sha256=sECG_SZ6NDA1ielOtLhtkseIJg6fp7HrXyGIOn1dDGM,517 +lm_eval/tasks/unitxt/unitxt_tasks.classification.multi_label,sha256=kfKKmrLD4yxLAsPHpF8Pl8PQsH7JRynOXI66lLRB6Dc,541 +lm_eval/tasks/unitxt/unitxt_tasks.grammatical_error_correction,sha256=FC4FQZiTjhGjt27A9Qnf-QKEPr5N4p2mdM7E_AEQvaw,570 +lm_eval/tasks/unitxt/unitxt_tasks.qa.with_context.extractive,sha256=7DzmOgMPHVVbP52PbZDzTdwHvDeaRKyxVgGEAyq32S0,368 +lm_eval/tasks/unitxt/unitxt_tasks.regression.two_texts,sha256=koYXJ2yPPDBlhCDQtGfXV2Rqb9C2VADCHadyP85WZyA,371 +lm_eval/tasks/unitxt/unitxt_tasks.span_labeling.extraction,sha256=QZ2f3hYcFLFVOvS32PBil9MxJEGFf-LiNREci25AXw0,366 +lm_eval/tasks/unitxt/unitxt_tasks.summarization.abstractive,sha256=J8CX5phvZN9RrnOU4LHaYHu_hA6vFBqmrL3u7osmW3s,368 +lm_eval/tasks/unitxt/unitxt_wrapper.py,sha256=dEFZAnQnHVzuXuJDiUwljXahl-Yl2MpmFrf4saiyjb4,1232 +lm_eval/tasks/unitxt/xsum.yaml,sha256=Ze9kHs7ggmvGsSlmPRHUi4X-HE0LtNTqYiCRpcq2Dao,139 +lm_eval/tasks/unitxt/yahoo_answers_topics.yaml,sha256=NcKYw0NWQw6plo5btq5kvc84rxMsY5xCYTnVVWYSeWg,174 +lm_eval/tasks/unscramble/README.md,sha256=8fD3JDITiBTcee1qvuz-EzbXAjdGI4IR6hGY6dCdIaw,2615 +lm_eval/tasks/unscramble/anagrams1.yaml,sha256=l1cfwRW6nxbBkDFm3lJGcpi112REjsvxbBTL6Xd-zI4,463 +lm_eval/tasks/unscramble/anagrams2.yaml,sha256=djXvxXNfC3p-heygzjR4wlufyTPaGKXuQP9t2n6GjCs,463 +lm_eval/tasks/unscramble/cycle_letters.yaml,sha256=XA3XPKaeqviVedLTxj_yWYV9joEUXRymoSy9Fi0WW7k,469 +lm_eval/tasks/unscramble/random_insertion.yaml,sha256=aOxzwtkMUMFKDa-MGoFvgkpfHOYP_8o2rpwJpSV037A,475 +lm_eval/tasks/unscramble/reversed_words.yaml,sha256=niZuIfApjhPBO_j4KN955nGeDcoE4gJ88tYXSEQYjOA,421 +lm_eval/tasks/webqs/README.md,sha256=XaGMylFq_iwthSyM7VvHE5rVMzgQ9GJ6cVaQLMmagaY,1933 +lm_eval/tasks/webqs/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/webqs/utils.py,sha256=s01Tkm1AQQ_BjJtUVayw1fJ5BsxaGjtCTrkJnF_fy_g,773 +lm_eval/tasks/webqs/webqs.yaml,sha256=qfxQ_Lf-olbLay21rv_4qPvWhIbRLTNtuTUIg9EsO2Y,484 +lm_eval/tasks/wikitext/README.md,sha256=TIKOT6ySFrA3YAFL66ftz8FRL-hgJ0EfirXpSqH1294,1477 +lm_eval/tasks/wikitext/__pycache__/preprocess_wikitext.cpython-310.pyc,, +lm_eval/tasks/wikitext/preprocess_wikitext.py,sha256=pEAgN0sXIVm_W-gKZNLEGUydXHcoT2lqxmY2EzjI2n0,1738 +lm_eval/tasks/wikitext/wikitext.yaml,sha256=Yzm4WJBjfaGwZKSE8T2ey-y1QiEePs3PbnYVabAxQ6c,574 +lm_eval/tasks/winogrande/README.md,sha256=vA2S-iOSnXTAXPQxEqRhwZMd3axmvKA3P-7tUcY2SFo,1816 +lm_eval/tasks/winogrande/__pycache__/preprocess_winogrande.cpython-310.pyc,, +lm_eval/tasks/winogrande/default.yaml,sha256=7diBVsCZbcWNM7Vfgow1_w0sSod6GjR1JOYBXBUaxFM,498 +lm_eval/tasks/winogrande/preprocess_winogrande.py,sha256=5VMnYpJkqY8dOD_aJGRbZ3mvtT-gvOIVAEK5QWsa4AY,377 +lm_eval/tasks/wmdp/README.md,sha256=mgqAtEIrAnK2OsW4v1jyZaPsnMse4XU6X9vcDcv5iTI,2795 +lm_eval/tasks/wmdp/_default_template_yaml,sha256=Qvs27h_LiZx36xm7H5zgwFHCd2FY1Fa6CjTJYmSiaeQ,421 +lm_eval/tasks/wmdp/wmdp_bio.yaml,sha256=m-1-UcfSRncg9OeKLVjRHcf2vUZwW8l8cXAViPClKwU,177 +lm_eval/tasks/wmdp/wmdp_chem.yaml,sha256=39eQizGmPz7BO6m89T_9EWiYokPB4Fk1IRQEBNV-9-Y,181 +lm_eval/tasks/wmdp/wmdp_cyber.yaml,sha256=2iqzu1KkuTHw0tnd-GHYaOtaQ-UZwfMTAlr2nMVvKYA,187 +lm_eval/tasks/wmt2016/README.md,sha256=KlOtv8lY7r4KGFf_-quEOdwm90d0bp3Wfz9TimENrJs,2092 +lm_eval/tasks/wmt2016/__pycache__/metrics.cpython-310.pyc,, +lm_eval/tasks/wmt2016/metrics.py,sha256=V629nou9UMoPluWjgjf2D9IlbXi0YD2HWy7mspQZQmE,280 +lm_eval/tasks/wmt2016/ro_en-t5_prompt.yaml,sha256=87dSDcZQieh1V-j9QKE0FOl9FV40R8QttfBxIX0CLuA,481 +lm_eval/tasks/wsc273/README.md,sha256=ACWo1bwzuYf66R7z0xxa4hMc2I6jdb71D5V-GeXNL-c,2963 +lm_eval/tasks/wsc273/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/wsc273/default.yaml,sha256=1t8UiaRZWvEGfFS6REqxXek1OEwc5fhzV11RAYa8dls,518 +lm_eval/tasks/wsc273/utils.py,sha256=LCldN-jXX1ilzpSIOdIMuZcdHA12J4eCkb69RYTGNQc,1005 +lm_eval/tasks/xcopa/README.md,sha256=bszl23gtJTrwRRgk3JS7pbStFHqU5n7CW2s6YnNdwQI,2211 +lm_eval/tasks/xcopa/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/xcopa/default_et.yaml,sha256=SrP37-d0yWJyog3yuH8ebbjorTooXciVaInVYKHns0g,304 +lm_eval/tasks/xcopa/default_ht.yaml,sha256=YiVPPHda2D5HOmRzwiZsBXsSBdo90wBaRH5X7YQGnTY,101 +lm_eval/tasks/xcopa/default_id.yaml,sha256=XxcNzEJFlUUGpyx_vvEiDKqPlzqr2rlkDpunwcp-Wzc,101 +lm_eval/tasks/xcopa/default_it.yaml,sha256=P85UpV5Ilfr8wFA1Dupc6dQn-KVn9LDhxT9YOQb4A7Q,101 +lm_eval/tasks/xcopa/default_qu.yaml,sha256=6CR5W6wWzpvLSr6X16gELeM_pDjahhLfnhUnyEKvnWk,101 +lm_eval/tasks/xcopa/default_sw.yaml,sha256=I0HIJi_MHQPkbBj2OGF9yn_9nupq-bxsWaU0mfLntf0,101 +lm_eval/tasks/xcopa/default_ta.yaml,sha256=T-ZV3pCgYTToODyBNJA0L5CrD4OspR8-hkS35TEfIqE,101 +lm_eval/tasks/xcopa/default_th.yaml,sha256=_eMapb7miFw0cZuZaG1kSSR4Kjx2LFv2_8XTkkIb9BE,101 +lm_eval/tasks/xcopa/default_tr.yaml,sha256=6VzN3-CzEotaJrB_ZesEEHKM6XEQqY_kzHiXrDInNYs,101 +lm_eval/tasks/xcopa/default_vi.yaml,sha256=0TBQaLnbCUIB74GGs5gOgoprp4OSfK1vZ1fZgCIqrLw,101 +lm_eval/tasks/xcopa/default_zh.yaml,sha256=R4P1Ibs5oJps9Hs2AeBBrL27yJW8OCXkL3ORaBCnfto,101 +lm_eval/tasks/xcopa/utils.py,sha256=GR0xu7_Ga-e2bLxBAFPhNjEgGjcA33SfI8ZT-3g03UM,1791 +lm_eval/tasks/xnli/README.md,sha256=M6yJ8Ui08vdiDQRLW9EejDPrSLuop09XVmZu0RfJEgU,2224 +lm_eval/tasks/xnli/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/xnli/utils.py,sha256=sYhlevG44xK_xQ-nlIaLC_3TAddLR0bSS9EmELz61KM,5277 +lm_eval/tasks/xnli/xnli_ar.yaml,sha256=-vGMt34SYGsrxhJH2mzVJJ44UwCs44_EdPkT9F-b6zU,248 +lm_eval/tasks/xnli/xnli_bg.yaml,sha256=3ZCMy6xC4r1HN_324m3Tqc4LjL2ZJTVlQAzG6Anmq34,270 +lm_eval/tasks/xnli/xnli_common_yaml,sha256=JvhM_cqTEn1ALdYJDy00935ej4ip0ozGEa-Ag7Godas,482 +lm_eval/tasks/xnli/xnli_de.yaml,sha256=Jk1ZgtT9ji3lq3TVfu0jCQxUj8WJ1dZeaSyEkLzPiN4,237 +lm_eval/tasks/xnli/xnli_el.yaml,sha256=Ljnc0ksd4-SYjDNhCBtZMP5SDk8gjD9k9RgxzFk4kuo,262 +lm_eval/tasks/xnli/xnli_en.yaml,sha256=YeCSTN2rwAT0NLWzh1DW19PoAMee46W-hf0ScBeyhfE,230 +lm_eval/tasks/xnli/xnli_es.yaml,sha256=GkwQMf22cNfBhIVubRAzkRPL8TGPCi0gilZFWdaoF1w,242 +lm_eval/tasks/xnli/xnli_fr.yaml,sha256=RdfT4cthik8ZS7sSmkvsoxuK2nTdDouNOpzrZ-Lebdg,238 +lm_eval/tasks/xnli/xnli_hi.yaml,sha256=pPuF91nLvDCOVXQ1bANGV-UQFedcez_2XW-OapqEX6Y,269 +lm_eval/tasks/xnli/xnli_ru.yaml,sha256=1tAyhdGQKXpFQrIM_2-SAdPv7v34Ot1Y_NlX1WNk2PI,276 +lm_eval/tasks/xnli/xnli_sw.yaml,sha256=Z6CF-2C6DyPh0nzk7GnqjtWnOHAw5zblmfDVjAQmJAU,240 +lm_eval/tasks/xnli/xnli_th.yaml,sha256=N1QOrp7HkzYrx0TAiSMhEAJmWwETEAGsMBM3gTeoWnc,308 +lm_eval/tasks/xnli/xnli_tr.yaml,sha256=bUvapKIUdJCJKc7CCIl918aJiWwhEiEsoMXJtbrTgn4,242 +lm_eval/tasks/xnli/xnli_ur.yaml,sha256=47LmNHEByKsde-KLFlxDfWgHiF6MX06isosv6YF7Rj4,260 +lm_eval/tasks/xnli/xnli_vi.yaml,sha256=Aw64QMiB-AAhq5xMgbZQs6dEzFC4njOpbH7bMokjq2w,244 +lm_eval/tasks/xnli/xnli_zh.yaml,sha256=f7rvxUp0E8CgBu4d-YyCQOYx-d6eYRmiVfj0vNMdpsg,245 +lm_eval/tasks/xnli_eu/README.md,sha256=nBIAxUINTOQMxMH2LAuS6D9t8APzCurj9A5RFsN5n_w,2602 +lm_eval/tasks/xnli_eu/xnli_common_yaml,sha256=5xcCDYmZ_w3dJbjlETm_MkJq_FAW4Qzq_e6W2T7Yts0,303 +lm_eval/tasks/xnli_eu/xnli_eu.yaml,sha256=DqTR2zooK6xvpF6XXRQyq5ZScLga6UBz4vYHB_1Jbd4,248 +lm_eval/tasks/xnli_eu/xnli_eu_mt.yaml,sha256=PP30wI9j7OFUT1jL4hNgjISwsoew1dxbqUjD3KWGYZk,84 +lm_eval/tasks/xnli_eu/xnli_eu_native.yaml,sha256=XYhCfwkUSz4qsiAxyXiaD3ex74xFT58be7w0-hghx3k,136 +lm_eval/tasks/xstorycloze/README.md,sha256=zFx4IhOCGFNVCkUqmcnBH10c7_xyEHX4p_V4OPEFRJg,2674 +lm_eval/tasks/xstorycloze/default_ar.yaml,sha256=afOQjiQuTcheJoiYRATRgtCQgkb3DKRq522TzVBESBc,616 +lm_eval/tasks/xstorycloze/default_en.yaml,sha256=jkXDziy5ZFSxiBBfvpF5X0PD7r2-EoJuPvpM_YO57mo,63 +lm_eval/tasks/xstorycloze/default_es.yaml,sha256=krymcDmxJbEqyaLMjJ2qCTp72_vpe30EyrqAytvGmFA,63 +lm_eval/tasks/xstorycloze/default_eu.yaml,sha256=Jp7s9WOyPBO-r8ZMHXgrHWYXsOSxwTFoLM09w7xktT4,63 +lm_eval/tasks/xstorycloze/default_hi.yaml,sha256=0baA81PaJh6O_rHk5Zt75RlB0Rm8IeIEmcwWl65AeCc,63 +lm_eval/tasks/xstorycloze/default_id.yaml,sha256=3eufzTCUzloyMmZmNmtT9jkilhLaaUlhZyWYtSoO6K4,63 +lm_eval/tasks/xstorycloze/default_my.yaml,sha256=Lru52K3docj3SyM8yb_vKEdejBL5587nj2WIyPEoKXk,63 +lm_eval/tasks/xstorycloze/default_ru.yaml,sha256=NQLa7Ztu0eLDeJSeSiiR-6KYJE4im3-0IFP7JG-E-AU,63 +lm_eval/tasks/xstorycloze/default_sw.yaml,sha256=BkOasjoNtcIMwhhgB51ZhY9R8E0O2K8RMiiQewpRoBQ,63 +lm_eval/tasks/xstorycloze/default_te.yaml,sha256=uS7g8yrYniDdX3QuXwCSZsXMBQNAoDFDuGLXKNJ9P-Y,63 +lm_eval/tasks/xstorycloze/default_zh.yaml,sha256=TTaSyzTXWpqEgcCaadNWnxrHKXB7cdMuSEpZ9OeqHZE,63 +lm_eval/tasks/xwinograd/README.md,sha256=qPmixk1nZorlQSshnqtAoP1i5Zy4vrgJry65OLGklXk,2601 +lm_eval/tasks/xwinograd/__pycache__/utils.cpython-310.pyc,, +lm_eval/tasks/xwinograd/utils.py,sha256=7DLwv-y0XYAiAnlSKsBG7yrD94kERHmLVqwpNIsnNV0,2844 +lm_eval/tasks/xwinograd/xwinograd_common_yaml,sha256=Eve4-QbUaUIo2_ztQ-RJNIt2bdfa8Wk3mQUQUhlFM5k,622 +lm_eval/tasks/xwinograd/xwinograd_en.yaml,sha256=xbEp4QSQgNlKymjEFxXVonpbG7IKDjtFuTa1DzNTpUc,91 +lm_eval/tasks/xwinograd/xwinograd_fr.yaml,sha256=UZ7Txl6Q3d9bWvZXvjGxVQxGMnZ2_5bLL7Ykrhu_-nA,91 +lm_eval/tasks/xwinograd/xwinograd_jp.yaml,sha256=aRVwy9c6YOGpRFgm4oAUnljHW2y5UTF6IvwzEeOjVnc,91 +lm_eval/tasks/xwinograd/xwinograd_pt.yaml,sha256=A8oaox90xLwx0N1G8MfRpZGB8Tof6mux8EtgJpSrOaE,91 +lm_eval/tasks/xwinograd/xwinograd_ru.yaml,sha256=ra7PfDvFLZS1sBiMI7hRBjSWCmElclMWFwChrIg9-HY,91 +lm_eval/tasks/xwinograd/xwinograd_zh.yaml,sha256=OAf84RMb0BbFc3DGtBij-84FGwKDwHH9d_eGRXN_K0Y,91 +lm_eval/utils.py,sha256=CRJ1vJjjIV0SznwJ8zdHsWojxmKWVVVN4oBko45x1C8,14194 diff --git a/venv/lib/python3.10/site-packages/lm_eval-0.4.3.dist-info/REQUESTED b/venv/lib/python3.10/site-packages/lm_eval-0.4.3.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/lm_eval-0.4.3.dist-info/WHEEL b/venv/lib/python3.10/site-packages/lm_eval-0.4.3.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..edf4ec7c70d7dbfc16600ff1b368daf1097c5dc7 --- /dev/null +++ b/venv/lib/python3.10/site-packages/lm_eval-0.4.3.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (70.1.1) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/venv/lib/python3.10/site-packages/lm_eval-0.4.3.dist-info/entry_points.txt b/venv/lib/python3.10/site-packages/lm_eval-0.4.3.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..0cfb793897d6f65b9e7ba85d6ed10d57d52d0821 --- /dev/null +++ b/venv/lib/python3.10/site-packages/lm_eval-0.4.3.dist-info/entry_points.txt @@ -0,0 +1,3 @@ +[console_scripts] +lm-eval = lm_eval.__main__:cli_evaluate +lm_eval = lm_eval.__main__:cli_evaluate diff --git a/venv/lib/python3.10/site-packages/lm_eval-0.4.3.dist-info/top_level.txt b/venv/lib/python3.10/site-packages/lm_eval-0.4.3.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..b3d57e8da16b93f8501d104cad0591ca57995369 --- /dev/null +++ b/venv/lib/python3.10/site-packages/lm_eval-0.4.3.dist-info/top_level.txt @@ -0,0 +1 @@ +lm_eval diff --git a/venv/lib/python3.10/site-packages/lxml/ElementInclude.py b/venv/lib/python3.10/site-packages/lxml/ElementInclude.py new file mode 100644 index 0000000000000000000000000000000000000000..21884336f534cd2013165934111146684c9909cf --- /dev/null +++ b/venv/lib/python3.10/site-packages/lxml/ElementInclude.py @@ -0,0 +1,244 @@ +# +# ElementTree +# $Id: ElementInclude.py 1862 2004-06-18 07:31:02Z Fredrik $ +# +# limited xinclude support for element trees +# +# history: +# 2003-08-15 fl created +# 2003-11-14 fl fixed default loader +# +# Copyright (c) 2003-2004 by Fredrik Lundh. All rights reserved. +# +# fredrik@pythonware.com +# http://www.pythonware.com +# +# -------------------------------------------------------------------- +# The ElementTree toolkit is +# +# Copyright (c) 1999-2004 by Fredrik Lundh +# +# By obtaining, using, and/or copying this software and/or its +# associated documentation, you agree that you have read, understood, +# and will comply with the following terms and conditions: +# +# Permission to use, copy, modify, and distribute this software and +# its associated documentation for any purpose and without fee is +# hereby granted, provided that the above copyright notice appears in +# all copies, and that both that copyright notice and this permission +# notice appear in supporting documentation, and that the name of +# Secret Labs AB or the author not be used in advertising or publicity +# pertaining to distribution of the software without specific, written +# prior permission. +# +# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD +# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT- +# ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR +# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY +# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS +# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE +# OF THIS SOFTWARE. +# -------------------------------------------------------------------- + +""" +Limited XInclude support for the ElementTree package. + +While lxml.etree has full support for XInclude (see +`etree.ElementTree.xinclude()`), this module provides a simpler, pure +Python, ElementTree compatible implementation that supports a simple +form of custom URL resolvers. +""" + +from lxml import etree +try: + from urlparse import urljoin + from urllib2 import urlopen +except ImportError: + # Python 3 + from urllib.parse import urljoin + from urllib.request import urlopen + +XINCLUDE = "{http://www.w3.org/2001/XInclude}" + +XINCLUDE_INCLUDE = XINCLUDE + "include" +XINCLUDE_FALLBACK = XINCLUDE + "fallback" +XINCLUDE_ITER_TAG = XINCLUDE + "*" + +# For security reasons, the inclusion depth is limited to this read-only value by default. +DEFAULT_MAX_INCLUSION_DEPTH = 6 + + +## +# Fatal include error. + +class FatalIncludeError(etree.LxmlSyntaxError): + pass + + +class LimitedRecursiveIncludeError(FatalIncludeError): + pass + + +## +# ET compatible default loader. +# This loader reads an included resource from disk. +# +# @param href Resource reference. +# @param parse Parse mode. Either "xml" or "text". +# @param encoding Optional text encoding. +# @return The expanded resource. If the parse mode is "xml", this +# is an ElementTree instance. If the parse mode is "text", this +# is a Unicode string. If the loader fails, it can return None +# or raise an IOError exception. +# @throws IOError If the loader fails to load the resource. + +def default_loader(href, parse, encoding=None): + file = open(href, 'rb') + if parse == "xml": + data = etree.parse(file).getroot() + else: + data = file.read() + if not encoding: + encoding = 'utf-8' + data = data.decode(encoding) + file.close() + return data + + +## +# Default loader used by lxml.etree - handles custom resolvers properly +# + +def _lxml_default_loader(href, parse, encoding=None, parser=None): + if parse == "xml": + data = etree.parse(href, parser).getroot() + else: + if "://" in href: + f = urlopen(href) + else: + f = open(href, 'rb') + data = f.read() + f.close() + if not encoding: + encoding = 'utf-8' + data = data.decode(encoding) + return data + + +## +# Wrapper for ET compatibility - drops the parser + +def _wrap_et_loader(loader): + def load(href, parse, encoding=None, parser=None): + return loader(href, parse, encoding) + return load + + +## +# Expand XInclude directives. +# +# @param elem Root element. +# @param loader Optional resource loader. If omitted, it defaults +# to {@link default_loader}. If given, it should be a callable +# that implements the same interface as default_loader. +# @param base_url The base URL of the original file, to resolve +# relative include file references. +# @param max_depth The maximum number of recursive inclusions. +# Limited to reduce the risk of malicious content explosion. +# Pass None to disable the limitation. +# @throws LimitedRecursiveIncludeError If the {@link max_depth} was exceeded. +# @throws FatalIncludeError If the function fails to include a given +# resource, or if the tree contains malformed XInclude elements. +# @throws IOError If the function fails to load a given resource. +# @returns the node or its replacement if it was an XInclude node + +def include(elem, loader=None, base_url=None, + max_depth=DEFAULT_MAX_INCLUSION_DEPTH): + if max_depth is None: + max_depth = -1 + elif max_depth < 0: + raise ValueError("expected non-negative depth or None for 'max_depth', got %r" % max_depth) + + if base_url is None: + if hasattr(elem, 'getroot'): + tree = elem + elem = elem.getroot() + else: + tree = elem.getroottree() + if hasattr(tree, 'docinfo'): + base_url = tree.docinfo.URL + elif hasattr(elem, 'getroot'): + elem = elem.getroot() + _include(elem, loader, base_url, max_depth) + + +def _include(elem, loader=None, base_url=None, + max_depth=DEFAULT_MAX_INCLUSION_DEPTH, _parent_hrefs=None): + if loader is not None: + load_include = _wrap_et_loader(loader) + else: + load_include = _lxml_default_loader + + if _parent_hrefs is None: + _parent_hrefs = set() + + parser = elem.getroottree().parser + + include_elements = list( + elem.iter(XINCLUDE_ITER_TAG)) + + for e in include_elements: + if e.tag == XINCLUDE_INCLUDE: + # process xinclude directive + href = urljoin(base_url, e.get("href")) + parse = e.get("parse", "xml") + parent = e.getparent() + if parse == "xml": + if href in _parent_hrefs: + raise FatalIncludeError( + "recursive include of %r detected" % href + ) + if max_depth == 0: + raise LimitedRecursiveIncludeError( + "maximum xinclude depth reached when including file %s" % href) + node = load_include(href, parse, parser=parser) + if node is None: + raise FatalIncludeError( + "cannot load %r as %r" % (href, parse) + ) + node = _include(node, loader, href, max_depth - 1, {href} | _parent_hrefs) + if e.tail: + node.tail = (node.tail or "") + e.tail + if parent is None: + return node # replaced the root node! + parent.replace(e, node) + elif parse == "text": + text = load_include(href, parse, encoding=e.get("encoding")) + if text is None: + raise FatalIncludeError( + "cannot load %r as %r" % (href, parse) + ) + predecessor = e.getprevious() + if predecessor is not None: + predecessor.tail = (predecessor.tail or "") + text + elif parent is None: + return text # replaced the root node! + else: + parent.text = (parent.text or "") + text + (e.tail or "") + parent.remove(e) + else: + raise FatalIncludeError( + "unknown parse type in xi:include tag (%r)" % parse + ) + elif e.tag == XINCLUDE_FALLBACK: + parent = e.getparent() + if parent is not None and parent.tag != XINCLUDE_INCLUDE: + raise FatalIncludeError( + "xi:fallback tag must be child of xi:include (%r)" % e.tag + ) + else: + raise FatalIncludeError( + "Invalid element found in XInclude namespace (%r)" % e.tag + ) + return elem diff --git a/venv/lib/python3.10/site-packages/lxml/__init__.py b/venv/lib/python3.10/site-packages/lxml/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8443a349899a9677a9c7630cf9076b7d89341590 --- /dev/null +++ b/venv/lib/python3.10/site-packages/lxml/__init__.py @@ -0,0 +1,22 @@ +# this is a package + +__version__ = "6.0.0" + + +def get_include(): + """ + Returns a list of header include paths (for lxml itself, libxml2 + and libxslt) needed to compile C code against lxml if it was built + with statically linked libraries. + """ + import os + lxml_path = __path__[0] + include_path = os.path.join(lxml_path, 'includes') + includes = [include_path, lxml_path] + + for name in os.listdir(include_path): + path = os.path.join(include_path, name) + if os.path.isdir(path): + includes.append(path) + + return includes diff --git a/venv/lib/python3.10/site-packages/lxml/__pycache__/ElementInclude.cpython-310.pyc b/venv/lib/python3.10/site-packages/lxml/__pycache__/ElementInclude.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2232fd37f1ed44589fbb7127de1f39f616c67268 Binary files /dev/null and b/venv/lib/python3.10/site-packages/lxml/__pycache__/ElementInclude.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/lxml/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/lxml/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc2f54e3e391b1675731eaba13adb74315ff3bc6 Binary files /dev/null and b/venv/lib/python3.10/site-packages/lxml/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/lxml/__pycache__/_elementpath.cpython-310.pyc b/venv/lib/python3.10/site-packages/lxml/__pycache__/_elementpath.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc90c035f53827fda52357fffa64f94fc57b32d8 Binary files /dev/null and b/venv/lib/python3.10/site-packages/lxml/__pycache__/_elementpath.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/lxml/__pycache__/builder.cpython-310.pyc b/venv/lib/python3.10/site-packages/lxml/__pycache__/builder.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4722a5d49091d07e66b298cc16623347479e8221 Binary files /dev/null and b/venv/lib/python3.10/site-packages/lxml/__pycache__/builder.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/lxml/__pycache__/cssselect.cpython-310.pyc b/venv/lib/python3.10/site-packages/lxml/__pycache__/cssselect.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..563a831aa8463aab96529a1d098f0284d5ab22b5 Binary files /dev/null and b/venv/lib/python3.10/site-packages/lxml/__pycache__/cssselect.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/lxml/__pycache__/doctestcompare.cpython-310.pyc b/venv/lib/python3.10/site-packages/lxml/__pycache__/doctestcompare.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ecdf714d13a0aa1c85be324e45f07b7eff2cf07f Binary files /dev/null and b/venv/lib/python3.10/site-packages/lxml/__pycache__/doctestcompare.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/lxml/__pycache__/pyclasslookup.cpython-310.pyc b/venv/lib/python3.10/site-packages/lxml/__pycache__/pyclasslookup.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1fa60cd700d60842bb5a7d975660c0500d4f840d Binary files /dev/null and b/venv/lib/python3.10/site-packages/lxml/__pycache__/pyclasslookup.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/lxml/__pycache__/sax.cpython-310.pyc b/venv/lib/python3.10/site-packages/lxml/__pycache__/sax.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..59e68846a9f161873bc76ab0849b6dc1716bd551 Binary files /dev/null and b/venv/lib/python3.10/site-packages/lxml/__pycache__/sax.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/lxml/__pycache__/usedoctest.cpython-310.pyc b/venv/lib/python3.10/site-packages/lxml/__pycache__/usedoctest.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8274aef4cd4da81978513dc9d5fbda06771000ad Binary files /dev/null and b/venv/lib/python3.10/site-packages/lxml/__pycache__/usedoctest.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/lxml/_elementpath.py b/venv/lib/python3.10/site-packages/lxml/_elementpath.py new file mode 100644 index 0000000000000000000000000000000000000000..760a1e00b8e1611e3915085482af1d9efc3a6ae1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/lxml/_elementpath.py @@ -0,0 +1,343 @@ +# cython: language_level=3 + +# +# ElementTree +# $Id: ElementPath.py 3375 2008-02-13 08:05:08Z fredrik $ +# +# limited xpath support for element trees +# +# history: +# 2003-05-23 fl created +# 2003-05-28 fl added support for // etc +# 2003-08-27 fl fixed parsing of periods in element names +# 2007-09-10 fl new selection engine +# 2007-09-12 fl fixed parent selector +# 2007-09-13 fl added iterfind; changed findall to return a list +# 2007-11-30 fl added namespaces support +# 2009-10-30 fl added child element value filter +# +# Copyright (c) 2003-2009 by Fredrik Lundh. All rights reserved. +# +# fredrik@pythonware.com +# http://www.pythonware.com +# +# -------------------------------------------------------------------- +# The ElementTree toolkit is +# +# Copyright (c) 1999-2009 by Fredrik Lundh +# +# By obtaining, using, and/or copying this software and/or its +# associated documentation, you agree that you have read, understood, +# and will comply with the following terms and conditions: +# +# Permission to use, copy, modify, and distribute this software and +# its associated documentation for any purpose and without fee is +# hereby granted, provided that the above copyright notice appears in +# all copies, and that both that copyright notice and this permission +# notice appear in supporting documentation, and that the name of +# Secret Labs AB or the author not be used in advertising or publicity +# pertaining to distribution of the software without specific, written +# prior permission. +# +# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD +# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT- +# ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR +# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY +# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS +# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE +# OF THIS SOFTWARE. +# -------------------------------------------------------------------- + +## +# Implementation module for XPath support. There's usually no reason +# to import this module directly; the ElementTree does this for +# you, if needed. +## + + +import re + +xpath_tokenizer_re = re.compile( + "(" + "'[^']*'|\"[^\"]*\"|" + "::|" + "//?|" + r"\.\.|" + r"\(\)|" + r"[/.*:\[\]\(\)@=])|" + r"((?:\{[^}]+\})?[^/\[\]\(\)@=\s]+)|" + r"\s+" + ) + +def xpath_tokenizer(pattern, namespaces=None, with_prefixes=True): + # ElementTree uses '', lxml used None originally. + default_namespace = (namespaces.get(None) or namespaces.get('')) if namespaces else None + parsing_attribute = False + for token in xpath_tokenizer_re.findall(pattern): + ttype, tag = token + if tag and tag[0] != "{": + if ":" in tag and with_prefixes: + prefix, uri = tag.split(":", 1) + try: + if not namespaces: + raise KeyError + yield ttype, "{%s}%s" % (namespaces[prefix], uri) + except KeyError: + raise SyntaxError("prefix %r not found in prefix map" % prefix) + elif tag.isdecimal(): + yield token # index + elif default_namespace and not parsing_attribute: + yield ttype, "{%s}%s" % (default_namespace, tag) + else: + yield token + parsing_attribute = False + else: + yield token + parsing_attribute = ttype == '@' + + +def prepare_child(next, token): + tag = token[1] + def select(result): + for elem in result: + yield from elem.iterchildren(tag) + return select + +def prepare_star(next, token): + def select(result): + for elem in result: + yield from elem.iterchildren('*') + return select + +def prepare_self(next, token): + def select(result): + return result + return select + +def prepare_descendant(next, token): + token = next() + if token[0] == "*": + tag = "*" + elif not token[0]: + tag = token[1] + else: + raise SyntaxError("invalid descendant") + def select(result): + for elem in result: + yield from elem.iterdescendants(tag) + return select + +def prepare_parent(next, token): + def select(result): + for elem in result: + parent = elem.getparent() + if parent is not None: + yield parent + return select + +def prepare_predicate(next, token): + # FIXME: replace with real parser!!! refs: + # http://effbot.org/zone/simple-iterator-parser.htm + # http://javascript.crockford.com/tdop/tdop.html + signature = '' + predicate = [] + while 1: + token = next() + if token[0] == "]": + break + if token == ('', ''): + # ignore whitespace + continue + if token[0] and token[0][:1] in "'\"": + token = "'", token[0][1:-1] + signature += token[0] or "-" + predicate.append(token[1]) + + # use signature to determine predicate type + if signature == "@-": + # [@attribute] predicate + key = predicate[1] + def select(result): + for elem in result: + if elem.get(key) is not None: + yield elem + return select + if signature == "@-='": + # [@attribute='value'] + key = predicate[1] + value = predicate[-1] + def select(result): + for elem in result: + if elem.get(key) == value: + yield elem + return select + if signature == "-" and not re.match(r"-?\d+$", predicate[0]): + # [tag] + tag = predicate[0] + def select(result): + for elem in result: + for _ in elem.iterchildren(tag): + yield elem + break + return select + if signature == ".='" or (signature == "-='" and not re.match(r"-?\d+$", predicate[0])): + # [.='value'] or [tag='value'] + tag = predicate[0] + value = predicate[-1] + if tag: + def select(result): + for elem in result: + for e in elem.iterchildren(tag): + if "".join(e.itertext()) == value: + yield elem + break + else: + def select(result): + for elem in result: + if "".join(elem.itertext()) == value: + yield elem + return select + if signature == "-" or signature == "-()" or signature == "-()-": + # [index] or [last()] or [last()-index] + if signature == "-": + # [index] + index = int(predicate[0]) - 1 + if index < 0: + if index == -1: + raise SyntaxError( + "indices in path predicates are 1-based, not 0-based") + else: + raise SyntaxError("path index >= 1 expected") + else: + if predicate[0] != "last": + raise SyntaxError("unsupported function") + if signature == "-()-": + try: + index = int(predicate[2]) - 1 + except ValueError: + raise SyntaxError("unsupported expression") + else: + index = -1 + def select(result): + for elem in result: + parent = elem.getparent() + if parent is None: + continue + try: + # FIXME: what if the selector is "*" ? + elems = list(parent.iterchildren(elem.tag)) + if elems[index] is elem: + yield elem + except IndexError: + pass + return select + raise SyntaxError("invalid predicate") + +ops = { + "": prepare_child, + "*": prepare_star, + ".": prepare_self, + "..": prepare_parent, + "//": prepare_descendant, + "[": prepare_predicate, +} + + +# -------------------------------------------------------------------- + +_cache = {} + + +def _build_path_iterator(path, namespaces, with_prefixes=True): + """compile selector pattern""" + if path[-1:] == "/": + path += "*" # implicit all (FIXME: keep this?) + + cache_key = (path,) + if namespaces: + # lxml originally used None for the default namespace but ElementTree uses the + # more convenient (all-strings-dict) empty string, so we support both here, + # preferring the more convenient '', as long as they aren't ambiguous. + if None in namespaces: + if '' in namespaces and namespaces[None] != namespaces['']: + raise ValueError("Ambiguous default namespace provided: %r versus %r" % ( + namespaces[None], namespaces[''])) + cache_key += (namespaces[None],) + tuple(sorted( + item for item in namespaces.items() if item[0] is not None)) + else: + cache_key += tuple(sorted(namespaces.items())) + + try: + return _cache[cache_key] + except KeyError: + pass + if len(_cache) > 100: + _cache.clear() + + if path[:1] == "/": + raise SyntaxError("cannot use absolute path on element") + stream = iter(xpath_tokenizer(path, namespaces, with_prefixes=with_prefixes)) + try: + _next = stream.next + except AttributeError: + # Python 3 + _next = stream.__next__ + try: + token = _next() + except StopIteration: + raise SyntaxError("empty path expression") + selector = [] + while 1: + try: + selector.append(ops[token[0]](_next, token)) + except StopIteration: + raise SyntaxError("invalid path") + try: + token = _next() + if token[0] == "/": + token = _next() + except StopIteration: + break + _cache[cache_key] = selector + return selector + + +## +# Iterate over the matching nodes + +def iterfind(elem, path, namespaces=None, with_prefixes=True): + selector = _build_path_iterator(path, namespaces, with_prefixes=with_prefixes) + result = iter((elem,)) + for select in selector: + result = select(result) + return result + + +## +# Find first matching object. + +def find(elem, path, namespaces=None, with_prefixes=True): + it = iterfind(elem, path, namespaces, with_prefixes=with_prefixes) + try: + return next(it) + except StopIteration: + return None + + +## +# Find all matching objects. + +def findall(elem, path, namespaces=None, with_prefixes=True): + return list(iterfind(elem, path, namespaces)) + + +## +# Find text for first matching object. + +def findtext(elem, path, default=None, namespaces=None, with_prefixes=True): + el = find(elem, path, namespaces, with_prefixes=with_prefixes) + if el is None: + return default + else: + return el.text or '' diff --git a/venv/lib/python3.10/site-packages/lxml/apihelpers.pxi b/venv/lib/python3.10/site-packages/lxml/apihelpers.pxi new file mode 100644 index 0000000000000000000000000000000000000000..f683e70db95645fe22e1af17a52efc1993a352f0 --- /dev/null +++ b/venv/lib/python3.10/site-packages/lxml/apihelpers.pxi @@ -0,0 +1,1801 @@ +# Private/public helper functions for API functions + +from lxml.includes cimport uri + + +cdef void displayNode(xmlNode* c_node, indent) noexcept: + # to help with debugging + cdef xmlNode* c_child + try: + print(indent * ' ', c_node) + c_child = c_node.children + while c_child is not NULL: + displayNode(c_child, indent + 1) + c_child = c_child.next + finally: + return # swallow any exceptions + +cdef inline bint _isHtmlDocument(_Element element) except -1: + cdef xmlNode* c_node = element._c_node + return ( + c_node is not NULL and c_node.doc is not NULL and + c_node.doc.properties & tree.XML_DOC_HTML != 0 + ) + +cdef inline int _assertValidNode(_Element element) except -1: + assert element._c_node is not NULL, "invalid Element proxy at %s" % id(element) + +cdef inline int _assertValidDoc(_Document doc) except -1: + assert doc._c_doc is not NULL, "invalid Document proxy at %s" % id(doc) + +cdef _Document _documentOrRaise(object input): + """Call this to get the document of a _Document, _ElementTree or _Element + object, or to raise an exception if it can't be determined. + + Should be used in all API functions for consistency. + """ + cdef _Document doc + if isinstance(input, _ElementTree): + if (<_ElementTree>input)._context_node is not None: + doc = (<_ElementTree>input)._context_node._doc + else: + doc = None + elif isinstance(input, _Element): + doc = (<_Element>input)._doc + elif isinstance(input, _Document): + doc = <_Document>input + else: + raise TypeError, f"Invalid input object: {python._fqtypename(input).decode('utf8')}" + if doc is None: + raise ValueError, f"Input object has no document: {python._fqtypename(input).decode('utf8')}" + _assertValidDoc(doc) + return doc + +cdef _Element _rootNodeOrRaise(object input): + """Call this to get the root node of a _Document, _ElementTree or + _Element object, or to raise an exception if it can't be determined. + + Should be used in all API functions for consistency. + """ + cdef _Element node + if isinstance(input, _ElementTree): + node = (<_ElementTree>input)._context_node + elif isinstance(input, _Element): + node = <_Element>input + elif isinstance(input, _Document): + node = (<_Document>input).getroot() + else: + raise TypeError, f"Invalid input object: {python._fqtypename(input).decode('utf8')}" + if (node is None or not node._c_node or + node._c_node.type != tree.XML_ELEMENT_NODE): + raise ValueError, f"Input object is not an XML element: {python._fqtypename(input).decode('utf8')}" + _assertValidNode(node) + return node + +cdef bint _isAncestorOrSame(xmlNode* c_ancestor, xmlNode* c_node) noexcept: + while c_node: + if c_node is c_ancestor: + return True + c_node = c_node.parent + return False + +cdef _Element _makeElement(tag, xmlDoc* c_doc, _Document doc, + _BaseParser parser, text, tail, attrib, nsmap, + dict extra_attrs): + """Create a new element and initialize text content, namespaces and + attributes. + + This helper function will reuse as much of the existing document as + possible: + + If 'parser' is None, the parser will be inherited from 'doc' or the + default parser will be used. + + If 'doc' is None, 'c_doc' is used to create a new _Document and the new + element is made its root node. + + If 'c_doc' is also NULL, a new xmlDoc will be created. + """ + cdef xmlNode* c_node + if doc is not None: + c_doc = doc._c_doc + ns_utf, name_utf = _getNsTag(tag) + if parser is not None and parser._for_html: + _htmlTagValidOrRaise(name_utf) + if c_doc is NULL: + c_doc = _newHTMLDoc() + else: + _tagValidOrRaise(name_utf) + if c_doc is NULL: + c_doc = _newXMLDoc() + c_node = _createElement(c_doc, name_utf) + if c_node is NULL: + if doc is None and c_doc is not NULL: + tree.xmlFreeDoc(c_doc) + raise MemoryError() + try: + if doc is None: + tree.xmlDocSetRootElement(c_doc, c_node) + doc = _documentFactory(c_doc, parser) + if text is not None: + _setNodeText(c_node, text) + if tail is not None: + _setTailText(c_node, tail) + # add namespaces to node if necessary + _setNodeNamespaces(c_node, doc, ns_utf, nsmap) + _initNodeAttributes(c_node, doc, attrib, extra_attrs) + return _elementFactory(doc, c_node) + except: + # free allocated c_node/c_doc unless Python does it for us + if c_node.doc is not c_doc: + # node not yet in document => will not be freed by document + if tail is not None: + _removeText(c_node.next) # tail + tree.xmlFreeNode(c_node) + if doc is None: + # c_doc will not be freed by doc + tree.xmlFreeDoc(c_doc) + raise + +cdef int _initNewElement(_Element element, bint is_html, name_utf, ns_utf, + _BaseParser parser, attrib, nsmap, dict extra_attrs) except -1: + """Initialise a new Element object. + + This is used when users instantiate a Python Element subclass + directly, without it being mapped to an existing XML node. + """ + cdef xmlDoc* c_doc + cdef xmlNode* c_node + cdef _Document doc + if is_html: + _htmlTagValidOrRaise(name_utf) + c_doc = _newHTMLDoc() + else: + _tagValidOrRaise(name_utf) + c_doc = _newXMLDoc() + c_node = _createElement(c_doc, name_utf) + if c_node is NULL: + if c_doc is not NULL: + tree.xmlFreeDoc(c_doc) + raise MemoryError() + tree.xmlDocSetRootElement(c_doc, c_node) + doc = _documentFactory(c_doc, parser) + # add namespaces to node if necessary + _setNodeNamespaces(c_node, doc, ns_utf, nsmap) + _initNodeAttributes(c_node, doc, attrib, extra_attrs) + _registerProxy(element, doc, c_node) + element._init() + return 0 + +cdef _Element _makeSubElement(_Element parent, tag, text, tail, + attrib, nsmap, dict extra_attrs): + """Create a new child element and initialize text content, namespaces and + attributes. + """ + cdef xmlNode* c_node + cdef xmlDoc* c_doc + if parent is None or parent._doc is None: + return None + _assertValidNode(parent) + ns_utf, name_utf = _getNsTag(tag) + c_doc = parent._doc._c_doc + + if parent._doc._parser is not None and parent._doc._parser._for_html: + _htmlTagValidOrRaise(name_utf) + else: + _tagValidOrRaise(name_utf) + + c_node = _createElement(c_doc, name_utf) + if c_node is NULL: + raise MemoryError() + tree.xmlAddChild(parent._c_node, c_node) + + try: + if text is not None: + _setNodeText(c_node, text) + if tail is not None: + _setTailText(c_node, tail) + + # add namespaces to node if necessary + _setNodeNamespaces(c_node, parent._doc, ns_utf, nsmap) + _initNodeAttributes(c_node, parent._doc, attrib, extra_attrs) + return _elementFactory(parent._doc, c_node) + except: + # make sure we clean up in case of an error + _removeNode(parent._doc, c_node) + raise + + +cdef int _setNodeNamespaces(xmlNode* c_node, _Document doc, + object node_ns_utf, object nsmap) except -1: + """Lookup current namespace prefixes, then set namespace structure for + node (if 'node_ns_utf' was provided) and register new ns-prefix mappings. + + 'node_ns_utf' should only be passed for a newly created node. + """ + cdef xmlNs* c_ns + cdef list nsdefs + + if nsmap: + for prefix, href in _iter_nsmap(nsmap): + href_utf = _utf8(href) + _uriValidOrRaise(href_utf) + c_href = _xcstr(href_utf) + if prefix is not None: + prefix_utf = _utf8(prefix) + _prefixValidOrRaise(prefix_utf) + c_prefix = _xcstr(prefix_utf) + else: + c_prefix = NULL + # add namespace with prefix if it is not already known + c_ns = tree.xmlSearchNs(doc._c_doc, c_node, c_prefix) + if c_ns is NULL or \ + c_ns.href is NULL or \ + tree.xmlStrcmp(c_ns.href, c_href) != 0: + c_ns = tree.xmlNewNs(c_node, c_href, c_prefix) + if href_utf == node_ns_utf: + tree.xmlSetNs(c_node, c_ns) + node_ns_utf = None + + if node_ns_utf is not None: + _uriValidOrRaise(node_ns_utf) + doc._setNodeNs(c_node, _xcstr(node_ns_utf)) + return 0 + + +cdef dict _build_nsmap(xmlNode* c_node): + """ + Namespace prefix->URI mapping known in the context of this Element. + This includes all namespace declarations of the parents. + """ + cdef xmlNs* c_ns + nsmap = {} + while c_node is not NULL and c_node.type == tree.XML_ELEMENT_NODE: + c_ns = c_node.nsDef + while c_ns is not NULL: + if c_ns.prefix or c_ns.href: + prefix = funicodeOrNone(c_ns.prefix) + if prefix not in nsmap: + nsmap[prefix] = funicodeOrNone(c_ns.href) + c_ns = c_ns.next + c_node = c_node.parent + return nsmap + + +cdef _iter_nsmap(nsmap): + """ + Create a reproducibly ordered iterable from an nsmap mapping. + Tries to preserve an existing order and sorts if it assumes no order. + + The difference to _iter_attrib() is that None doesn't sort with strings + in Py3.x. + """ + if isinstance(nsmap, dict): + # dicts are insertion-ordered in Py3.6+ => keep the user provided order. + return nsmap.items() + if len(nsmap) <= 1: + return nsmap.items() + # nsmap will usually be a plain unordered dict => avoid type checking overhead + if type(nsmap) is not dict and isinstance(nsmap, OrderedDict): + return nsmap.items() # keep existing order + if None not in nsmap: + return sorted(nsmap.items()) + + # Move the default namespace to the end. This makes sure libxml2 + # prefers a prefix if the ns is defined redundantly on the same + # element. That way, users can work around a problem themselves + # where default namespace attributes on non-default namespaced + # elements serialise without prefix (i.e. into the non-default + # namespace). + default_ns = nsmap[None] + nsdefs = [(k, v) for k, v in nsmap.items() if k is not None] + nsdefs.sort() + nsdefs.append((None, default_ns)) + return nsdefs + + +cdef _iter_attrib(attrib): + """ + Create a reproducibly ordered iterable from an attrib mapping. + Tries to preserve an existing order and sorts if it assumes no order. + """ + # dicts are insertion-ordered in Py3.6+ => keep the user provided order. + if isinstance(attrib, (dict, _Attrib, OrderedDict)): + return attrib.items() + # assume it's an unordered mapping of some kind + return sorted(attrib.items()) + + +cdef _initNodeAttributes(xmlNode* c_node, _Document doc, attrib, dict extra): + """Initialise the attributes of an element node. + """ + cdef bint is_html + cdef xmlNs* c_ns + if attrib is not None and not hasattr(attrib, 'items'): + raise TypeError, f"Invalid attribute dictionary: {python._fqtypename(attrib).decode('utf8')}" + if not attrib and not extra: + return # nothing to do + is_html = doc._parser._for_html + seen = set() + if extra: + for name, value in extra.items(): + _addAttributeToNode(c_node, doc, is_html, name, value, seen) + if attrib: + for name, value in _iter_attrib(attrib): + _addAttributeToNode(c_node, doc, is_html, name, value, seen) + + +cdef int _addAttributeToNode(xmlNode* c_node, _Document doc, bint is_html, + name, value, set seen_tags) except -1: + ns_utf, name_utf = tag = _getNsTag(name) + if tag in seen_tags: + return 0 + seen_tags.add(tag) + if not is_html: + _attributeValidOrRaise(name_utf) + value_utf = _utf8(value) + if ns_utf is None: + tree.xmlNewProp(c_node, _xcstr(name_utf), _xcstr(value_utf)) + else: + _uriValidOrRaise(ns_utf) + c_ns = doc._findOrBuildNodeNs(c_node, _xcstr(ns_utf), NULL, 1) + tree.xmlNewNsProp(c_node, c_ns, + _xcstr(name_utf), _xcstr(value_utf)) + return 0 + + +ctypedef struct _ns_node_ref: + xmlNs* ns + xmlNode* node + + +cdef int _collectNsDefs(xmlNode* c_element, _ns_node_ref **_c_ns_list, + size_t *_c_ns_list_len, size_t *_c_ns_list_size) except -1: + c_ns_list = _c_ns_list[0] + cdef size_t c_ns_list_len = _c_ns_list_len[0] + cdef size_t c_ns_list_size = _c_ns_list_size[0] + + c_nsdef = c_element.nsDef + while c_nsdef is not NULL: + if c_ns_list_len >= c_ns_list_size: + if c_ns_list is NULL: + c_ns_list_size = 20 + else: + c_ns_list_size *= 2 + c_nsref_ptr = <_ns_node_ref*> python.lxml_realloc( + c_ns_list, c_ns_list_size, sizeof(_ns_node_ref)) + if c_nsref_ptr is NULL: + if c_ns_list is not NULL: + python.lxml_free(c_ns_list) + _c_ns_list[0] = NULL + raise MemoryError() + c_ns_list = c_nsref_ptr + + c_ns_list[c_ns_list_len] = _ns_node_ref(c_nsdef, c_element) + c_ns_list_len += 1 + c_nsdef = c_nsdef.next + + _c_ns_list_size[0] = c_ns_list_size + _c_ns_list_len[0] = c_ns_list_len + _c_ns_list[0] = c_ns_list + + +cdef int _removeUnusedNamespaceDeclarations(xmlNode* c_element, set prefixes_to_keep) except -1: + """Remove any namespace declarations from a subtree that are not used by + any of its elements (or attributes). + + If a 'prefixes_to_keep' is provided, it must be a set of prefixes. + Any corresponding namespace mappings will not be removed as part of the cleanup. + """ + cdef xmlNode* c_node + cdef _ns_node_ref* c_ns_list = NULL + cdef size_t c_ns_list_size = 0 + cdef size_t c_ns_list_len = 0 + cdef size_t i + + if c_element.parent and c_element.parent.type == tree.XML_DOCUMENT_NODE: + # include declarations on the document node + _collectNsDefs(c_element.parent, &c_ns_list, &c_ns_list_len, &c_ns_list_size) + + tree.BEGIN_FOR_EACH_ELEMENT_FROM(c_element, c_element, 1) + # collect all new namespace declarations into the ns list + if c_element.nsDef: + _collectNsDefs(c_element, &c_ns_list, &c_ns_list_len, &c_ns_list_size) + + # remove all namespace declarations from the list that are referenced + if c_ns_list_len and c_element.type == tree.XML_ELEMENT_NODE: + c_node = c_element + while c_node and c_ns_list_len: + if c_node.ns: + for i in range(c_ns_list_len): + if c_node.ns is c_ns_list[i].ns: + c_ns_list_len -= 1 + c_ns_list[i] = c_ns_list[c_ns_list_len] + #c_ns_list[c_ns_list_len] = _ns_node_ref(NULL, NULL) + break + if c_node is c_element: + # continue with attributes + c_node = c_element.properties + else: + c_node = c_node.next + tree.END_FOR_EACH_ELEMENT_FROM(c_element) + + if c_ns_list is NULL: + return 0 + + # free all namespace declarations that remained in the list, + # except for those we should keep explicitly + cdef xmlNs* c_nsdef + for i in range(c_ns_list_len): + if prefixes_to_keep is not None: + if c_ns_list[i].ns.prefix and c_ns_list[i].ns.prefix in prefixes_to_keep: + continue + c_node = c_ns_list[i].node + c_nsdef = c_node.nsDef + if c_nsdef is c_ns_list[i].ns: + c_node.nsDef = c_node.nsDef.next + else: + while c_nsdef.next is not c_ns_list[i].ns: + c_nsdef = c_nsdef.next + c_nsdef.next = c_nsdef.next.next + tree.xmlFreeNs(c_ns_list[i].ns) + + if c_ns_list is not NULL: + python.lxml_free(c_ns_list) + return 0 + +cdef xmlNs* _searchNsByHref(xmlNode* c_node, const_xmlChar* c_href, bint is_attribute) noexcept: + """Search a namespace declaration that covers a node (element or + attribute). + + For attributes, try to find a prefixed namespace declaration + instead of the default namespaces. This helps in supporting + round-trips for attributes on elements with a different namespace. + """ + cdef xmlNs* c_ns + cdef xmlNs* c_default_ns = NULL + cdef xmlNode* c_element + if c_href is NULL or c_node is NULL or c_node.type == tree.XML_ENTITY_REF_NODE: + return NULL + if tree.xmlStrcmp(c_href, tree.XML_XML_NAMESPACE) == 0: + # no special cases here, let libxml2 handle this + return tree.xmlSearchNsByHref(c_node.doc, c_node, c_href) + if c_node.type == tree.XML_ATTRIBUTE_NODE: + is_attribute = 1 + while c_node is not NULL and c_node.type != tree.XML_ELEMENT_NODE: + c_node = c_node.parent + c_element = c_node + while c_node is not NULL: + if c_node.type == tree.XML_ELEMENT_NODE: + c_ns = c_node.nsDef + while c_ns is not NULL: + if c_ns.href is not NULL and tree.xmlStrcmp(c_href, c_ns.href) == 0: + if c_ns.prefix is NULL and is_attribute: + # for attributes, continue searching a named + # prefix, but keep the first default namespace + # declaration that we found + if c_default_ns is NULL: + c_default_ns = c_ns + elif tree.xmlSearchNs( + c_element.doc, c_element, c_ns.prefix) is c_ns: + # start node is in namespace scope => found! + return c_ns + c_ns = c_ns.next + if c_node is not c_element and c_node.ns is not NULL: + # optimise: the node may have the namespace itself + c_ns = c_node.ns + if c_ns.href is not NULL and tree.xmlStrcmp(c_href, c_ns.href) == 0: + if c_ns.prefix is NULL and is_attribute: + # for attributes, continue searching a named + # prefix, but keep the first default namespace + # declaration that we found + if c_default_ns is NULL: + c_default_ns = c_ns + elif tree.xmlSearchNs( + c_element.doc, c_element, c_ns.prefix) is c_ns: + # start node is in namespace scope => found! + return c_ns + c_node = c_node.parent + # nothing found => use a matching default namespace or fail + if c_default_ns is not NULL: + if tree.xmlSearchNs(c_element.doc, c_element, NULL) is c_default_ns: + return c_default_ns + return NULL + +cdef int _replaceNodeByChildren(_Document doc, xmlNode* c_node) except -1: + # NOTE: this does not deallocate the node, just unlink it! + cdef xmlNode* c_parent + cdef xmlNode* c_child + if c_node.children is NULL: + tree.xmlUnlinkNode(c_node) + return 0 + + c_parent = c_node.parent + # fix parent links of children + c_child = c_node.children + while c_child is not NULL: + c_child.parent = c_parent + c_child = c_child.next + + # fix namespace references of children if their parent's namespace + # declarations get lost + if c_node.nsDef is not NULL: + c_child = c_node.children + while c_child is not NULL: + moveNodeToDocument(doc, doc._c_doc, c_child) + c_child = c_child.next + + # fix sibling links to/from child slice + if c_node.prev is NULL: + c_parent.children = c_node.children + else: + c_node.prev.next = c_node.children + c_node.children.prev = c_node.prev + if c_node.next is NULL: + c_parent.last = c_node.last + else: + c_node.next.prev = c_node.last + c_node.last.next = c_node.next + + # unlink c_node + c_node.children = c_node.last = NULL + c_node.parent = c_node.next = c_node.prev = NULL + return 0 + +cdef unicode _attributeValue(xmlNode* c_element, xmlAttr* c_attrib_node): + c_href = _getNs(c_attrib_node) + value = tree.xmlGetNsProp(c_element, c_attrib_node.name, c_href) + try: + result = funicode(value) + finally: + tree.xmlFree(value) + return result + +cdef unicode _attributeValueFromNsName(xmlNode* c_element, + const_xmlChar* c_href, const_xmlChar* c_name): + c_result = tree.xmlGetNsProp(c_element, c_name, c_href) + if c_result is NULL: + return None + try: + result = funicode(c_result) + finally: + tree.xmlFree(c_result) + return result + +cdef object _getNodeAttributeValue(xmlNode* c_node, key, default): + ns, tag = _getNsTag(key) + c_href = NULL if ns is None else _xcstr(ns) + c_result = tree.xmlGetNsProp(c_node, _xcstr(tag), c_href) + if c_result is NULL: + # XXX free namespace that is not in use..? + return default + try: + result = funicode(c_result) + finally: + tree.xmlFree(c_result) + return result + +cdef inline object _getAttributeValue(_Element element, key, default): + return _getNodeAttributeValue(element._c_node, key, default) + +cdef int _setAttributeValue(_Element element, key, value) except -1: + cdef const_xmlChar* c_value + cdef xmlNs* c_ns + ns, tag = _getNsTag(key) + is_html = element._doc._parser._for_html + if not is_html: + _attributeValidOrRaise(tag) + c_tag = _xcstr(tag) + if value is None and is_html: + c_value = NULL + else: + if isinstance(value, QName): + value = _resolveQNameText(element, value) + else: + value = _utf8(value) + c_value = _xcstr(value) + if ns is None: + c_ns = NULL + else: + c_ns = element._doc._findOrBuildNodeNs(element._c_node, _xcstr(ns), NULL, 1) + tree.xmlSetNsProp(element._c_node, c_ns, c_tag, c_value) + return 0 + +cdef int _delAttribute(_Element element, key) except -1: + ns, tag = _getNsTag(key) + c_href = NULL if ns is None else _xcstr(ns) + if _delAttributeFromNsName(element._c_node, c_href, _xcstr(tag)): + raise KeyError, key + return 0 + +cdef int _delAttributeFromNsName(xmlNode* c_node, const_xmlChar* c_href, const_xmlChar* c_name) noexcept: + c_attr = tree.xmlHasNsProp(c_node, c_name, c_href) + if c_attr is NULL: + # XXX free namespace that is not in use..? + return -1 + tree.xmlRemoveProp(c_attr) + return 0 + +cdef list _collectAttributes(xmlNode* c_node, int collecttype): + """Collect all attributes of a node in a list. Depending on collecttype, + it collects either the name (1), the value (2) or the name-value tuples. + """ + cdef Py_ssize_t count + c_attr = c_node.properties + count = 0 + while c_attr is not NULL: + if c_attr.type == tree.XML_ATTRIBUTE_NODE: + count += 1 + c_attr = c_attr.next + + if not count: + return [] + + attributes = [None] * count + c_attr = c_node.properties + count = 0 + while c_attr is not NULL: + if c_attr.type == tree.XML_ATTRIBUTE_NODE: + if collecttype == 1: + item = _namespacedName(c_attr) + elif collecttype == 2: + item = _attributeValue(c_node, c_attr) + else: + item = (_namespacedName(c_attr), + _attributeValue(c_node, c_attr)) + attributes[count] = item + count += 1 + c_attr = c_attr.next + return attributes + +cdef object __RE_XML_ENCODING = re.compile( + r'^(<\?xml[^>]+)\s+encoding\s*=\s*["\'][^"\']*["\'](\s*\?>|)', re.U) + +cdef object __REPLACE_XML_ENCODING = __RE_XML_ENCODING.sub +cdef object __HAS_XML_ENCODING = __RE_XML_ENCODING.match + +cdef object _stripEncodingDeclaration(object xml_string): + # this is a hack to remove the XML encoding declaration from unicode + return __REPLACE_XML_ENCODING(r'\g<1>\g<2>', xml_string) + +cdef bint _hasEncodingDeclaration(object xml_string) except -1: + # check if a (unicode) string has an XML encoding declaration + return __HAS_XML_ENCODING(xml_string) is not None + +cdef inline bint _hasText(xmlNode* c_node) noexcept: + return c_node is not NULL and _textNodeOrSkip(c_node.children) is not NULL + +cdef inline bint _hasTail(xmlNode* c_node) noexcept: + return c_node is not NULL and _textNodeOrSkip(c_node.next) is not NULL + +cdef inline bint _hasNonWhitespaceTail(xmlNode* c_node) except -1: + return _hasNonWhitespaceText(c_node, tail=True) + +cdef bint _hasNonWhitespaceText(xmlNode* c_node, bint tail=False) except -1: + c_text_node = c_node and _textNodeOrSkip(c_node.next if tail else c_node.children) + if c_text_node is NULL: + return False + while c_text_node is not NULL: + if c_text_node.content[0] != c'\0' and not _collectText(c_text_node).isspace(): + return True + c_text_node = _textNodeOrSkip(c_text_node.next) + return False + +cdef unicode _collectText(xmlNode* c_node): + """Collect all text nodes and return them as a unicode string. + + Start collecting at c_node. + + If there was no text to collect, return None + """ + cdef Py_ssize_t scount + cdef xmlChar* c_text + cdef xmlNode* c_node_cur + # check for multiple text nodes + scount = 0 + c_text = NULL + c_node_cur = c_node = _textNodeOrSkip(c_node) + while c_node_cur is not NULL: + if c_node_cur.content[0] != c'\0': + c_text = c_node_cur.content + scount += 1 + c_node_cur = _textNodeOrSkip(c_node_cur.next) + + # handle two most common cases first + if c_text is NULL: + return '' if scount > 0 else None + if scount == 1: + return funicode(c_text) + + # the rest is not performance critical anymore + result = b'' + while c_node is not NULL: + result += c_node.content + c_node = _textNodeOrSkip(c_node.next) + return funicode(result) + +cdef void _removeText(xmlNode* c_node) noexcept: + """Remove all text nodes. + + Start removing at c_node. + """ + cdef xmlNode* c_next + c_node = _textNodeOrSkip(c_node) + while c_node is not NULL: + c_next = _textNodeOrSkip(c_node.next) + tree.xmlUnlinkNode(c_node) + tree.xmlFreeNode(c_node) + c_node = c_next + +cdef xmlNode* _createTextNode(xmlDoc* doc, value) except NULL: + cdef xmlNode* c_text_node + if isinstance(value, CDATA): + c_text_node = tree.xmlNewCDataBlock( + doc, _xcstr((value)._utf8_data), + python.PyBytes_GET_SIZE((value)._utf8_data)) + else: + text = _utf8(value) + c_text_node = tree.xmlNewDocText(doc, _xcstr(text)) + if not c_text_node: + raise MemoryError() + return c_text_node + +cdef int _setNodeText(xmlNode* c_node, value) except -1: + # remove all text nodes at the start first + _removeText(c_node.children) + if value is None: + return 0 + # now add new text node with value at start + c_text_node = _createTextNode(c_node.doc, value) + if c_node.children is NULL: + tree.xmlAddChild(c_node, c_text_node) + else: + tree.xmlAddPrevSibling(c_node.children, c_text_node) + return 0 + +cdef int _setTailText(xmlNode* c_node, value) except -1: + # remove all text nodes at the start first + _removeText(c_node.next) + if value is None: + return 0 + # now append new text node with value + c_text_node = _createTextNode(c_node.doc, value) + tree.xmlAddNextSibling(c_node, c_text_node) + return 0 + +cdef bytes _resolveQNameText(_Element element, value): + cdef xmlNs* c_ns + ns, tag = _getNsTag(value) + if ns is None: + return tag + else: + c_ns = element._doc._findOrBuildNodeNs( + element._c_node, _xcstr(ns), NULL, 0) + return python.PyBytes_FromFormat('%s:%s', c_ns.prefix, _cstr(tag)) + +cdef inline bint _hasChild(xmlNode* c_node) noexcept: + return c_node is not NULL and _findChildForwards(c_node, 0) is not NULL + +cdef inline Py_ssize_t _countElements(xmlNode* c_node) noexcept: + "Counts the elements within the following siblings and the node itself." + cdef Py_ssize_t count + count = 0 + while c_node is not NULL: + if _isElement(c_node): + count += 1 + c_node = c_node.next + return count + +cdef int _findChildSlice( + slice sliceobject, xmlNode* c_parent, + xmlNode** c_start_node, Py_ssize_t* c_step, Py_ssize_t* c_length) except -1: + """Resolve a children slice. + + Returns the start node, step size and the slice length in the + pointer arguments. + """ + cdef Py_ssize_t start = 0, stop = 0, childcount + childcount = _countElements(c_parent.children) + if childcount == 0: + c_start_node[0] = NULL + c_length[0] = 0 + if sliceobject.step is None: + c_step[0] = 1 + else: + python._PyEval_SliceIndex(sliceobject.step, c_step) + return 0 + python.PySlice_GetIndicesEx( + sliceobject, childcount, &start, &stop, c_step, c_length) + if start > childcount // 2: + c_start_node[0] = _findChildBackwards(c_parent, childcount - start - 1) + else: + c_start_node[0] = _findChild(c_parent, start) + return 0 + +cdef bint _isFullSlice(slice sliceobject) except -1: + """Conservative guess if this slice is a full slice as in ``s[:]``. + """ + cdef Py_ssize_t step = 0 + if sliceobject is None: + return 0 + if sliceobject.start is None and \ + sliceobject.stop is None: + if sliceobject.step is None: + return 1 + python._PyEval_SliceIndex(sliceobject.step, &step) + if step == 1: + return 1 + return 0 + return 0 + +cdef _collectChildren(_Element element): + cdef xmlNode* c_node + cdef list result = [] + c_node = element._c_node.children + if c_node is not NULL: + if not _isElement(c_node): + c_node = _nextElement(c_node) + while c_node is not NULL: + result.append(_elementFactory(element._doc, c_node)) + c_node = _nextElement(c_node) + return result + +cdef inline xmlNode* _findChild(xmlNode* c_node, Py_ssize_t index) noexcept: + if index < 0: + return _findChildBackwards(c_node, -index - 1) + else: + return _findChildForwards(c_node, index) + +cdef inline xmlNode* _findChildForwards(xmlNode* c_node, Py_ssize_t index) noexcept: + """Return child element of c_node with index, or return NULL if not found. + """ + cdef xmlNode* c_child + cdef Py_ssize_t c + c_child = c_node.children + c = 0 + while c_child is not NULL: + if _isElement(c_child): + if c == index: + return c_child + c += 1 + c_child = c_child.next + return NULL + +cdef inline xmlNode* _findChildBackwards(xmlNode* c_node, Py_ssize_t index) noexcept: + """Return child element of c_node with index, or return NULL if not found. + Search from the end. + """ + cdef xmlNode* c_child + cdef Py_ssize_t c + c_child = c_node.last + c = 0 + while c_child is not NULL: + if _isElement(c_child): + if c == index: + return c_child + c += 1 + c_child = c_child.prev + return NULL + +cdef inline xmlNode* _textNodeOrSkip(xmlNode* c_node) noexcept nogil: + """Return the node if it's a text node. Skip over ignorable nodes in a + series of text nodes. Return NULL if a non-ignorable node is found. + + This is used to skip over XInclude nodes when collecting adjacent text + nodes. + """ + while c_node is not NULL: + if c_node.type == tree.XML_TEXT_NODE or \ + c_node.type == tree.XML_CDATA_SECTION_NODE: + return c_node + elif c_node.type == tree.XML_XINCLUDE_START or \ + c_node.type == tree.XML_XINCLUDE_END: + c_node = c_node.next + else: + return NULL + return NULL + +cdef inline xmlNode* _nextElement(xmlNode* c_node) noexcept: + """Given a node, find the next sibling that is an element. + """ + if c_node is NULL: + return NULL + c_node = c_node.next + while c_node is not NULL: + if _isElement(c_node): + return c_node + c_node = c_node.next + return NULL + +cdef inline xmlNode* _previousElement(xmlNode* c_node) noexcept: + """Given a node, find the next sibling that is an element. + """ + if c_node is NULL: + return NULL + c_node = c_node.prev + while c_node is not NULL: + if _isElement(c_node): + return c_node + c_node = c_node.prev + return NULL + +cdef inline xmlNode* _parentElement(xmlNode* c_node) noexcept: + "Given a node, find the parent element." + if c_node is NULL or not _isElement(c_node): + return NULL + c_node = c_node.parent + if c_node is NULL or not _isElement(c_node): + return NULL + return c_node + +cdef inline bint _tagMatches(xmlNode* c_node, const_xmlChar* c_href, const_xmlChar* c_name) noexcept: + """Tests if the node matches namespace URI and tag name. + + A node matches if it matches both c_href and c_name. + + A node matches c_href if any of the following is true: + * c_href is NULL + * its namespace is NULL and c_href is the empty string + * its namespace string equals the c_href string + + A node matches c_name if any of the following is true: + * c_name is NULL + * its name string equals the c_name string + """ + if c_node is NULL: + return 0 + if c_node.type != tree.XML_ELEMENT_NODE: + # not an element, only succeed if we match everything + return c_name is NULL and c_href is NULL + if c_name is NULL: + if c_href is NULL: + # always match + return 1 + else: + c_node_href = _getNs(c_node) + if c_node_href is NULL: + return c_href[0] == c'\0' + else: + return tree.xmlStrcmp(c_node_href, c_href) == 0 + elif c_href is NULL: + if _getNs(c_node) is not NULL: + return 0 + return c_node.name == c_name or tree.xmlStrcmp(c_node.name, c_name) == 0 + elif c_node.name == c_name or tree.xmlStrcmp(c_node.name, c_name) == 0: + c_node_href = _getNs(c_node) + if c_node_href is NULL: + return c_href[0] == c'\0' + else: + return tree.xmlStrcmp(c_node_href, c_href) == 0 + else: + return 0 + +cdef inline bint _tagMatchesExactly(xmlNode* c_node, qname* c_qname) noexcept: + """Tests if the node matches namespace URI and tag name. + + This differs from _tagMatches() in that it does not consider a + NULL value in qname.href a wildcard, and that it expects the c_name + to be taken from the doc dict, i.e. it only compares the names by + address. + + A node matches if it matches both href and c_name of the qname. + + A node matches c_href if any of the following is true: + * its namespace is NULL and c_href is the empty string + * its namespace string equals the c_href string + + A node matches c_name if any of the following is true: + * c_name is NULL + * its name string points to the same address (!) as c_name + """ + return _nsTagMatchesExactly(_getNs(c_node), c_node.name, c_qname) + +cdef inline bint _nsTagMatchesExactly(const_xmlChar* c_node_href, + const_xmlChar* c_node_name, + qname* c_qname) noexcept: + """Tests if name and namespace URI match those of c_qname. + + This differs from _tagMatches() in that it does not consider a + NULL value in qname.href a wildcard, and that it expects the c_name + to be taken from the doc dict, i.e. it only compares the names by + address. + + A node matches if it matches both href and c_name of the qname. + + A node matches c_href if any of the following is true: + * its namespace is NULL and c_href is the empty string + * its namespace string equals the c_href string + + A node matches c_name if any of the following is true: + * c_name is NULL + * its name string points to the same address (!) as c_name + """ + cdef char* c_href + if c_qname.c_name is not NULL and c_qname.c_name is not c_node_name: + return 0 + if c_qname.href is NULL: + return 1 + c_href = python.__cstr(c_qname.href) + if c_href[0] == b'\0': + return c_node_href is NULL or c_node_href[0] == b'\0' + elif c_node_href is NULL: + return 0 + else: + return tree.xmlStrcmp(c_href, c_node_href) == 0 + +cdef Py_ssize_t _mapTagsToQnameMatchArray(xmlDoc* c_doc, list ns_tags, + qname* c_ns_tags, bint force_into_dict) except -1: + """Map a sequence of (name, namespace) pairs to a qname array for efficient + matching with _tagMatchesExactly() above. + + Note that each qname struct in the array owns its href byte string object + if it is not NULL. + """ + cdef Py_ssize_t count = 0, i, c_tag_len + cdef bytes ns, tag + cdef const_xmlChar* c_tag + + for ns, tag in ns_tags: + if tag is None: + c_tag = NULL + else: + c_tag_len = len(tag) + if c_tag_len > limits.INT_MAX: + # too long, not in the dict => not in the document + continue + elif force_into_dict: + c_tag = tree.xmlDictLookup(c_doc.dict, _xcstr(tag), c_tag_len) + if c_tag is NULL: + # clean up before raising the error + for i in xrange(count): + cpython.ref.Py_XDECREF(c_ns_tags[i].href) + raise MemoryError() + else: + c_tag = tree.xmlDictExists(c_doc.dict, _xcstr(tag), c_tag_len) + if c_tag is NULL: + # not in the dict => not in the document + continue + + c_ns_tags[count].c_name = c_tag + if ns is None: + c_ns_tags[count].href = NULL + else: + cpython.ref.Py_INCREF(ns) # keep an owned reference! + c_ns_tags[count].href = ns + count += 1 + return count + +cdef int _removeNode(_Document doc, xmlNode* c_node) except -1: + """Unlink and free a node and subnodes if possible. Otherwise, make sure + it's self-contained. + """ + cdef xmlNode* c_next + c_next = c_node.next + tree.xmlUnlinkNode(c_node) + _moveTail(c_next, c_node) + if not attemptDeallocation(c_node): + # make namespaces absolute + moveNodeToDocument(doc, c_node.doc, c_node) + return 0 + +cdef int _removeSiblings(xmlNode* c_element, tree.xmlElementType node_type, bint with_tail) except -1: + cdef xmlNode* c_node + cdef xmlNode* c_next + c_node = c_element.next + while c_node is not NULL: + c_next = _nextElement(c_node) + if c_node.type == node_type: + if with_tail: + _removeText(c_node.next) + tree.xmlUnlinkNode(c_node) + attemptDeallocation(c_node) + c_node = c_next + c_node = c_element.prev + while c_node is not NULL: + c_next = _previousElement(c_node) + if c_node.type == node_type: + if with_tail: + _removeText(c_node.next) + tree.xmlUnlinkNode(c_node) + attemptDeallocation(c_node) + c_node = c_next + return 0 + +cdef void _moveTail(xmlNode* c_tail, xmlNode* c_target) noexcept: + cdef xmlNode* c_next + # tail support: look for any text nodes trailing this node and + # move them too + c_tail = _textNodeOrSkip(c_tail) + while c_tail is not NULL: + c_next = _textNodeOrSkip(c_tail.next) + c_target = tree.xmlAddNextSibling(c_target, c_tail) + c_tail = c_next + +cdef int _copyTail(xmlNode* c_tail, xmlNode* c_target) except -1: + cdef xmlNode* c_new_tail + # tail copying support: look for any text nodes trailing this node and + # copy it to the target node + c_tail = _textNodeOrSkip(c_tail) + while c_tail is not NULL: + if c_target.doc is not c_tail.doc: + c_new_tail = tree.xmlDocCopyNode(c_tail, c_target.doc, 0) + else: + c_new_tail = tree.xmlCopyNode(c_tail, 0) + if c_new_tail is NULL: + raise MemoryError() + c_target = tree.xmlAddNextSibling(c_target, c_new_tail) + c_tail = _textNodeOrSkip(c_tail.next) + return 0 + +cdef int _copyNonElementSiblings(xmlNode* c_node, xmlNode* c_target) except -1: + cdef xmlNode* c_copy + cdef xmlNode* c_sibling = c_node + while c_sibling.prev != NULL and \ + (c_sibling.prev.type == tree.XML_PI_NODE or + c_sibling.prev.type == tree.XML_COMMENT_NODE or + c_sibling.prev.type == tree.XML_DTD_NODE): + c_sibling = c_sibling.prev + while c_sibling != c_node: + if c_sibling.type == tree.XML_DTD_NODE: + c_copy = _copyDtd(c_sibling) + if c_sibling == c_node.doc.intSubset: + c_target.doc.intSubset = c_copy + else: # c_sibling == c_node.doc.extSubset + c_target.doc.extSubset = c_copy + else: + c_copy = tree.xmlDocCopyNode(c_sibling, c_target.doc, 1) + if c_copy is NULL: + raise MemoryError() + tree.xmlAddPrevSibling(c_target, c_copy) + c_sibling = c_sibling.next + while c_sibling.next != NULL and \ + (c_sibling.next.type == tree.XML_PI_NODE or + c_sibling.next.type == tree.XML_COMMENT_NODE): + c_sibling = c_sibling.next + c_copy = tree.xmlDocCopyNode(c_sibling, c_target.doc, 1) + if c_copy is NULL: + raise MemoryError() + tree.xmlAddNextSibling(c_target, c_copy) + +cdef int _deleteSlice(_Document doc, xmlNode* c_node, + Py_ssize_t count, Py_ssize_t step) except -1: + """Delete slice, ``count`` items starting with ``c_node`` with a step + width of ``step``. + """ + cdef xmlNode* c_next + cdef Py_ssize_t c, i + cdef _node_to_node_function next_element + if c_node is NULL: + return 0 + if step > 0: + next_element = _nextElement + else: + step = -step + next_element = _previousElement + # now start deleting nodes + c = 0 + c_next = c_node + while c_node is not NULL and c < count: + for i in range(step): + c_next = next_element(c_next) + if c_next is NULL: + break + _removeNode(doc, c_node) + c += 1 + c_node = c_next + return 0 + +cdef int _replaceSlice(_Element parent, xmlNode* c_node, + Py_ssize_t slicelength, Py_ssize_t step, + bint left_to_right, elements) except -1: + """Replace the slice of ``count`` elements starting at ``c_node`` with + positive step width ``step`` by the Elements in ``elements``. The + direction is given by the boolean argument ``left_to_right``. + + ``c_node`` may be NULL to indicate the end of the children list. + """ + cdef xmlNode* c_orig_neighbour + cdef xmlNode* c_next + cdef xmlDoc* c_source_doc + cdef _Element element + cdef Py_ssize_t seqlength, i, c + cdef _node_to_node_function next_element + assert step > 0 + if left_to_right: + next_element = _nextElement + else: + next_element = _previousElement + + if not isinstance(elements, (list, tuple)): + elements = list(elements) + + if step != 1 or not left_to_right: + # *replacing* children stepwise with list => check size! + seqlength = len(elements) + if seqlength != slicelength: + raise ValueError, f"attempt to assign sequence of size {seqlength} " \ + f"to extended slice of size {slicelength}" + + if c_node is NULL: + # no children yet => add all elements straight away + if left_to_right: + for element in elements: + assert element is not None, "Node must not be None" + _appendChild(parent, element) + else: + for element in elements: + assert element is not None, "Node must not be None" + _prependChild(parent, element) + return 0 + + # remove the elements first as some might be re-added + if left_to_right: + # L->R, remember left neighbour + c_orig_neighbour = _previousElement(c_node) + else: + # R->L, remember right neighbour + c_orig_neighbour = _nextElement(c_node) + + # We remove the original slice elements one by one. Since we hold + # a Python reference to all elements that we will insert, it is + # safe to let _removeNode() try (and fail) to free them even if + # the element itself or one of its descendents will be reinserted. + c = 0 + c_next = c_node + while c_node is not NULL and c < slicelength: + for i in range(step): + c_next = next_element(c_next) + if c_next is NULL: + break + _removeNode(parent._doc, c_node) + c += 1 + c_node = c_next + + # make sure each element is inserted only once + elements = iter(elements) + + # find the first node right of the new insertion point + if left_to_right: + if c_orig_neighbour is not NULL: + c_node = next_element(c_orig_neighbour) + else: + # before the first element + c_node = _findChildForwards(parent._c_node, 0) + elif c_orig_neighbour is NULL: + # at the end, but reversed stepping + # append one element and go to the next insertion point + for element in elements: + assert element is not None, "Node must not be None" + _appendChild(parent, element) + c_node = element._c_node + if slicelength > 0: + slicelength -= 1 + for i in range(1, step): + c_node = next_element(c_node) + if c_node is NULL: + break + break + else: + c_node = c_orig_neighbour + + if left_to_right: + # adjust step size after removing slice as we are not stepping + # over the newly inserted elements + step -= 1 + + # now insert elements where we removed them + if c_node is not NULL: + for element in elements: + assert element is not None, "Node must not be None" + _assertValidNode(element) + # move element and tail over + c_source_doc = element._c_node.doc + c_next = element._c_node.next + tree.xmlAddPrevSibling(c_node, element._c_node) + _moveTail(c_next, element._c_node) + + # integrate element into new document + moveNodeToDocument(parent._doc, c_source_doc, element._c_node) + + # stop at the end of the slice + if slicelength > 0: + slicelength -= 1 + for i in range(step): + c_node = next_element(c_node) + if c_node is NULL: + break + if c_node is NULL: + break + else: + # everything inserted + return 0 + + # append the remaining elements at the respective end + if left_to_right: + for element in elements: + assert element is not None, "Node must not be None" + _assertValidNode(element) + _appendChild(parent, element) + else: + for element in elements: + assert element is not None, "Node must not be None" + _assertValidNode(element) + _prependChild(parent, element) + + return 0 + + +cdef int _linkChild(xmlNode* c_parent, xmlNode* c_node) except -1: + """Adaptation of 'xmlAddChild()' that deep-fix the document links iteratively. + """ + assert _isElement(c_node) + c_node.parent = c_parent + if c_parent.children is NULL: + c_parent.children = c_parent.last = c_node + else: + c_node.prev = c_parent.last + c_parent.last.next = c_node + c_parent.last = c_node + + _setTreeDoc(c_node, c_parent.doc) + return 0 + + +cdef int _appendChild(_Element parent, _Element child) except -1: + """Append a new child to a parent element. + """ + c_node = child._c_node + c_source_doc = c_node.doc + # prevent cycles + if _isAncestorOrSame(c_node, parent._c_node): + raise ValueError("cannot append parent to itself") + # store possible text node + c_next = c_node.next + # move node itself + tree.xmlUnlinkNode(c_node) + # do not call xmlAddChild() here since it would deep-traverse the tree + _linkChild(parent._c_node, c_node) + _moveTail(c_next, c_node) + # uh oh, elements may be pointing to different doc when + # parent element has moved; change them too.. + moveNodeToDocument(parent._doc, c_source_doc, c_node) + return 0 + +cdef int _prependChild(_Element parent, _Element child) except -1: + """Prepend a new child to a parent element. + """ + c_node = child._c_node + c_source_doc = c_node.doc + # prevent cycles + if _isAncestorOrSame(c_node, parent._c_node): + raise ValueError("cannot append parent to itself") + # store possible text node + c_next = c_node.next + # move node itself + c_child = _findChildForwards(parent._c_node, 0) + if c_child is NULL: + tree.xmlUnlinkNode(c_node) + # do not call xmlAddChild() here since it would deep-traverse the tree + _linkChild(parent._c_node, c_node) + else: + tree.xmlAddPrevSibling(c_child, c_node) + _moveTail(c_next, c_node) + # uh oh, elements may be pointing to different doc when + # parent element has moved; change them too.. + moveNodeToDocument(parent._doc, c_source_doc, c_node) + return 0 + +cdef int _appendSibling(_Element element, _Element sibling) except -1: + """Add a new sibling behind an element. + """ + return _addSibling(element, sibling, as_next=True) + +cdef int _prependSibling(_Element element, _Element sibling) except -1: + """Add a new sibling before an element. + """ + return _addSibling(element, sibling, as_next=False) + +cdef int _addSibling(_Element element, _Element sibling, bint as_next) except -1: + c_node = sibling._c_node + c_source_doc = c_node.doc + # prevent cycles + if _isAncestorOrSame(c_node, element._c_node): + if element._c_node is c_node: + return 0 # nothing to do + raise ValueError("cannot add ancestor as sibling, please break cycle first") + # store possible text node + c_next = c_node.next + # move node itself + if as_next: + # must insert after any tail text + c_next_node = _nextElement(element._c_node) + if c_next_node is NULL: + c_next_node = element._c_node + while c_next_node.next: + c_next_node = c_next_node.next + tree.xmlAddNextSibling(c_next_node, c_node) + else: + tree.xmlAddPrevSibling(c_next_node, c_node) + else: + tree.xmlAddPrevSibling(element._c_node, c_node) + _moveTail(c_next, c_node) + # uh oh, elements may be pointing to different doc when + # parent element has moved; change them too.. + moveNodeToDocument(element._doc, c_source_doc, c_node) + return 0 + +cdef inline bint isutf8(const_xmlChar* s) noexcept: + cdef xmlChar c = s[0] + while c != c'\0': + if c & 0x80: + return True + s += 1 + c = s[0] + return False + +cdef bint isutf8l(const_xmlChar* s, size_t length) noexcept: + """ + Search for non-ASCII characters in the string, knowing its length in advance. + """ + cdef unsigned int i + cdef unsigned long non_ascii_mask + cdef const unsigned long *lptr = s + + cdef const unsigned long *end = lptr + length // sizeof(unsigned long) + if length >= sizeof(non_ascii_mask): + # Build constant 0x80808080... mask (and let the C compiler fold it). + non_ascii_mask = 0 + for i in range(sizeof(non_ascii_mask) // 2): + non_ascii_mask = (non_ascii_mask << 16) | 0x8080 + + # Advance to long-aligned character before we start reading longs. + while (s) % sizeof(unsigned long) and s < end: + if s[0] & 0x80: + return True + s += 1 + + # Read one long at a time + lptr = s + while lptr < end: + if lptr[0] & non_ascii_mask: + return True + lptr += 1 + s = lptr + + while s < (end + length % sizeof(unsigned long)): + if s[0] & 0x80: + return True + s += 1 + + return False + +cdef int _is_valid_xml_ascii(bytes pystring) except -1: + """Check if a string is XML ascii content.""" + cdef signed char ch + # When ch is a *signed* char, non-ascii characters are negative integers + # and xmlIsChar_ch does not accept them. + for ch in pystring: + if not tree.xmlIsChar_ch(ch): + return 0 + return 1 + +cdef bint _is_valid_xml_utf8(bytes pystring) except -1: + """Check if a string is like valid UTF-8 XML content.""" + cdef const_xmlChar* s = _xcstr(pystring) + cdef const_xmlChar* c_end = s + len(pystring) + cdef unsigned long next3 = 0 + if s < c_end - 2: + next3 = (s[0] << 8) | (s[1]) + + while s < c_end - 2: + next3 = 0x00ffffff & ((next3 << 8) | s[2]) + if s[0] & 0x80: + # 0xefbfbe and 0xefbfbf are utf-8 encodings of + # forbidden characters \ufffe and \uffff + if next3 == 0x00efbfbe or next3 == 0x00efbfbf: + return 0 + # 0xeda080 and 0xedbfbf are utf-8 encodings of + # \ud800 and \udfff. Anything between them (inclusive) + # is forbidden, because they are surrogate blocks in utf-16. + if 0x00eda080 <= next3 <= 0x00edbfbf: + return 0 + elif not tree.xmlIsChar_ch(s[0]): + return 0 # invalid ascii char + s += 1 + + while s < c_end: + if not s[0] & 0x80 and not tree.xmlIsChar_ch(s[0]): + return 0 # invalid ascii char + s += 1 + + return 1 + +cdef inline unicode funicodeOrNone(const_xmlChar* s): + return funicode(s) if s is not NULL else None + +cdef inline unicode funicodeOrEmpty(const_xmlChar* s): + return funicode(s) if s is not NULL else '' + +cdef unicode funicode(const_xmlChar* s): + return s.decode('UTF-8') + +cdef bytes _utf8(object s): + """Test if a string is valid user input and encode it to UTF-8. + Reject all bytes/unicode input that contains non-XML characters. + Reject all bytes input that contains non-ASCII characters. + """ + cdef int valid + cdef bytes utf8_string + if isinstance(s, unicode): + utf8_string = (s).encode('utf8') + valid = _is_valid_xml_utf8(utf8_string) + elif isinstance(s, (bytes, bytearray)): + utf8_string = s if type(s) is bytes else bytes(s) + valid = _is_valid_xml_ascii(utf8_string) + else: + raise TypeError("Argument must be bytes or unicode, got '%.200s'" % type(s).__name__) + if not valid: + raise ValueError( + "All strings must be XML compatible: Unicode or ASCII, no NULL bytes or control characters") + return utf8_string + + +cdef bytes _utf8orNone(object s): + return _utf8(s) if s is not None else None + + +cdef enum: + NO_FILE_PATH = 0 + ABS_UNIX_FILE_PATH = 1 + ABS_WIN_FILE_PATH = 2 + REL_FILE_PATH = 3 + + +cdef bint _isFilePath(const_xmlChar* c_path) noexcept: + "simple heuristic to see if a path is a filename" + cdef xmlChar c + # test if it looks like an absolute Unix path or a Windows network path + if c_path[0] == c'/': + return ABS_UNIX_FILE_PATH + + # test if it looks like an absolute Windows path or URL + if c'a' <= c_path[0] <= c'z' or c'A' <= c_path[0] <= c'Z': + c_path += 1 + if c_path[0] == c':' and c_path[1] in b'\0\\': + return ABS_WIN_FILE_PATH # C: or C:\... + + # test if it looks like a URL with scheme:// + while c'a' <= c_path[0] <= c'z' or c'A' <= c_path[0] <= c'Z': + c_path += 1 + if c_path[0] == c':' and c_path[1] == c'/' and c_path[2] == c'/': + return NO_FILE_PATH + + # assume it's a relative path + return REL_FILE_PATH + + +cdef object _getFSPathOrObject(object obj): + """ + Get the __fspath__ attribute of an object if it exists. + Otherwise, the original object is returned. + """ + if _isString(obj): + return obj + try: + return python.PyOS_FSPath(obj) + except TypeError: + return obj + + +cdef object _encodeFilename(object filename): + """Make sure a filename is 8-bit encoded (or None). + """ + if filename is None: + return None + elif isinstance(filename, bytes): + return filename + elif isinstance(filename, unicode): + filename8 = (filename).encode('utf8') + if _isFilePath(filename8): + try: + return python.PyUnicode_AsEncodedString( + filename, _C_FILENAME_ENCODING, NULL) + except UnicodeEncodeError: + pass + return filename8 + else: + raise TypeError("Argument must be string or unicode.") + +cdef object _decodeFilename(const_xmlChar* c_path): + """Make the filename a unicode string if we are in Py3. + """ + return _decodeFilenameWithLength(c_path, tree.xmlStrlen(c_path)) + +cdef object _decodeFilenameWithLength(const_xmlChar* c_path, size_t c_len): + """Make the filename a unicode string if we are in Py3. + """ + if _isFilePath(c_path): + try: + return python.PyUnicode_Decode( + c_path, c_len, _C_FILENAME_ENCODING, NULL) + except UnicodeDecodeError: + pass + try: + return (c_path)[:c_len].decode('UTF-8') + except UnicodeDecodeError: + # this is a stupid fallback, but it might still work... + return (c_path)[:c_len].decode('latin-1', 'replace') + +cdef object _encodeFilenameUTF8(object filename): + """Recode filename as UTF-8. Tries ASCII, local filesystem encoding and + UTF-8 as source encoding. + """ + cdef char* c_filename + if filename is None: + return None + elif isinstance(filename, bytes): + if not isutf8l(filename, len(filename)): + # plain ASCII! + return filename + c_filename = _cstr(filename) + try: + # try to decode with default encoding + filename = python.PyUnicode_Decode( + c_filename, len(filename), + _C_FILENAME_ENCODING, NULL) + except UnicodeDecodeError as decode_exc: + try: + # try if it's proper UTF-8 + (filename).decode('utf8') + return filename + except UnicodeDecodeError: + raise decode_exc # otherwise re-raise original exception + if isinstance(filename, unicode): + return (filename).encode('utf8') + else: + raise TypeError("Argument must be string or unicode.") + +cdef tuple _getNsTag(tag): + """Given a tag, find namespace URI and tag name. + Return None for NS uri if no namespace URI provided. + """ + return __getNsTag(tag, 0) + +cdef tuple _getNsTagWithEmptyNs(tag): + """Given a tag, find namespace URI and tag name. Return None for NS uri + if no namespace URI provided, or the empty string if namespace + part is '{}'. + """ + return __getNsTag(tag, 1) + +cdef tuple __getNsTag(tag, bint empty_ns): + cdef char* c_tag + cdef char* c_ns_end + cdef Py_ssize_t taglen + cdef Py_ssize_t nslen + cdef bytes ns = None + # _isString() is much faster than isinstance() + if not _isString(tag) and isinstance(tag, QName): + tag = (tag).text + tag = _utf8(tag) + c_tag = _cstr(tag) + if c_tag[0] == c'{': + c_tag += 1 + c_ns_end = cstring_h.strchr(c_tag, c'}') + if c_ns_end is NULL: + raise ValueError, "Invalid tag name" + nslen = c_ns_end - c_tag + taglen = python.PyBytes_GET_SIZE(tag) - nslen - 2 + if taglen == 0: + raise ValueError, "Empty tag name" + if nslen > 0: + ns = c_tag[:nslen] + elif empty_ns: + ns = b'' + tag = c_ns_end[1:taglen+1] + elif python.PyBytes_GET_SIZE(tag) == 0: + raise ValueError, "Empty tag name" + return ns, tag + +cdef inline int _pyXmlNameIsValid(name_utf8): + return _xmlNameIsValid(_xcstr(name_utf8)) and b':' not in name_utf8 + +cdef inline int _pyHtmlNameIsValid(name_utf8): + return _htmlNameIsValid(_xcstr(name_utf8)) + +cdef inline int _xmlNameIsValid(const_xmlChar* c_name) noexcept: + return tree.xmlValidateNameValue(c_name) + +cdef int _htmlNameIsValid(const_xmlChar* c_name) noexcept: + if c_name is NULL or c_name[0] == c'\0': + return 0 + while c_name[0] != c'\0': + if c_name[0] in b'&<>/"\'\t\n\x0B\x0C\r ': + return 0 + c_name += 1 + return 1 + +cdef bint _characterReferenceIsValid(const_xmlChar* c_name) noexcept: + cdef bint is_hex + if c_name[0] == c'x': + c_name += 1 + is_hex = 1 + else: + is_hex = 0 + if c_name[0] == c'\0': + return 0 + while c_name[0] != c'\0': + if c_name[0] < c'0' or c_name[0] > c'9': + if not is_hex: + return 0 + if not (c'a' <= c_name[0] <= c'f'): + if not (c'A' <= c_name[0] <= c'F'): + return 0 + c_name += 1 + return 1 + +cdef int _tagValidOrRaise(tag_utf) except -1: + if not _pyXmlNameIsValid(tag_utf): + raise ValueError(f"Invalid tag name {(tag_utf).decode('utf8')!r}") + return 0 + +cdef int _htmlTagValidOrRaise(tag_utf) except -1: + if not _pyHtmlNameIsValid(tag_utf): + raise ValueError(f"Invalid HTML tag name {(tag_utf).decode('utf8')!r}") + return 0 + +cdef int _attributeValidOrRaise(name_utf) except -1: + if not _pyXmlNameIsValid(name_utf): + raise ValueError(f"Invalid attribute name {(name_utf).decode('utf8')!r}") + return 0 + +cdef int _prefixValidOrRaise(tag_utf) except -1: + if not _pyXmlNameIsValid(tag_utf): + raise ValueError(f"Invalid namespace prefix {(tag_utf).decode('utf8')!r}") + return 0 + +cdef int _uriValidOrRaise(uri_utf) except -1: + cdef uri.xmlURI* c_uri = uri.xmlParseURI(_cstr(uri_utf)) + if c_uri is NULL: + raise ValueError(f"Invalid namespace URI {(uri_utf).decode('utf8')!r}") + uri.xmlFreeURI(c_uri) + return 0 + +cdef inline unicode _namespacedName(xmlNode* c_node): + return _namespacedNameFromNsName(_getNs(c_node), c_node.name) + + +cdef unicode _namespacedNameFromNsName(const_xmlChar* c_href, const_xmlChar* c_name): + name = funicode(c_name) + if c_href is NULL: + return name + href = funicode(c_href) + return f"{{{href}}}{name}" + + +cdef _getFilenameForFile(source): + """Given a Python File or Gzip object, give filename back. + + Returns None if not a file object. + """ + # urllib2 provides a geturl() method + try: + return source.geturl() + except: + pass + # file instances have a name attribute + try: + filename = source.name + if _isString(filename): + return os_path_abspath(filename) + except: + pass + # gzip file instances have a filename attribute (before Py3k) + try: + filename = source.filename + if _isString(filename): + return os_path_abspath(filename) + except: + pass + # can't determine filename + return None diff --git a/venv/lib/python3.10/site-packages/lxml/builder.py b/venv/lib/python3.10/site-packages/lxml/builder.py new file mode 100644 index 0000000000000000000000000000000000000000..f5831fb34b7911eb1f420e41ea32484eebff5f85 --- /dev/null +++ b/venv/lib/python3.10/site-packages/lxml/builder.py @@ -0,0 +1,243 @@ +# cython: language_level=2 + +# +# Element generator factory by Fredrik Lundh. +# +# Source: +# http://online.effbot.org/2006_11_01_archive.htm#et-builder +# http://effbot.python-hosting.com/file/stuff/sandbox/elementlib/builder.py +# +# -------------------------------------------------------------------- +# The ElementTree toolkit is +# +# Copyright (c) 1999-2004 by Fredrik Lundh +# +# By obtaining, using, and/or copying this software and/or its +# associated documentation, you agree that you have read, understood, +# and will comply with the following terms and conditions: +# +# Permission to use, copy, modify, and distribute this software and +# its associated documentation for any purpose and without fee is +# hereby granted, provided that the above copyright notice appears in +# all copies, and that both that copyright notice and this permission +# notice appear in supporting documentation, and that the name of +# Secret Labs AB or the author not be used in advertising or publicity +# pertaining to distribution of the software without specific, written +# prior permission. +# +# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD +# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT- +# ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR +# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY +# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS +# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE +# OF THIS SOFTWARE. +# -------------------------------------------------------------------- + +""" +The ``E`` Element factory for generating XML documents. +""" + + +import lxml.etree as ET +_QName = ET.QName + +from functools import partial + +try: + from types import GenericAlias as _GenericAlias +except ImportError: + # Python 3.8 - we only need this as return value from "__class_getitem__" + def _GenericAlias(cls, item): + return f"{cls.__name__}[{item.__name__}]" + +try: + basestring +except NameError: + basestring = str + +try: + unicode +except NameError: + unicode = str + + +class ElementMaker: + """Element generator factory. + + Unlike the ordinary Element factory, the E factory allows you to pass in + more than just a tag and some optional attributes; you can also pass in + text and other elements. The text is added as either text or tail + attributes, and elements are inserted at the right spot. Some small + examples:: + + >>> from lxml import etree as ET + >>> from lxml.builder import E + + >>> ET.tostring(E("tag")) + '' + >>> ET.tostring(E("tag", "text")) + 'text' + >>> ET.tostring(E("tag", "text", key="value")) + 'text' + >>> ET.tostring(E("tag", E("subtag", "text"), "tail")) + 'texttail' + + For simple tags, the factory also allows you to write ``E.tag(...)`` instead + of ``E('tag', ...)``:: + + >>> ET.tostring(E.tag()) + '' + >>> ET.tostring(E.tag("text")) + 'text' + >>> ET.tostring(E.tag(E.subtag("text"), "tail")) + 'texttail' + + Here's a somewhat larger example; this shows how to generate HTML + documents, using a mix of prepared factory functions for inline elements, + nested ``E.tag`` calls, and embedded XHTML fragments:: + + # some common inline elements + A = E.a + I = E.i + B = E.b + + def CLASS(v): + # helper function, 'class' is a reserved word + return {'class': v} + + page = ( + E.html( + E.head( + E.title("This is a sample document") + ), + E.body( + E.h1("Hello!", CLASS("title")), + E.p("This is a paragraph with ", B("bold"), " text in it!"), + E.p("This is another paragraph, with a ", + A("link", href="http://www.python.org"), "."), + E.p("Here are some reserved characters: ."), + ET.XML("

And finally, here is an embedded XHTML fragment.

"), + ) + ) + ) + + print ET.tostring(page) + + Here's a prettyprinted version of the output from the above script:: + + + + This is a sample document + + +

Hello!

+

This is a paragraph with bold text in it!

+

This is another paragraph, with link.

+

Here are some reserved characters: <spam&egg>.

+

And finally, here is an embedded XHTML fragment.

+ + + + For namespace support, you can pass a namespace map (``nsmap``) + and/or a specific target ``namespace`` to the ElementMaker class:: + + >>> E = ElementMaker(namespace="http://my.ns/") + >>> print(ET.tostring( E.test )) + + + >>> E = ElementMaker(namespace="http://my.ns/", nsmap={'p':'http://my.ns/'}) + >>> print(ET.tostring( E.test )) + + """ + + def __init__(self, typemap=None, + namespace=None, nsmap=None, makeelement=None): + self._namespace = '{' + namespace + '}' if namespace is not None else None + self._nsmap = dict(nsmap) if nsmap else None + + assert makeelement is None or callable(makeelement) + self._makeelement = makeelement if makeelement is not None else ET.Element + + # initialize the default type map functions for this element factory + typemap = dict(typemap) if typemap else {} + + def add_text(elem, item): + try: + last_child = elem[-1] + except IndexError: + elem.text = (elem.text or "") + item + else: + last_child.tail = (last_child.tail or "") + item + + def add_cdata(elem, cdata): + if elem.text: + raise ValueError("Can't add a CDATA section. Element already has some text: %r" % elem.text) + elem.text = cdata + + if str not in typemap: + typemap[str] = add_text + if unicode not in typemap: + typemap[unicode] = add_text + if ET.CDATA not in typemap: + typemap[ET.CDATA] = add_cdata + + def add_dict(elem, item): + attrib = elem.attrib + for k, v in item.items(): + if isinstance(v, basestring): + attrib[k] = v + else: + attrib[k] = typemap[type(v)](None, v) + + if dict not in typemap: + typemap[dict] = add_dict + + self._typemap = typemap + + def __call__(self, tag, *children, **attrib): + typemap = self._typemap + + # We'll usually get a 'str', and the compiled type check is very fast. + if not isinstance(tag, str) and isinstance(tag, _QName): + # A QName is explicitly qualified, do not look at self._namespace. + tag = tag.text + elif self._namespace is not None and tag[0] != '{': + tag = self._namespace + tag + elem = self._makeelement(tag, nsmap=self._nsmap) + if attrib: + typemap[dict](elem, attrib) + + for item in children: + if callable(item): + item = item() + t = typemap.get(type(item)) + if t is None: + if ET.iselement(item): + elem.append(item) + continue + for basetype in type(item).__mro__: + # See if the typemap knows of any of this type's bases. + t = typemap.get(basetype) + if t is not None: + break + else: + raise TypeError("bad argument type: %s(%r)" % + (type(item).__name__, item)) + v = t(elem, item) + if v: + typemap.get(type(v))(elem, v) + + return elem + + def __getattr__(self, tag): + return partial(self, tag) + + # Allow subscripting ElementMaker in type annotions (PEP 560) + def __class_getitem__(cls, item): + return _GenericAlias(cls, item) + + +# create factory object +E = ElementMaker() diff --git a/venv/lib/python3.10/site-packages/lxml/classlookup.pxi b/venv/lib/python3.10/site-packages/lxml/classlookup.pxi new file mode 100644 index 0000000000000000000000000000000000000000..92d1d47a58657a7741d20f48cfe3525a66dbc722 --- /dev/null +++ b/venv/lib/python3.10/site-packages/lxml/classlookup.pxi @@ -0,0 +1,580 @@ +# Configurable Element class lookup + +################################################################################ +# Custom Element classes + +cdef public class ElementBase(_Element) [ type LxmlElementBaseType, + object LxmlElementBase ]: + """ElementBase(*children, attrib=None, nsmap=None, **_extra) + + The public Element class. All custom Element classes must inherit + from this one. To create an Element, use the `Element()` factory. + + BIG FAT WARNING: Subclasses *must not* override __init__ or + __new__ as it is absolutely undefined when these objects will be + created or destroyed. All persistent state of Elements must be + stored in the underlying XML. If you really need to initialize + the object after creation, you can implement an ``_init(self)`` + method that will be called directly after object creation. + + Subclasses of this class can be instantiated to create a new + Element. By default, the tag name will be the class name and the + namespace will be empty. You can modify this with the following + class attributes: + + * TAG - the tag name, possibly containing a namespace in Clark + notation + + * NAMESPACE - the default namespace URI, unless provided as part + of the TAG attribute. + + * HTML - flag if the class is an HTML tag, as opposed to an XML + tag. This only applies to un-namespaced tags and defaults to + false (i.e. XML). + + * PARSER - the parser that provides the configuration for the + newly created document. Providing an HTML parser here will + default to creating an HTML element. + + In user code, the latter three are commonly inherited in class + hierarchies that implement a common namespace. + """ + def __init__(self, *children, attrib=None, nsmap=None, **_extra): + """ElementBase(*children, attrib=None, nsmap=None, **_extra) + """ + cdef bint is_html = 0 + cdef _BaseParser parser + cdef _Element last_child + # don't use normal attribute access as it might be overridden + _getattr = object.__getattribute__ + try: + namespace = _utf8(_getattr(self, 'NAMESPACE')) + except AttributeError: + namespace = None + try: + ns, tag = _getNsTag(_getattr(self, 'TAG')) + if ns is not None: + namespace = ns + except AttributeError: + tag = _utf8(_getattr(_getattr(self, '__class__'), '__name__')) + if b'.' in tag: + tag = tag.split(b'.')[-1] + try: + parser = _getattr(self, 'PARSER') + except AttributeError: + parser = None + for child in children: + if isinstance(child, _Element): + parser = (<_Element>child)._doc._parser + break + if isinstance(parser, HTMLParser): + is_html = 1 + if namespace is None: + try: + is_html = _getattr(self, 'HTML') + except AttributeError: + pass + _initNewElement(self, is_html, tag, namespace, parser, + attrib, nsmap, _extra) + last_child = None + for child in children: + if _isString(child): + if last_child is None: + _setNodeText(self._c_node, + (_collectText(self._c_node.children) or '') + child) + else: + _setTailText(last_child._c_node, + (_collectText(last_child._c_node.next) or '') + child) + elif isinstance(child, _Element): + last_child = child + _appendChild(self, last_child) + elif isinstance(child, type) and issubclass(child, ElementBase): + last_child = child() + _appendChild(self, last_child) + else: + raise TypeError, f"Invalid child type: {type(child)!r}" + +cdef class CommentBase(_Comment): + """All custom Comment classes must inherit from this one. + + To create an XML Comment instance, use the ``Comment()`` factory. + + Subclasses *must not* override __init__ or __new__ as it is + absolutely undefined when these objects will be created or + destroyed. All persistent state of Comments must be stored in the + underlying XML. If you really need to initialize the object after + creation, you can implement an ``_init(self)`` method that will be + called after object creation. + """ + def __init__(self, text): + # copied from Comment() factory + cdef _Document doc + cdef xmlDoc* c_doc + if text is None: + text = b'' + else: + text = _utf8(text) + c_doc = _newXMLDoc() + doc = _documentFactory(c_doc, None) + self._c_node = _createComment(c_doc, _xcstr(text)) + if self._c_node is NULL: + raise MemoryError() + tree.xmlAddChild(c_doc, self._c_node) + _registerProxy(self, doc, self._c_node) + self._init() + +cdef class PIBase(_ProcessingInstruction): + """All custom Processing Instruction classes must inherit from this one. + + To create an XML ProcessingInstruction instance, use the ``PI()`` + factory. + + Subclasses *must not* override __init__ or __new__ as it is + absolutely undefined when these objects will be created or + destroyed. All persistent state of PIs must be stored in the + underlying XML. If you really need to initialize the object after + creation, you can implement an ``_init(self)`` method that will be + called after object creation. + """ + def __init__(self, target, text=None): + # copied from PI() factory + cdef _Document doc + cdef xmlDoc* c_doc + target = _utf8(target) + if text is None: + text = b'' + else: + text = _utf8(text) + c_doc = _newXMLDoc() + doc = _documentFactory(c_doc, None) + self._c_node = _createPI(c_doc, _xcstr(target), _xcstr(text)) + if self._c_node is NULL: + raise MemoryError() + tree.xmlAddChild(c_doc, self._c_node) + _registerProxy(self, doc, self._c_node) + self._init() + +cdef class EntityBase(_Entity): + """All custom Entity classes must inherit from this one. + + To create an XML Entity instance, use the ``Entity()`` factory. + + Subclasses *must not* override __init__ or __new__ as it is + absolutely undefined when these objects will be created or + destroyed. All persistent state of Entities must be stored in the + underlying XML. If you really need to initialize the object after + creation, you can implement an ``_init(self)`` method that will be + called after object creation. + """ + def __init__(self, name): + cdef _Document doc + cdef xmlDoc* c_doc + name_utf = _utf8(name) + c_name = _xcstr(name_utf) + if c_name[0] == c'#': + if not _characterReferenceIsValid(c_name + 1): + raise ValueError, f"Invalid character reference: '{name}'" + elif not _xmlNameIsValid(c_name): + raise ValueError, f"Invalid entity reference: '{name}'" + c_doc = _newXMLDoc() + doc = _documentFactory(c_doc, None) + self._c_node = _createEntity(c_doc, c_name) + if self._c_node is NULL: + raise MemoryError() + tree.xmlAddChild(c_doc, self._c_node) + _registerProxy(self, doc, self._c_node) + self._init() + + +cdef int _validateNodeClass(xmlNode* c_node, cls) except -1: + if c_node.type == tree.XML_ELEMENT_NODE: + expected = ElementBase + elif c_node.type == tree.XML_COMMENT_NODE: + expected = CommentBase + elif c_node.type == tree.XML_ENTITY_REF_NODE: + expected = EntityBase + elif c_node.type == tree.XML_PI_NODE: + expected = PIBase + else: + assert False, f"Unknown node type: {c_node.type}" + + if not (isinstance(cls, type) and issubclass(cls, expected)): + raise TypeError( + f"result of class lookup must be subclass of {type(expected)}, got {type(cls)}") + return 0 + + +################################################################################ +# Element class lookup + +ctypedef public object (*_element_class_lookup_function)(object, _Document, xmlNode*) + +# class to store element class lookup functions +cdef public class ElementClassLookup [ type LxmlElementClassLookupType, + object LxmlElementClassLookup ]: + """ElementClassLookup(self) + Superclass of Element class lookups. + """ + cdef _element_class_lookup_function _lookup_function + + +cdef public class FallbackElementClassLookup(ElementClassLookup) \ + [ type LxmlFallbackElementClassLookupType, + object LxmlFallbackElementClassLookup ]: + """FallbackElementClassLookup(self, fallback=None) + + Superclass of Element class lookups with additional fallback. + """ + cdef readonly ElementClassLookup fallback + cdef _element_class_lookup_function _fallback_function + def __cinit__(self): + # fall back to default lookup + self._fallback_function = _lookupDefaultElementClass + + def __init__(self, ElementClassLookup fallback=None): + if fallback is not None: + self._setFallback(fallback) + else: + self._fallback_function = _lookupDefaultElementClass + + cdef void _setFallback(self, ElementClassLookup lookup): + """Sets the fallback scheme for this lookup method. + """ + self.fallback = lookup + self._fallback_function = lookup._lookup_function + if self._fallback_function is NULL: + self._fallback_function = _lookupDefaultElementClass + + def set_fallback(self, ElementClassLookup lookup not None): + """set_fallback(self, lookup) + + Sets the fallback scheme for this lookup method. + """ + self._setFallback(lookup) + +cdef inline object _callLookupFallback(FallbackElementClassLookup lookup, + _Document doc, xmlNode* c_node): + return lookup._fallback_function(lookup.fallback, doc, c_node) + + +################################################################################ +# default lookup scheme + +cdef class ElementDefaultClassLookup(ElementClassLookup): + """ElementDefaultClassLookup(self, element=None, comment=None, pi=None, entity=None) + Element class lookup scheme that always returns the default Element + class. + + The keyword arguments ``element``, ``comment``, ``pi`` and ``entity`` + accept the respective Element classes. + """ + cdef readonly object element_class + cdef readonly object comment_class + cdef readonly object pi_class + cdef readonly object entity_class + def __cinit__(self): + self._lookup_function = _lookupDefaultElementClass + + def __init__(self, element=None, comment=None, pi=None, entity=None): + if element is None: + self.element_class = _Element + elif issubclass(element, ElementBase): + self.element_class = element + else: + raise TypeError, "element class must be subclass of ElementBase" + + if comment is None: + self.comment_class = _Comment + elif issubclass(comment, CommentBase): + self.comment_class = comment + else: + raise TypeError, "comment class must be subclass of CommentBase" + + if entity is None: + self.entity_class = _Entity + elif issubclass(entity, EntityBase): + self.entity_class = entity + else: + raise TypeError, "Entity class must be subclass of EntityBase" + + if pi is None: + self.pi_class = None # special case, see below + elif issubclass(pi, PIBase): + self.pi_class = pi + else: + raise TypeError, "PI class must be subclass of PIBase" + +cdef object _lookupDefaultElementClass(state, _Document _doc, xmlNode* c_node): + "Trivial class lookup function that always returns the default class." + if c_node.type == tree.XML_ELEMENT_NODE: + if state is not None: + return (state).element_class + else: + return _Element + elif c_node.type == tree.XML_COMMENT_NODE: + if state is not None: + return (state).comment_class + else: + return _Comment + elif c_node.type == tree.XML_ENTITY_REF_NODE: + if state is not None: + return (state).entity_class + else: + return _Entity + elif c_node.type == tree.XML_PI_NODE: + if state is None or (state).pi_class is None: + # special case XSLT-PI + if c_node.name is not NULL and c_node.content is not NULL: + if tree.xmlStrcmp(c_node.name, "xml-stylesheet") == 0: + if tree.xmlStrstr(c_node.content, "text/xsl") is not NULL or \ + tree.xmlStrstr(c_node.content, "text/xml") is not NULL: + return _XSLTProcessingInstruction + return _ProcessingInstruction + else: + return (state).pi_class + else: + assert False, f"Unknown node type: {c_node.type}" + + +################################################################################ +# attribute based lookup scheme + +cdef class AttributeBasedElementClassLookup(FallbackElementClassLookup): + """AttributeBasedElementClassLookup(self, attribute_name, class_mapping, fallback=None) + Checks an attribute of an Element and looks up the value in a + class dictionary. + + Arguments: + - attribute name - '{ns}name' style string + - class mapping - Python dict mapping attribute values to Element classes + - fallback - optional fallback lookup mechanism + + A None key in the class mapping will be checked if the attribute is + missing. + """ + cdef object _class_mapping + cdef tuple _pytag + cdef const_xmlChar* _c_ns + cdef const_xmlChar* _c_name + def __cinit__(self): + self._lookup_function = _attribute_class_lookup + + def __init__(self, attribute_name, class_mapping, + ElementClassLookup fallback=None): + self._pytag = _getNsTag(attribute_name) + ns, name = self._pytag + if ns is None: + self._c_ns = NULL + else: + self._c_ns = _xcstr(ns) + self._c_name = _xcstr(name) + self._class_mapping = dict(class_mapping) + + FallbackElementClassLookup.__init__(self, fallback) + +cdef object _attribute_class_lookup(state, _Document doc, xmlNode* c_node): + cdef AttributeBasedElementClassLookup lookup + cdef python.PyObject* dict_result + + lookup = state + if c_node.type == tree.XML_ELEMENT_NODE: + value = _attributeValueFromNsName( + c_node, lookup._c_ns, lookup._c_name) + dict_result = python.PyDict_GetItem(lookup._class_mapping, value) + if dict_result is not NULL: + cls = dict_result + _validateNodeClass(c_node, cls) + return cls + return _callLookupFallback(lookup, doc, c_node) + + +################################################################################ +# per-parser lookup scheme + +cdef class ParserBasedElementClassLookup(FallbackElementClassLookup): + """ParserBasedElementClassLookup(self, fallback=None) + Element class lookup based on the XML parser. + """ + def __cinit__(self): + self._lookup_function = _parser_class_lookup + +cdef object _parser_class_lookup(state, _Document doc, xmlNode* c_node): + if doc._parser._class_lookup is not None: + return doc._parser._class_lookup._lookup_function( + doc._parser._class_lookup, doc, c_node) + return _callLookupFallback(state, doc, c_node) + + +################################################################################ +# custom class lookup based on node type, namespace, name + +cdef class CustomElementClassLookup(FallbackElementClassLookup): + """CustomElementClassLookup(self, fallback=None) + Element class lookup based on a subclass method. + + You can inherit from this class and override the method:: + + lookup(self, type, doc, namespace, name) + + to lookup the element class for a node. Arguments of the method: + * type: one of 'element', 'comment', 'PI', 'entity' + * doc: document that the node is in + * namespace: namespace URI of the node (or None for comments/PIs/entities) + * name: name of the element/entity, None for comments, target for PIs + + If you return None from this method, the fallback will be called. + """ + def __cinit__(self): + self._lookup_function = _custom_class_lookup + + def lookup(self, type, doc, namespace, name): + "lookup(self, type, doc, namespace, name)" + return None + +cdef object _custom_class_lookup(state, _Document doc, xmlNode* c_node): + cdef CustomElementClassLookup lookup + + lookup = state + + if c_node.type == tree.XML_ELEMENT_NODE: + element_type = "element" + elif c_node.type == tree.XML_COMMENT_NODE: + element_type = "comment" + elif c_node.type == tree.XML_PI_NODE: + element_type = "PI" + elif c_node.type == tree.XML_ENTITY_REF_NODE: + element_type = "entity" + else: + element_type = "element" + if c_node.name is NULL: + name = None + else: + name = funicode(c_node.name) + c_str = tree._getNs(c_node) + ns = funicode(c_str) if c_str is not NULL else None + + cls = lookup.lookup(element_type, doc, ns, name) + if cls is not None: + _validateNodeClass(c_node, cls) + return cls + return _callLookupFallback(lookup, doc, c_node) + + +################################################################################ +# read-only tree based class lookup + +cdef class PythonElementClassLookup(FallbackElementClassLookup): + """PythonElementClassLookup(self, fallback=None) + Element class lookup based on a subclass method. + + This class lookup scheme allows access to the entire XML tree in + read-only mode. To use it, re-implement the ``lookup(self, doc, + root)`` method in a subclass:: + + from lxml import etree, pyclasslookup + + class MyElementClass(etree.ElementBase): + honkey = True + + class MyLookup(pyclasslookup.PythonElementClassLookup): + def lookup(self, doc, root): + if root.tag == "sometag": + return MyElementClass + else: + for child in root: + if child.tag == "someothertag": + return MyElementClass + # delegate to default + return None + + If you return None from this method, the fallback will be called. + + The first argument is the opaque document instance that contains + the Element. The second argument is a lightweight Element proxy + implementation that is only valid during the lookup. Do not try + to keep a reference to it. Once the lookup is done, the proxy + will be invalid. + + Also, you cannot wrap such a read-only Element in an ElementTree, + and you must take care not to keep a reference to them outside of + the `lookup()` method. + + Note that the API of the Element objects is not complete. It is + purely read-only and does not support all features of the normal + `lxml.etree` API (such as XPath, extended slicing or some + iteration methods). + + See https://lxml.de/element_classes.html + """ + def __cinit__(self): + self._lookup_function = _python_class_lookup + + def lookup(self, doc, element): + """lookup(self, doc, element) + + Override this method to implement your own lookup scheme. + """ + return None + +cdef object _python_class_lookup(state, _Document doc, tree.xmlNode* c_node): + cdef PythonElementClassLookup lookup + cdef _ReadOnlyProxy proxy + lookup = state + + proxy = _newReadOnlyProxy(None, c_node) + cls = lookup.lookup(doc, proxy) + _freeReadOnlyProxies(proxy) + + if cls is not None: + _validateNodeClass(c_node, cls) + return cls + return _callLookupFallback(lookup, doc, c_node) + +################################################################################ +# Global setup + +cdef _element_class_lookup_function LOOKUP_ELEMENT_CLASS +cdef object ELEMENT_CLASS_LOOKUP_STATE + +cdef void _setElementClassLookupFunction( + _element_class_lookup_function function, object state): + global LOOKUP_ELEMENT_CLASS, ELEMENT_CLASS_LOOKUP_STATE + if function is NULL: + state = DEFAULT_ELEMENT_CLASS_LOOKUP + function = DEFAULT_ELEMENT_CLASS_LOOKUP._lookup_function + + ELEMENT_CLASS_LOOKUP_STATE = state + LOOKUP_ELEMENT_CLASS = function + +def set_element_class_lookup(ElementClassLookup lookup = None): + """set_element_class_lookup(lookup = None) + + Set the global element class lookup method. + + This defines the main entry point for looking up element implementations. + The standard implementation uses the :class:`ParserBasedElementClassLookup` + to delegate to different lookup schemes for each parser. + + .. warning:: + + This should only be changed by applications, not by library packages. + In most cases, parser specific lookups should be preferred, + which can be configured via + :meth:`~lxml.etree.XMLParser.set_element_class_lookup` + (and the same for HTML parsers). + + Globally replacing the element class lookup by something other than a + :class:`ParserBasedElementClassLookup` will prevent parser specific lookup + schemes from working. Several tools rely on parser specific lookups, + including :mod:`lxml.html` and :mod:`lxml.objectify`. + """ + if lookup is None or lookup._lookup_function is NULL: + _setElementClassLookupFunction(NULL, None) + else: + _setElementClassLookupFunction(lookup._lookup_function, lookup) + +# default setup: parser delegation +cdef ParserBasedElementClassLookup DEFAULT_ELEMENT_CLASS_LOOKUP +DEFAULT_ELEMENT_CLASS_LOOKUP = ParserBasedElementClassLookup() + +set_element_class_lookup(DEFAULT_ELEMENT_CLASS_LOOKUP) diff --git a/venv/lib/python3.10/site-packages/lxml/cleanup.pxi b/venv/lib/python3.10/site-packages/lxml/cleanup.pxi new file mode 100644 index 0000000000000000000000000000000000000000..8e266b33f0f3aef34f3448276abfb2cb8b1e4772 --- /dev/null +++ b/venv/lib/python3.10/site-packages/lxml/cleanup.pxi @@ -0,0 +1,215 @@ +# functions for tree cleanup and removing elements from subtrees + +def cleanup_namespaces(tree_or_element, top_nsmap=None, keep_ns_prefixes=None): + """cleanup_namespaces(tree_or_element, top_nsmap=None, keep_ns_prefixes=None) + + Remove all namespace declarations from a subtree that are not used + by any of the elements or attributes in that tree. + + If a 'top_nsmap' is provided, it must be a mapping from prefixes + to namespace URIs. These namespaces will be declared on the top + element of the subtree before running the cleanup, which allows + moving namespace declarations to the top of the tree. + + If a 'keep_ns_prefixes' is provided, it must be a list of prefixes. + These prefixes will not be removed as part of the cleanup. + """ + element = _rootNodeOrRaise(tree_or_element) + c_element = element._c_node + + if top_nsmap: + doc = element._doc + # declare namespaces from nsmap, then apply them to the subtree + _setNodeNamespaces(c_element, doc, None, top_nsmap) + moveNodeToDocument(doc, c_element.doc, c_element) + + keep_ns_prefixes = ( + set([_utf8(prefix) for prefix in keep_ns_prefixes]) + if keep_ns_prefixes else None) + + _removeUnusedNamespaceDeclarations(c_element, keep_ns_prefixes) + + +def strip_attributes(tree_or_element, *attribute_names): + """strip_attributes(tree_or_element, *attribute_names) + + Delete all attributes with the provided attribute names from an + Element (or ElementTree) and its descendants. + + Attribute names can contain wildcards as in `_Element.iter`. + + Example usage:: + + strip_attributes(root_element, + 'simpleattr', + '{http://some/ns}attrname', + '{http://other/ns}*') + """ + cdef _MultiTagMatcher matcher + element = _rootNodeOrRaise(tree_or_element) + if not attribute_names: + return + + matcher = _MultiTagMatcher.__new__(_MultiTagMatcher, attribute_names) + matcher.cacheTags(element._doc) + if matcher.rejectsAllAttributes(): + return + _strip_attributes(element._c_node, matcher) + + +cdef _strip_attributes(xmlNode* c_node, _MultiTagMatcher matcher): + cdef xmlAttr* c_attr + cdef xmlAttr* c_next_attr + tree.BEGIN_FOR_EACH_ELEMENT_FROM(c_node, c_node, 1) + if c_node.type == tree.XML_ELEMENT_NODE: + c_attr = c_node.properties + while c_attr is not NULL: + c_next_attr = c_attr.next + if matcher.matchesAttribute(c_attr): + tree.xmlRemoveProp(c_attr) + c_attr = c_next_attr + tree.END_FOR_EACH_ELEMENT_FROM(c_node) + + +def strip_elements(tree_or_element, *tag_names, bint with_tail=True): + """strip_elements(tree_or_element, *tag_names, with_tail=True) + + Delete all elements with the provided tag names from a tree or + subtree. This will remove the elements and their entire subtree, + including all their attributes, text content and descendants. It + will also remove the tail text of the element unless you + explicitly set the ``with_tail`` keyword argument option to False. + + Tag names can contain wildcards as in `_Element.iter`. + + Note that this will not delete the element (or ElementTree root + element) that you passed even if it matches. It will only treat + its descendants. If you want to include the root element, check + its tag name directly before even calling this function. + + Example usage:: + + strip_elements(some_element, + 'simpletagname', # non-namespaced tag + '{http://some/ns}tagname', # namespaced tag + '{http://some/other/ns}*' # any tag from a namespace + lxml.etree.Comment # comments + ) + """ + cdef _MultiTagMatcher matcher + doc = _documentOrRaise(tree_or_element) + element = _rootNodeOrRaise(tree_or_element) + if not tag_names: + return + + matcher = _MultiTagMatcher.__new__(_MultiTagMatcher, tag_names) + matcher.cacheTags(doc) + if matcher.rejectsAll(): + return + + if isinstance(tree_or_element, _ElementTree): + # include PIs and comments next to the root node + if matcher.matchesType(tree.XML_COMMENT_NODE): + _removeSiblings(element._c_node, tree.XML_COMMENT_NODE, with_tail) + if matcher.matchesType(tree.XML_PI_NODE): + _removeSiblings(element._c_node, tree.XML_PI_NODE, with_tail) + _strip_elements(doc, element._c_node, matcher, with_tail) + +cdef _strip_elements(_Document doc, xmlNode* c_node, _MultiTagMatcher matcher, + bint with_tail): + cdef xmlNode* c_child + cdef xmlNode* c_next + + tree.BEGIN_FOR_EACH_ELEMENT_FROM(c_node, c_node, 1) + if c_node.type == tree.XML_ELEMENT_NODE: + # we run through the children here to prevent any problems + # with the tree iteration which would occur if we unlinked the + # c_node itself + c_child = _findChildForwards(c_node, 0) + while c_child is not NULL: + c_next = _nextElement(c_child) + if matcher.matches(c_child): + if c_child.type == tree.XML_ELEMENT_NODE: + if not with_tail: + tree.xmlUnlinkNode(c_child) + _removeNode(doc, c_child) + else: + if with_tail: + _removeText(c_child.next) + tree.xmlUnlinkNode(c_child) + attemptDeallocation(c_child) + c_child = c_next + tree.END_FOR_EACH_ELEMENT_FROM(c_node) + + +def strip_tags(tree_or_element, *tag_names): + """strip_tags(tree_or_element, *tag_names) + + Delete all elements with the provided tag names from a tree or + subtree. This will remove the elements and their attributes, but + *not* their text/tail content or descendants. Instead, it will + merge the text content and children of the element into its + parent. + + Tag names can contain wildcards as in `_Element.iter`. + + Note that this will not delete the element (or ElementTree root + element) that you passed even if it matches. It will only treat + its descendants. + + Example usage:: + + strip_tags(some_element, + 'simpletagname', # non-namespaced tag + '{http://some/ns}tagname', # namespaced tag + '{http://some/other/ns}*' # any tag from a namespace + Comment # comments (including their text!) + ) + """ + cdef _MultiTagMatcher matcher + doc = _documentOrRaise(tree_or_element) + element = _rootNodeOrRaise(tree_or_element) + if not tag_names: + return + + matcher = _MultiTagMatcher.__new__(_MultiTagMatcher, tag_names) + matcher.cacheTags(doc) + if matcher.rejectsAll(): + return + + if isinstance(tree_or_element, _ElementTree): + # include PIs and comments next to the root node + if matcher.matchesType(tree.XML_COMMENT_NODE): + _removeSiblings(element._c_node, tree.XML_COMMENT_NODE, 0) + if matcher.matchesType(tree.XML_PI_NODE): + _removeSiblings(element._c_node, tree.XML_PI_NODE, 0) + _strip_tags(doc, element._c_node, matcher) + +cdef _strip_tags(_Document doc, xmlNode* c_node, _MultiTagMatcher matcher): + cdef xmlNode* c_child + cdef xmlNode* c_next + + tree.BEGIN_FOR_EACH_ELEMENT_FROM(c_node, c_node, 1) + if c_node.type == tree.XML_ELEMENT_NODE: + # we run through the children here to prevent any problems + # with the tree iteration which would occur if we unlinked the + # c_node itself + c_child = _findChildForwards(c_node, 0) + while c_child is not NULL: + if not matcher.matches(c_child): + c_child = _nextElement(c_child) + continue + if c_child.type == tree.XML_ELEMENT_NODE: + c_next = _findChildForwards(c_child, 0) or _nextElement(c_child) + _replaceNodeByChildren(doc, c_child) + if not attemptDeallocation(c_child): + if c_child.nsDef is not NULL: + # make namespaces absolute + moveNodeToDocument(doc, doc._c_doc, c_child) + c_child = c_next + else: + c_next = _nextElement(c_child) + tree.xmlUnlinkNode(c_child) + attemptDeallocation(c_child) + c_child = c_next + tree.END_FOR_EACH_ELEMENT_FROM(c_node) diff --git a/venv/lib/python3.10/site-packages/lxml/cssselect.py b/venv/lib/python3.10/site-packages/lxml/cssselect.py new file mode 100644 index 0000000000000000000000000000000000000000..54cd75ac9bfecdec7ea81e91b0840c6edd401515 --- /dev/null +++ b/venv/lib/python3.10/site-packages/lxml/cssselect.py @@ -0,0 +1,101 @@ +"""CSS Selectors based on XPath. + +This module supports selecting XML/HTML tags based on CSS selectors. +See the `CSSSelector` class for details. + +This is a thin wrapper around cssselect 0.7 or later. +""" + + +from . import etree +try: + import cssselect as external_cssselect +except ImportError: + raise ImportError( + 'cssselect does not seem to be installed. ' + 'See https://pypi.org/project/cssselect/') + + +SelectorSyntaxError = external_cssselect.SelectorSyntaxError +ExpressionError = external_cssselect.ExpressionError +SelectorError = external_cssselect.SelectorError + + +__all__ = ['SelectorSyntaxError', 'ExpressionError', 'SelectorError', + 'CSSSelector'] + + +class LxmlTranslator(external_cssselect.GenericTranslator): + """ + A custom CSS selector to XPath translator with lxml-specific extensions. + """ + def xpath_contains_function(self, xpath, function): + # Defined there, removed in later drafts: + # http://www.w3.org/TR/2001/CR-css3-selectors-20011113/#content-selectors + if function.argument_types() not in (['STRING'], ['IDENT']): + raise ExpressionError( + "Expected a single string or ident for :contains(), got %r" + % function.arguments) + value = function.arguments[0].value + return xpath.add_condition( + 'contains(__lxml_internal_css:lower-case(string(.)), %s)' + % self.xpath_literal(value.lower())) + + +class LxmlHTMLTranslator(LxmlTranslator, external_cssselect.HTMLTranslator): + """ + lxml extensions + HTML support. + """ + + +def _make_lower_case(context, s): + return s.lower() + +ns = etree.FunctionNamespace('http://codespeak.net/lxml/css/') +ns.prefix = '__lxml_internal_css' +ns['lower-case'] = _make_lower_case + + +class CSSSelector(etree.XPath): + """A CSS selector. + + Usage:: + + >>> from lxml import etree, cssselect + >>> select = cssselect.CSSSelector("a tag > child") + + >>> root = etree.XML("TEXT") + >>> [ el.tag for el in select(root) ] + ['child'] + + To use CSS namespaces, you need to pass a prefix-to-namespace + mapping as ``namespaces`` keyword argument:: + + >>> rdfns = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#' + >>> select_ns = cssselect.CSSSelector('root > rdf|Description', + ... namespaces={'rdf': rdfns}) + + >>> rdf = etree.XML(( + ... '' + ... 'blah' + ... '') % rdfns) + >>> [(el.tag, el.text) for el in select_ns(rdf)] + [('{http://www.w3.org/1999/02/22-rdf-syntax-ns#}Description', 'blah')] + + """ + def __init__(self, css, namespaces=None, translator='xml'): + if translator == 'xml': + translator = LxmlTranslator() + elif translator == 'html': + translator = LxmlHTMLTranslator() + elif translator == 'xhtml': + translator = LxmlHTMLTranslator(xhtml=True) + path = translator.css_to_xpath(css) + super().__init__(path, namespaces=namespaces) + self.css = css + + def __repr__(self): + return '<%s %x for %r>' % ( + self.__class__.__name__, + abs(id(self)), + self.css) diff --git a/venv/lib/python3.10/site-packages/lxml/debug.pxi b/venv/lib/python3.10/site-packages/lxml/debug.pxi new file mode 100644 index 0000000000000000000000000000000000000000..d728e841937db9c1f81949a5d0a2e5f1d0e1e594 --- /dev/null +++ b/venv/lib/python3.10/site-packages/lxml/debug.pxi @@ -0,0 +1,36 @@ +@cython.final +@cython.internal +cdef class _MemDebug: + """Debugging support for the memory allocation in libxml2. + """ + def bytes_used(self): + """bytes_used(self) + + Returns the total amount of memory (in bytes) currently used by libxml2. + Note that libxml2 constrains this value to a C int, which limits + the accuracy on 64 bit systems. + """ + return tree.xmlMemUsed() + + def blocks_used(self): + """blocks_used(self) + + Returns the total number of memory blocks currently allocated by libxml2. + Note that libxml2 constrains this value to a C int, which limits + the accuracy on 64 bit systems. + """ + return tree.xmlMemBlocks() + + def dict_size(self): + """dict_size(self) + + Returns the current size of the global name dictionary used by libxml2 + for the current thread. Each thread has its own dictionary. + """ + c_dict = __GLOBAL_PARSER_CONTEXT._getThreadDict(NULL) + if c_dict is NULL: + raise MemoryError() + return tree.xmlDictSize(c_dict) + + +memory_debugger = _MemDebug() diff --git a/venv/lib/python3.10/site-packages/lxml/docloader.pxi b/venv/lib/python3.10/site-packages/lxml/docloader.pxi new file mode 100644 index 0000000000000000000000000000000000000000..7b38f43838592445d2618440b178bd9c8557073c --- /dev/null +++ b/venv/lib/python3.10/site-packages/lxml/docloader.pxi @@ -0,0 +1,178 @@ +# Custom resolver API + +ctypedef enum _InputDocumentDataType: + PARSER_DATA_INVALID + PARSER_DATA_EMPTY + PARSER_DATA_STRING + PARSER_DATA_FILENAME + PARSER_DATA_FILE + +@cython.final +@cython.internal +cdef class _InputDocument: + cdef _InputDocumentDataType _type + cdef bytes _data_bytes + cdef object _filename + cdef object _file + cdef bint _close_file + + def __cinit__(self): + self._type = PARSER_DATA_INVALID + + +cdef class Resolver: + "This is the base class of all resolvers." + def resolve(self, system_url, public_id, context): + """resolve(self, system_url, public_id, context) + + Override this method to resolve an external source by + ``system_url`` and ``public_id``. The third argument is an + opaque context object. + + Return the result of one of the ``resolve_*()`` methods. + """ + return None + + def resolve_empty(self, context): + """resolve_empty(self, context) + + Return an empty input document. + + Pass context as parameter. + """ + cdef _InputDocument doc_ref + doc_ref = _InputDocument() + doc_ref._type = PARSER_DATA_EMPTY + return doc_ref + + def resolve_string(self, string, context, *, base_url=None): + """resolve_string(self, string, context, base_url=None) + + Return a parsable string as input document. + + Pass data string and context as parameters. You can pass the + source URL or filename through the ``base_url`` keyword + argument. + """ + cdef _InputDocument doc_ref + if isinstance(string, unicode): + string = (string).encode('utf8') + elif not isinstance(string, bytes): + raise TypeError, "argument must be a byte string or unicode string" + doc_ref = _InputDocument() + doc_ref._type = PARSER_DATA_STRING + doc_ref._data_bytes = string + if base_url is not None: + doc_ref._filename = _encodeFilename(base_url) + return doc_ref + + def resolve_filename(self, filename, context): + """resolve_filename(self, filename, context) + + Return the name of a parsable file as input document. + + Pass filename and context as parameters. You can also pass a + URL with an HTTP, FTP or file target. + """ + cdef _InputDocument doc_ref + doc_ref = _InputDocument() + doc_ref._type = PARSER_DATA_FILENAME + doc_ref._filename = _encodeFilename(filename) + return doc_ref + + def resolve_file(self, f, context, *, base_url=None, bint close=True): + """resolve_file(self, f, context, base_url=None, close=True) + + Return an open file-like object as input document. + + Pass open file and context as parameters. You can pass the + base URL or filename of the file through the ``base_url`` + keyword argument. If the ``close`` flag is True (the + default), the file will be closed after reading. + + Note that using ``.resolve_filename()`` is more efficient, + especially in threaded environments. + """ + cdef _InputDocument doc_ref + try: + f.read + except AttributeError: + raise TypeError, "Argument is not a file-like object" + doc_ref = _InputDocument() + doc_ref._type = PARSER_DATA_FILE + if base_url is not None: + doc_ref._filename = _encodeFilename(base_url) + else: + doc_ref._filename = _getFilenameForFile(f) + doc_ref._close_file = close + doc_ref._file = f + return doc_ref + +@cython.final +@cython.internal +cdef class _ResolverRegistry: + cdef object _resolvers + cdef Resolver _default_resolver + def __cinit__(self, Resolver default_resolver=None): + self._resolvers = set() + self._default_resolver = default_resolver + + def add(self, Resolver resolver not None): + """add(self, resolver) + + Register a resolver. + + For each requested entity, the 'resolve' method of the resolver will + be called and the result will be passed to the parser. If this method + returns None, the request will be delegated to other resolvers or the + default resolver. The resolvers will be tested in an arbitrary order + until the first match is found. + """ + self._resolvers.add(resolver) + + def remove(self, resolver): + "remove(self, resolver)" + self._resolvers.discard(resolver) + + cdef _ResolverRegistry _copy(self): + cdef _ResolverRegistry registry + registry = _ResolverRegistry(self._default_resolver) + registry._resolvers = self._resolvers.copy() + return registry + + def copy(self): + "copy(self)" + return self._copy() + + def resolve(self, system_url, public_id, context): + "resolve(self, system_url, public_id, context)" + for resolver in self._resolvers: + result = resolver.resolve(system_url, public_id, context) + if result is not None: + return result + if self._default_resolver is None: + return None + return self._default_resolver.resolve(system_url, public_id, context) + + def __repr__(self): + return repr(self._resolvers) + + +@cython.internal +cdef class _ResolverContext(_ExceptionContext): + cdef _ResolverRegistry _resolvers + cdef _TempStore _storage + + cdef int clear(self) except -1: + _ExceptionContext.clear(self) + self._storage.clear() + return 0 + + +cdef _initResolverContext(_ResolverContext context, + _ResolverRegistry resolvers): + if resolvers is None: + context._resolvers = _ResolverRegistry() + else: + context._resolvers = resolvers + context._storage = _TempStore() diff --git a/venv/lib/python3.10/site-packages/lxml/doctestcompare.py b/venv/lib/python3.10/site-packages/lxml/doctestcompare.py new file mode 100644 index 0000000000000000000000000000000000000000..8099771de906a37ed007c779f152fe96f182060d --- /dev/null +++ b/venv/lib/python3.10/site-packages/lxml/doctestcompare.py @@ -0,0 +1,488 @@ +""" +lxml-based doctest output comparison. + +Note: normally, you should just import the `lxml.usedoctest` and +`lxml.html.usedoctest` modules from within a doctest, instead of this +one:: + + >>> import lxml.usedoctest # for XML output + + >>> import lxml.html.usedoctest # for HTML output + +To use this module directly, you must call ``lxmldoctest.install()``, +which will cause doctest to use this in all subsequent calls. + +This changes the way output is checked and comparisons are made for +XML or HTML-like content. + +XML or HTML content is noticed because the example starts with ``<`` +(it's HTML if it starts with ```` or include an ``any`` +attribute in the tag. An ``any`` tag matches any tag, while the +attribute matches any and all attributes. + +When a match fails, the reformatted example and gotten text is +displayed (indented), and a rough diff-like output is given. Anything +marked with ``+`` is in the output but wasn't supposed to be, and +similarly ``-`` means its in the example but wasn't in the output. + +You can disable parsing on one line with ``# doctest:+NOPARSE_MARKUP`` +""" + +from lxml import etree +import sys +import re +import doctest +try: + from html import escape as html_escape +except ImportError: + from cgi import escape as html_escape + +__all__ = ['PARSE_HTML', 'PARSE_XML', 'NOPARSE_MARKUP', 'LXMLOutputChecker', + 'LHTMLOutputChecker', 'install', 'temp_install'] + +PARSE_HTML = doctest.register_optionflag('PARSE_HTML') +PARSE_XML = doctest.register_optionflag('PARSE_XML') +NOPARSE_MARKUP = doctest.register_optionflag('NOPARSE_MARKUP') + +OutputChecker = doctest.OutputChecker + +def strip(v): + if v is None: + return None + else: + return v.strip() + +def norm_whitespace(v): + return _norm_whitespace_re.sub(' ', v) + +_html_parser = etree.HTMLParser(recover=False, remove_blank_text=True) + +def html_fromstring(html): + return etree.fromstring(html, _html_parser) + +# We use this to distinguish repr()s from elements: +_repr_re = re.compile(r'^<[^>]+ (at|object) ') +_norm_whitespace_re = re.compile(r'[ \t\n][ \t\n]+') + +class LXMLOutputChecker(OutputChecker): + + empty_tags = ( + 'param', 'img', 'area', 'br', 'basefont', 'input', + 'base', 'meta', 'link', 'col') + + def get_default_parser(self): + return etree.XML + + def check_output(self, want, got, optionflags): + alt_self = getattr(self, '_temp_override_self', None) + if alt_self is not None: + super_method = self._temp_call_super_check_output + self = alt_self + else: + super_method = OutputChecker.check_output + parser = self.get_parser(want, got, optionflags) + if not parser: + return super_method( + self, want, got, optionflags) + try: + want_doc = parser(want) + except etree.XMLSyntaxError: + return False + try: + got_doc = parser(got) + except etree.XMLSyntaxError: + return False + return self.compare_docs(want_doc, got_doc) + + def get_parser(self, want, got, optionflags): + parser = None + if NOPARSE_MARKUP & optionflags: + return None + if PARSE_HTML & optionflags: + parser = html_fromstring + elif PARSE_XML & optionflags: + parser = etree.XML + elif (want.strip().lower().startswith('' % el.tag + return '<%s %s>' % (el.tag, ' '.join(attrs)) + + def format_end_tag(self, el): + if isinstance(el, etree.CommentBase): + # FIXME: probably PIs should be handled specially too? + return '-->' + return '' % el.tag + + def collect_diff(self, want, got, html, indent): + parts = [] + if not len(want) and not len(got): + parts.append(' '*indent) + parts.append(self.collect_diff_tag(want, got)) + if not self.html_empty_tag(got, html): + parts.append(self.collect_diff_text(want.text, got.text)) + parts.append(self.collect_diff_end_tag(want, got)) + parts.append(self.collect_diff_text(want.tail, got.tail)) + parts.append('\n') + return ''.join(parts) + parts.append(' '*indent) + parts.append(self.collect_diff_tag(want, got)) + parts.append('\n') + if strip(want.text) or strip(got.text): + parts.append(' '*indent) + parts.append(self.collect_diff_text(want.text, got.text)) + parts.append('\n') + want_children = list(want) + got_children = list(got) + while want_children or got_children: + if not want_children: + parts.append(self.format_doc(got_children.pop(0), html, indent+2, '+')) + continue + if not got_children: + parts.append(self.format_doc(want_children.pop(0), html, indent+2, '-')) + continue + parts.append(self.collect_diff( + want_children.pop(0), got_children.pop(0), html, indent+2)) + parts.append(' '*indent) + parts.append(self.collect_diff_end_tag(want, got)) + parts.append('\n') + if strip(want.tail) or strip(got.tail): + parts.append(' '*indent) + parts.append(self.collect_diff_text(want.tail, got.tail)) + parts.append('\n') + return ''.join(parts) + + def collect_diff_tag(self, want, got): + if not self.tag_compare(want.tag, got.tag): + tag = '%s (got: %s)' % (want.tag, got.tag) + else: + tag = got.tag + attrs = [] + any = want.tag == 'any' or 'any' in want.attrib + for name, value in sorted(got.attrib.items()): + if name not in want.attrib and not any: + attrs.append('+%s="%s"' % (name, self.format_text(value, False))) + else: + if name in want.attrib: + text = self.collect_diff_text(want.attrib[name], value, False) + else: + text = self.format_text(value, False) + attrs.append('%s="%s"' % (name, text)) + if not any: + for name, value in sorted(want.attrib.items()): + if name in got.attrib: + continue + attrs.append('-%s="%s"' % (name, self.format_text(value, False))) + if attrs: + tag = '<%s %s>' % (tag, ' '.join(attrs)) + else: + tag = '<%s>' % tag + return tag + + def collect_diff_end_tag(self, want, got): + if want.tag != got.tag: + tag = '%s (got: %s)' % (want.tag, got.tag) + else: + tag = got.tag + return '' % tag + + def collect_diff_text(self, want, got, strip=True): + if self.text_compare(want, got, strip): + if not got: + return '' + return self.format_text(got, strip) + text = '%s (got: %s)' % (want, got) + return self.format_text(text, strip) + +class LHTMLOutputChecker(LXMLOutputChecker): + def get_default_parser(self): + return html_fromstring + +def install(html=False): + """ + Install doctestcompare for all future doctests. + + If html is true, then by default the HTML parser will be used; + otherwise the XML parser is used. + """ + if html: + doctest.OutputChecker = LHTMLOutputChecker + else: + doctest.OutputChecker = LXMLOutputChecker + +def temp_install(html=False, del_module=None): + """ + Use this *inside* a doctest to enable this checker for this + doctest only. + + If html is true, then by default the HTML parser will be used; + otherwise the XML parser is used. + """ + if html: + Checker = LHTMLOutputChecker + else: + Checker = LXMLOutputChecker + frame = _find_doctest_frame() + dt_self = frame.f_locals['self'] + checker = Checker() + old_checker = dt_self._checker + dt_self._checker = checker + # The unfortunate thing is that there is a local variable 'check' + # in the function that runs the doctests, that is a bound method + # into the output checker. We have to update that. We can't + # modify the frame, so we have to modify the object in place. The + # only way to do this is to actually change the func_code + # attribute of the method. We change it, and then wait for + # __record_outcome to be run, which signals the end of the __run + # method, at which point we restore the previous check_output + # implementation. + check_func = frame.f_locals['check'].__func__ + checker_check_func = checker.check_output.__func__ + # Because we can't patch up func_globals, this is the only global + # in check_output that we care about: + doctest.etree = etree + _RestoreChecker(dt_self, old_checker, checker, + check_func, checker_check_func, + del_module) + +class _RestoreChecker: + def __init__(self, dt_self, old_checker, new_checker, check_func, clone_func, + del_module): + self.dt_self = dt_self + self.checker = old_checker + self.checker._temp_call_super_check_output = self.call_super + self.checker._temp_override_self = new_checker + self.check_func = check_func + self.clone_func = clone_func + self.del_module = del_module + self.install_clone() + self.install_dt_self() + def install_clone(self): + self.func_code = self.check_func.__code__ + self.func_globals = self.check_func.__globals__ + self.check_func.__code__ = self.clone_func.__code__ + def uninstall_clone(self): + self.check_func.__code__ = self.func_code + def install_dt_self(self): + self.prev_func = self.dt_self._DocTestRunner__record_outcome + self.dt_self._DocTestRunner__record_outcome = self + def uninstall_dt_self(self): + self.dt_self._DocTestRunner__record_outcome = self.prev_func + def uninstall_module(self): + if self.del_module: + import sys + del sys.modules[self.del_module] + if '.' in self.del_module: + package, module = self.del_module.rsplit('.', 1) + package_mod = sys.modules[package] + delattr(package_mod, module) + def __call__(self, *args, **kw): + self.uninstall_clone() + self.uninstall_dt_self() + del self.checker._temp_override_self + del self.checker._temp_call_super_check_output + result = self.prev_func(*args, **kw) + self.uninstall_module() + return result + def call_super(self, *args, **kw): + self.uninstall_clone() + try: + return self.check_func(*args, **kw) + finally: + self.install_clone() + +def _find_doctest_frame(): + import sys + frame = sys._getframe(1) + while frame: + l = frame.f_locals + if 'BOOM' in l: + # Sign of doctest + return frame + frame = frame.f_back + raise LookupError( + "Could not find doctest (only use this function *inside* a doctest)") + +__test__ = { + 'basic': ''' + >>> temp_install() + >>> print """stuff""" + ... + >>> print """""" + + + + >>> print """blahblahblah""" # doctest: +NOPARSE_MARKUP, +ELLIPSIS + ...foo /> + '''} + +if __name__ == '__main__': + import doctest + doctest.testmod() + + diff --git a/venv/lib/python3.10/site-packages/lxml/dtd.pxi b/venv/lib/python3.10/site-packages/lxml/dtd.pxi new file mode 100644 index 0000000000000000000000000000000000000000..ee1b3d4750c7596e72bac0eaa905908b60dcb1e8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/lxml/dtd.pxi @@ -0,0 +1,479 @@ +# support for DTD validation +from lxml.includes cimport dtdvalid + +cdef class DTDError(LxmlError): + """Base class for DTD errors. + """ + +cdef class DTDParseError(DTDError): + """Error while parsing a DTD. + """ + +cdef class DTDValidateError(DTDError): + """Error while validating an XML document with a DTD. + """ + + +cdef inline int _assertValidDTDNode(node, void *c_node) except -1: + assert c_node is not NULL, "invalid DTD proxy at %s" % id(node) + + +@cython.final +@cython.internal +@cython.freelist(8) +cdef class _DTDElementContentDecl: + cdef DTD _dtd + cdef tree.xmlElementContent* _c_node + + def __repr__(self): + return "<%s.%s object name=%r type=%r occur=%r at 0x%x>" % (self.__class__.__module__, self.__class__.__name__, self.name, self.type, self.occur, id(self)) + + @property + def name(self): + _assertValidDTDNode(self, self._c_node) + return funicodeOrNone(self._c_node.name) + + @property + def type(self): + _assertValidDTDNode(self, self._c_node) + cdef int type = self._c_node.type + if type == tree.XML_ELEMENT_CONTENT_PCDATA: + return "pcdata" + elif type == tree.XML_ELEMENT_CONTENT_ELEMENT: + return "element" + elif type == tree.XML_ELEMENT_CONTENT_SEQ: + return "seq" + elif type == tree.XML_ELEMENT_CONTENT_OR: + return "or" + else: + return None + + @property + def occur(self): + _assertValidDTDNode(self, self._c_node) + cdef int occur = self._c_node.ocur + if occur == tree.XML_ELEMENT_CONTENT_ONCE: + return "once" + elif occur == tree.XML_ELEMENT_CONTENT_OPT: + return "opt" + elif occur == tree.XML_ELEMENT_CONTENT_MULT: + return "mult" + elif occur == tree.XML_ELEMENT_CONTENT_PLUS: + return "plus" + else: + return None + + @property + def left(self): + _assertValidDTDNode(self, self._c_node) + c1 = self._c_node.c1 + if c1: + node = <_DTDElementContentDecl>_DTDElementContentDecl.__new__(_DTDElementContentDecl) + node._dtd = self._dtd + node._c_node = c1 + return node + else: + return None + + @property + def right(self): + _assertValidDTDNode(self, self._c_node) + c2 = self._c_node.c2 + if c2: + node = <_DTDElementContentDecl>_DTDElementContentDecl.__new__(_DTDElementContentDecl) + node._dtd = self._dtd + node._c_node = c2 + return node + else: + return None + + +@cython.final +@cython.internal +@cython.freelist(8) +cdef class _DTDAttributeDecl: + cdef DTD _dtd + cdef tree.xmlAttribute* _c_node + + def __repr__(self): + return "<%s.%s object name=%r elemname=%r prefix=%r type=%r default=%r default_value=%r at 0x%x>" % (self.__class__.__module__, self.__class__.__name__, self.name, self.elemname, self.prefix, self.type, self.default, self.default_value, id(self)) + + @property + def name(self): + _assertValidDTDNode(self, self._c_node) + return funicodeOrNone(self._c_node.name) + + @property + def elemname(self): + _assertValidDTDNode(self, self._c_node) + return funicodeOrNone(self._c_node.elem) + + @property + def prefix(self): + _assertValidDTDNode(self, self._c_node) + return funicodeOrNone(self._c_node.prefix) + + @property + def type(self): + _assertValidDTDNode(self, self._c_node) + cdef int type = self._c_node.atype + if type == tree.XML_ATTRIBUTE_CDATA: + return "cdata" + elif type == tree.XML_ATTRIBUTE_ID: + return "id" + elif type == tree.XML_ATTRIBUTE_IDREF: + return "idref" + elif type == tree.XML_ATTRIBUTE_IDREFS: + return "idrefs" + elif type == tree.XML_ATTRIBUTE_ENTITY: + return "entity" + elif type == tree.XML_ATTRIBUTE_ENTITIES: + return "entities" + elif type == tree.XML_ATTRIBUTE_NMTOKEN: + return "nmtoken" + elif type == tree.XML_ATTRIBUTE_NMTOKENS: + return "nmtokens" + elif type == tree.XML_ATTRIBUTE_ENUMERATION: + return "enumeration" + elif type == tree.XML_ATTRIBUTE_NOTATION: + return "notation" + else: + return None + + @property + def default(self): + _assertValidDTDNode(self, self._c_node) + cdef int default = self._c_node.def_ + if default == tree.XML_ATTRIBUTE_NONE: + return "none" + elif default == tree.XML_ATTRIBUTE_REQUIRED: + return "required" + elif default == tree.XML_ATTRIBUTE_IMPLIED: + return "implied" + elif default == tree.XML_ATTRIBUTE_FIXED: + return "fixed" + else: + return None + + @property + def default_value(self): + _assertValidDTDNode(self, self._c_node) + return funicodeOrNone(self._c_node.defaultValue) + + def itervalues(self): + _assertValidDTDNode(self, self._c_node) + cdef tree.xmlEnumeration *c_node = self._c_node.tree + while c_node is not NULL: + yield funicode(c_node.name) + c_node = c_node.next + + def values(self): + return list(self.itervalues()) + + +@cython.final +@cython.internal +@cython.freelist(8) +cdef class _DTDElementDecl: + cdef DTD _dtd + cdef tree.xmlElement* _c_node + + def __repr__(self): + return "<%s.%s object name=%r prefix=%r type=%r at 0x%x>" % (self.__class__.__module__, self.__class__.__name__, self.name, self.prefix, self.type, id(self)) + + @property + def name(self): + _assertValidDTDNode(self, self._c_node) + return funicodeOrNone(self._c_node.name) + + @property + def prefix(self): + _assertValidDTDNode(self, self._c_node) + return funicodeOrNone(self._c_node.prefix) + + @property + def type(self): + _assertValidDTDNode(self, self._c_node) + cdef int type = self._c_node.etype + if type == tree.XML_ELEMENT_TYPE_UNDEFINED: + return "undefined" + elif type == tree.XML_ELEMENT_TYPE_EMPTY: + return "empty" + elif type == tree.XML_ELEMENT_TYPE_ANY: + return "any" + elif type == tree.XML_ELEMENT_TYPE_MIXED: + return "mixed" + elif type == tree.XML_ELEMENT_TYPE_ELEMENT: + return "element" + else: + return None + + @property + def content(self): + _assertValidDTDNode(self, self._c_node) + cdef tree.xmlElementContent *content = self._c_node.content + if content: + node = <_DTDElementContentDecl>_DTDElementContentDecl.__new__(_DTDElementContentDecl) + node._dtd = self._dtd + node._c_node = content + return node + else: + return None + + def iterattributes(self): + _assertValidDTDNode(self, self._c_node) + cdef tree.xmlAttribute *c_node = self._c_node.attributes + while c_node: + node = <_DTDAttributeDecl>_DTDAttributeDecl.__new__(_DTDAttributeDecl) + node._dtd = self._dtd + node._c_node = c_node + yield node + c_node = c_node.nexth + + def attributes(self): + return list(self.iterattributes()) + + +@cython.final +@cython.internal +@cython.freelist(8) +cdef class _DTDEntityDecl: + cdef DTD _dtd + cdef tree.xmlEntity* _c_node + def __repr__(self): + return "<%s.%s object name=%r at 0x%x>" % (self.__class__.__module__, self.__class__.__name__, self.name, id(self)) + + @property + def name(self): + _assertValidDTDNode(self, self._c_node) + return funicodeOrNone(self._c_node.name) + + @property + def orig(self): + _assertValidDTDNode(self, self._c_node) + return funicodeOrNone(self._c_node.orig) + + @property + def content(self): + _assertValidDTDNode(self, self._c_node) + return funicodeOrNone(self._c_node.content) + + @property + def system_url(self): + _assertValidDTDNode(self, self._c_node) + return funicodeOrNone(self._c_node.SystemID) + + +################################################################################ +# DTD + +cdef class DTD(_Validator): + """DTD(self, file=None, external_id=None) + A DTD validator. + + Can load from filesystem directly given a filename or file-like object. + Alternatively, pass the keyword parameter ``external_id`` to load from a + catalog. + """ + cdef tree.xmlDtd* _c_dtd + def __init__(self, file=None, *, external_id=None): + _Validator.__init__(self) + if file is not None: + file = _getFSPathOrObject(file) + if _isString(file): + file = _encodeFilename(file) + with self._error_log: + orig_loader = _register_document_loader() + self._c_dtd = xmlparser.xmlParseDTD(NULL, _xcstr(file)) + _reset_document_loader(orig_loader) + elif hasattr(file, 'read'): + orig_loader = _register_document_loader() + self._c_dtd = _parseDtdFromFilelike(file) + _reset_document_loader(orig_loader) + else: + raise DTDParseError, "file must be a filename, file-like or path-like object" + elif external_id is not None: + external_id_utf = _utf8(external_id) + with self._error_log: + orig_loader = _register_document_loader() + self._c_dtd = xmlparser.xmlParseDTD(external_id_utf, NULL) + _reset_document_loader(orig_loader) + else: + raise DTDParseError, "either filename or external ID required" + + if self._c_dtd is NULL: + raise DTDParseError( + self._error_log._buildExceptionMessage("error parsing DTD"), + self._error_log) + + @property + def name(self): + if self._c_dtd is NULL: + return None + return funicodeOrNone(self._c_dtd.name) + + @property + def external_id(self): + if self._c_dtd is NULL: + return None + return funicodeOrNone(self._c_dtd.ExternalID) + + @property + def system_url(self): + if self._c_dtd is NULL: + return None + return funicodeOrNone(self._c_dtd.SystemID) + + def iterelements(self): + cdef tree.xmlNode *c_node = self._c_dtd.children if self._c_dtd is not NULL else NULL + while c_node is not NULL: + if c_node.type == tree.XML_ELEMENT_DECL: + node = _DTDElementDecl() + node._dtd = self + node._c_node = c_node + yield node + c_node = c_node.next + + def elements(self): + return list(self.iterelements()) + + def iterentities(self): + cdef tree.xmlNode *c_node = self._c_dtd.children if self._c_dtd is not NULL else NULL + while c_node is not NULL: + if c_node.type == tree.XML_ENTITY_DECL: + node = _DTDEntityDecl() + node._dtd = self + node._c_node = c_node + yield node + c_node = c_node.next + + def entities(self): + return list(self.iterentities()) + + def __dealloc__(self): + tree.xmlFreeDtd(self._c_dtd) + + def __call__(self, etree): + """__call__(self, etree) + + Validate doc using the DTD. + + Returns true if the document is valid, false if not. + """ + cdef _Document doc + cdef _Element root_node + cdef xmlDoc* c_doc + cdef dtdvalid.xmlValidCtxt* valid_ctxt + cdef int ret = -1 + + assert self._c_dtd is not NULL, "DTD not initialised" + doc = _documentOrRaise(etree) + root_node = _rootNodeOrRaise(etree) + + valid_ctxt = dtdvalid.xmlNewValidCtxt() + if valid_ctxt is NULL: + raise DTDError("Failed to create validation context") + + # work around error reporting bug in libxml2 <= 2.9.1 (and later?) + # https://bugzilla.gnome.org/show_bug.cgi?id=724903 + valid_ctxt.error = _nullGenericErrorFunc + valid_ctxt.userData = NULL + + try: + with self._error_log: + c_doc = _fakeRootDoc(doc._c_doc, root_node._c_node) + ret = dtdvalid.xmlValidateDtd(valid_ctxt, c_doc, self._c_dtd) + _destroyFakeDoc(doc._c_doc, c_doc) + finally: + dtdvalid.xmlFreeValidCtxt(valid_ctxt) + + if ret == -1: + raise DTDValidateError("Internal error in DTD validation", + self._error_log) + return ret == 1 + + +cdef tree.xmlDtd* _parseDtdFromFilelike(file) except NULL: + cdef _ExceptionContext exc_context + cdef _FileReaderContext dtd_parser + cdef _ErrorLog error_log + cdef tree.xmlDtd* c_dtd = NULL + exc_context = _ExceptionContext() + dtd_parser = _FileReaderContext(file, exc_context, None) + error_log = _ErrorLog() + + with error_log: + c_dtd = dtd_parser._readDtd() + + exc_context._raise_if_stored() + if c_dtd is NULL: + raise DTDParseError("error parsing DTD", error_log) + return c_dtd + +cdef DTD _dtdFactory(tree.xmlDtd* c_dtd): + # do not run through DTD.__init__()! + cdef DTD dtd + if c_dtd is NULL: + return None + dtd = DTD.__new__(DTD) + dtd._c_dtd = _copyDtd(c_dtd) + _Validator.__init__(dtd) + return dtd + + +cdef tree.xmlDtd* _copyDtd(tree.xmlDtd* c_orig_dtd) except NULL: + """ + Copy a DTD. libxml2 (currently) fails to set up the element->attributes + links when copying DTDs, so we have to rebuild them here. + """ + c_dtd = tree.xmlCopyDtd(c_orig_dtd) + if not c_dtd: + raise MemoryError + cdef tree.xmlNode* c_node = c_dtd.children + while c_node: + if c_node.type == tree.XML_ATTRIBUTE_DECL: + _linkDtdAttribute(c_dtd, c_node) + c_node = c_node.next + return c_dtd + + +cdef void _linkDtdAttribute(tree.xmlDtd* c_dtd, tree.xmlAttribute* c_attr) noexcept: + """ + Create the link to the DTD attribute declaration from the corresponding + element declaration. + """ + c_elem = dtdvalid.xmlGetDtdElementDesc(c_dtd, c_attr.elem) + if not c_elem: + # no such element? something is wrong with the DTD ... + return + c_pos = c_elem.attributes + if not c_pos: + c_elem.attributes = c_attr + c_attr.nexth = NULL + return + # libxml2 keeps namespace declarations first, and we need to make + # sure we don't re-insert attributes that are already there + if _isDtdNsDecl(c_attr): + if not _isDtdNsDecl(c_pos): + c_elem.attributes = c_attr + c_attr.nexth = c_pos + return + while c_pos != c_attr and c_pos.nexth and _isDtdNsDecl(c_pos.nexth): + c_pos = c_pos.nexth + else: + # append at end + while c_pos != c_attr and c_pos.nexth: + c_pos = c_pos.nexth + if c_pos == c_attr: + return + c_attr.nexth = c_pos.nexth + c_pos.nexth = c_attr + + +cdef bint _isDtdNsDecl(tree.xmlAttribute* c_attr) noexcept: + if cstring_h.strcmp(c_attr.name, "xmlns") == 0: + return True + if (c_attr.prefix is not NULL and + cstring_h.strcmp(c_attr.prefix, "xmlns") == 0): + return True + return False diff --git a/venv/lib/python3.10/site-packages/lxml/etree.h b/venv/lib/python3.10/site-packages/lxml/etree.h new file mode 100644 index 0000000000000000000000000000000000000000..34f0efb119805677a83412a14cee6b48a05fec52 --- /dev/null +++ b/venv/lib/python3.10/site-packages/lxml/etree.h @@ -0,0 +1,244 @@ +/* Generated by Cython 3.1.2 */ + +#ifndef __PYX_HAVE__lxml__etree +#define __PYX_HAVE__lxml__etree + +#include "Python.h" +struct LxmlDocument; +struct LxmlElement; +struct LxmlElementTree; +struct LxmlElementTagMatcher; +struct LxmlElementIterator; +struct LxmlElementBase; +struct LxmlElementClassLookup; +struct LxmlFallbackElementClassLookup; + +/* "lxml/etree.pyx":451 + * + * # type of a function that steps from node to node + * ctypedef public xmlNode* (*_node_to_node_function)(xmlNode*) # <<<<<<<<<<<<<< + * + * +*/ +typedef xmlNode *(*_node_to_node_function)(xmlNode *); + +/* "lxml/etree.pyx":465 + * # Public Python API + * + * @cython.final # <<<<<<<<<<<<<< + * @cython.freelist(8) + * cdef public class _Document [ type LxmlDocumentType, object LxmlDocument ]: +*/ +struct LxmlDocument { + PyObject_HEAD + struct __pyx_vtabstruct_4lxml_5etree__Document *__pyx_vtab; + int _ns_counter; + PyObject *_prefix_tail; + xmlDoc *_c_doc; + struct __pyx_obj_4lxml_5etree__BaseParser *_parser; +}; + +/* "lxml/etree.pyx":817 + * + * + * @cython.no_gc_clear # <<<<<<<<<<<<<< + * cdef public class _Element [ type LxmlElementType, object LxmlElement ]: + * """Element class. +*/ +struct LxmlElement { + PyObject_HEAD + struct LxmlDocument *_doc; + xmlNode *_c_node; + PyObject *_tag; +}; + +/* "lxml/etree.pyx":1991 + * + * + * cdef public class _ElementTree [ type LxmlElementTreeType, # <<<<<<<<<<<<<< + * object LxmlElementTree ]: + * cdef _Document _doc +*/ +struct LxmlElementTree { + PyObject_HEAD + struct __pyx_vtabstruct_4lxml_5etree__ElementTree *__pyx_vtab; + struct LxmlDocument *_doc; + struct LxmlElement *_context_node; +}; + +/* "lxml/etree.pyx":2765 + * + * + * cdef public class _ElementTagMatcher [ object LxmlElementTagMatcher, # <<<<<<<<<<<<<< + * type LxmlElementTagMatcherType ]: + * """ +*/ +struct LxmlElementTagMatcher { + PyObject_HEAD + struct __pyx_vtabstruct_4lxml_5etree__ElementTagMatcher *__pyx_vtab; + PyObject *_pystrings; + int _node_type; + char *_href; + char *_name; +}; + +/* "lxml/etree.pyx":2796 + * self._name = NULL + * + * cdef public class _ElementIterator(_ElementTagMatcher) [ # <<<<<<<<<<<<<< + * object LxmlElementIterator, type LxmlElementIteratorType ]: + * """ +*/ +struct LxmlElementIterator { + struct LxmlElementTagMatcher __pyx_base; + struct LxmlElement *_node; + _node_to_node_function _next_element; +}; + +/* "src/lxml/classlookup.pxi":6 + * # Custom Element classes + * + * cdef public class ElementBase(_Element) [ type LxmlElementBaseType, # <<<<<<<<<<<<<< + * object LxmlElementBase ]: + * """ElementBase(*children, attrib=None, nsmap=None, **_extra) +*/ +struct LxmlElementBase { + struct LxmlElement __pyx_base; +}; + +/* "src/lxml/classlookup.pxi":210 + * # Element class lookup + * + * ctypedef public object (*_element_class_lookup_function)(object, _Document, xmlNode*) # <<<<<<<<<<<<<< + * + * # class to store element class lookup functions +*/ +typedef PyObject *(*_element_class_lookup_function)(PyObject *, struct LxmlDocument *, xmlNode *); + +/* "src/lxml/classlookup.pxi":213 + * + * # class to store element class lookup functions + * cdef public class ElementClassLookup [ type LxmlElementClassLookupType, # <<<<<<<<<<<<<< + * object LxmlElementClassLookup ]: + * """ElementClassLookup(self) +*/ +struct LxmlElementClassLookup { + PyObject_HEAD + _element_class_lookup_function _lookup_function; +}; + +/* "src/lxml/classlookup.pxi":221 + * + * + * cdef public class FallbackElementClassLookup(ElementClassLookup) \ # <<<<<<<<<<<<<< + * [ type LxmlFallbackElementClassLookupType, + * object LxmlFallbackElementClassLookup ]: +*/ +struct LxmlFallbackElementClassLookup { + struct LxmlElementClassLookup __pyx_base; + struct __pyx_vtabstruct_4lxml_5etree_FallbackElementClassLookup *__pyx_vtab; + struct LxmlElementClassLookup *fallback; + _element_class_lookup_function _fallback_function; +}; + +#ifndef __PYX_HAVE_API__lxml__etree + +#ifdef CYTHON_EXTERN_C + #undef __PYX_EXTERN_C + #define __PYX_EXTERN_C CYTHON_EXTERN_C +#elif defined(__PYX_EXTERN_C) + #ifdef _MSC_VER + #pragma message ("Please do not define the '__PYX_EXTERN_C' macro externally. Use 'CYTHON_EXTERN_C' instead.") + #else + #warning Please do not define the '__PYX_EXTERN_C' macro externally. Use 'CYTHON_EXTERN_C' instead. + #endif +#else + #ifdef __cplusplus + #define __PYX_EXTERN_C extern "C" + #else + #define __PYX_EXTERN_C extern + #endif +#endif + +#ifndef DL_IMPORT + #define DL_IMPORT(_T) _T +#endif + +__PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlDocumentType; +__PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlElementType; +__PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlElementTreeType; +__PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlElementTagMatcherType; +__PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlElementIteratorType; +__PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlElementBaseType; +__PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlElementClassLookupType; +__PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlFallbackElementClassLookupType; + +__PYX_EXTERN_C struct LxmlElement *deepcopyNodeToDocument(struct LxmlDocument *, xmlNode *); +__PYX_EXTERN_C struct LxmlElementTree *elementTreeFactory(struct LxmlElement *); +__PYX_EXTERN_C struct LxmlElementTree *newElementTree(struct LxmlElement *, PyObject *); +__PYX_EXTERN_C struct LxmlElementTree *adoptExternalDocument(xmlDoc *, PyObject *, int); +__PYX_EXTERN_C struct LxmlElement *elementFactory(struct LxmlDocument *, xmlNode *); +__PYX_EXTERN_C struct LxmlElement *makeElement(PyObject *, struct LxmlDocument *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *); +__PYX_EXTERN_C struct LxmlElement *makeSubElement(struct LxmlElement *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *); +__PYX_EXTERN_C void setElementClassLookupFunction(_element_class_lookup_function, PyObject *); +__PYX_EXTERN_C PyObject *lookupDefaultElementClass(PyObject *, PyObject *, xmlNode *); +__PYX_EXTERN_C PyObject *lookupNamespaceElementClass(PyObject *, PyObject *, xmlNode *); +__PYX_EXTERN_C PyObject *callLookupFallback(struct LxmlFallbackElementClassLookup *, struct LxmlDocument *, xmlNode *); +__PYX_EXTERN_C int tagMatches(xmlNode *, const xmlChar *, const xmlChar *); +__PYX_EXTERN_C struct LxmlDocument *documentOrRaise(PyObject *); +__PYX_EXTERN_C struct LxmlElement *rootNodeOrRaise(PyObject *); +__PYX_EXTERN_C int hasText(xmlNode *); +__PYX_EXTERN_C int hasTail(xmlNode *); +__PYX_EXTERN_C PyObject *textOf(xmlNode *); +__PYX_EXTERN_C PyObject *tailOf(xmlNode *); +__PYX_EXTERN_C int setNodeText(xmlNode *, PyObject *); +__PYX_EXTERN_C int setTailText(xmlNode *, PyObject *); +__PYX_EXTERN_C PyObject *attributeValue(xmlNode *, xmlAttr *); +__PYX_EXTERN_C PyObject *attributeValueFromNsName(xmlNode *, const xmlChar *, const xmlChar *); +__PYX_EXTERN_C PyObject *getAttributeValue(struct LxmlElement *, PyObject *, PyObject *); +__PYX_EXTERN_C PyObject *iterattributes(struct LxmlElement *, int); +__PYX_EXTERN_C PyObject *collectAttributes(xmlNode *, int); +__PYX_EXTERN_C int setAttributeValue(struct LxmlElement *, PyObject *, PyObject *); +__PYX_EXTERN_C int delAttribute(struct LxmlElement *, PyObject *); +__PYX_EXTERN_C int delAttributeFromNsName(xmlNode *, const xmlChar *, const xmlChar *); +__PYX_EXTERN_C int hasChild(xmlNode *); +__PYX_EXTERN_C xmlNode *findChild(xmlNode *, Py_ssize_t); +__PYX_EXTERN_C xmlNode *findChildForwards(xmlNode *, Py_ssize_t); +__PYX_EXTERN_C xmlNode *findChildBackwards(xmlNode *, Py_ssize_t); +__PYX_EXTERN_C xmlNode *nextElement(xmlNode *); +__PYX_EXTERN_C xmlNode *previousElement(xmlNode *); +__PYX_EXTERN_C void appendChild(struct LxmlElement *, struct LxmlElement *); +__PYX_EXTERN_C int appendChildToElement(struct LxmlElement *, struct LxmlElement *); +__PYX_EXTERN_C PyObject *pyunicode(const xmlChar *); +__PYX_EXTERN_C PyObject *utf8(PyObject *); +__PYX_EXTERN_C PyObject *getNsTag(PyObject *); +__PYX_EXTERN_C PyObject *getNsTagWithEmptyNs(PyObject *); +__PYX_EXTERN_C PyObject *namespacedName(xmlNode *); +__PYX_EXTERN_C PyObject *namespacedNameFromNsName(const xmlChar *, const xmlChar *); +__PYX_EXTERN_C void iteratorStoreNext(struct LxmlElementIterator *, struct LxmlElement *); +__PYX_EXTERN_C void initTagMatch(struct LxmlElementTagMatcher *, PyObject *); +__PYX_EXTERN_C xmlNs *findOrBuildNodeNsPrefix(struct LxmlDocument *, xmlNode *, const xmlChar *, const xmlChar *); + +#endif /* !__PYX_HAVE_API__lxml__etree */ + +/* WARNING: the interface of the module init function changed in CPython 3.5. */ +/* It now returns a PyModuleDef instance instead of a PyModule instance. */ + +/* WARNING: Use PyImport_AppendInittab("etree", PyInit_etree) instead of calling PyInit_etree directly from Python 3.5 */ +PyMODINIT_FUNC PyInit_etree(void); + +#if PY_VERSION_HEX >= 0x03050000 && (defined(__GNUC__) || defined(__clang__) || defined(_MSC_VER) || (defined(__cplusplus) && __cplusplus >= 201402L)) +#if defined(__cplusplus) && __cplusplus >= 201402L +[[deprecated("Use PyImport_AppendInittab(\"etree\", PyInit_etree) instead of calling PyInit_etree directly.")]] inline +#elif defined(__GNUC__) || defined(__clang__) +__attribute__ ((__deprecated__("Use PyImport_AppendInittab(\"etree\", PyInit_etree) instead of calling PyInit_etree directly."), __unused__)) __inline__ +#elif defined(_MSC_VER) +__declspec(deprecated("Use PyImport_AppendInittab(\"etree\", PyInit_etree) instead of calling PyInit_etree directly.")) __inline +#endif +static PyObject* __PYX_WARN_IF_PyInit_etree_INIT_CALLED(PyObject* res) { + return res; +} +#define PyInit_etree() __PYX_WARN_IF_PyInit_etree_INIT_CALLED(PyInit_etree()) +#endif + +#endif /* !__PYX_HAVE__lxml__etree */ diff --git a/venv/lib/python3.10/site-packages/lxml/etree.pyx b/venv/lib/python3.10/site-packages/lxml/etree.pyx new file mode 100644 index 0000000000000000000000000000000000000000..562d95ed167945504fd50182824340a5931c4b10 --- /dev/null +++ b/venv/lib/python3.10/site-packages/lxml/etree.pyx @@ -0,0 +1,3853 @@ +# cython: binding=True +# cython: auto_pickle=False +# cython: language_level=3 + +""" +The ``lxml.etree`` module implements the extended ElementTree API for XML. +""" + +__docformat__ = "restructuredtext en" + +__all__ = [ + 'AttributeBasedElementClassLookup', 'C14NError', 'C14NWriterTarget', 'CDATA', + 'Comment', 'CommentBase', 'CustomElementClassLookup', 'DEBUG', + 'DTD', 'DTDError', 'DTDParseError', 'DTDValidateError', + 'DocumentInvalid', 'ETCompatXMLParser', 'ETXPath', 'Element', + 'ElementBase', 'ElementClassLookup', 'ElementDefaultClassLookup', + 'ElementNamespaceClassLookup', 'ElementTree', 'Entity', 'EntityBase', + 'Error', 'ErrorDomains', 'ErrorLevels', 'ErrorTypes', 'Extension', + 'FallbackElementClassLookup', 'FunctionNamespace', 'HTML', 'HTMLParser', + 'ICONV_COMPILED_VERSION', + 'LIBXML_COMPILED_VERSION', 'LIBXML_VERSION', + 'LIBXML_FEATURES', + 'LIBXSLT_COMPILED_VERSION', 'LIBXSLT_VERSION', + 'LXML_VERSION', + 'LxmlError', 'LxmlRegistryError', 'LxmlSyntaxError', + 'NamespaceRegistryError', 'PI', 'PIBase', 'ParseError', + 'ParserBasedElementClassLookup', 'ParserError', 'ProcessingInstruction', + 'PyErrorLog', 'PythonElementClassLookup', 'QName', 'RelaxNG', + 'RelaxNGError', 'RelaxNGErrorTypes', 'RelaxNGParseError', + 'RelaxNGValidateError', 'Resolver', 'Schematron', 'SchematronError', + 'SchematronParseError', 'SchematronValidateError', 'SerialisationError', + 'SubElement', 'TreeBuilder', 'XInclude', 'XIncludeError', 'XML', + 'XMLDTDID', 'XMLID', 'XMLParser', 'XMLSchema', 'XMLSchemaError', + 'XMLSchemaParseError', 'XMLSchemaValidateError', 'XMLSyntaxError', + 'XMLTreeBuilder', 'XPath', 'XPathDocumentEvaluator', 'XPathError', + 'XPathEvalError', 'XPathEvaluator', 'XPathFunctionError', 'XPathResultError', + 'XPathSyntaxError', 'XSLT', 'XSLTAccessControl', 'XSLTApplyError', + 'XSLTError', 'XSLTExtension', 'XSLTExtensionError', 'XSLTParseError', + 'XSLTSaveError', 'canonicalize', + 'cleanup_namespaces', 'clear_error_log', 'dump', + 'fromstring', 'fromstringlist', 'get_default_parser', 'iselement', + 'iterparse', 'iterwalk', 'parse', 'parseid', 'register_namespace', + 'set_default_parser', 'set_element_class_lookup', 'strip_attributes', + 'strip_elements', 'strip_tags', 'tostring', 'tostringlist', 'tounicode', + 'use_global_python_log' + ] + +cimport cython + +from lxml cimport python +from lxml.includes cimport tree, config +from lxml.includes.tree cimport xmlDoc, xmlNode, xmlAttr, xmlNs, _isElement, _getNs +from lxml.includes.tree cimport const_xmlChar, xmlChar, _xcstr +from lxml.python cimport _cstr, _isString +from lxml.includes cimport xpath +from lxml.includes cimport c14n + +# Cython's standard declarations +cimport cpython.mem +cimport cpython.ref +from libc cimport limits, stdio, stdlib +from libc cimport string as cstring_h # not to be confused with stdlib 'string' +from libc.string cimport const_char + +cdef object os_path_abspath +from os.path import abspath as os_path_abspath + +cdef object BytesIO, StringIO +from io import BytesIO, StringIO + +cdef object OrderedDict +from collections import OrderedDict + +cdef object _elementpath +from lxml import _elementpath + +cdef object sys +import sys + +cdef object re +import re + +cdef object partial +from functools import partial + +cdef object islice +from itertools import islice + +cdef object ITER_EMPTY = iter(()) + +cdef object MutableMapping +from collections.abc import MutableMapping + +class _ImmutableMapping(MutableMapping): + def __getitem__(self, key): + raise KeyError, key + + def __setitem__(self, key, value): + raise KeyError, key + + def __delitem__(self, key): + raise KeyError, key + + def __contains__(self, key): + return False + + def __len__(self): + return 0 + + def __iter__(self): + return ITER_EMPTY + iterkeys = itervalues = iteritems = __iter__ + +cdef object IMMUTABLE_EMPTY_MAPPING = _ImmutableMapping() +del _ImmutableMapping + + +# the rules +# --------- +# any libxml C argument/variable is prefixed with c_ +# any non-public function/class is prefixed with an underscore +# instance creation is always through factories + +# what to do with libxml2/libxslt error messages? +# 0 : drop +# 1 : use log +DEF __DEBUG = 1 + +# maximum number of lines in the libxml2/xslt log if __DEBUG == 1 +DEF __MAX_LOG_SIZE = 100 + +# make the compiled-in debug state publicly available +DEBUG = __DEBUG + +# A struct to store a cached qualified tag name+href pair. +# While we can borrow the c_name from the document dict, +# PyPy requires us to store a Python reference for the +# namespace in order to keep the byte buffer alive. +cdef struct qname: + const_xmlChar* c_name + python.PyObject* href + +# initialize parser (and threading) +xmlparser.xmlInitParser() + +# global per-thread setup +tree.xmlThrDefIndentTreeOutput(1) +tree.xmlThrDefLineNumbersDefaultValue(1) + +_initThreadLogging() + +# filename encoding +cdef bytes _FILENAME_ENCODING = (sys.getfilesystemencoding() or sys.getdefaultencoding() or 'ascii').encode("UTF-8") +cdef char* _C_FILENAME_ENCODING = _cstr(_FILENAME_ENCODING) + +# set up some default namespace prefixes +cdef dict _DEFAULT_NAMESPACE_PREFIXES = { + b"http://www.w3.org/XML/1998/namespace": b'xml', + b"http://www.w3.org/1999/xhtml": b"html", + b"http://www.w3.org/1999/XSL/Transform": b"xsl", + b"http://www.w3.org/1999/02/22-rdf-syntax-ns#": b"rdf", + b"http://schemas.xmlsoap.org/wsdl/": b"wsdl", + # xml schema + b"http://www.w3.org/2001/XMLSchema": b"xs", + b"http://www.w3.org/2001/XMLSchema-instance": b"xsi", + # dublin core + b"http://purl.org/dc/elements/1.1/": b"dc", + # objectify + b"http://codespeak.net/lxml/objectify/pytype" : b"py", +} + +# To avoid runtime encoding overhead, we keep a Unicode copy +# of the uri-prefix mapping as (str, str) items view. +cdef object _DEFAULT_NAMESPACE_PREFIXES_ITEMS = [] + +cdef _update_default_namespace_prefixes_items(): + cdef bytes ns, prefix + global _DEFAULT_NAMESPACE_PREFIXES_ITEMS + _DEFAULT_NAMESPACE_PREFIXES_ITEMS = { + ns.decode('utf-8') : prefix.decode('utf-8') + for ns, prefix in _DEFAULT_NAMESPACE_PREFIXES.items() + }.items() + +_update_default_namespace_prefixes_items() + +cdef object _check_internal_prefix = re.compile(br"ns\d+$").match + +def register_namespace(prefix, uri): + """Registers a namespace prefix that newly created Elements in that + namespace will use. The registry is global, and any existing + mapping for either the given prefix or the namespace URI will be + removed. + """ + prefix_utf, uri_utf = _utf8(prefix), _utf8(uri) + if _check_internal_prefix(prefix_utf): + raise ValueError("Prefix format reserved for internal use") + _tagValidOrRaise(prefix_utf) + _uriValidOrRaise(uri_utf) + if (uri_utf == b"http://www.w3.org/XML/1998/namespace" and prefix_utf != b'xml' + or prefix_utf == b'xml' and uri_utf != b"http://www.w3.org/XML/1998/namespace"): + raise ValueError("Cannot change the 'xml' prefix of the XML namespace") + for k, v in list(_DEFAULT_NAMESPACE_PREFIXES.items()): + if k == uri_utf or v == prefix_utf: + del _DEFAULT_NAMESPACE_PREFIXES[k] + _DEFAULT_NAMESPACE_PREFIXES[uri_utf] = prefix_utf + _update_default_namespace_prefixes_items() + + +# Error superclass for ElementTree compatibility +cdef class Error(Exception): + pass + +# module level superclass for all exceptions +cdef class LxmlError(Error): + """Main exception base class for lxml. All other exceptions inherit from + this one. + """ + def __init__(self, message, error_log=None): + super(_Error, self).__init__(message) + if error_log is None: + self.error_log = __copyGlobalErrorLog() + else: + self.error_log = error_log.copy() + +cdef object _Error = Error + + +# superclass for all syntax errors +class LxmlSyntaxError(LxmlError, SyntaxError): + """Base class for all syntax errors. + """ + +cdef class C14NError(LxmlError): + """Error during C14N serialisation. + """ + +# version information +cdef tuple __unpackDottedVersion(version): + version_list = [] + l = (version.decode("ascii").replace('-', '.').split('.') + [0]*4)[:4] + for item in l: + try: + item = int(item) + except ValueError: + if item.startswith('dev'): + count = item[3:] + item = -300 + elif item.startswith('alpha'): + count = item[5:] + item = -200 + elif item.startswith('beta'): + count = item[4:] + item = -100 + else: + count = 0 + if count: + item += int(count) + version_list.append(item) + return tuple(version_list) + +cdef tuple __unpackIntVersion(int c_version, int base=100): + return ( + ((c_version // (base*base)) % base), + ((c_version // base) % base), + (c_version % base) + ) + +cdef int _LIBXML_VERSION_INT +try: + _LIBXML_VERSION_INT = int( + re.match('[0-9]+', (tree.xmlParserVersion).decode("ascii")).group(0)) +except Exception: + print("Unknown libxml2 version: " + (tree.xmlParserVersion).decode("latin1")) + _LIBXML_VERSION_INT = 0 + +LIBXML_VERSION = __unpackIntVersion(_LIBXML_VERSION_INT) +LIBXML_COMPILED_VERSION = __unpackIntVersion(tree.LIBXML_VERSION) +LXML_VERSION = __unpackDottedVersion(tree.LXML_VERSION_STRING) + +__version__ = tree.LXML_VERSION_STRING.decode("ascii") + +cdef extern from *: + """ + #ifdef ZLIB_VERNUM + #define __lxml_zlib_version (ZLIB_VERNUM >> 4) + #else + #define __lxml_zlib_version 0 + #endif + #ifdef _LIBICONV_VERSION + #define __lxml_iconv_version (_LIBICONV_VERSION << 8) + #else + #define __lxml_iconv_version 0 + #endif + """ + # zlib isn't included automatically by libxml2's headers + #long ZLIB_HEX_VERSION "__lxml_zlib_version" + long LIBICONV_HEX_VERSION "__lxml_iconv_version" + +#ZLIB_COMPILED_VERSION = __unpackIntVersion(ZLIB_HEX_VERSION, base=0x10) +ICONV_COMPILED_VERSION = __unpackIntVersion(LIBICONV_HEX_VERSION, base=0x100)[:2] + + +cdef extern from "libxml/xmlversion.h": + """ + static const char* const _lxml_lib_features[] = { +#ifdef LIBXML_HTML_ENABLED + "html", +#endif +#ifdef LIBXML_FTP_ENABLED + "ftp", +#endif +#ifdef LIBXML_HTTP_ENABLED + "http", +#endif +#ifdef LIBXML_CATALOG_ENABLED + "catalog", +#endif +#ifdef LIBXML_XPATH_ENABLED + "xpath", +#endif +#ifdef LIBXML_ICONV_ENABLED + "iconv", +#endif +#ifdef LIBXML_ICU_ENABLED + "icu", +#endif +#ifdef LIBXML_REGEXP_ENABLED + "regexp", +#endif +#ifdef LIBXML_SCHEMAS_ENABLED + "xmlschema", +#endif +#ifdef LIBXML_SCHEMATRON_ENABLED + "schematron", +#endif +#ifdef LIBXML_ZLIB_ENABLED + "zlib", +#endif +#ifdef LIBXML_LZMA_ENABLED + "lzma", +#endif + 0 + }; + """ + const char* const* _LXML_LIB_FEATURES "_lxml_lib_features" + + +cdef set _copy_lib_features(): + features = set() + feature = _LXML_LIB_FEATURES + while feature[0]: + features.add(feature[0].decode('ASCII')) + feature += 1 + return features + +LIBXML_COMPILED_FEATURES = _copy_lib_features() +LIBXML_FEATURES = { + feature_name for feature_id, feature_name in [ + #XML_WITH_THREAD = 1 + #XML_WITH_TREE = 2 + #XML_WITH_OUTPUT = 3 + #XML_WITH_PUSH = 4 + #XML_WITH_READER = 5 + #XML_WITH_PATTERN = 6 + #XML_WITH_WRITER = 7 + #XML_WITH_SAX1 = 8 + (xmlparser.XML_WITH_FTP, "ftp"), # XML_WITH_FTP = 9 + (xmlparser.XML_WITH_HTTP, "http"), # XML_WITH_HTTP = 10 + #XML_WITH_VALID = 11 + (xmlparser.XML_WITH_HTML, "html"), # XML_WITH_HTML = 12 + #XML_WITH_LEGACY = 13 + #XML_WITH_C14N = 14 + (xmlparser.XML_WITH_CATALOG, "catalog"), # XML_WITH_CATALOG = 15 + (xmlparser.XML_WITH_XPATH, "xpath"), # XML_WITH_XPATH = 16 + #XML_WITH_XPTR = 17 + #XML_WITH_XINCLUDE = 18 + (xmlparser.XML_WITH_ICONV, "iconv"), # XML_WITH_ICONV = 19 + #XML_WITH_ISO8859X = 20 + #XML_WITH_UNICODE = 21 + (xmlparser.XML_WITH_REGEXP, "regexp"), # XML_WITH_REGEXP = 22 + #XML_WITH_AUTOMATA = 23 + #XML_WITH_EXPR = 24 + (xmlparser.XML_WITH_SCHEMAS, "xmlschema"), # XML_WITH_SCHEMAS = 25 + (xmlparser.XML_WITH_SCHEMATRON, "schematron"), # XML_WITH_SCHEMATRON = 26 + #XML_WITH_MODULES = 27 + #XML_WITH_DEBUG = 28 + #XML_WITH_DEBUG_MEM = 29 + #XML_WITH_DEBUG_RUN = 30 # unused + (xmlparser.XML_WITH_ZLIB, "zlib"), # XML_WITH_ZLIB = 31 + (xmlparser.XML_WITH_ICU, "icu"), # XML_WITH_ICU = 32 + (xmlparser.XML_WITH_LZMA, "lzma"), # XML_WITH_LZMA = 33 + ] if xmlparser.xmlHasFeature(feature_id) +} + +cdef bint HAS_ZLIB_COMPRESSION = xmlparser.xmlHasFeature(xmlparser.XML_WITH_ZLIB) + + +# class for temporary storage of Python references, +# used e.g. for XPath results +@cython.final +@cython.internal +cdef class _TempStore: + cdef list _storage + def __init__(self): + self._storage = [] + + cdef int add(self, obj) except -1: + self._storage.append(obj) + return 0 + + cdef int clear(self) except -1: + del self._storage[:] + return 0 + + +# class for temporarily storing exceptions raised in extensions +@cython.internal +cdef class _ExceptionContext: + cdef object _exc_info + cdef int clear(self) except -1: + self._exc_info = None + return 0 + + cdef void _store_raised(self) noexcept: + try: + self._exc_info = sys.exc_info() + except BaseException as e: + self._store_exception(e) + finally: + return # and swallow any further exceptions + + cdef int _store_exception(self, exception) except -1: + self._exc_info = (exception, None, None) + return 0 + + cdef bint _has_raised(self) except -1: + return self._exc_info is not None + + cdef int _raise_if_stored(self) except -1: + if self._exc_info is None: + return 0 + type, value, traceback = self._exc_info + self._exc_info = None + if value is None and traceback is None: + raise type + else: + raise type, value, traceback + + +# type of a function that steps from node to node +ctypedef public xmlNode* (*_node_to_node_function)(xmlNode*) + + +################################################################################ +# Include submodules + +include "proxy.pxi" # Proxy handling (element backpointers/memory/etc.) +include "apihelpers.pxi" # Private helper functions +include "xmlerror.pxi" # Error and log handling + + +################################################################################ +# Public Python API + +@cython.final +@cython.freelist(8) +cdef public class _Document [ type LxmlDocumentType, object LxmlDocument ]: + """Internal base class to reference a libxml document. + + When instances of this class are garbage collected, the libxml + document is cleaned up. + """ + cdef int _ns_counter + cdef bytes _prefix_tail + cdef xmlDoc* _c_doc + cdef _BaseParser _parser + + def __dealloc__(self): + # if there are no more references to the document, it is safe + # to clean the whole thing up, as all nodes have a reference to + # the document + tree.xmlFreeDoc(self._c_doc) + + @cython.final + cdef getroot(self): + # return an element proxy for the document root + cdef xmlNode* c_node + c_node = tree.xmlDocGetRootElement(self._c_doc) + if c_node is NULL: + return None + return _elementFactory(self, c_node) + + @cython.final + cdef bint hasdoctype(self) noexcept: + # DOCTYPE gets parsed into internal subset (xmlDTD*) + return self._c_doc is not NULL and self._c_doc.intSubset is not NULL + + @cython.final + cdef getdoctype(self): + # get doctype info: root tag, public/system ID (or None if not known) + cdef tree.xmlDtd* c_dtd + cdef xmlNode* c_root_node + public_id = None + sys_url = None + c_dtd = self._c_doc.intSubset + if c_dtd is not NULL: + if c_dtd.ExternalID is not NULL: + public_id = funicode(c_dtd.ExternalID) + if c_dtd.SystemID is not NULL: + sys_url = funicode(c_dtd.SystemID) + c_dtd = self._c_doc.extSubset + if c_dtd is not NULL: + if not public_id and c_dtd.ExternalID is not NULL: + public_id = funicode(c_dtd.ExternalID) + if not sys_url and c_dtd.SystemID is not NULL: + sys_url = funicode(c_dtd.SystemID) + c_root_node = tree.xmlDocGetRootElement(self._c_doc) + if c_root_node is NULL: + root_name = None + else: + root_name = funicode(c_root_node.name) + return root_name, public_id, sys_url + + @cython.final + cdef getxmlinfo(self): + # return XML version and encoding (or None if not known) + cdef xmlDoc* c_doc = self._c_doc + if c_doc.version is NULL: + version = None + else: + version = funicode(c_doc.version) + if c_doc.encoding is NULL: + encoding = None + else: + encoding = funicode(c_doc.encoding) + return version, encoding + + @cython.final + cdef isstandalone(self): + # returns True for "standalone=true", + # False for "standalone=false", None if not provided + if self._c_doc.standalone == -1: + return None + else: + return (self._c_doc.standalone == 1) + + @cython.final + cdef bytes buildNewPrefix(self): + # get a new unique prefix ("nsX") for this document + cdef bytes ns + if self._ns_counter < len(_PREFIX_CACHE): + ns = _PREFIX_CACHE[self._ns_counter] + else: + ns = python.PyBytes_FromFormat("ns%d", self._ns_counter) + if self._prefix_tail is not None: + ns += self._prefix_tail + self._ns_counter += 1 + if self._ns_counter < 0: + # overflow! + self._ns_counter = 0 + if self._prefix_tail is None: + self._prefix_tail = b"A" + else: + self._prefix_tail += b"A" + return ns + + @cython.final + cdef xmlNs* _findOrBuildNodeNs(self, xmlNode* c_node, + const_xmlChar* c_href, const_xmlChar* c_prefix, + bint is_attribute) except NULL: + """Get or create namespace structure for a node. Reuses the prefix if + possible. + """ + cdef xmlNs* c_ns + cdef xmlNs* c_doc_ns + cdef python.PyObject* dict_result + if c_node.type != tree.XML_ELEMENT_NODE: + assert c_node.type == tree.XML_ELEMENT_NODE, \ + "invalid node type %d, expected %d" % ( + c_node.type, tree.XML_ELEMENT_NODE) + # look for existing ns declaration + c_ns = _searchNsByHref(c_node, c_href, is_attribute) + if c_ns is not NULL: + if is_attribute and c_ns.prefix is NULL: + # do not put namespaced attributes into the default + # namespace as this would break serialisation + pass + else: + return c_ns + + # none found => determine a suitable new prefix + if c_prefix is NULL: + dict_result = python.PyDict_GetItem( + _DEFAULT_NAMESPACE_PREFIXES, c_href) + if dict_result is not NULL: + prefix = dict_result + else: + prefix = self.buildNewPrefix() + c_prefix = _xcstr(prefix) + + # make sure the prefix is not in use already + while tree.xmlSearchNs(self._c_doc, c_node, c_prefix) is not NULL: + prefix = self.buildNewPrefix() + c_prefix = _xcstr(prefix) + + # declare the namespace and return it + c_ns = tree.xmlNewNs(c_node, c_href, c_prefix) + if c_ns is NULL: + raise MemoryError() + return c_ns + + @cython.final + cdef int _setNodeNs(self, xmlNode* c_node, const_xmlChar* c_href) except -1: + "Lookup namespace structure and set it for the node." + c_ns = self._findOrBuildNodeNs(c_node, c_href, NULL, 0) + tree.xmlSetNs(c_node, c_ns) + + +cdef tuple __initPrefixCache(): + cdef int i + return tuple([ python.PyBytes_FromFormat("ns%d", i) + for i in range(26) ]) + +cdef tuple _PREFIX_CACHE = __initPrefixCache() + + +cdef _Document _documentFactory(xmlDoc* c_doc, _BaseParser parser): + cdef _Document result + result = _Document.__new__(_Document) + result._c_doc = c_doc + result._ns_counter = 0 + result._prefix_tail = None + if parser is None: + parser = __GLOBAL_PARSER_CONTEXT.getDefaultParser() + result._parser = parser + return result + + +cdef object _find_invalid_public_id_characters = re.compile( + ur"[^\x20\x0D\x0Aa-zA-Z0-9'()+,./:=?;!*#@$_%-]+").search + + +cdef class DocInfo: + "Document information provided by parser and DTD." + cdef _Document _doc + def __cinit__(self, tree): + "Create a DocInfo object for an ElementTree object or root Element." + self._doc = _documentOrRaise(tree) + root_name, public_id, system_url = self._doc.getdoctype() + if not root_name and (public_id or system_url): + raise ValueError, "Could not find root node" + + @property + def root_name(self): + """Returns the name of the root node as defined by the DOCTYPE.""" + root_name, public_id, system_url = self._doc.getdoctype() + return root_name + + @cython.final + cdef tree.xmlDtd* _get_c_dtd(self): + """"Return the DTD. Create it if it does not yet exist.""" + cdef xmlDoc* c_doc = self._doc._c_doc + cdef xmlNode* c_root_node + cdef const_xmlChar* c_name + + if c_doc.intSubset: + return c_doc.intSubset + + c_root_node = tree.xmlDocGetRootElement(c_doc) + c_name = c_root_node.name if c_root_node else NULL + return tree.xmlCreateIntSubset(c_doc, c_name, NULL, NULL) + + def clear(self): + """Removes DOCTYPE and internal subset from the document.""" + cdef xmlDoc* c_doc = self._doc._c_doc + cdef tree.xmlNode* c_dtd = c_doc.intSubset + if c_dtd is NULL: + return + tree.xmlUnlinkNode(c_dtd) + tree.xmlFreeNode(c_dtd) + + property public_id: + """Public ID of the DOCTYPE. + + Mutable. May be set to a valid string or None. If a DTD does not + exist, setting this variable (even to None) will create one. + """ + def __get__(self): + root_name, public_id, system_url = self._doc.getdoctype() + return public_id + + def __set__(self, value): + cdef xmlChar* c_value = NULL + if value is not None: + match = _find_invalid_public_id_characters(value) + if match: + raise ValueError, f'Invalid character(s) {match.group(0)!r} in public_id.' + value = _utf8(value) + c_value = tree.xmlStrdup(_xcstr(value)) + if not c_value: + raise MemoryError() + + c_dtd = self._get_c_dtd() + if not c_dtd: + tree.xmlFree(c_value) + raise MemoryError() + if c_dtd.ExternalID: + tree.xmlFree(c_dtd.ExternalID) + c_dtd.ExternalID = c_value + + property system_url: + """System ID of the DOCTYPE. + + Mutable. May be set to a valid string or None. If a DTD does not + exist, setting this variable (even to None) will create one. + """ + def __get__(self): + root_name, public_id, system_url = self._doc.getdoctype() + return system_url + + def __set__(self, value): + cdef xmlChar* c_value = NULL + if value is not None: + bvalue = _utf8(value) + # sys_url may be any valid unicode string that can be + # enclosed in single quotes or quotes. + if b"'" in bvalue and b'"' in bvalue: + raise ValueError( + 'System URL may not contain both single (\') and double quotes (").') + c_value = tree.xmlStrdup(_xcstr(bvalue)) + if not c_value: + raise MemoryError() + + c_dtd = self._get_c_dtd() + if not c_dtd: + tree.xmlFree(c_value) + raise MemoryError() + if c_dtd.SystemID: + tree.xmlFree(c_dtd.SystemID) + c_dtd.SystemID = c_value + + @property + def xml_version(self): + """Returns the XML version as declared by the document.""" + xml_version, encoding = self._doc.getxmlinfo() + return xml_version + + @property + def encoding(self): + """Returns the encoding name as declared by the document.""" + xml_version, encoding = self._doc.getxmlinfo() + return encoding + + @property + def standalone(self): + """Returns the standalone flag as declared by the document. The possible + values are True (``standalone='yes'``), False + (``standalone='no'`` or flag not provided in the declaration), + and None (unknown or no declaration found). Note that a + normal truth test on this value will always tell if the + ``standalone`` flag was set to ``'yes'`` or not. + """ + return self._doc.isstandalone() + + property URL: + "The source URL of the document (or None if unknown)." + def __get__(self): + if self._doc._c_doc.URL is NULL: + return None + return _decodeFilename(self._doc._c_doc.URL) + def __set__(self, url): + url = _encodeFilename(url) + c_oldurl = self._doc._c_doc.URL + if url is None: + self._doc._c_doc.URL = NULL + else: + self._doc._c_doc.URL = tree.xmlStrdup(_xcstr(url)) + if c_oldurl is not NULL: + tree.xmlFree(c_oldurl) + + @property + def doctype(self): + """Returns a DOCTYPE declaration string for the document.""" + root_name, public_id, system_url = self._doc.getdoctype() + if system_url: + # If '"' in system_url, we must escape it with single + # quotes, otherwise escape with double quotes. If url + # contains both a single quote and a double quote, XML + # standard is being violated. + if '"' in system_url: + quoted_system_url = f"'{system_url}'" + else: + quoted_system_url = f'"{system_url}"' + if public_id: + if system_url: + return f'' + else: + return f'' + elif system_url: + return f'' + elif self._doc.hasdoctype(): + return f'' + else: + return '' + + @property + def internalDTD(self): + """Returns a DTD validator based on the internal subset of the document.""" + return _dtdFactory(self._doc._c_doc.intSubset) + + @property + def externalDTD(self): + """Returns a DTD validator based on the external subset of the document.""" + return _dtdFactory(self._doc._c_doc.extSubset) + + +@cython.no_gc_clear +cdef public class _Element [ type LxmlElementType, object LxmlElement ]: + """Element class. + + References a document object and a libxml node. + + By pointing to a Document instance, a reference is kept to + _Document as long as there is some pointer to a node in it. + """ + cdef _Document _doc + cdef xmlNode* _c_node + cdef object _tag + + def _init(self): + """_init(self) + + Called after object initialisation. Custom subclasses may override + this if they recursively call _init() in the superclasses. + """ + + @cython.linetrace(False) + @cython.profile(False) + def __dealloc__(self): + #print("trying to free node:", self._c_node) + #displayNode(self._c_node, 0) + if self._c_node is not NULL: + _unregisterProxy(self) + attemptDeallocation(self._c_node) + + # MANIPULATORS + + def __setitem__(self, x, value): + """__setitem__(self, x, value) + + Replaces the given subelement index or slice. + """ + cdef xmlNode* c_node = NULL + cdef xmlNode* c_next + cdef xmlDoc* c_source_doc + cdef _Element element + cdef bint left_to_right + cdef Py_ssize_t slicelength = 0, step = 0 + _assertValidNode(self) + if value is None: + raise ValueError, "cannot assign None" + if isinstance(x, slice): + # slice assignment + _findChildSlice(x, self._c_node, &c_node, &step, &slicelength) + if step > 0: + left_to_right = 1 + else: + left_to_right = 0 + step = -step + _replaceSlice(self, c_node, slicelength, step, left_to_right, value) + return + else: + # otherwise: normal item assignment + element = value + _assertValidNode(element) + c_node = _findChild(self._c_node, x) + if c_node is NULL: + raise IndexError, "list index out of range" + c_source_doc = element._c_node.doc + c_next = element._c_node.next + _removeText(c_node.next) + tree.xmlReplaceNode(c_node, element._c_node) + _moveTail(c_next, element._c_node) + moveNodeToDocument(self._doc, c_source_doc, element._c_node) + if not attemptDeallocation(c_node): + moveNodeToDocument(self._doc, c_node.doc, c_node) + + def __delitem__(self, x): + """__delitem__(self, x) + + Deletes the given subelement or a slice. + """ + cdef xmlNode* c_node = NULL + cdef xmlNode* c_next + cdef Py_ssize_t step = 0, slicelength = 0 + _assertValidNode(self) + if isinstance(x, slice): + # slice deletion + if _isFullSlice(x): + c_node = self._c_node.children + if c_node is not NULL: + if not _isElement(c_node): + c_node = _nextElement(c_node) + while c_node is not NULL: + c_next = _nextElement(c_node) + _removeNode(self._doc, c_node) + c_node = c_next + else: + _findChildSlice(x, self._c_node, &c_node, &step, &slicelength) + _deleteSlice(self._doc, c_node, slicelength, step) + else: + # item deletion + c_node = _findChild(self._c_node, x) + if c_node is NULL: + raise IndexError, f"index out of range: {x}" + _removeNode(self._doc, c_node) + + def __deepcopy__(self, memo): + "__deepcopy__(self, memo)" + return self.__copy__() + + def __copy__(self): + "__copy__(self)" + cdef xmlDoc* c_doc + cdef xmlNode* c_node + cdef _Document new_doc + _assertValidNode(self) + c_doc = _copyDocRoot(self._doc._c_doc, self._c_node) # recursive + new_doc = _documentFactory(c_doc, self._doc._parser) + root = new_doc.getroot() + if root is not None: + return root + # Comment/PI + c_node = c_doc.children + while c_node is not NULL and c_node.type != self._c_node.type: + c_node = c_node.next + if c_node is NULL: + return None + return _elementFactory(new_doc, c_node) + + def set(self, key, value): + """set(self, key, value) + + Sets an element attribute. + In HTML documents (not XML or XHTML), the value None is allowed and creates + an attribute without value (just the attribute name). + """ + _assertValidNode(self) + _setAttributeValue(self, key, value) + + def append(self, _Element element not None): + """append(self, element) + + Adds a subelement to the end of this element. + """ + _assertValidNode(self) + _assertValidNode(element) + _appendChild(self, element) + + def addnext(self, _Element element not None): + """addnext(self, element) + + Adds the element as a following sibling directly after this + element. + + This is normally used to set a processing instruction or comment after + the root node of a document. Note that tail text is automatically + discarded when adding at the root level. + """ + _assertValidNode(self) + _assertValidNode(element) + if self._c_node.parent != NULL and not _isElement(self._c_node.parent): + if element._c_node.type not in (tree.XML_PI_NODE, tree.XML_COMMENT_NODE): + raise TypeError, "Only processing instructions and comments can be siblings of the root element" + element.tail = None + _appendSibling(self, element) + + def addprevious(self, _Element element not None): + """addprevious(self, element) + + Adds the element as a preceding sibling directly before this + element. + + This is normally used to set a processing instruction or comment + before the root node of a document. Note that tail text is + automatically discarded when adding at the root level. + """ + _assertValidNode(self) + _assertValidNode(element) + if self._c_node.parent != NULL and not _isElement(self._c_node.parent): + if element._c_node.type != tree.XML_PI_NODE: + if element._c_node.type != tree.XML_COMMENT_NODE: + raise TypeError, "Only processing instructions and comments can be siblings of the root element" + element.tail = None + _prependSibling(self, element) + + def extend(self, elements): + """extend(self, elements) + + Extends the current children by the elements in the iterable. + """ + cdef _Element element + _assertValidNode(self) + for element in elements: + if element is None: + raise TypeError, "Node must not be None" + _assertValidNode(element) + _appendChild(self, element) + + def clear(self, bint keep_tail=False): + """clear(self, keep_tail=False) + + Resets an element. This function removes all subelements, clears + all attributes and sets the text and tail properties to None. + + Pass ``keep_tail=True`` to leave the tail text untouched. + """ + cdef xmlAttr* c_attr + cdef xmlAttr* c_attr_next + cdef xmlNode* c_node + cdef xmlNode* c_node_next + _assertValidNode(self) + c_node = self._c_node + # remove self.text and self.tail + _removeText(c_node.children) + if not keep_tail: + _removeText(c_node.next) + # remove all attributes + c_attr = c_node.properties + if c_attr: + c_node.properties = NULL + tree.xmlFreePropList(c_attr) + # remove all subelements + c_node = c_node.children + if c_node and not _isElement(c_node): + c_node = _nextElement(c_node) + while c_node is not NULL: + c_node_next = _nextElement(c_node) + _removeNode(self._doc, c_node) + c_node = c_node_next + + def insert(self, index: int, _Element element not None): + """insert(self, index, element) + + Inserts a subelement at the given position in this element + """ + cdef xmlNode* c_node + cdef xmlNode* c_next + cdef xmlDoc* c_source_doc + _assertValidNode(self) + _assertValidNode(element) + c_node = _findChild(self._c_node, index) + if c_node is NULL: + _appendChild(self, element) + return + # prevent cycles + if _isAncestorOrSame(element._c_node, self._c_node): + raise ValueError("cannot append parent to itself") + c_source_doc = element._c_node.doc + c_next = element._c_node.next + tree.xmlAddPrevSibling(c_node, element._c_node) + _moveTail(c_next, element._c_node) + moveNodeToDocument(self._doc, c_source_doc, element._c_node) + + def remove(self, _Element element not None): + """remove(self, element) + + Removes a matching subelement. Unlike the find methods, this + method compares elements based on identity, not on tag value + or contents. + """ + cdef xmlNode* c_node + cdef xmlNode* c_next + _assertValidNode(self) + _assertValidNode(element) + c_node = element._c_node + if c_node.parent is not self._c_node: + raise ValueError, "Element is not a child of this node." + c_next = element._c_node.next + tree.xmlUnlinkNode(c_node) + _moveTail(c_next, c_node) + # fix namespace declarations + moveNodeToDocument(self._doc, c_node.doc, c_node) + + def replace(self, _Element old_element not None, + _Element new_element not None): + """replace(self, old_element, new_element) + + Replaces a subelement with the element passed as second argument. + """ + cdef xmlNode* c_old_node + cdef xmlNode* c_old_next + cdef xmlNode* c_new_node + cdef xmlNode* c_new_next + cdef xmlDoc* c_source_doc + _assertValidNode(self) + _assertValidNode(old_element) + _assertValidNode(new_element) + c_old_node = old_element._c_node + if c_old_node.parent is not self._c_node: + raise ValueError, "Element is not a child of this node." + c_new_node = new_element._c_node + # prevent cycles + if _isAncestorOrSame(c_new_node, self._c_node): + raise ValueError("cannot append parent to itself") + # replace node + c_old_next = c_old_node.next + c_new_next = c_new_node.next + c_source_doc = c_new_node.doc + tree.xmlReplaceNode(c_old_node, c_new_node) + _moveTail(c_new_next, c_new_node) + _moveTail(c_old_next, c_old_node) + moveNodeToDocument(self._doc, c_source_doc, c_new_node) + # fix namespace declarations + moveNodeToDocument(self._doc, c_old_node.doc, c_old_node) + + # PROPERTIES + property tag: + """Element tag + """ + def __get__(self): + if self._tag is not None: + return self._tag + _assertValidNode(self) + self._tag = _namespacedName(self._c_node) + return self._tag + + def __set__(self, value): + cdef _BaseParser parser + _assertValidNode(self) + ns, name = _getNsTag(value) + parser = self._doc._parser + if parser is not None and parser._for_html: + _htmlTagValidOrRaise(name) + else: + _tagValidOrRaise(name) + self._tag = value + tree.xmlNodeSetName(self._c_node, _xcstr(name)) + if ns is None: + self._c_node.ns = NULL + else: + self._doc._setNodeNs(self._c_node, _xcstr(ns)) + + @property + def attrib(self): + """Element attribute dictionary. Where possible, use get(), set(), + keys(), values() and items() to access element attributes. + """ + return _Attrib.__new__(_Attrib, self) + + property text: + """Text before the first subelement. This is either a string or + the value None, if there was no text. + """ + def __get__(self): + _assertValidNode(self) + return _collectText(self._c_node.children) + + def __set__(self, value): + _assertValidNode(self) + if isinstance(value, QName): + value = _resolveQNameText(self, value).decode('utf8') + _setNodeText(self._c_node, value) + + # using 'del el.text' is the wrong thing to do + #def __del__(self): + # _setNodeText(self._c_node, None) + + property tail: + """Text after this element's end tag, but before the next sibling + element's start tag. This is either a string or the value None, if + there was no text. + """ + def __get__(self): + _assertValidNode(self) + return _collectText(self._c_node.next) + + def __set__(self, value): + _assertValidNode(self) + _setTailText(self._c_node, value) + + # using 'del el.tail' is the wrong thing to do + #def __del__(self): + # _setTailText(self._c_node, None) + + # not in ElementTree, read-only + @property + def prefix(self): + """Namespace prefix or None. + """ + if self._c_node.ns is not NULL: + if self._c_node.ns.prefix is not NULL: + return funicode(self._c_node.ns.prefix) + return None + + # not in ElementTree, read-only + property sourceline: + """Original line number as found by the parser or None if unknown. + """ + def __get__(self): + cdef long line + _assertValidNode(self) + line = tree.xmlGetLineNo(self._c_node) + return line if line > 0 else None + + def __set__(self, line): + _assertValidNode(self) + if line <= 0: + self._c_node.line = 0 + else: + self._c_node.line = line + + # not in ElementTree, read-only + @property + def nsmap(self): + """Namespace prefix->URI mapping known in the context of this + Element. This includes all namespace declarations of the + parents. + + Note that changing the returned dict has no effect on the Element. + """ + _assertValidNode(self) + return _build_nsmap(self._c_node) + + # not in ElementTree, read-only + property base: + """The base URI of the Element (xml:base or HTML base URL). + None if the base URI is unknown. + + Note that the value depends on the URL of the document that + holds the Element if there is no xml:base attribute on the + Element or its ancestors. + + Setting this property will set an xml:base attribute on the + Element, regardless of the document type (XML or HTML). + """ + def __get__(self): + _assertValidNode(self) + c_base = tree.xmlNodeGetBase(self._doc._c_doc, self._c_node) + if c_base is NULL: + if self._doc._c_doc.URL is NULL: + return None + return _decodeFilename(self._doc._c_doc.URL) + try: + base = _decodeFilename(c_base) + finally: + tree.xmlFree(c_base) + return base + + def __set__(self, url): + _assertValidNode(self) + if url is None: + c_base = NULL + else: + url = _encodeFilename(url) + c_base = _xcstr(url) + tree.xmlNodeSetBase(self._c_node, c_base) + + # ACCESSORS + def __repr__(self): + "__repr__(self)" + return "" % (self.tag, id(self)) + + def __getitem__(self, x): + """Returns the subelement at the given position or the requested + slice. + """ + cdef xmlNode* c_node = NULL + cdef Py_ssize_t step = 0, slicelength = 0 + cdef Py_ssize_t c, i + cdef _node_to_node_function next_element + cdef list result + _assertValidNode(self) + if isinstance(x, slice): + # slicing + if _isFullSlice(x): + return _collectChildren(self) + _findChildSlice(x, self._c_node, &c_node, &step, &slicelength) + if c_node is NULL: + return [] + if step > 0: + next_element = _nextElement + else: + step = -step + next_element = _previousElement + result = [] + c = 0 + while c_node is not NULL and c < slicelength: + result.append(_elementFactory(self._doc, c_node)) + c += 1 + for i in range(step): + c_node = next_element(c_node) + if c_node is NULL: + break + return result + else: + # indexing + c_node = _findChild(self._c_node, x) + if c_node is NULL: + raise IndexError, "list index out of range" + return _elementFactory(self._doc, c_node) + + def __len__(self): + """__len__(self) + + Returns the number of subelements. + """ + _assertValidNode(self) + return _countElements(self._c_node.children) + + def __bool__(self): + """__bool__(self)""" + import warnings + warnings.warn( + "Truth-testing of elements was a source of confusion and will always " + "return True in future versions. " + "Use specific 'len(elem)' or 'elem is not None' test instead.", + FutureWarning + ) + # emulate old behaviour + _assertValidNode(self) + return _hasChild(self._c_node) + + def __contains__(self, element): + "__contains__(self, element)" + cdef xmlNode* c_node + _assertValidNode(self) + if not isinstance(element, _Element): + return 0 + c_node = (<_Element>element)._c_node + return c_node is not NULL and c_node.parent is self._c_node + + def __iter__(self): + "__iter__(self)" + return ElementChildIterator(self) + + def __reversed__(self): + "__reversed__(self)" + return ElementChildIterator(self, reversed=True) + + def index(self, child: _Element, start: int = None, stop: int = None): + """index(self, child, start=None, stop=None) + + Find the position of the child within the parent. + + This method is not part of the original ElementTree API. + """ + cdef Py_ssize_t k, l + cdef Py_ssize_t c_start, c_stop + cdef xmlNode* c_child + cdef xmlNode* c_start_node + _assertValidNode(self) + _assertValidNode(child) + c_child = child._c_node + if c_child.parent is not self._c_node: + raise ValueError, "Element is not a child of this node." + + # handle the unbounded search straight away (normal case) + if stop is None and (start is None or start == 0): + k = 0 + c_child = c_child.prev + while c_child is not NULL: + if _isElement(c_child): + k += 1 + c_child = c_child.prev + return k + + # check indices + if start is None: + c_start = 0 + else: + c_start = start + if stop is None: + c_stop = 0 + else: + c_stop = stop + if c_stop == 0 or \ + c_start >= c_stop and (c_stop > 0 or c_start < 0): + raise ValueError, "list.index(x): x not in slice" + + # for negative slice indices, check slice before searching index + if c_start < 0 or c_stop < 0: + # start from right, at most up to leftmost(c_start, c_stop) + if c_start < c_stop: + k = -c_start + else: + k = -c_stop + c_start_node = self._c_node.last + l = 1 + while c_start_node != c_child and l < k: + if _isElement(c_start_node): + l += 1 + c_start_node = c_start_node.prev + if c_start_node == c_child: + # found! before slice end? + if c_stop < 0 and l <= -c_stop: + raise ValueError, "list.index(x): x not in slice" + elif c_start < 0: + raise ValueError, "list.index(x): x not in slice" + + # now determine the index backwards from child + c_child = c_child.prev + k = 0 + if c_stop > 0: + # we can optimize: stop after c_stop elements if not found + while c_child != NULL and k < c_stop: + if _isElement(c_child): + k += 1 + c_child = c_child.prev + if k < c_stop: + return k + else: + # traverse all + while c_child != NULL: + if _isElement(c_child): + k = k + 1 + c_child = c_child.prev + if c_start > 0: + if k >= c_start: + return k + else: + return k + if c_start != 0 or c_stop != 0: + raise ValueError, "list.index(x): x not in slice" + else: + raise ValueError, "list.index(x): x not in list" + + def get(self, key, default=None): + """get(self, key, default=None) + + Gets an element attribute. + """ + _assertValidNode(self) + return _getAttributeValue(self, key, default) + + def keys(self): + """keys(self) + + Gets a list of attribute names. The names are returned in an + arbitrary order (just like for an ordinary Python dictionary). + """ + _assertValidNode(self) + return _collectAttributes(self._c_node, 1) + + def values(self): + """values(self) + + Gets element attribute values as a sequence of strings. The + attributes are returned in an arbitrary order. + """ + _assertValidNode(self) + return _collectAttributes(self._c_node, 2) + + def items(self): + """items(self) + + Gets element attributes, as a sequence. The attributes are returned in + an arbitrary order. + """ + _assertValidNode(self) + return _collectAttributes(self._c_node, 3) + + def getchildren(self): + """getchildren(self) + + Returns all direct children. The elements are returned in document + order. + + :deprecated: Note that this method has been deprecated as of + ElementTree 1.3 and lxml 2.0. New code should use + ``list(element)`` or simply iterate over elements. + """ + _assertValidNode(self) + return _collectChildren(self) + + def getparent(self): + """getparent(self) + + Returns the parent of this element or None for the root element. + """ + cdef xmlNode* c_node + #_assertValidNode(self) # not needed + c_node = _parentElement(self._c_node) + if c_node is NULL: + return None + return _elementFactory(self._doc, c_node) + + def getnext(self): + """getnext(self) + + Returns the following sibling of this element or None. + """ + cdef xmlNode* c_node + #_assertValidNode(self) # not needed + c_node = _nextElement(self._c_node) + if c_node is NULL: + return None + return _elementFactory(self._doc, c_node) + + def getprevious(self): + """getprevious(self) + + Returns the preceding sibling of this element or None. + """ + cdef xmlNode* c_node + #_assertValidNode(self) # not needed + c_node = _previousElement(self._c_node) + if c_node is NULL: + return None + return _elementFactory(self._doc, c_node) + + def itersiblings(self, tag=None, *tags, preceding=False): + """itersiblings(self, tag=None, *tags, preceding=False) + + Iterate over the following or preceding siblings of this element. + + The direction is determined by the 'preceding' keyword which + defaults to False, i.e. forward iteration over the following + siblings. When True, the iterator yields the preceding + siblings in reverse document order, i.e. starting right before + the current element and going backwards. + + Can be restricted to find only elements with specific tags, + see `iter`. + """ + if preceding: + if self._c_node and not self._c_node.prev: + return ITER_EMPTY + elif self._c_node and not self._c_node.next: + return ITER_EMPTY + if tag is not None: + tags += (tag,) + return SiblingsIterator(self, tags, preceding=preceding) + + def iterancestors(self, tag=None, *tags): + """iterancestors(self, tag=None, *tags) + + Iterate over the ancestors of this element (from parent to parent). + + Can be restricted to find only elements with specific tags, + see `iter`. + """ + if self._c_node and not self._c_node.parent: + return ITER_EMPTY + if tag is not None: + tags += (tag,) + return AncestorsIterator(self, tags) + + def iterdescendants(self, tag=None, *tags): + """iterdescendants(self, tag=None, *tags) + + Iterate over the descendants of this element in document order. + + As opposed to ``el.iter()``, this iterator does not yield the element + itself. The returned elements can be restricted to find only elements + with specific tags, see `iter`. + """ + if self._c_node and not self._c_node.children: + return ITER_EMPTY + if tag is not None: + tags += (tag,) + return ElementDepthFirstIterator(self, tags, inclusive=False) + + def iterchildren(self, tag=None, *tags, reversed=False): + """iterchildren(self, tag=None, *tags, reversed=False) + + Iterate over the children of this element. + + As opposed to using normal iteration on this element, the returned + elements can be reversed with the 'reversed' keyword and restricted + to find only elements with specific tags, see `iter`. + """ + if self._c_node and not self._c_node.children: + return ITER_EMPTY + if tag is not None: + tags += (tag,) + return ElementChildIterator(self, tags, reversed=reversed) + + def getroottree(self): + """getroottree(self) + + Return an ElementTree for the root node of the document that + contains this element. + + This is the same as following element.getparent() up the tree until it + returns None (for the root element) and then build an ElementTree for + the last parent that was returned.""" + _assertValidDoc(self._doc) + return _elementTreeFactory(self._doc, None) + + def getiterator(self, tag=None, *tags): + """getiterator(self, tag=None, *tags) + + Returns a sequence or iterator of all elements in the subtree in + document order (depth first pre-order), starting with this + element. + + Can be restricted to find only elements with specific tags, + see `iter`. + + :deprecated: Note that this method is deprecated as of + ElementTree 1.3 and lxml 2.0. It returns an iterator in + lxml, which diverges from the original ElementTree + behaviour. If you want an efficient iterator, use the + ``element.iter()`` method instead. You should only use this + method in new code if you require backwards compatibility + with older versions of lxml or ElementTree. + """ + if tag is not None: + tags += (tag,) + return ElementDepthFirstIterator(self, tags) + + def iter(self, tag=None, *tags): + """iter(self, tag=None, *tags) + + Iterate over all elements in the subtree in document order (depth + first pre-order), starting with this element. + + Can be restricted to find only elements with specific tags: + pass ``"{ns}localname"`` as tag. Either or both of ``ns`` and + ``localname`` can be ``*`` for a wildcard; ``ns`` can be empty + for no namespace. ``"localname"`` is equivalent to ``"{}localname"`` + (i.e. no namespace) but ``"*"`` is ``"{*}*"`` (any or no namespace), + not ``"{}*"``. + + You can also pass the Element, Comment, ProcessingInstruction and + Entity factory functions to look only for the specific element type. + + Passing multiple tags (or a sequence of tags) instead of a single tag + will let the iterator return all elements matching any of these tags, + in document order. + """ + if tag is not None: + tags += (tag,) + return ElementDepthFirstIterator(self, tags) + + def itertext(self, tag=None, *tags, with_tail=True): + """itertext(self, tag=None, *tags, with_tail=True) + + Iterates over the text content of a subtree. + + You can pass tag names to restrict text content to specific elements, + see `iter`. + + You can set the ``with_tail`` keyword argument to ``False`` to skip + over tail text. + """ + if tag is not None: + tags += (tag,) + return ElementTextIterator(self, tags, with_tail=with_tail) + + def makeelement(self, _tag, attrib=None, nsmap=None, **_extra): + """makeelement(self, _tag, attrib=None, nsmap=None, **_extra) + + Creates a new element associated with the same document. + """ + _assertValidDoc(self._doc) + return _makeElement(_tag, NULL, self._doc, None, None, None, + attrib, nsmap, _extra) + + def find(self, path, namespaces=None): + """find(self, path, namespaces=None) + + Finds the first matching subelement, by tag name or path. + + The optional ``namespaces`` argument accepts a + prefix-to-namespace mapping that allows the usage of XPath + prefixes in the path expression. + """ + if isinstance(path, QName): + path = (path).text + return _elementpath.find(self, path, namespaces, with_prefixes=not _isHtmlDocument(self)) + + def findtext(self, path, default=None, namespaces=None): + """findtext(self, path, default=None, namespaces=None) + + Finds text for the first matching subelement, by tag name or path. + + The optional ``namespaces`` argument accepts a + prefix-to-namespace mapping that allows the usage of XPath + prefixes in the path expression. + """ + if isinstance(path, QName): + path = (path).text + return _elementpath.findtext(self, path, default, namespaces, with_prefixes=not _isHtmlDocument(self)) + + def findall(self, path, namespaces=None): + """findall(self, path, namespaces=None) + + Finds all matching subelements, by tag name or path. + + The optional ``namespaces`` argument accepts a + prefix-to-namespace mapping that allows the usage of XPath + prefixes in the path expression. + """ + if isinstance(path, QName): + path = (path).text + return _elementpath.findall(self, path, namespaces, with_prefixes=not _isHtmlDocument(self)) + + def iterfind(self, path, namespaces=None): + """iterfind(self, path, namespaces=None) + + Iterates over all matching subelements, by tag name or path. + + The optional ``namespaces`` argument accepts a + prefix-to-namespace mapping that allows the usage of XPath + prefixes in the path expression. + """ + if isinstance(path, QName): + path = (path).text + return _elementpath.iterfind(self, path, namespaces, with_prefixes=not _isHtmlDocument(self)) + + def xpath(self, _path, *, namespaces=None, extensions=None, + smart_strings=True, **_variables): + """xpath(self, _path, namespaces=None, extensions=None, smart_strings=True, **_variables) + + Evaluate an xpath expression using the element as context node. + """ + evaluator = XPathElementEvaluator(self, namespaces=namespaces, + extensions=extensions, + smart_strings=smart_strings) + return evaluator(_path, **_variables) + + def cssselect(self, expr, *, translator='xml'): + """ + Run the CSS expression on this element and its children, + returning a list of the results. + + Equivalent to lxml.cssselect.CSSSelect(expr)(self) -- note + that pre-compiling the expression can provide a substantial + speedup. + """ + # Do the import here to make the dependency optional. + from lxml.cssselect import CSSSelector + return CSSSelector(expr, translator=translator)(self) + + +@cython.linetrace(False) +cdef _Element _elementFactory(_Document doc, xmlNode* c_node): + cdef _Element result + result = getProxy(c_node) + if result is not None: + return result + if c_node is NULL: + return None + + element_class = LOOKUP_ELEMENT_CLASS( + ELEMENT_CLASS_LOOKUP_STATE, doc, c_node) + if type(element_class) is not type: + if not isinstance(element_class, type): + raise TypeError(f"Element class is not a type, got {type(element_class)}") + if hasProxy(c_node): + # prevent re-entry race condition - we just called into Python + return getProxy(c_node) + result = element_class.__new__(element_class) + if hasProxy(c_node): + # prevent re-entry race condition - we just called into Python + result._c_node = NULL + return getProxy(c_node) + + _registerProxy(result, doc, c_node) + if element_class is not _Element: + result._init() + return result + + +@cython.internal +cdef class __ContentOnlyElement(_Element): + cdef int _raiseImmutable(self) except -1: + raise TypeError, "this element does not have children or attributes" + + def set(self, key, value): + "set(self, key, value)" + self._raiseImmutable() + + def append(self, value): + "append(self, value)" + self._raiseImmutable() + + def insert(self, index, value): + "insert(self, index, value)" + self._raiseImmutable() + + def __setitem__(self, index, value): + "__setitem__(self, index, value)" + self._raiseImmutable() + + @property + def attrib(self): + return IMMUTABLE_EMPTY_MAPPING + + property text: + def __get__(self): + _assertValidNode(self) + return funicodeOrEmpty(self._c_node.content) + + def __set__(self, value): + cdef tree.xmlDict* c_dict + _assertValidNode(self) + if value is None: + c_text = NULL + else: + value = _utf8(value) + c_text = _xcstr(value) + tree.xmlNodeSetContent(self._c_node, c_text) + + # ACCESSORS + def __getitem__(self, x): + "__getitem__(self, x)" + if isinstance(x, slice): + return [] + else: + raise IndexError, "list index out of range" + + def __len__(self): + "__len__(self)" + return 0 + + def get(self, key, default=None): + "get(self, key, default=None)" + return None + + def keys(self): + "keys(self)" + return [] + + def items(self): + "items(self)" + return [] + + def values(self): + "values(self)" + return [] + +cdef class _Comment(__ContentOnlyElement): + @property + def tag(self): + return Comment + + def __repr__(self): + return "" % self.text + +cdef class _ProcessingInstruction(__ContentOnlyElement): + @property + def tag(self): + return ProcessingInstruction + + property target: + # not in ElementTree + def __get__(self): + _assertValidNode(self) + return funicode(self._c_node.name) + + def __set__(self, value): + _assertValidNode(self) + value = _utf8(value) + c_text = _xcstr(value) + tree.xmlNodeSetName(self._c_node, c_text) + + def __repr__(self): + text = self.text + if text: + return "" % (self.target, text) + else: + return "" % self.target + + def get(self, key, default=None): + """get(self, key, default=None) + + Try to parse pseudo-attributes from the text content of the + processing instruction, search for one with the given key as + name and return its associated value. + + Note that this is only a convenience method for the most + common case that all text content is structured in + attribute-like name-value pairs with properly quoted values. + It is not guaranteed to work for all possible text content. + """ + return self.attrib.get(key, default) + + @property + def attrib(self): + """Returns a dict containing all pseudo-attributes that can be + parsed from the text content of this processing instruction. + Note that modifying the dict currently has no effect on the + XML node, although this is not guaranteed to stay this way. + """ + return { attr : (value1 or value2) + for attr, value1, value2 in _FIND_PI_ATTRIBUTES(' ' + self.text) } + +cdef object _FIND_PI_ATTRIBUTES = re.compile(r'\s+(\w+)\s*=\s*(?:\'([^\']*)\'|"([^"]*)")', re.U).findall + +cdef class _Entity(__ContentOnlyElement): + @property + def tag(self): + return Entity + + property name: + # not in ElementTree + def __get__(self): + _assertValidNode(self) + return funicode(self._c_node.name) + + def __set__(self, value): + _assertValidNode(self) + value_utf = _utf8(value) + if b'&' in value_utf or b';' in value_utf: + raise ValueError, f"Invalid entity name '{value}'" + tree.xmlNodeSetName(self._c_node, _xcstr(value_utf)) + + @property + def text(self): + # FIXME: should this be None or '&[VALUE];' or the resolved + # entity value ? + _assertValidNode(self) + return f'&{funicode(self._c_node.name)};' + + def __repr__(self): + return "&%s;" % self.name + + +cdef class QName: + """QName(text_or_uri_or_element, tag=None) + + QName wrapper for qualified XML names. + + Pass a tag name by itself or a namespace URI and a tag name to + create a qualified name. Alternatively, pass an Element to + extract its tag name. ``None`` as first argument is ignored in + order to allow for generic 2-argument usage. + + The ``text`` property holds the qualified name in + ``{namespace}tagname`` notation. The ``namespace`` and + ``localname`` properties hold the respective parts of the tag + name. + + You can pass QName objects wherever a tag name is expected. Also, + setting Element text from a QName will resolve the namespace prefix + on assignment and set a qualified text value. This is helpful in XML + languages like SOAP or XML-Schema that use prefixed tag names in + their text content. + """ + cdef readonly unicode text + cdef readonly unicode localname + cdef readonly unicode namespace + def __init__(self, text_or_uri_or_element, tag=None): + if text_or_uri_or_element is None: + # Allow None as no namespace. + text_or_uri_or_element, tag = tag, None + if not _isString(text_or_uri_or_element): + if isinstance(text_or_uri_or_element, _Element): + text_or_uri_or_element = (<_Element>text_or_uri_or_element).tag + if not _isString(text_or_uri_or_element): + raise ValueError, f"Invalid input tag of type {type(text_or_uri_or_element)!r}" + elif isinstance(text_or_uri_or_element, QName): + text_or_uri_or_element = (text_or_uri_or_element).text + elif text_or_uri_or_element is not None: + text_or_uri_or_element = unicode(text_or_uri_or_element) + else: + raise ValueError, f"Invalid input tag of type {type(text_or_uri_or_element)!r}" + + ns_utf, tag_utf = _getNsTag(text_or_uri_or_element) + if tag is not None: + # either ('ns', 'tag') or ('{ns}oldtag', 'newtag') + if ns_utf is None: + ns_utf = tag_utf # case 1: namespace ended up as tag name + tag_utf = _utf8(tag) + _tagValidOrRaise(tag_utf) + self.localname = (tag_utf).decode('utf8') + if ns_utf is None: + self.namespace = None + self.text = self.localname + else: + self.namespace = (ns_utf).decode('utf8') + self.text = "{%s}%s" % (self.namespace, self.localname) + def __str__(self): + return self.text + def __hash__(self): + return hash(self.text) + def __richcmp__(self, other, int op): + try: + if type(other) is QName: + other = (other).text + elif not isinstance(other, unicode): + other = unicode(other) + except (ValueError, UnicodeDecodeError): + return NotImplemented + return python.PyObject_RichCompare(self.text, other, op) + + +cdef public class _ElementTree [ type LxmlElementTreeType, + object LxmlElementTree ]: + cdef _Document _doc + cdef _Element _context_node + + # Note that _doc is only used to store the original document if we do not + # have a _context_node. All methods should prefer self._context_node._doc + # to honour tree restructuring. _doc can happily be None! + + @cython.final + cdef int _assertHasRoot(self) except -1: + """We have to take care here: the document may not have a root node! + This can happen if ElementTree() is called without any argument and + the caller 'forgets' to call parse() afterwards, so this is a bug in + the caller program. + """ + assert self._context_node is not None, \ + "ElementTree not initialized, missing root" + return 0 + + def parse(self, source, _BaseParser parser=None, *, base_url=None): + """parse(self, source, parser=None, base_url=None) + + Updates self with the content of source and returns its root. + """ + cdef _Document doc = None + try: + doc = _parseDocument(source, parser, base_url) + except _TargetParserResult as result_container: + # raises a TypeError if we don't get an _Element + self._context_node = result_container.result + else: + self._context_node = doc.getroot() + self._doc = None if self._context_node is not None else doc + return self._context_node + + def _setroot(self, _Element root not None): + """_setroot(self, root) + + Relocate the ElementTree to a new root node. + """ + _assertValidNode(root) + if root._c_node.type != tree.XML_ELEMENT_NODE: + raise TypeError, "Only elements can be the root of an ElementTree" + self._context_node = root + self._doc = None + + def getroot(self): + """getroot(self) + + Gets the root element for this tree. + """ + return self._context_node + + def __copy__(self): + return _elementTreeFactory(self._doc, self._context_node) + + def __deepcopy__(self, memo): + cdef _Element root + cdef _Document doc + cdef xmlDoc* c_doc + if self._context_node is not None: + root = self._context_node.__copy__() + assert root is not None + _assertValidNode(root) + _copyNonElementSiblings(self._context_node._c_node, root._c_node) + return _elementTreeFactory(None, root) + elif self._doc is not None: + _assertValidDoc(self._doc) + c_doc = tree.xmlCopyDoc(self._doc._c_doc, 1) + if c_doc is NULL: + raise MemoryError() + doc = _documentFactory(c_doc, self._doc._parser) + return _elementTreeFactory(doc, None) + else: + # so what ... + return self + + # not in ElementTree + @property + def docinfo(self) -> DocInfo: + """Information about the document provided by parser and DTD.""" + self._assertHasRoot() + return DocInfo(self._context_node._doc) + + # not in ElementTree, read-only + @property + def parser(self): + """The parser that was used to parse the document in this ElementTree. + """ + if self._context_node is not None and \ + self._context_node._doc is not None: + return self._context_node._doc._parser + if self._doc is not None: + return self._doc._parser + return None + + def write(self, file, *, encoding=None, method="xml", + bint pretty_print=False, xml_declaration=None, bint with_tail=True, + standalone=None, doctype=None, compression=0, + bint exclusive=False, inclusive_ns_prefixes=None, + bint with_comments=True, bint strip_text=False, + docstring=None): + """write(self, file, encoding=None, method="xml", + pretty_print=False, xml_declaration=None, with_tail=True, + standalone=None, doctype=None, compression=0, + exclusive=False, inclusive_ns_prefixes=None, + with_comments=True, strip_text=False) + + Write the tree to a filename, file or file-like object. + + Defaults to ASCII encoding and writing a declaration as needed. + + The keyword argument 'method' selects the output method: + 'xml', 'html', 'text', 'c14n' or 'c14n2'. Default is 'xml'. + + With ``method="c14n"`` (C14N version 1), the options ``exclusive``, + ``with_comments`` and ``inclusive_ns_prefixes`` request exclusive + C14N, include comments, and list the inclusive prefixes respectively. + + With ``method="c14n2"`` (C14N version 2), the ``with_comments`` and + ``strip_text`` options control the output of comments and text space + according to C14N 2.0. + + Passing a boolean value to the ``standalone`` option will + output an XML declaration with the corresponding + ``standalone`` flag. + + The ``doctype`` option allows passing in a plain string that will + be serialised before the XML tree. Note that passing in non + well-formed content here will make the XML output non well-formed. + Also, an existing doctype in the document tree will not be removed + when serialising an ElementTree instance. + + The ``compression`` option enables GZip compression level 1-9. + + The ``inclusive_ns_prefixes`` should be a list of namespace strings + (i.e. ['xs', 'xsi']) that will be promoted to the top-level element + during exclusive C14N serialisation. This parameter is ignored if + exclusive mode=False. + + If exclusive=True and no list is provided, a namespace will only be + rendered if it is used by the immediate parent or one of its attributes + and its prefix and values have not already been rendered by an ancestor + of the namespace node's parent element. + """ + cdef bint write_declaration + cdef int is_standalone + + self._assertHasRoot() + _assertValidNode(self._context_node) + if compression is None or compression < 0: + compression = 0 + + # C14N serialisation + if method in ('c14n', 'c14n2'): + if encoding is not None: + raise ValueError("Cannot specify encoding with C14N") + if xml_declaration: + raise ValueError("Cannot enable XML declaration in C14N") + + if method == 'c14n': + _tofilelikeC14N(file, self._context_node, exclusive, with_comments, + compression, inclusive_ns_prefixes) + else: # c14n2 + with _open_utf8_file(file, compression=compression) as f: + target = C14NWriterTarget( + f.write, with_comments=with_comments, strip_text=strip_text) + _tree_to_target(self, target) + return + + if not with_comments: + raise ValueError("Can only discard comments in C14N serialisation") + # suppress decl. in default case (purely for ElementTree compatibility) + if xml_declaration is not None: + write_declaration = xml_declaration + if encoding is None: + encoding = 'ASCII' + else: + encoding = encoding.upper() + elif encoding is None: + encoding = 'ASCII' + write_declaration = 0 + else: + encoding = encoding.upper() + write_declaration = encoding not in ( + 'US-ASCII', 'ASCII', 'UTF8', 'UTF-8') + if standalone is None: + is_standalone = -1 + elif standalone: + write_declaration = 1 + is_standalone = 1 + else: + write_declaration = 1 + is_standalone = 0 + + if docstring is not None and doctype is None: + import warnings + warnings.warn( + "The 'docstring' option is deprecated. Use 'doctype' instead.", + DeprecationWarning) + doctype = docstring + + _tofilelike(file, self._context_node, encoding, doctype, method, + write_declaration, 1, pretty_print, with_tail, + is_standalone, compression) + + def getpath(self, _Element element not None): + """getpath(self, element) + + Returns a structural, absolute XPath expression to find the element. + + For namespaced elements, the expression uses prefixes from the + document, which therefore need to be provided in order to make any + use of the expression in XPath. + + Also see the method getelementpath(self, element), which returns a + self-contained ElementPath expression. + """ + cdef _Document doc + cdef _Element root + cdef xmlDoc* c_doc + _assertValidNode(element) + if self._context_node is not None: + root = self._context_node + doc = root._doc + elif self._doc is not None: + doc = self._doc + root = doc.getroot() + else: + raise ValueError, "Element is not in this tree." + _assertValidDoc(doc) + _assertValidNode(root) + if element._doc is not doc: + raise ValueError, "Element is not in this tree." + + c_doc = _fakeRootDoc(doc._c_doc, root._c_node) + c_path = tree.xmlGetNodePath(element._c_node) + _destroyFakeDoc(doc._c_doc, c_doc) + if c_path is NULL: + raise MemoryError() + path = funicode(c_path) + tree.xmlFree(c_path) + return path + + def getelementpath(self, _Element element not None): + """getelementpath(self, element) + + Returns a structural, absolute ElementPath expression to find the + element. This path can be used in the .find() method to look up + the element, provided that the elements along the path and their + list of immediate children were not modified in between. + + ElementPath has the advantage over an XPath expression (as returned + by the .getpath() method) that it does not require additional prefix + declarations. It is always self-contained. + """ + cdef _Element root + cdef Py_ssize_t count + _assertValidNode(element) + if element._c_node.type != tree.XML_ELEMENT_NODE: + raise ValueError, "input is not an Element" + if self._context_node is not None: + root = self._context_node + elif self._doc is not None: + root = self._doc.getroot() + else: + raise ValueError, "Element is not in this tree" + _assertValidNode(root) + if element._doc is not root._doc: + raise ValueError, "Element is not in this tree" + + path = [] + c_element = element._c_node + while c_element is not root._c_node: + c_name = c_element.name + c_href = _getNs(c_element) + tag = _namespacedNameFromNsName(c_href, c_name) + if c_href is NULL: + c_href = b'' # no namespace (NULL is wildcard) + # use tag[N] if there are preceding siblings with the same tag + count = 0 + c_node = c_element.prev + while c_node is not NULL: + if c_node.type == tree.XML_ELEMENT_NODE: + if _tagMatches(c_node, c_href, c_name): + count += 1 + c_node = c_node.prev + if count: + tag = f'{tag}[{count+1}]' + else: + # use tag[1] if there are following siblings with the same tag + c_node = c_element.next + while c_node is not NULL: + if c_node.type == tree.XML_ELEMENT_NODE: + if _tagMatches(c_node, c_href, c_name): + tag += '[1]' + break + c_node = c_node.next + + path.append(tag) + c_element = c_element.parent + if c_element is NULL or c_element.type != tree.XML_ELEMENT_NODE: + raise ValueError, "Element is not in this tree." + if not path: + return '.' + path.reverse() + return '/'.join(path) + + def getiterator(self, tag=None, *tags): + """getiterator(self, *tags, tag=None) + + Returns a sequence or iterator of all elements in document order + (depth first pre-order), starting with the root element. + + Can be restricted to find only elements with specific tags, + see `_Element.iter`. + + :deprecated: Note that this method is deprecated as of + ElementTree 1.3 and lxml 2.0. It returns an iterator in + lxml, which diverges from the original ElementTree + behaviour. If you want an efficient iterator, use the + ``tree.iter()`` method instead. You should only use this + method in new code if you require backwards compatibility + with older versions of lxml or ElementTree. + """ + root = self.getroot() + if root is None: + return ITER_EMPTY + if tag is not None: + tags += (tag,) + return root.getiterator(*tags) + + def iter(self, tag=None, *tags): + """iter(self, tag=None, *tags) + + Creates an iterator for the root element. The iterator loops over + all elements in this tree, in document order. Note that siblings + of the root element (comments or processing instructions) are not + returned by the iterator. + + Can be restricted to find only elements with specific tags, + see `_Element.iter`. + """ + root = self.getroot() + if root is None: + return ITER_EMPTY + if tag is not None: + tags += (tag,) + return root.iter(*tags) + + def find(self, path, namespaces=None): + """find(self, path, namespaces=None) + + Finds the first toplevel element with given tag. Same as + ``tree.getroot().find(path)``. + + The optional ``namespaces`` argument accepts a + prefix-to-namespace mapping that allows the usage of XPath + prefixes in the path expression. + """ + self._assertHasRoot() + root = self.getroot() + if _isString(path): + if path[:1] == "/": + path = "." + path + from warnings import warn + warn( + "This search incorrectly ignores the root element, and will be " + "fixed in a future version. If you rely on the current " + f"behaviour, change it to {path!r}", + FutureWarning, stacklevel=1 + ) + return root.find(path, namespaces) + + def findtext(self, path, default=None, namespaces=None): + """findtext(self, path, default=None, namespaces=None) + + Finds the text for the first element matching the ElementPath + expression. Same as getroot().findtext(path) + + The optional ``namespaces`` argument accepts a + prefix-to-namespace mapping that allows the usage of XPath + prefixes in the path expression. + """ + self._assertHasRoot() + root = self.getroot() + if _isString(path): + if path[:1] == "/": + path = "." + path + from warnings import warn + warn( + "This search incorrectly ignores the root element, and will be " + "fixed in a future version. If you rely on the current " + f"behaviour, change it to {path!r}", + FutureWarning, stacklevel=1 + ) + return root.findtext(path, default, namespaces) + + def findall(self, path, namespaces=None): + """findall(self, path, namespaces=None) + + Finds all elements matching the ElementPath expression. Same as + getroot().findall(path). + + The optional ``namespaces`` argument accepts a + prefix-to-namespace mapping that allows the usage of XPath + prefixes in the path expression. + """ + self._assertHasRoot() + root = self.getroot() + if _isString(path): + if path[:1] == "/": + path = "." + path + from warnings import warn + warn( + "This search incorrectly ignores the root element, and will be " + "fixed in a future version. If you rely on the current " + f"behaviour, change it to {path!r}", + FutureWarning, stacklevel=1 + ) + return root.findall(path, namespaces) + + def iterfind(self, path, namespaces=None): + """iterfind(self, path, namespaces=None) + + Iterates over all elements matching the ElementPath expression. + Same as getroot().iterfind(path). + + The optional ``namespaces`` argument accepts a + prefix-to-namespace mapping that allows the usage of XPath + prefixes in the path expression. + """ + self._assertHasRoot() + root = self.getroot() + if _isString(path): + if path[:1] == "/": + path = "." + path + from warnings import warn + warn( + "This search incorrectly ignores the root element, and will be " + "fixed in a future version. If you rely on the current " + f"behaviour, change it to {path!r}", + FutureWarning, stacklevel=1 + ) + return root.iterfind(path, namespaces) + + def xpath(self, _path, *, namespaces=None, extensions=None, + smart_strings=True, **_variables): + """xpath(self, _path, namespaces=None, extensions=None, smart_strings=True, **_variables) + + XPath evaluate in context of document. + + ``namespaces`` is an optional dictionary with prefix to namespace URI + mappings, used by XPath. ``extensions`` defines additional extension + functions. + + Returns a list (nodeset), or bool, float or string. + + In case of a list result, return Element for element nodes, + string for text and attribute values. + + Note: if you are going to apply multiple XPath expressions + against the same document, it is more efficient to use + XPathEvaluator directly. + """ + self._assertHasRoot() + evaluator = XPathDocumentEvaluator(self, namespaces=namespaces, + extensions=extensions, + smart_strings=smart_strings) + return evaluator(_path, **_variables) + + def xslt(self, _xslt, extensions=None, access_control=None, **_kw): + """xslt(self, _xslt, extensions=None, access_control=None, **_kw) + + Transform this document using other document. + + xslt is a tree that should be XSLT + keyword parameters are XSLT transformation parameters. + + Returns the transformed tree. + + Note: if you are going to apply the same XSLT stylesheet against + multiple documents, it is more efficient to use the XSLT + class directly. + """ + self._assertHasRoot() + style = XSLT(_xslt, extensions=extensions, + access_control=access_control) + return style(self, **_kw) + + def relaxng(self, relaxng): + """relaxng(self, relaxng) + + Validate this document using other document. + + The relaxng argument is a tree that should contain a Relax NG schema. + + Returns True or False, depending on whether validation + succeeded. + + Note: if you are going to apply the same Relax NG schema against + multiple documents, it is more efficient to use the RelaxNG + class directly. + """ + self._assertHasRoot() + schema = RelaxNG(relaxng) + return schema.validate(self) + + def xmlschema(self, xmlschema): + """xmlschema(self, xmlschema) + + Validate this document using other document. + + The xmlschema argument is a tree that should contain an XML Schema. + + Returns True or False, depending on whether validation + succeeded. + + Note: If you are going to apply the same XML Schema against + multiple documents, it is more efficient to use the XMLSchema + class directly. + """ + self._assertHasRoot() + schema = XMLSchema(xmlschema) + return schema.validate(self) + + def xinclude(self): + """xinclude(self) + + Process the XInclude nodes in this document and include the + referenced XML fragments. + + There is support for loading files through the file system, HTTP and + FTP. + + Note that XInclude does not support custom resolvers in Python space + due to restrictions of libxml2 <= 2.6.29. + """ + self._assertHasRoot() + XInclude()(self._context_node) + + def write_c14n(self, file, *, bint exclusive=False, bint with_comments=True, + compression=0, inclusive_ns_prefixes=None): + """write_c14n(self, file, exclusive=False, with_comments=True, + compression=0, inclusive_ns_prefixes=None) + + C14N write of document. Always writes UTF-8. + + The ``compression`` option enables GZip compression level 1-9. + + The ``inclusive_ns_prefixes`` should be a list of namespace strings + (i.e. ['xs', 'xsi']) that will be promoted to the top-level element + during exclusive C14N serialisation. This parameter is ignored if + exclusive mode=False. + + If exclusive=True and no list is provided, a namespace will only be + rendered if it is used by the immediate parent or one of its attributes + and its prefix and values have not already been rendered by an ancestor + of the namespace node's parent element. + + NOTE: This method is deprecated as of lxml 4.4 and will be removed in a + future release. Use ``.write(f, method="c14n")`` instead. + """ + self._assertHasRoot() + _assertValidNode(self._context_node) + if compression is None or compression < 0: + compression = 0 + + _tofilelikeC14N(file, self._context_node, exclusive, with_comments, + compression, inclusive_ns_prefixes) + +cdef _ElementTree _elementTreeFactory(_Document doc, _Element context_node): + return _newElementTree(doc, context_node, _ElementTree) + +cdef _ElementTree _newElementTree(_Document doc, _Element context_node, + object baseclass): + cdef _ElementTree result + result = baseclass() + if context_node is None and doc is not None: + context_node = doc.getroot() + if context_node is None: + _assertValidDoc(doc) + result._doc = doc + else: + _assertValidNode(context_node) + result._context_node = context_node + return result + + +@cython.final +@cython.freelist(16) +cdef class _Attrib: + """A dict-like proxy for the ``Element.attrib`` property. + """ + cdef _Element _element + def __cinit__(self, _Element element not None): + _assertValidNode(element) + self._element = element + + # MANIPULATORS + def __setitem__(self, key, value): + _assertValidNode(self._element) + _setAttributeValue(self._element, key, value) + + def __delitem__(self, key): + _assertValidNode(self._element) + _delAttribute(self._element, key) + + def update(self, sequence_or_dict): + _assertValidNode(self._element) + if isinstance(sequence_or_dict, (dict, _Attrib)): + sequence_or_dict = sequence_or_dict.items() + for key, value in sequence_or_dict: + _setAttributeValue(self._element, key, value) + + def pop(self, key, *default): + if len(default) > 1: + raise TypeError, f"pop expected at most 2 arguments, got {len(default)+1}" + _assertValidNode(self._element) + result = _getAttributeValue(self._element, key, None) + if result is None: + if not default: + raise KeyError, key + result = default[0] + else: + _delAttribute(self._element, key) + return result + + def clear(self): + _assertValidNode(self._element) + c_attrs = self._element._c_node.properties + if c_attrs: + self._element._c_node.properties = NULL + tree.xmlFreePropList(c_attrs) + + # ACCESSORS + def __repr__(self): + _assertValidNode(self._element) + return repr(dict( _collectAttributes(self._element._c_node, 3) )) + + def __copy__(self): + _assertValidNode(self._element) + return dict(_collectAttributes(self._element._c_node, 3)) + + def __deepcopy__(self, memo): + _assertValidNode(self._element) + return dict(_collectAttributes(self._element._c_node, 3)) + + def __getitem__(self, key): + _assertValidNode(self._element) + result = _getAttributeValue(self._element, key, None) + if result is None: + raise KeyError, key + return result + + def __bool__(self): + _assertValidNode(self._element) + cdef xmlAttr* c_attr = self._element._c_node.properties + while c_attr is not NULL: + if c_attr.type == tree.XML_ATTRIBUTE_NODE: + return 1 + c_attr = c_attr.next + return 0 + + def __len__(self): + _assertValidNode(self._element) + cdef xmlAttr* c_attr = self._element._c_node.properties + cdef Py_ssize_t c = 0 + while c_attr is not NULL: + if c_attr.type == tree.XML_ATTRIBUTE_NODE: + c += 1 + c_attr = c_attr.next + return c + + def get(self, key, default=None): + _assertValidNode(self._element) + return _getAttributeValue(self._element, key, default) + + def keys(self): + _assertValidNode(self._element) + return _collectAttributes(self._element._c_node, 1) + + def __iter__(self): + _assertValidNode(self._element) + return iter(_collectAttributes(self._element._c_node, 1)) + + def iterkeys(self): + _assertValidNode(self._element) + return iter(_collectAttributes(self._element._c_node, 1)) + + def values(self): + _assertValidNode(self._element) + return _collectAttributes(self._element._c_node, 2) + + def itervalues(self): + _assertValidNode(self._element) + return iter(_collectAttributes(self._element._c_node, 2)) + + def items(self): + _assertValidNode(self._element) + return _collectAttributes(self._element._c_node, 3) + + def iteritems(self): + _assertValidNode(self._element) + return iter(_collectAttributes(self._element._c_node, 3)) + + def has_key(self, key): + _assertValidNode(self._element) + return key in self + + def __contains__(self, key): + _assertValidNode(self._element) + cdef xmlNode* c_node + ns, tag = _getNsTag(key) + c_node = self._element._c_node + c_href = NULL if ns is None else _xcstr(ns) + return 1 if tree.xmlHasNsProp(c_node, _xcstr(tag), c_href) else 0 + + def __richcmp__(self, other, int op): + try: + one = dict(self.items()) + if not isinstance(other, dict): + other = dict(other) + except (TypeError, ValueError): + return NotImplemented + return python.PyObject_RichCompare(one, other, op) + +MutableMapping.register(_Attrib) + + +@cython.final +@cython.internal +cdef class _AttribIterator: + """Attribute iterator - for internal use only! + """ + # XML attributes must not be removed while running! + cdef _Element _node + cdef xmlAttr* _c_attr + cdef int _keysvalues # 1 - keys, 2 - values, 3 - items (key, value) + def __iter__(self): + return self + + def __next__(self): + cdef xmlAttr* c_attr + if self._node is None: + raise StopIteration + c_attr = self._c_attr + while c_attr is not NULL and c_attr.type != tree.XML_ATTRIBUTE_NODE: + c_attr = c_attr.next + if c_attr is NULL: + self._node = None + raise StopIteration + + self._c_attr = c_attr.next + if self._keysvalues == 1: + return _namespacedName(c_attr) + elif self._keysvalues == 2: + return _attributeValue(self._node._c_node, c_attr) + else: + return (_namespacedName(c_attr), + _attributeValue(self._node._c_node, c_attr)) + +cdef object _attributeIteratorFactory(_Element element, int keysvalues): + cdef _AttribIterator attribs + if element._c_node.properties is NULL: + return ITER_EMPTY + attribs = _AttribIterator() + attribs._node = element + attribs._c_attr = element._c_node.properties + attribs._keysvalues = keysvalues + return attribs + + +cdef public class _ElementTagMatcher [ object LxmlElementTagMatcher, + type LxmlElementTagMatcherType ]: + """ + Dead but public. :) + """ + cdef object _pystrings + cdef int _node_type + cdef char* _href + cdef char* _name + cdef _initTagMatch(self, tag): + self._href = NULL + self._name = NULL + if tag is None: + self._node_type = 0 + elif tag is Comment: + self._node_type = tree.XML_COMMENT_NODE + elif tag is ProcessingInstruction: + self._node_type = tree.XML_PI_NODE + elif tag is Entity: + self._node_type = tree.XML_ENTITY_REF_NODE + elif tag is Element: + self._node_type = tree.XML_ELEMENT_NODE + else: + self._node_type = tree.XML_ELEMENT_NODE + self._pystrings = _getNsTag(tag) + if self._pystrings[0] is not None: + self._href = _cstr(self._pystrings[0]) + self._name = _cstr(self._pystrings[1]) + if self._name[0] == c'*' and self._name[1] == c'\0': + self._name = NULL + +cdef public class _ElementIterator(_ElementTagMatcher) [ + object LxmlElementIterator, type LxmlElementIteratorType ]: + """ + Dead but public. :) + """ + # we keep Python references here to control GC + cdef _Element _node + cdef _node_to_node_function _next_element + def __iter__(self): + return self + + cdef void _storeNext(self, _Element node): + cdef xmlNode* c_node + c_node = self._next_element(node._c_node) + while c_node is not NULL and \ + self._node_type != 0 and \ + (self._node_type != c_node.type or + not _tagMatches(c_node, self._href, self._name)): + c_node = self._next_element(c_node) + if c_node is NULL: + self._node = None + else: + # Python ref: + self._node = _elementFactory(node._doc, c_node) + + def __next__(self): + cdef xmlNode* c_node + cdef _Element current_node + if self._node is None: + raise StopIteration + # Python ref: + current_node = self._node + self._storeNext(current_node) + return current_node + +@cython.final +@cython.internal +cdef class _MultiTagMatcher: + """ + Match an xmlNode against a list of tags. + """ + cdef list _py_tags + cdef qname* _cached_tags + cdef size_t _tag_count + cdef size_t _cached_size + cdef _Document _cached_doc + cdef int _node_types + + def __cinit__(self, tags): + self._py_tags = [] + self.initTagMatch(tags) + + def __dealloc__(self): + self._clear() + + cdef bint rejectsAll(self) noexcept: + return not self._tag_count and not self._node_types + + cdef bint rejectsAllAttributes(self) noexcept: + return not self._tag_count + + cdef bint matchesType(self, int node_type) noexcept: + if node_type == tree.XML_ELEMENT_NODE and self._tag_count: + return True + return self._node_types & (1 << node_type) + + cdef void _clear(self) noexcept: + cdef size_t i, count + count = self._tag_count + self._tag_count = 0 + if self._cached_tags: + for i in range(count): + cpython.ref.Py_XDECREF(self._cached_tags[i].href) + python.lxml_free(self._cached_tags) + self._cached_tags = NULL + + cdef initTagMatch(self, tags): + self._cached_doc = None + del self._py_tags[:] + self._clear() + if tags is None or tags == (): + # no selection in tags argument => match anything + self._node_types = ( + 1 << tree.XML_COMMENT_NODE | + 1 << tree.XML_PI_NODE | + 1 << tree.XML_ENTITY_REF_NODE | + 1 << tree.XML_ELEMENT_NODE) + else: + self._node_types = 0 + self._storeTags(tags, set()) + + cdef _storeTags(self, tag, set seen): + if tag is Comment: + self._node_types |= 1 << tree.XML_COMMENT_NODE + elif tag is ProcessingInstruction: + self._node_types |= 1 << tree.XML_PI_NODE + elif tag is Entity: + self._node_types |= 1 << tree.XML_ENTITY_REF_NODE + elif tag is Element: + self._node_types |= 1 << tree.XML_ELEMENT_NODE + elif python._isString(tag): + if tag in seen: + return + seen.add(tag) + if tag in ('*', '{*}*'): + self._node_types |= 1 << tree.XML_ELEMENT_NODE + else: + href, name = _getNsTag(tag) + if name == b'*': + name = None + if href is None: + href = b'' # no namespace + elif href == b'*': + href = None # wildcard: any namespace, including none + self._py_tags.append((href, name)) + elif isinstance(tag, QName): + self._storeTags(tag.text, seen) + else: + # support a sequence of tags + for item in tag: + self._storeTags(item, seen) + + cdef inline int cacheTags(self, _Document doc, bint force_into_dict=False) except -1: + """ + Look up the tag names in the doc dict to enable string pointer comparisons. + """ + cdef size_t dict_size = tree.xmlDictSize(doc._c_doc.dict) + if doc is self._cached_doc and dict_size == self._cached_size: + # doc and dict didn't change => names already cached + return 0 + self._tag_count = 0 + if not self._py_tags: + self._cached_doc = doc + self._cached_size = dict_size + return 0 + if not self._cached_tags: + self._cached_tags = python.lxml_malloc(len(self._py_tags), sizeof(qname)) + if not self._cached_tags: + self._cached_doc = None + raise MemoryError() + self._tag_count = _mapTagsToQnameMatchArray( + doc._c_doc, self._py_tags, self._cached_tags, force_into_dict) + self._cached_doc = doc + self._cached_size = dict_size + return 0 + + cdef inline bint matches(self, xmlNode* c_node) noexcept: + cdef qname* c_qname + if self._node_types & (1 << c_node.type): + return True + elif c_node.type == tree.XML_ELEMENT_NODE: + for c_qname in self._cached_tags[:self._tag_count]: + if _tagMatchesExactly(c_node, c_qname): + return True + return False + + cdef inline bint matchesNsTag(self, const_xmlChar* c_href, + const_xmlChar* c_name) noexcept: + cdef qname* c_qname + if self._node_types & (1 << tree.XML_ELEMENT_NODE): + return True + for c_qname in self._cached_tags[:self._tag_count]: + if _nsTagMatchesExactly(c_href, c_name, c_qname): + return True + return False + + cdef inline bint matchesAttribute(self, xmlAttr* c_attr) noexcept: + """Attribute matches differ from Element matches in that they do + not care about node types. + """ + cdef qname* c_qname + for c_qname in self._cached_tags[:self._tag_count]: + if _tagMatchesExactly(c_attr, c_qname): + return True + return False + +cdef class _ElementMatchIterator: + cdef _Element _node + cdef _node_to_node_function _next_element + cdef _MultiTagMatcher _matcher + + @cython.final + cdef _initTagMatcher(self, tags): + self._matcher = _MultiTagMatcher.__new__(_MultiTagMatcher, tags) + + def __iter__(self): + return self + + @cython.final + cdef int _storeNext(self, _Element node) except -1: + self._matcher.cacheTags(node._doc) + c_node = self._next_element(node._c_node) + while c_node is not NULL and not self._matcher.matches(c_node): + c_node = self._next_element(c_node) + # store Python ref to next node to make sure it's kept alive + self._node = _elementFactory(node._doc, c_node) if c_node is not NULL else None + return 0 + + def __next__(self): + cdef _Element current_node = self._node + if current_node is None: + raise StopIteration + self._storeNext(current_node) + return current_node + +cdef class ElementChildIterator(_ElementMatchIterator): + """ElementChildIterator(self, node, tag=None, reversed=False) + Iterates over the children of an element. + """ + def __cinit__(self, _Element node not None, tag=None, *, bint reversed=False): + cdef xmlNode* c_node + _assertValidNode(node) + self._initTagMatcher(tag) + if reversed: + c_node = _findChildBackwards(node._c_node, 0) + self._next_element = _previousElement + else: + c_node = _findChildForwards(node._c_node, 0) + self._next_element = _nextElement + self._matcher.cacheTags(node._doc) + while c_node is not NULL and not self._matcher.matches(c_node): + c_node = self._next_element(c_node) + # store Python ref to next node to make sure it's kept alive + self._node = _elementFactory(node._doc, c_node) if c_node is not NULL else None + +cdef class SiblingsIterator(_ElementMatchIterator): + """SiblingsIterator(self, node, tag=None, preceding=False) + Iterates over the siblings of an element. + + You can pass the boolean keyword ``preceding`` to specify the direction. + """ + def __cinit__(self, _Element node not None, tag=None, *, bint preceding=False): + _assertValidNode(node) + self._initTagMatcher(tag) + if preceding: + self._next_element = _previousElement + else: + self._next_element = _nextElement + self._storeNext(node) + +cdef class AncestorsIterator(_ElementMatchIterator): + """AncestorsIterator(self, node, tag=None) + Iterates over the ancestors of an element (from parent to parent). + """ + def __cinit__(self, _Element node not None, tag=None): + _assertValidNode(node) + self._initTagMatcher(tag) + self._next_element = _parentElement + self._storeNext(node) + +cdef class ElementDepthFirstIterator: + """ElementDepthFirstIterator(self, node, tag=None, inclusive=True) + Iterates over an element and its sub-elements in document order (depth + first pre-order). + + Note that this also includes comments, entities and processing + instructions. To filter them out, check if the ``tag`` property + of the returned element is a string (i.e. not None and not a + factory function), or pass the ``Element`` factory for the ``tag`` + argument to receive only Elements. + + If the optional ``tag`` argument is not None, the iterator returns only + the elements that match the respective name and namespace. + + The optional boolean argument 'inclusive' defaults to True and can be set + to False to exclude the start element itself. + + Note that the behaviour of this iterator is completely undefined if the + tree it traverses is modified during iteration. + """ + # we keep Python references here to control GC + # keep the next Element after the one we return, and the (s)top node + cdef _Element _next_node + cdef _Element _top_node + cdef _MultiTagMatcher _matcher + def __cinit__(self, _Element node not None, tag=None, *, bint inclusive=True): + _assertValidNode(node) + self._top_node = node + self._next_node = node + self._matcher = _MultiTagMatcher.__new__(_MultiTagMatcher, tag) + self._matcher.cacheTags(node._doc) + if not inclusive or not self._matcher.matches(node._c_node): + # find start node (this cannot raise StopIteration, self._next_node != None) + next(self) + + def __iter__(self): + return self + + def __next__(self): + cdef xmlNode* c_node + cdef _Element current_node = self._next_node + if current_node is None: + raise StopIteration + c_node = current_node._c_node + self._matcher.cacheTags(current_node._doc) + if not self._matcher._tag_count: + # no tag name was found in the dict => not in document either + # try to match by node type + c_node = self._nextNodeAnyTag(c_node) + else: + c_node = self._nextNodeMatchTag(c_node) + if c_node is NULL: + self._next_node = None + else: + self._next_node = _elementFactory(current_node._doc, c_node) + return current_node + + @cython.final + cdef xmlNode* _nextNodeAnyTag(self, xmlNode* c_node) noexcept: + cdef int node_types = self._matcher._node_types + if not node_types: + return NULL + tree.BEGIN_FOR_EACH_ELEMENT_FROM(self._top_node._c_node, c_node, 0) + if node_types & (1 << c_node.type): + return c_node + tree.END_FOR_EACH_ELEMENT_FROM(c_node) + return NULL + + @cython.final + cdef xmlNode* _nextNodeMatchTag(self, xmlNode* c_node) noexcept: + tree.BEGIN_FOR_EACH_ELEMENT_FROM(self._top_node._c_node, c_node, 0) + if self._matcher.matches(c_node): + return c_node + tree.END_FOR_EACH_ELEMENT_FROM(c_node) + return NULL + + +cdef class ElementTextIterator: + """ElementTextIterator(self, element, tag=None, with_tail=True) + Iterates over the text content of a subtree. + + You can pass the ``tag`` keyword argument to restrict text content to a + specific tag name. + + You can set the ``with_tail`` keyword argument to ``False`` to skip over + tail text (e.g. if you know that it's only whitespace from pretty-printing). + """ + cdef object _events + cdef _Element _start_element + def __cinit__(self, _Element element not None, tag=None, *, bint with_tail=True): + _assertValidNode(element) + if with_tail: + events = ("start", "comment", "pi", "end") + else: + events = ("start",) + self._start_element = element + self._events = iterwalk(element, events=events, tag=tag) + + def __iter__(self): + return self + + def __next__(self): + cdef _Element element + result = None + while result is None: + event, element = next(self._events) # raises StopIteration + if event == "start": + result = element.text + elif element is not self._start_element: + result = element.tail + return result + + +cdef xmlNode* _createElement(xmlDoc* c_doc, object name_utf) except NULL: + cdef xmlNode* c_node + c_node = tree.xmlNewDocNode(c_doc, NULL, _xcstr(name_utf), NULL) + return c_node + +cdef xmlNode* _createComment(xmlDoc* c_doc, const_xmlChar* text) noexcept: + cdef xmlNode* c_node + c_node = tree.xmlNewDocComment(c_doc, text) + return c_node + +cdef xmlNode* _createPI(xmlDoc* c_doc, const_xmlChar* target, const_xmlChar* text) noexcept: + cdef xmlNode* c_node + c_node = tree.xmlNewDocPI(c_doc, target, text) + return c_node + +cdef xmlNode* _createEntity(xmlDoc* c_doc, const_xmlChar* name) noexcept: + cdef xmlNode* c_node + c_node = tree.xmlNewReference(c_doc, name) + return c_node + +# module-level API for ElementTree + +from abc import ABC + +class Element(ABC): + """Element(_tag, attrib=None, nsmap=None, **_extra) + + Element factory, as a class. + + An instance of this class is an object implementing the + Element interface. + + >>> element = Element("test") + >>> type(element) + + >>> isinstance(element, Element) + True + >>> issubclass(_Element, Element) + True + + Also look at the `_Element.makeelement()` and + `_BaseParser.makeelement()` methods, which provide a faster way to + create an Element within a specific document or parser context. + """ + def __new__(cls, _tag, attrib=None, nsmap=None, **_extra): + return _makeElement(_tag, NULL, None, None, None, None, + attrib, nsmap, _extra) + +# Register _Element as a virtual subclass of Element +Element.register(_Element) + + +def Comment(text=None): + """Comment(text=None) + + Comment element factory. This factory function creates a special element that will + be serialized as an XML comment. + """ + cdef _Document doc + cdef xmlNode* c_node + cdef xmlDoc* c_doc + + if text is None: + text = b'' + else: + text = _utf8(text) + if b'--' in text or text.endswith(b'-'): + raise ValueError("Comment may not contain '--' or end with '-'") + + c_doc = _newXMLDoc() + doc = _documentFactory(c_doc, None) + c_node = _createComment(c_doc, _xcstr(text)) + tree.xmlAddChild(c_doc, c_node) + return _elementFactory(doc, c_node) + + +def ProcessingInstruction(target, text=None): + """ProcessingInstruction(target, text=None) + + ProcessingInstruction element factory. This factory function creates a + special element that will be serialized as an XML processing instruction. + """ + cdef _Document doc + cdef xmlNode* c_node + cdef xmlDoc* c_doc + + target = _utf8(target) + _tagValidOrRaise(target) + if target.lower() == b'xml': + raise ValueError, f"Invalid PI name '{target}'" + + if text is None: + text = b'' + else: + text = _utf8(text) + if b'?>' in text: + raise ValueError, "PI text must not contain '?>'" + + c_doc = _newXMLDoc() + doc = _documentFactory(c_doc, None) + c_node = _createPI(c_doc, _xcstr(target), _xcstr(text)) + tree.xmlAddChild(c_doc, c_node) + return _elementFactory(doc, c_node) + +PI = ProcessingInstruction + + +cdef class CDATA: + """CDATA(data) + + CDATA factory. This factory creates an opaque data object that + can be used to set Element text. The usual way to use it is:: + + >>> el = Element('content') + >>> el.text = CDATA('a string') + + >>> print(el.text) + a string + >>> print(tostring(el, encoding="unicode")) + + """ + cdef bytes _utf8_data + def __cinit__(self, data): + self._utf8_data = _utf8(data) + + +def Entity(name): + """Entity(name) + + Entity factory. This factory function creates a special element + that will be serialized as an XML entity reference or character + reference. Note, however, that entities will not be automatically + declared in the document. A document that uses entity references + requires a DTD to define the entities. + """ + cdef _Document doc + cdef xmlNode* c_node + cdef xmlDoc* c_doc + name_utf = _utf8(name) + c_name = _xcstr(name_utf) + if c_name[0] == c'#': + if not _characterReferenceIsValid(c_name + 1): + raise ValueError, f"Invalid character reference: '{name}'" + elif not _xmlNameIsValid(c_name): + raise ValueError, f"Invalid entity reference: '{name}'" + c_doc = _newXMLDoc() + doc = _documentFactory(c_doc, None) + c_node = _createEntity(c_doc, c_name) + tree.xmlAddChild(c_doc, c_node) + return _elementFactory(doc, c_node) + + +def SubElement(_Element _parent not None, _tag, + attrib=None, nsmap=None, **_extra): + """SubElement(_parent, _tag, attrib=None, nsmap=None, **_extra) + + Subelement factory. This function creates an element instance, and + appends it to an existing element. + """ + return _makeSubElement(_parent, _tag, None, None, attrib, nsmap, _extra) + +from typing import Generic, TypeVar + +T = TypeVar("T") + +class ElementTree(ABC, Generic[T]): + def __new__(cls, _Element element=None, *, file=None, _BaseParser parser=None): + """ElementTree(element=None, file=None, parser=None) + + ElementTree wrapper class. + """ + cdef xmlNode* c_next + cdef xmlNode* c_node + cdef xmlNode* c_node_copy + cdef xmlDoc* c_doc + cdef _ElementTree etree + cdef _Document doc + + if element is not None: + doc = element._doc + elif file is not None: + try: + doc = _parseDocument(file, parser, None) + except _TargetParserResult as result_container: + return result_container.result + else: + c_doc = _newXMLDoc() + doc = _documentFactory(c_doc, parser) + + return _elementTreeFactory(doc, element) + +# Register _ElementTree as a virtual subclass of ElementTree +ElementTree.register(_ElementTree) + +# Remove "ABC" and typing helpers from module dict +del ABC, Generic, TypeVar, T + +def HTML(text, _BaseParser parser=None, *, base_url=None): + """HTML(text, parser=None, base_url=None) + + Parses an HTML document from a string constant. Returns the root + node (or the result returned by a parser target). This function + can be used to embed "HTML literals" in Python code. + + To override the parser with a different ``HTMLParser`` you can pass it to + the ``parser`` keyword argument. + + The ``base_url`` keyword argument allows to set the original base URL of + the document to support relative Paths when looking up external entities + (DTD, XInclude, ...). + """ + cdef _Document doc + if parser is None: + parser = __GLOBAL_PARSER_CONTEXT.getDefaultParser() + if not isinstance(parser, HTMLParser): + parser = __DEFAULT_HTML_PARSER + try: + doc = _parseMemoryDocument(text, base_url, parser) + return doc.getroot() + except _TargetParserResult as result_container: + return result_container.result + + +def XML(text, _BaseParser parser=None, *, base_url=None): + """XML(text, parser=None, base_url=None) + + Parses an XML document or fragment from a string constant. + Returns the root node (or the result returned by a parser target). + This function can be used to embed "XML literals" in Python code, + like in + + >>> root = XML("") + >>> print(root.tag) + root + + To override the parser with a different ``XMLParser`` you can pass it to + the ``parser`` keyword argument. + + The ``base_url`` keyword argument allows to set the original base URL of + the document to support relative Paths when looking up external entities + (DTD, XInclude, ...). + """ + cdef _Document doc + if parser is None: + parser = __GLOBAL_PARSER_CONTEXT.getDefaultParser() + if not isinstance(parser, XMLParser): + parser = __DEFAULT_XML_PARSER + try: + doc = _parseMemoryDocument(text, base_url, parser) + return doc.getroot() + except _TargetParserResult as result_container: + return result_container.result + + +def fromstring(text, _BaseParser parser=None, *, base_url=None): + """fromstring(text, parser=None, base_url=None) + + Parses an XML document or fragment from a string. Returns the + root node (or the result returned by a parser target). + + To override the default parser with a different parser you can pass it to + the ``parser`` keyword argument. + + The ``base_url`` keyword argument allows to set the original base URL of + the document to support relative Paths when looking up external entities + (DTD, XInclude, ...). + """ + cdef _Document doc + try: + doc = _parseMemoryDocument(text, base_url, parser) + return doc.getroot() + except _TargetParserResult as result_container: + return result_container.result + + +def fromstringlist(strings, _BaseParser parser=None): + """fromstringlist(strings, parser=None) + + Parses an XML document from a sequence of strings. Returns the + root node (or the result returned by a parser target). + + To override the default parser with a different parser you can pass it to + the ``parser`` keyword argument. + """ + cdef _Document doc + if isinstance(strings, (bytes, unicode)): + raise ValueError("passing a single string into fromstringlist() is not" + " efficient, use fromstring() instead") + if parser is None: + parser = __GLOBAL_PARSER_CONTEXT.getDefaultParser() + feed = parser.feed + for data in strings: + feed(data) + return parser.close() + + +def iselement(element): + """iselement(element) + + Checks if an object appears to be a valid element object. + """ + return isinstance(element, _Element) and (<_Element>element)._c_node is not NULL + + +def indent(tree, space=" ", *, Py_ssize_t level=0): + """indent(tree, space=" ", level=0) + + Indent an XML document by inserting newlines and indentation space + after elements. + + *tree* is the ElementTree or Element to modify. The (root) element + itself will not be changed, but the tail text of all elements in its + subtree will be adapted. + + *space* is the whitespace to insert for each indentation level, two + space characters by default. + + *level* is the initial indentation level. Setting this to a higher + value than 0 can be used for indenting subtrees that are more deeply + nested inside of a document. + """ + root = _rootNodeOrRaise(tree) + if level < 0: + raise ValueError(f"Initial indentation level must be >= 0, got {level}") + if _hasChild(root._c_node): + space = _utf8(space) + indent = b"\n" + level * space + _indent_children(root._c_node, 1, space, [indent, indent + space]) + + +cdef int _indent_children(xmlNode* c_node, Py_ssize_t level, bytes one_space, list indentations) except -1: + # Reuse indentation strings for speed. + if len(indentations) <= level: + indentations.append(indentations[-1] + one_space) + + # Start a new indentation level for the first child. + child_indentation = indentations[level] + if not _hasNonWhitespaceText(c_node): + _setNodeText(c_node, child_indentation) + + # Recursively indent all children. + cdef xmlNode* c_child = _findChildForwards(c_node, 0) + while c_child is not NULL: + if _hasChild(c_child): + _indent_children(c_child, level+1, one_space, indentations) + c_next_child = _nextElement(c_child) + if not _hasNonWhitespaceTail(c_child): + if c_next_child is NULL: + # Dedent after the last child. + child_indentation = indentations[level-1] + _setTailText(c_child, child_indentation) + c_child = c_next_child + return 0 + + +def dump(_Element elem not None, *, bint pretty_print=True, bint with_tail=True): + """dump(elem, pretty_print=True, with_tail=True) + + Writes an element tree or element structure to sys.stdout. This function + should be used for debugging only. + """ + xml = tostring(elem, pretty_print=pretty_print, with_tail=with_tail, encoding='unicode') + if not pretty_print: + xml += '\n' + sys.stdout.write(xml) + + +def tostring(element_or_tree, *, encoding=None, method="xml", + xml_declaration=None, bint pretty_print=False, bint with_tail=True, + standalone=None, doctype=None, + # method='c14n' + bint exclusive=False, inclusive_ns_prefixes=None, + # method='c14n2' + bint with_comments=True, bint strip_text=False, + ): + """tostring(element_or_tree, encoding=None, method="xml", + xml_declaration=None, pretty_print=False, with_tail=True, + standalone=None, doctype=None, + exclusive=False, inclusive_ns_prefixes=None, + with_comments=True, strip_text=False, + ) + + Serialize an element to an encoded string representation of its XML + tree. + + Defaults to ASCII encoding without XML declaration. This + behaviour can be configured with the keyword arguments 'encoding' + (string) and 'xml_declaration' (bool). Note that changing the + encoding to a non UTF-8 compatible encoding will enable a + declaration by default. + + You can also serialise to a Unicode string without declaration by + passing the name ``'unicode'`` as encoding (or the ``str`` function + in Py3 or ``unicode`` in Py2). This changes the return value from + a byte string to an unencoded unicode string. + + The keyword argument 'pretty_print' (bool) enables formatted XML. + + The keyword argument 'method' selects the output method: 'xml', + 'html', plain 'text' (text content without tags), 'c14n' or 'c14n2'. + Default is 'xml'. + + With ``method="c14n"`` (C14N version 1), the options ``exclusive``, + ``with_comments`` and ``inclusive_ns_prefixes`` request exclusive + C14N, include comments, and list the inclusive prefixes respectively. + + With ``method="c14n2"`` (C14N version 2), the ``with_comments`` and + ``strip_text`` options control the output of comments and text space + according to C14N 2.0. + + Passing a boolean value to the ``standalone`` option will output + an XML declaration with the corresponding ``standalone`` flag. + + The ``doctype`` option allows passing in a plain string that will + be serialised before the XML tree. Note that passing in non + well-formed content here will make the XML output non well-formed. + Also, an existing doctype in the document tree will not be removed + when serialising an ElementTree instance. + + You can prevent the tail text of the element from being serialised + by passing the boolean ``with_tail`` option. This has no impact + on the tail text of children, which will always be serialised. + """ + cdef bint write_declaration + cdef int is_standalone + # C14N serialisation + if method in ('c14n', 'c14n2'): + if encoding is not None: + raise ValueError("Cannot specify encoding with C14N") + if xml_declaration: + raise ValueError("Cannot enable XML declaration in C14N") + if method == 'c14n': + return _tostringC14N(element_or_tree, exclusive, with_comments, inclusive_ns_prefixes) + else: + out = BytesIO() + target = C14NWriterTarget( + utf8_writer(out).write, + with_comments=with_comments, strip_text=strip_text) + _tree_to_target(element_or_tree, target) + return out.getvalue() + if not with_comments: + raise ValueError("Can only discard comments in C14N serialisation") + if strip_text: + raise ValueError("Can only strip text in C14N 2.0 serialisation") + if encoding is unicode or (encoding is not None and encoding.lower() == 'unicode'): + if xml_declaration: + raise ValueError, \ + "Serialisation to unicode must not request an XML declaration" + write_declaration = 0 + encoding = unicode + elif xml_declaration is None: + # by default, write an XML declaration only for non-standard encodings + write_declaration = encoding is not None and encoding.upper() not in \ + ('ASCII', 'UTF-8', 'UTF8', 'US-ASCII') + else: + write_declaration = xml_declaration + if encoding is None: + encoding = 'ASCII' + if standalone is None: + is_standalone = -1 + elif standalone: + write_declaration = 1 + is_standalone = 1 + else: + write_declaration = 1 + is_standalone = 0 + + if isinstance(element_or_tree, _Element): + return _tostring(<_Element>element_or_tree, encoding, doctype, method, + write_declaration, 0, pretty_print, with_tail, + is_standalone) + elif isinstance(element_or_tree, _ElementTree): + return _tostring((<_ElementTree>element_or_tree)._context_node, + encoding, doctype, method, write_declaration, 1, + pretty_print, with_tail, is_standalone) + else: + raise TypeError, f"Type '{python._fqtypename(element_or_tree).decode('utf8')}' cannot be serialized." + + + +def tostringlist(element_or_tree, *args, **kwargs): + """tostringlist(element_or_tree, *args, **kwargs) + + Serialize an element to an encoded string representation of its XML + tree, stored in a list of partial strings. + + This is purely for ElementTree 1.3 compatibility. The result is a + single string wrapped in a list. + """ + return [tostring(element_or_tree, *args, **kwargs)] + + +def tounicode(element_or_tree, *, method="xml", bint pretty_print=False, + bint with_tail=True, doctype=None): + """tounicode(element_or_tree, method="xml", pretty_print=False, + with_tail=True, doctype=None) + + Serialize an element to the Python unicode representation of its XML + tree. + + :deprecated: use ``tostring(el, encoding='unicode')`` instead. + + Note that the result does not carry an XML encoding declaration and is + therefore not necessarily suited for serialization to byte streams without + further treatment. + + The boolean keyword argument 'pretty_print' enables formatted XML. + + The keyword argument 'method' selects the output method: 'xml', + 'html' or plain 'text'. + + You can prevent the tail text of the element from being serialised + by passing the boolean ``with_tail`` option. This has no impact + on the tail text of children, which will always be serialised. + """ + if isinstance(element_or_tree, _Element): + return _tostring(<_Element>element_or_tree, unicode, doctype, method, + 0, 0, pretty_print, with_tail, -1) + elif isinstance(element_or_tree, _ElementTree): + return _tostring((<_ElementTree>element_or_tree)._context_node, + unicode, doctype, method, 0, 1, pretty_print, + with_tail, -1) + else: + raise TypeError, f"Type '{type(element_or_tree)}' cannot be serialized." + + +def parse(source, _BaseParser parser=None, *, base_url=None): + """parse(source, parser=None, base_url=None) + + Return an ElementTree object loaded with source elements. If no parser + is provided as second argument, the default parser is used. + + The ``source`` can be any of the following: + + - a file name/path + - a file object + - a file-like object + - a URL using the HTTP or FTP protocol + + To parse from a string, use the ``fromstring()`` function instead. + + Note that it is generally faster to parse from a file path or URL + than from an open file object or file-like object. Transparent + decompression from gzip compressed sources is supported (unless + explicitly disabled in libxml2). + + The ``base_url`` keyword allows setting a URL for the document + when parsing from a file-like object. This is needed when looking + up external entities (DTD, XInclude, ...) with relative paths. + """ + cdef _Document doc + try: + doc = _parseDocument(source, parser, base_url) + return _elementTreeFactory(doc, None) + except _TargetParserResult as result_container: + return result_container.result + + +def adopt_external_document(capsule, _BaseParser parser=None): + """adopt_external_document(capsule, parser=None) + + Unpack a libxml2 document pointer from a PyCapsule and wrap it in an + lxml ElementTree object. + + This allows external libraries to build XML/HTML trees using libxml2 + and then pass them efficiently into lxml for further processing. + + If a ``parser`` is provided, it will be used for configuring the + lxml document. No parsing will be done. + + The capsule must have the name ``"libxml2:xmlDoc"`` and its pointer + value must reference a correct libxml2 document of type ``xmlDoc*``. + The creator of the capsule must take care to correctly clean up the + document using an appropriate capsule destructor. By default, the + libxml2 document will be copied to let lxml safely own the memory + of the internal tree that it uses. + + If the capsule context is non-NULL, it must point to a C string that + can be compared using ``strcmp()``. If the context string equals + ``"destructor:xmlFreeDoc"``, the libxml2 document will not be copied + but the capsule invalidated instead by clearing its destructor and + name. That way, lxml takes ownership of the libxml2 document in memory + without creating a copy first, and the capsule destructor will not be + called. The document will then eventually be cleaned up by lxml using + the libxml2 API function ``xmlFreeDoc()`` once it is no longer used. + + If no copy is made, later modifications of the tree outside of lxml + should not be attempted after transferring the ownership. + """ + cdef xmlDoc* c_doc + cdef bint is_owned = False + c_doc = python.lxml_unpack_xmldoc_capsule(capsule, &is_owned) + doc = _adoptForeignDoc(c_doc, parser, is_owned) + return _elementTreeFactory(doc, None) + + +################################################################################ +# Include submodules + +include "readonlytree.pxi" # Read-only implementation of Element proxies +include "classlookup.pxi" # Element class lookup mechanisms +include "nsclasses.pxi" # Namespace implementation and registry +include "docloader.pxi" # Support for custom document loaders +include "parser.pxi" # XML and HTML parsers +include "saxparser.pxi" # SAX-like Parser interface and tree builder +include "parsertarget.pxi" # ET Parser target +include "serializer.pxi" # XML output functions +include "iterparse.pxi" # incremental XML parsing +include "xmlid.pxi" # XMLID and IDDict +include "xinclude.pxi" # XInclude +include "cleanup.pxi" # Cleanup and recursive element removal functions + + +################################################################################ +# Include submodules for XPath and XSLT + +include "extensions.pxi" # XPath/XSLT extension functions +include "xpath.pxi" # XPath evaluation +include "xslt.pxi" # XSL transformations +include "xsltext.pxi" # XSL extension elements + + +################################################################################ +# Validation + +cdef class DocumentInvalid(LxmlError): + """Validation error. + + Raised by all document validators when their ``assertValid(tree)`` + method fails. + """ + + +cdef class _Validator: + "Base class for XML validators." + cdef _ErrorLog _error_log + def __cinit__(self): + self._error_log = _ErrorLog() + + def validate(self, etree): + """validate(self, etree) + + Validate the document using this schema. + + Returns true if document is valid, false if not. + """ + return self(etree) + + def assertValid(self, etree): + """assertValid(self, etree) + + Raises `DocumentInvalid` if the document does not comply with the schema. + """ + if not self(etree): + raise DocumentInvalid(self._error_log._buildExceptionMessage( + "Document does not comply with schema"), + self._error_log) + + def assert_(self, etree): + """assert_(self, etree) + + Raises `AssertionError` if the document does not comply with the schema. + """ + if not self(etree): + raise AssertionError, self._error_log._buildExceptionMessage( + "Document does not comply with schema") + + cpdef _append_log_message(self, int domain, int type, int level, int line, + message, filename): + self._error_log._receiveGeneric(domain, type, level, line, message, + filename) + + cpdef _clear_error_log(self): + self._error_log.clear() + + @property + def error_log(self): + """The log of validation errors and warnings.""" + assert self._error_log is not None, "XPath evaluator not initialised" + return self._error_log.copy() + +include "dtd.pxi" # DTD +include "relaxng.pxi" # RelaxNG +include "xmlschema.pxi" # XMLSchema +include "schematron.pxi" # Schematron (requires libxml2 2.6.21+) + +################################################################################ +# Public C API + +include "public-api.pxi" + +################################################################################ +# Other stuff + +include "debug.pxi" diff --git a/venv/lib/python3.10/site-packages/lxml/etree_api.h b/venv/lib/python3.10/site-packages/lxml/etree_api.h new file mode 100644 index 0000000000000000000000000000000000000000..3c18b87a75d1e116180a150aedd6827d417954e7 --- /dev/null +++ b/venv/lib/python3.10/site-packages/lxml/etree_api.h @@ -0,0 +1,204 @@ +/* Generated by Cython 3.1.2 */ + +#ifndef __PYX_HAVE_API__lxml__etree +#define __PYX_HAVE_API__lxml__etree +#ifdef __MINGW64__ +#define MS_WIN64 +#endif +#include "Python.h" +#include "etree.h" + +static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_deepcopyNodeToDocument)(struct LxmlDocument *, xmlNode *) = 0; +#define deepcopyNodeToDocument __pyx_api_f_4lxml_5etree_deepcopyNodeToDocument +static struct LxmlElementTree *(*__pyx_api_f_4lxml_5etree_elementTreeFactory)(struct LxmlElement *) = 0; +#define elementTreeFactory __pyx_api_f_4lxml_5etree_elementTreeFactory +static struct LxmlElementTree *(*__pyx_api_f_4lxml_5etree_newElementTree)(struct LxmlElement *, PyObject *) = 0; +#define newElementTree __pyx_api_f_4lxml_5etree_newElementTree +static struct LxmlElementTree *(*__pyx_api_f_4lxml_5etree_adoptExternalDocument)(xmlDoc *, PyObject *, int) = 0; +#define adoptExternalDocument __pyx_api_f_4lxml_5etree_adoptExternalDocument +static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_elementFactory)(struct LxmlDocument *, xmlNode *) = 0; +#define elementFactory __pyx_api_f_4lxml_5etree_elementFactory +static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_makeElement)(PyObject *, struct LxmlDocument *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *) = 0; +#define makeElement __pyx_api_f_4lxml_5etree_makeElement +static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_makeSubElement)(struct LxmlElement *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *) = 0; +#define makeSubElement __pyx_api_f_4lxml_5etree_makeSubElement +static void (*__pyx_api_f_4lxml_5etree_setElementClassLookupFunction)(_element_class_lookup_function, PyObject *) = 0; +#define setElementClassLookupFunction __pyx_api_f_4lxml_5etree_setElementClassLookupFunction +static PyObject *(*__pyx_api_f_4lxml_5etree_lookupDefaultElementClass)(PyObject *, PyObject *, xmlNode *) = 0; +#define lookupDefaultElementClass __pyx_api_f_4lxml_5etree_lookupDefaultElementClass +static PyObject *(*__pyx_api_f_4lxml_5etree_lookupNamespaceElementClass)(PyObject *, PyObject *, xmlNode *) = 0; +#define lookupNamespaceElementClass __pyx_api_f_4lxml_5etree_lookupNamespaceElementClass +static PyObject *(*__pyx_api_f_4lxml_5etree_callLookupFallback)(struct LxmlFallbackElementClassLookup *, struct LxmlDocument *, xmlNode *) = 0; +#define callLookupFallback __pyx_api_f_4lxml_5etree_callLookupFallback +static int (*__pyx_api_f_4lxml_5etree_tagMatches)(xmlNode *, const xmlChar *, const xmlChar *) = 0; +#define tagMatches __pyx_api_f_4lxml_5etree_tagMatches +static struct LxmlDocument *(*__pyx_api_f_4lxml_5etree_documentOrRaise)(PyObject *) = 0; +#define documentOrRaise __pyx_api_f_4lxml_5etree_documentOrRaise +static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_rootNodeOrRaise)(PyObject *) = 0; +#define rootNodeOrRaise __pyx_api_f_4lxml_5etree_rootNodeOrRaise +static int (*__pyx_api_f_4lxml_5etree_hasText)(xmlNode *) = 0; +#define hasText __pyx_api_f_4lxml_5etree_hasText +static int (*__pyx_api_f_4lxml_5etree_hasTail)(xmlNode *) = 0; +#define hasTail __pyx_api_f_4lxml_5etree_hasTail +static PyObject *(*__pyx_api_f_4lxml_5etree_textOf)(xmlNode *) = 0; +#define textOf __pyx_api_f_4lxml_5etree_textOf +static PyObject *(*__pyx_api_f_4lxml_5etree_tailOf)(xmlNode *) = 0; +#define tailOf __pyx_api_f_4lxml_5etree_tailOf +static int (*__pyx_api_f_4lxml_5etree_setNodeText)(xmlNode *, PyObject *) = 0; +#define setNodeText __pyx_api_f_4lxml_5etree_setNodeText +static int (*__pyx_api_f_4lxml_5etree_setTailText)(xmlNode *, PyObject *) = 0; +#define setTailText __pyx_api_f_4lxml_5etree_setTailText +static PyObject *(*__pyx_api_f_4lxml_5etree_attributeValue)(xmlNode *, xmlAttr *) = 0; +#define attributeValue __pyx_api_f_4lxml_5etree_attributeValue +static PyObject *(*__pyx_api_f_4lxml_5etree_attributeValueFromNsName)(xmlNode *, const xmlChar *, const xmlChar *) = 0; +#define attributeValueFromNsName __pyx_api_f_4lxml_5etree_attributeValueFromNsName +static PyObject *(*__pyx_api_f_4lxml_5etree_getAttributeValue)(struct LxmlElement *, PyObject *, PyObject *) = 0; +#define getAttributeValue __pyx_api_f_4lxml_5etree_getAttributeValue +static PyObject *(*__pyx_api_f_4lxml_5etree_iterattributes)(struct LxmlElement *, int) = 0; +#define iterattributes __pyx_api_f_4lxml_5etree_iterattributes +static PyObject *(*__pyx_api_f_4lxml_5etree_collectAttributes)(xmlNode *, int) = 0; +#define collectAttributes __pyx_api_f_4lxml_5etree_collectAttributes +static int (*__pyx_api_f_4lxml_5etree_setAttributeValue)(struct LxmlElement *, PyObject *, PyObject *) = 0; +#define setAttributeValue __pyx_api_f_4lxml_5etree_setAttributeValue +static int (*__pyx_api_f_4lxml_5etree_delAttribute)(struct LxmlElement *, PyObject *) = 0; +#define delAttribute __pyx_api_f_4lxml_5etree_delAttribute +static int (*__pyx_api_f_4lxml_5etree_delAttributeFromNsName)(xmlNode *, const xmlChar *, const xmlChar *) = 0; +#define delAttributeFromNsName __pyx_api_f_4lxml_5etree_delAttributeFromNsName +static int (*__pyx_api_f_4lxml_5etree_hasChild)(xmlNode *) = 0; +#define hasChild __pyx_api_f_4lxml_5etree_hasChild +static xmlNode *(*__pyx_api_f_4lxml_5etree_findChild)(xmlNode *, Py_ssize_t) = 0; +#define findChild __pyx_api_f_4lxml_5etree_findChild +static xmlNode *(*__pyx_api_f_4lxml_5etree_findChildForwards)(xmlNode *, Py_ssize_t) = 0; +#define findChildForwards __pyx_api_f_4lxml_5etree_findChildForwards +static xmlNode *(*__pyx_api_f_4lxml_5etree_findChildBackwards)(xmlNode *, Py_ssize_t) = 0; +#define findChildBackwards __pyx_api_f_4lxml_5etree_findChildBackwards +static xmlNode *(*__pyx_api_f_4lxml_5etree_nextElement)(xmlNode *) = 0; +#define nextElement __pyx_api_f_4lxml_5etree_nextElement +static xmlNode *(*__pyx_api_f_4lxml_5etree_previousElement)(xmlNode *) = 0; +#define previousElement __pyx_api_f_4lxml_5etree_previousElement +static void (*__pyx_api_f_4lxml_5etree_appendChild)(struct LxmlElement *, struct LxmlElement *) = 0; +#define appendChild __pyx_api_f_4lxml_5etree_appendChild +static int (*__pyx_api_f_4lxml_5etree_appendChildToElement)(struct LxmlElement *, struct LxmlElement *) = 0; +#define appendChildToElement __pyx_api_f_4lxml_5etree_appendChildToElement +static PyObject *(*__pyx_api_f_4lxml_5etree_pyunicode)(const xmlChar *) = 0; +#define pyunicode __pyx_api_f_4lxml_5etree_pyunicode +static PyObject *(*__pyx_api_f_4lxml_5etree_utf8)(PyObject *) = 0; +#define utf8 __pyx_api_f_4lxml_5etree_utf8 +static PyObject *(*__pyx_api_f_4lxml_5etree_getNsTag)(PyObject *) = 0; +#define getNsTag __pyx_api_f_4lxml_5etree_getNsTag +static PyObject *(*__pyx_api_f_4lxml_5etree_getNsTagWithEmptyNs)(PyObject *) = 0; +#define getNsTagWithEmptyNs __pyx_api_f_4lxml_5etree_getNsTagWithEmptyNs +static PyObject *(*__pyx_api_f_4lxml_5etree_namespacedName)(xmlNode *) = 0; +#define namespacedName __pyx_api_f_4lxml_5etree_namespacedName +static PyObject *(*__pyx_api_f_4lxml_5etree_namespacedNameFromNsName)(const xmlChar *, const xmlChar *) = 0; +#define namespacedNameFromNsName __pyx_api_f_4lxml_5etree_namespacedNameFromNsName +static void (*__pyx_api_f_4lxml_5etree_iteratorStoreNext)(struct LxmlElementIterator *, struct LxmlElement *) = 0; +#define iteratorStoreNext __pyx_api_f_4lxml_5etree_iteratorStoreNext +static void (*__pyx_api_f_4lxml_5etree_initTagMatch)(struct LxmlElementTagMatcher *, PyObject *) = 0; +#define initTagMatch __pyx_api_f_4lxml_5etree_initTagMatch +static xmlNs *(*__pyx_api_f_4lxml_5etree_findOrBuildNodeNsPrefix)(struct LxmlDocument *, xmlNode *, const xmlChar *, const xmlChar *) = 0; +#define findOrBuildNodeNsPrefix __pyx_api_f_4lxml_5etree_findOrBuildNodeNsPrefix +static int __Pyx_ImportFunction_3_1_2(PyObject *module, const char *funcname, void (**f)(void), const char *sig); + +#ifndef __PYX_HAVE_RT_ImportFunction_3_1_2 +#define __PYX_HAVE_RT_ImportFunction_3_1_2 +static int __Pyx_ImportFunction_3_1_2(PyObject *module, const char *funcname, void (**f)(void), const char *sig) { + PyObject *d = 0; + PyObject *cobj = 0; + union { + void (*fp)(void); + void *p; + } tmp; + d = PyObject_GetAttrString(module, "__pyx_capi__"); + if (!d) + goto bad; +#if (defined(Py_LIMITED_API) && Py_LIMITED_API >= 0x030d0000) || (!defined(Py_LIMITED_API) && PY_VERSION_HEX >= 0x030d0000) + PyDict_GetItemStringRef(d, funcname, &cobj); +#else + cobj = PyDict_GetItemString(d, funcname); + Py_XINCREF(cobj); +#endif + if (!cobj) { + PyErr_Format(PyExc_ImportError, + "%.200s does not export expected C function %.200s", + PyModule_GetName(module), funcname); + goto bad; + } + if (!PyCapsule_IsValid(cobj, sig)) { + PyErr_Format(PyExc_TypeError, + "C function %.200s.%.200s has wrong signature (expected %.500s, got %.500s)", + PyModule_GetName(module), funcname, sig, PyCapsule_GetName(cobj)); + goto bad; + } + tmp.p = PyCapsule_GetPointer(cobj, sig); + *f = tmp.fp; + if (!(*f)) + goto bad; + Py_DECREF(d); + Py_DECREF(cobj); + return 0; +bad: + Py_XDECREF(d); + Py_XDECREF(cobj); + return -1; +} +#endif + + +static int import_lxml__etree(void) { + PyObject *module = 0; + module = PyImport_ImportModule("lxml.etree"); + if (!module) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "deepcopyNodeToDocument", (void (**)(void))&__pyx_api_f_4lxml_5etree_deepcopyNodeToDocument, "struct LxmlElement *(struct LxmlDocument *, xmlNode *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "elementTreeFactory", (void (**)(void))&__pyx_api_f_4lxml_5etree_elementTreeFactory, "struct LxmlElementTree *(struct LxmlElement *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "newElementTree", (void (**)(void))&__pyx_api_f_4lxml_5etree_newElementTree, "struct LxmlElementTree *(struct LxmlElement *, PyObject *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "adoptExternalDocument", (void (**)(void))&__pyx_api_f_4lxml_5etree_adoptExternalDocument, "struct LxmlElementTree *(xmlDoc *, PyObject *, int)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "elementFactory", (void (**)(void))&__pyx_api_f_4lxml_5etree_elementFactory, "struct LxmlElement *(struct LxmlDocument *, xmlNode *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "makeElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_makeElement, "struct LxmlElement *(PyObject *, struct LxmlDocument *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "makeSubElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_makeSubElement, "struct LxmlElement *(struct LxmlElement *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "setElementClassLookupFunction", (void (**)(void))&__pyx_api_f_4lxml_5etree_setElementClassLookupFunction, "void (_element_class_lookup_function, PyObject *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "lookupDefaultElementClass", (void (**)(void))&__pyx_api_f_4lxml_5etree_lookupDefaultElementClass, "PyObject *(PyObject *, PyObject *, xmlNode *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "lookupNamespaceElementClass", (void (**)(void))&__pyx_api_f_4lxml_5etree_lookupNamespaceElementClass, "PyObject *(PyObject *, PyObject *, xmlNode *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "callLookupFallback", (void (**)(void))&__pyx_api_f_4lxml_5etree_callLookupFallback, "PyObject *(struct LxmlFallbackElementClassLookup *, struct LxmlDocument *, xmlNode *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "tagMatches", (void (**)(void))&__pyx_api_f_4lxml_5etree_tagMatches, "int (xmlNode *, const xmlChar *, const xmlChar *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "documentOrRaise", (void (**)(void))&__pyx_api_f_4lxml_5etree_documentOrRaise, "struct LxmlDocument *(PyObject *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "rootNodeOrRaise", (void (**)(void))&__pyx_api_f_4lxml_5etree_rootNodeOrRaise, "struct LxmlElement *(PyObject *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "hasText", (void (**)(void))&__pyx_api_f_4lxml_5etree_hasText, "int (xmlNode *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "hasTail", (void (**)(void))&__pyx_api_f_4lxml_5etree_hasTail, "int (xmlNode *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "textOf", (void (**)(void))&__pyx_api_f_4lxml_5etree_textOf, "PyObject *(xmlNode *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "tailOf", (void (**)(void))&__pyx_api_f_4lxml_5etree_tailOf, "PyObject *(xmlNode *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "setNodeText", (void (**)(void))&__pyx_api_f_4lxml_5etree_setNodeText, "int (xmlNode *, PyObject *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "setTailText", (void (**)(void))&__pyx_api_f_4lxml_5etree_setTailText, "int (xmlNode *, PyObject *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "attributeValue", (void (**)(void))&__pyx_api_f_4lxml_5etree_attributeValue, "PyObject *(xmlNode *, xmlAttr *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "attributeValueFromNsName", (void (**)(void))&__pyx_api_f_4lxml_5etree_attributeValueFromNsName, "PyObject *(xmlNode *, const xmlChar *, const xmlChar *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "getAttributeValue", (void (**)(void))&__pyx_api_f_4lxml_5etree_getAttributeValue, "PyObject *(struct LxmlElement *, PyObject *, PyObject *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "iterattributes", (void (**)(void))&__pyx_api_f_4lxml_5etree_iterattributes, "PyObject *(struct LxmlElement *, int)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "collectAttributes", (void (**)(void))&__pyx_api_f_4lxml_5etree_collectAttributes, "PyObject *(xmlNode *, int)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "setAttributeValue", (void (**)(void))&__pyx_api_f_4lxml_5etree_setAttributeValue, "int (struct LxmlElement *, PyObject *, PyObject *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "delAttribute", (void (**)(void))&__pyx_api_f_4lxml_5etree_delAttribute, "int (struct LxmlElement *, PyObject *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "delAttributeFromNsName", (void (**)(void))&__pyx_api_f_4lxml_5etree_delAttributeFromNsName, "int (xmlNode *, const xmlChar *, const xmlChar *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "hasChild", (void (**)(void))&__pyx_api_f_4lxml_5etree_hasChild, "int (xmlNode *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "findChild", (void (**)(void))&__pyx_api_f_4lxml_5etree_findChild, "xmlNode *(xmlNode *, Py_ssize_t)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "findChildForwards", (void (**)(void))&__pyx_api_f_4lxml_5etree_findChildForwards, "xmlNode *(xmlNode *, Py_ssize_t)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "findChildBackwards", (void (**)(void))&__pyx_api_f_4lxml_5etree_findChildBackwards, "xmlNode *(xmlNode *, Py_ssize_t)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "nextElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_nextElement, "xmlNode *(xmlNode *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "previousElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_previousElement, "xmlNode *(xmlNode *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "appendChild", (void (**)(void))&__pyx_api_f_4lxml_5etree_appendChild, "void (struct LxmlElement *, struct LxmlElement *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "appendChildToElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_appendChildToElement, "int (struct LxmlElement *, struct LxmlElement *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "pyunicode", (void (**)(void))&__pyx_api_f_4lxml_5etree_pyunicode, "PyObject *(const xmlChar *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "utf8", (void (**)(void))&__pyx_api_f_4lxml_5etree_utf8, "PyObject *(PyObject *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "getNsTag", (void (**)(void))&__pyx_api_f_4lxml_5etree_getNsTag, "PyObject *(PyObject *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "getNsTagWithEmptyNs", (void (**)(void))&__pyx_api_f_4lxml_5etree_getNsTagWithEmptyNs, "PyObject *(PyObject *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "namespacedName", (void (**)(void))&__pyx_api_f_4lxml_5etree_namespacedName, "PyObject *(xmlNode *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "namespacedNameFromNsName", (void (**)(void))&__pyx_api_f_4lxml_5etree_namespacedNameFromNsName, "PyObject *(const xmlChar *, const xmlChar *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "iteratorStoreNext", (void (**)(void))&__pyx_api_f_4lxml_5etree_iteratorStoreNext, "void (struct LxmlElementIterator *, struct LxmlElement *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "initTagMatch", (void (**)(void))&__pyx_api_f_4lxml_5etree_initTagMatch, "void (struct LxmlElementTagMatcher *, PyObject *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_1_2(module, "findOrBuildNodeNsPrefix", (void (**)(void))&__pyx_api_f_4lxml_5etree_findOrBuildNodeNsPrefix, "xmlNs *(struct LxmlDocument *, xmlNode *, const xmlChar *, const xmlChar *)") < 0) goto bad; + Py_DECREF(module); module = 0; + return 0; + bad: + Py_XDECREF(module); + return -1; +} + +#endif /* !__PYX_HAVE_API__lxml__etree */ diff --git a/venv/lib/python3.10/site-packages/lxml/extensions.pxi b/venv/lib/python3.10/site-packages/lxml/extensions.pxi new file mode 100644 index 0000000000000000000000000000000000000000..ab687bec9c1d58c1220fae31bce1712d4751a9f2 --- /dev/null +++ b/venv/lib/python3.10/site-packages/lxml/extensions.pxi @@ -0,0 +1,830 @@ +# support for extension functions in XPath and XSLT + +cdef class XPathError(LxmlError): + """Base class of all XPath errors. + """ + +cdef class XPathEvalError(XPathError): + """Error during XPath evaluation. + """ + +cdef class XPathFunctionError(XPathEvalError): + """Internal error looking up an XPath extension function. + """ + +cdef class XPathResultError(XPathEvalError): + """Error handling an XPath result. + """ + + +# forward declarations + +ctypedef int (*_register_function)(void* ctxt, name_utf, ns_uri_utf) +cdef class _ExsltRegExp + +################################################################################ +# Base class for XSLT and XPath evaluation contexts: functions, namespaces, ... + +@cython.internal +cdef class _BaseContext: + cdef xpath.xmlXPathContext* _xpathCtxt + cdef _Document _doc + cdef dict _extensions + cdef list _namespaces + cdef list _global_namespaces + cdef dict _utf_refs + cdef dict _function_cache + cdef dict _eval_context_dict + cdef bint _build_smart_strings + # for exception handling and temporary reference keeping: + cdef _TempStore _temp_refs + cdef set _temp_documents + cdef _ExceptionContext _exc + cdef _ErrorLog _error_log + + def __init__(self, namespaces, extensions, error_log, enable_regexp, + build_smart_strings): + cdef _ExsltRegExp _regexp + cdef dict new_extensions + cdef list ns + self._utf_refs = {} + self._global_namespaces = [] + self._function_cache = {} + self._eval_context_dict = None + self._error_log = error_log + + if extensions is not None: + # convert extensions to UTF-8 + if isinstance(extensions, dict): + extensions = (extensions,) + # format: [ {(ns, name):function} ] -> {(ns_utf, name_utf):function} + new_extensions = {} + for extension in extensions: + for (ns_uri, name), function in extension.items(): + if name is None: + raise ValueError, "extensions must have non empty names" + ns_utf = self._to_utf(ns_uri) + name_utf = self._to_utf(name) + new_extensions[(ns_utf, name_utf)] = function + extensions = new_extensions or None + + if namespaces is not None: + if isinstance(namespaces, dict): + namespaces = namespaces.items() + if namespaces: + ns = [] + for prefix, ns_uri in namespaces: + if prefix is None or not prefix: + raise TypeError, \ + "empty namespace prefix is not supported in XPath" + if ns_uri is None or not ns_uri: + raise TypeError, \ + "setting default namespace is not supported in XPath" + prefix_utf = self._to_utf(prefix) + ns_uri_utf = self._to_utf(ns_uri) + ns.append( (prefix_utf, ns_uri_utf) ) + namespaces = ns + else: + namespaces = None + + self._doc = None + self._exc = _ExceptionContext() + self._extensions = extensions + self._namespaces = namespaces + self._temp_refs = _TempStore() + self._temp_documents = set() + self._build_smart_strings = build_smart_strings + + if enable_regexp: + _regexp = _ExsltRegExp() + _regexp._register_in_context(self) + + cdef _BaseContext _copy(self): + cdef _BaseContext context + if self._namespaces is not None: + namespaces = self._namespaces[:] + else: + namespaces = None + context = self.__class__(namespaces, None, self._error_log, False, + self._build_smart_strings) + if self._extensions is not None: + context._extensions = self._extensions.copy() + return context + + cdef bytes _to_utf(self, s): + "Convert to UTF-8 and keep a reference to the encoded string" + cdef python.PyObject* dict_result + if s is None: + return None + dict_result = python.PyDict_GetItem(self._utf_refs, s) + if dict_result is not NULL: + return dict_result + utf = _utf8(s) + self._utf_refs[s] = utf + if python.IS_PYPY: + # use C level refs, PyPy refs are not enough! + python.Py_INCREF(utf) + return utf + + cdef void _set_xpath_context(self, xpath.xmlXPathContext* xpathCtxt) noexcept: + self._xpathCtxt = xpathCtxt + xpathCtxt.userData = self + # Need a cast here because older libxml2 releases do not use 'const' in the functype. + xpathCtxt.error = _receiveXPathError + + @cython.final + cdef _register_context(self, _Document doc): + self._doc = doc + self._exc.clear() + + @cython.final + cdef _cleanup_context(self): + #xpath.xmlXPathRegisteredNsCleanup(self._xpathCtxt) + #self.unregisterGlobalNamespaces() + if python.IS_PYPY: + # clean up double refs in PyPy (see "_to_utf()" method) + for ref in self._utf_refs.itervalues(): + python.Py_DECREF(ref) + self._utf_refs.clear() + self._eval_context_dict = None + self._doc = None + + @cython.final + cdef _release_context(self): + if self._xpathCtxt is not NULL: + self._xpathCtxt.userData = NULL + self._xpathCtxt = NULL + + # namespaces (internal UTF-8 methods with leading '_') + + cdef addNamespace(self, prefix, ns_uri): + cdef list namespaces + if prefix is None: + raise TypeError, "empty prefix is not supported in XPath" + prefix_utf = self._to_utf(prefix) + ns_uri_utf = self._to_utf(ns_uri) + new_item = (prefix_utf, ns_uri_utf) + if self._namespaces is None: + self._namespaces = [new_item] + else: + namespaces = [] + for item in self._namespaces: + if item[0] == prefix_utf: + item = new_item + new_item = None + namespaces.append(item) + if new_item is not None: + namespaces.append(new_item) + self._namespaces = namespaces + if self._xpathCtxt is not NULL: + xpath.xmlXPathRegisterNs( + self._xpathCtxt, _xcstr(prefix_utf), _xcstr(ns_uri_utf)) + + cdef registerNamespace(self, prefix, ns_uri): + if prefix is None: + raise TypeError, "empty prefix is not supported in XPath" + prefix_utf = self._to_utf(prefix) + ns_uri_utf = self._to_utf(ns_uri) + self._global_namespaces.append(prefix_utf) + xpath.xmlXPathRegisterNs(self._xpathCtxt, + _xcstr(prefix_utf), _xcstr(ns_uri_utf)) + + cdef registerLocalNamespaces(self): + if self._namespaces is None: + return + for prefix_utf, ns_uri_utf in self._namespaces: + xpath.xmlXPathRegisterNs( + self._xpathCtxt, _xcstr(prefix_utf), _xcstr(ns_uri_utf)) + + cdef registerGlobalNamespaces(self): + cdef list ns_prefixes = _find_all_extension_prefixes() + if python.PyList_GET_SIZE(ns_prefixes) > 0: + for prefix_utf, ns_uri_utf in ns_prefixes: + self._global_namespaces.append(prefix_utf) + xpath.xmlXPathRegisterNs( + self._xpathCtxt, _xcstr(prefix_utf), _xcstr(ns_uri_utf)) + + cdef unregisterGlobalNamespaces(self): + if python.PyList_GET_SIZE(self._global_namespaces) > 0: + for prefix_utf in self._global_namespaces: + xpath.xmlXPathRegisterNs(self._xpathCtxt, + _xcstr(prefix_utf), NULL) + del self._global_namespaces[:] + + cdef void _unregisterNamespace(self, prefix_utf) noexcept: + xpath.xmlXPathRegisterNs(self._xpathCtxt, + _xcstr(prefix_utf), NULL) + + # extension functions + + cdef int _addLocalExtensionFunction(self, ns_utf, name_utf, function) except -1: + if self._extensions is None: + self._extensions = {} + self._extensions[(ns_utf, name_utf)] = function + return 0 + + cdef registerGlobalFunctions(self, void* ctxt, + _register_function reg_func): + cdef python.PyObject* dict_result + cdef dict d + for ns_utf, ns_functions in __FUNCTION_NAMESPACE_REGISTRIES.iteritems(): + dict_result = python.PyDict_GetItem( + self._function_cache, ns_utf) + if dict_result is not NULL: + d = dict_result + else: + d = {} + self._function_cache[ns_utf] = d + for name_utf, function in ns_functions.iteritems(): + d[name_utf] = function + reg_func(ctxt, name_utf, ns_utf) + + cdef registerLocalFunctions(self, void* ctxt, + _register_function reg_func): + cdef python.PyObject* dict_result + cdef dict d + if self._extensions is None: + return # done + last_ns = None + d = None + for (ns_utf, name_utf), function in self._extensions.iteritems(): + if ns_utf is not last_ns or d is None: + last_ns = ns_utf + dict_result = python.PyDict_GetItem( + self._function_cache, ns_utf) + if dict_result is not NULL: + d = dict_result + else: + d = {} + self._function_cache[ns_utf] = d + d[name_utf] = function + reg_func(ctxt, name_utf, ns_utf) + + cdef unregisterAllFunctions(self, void* ctxt, + _register_function unreg_func): + for ns_utf, functions in self._function_cache.iteritems(): + for name_utf in functions: + unreg_func(ctxt, name_utf, ns_utf) + + cdef unregisterGlobalFunctions(self, void* ctxt, + _register_function unreg_func): + for ns_utf, functions in self._function_cache.items(): + for name_utf in functions: + if self._extensions is None or \ + (ns_utf, name_utf) not in self._extensions: + unreg_func(ctxt, name_utf, ns_utf) + + @cython.final + cdef _find_cached_function(self, const_xmlChar* c_ns_uri, const_xmlChar* c_name): + """Lookup an extension function in the cache and return it. + + Parameters: c_ns_uri may be NULL, c_name must not be NULL + """ + cdef python.PyObject* c_dict + cdef python.PyObject* dict_result + c_dict = python.PyDict_GetItem( + self._function_cache, None if c_ns_uri is NULL else c_ns_uri) + if c_dict is not NULL: + dict_result = python.PyDict_GetItem( + c_dict, c_name) + if dict_result is not NULL: + return dict_result + return None + + # Python access to the XPath context for extension functions + + @property + def context_node(self): + cdef xmlNode* c_node + if self._xpathCtxt is NULL: + raise XPathError, \ + "XPath context is only usable during the evaluation" + c_node = self._xpathCtxt.node + if c_node is NULL: + raise XPathError, "no context node" + if c_node.doc != self._xpathCtxt.doc: + raise XPathError, \ + "document-external context nodes are not supported" + if self._doc is None: + raise XPathError, "document context is missing" + return _elementFactory(self._doc, c_node) + + @property + def eval_context(self): + if self._eval_context_dict is None: + self._eval_context_dict = {} + return self._eval_context_dict + + # Python reference keeping during XPath function evaluation + + @cython.final + cdef _release_temp_refs(self): + "Free temporarily referenced objects from this context." + self._temp_refs.clear() + self._temp_documents.clear() + + @cython.final + cdef _hold(self, obj): + """A way to temporarily hold references to nodes in the evaluator. + + This is needed because otherwise nodes created in XPath extension + functions would be reference counted too soon, during the XPath + evaluation. This is most important in the case of exceptions. + """ + cdef _Element element + if isinstance(obj, _Element): + self._temp_refs.add(obj) + self._temp_documents.add((<_Element>obj)._doc) + return + elif _isString(obj) or not python.PySequence_Check(obj): + return + for o in obj: + if isinstance(o, _Element): + #print "Holding element:", element._c_node + self._temp_refs.add(o) + #print "Holding document:", element._doc._c_doc + self._temp_documents.add((<_Element>o)._doc) + + @cython.final + cdef _Document _findDocumentForNode(self, xmlNode* c_node): + """If an XPath expression returns an element from a different + document than the current context document, we call this to + see if it was possibly created by an extension and is a known + document instance. + """ + cdef _Document doc + for doc in self._temp_documents: + if doc is not None and doc._c_doc is c_node.doc: + return doc + return None + + +# libxml2 keeps these error messages in a static array in its code +# and doesn't give us access to them ... + +cdef tuple LIBXML2_XPATH_ERROR_MESSAGES = ( + b"Ok", + b"Number encoding", + b"Unfinished literal", + b"Start of literal", + b"Expected $ for variable reference", + b"Undefined variable", + b"Invalid predicate", + b"Invalid expression", + b"Missing closing curly brace", + b"Unregistered function", + b"Invalid operand", + b"Invalid type", + b"Invalid number of arguments", + b"Invalid context size", + b"Invalid context position", + b"Memory allocation error", + b"Syntax error", + b"Resource error", + b"Sub resource error", + b"Undefined namespace prefix", + b"Encoding error", + b"Char out of XML range", + b"Invalid or incomplete context", + b"Stack usage error", + b"Forbidden variable\n", + b"?? Unknown error ??\n", +) + +cdef void _forwardXPathError(void* c_ctxt, const xmlerror.xmlError* c_error) noexcept with gil: + cdef xmlerror.xmlError error + cdef int xpath_code + if c_error.message is not NULL: + error.message = c_error.message + else: + xpath_code = c_error.code - xmlerror.XML_XPATH_EXPRESSION_OK + if 0 <= xpath_code < len(LIBXML2_XPATH_ERROR_MESSAGES): + error.message = _cstr(LIBXML2_XPATH_ERROR_MESSAGES[xpath_code]) + else: + error.message = b"unknown error" + error.domain = c_error.domain + error.code = c_error.code + error.level = c_error.level + error.line = c_error.line + error.int2 = c_error.int1 # column + error.file = c_error.file + error.node = NULL + + (<_BaseContext>c_ctxt)._error_log._receive(&error) + +cdef void _receiveXPathError(void* c_context, const xmlerror.xmlError* error) noexcept nogil: + if not __DEBUG: + return + if c_context is NULL: + _forwardError(NULL, error) + else: + _forwardXPathError(c_context, error) + + +def Extension(module, function_mapping=None, *, ns=None): + """Extension(module, function_mapping=None, ns=None) + + Build a dictionary of extension functions from the functions + defined in a module or the methods of an object. + + As second argument, you can pass an additional mapping of + attribute names to XPath function names, or a list of function + names that should be taken. + + The ``ns`` keyword argument accepts a namespace URI for the XPath + functions. + """ + cdef dict functions = {} + if isinstance(function_mapping, dict): + for function_name, xpath_name in function_mapping.items(): + functions[(ns, xpath_name)] = getattr(module, function_name) + else: + if function_mapping is None: + function_mapping = [ name for name in dir(module) + if not name.startswith('_') ] + for function_name in function_mapping: + functions[(ns, function_name)] = getattr(module, function_name) + return functions + +################################################################################ +# EXSLT regexp implementation + +@cython.final +@cython.internal +cdef class _ExsltRegExp: + cdef dict _compile_map + def __cinit__(self): + self._compile_map = {} + + cdef _make_string(self, value): + if _isString(value): + return value + elif isinstance(value, list): + # node set: take recursive text concatenation of first element + if python.PyList_GET_SIZE(value) == 0: + return '' + firstnode = value[0] + if _isString(firstnode): + return firstnode + elif isinstance(firstnode, _Element): + c_text = tree.xmlNodeGetContent((<_Element>firstnode)._c_node) + if c_text is NULL: + raise MemoryError() + try: + return funicode(c_text) + finally: + tree.xmlFree(c_text) + else: + return unicode(firstnode) + else: + return unicode(value) + + cdef _compile(self, rexp, ignore_case): + cdef python.PyObject* c_result + rexp = self._make_string(rexp) + key = (rexp, ignore_case) + c_result = python.PyDict_GetItem(self._compile_map, key) + if c_result is not NULL: + return c_result + py_flags = re.UNICODE + if ignore_case: + py_flags = py_flags | re.IGNORECASE + rexp_compiled = re.compile(rexp, py_flags) + self._compile_map[key] = rexp_compiled + return rexp_compiled + + def test(self, ctxt, s, rexp, flags=''): + flags = self._make_string(flags) + s = self._make_string(s) + rexpc = self._compile(rexp, 'i' in flags) + if rexpc.search(s) is None: + return False + else: + return True + + def match(self, ctxt, s, rexp, flags=''): + cdef list result_list + flags = self._make_string(flags) + s = self._make_string(s) + rexpc = self._compile(rexp, 'i' in flags) + if 'g' in flags: + results = rexpc.findall(s) + if not results: + return () + else: + result = rexpc.search(s) + if not result: + return () + results = [ result.group() ] + results.extend( result.groups('') ) + result_list = [] + root = Element('matches') + for s_match in results: + if python.PyTuple_CheckExact(s_match): + s_match = ''.join(s_match) + elem = SubElement(root, 'match') + elem.text = s_match + result_list.append(elem) + return result_list + + def replace(self, ctxt, s, rexp, flags, replacement): + replacement = self._make_string(replacement) + flags = self._make_string(flags) + s = self._make_string(s) + rexpc = self._compile(rexp, 'i' in flags) + count: object = 0 if 'g' in flags else 1 + return rexpc.sub(replacement, s, count) + + cdef _register_in_context(self, _BaseContext context): + ns = b"http://exslt.org/regular-expressions" + context._addLocalExtensionFunction(ns, b"test", self.test) + context._addLocalExtensionFunction(ns, b"match", self.match) + context._addLocalExtensionFunction(ns, b"replace", self.replace) + + +################################################################################ +# helper functions + +cdef xpath.xmlXPathObject* _wrapXPathObject(object obj, _Document doc, + _BaseContext context) except NULL: + cdef xpath.xmlNodeSet* resultSet + cdef _Element fake_node = None + cdef xmlNode* c_node + + if isinstance(obj, unicode): + obj = _utf8(obj) + if isinstance(obj, bytes): + # libxml2 copies the string value + return xpath.xmlXPathNewCString(_cstr(obj)) + if isinstance(obj, bool): + return xpath.xmlXPathNewBoolean(obj) + if python.PyNumber_Check(obj): + return xpath.xmlXPathNewFloat(obj) + if obj is None: + resultSet = xpath.xmlXPathNodeSetCreate(NULL) + elif isinstance(obj, _Element): + resultSet = xpath.xmlXPathNodeSetCreate((<_Element>obj)._c_node) + elif python.PySequence_Check(obj): + resultSet = xpath.xmlXPathNodeSetCreate(NULL) + try: + for value in obj: + if isinstance(value, _Element): + if context is not None: + context._hold(value) + xpath.xmlXPathNodeSetAdd(resultSet, (<_Element>value)._c_node) + else: + if context is None or doc is None: + raise XPathResultError, \ + f"Non-Element values not supported at this point - got {value!r}" + # support strings by appending text nodes to an Element + if isinstance(value, unicode): + value = _utf8(value) + if isinstance(value, bytes): + if fake_node is None: + fake_node = _makeElement("text-root", NULL, doc, None, + None, None, None, None, None) + context._hold(fake_node) + else: + # append a comment node to keep the text nodes separate + c_node = tree.xmlNewDocComment(doc._c_doc, "") + if c_node is NULL: + raise MemoryError() + tree.xmlAddChild(fake_node._c_node, c_node) + context._hold(value) + c_node = tree.xmlNewDocText(doc._c_doc, _xcstr(value)) + if c_node is NULL: + raise MemoryError() + tree.xmlAddChild(fake_node._c_node, c_node) + xpath.xmlXPathNodeSetAdd(resultSet, c_node) + else: + raise XPathResultError, \ + f"This is not a supported node-set result: {value!r}" + except: + xpath.xmlXPathFreeNodeSet(resultSet) + raise + else: + raise XPathResultError, f"Unknown return type: {python._fqtypename(obj).decode('utf8')}" + return xpath.xmlXPathWrapNodeSet(resultSet) + +cdef object _unwrapXPathObject(xpath.xmlXPathObject* xpathObj, + _Document doc, _BaseContext context): + if xpathObj.type == xpath.XPATH_UNDEFINED: + raise XPathResultError, "Undefined xpath result" + elif xpathObj.type == xpath.XPATH_NODESET: + return _createNodeSetResult(xpathObj, doc, context) + elif xpathObj.type == xpath.XPATH_BOOLEAN: + return xpathObj.boolval + elif xpathObj.type == xpath.XPATH_NUMBER: + return xpathObj.floatval + elif xpathObj.type == xpath.XPATH_STRING: + stringval = funicode(xpathObj.stringval) + if context._build_smart_strings: + stringval = _elementStringResultFactory( + stringval, None, None, False) + return stringval + elif xpathObj.type == xpath.XPATH_POINT: + raise NotImplementedError, "XPATH_POINT" + elif xpathObj.type == xpath.XPATH_RANGE: + raise NotImplementedError, "XPATH_RANGE" + elif xpathObj.type == xpath.XPATH_LOCATIONSET: + raise NotImplementedError, "XPATH_LOCATIONSET" + elif xpathObj.type == xpath.XPATH_USERS: + raise NotImplementedError, "XPATH_USERS" + elif xpathObj.type == xpath.XPATH_XSLT_TREE: + return _createNodeSetResult(xpathObj, doc, context) + else: + raise XPathResultError, f"Unknown xpath result {xpathObj.type}" + +cdef object _createNodeSetResult(xpath.xmlXPathObject* xpathObj, _Document doc, + _BaseContext context): + cdef xmlNode* c_node + cdef int i + cdef list result + result = [] + if xpathObj.nodesetval is NULL: + return result + for i in range(xpathObj.nodesetval.nodeNr): + c_node = xpathObj.nodesetval.nodeTab[i] + _unpackNodeSetEntry(result, c_node, doc, context, + xpathObj.type == xpath.XPATH_XSLT_TREE) + return result + +cdef _unpackNodeSetEntry(list results, xmlNode* c_node, _Document doc, + _BaseContext context, bint is_fragment): + cdef xmlNode* c_child + if _isElement(c_node): + if c_node.doc != doc._c_doc and c_node.doc._private is NULL: + # XXX: works, but maybe not always the right thing to do? + # XPath: only runs when extensions create or copy trees + # -> we store Python refs to these, so that is OK + # XSLT: can it leak when merging trees from multiple sources? + c_node = tree.xmlDocCopyNode(c_node, doc._c_doc, 1) + # FIXME: call _instantiateElementFromXPath() instead? + results.append( + _fakeDocElementFactory(doc, c_node)) + elif c_node.type == tree.XML_TEXT_NODE or \ + c_node.type == tree.XML_CDATA_SECTION_NODE or \ + c_node.type == tree.XML_ATTRIBUTE_NODE: + results.append( + _buildElementStringResult(doc, c_node, context)) + elif c_node.type == tree.XML_NAMESPACE_DECL: + results.append( (funicodeOrNone((c_node).prefix), + funicodeOrNone((c_node).href)) ) + elif c_node.type == tree.XML_DOCUMENT_NODE or \ + c_node.type == tree.XML_HTML_DOCUMENT_NODE: + # ignored for everything but result tree fragments + if is_fragment: + c_child = c_node.children + while c_child is not NULL: + _unpackNodeSetEntry(results, c_child, doc, context, 0) + c_child = c_child.next + elif c_node.type == tree.XML_XINCLUDE_START or \ + c_node.type == tree.XML_XINCLUDE_END: + pass + else: + raise NotImplementedError, \ + f"Not yet implemented result node type: {c_node.type}" + +cdef void _freeXPathObject(xpath.xmlXPathObject* xpathObj) noexcept: + """Free the XPath object, but *never* free the *content* of node sets. + Python dealloc will do that for us. + """ + if xpathObj.nodesetval is not NULL: + xpath.xmlXPathFreeNodeSet(xpathObj.nodesetval) + xpathObj.nodesetval = NULL + xpath.xmlXPathFreeObject(xpathObj) + +cdef _Element _instantiateElementFromXPath(xmlNode* c_node, _Document doc, + _BaseContext context): + # NOTE: this may copy the element - only call this when it can't leak + if c_node.doc != doc._c_doc and c_node.doc._private is NULL: + # not from the context document and not from a fake document + # either => may still be from a known document, e.g. one + # created by an extension function + node_doc = context._findDocumentForNode(c_node) + if node_doc is None: + # not from a known document at all! => can only make a + # safety copy here + c_node = tree.xmlDocCopyNode(c_node, doc._c_doc, 1) + else: + doc = node_doc + return _fakeDocElementFactory(doc, c_node) + +################################################################################ +# special str/unicode subclasses + +@cython.final +cdef class _ElementUnicodeResult(unicode): + cdef _Element _parent + cdef readonly object attrname + cdef readonly bint is_tail + + def getparent(self): + return self._parent + + @property + def is_text(self): + return self._parent is not None and not (self.is_tail or self.attrname is not None) + + @property + def is_attribute(self): + return self.attrname is not None + +cdef object _elementStringResultFactory(string_value, _Element parent, + attrname, bint is_tail): + result = _ElementUnicodeResult(string_value) + result._parent = parent + result.is_tail = is_tail + result.attrname = attrname + return result + +cdef object _buildElementStringResult(_Document doc, xmlNode* c_node, + _BaseContext context): + cdef _Element parent = None + cdef object attrname = None + cdef xmlNode* c_element + cdef bint is_tail + + if c_node.type == tree.XML_ATTRIBUTE_NODE: + attrname = _namespacedName(c_node) + is_tail = 0 + s = tree.xmlNodeGetContent(c_node) + try: + value = funicode(s) + finally: + tree.xmlFree(s) + c_element = NULL + else: + #assert c_node.type == tree.XML_TEXT_NODE or c_node.type == tree.XML_CDATA_SECTION_NODE, "invalid node type" + # may be tail text or normal text + value = funicode(c_node.content) + c_element = _previousElement(c_node) + is_tail = c_element is not NULL + + if not context._build_smart_strings: + return value + + if c_element is NULL: + # non-tail text or attribute text + c_element = c_node.parent + while c_element is not NULL and not _isElement(c_element): + c_element = c_element.parent + + if c_element is not NULL: + parent = _instantiateElementFromXPath(c_element, doc, context) + + return _elementStringResultFactory( + value, parent, attrname, is_tail) + +################################################################################ +# callbacks for XPath/XSLT extension functions + +cdef void _extension_function_call(_BaseContext context, function, + xpath.xmlXPathParserContext* ctxt, int nargs) noexcept: + cdef _Document doc + cdef xpath.xmlXPathObject* obj + cdef list args + cdef int i + doc = context._doc + try: + args = [] + for i in range(nargs): + obj = xpath.valuePop(ctxt) + o = _unwrapXPathObject(obj, doc, context) + _freeXPathObject(obj) + args.append(o) + args.reverse() + + res = function(context, *args) + # wrap result for XPath consumption + obj = _wrapXPathObject(res, doc, context) + # prevent Python from deallocating elements handed to libxml2 + context._hold(res) + xpath.valuePush(ctxt, obj) + except: + xpath.xmlXPathErr(ctxt, xpath.XPATH_EXPR_ERROR) + context._exc._store_raised() + finally: + return # swallow any further exceptions + +# lookup the function by name and call it + +cdef void _xpath_function_call(xpath.xmlXPathParserContext* ctxt, + int nargs) noexcept with gil: + cdef _BaseContext context + cdef xpath.xmlXPathContext* rctxt = ctxt.context + context = <_BaseContext> rctxt.userData + try: + function = context._find_cached_function(rctxt.functionURI, rctxt.function) + if function is not None: + _extension_function_call(context, function, ctxt, nargs) + else: + xpath.xmlXPathErr(ctxt, xpath.XPATH_UNKNOWN_FUNC_ERROR) + context._exc._store_exception(XPathFunctionError( + f"XPath function '{_namespacedNameFromNsName(rctxt.functionURI, rctxt.function)}' not found")) + except: + # may not be the right error, but we need to tell libxml2 *something* + xpath.xmlXPathErr(ctxt, xpath.XPATH_UNKNOWN_FUNC_ERROR) + context._exc._store_raised() + finally: + return # swallow any further exceptions diff --git a/venv/lib/python3.10/site-packages/lxml/html/ElementSoup.py b/venv/lib/python3.10/site-packages/lxml/html/ElementSoup.py new file mode 100644 index 0000000000000000000000000000000000000000..c35365d0510605c08588775d4e5598586c8f8311 --- /dev/null +++ b/venv/lib/python3.10/site-packages/lxml/html/ElementSoup.py @@ -0,0 +1,10 @@ +__doc__ = """Legacy interface to the BeautifulSoup HTML parser. +""" + +__all__ = ["parse", "convert_tree"] + +from .soupparser import convert_tree, parse as _parse + +def parse(file, beautifulsoup=None, makeelement=None): + root = _parse(file, beautifulsoup=beautifulsoup, makeelement=makeelement) + return root.getroot() diff --git a/venv/lib/python3.10/site-packages/lxml/html/__init__.py b/venv/lib/python3.10/site-packages/lxml/html/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2cee9f441d896b088bd873aa1ceef12abbb31dda --- /dev/null +++ b/venv/lib/python3.10/site-packages/lxml/html/__init__.py @@ -0,0 +1,1927 @@ +# Copyright (c) 2004 Ian Bicking. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# 2. 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. +# +# 3. Neither the name of Ian Bicking 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 IAN BICKING 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. + +"""The ``lxml.html`` tool set for HTML handling. +""" + + +__all__ = [ + 'document_fromstring', 'fragment_fromstring', 'fragments_fromstring', 'fromstring', + 'tostring', 'Element', 'defs', 'open_in_browser', 'submit_form', + 'find_rel_links', 'find_class', 'make_links_absolute', + 'resolve_base_href', 'iterlinks', 'rewrite_links', 'parse'] + + +import copy +import re + +from collections.abc import MutableMapping, MutableSet +from functools import partial +from urllib.parse import urljoin + +from .. import etree +from . import defs +from ._setmixin import SetMixin + + +def __fix_docstring(s): + # TODO: remove and clean up doctests + if not s: + return s + sub = re.compile(r"^(\s*)u'", re.M).sub + return sub(r"\1'", s) + + +XHTML_NAMESPACE = "http://www.w3.org/1999/xhtml" + +_rel_links_xpath = etree.XPath("descendant-or-self::a[@rel]|descendant-or-self::x:a[@rel]", + namespaces={'x':XHTML_NAMESPACE}) +_options_xpath = etree.XPath("descendant-or-self::option|descendant-or-self::x:option", + namespaces={'x':XHTML_NAMESPACE}) +_forms_xpath = etree.XPath("descendant-or-self::form|descendant-or-self::x:form", + namespaces={'x':XHTML_NAMESPACE}) +#_class_xpath = etree.XPath(r"descendant-or-self::*[regexp:match(@class, concat('\b', $class_name, '\b'))]", {'regexp': 'http://exslt.org/regular-expressions'}) +_class_xpath = etree.XPath("descendant-or-self::*[@class and contains(concat(' ', normalize-space(@class), ' '), concat(' ', $class_name, ' '))]") +_id_xpath = etree.XPath("descendant-or-self::*[@id=$id]") +_collect_string_content = etree.XPath("string()", smart_strings=False) +_iter_css_urls = re.compile(r'url\(('+'["][^"]*["]|'+"['][^']*[']|"+r'[^)]*)\)', re.I).finditer +_iter_css_imports = re.compile(r'@import "(.*?)"').finditer +_label_xpath = etree.XPath("//label[@for=$id]|//x:label[@for=$id]", + namespaces={'x':XHTML_NAMESPACE}) +_archive_re = re.compile(r'[^ ]+') +_parse_meta_refresh_url = re.compile( + r'[^;=]*;\s*(?:url\s*=\s*)?(?P.*)$', re.I).search + + +def _unquote_match(s, pos): + if s[:1] == '"' and s[-1:] == '"' or s[:1] == "'" and s[-1:] == "'": + return s[1:-1], pos+1 + else: + return s,pos + + +def _transform_result(typ, result): + """Convert the result back into the input type. + """ + if issubclass(typ, bytes): + return tostring(result, encoding='utf-8') + elif issubclass(typ, str): + return tostring(result, encoding='unicode') + else: + return result + + +def _nons(tag): + if isinstance(tag, str): + if tag[0] == '{' and tag[1:len(XHTML_NAMESPACE)+1] == XHTML_NAMESPACE: + return tag.split('}')[-1] + return tag + + +class Classes(MutableSet): + """Provides access to an element's class attribute as a set-like collection. + Usage:: + + >>> el = fromstring('') + >>> classes = el.classes # or: classes = Classes(el.attrib) + >>> classes |= ['block', 'paragraph'] + >>> el.get('class') + 'hidden large block paragraph' + >>> classes.toggle('hidden') + False + >>> el.get('class') + 'large block paragraph' + >>> classes -= ('some', 'classes', 'block') + >>> el.get('class') + 'large paragraph' + """ + def __init__(self, attributes): + self._attributes = attributes + self._get_class_value = partial(attributes.get, 'class', '') + + def add(self, value): + """ + Add a class. + + This has no effect if the class is already present. + """ + if not value or re.search(r'\s', value): + raise ValueError("Invalid class name: %r" % value) + classes = self._get_class_value().split() + if value in classes: + return + classes.append(value) + self._attributes['class'] = ' '.join(classes) + + def discard(self, value): + """ + Remove a class if it is currently present. + + If the class is not present, do nothing. + """ + if not value or re.search(r'\s', value): + raise ValueError("Invalid class name: %r" % value) + classes = [name for name in self._get_class_value().split() + if name != value] + if classes: + self._attributes['class'] = ' '.join(classes) + elif 'class' in self._attributes: + del self._attributes['class'] + + def remove(self, value): + """ + Remove a class; it must currently be present. + + If the class is not present, raise a KeyError. + """ + if not value or re.search(r'\s', value): + raise ValueError("Invalid class name: %r" % value) + super().remove(value) + + def __contains__(self, name): + classes = self._get_class_value() + return name in classes and name in classes.split() + + def __iter__(self): + return iter(self._get_class_value().split()) + + def __len__(self): + return len(self._get_class_value().split()) + + # non-standard methods + + def update(self, values): + """ + Add all names from 'values'. + """ + classes = self._get_class_value().split() + extended = False + for value in values: + if value not in classes: + classes.append(value) + extended = True + if extended: + self._attributes['class'] = ' '.join(classes) + + def toggle(self, value): + """ + Add a class name if it isn't there yet, or remove it if it exists. + + Returns true if the class was added (and is now enabled) and + false if it was removed (and is now disabled). + """ + if not value or re.search(r'\s', value): + raise ValueError("Invalid class name: %r" % value) + classes = self._get_class_value().split() + try: + classes.remove(value) + enabled = False + except ValueError: + classes.append(value) + enabled = True + if classes: + self._attributes['class'] = ' '.join(classes) + else: + del self._attributes['class'] + return enabled + + +class HtmlMixin: + + def set(self, key, value=None): + """set(self, key, value=None) + + Sets an element attribute. If no value is provided, or if the value is None, + creates a 'boolean' attribute without value, e.g. "
" + for ``form.set('novalidate')``. + """ + super().set(key, value) + + @property + def classes(self): + """ + A set-like wrapper around the 'class' attribute. + """ + return Classes(self.attrib) + + @classes.setter + def classes(self, classes): + assert isinstance(classes, Classes) # only allow "el.classes |= ..." etc. + value = classes._get_class_value() + if value: + self.set('class', value) + elif self.get('class') is not None: + del self.attrib['class'] + + @property + def base_url(self): + """ + Returns the base URL, given when the page was parsed. + + Use with ``urlparse.urljoin(el.base_url, href)`` to get + absolute URLs. + """ + return self.getroottree().docinfo.URL + + @property + def forms(self): + """ + Return a list of all the forms + """ + return _forms_xpath(self) + + @property + def body(self): + """ + Return the element. Can be called from a child element + to get the document's head. + """ + for element in self.getroottree().iter("body", f"{{{XHTML_NAMESPACE}}}body"): + return element + return None + + @property + def head(self): + """ + Returns the element. Can be called from a child + element to get the document's head. + """ + for element in self.getroottree().iter("head", f"{{{XHTML_NAMESPACE}}}head"): + return element + return None + + @property + def label(self): + """ + Get or set any