diff --git a/.gitattributes b/.gitattributes index 0c0153ac74ca196a4288ce693be0bdac562e73a7..a3d52156c6a4a4fdc57796e3856d5383d9f3b750 100644 --- a/.gitattributes +++ b/.gitattributes @@ -399,3 +399,12 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text .venv/lib/python3.12/site-packages/scipy.libs/libquadmath-2284e583.so.0.0.0 filter=lfs diff=lfs merge=lfs -text .venv/lib/python3.12/site-packages/scipy.libs/libquadmath-96973f99-934c22de.so.0.0.0 filter=lfs diff=lfs merge=lfs -text .venv/lib/python3.12/site-packages/scipy.libs/libscipy_openblas-5f890258.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/setuptools/_vendor/__pycache__/typing_extensions.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/setuptools/_vendor/backports/tarfile/__pycache__/__init__.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/setuptools/_vendor/inflect/__pycache__/__init__.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools/__pycache__/more.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/easy_install.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/__pycache__/fastjsonschema_validations.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/supervision/annotators/__pycache__/core.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/supervision/detection/__pycache__/core.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/sympy/assumptions/tests/__pycache__/test_query.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text diff --git a/.venv/lib/python3.12/site-packages/setuptools-78.1.0.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/setuptools-78.1.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools-78.1.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv/lib/python3.12/site-packages/setuptools-78.1.0.dist-info/METADATA b/.venv/lib/python3.12/site-packages/setuptools-78.1.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..83299c05e2e3fec725c891d7615a076292987010 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools-78.1.0.dist-info/METADATA @@ -0,0 +1,141 @@ +Metadata-Version: 2.4 +Name: setuptools +Version: 78.1.0 +Summary: Easily download, build, install, upgrade, and uninstall Python packages +Author-email: Python Packaging Authority +Project-URL: Source, https://github.com/pypa/setuptools +Project-URL: Documentation, https://setuptools.pypa.io/ +Project-URL: Changelog, https://setuptools.pypa.io/en/stable/history.html +Keywords: CPAN PyPI distutils eggs package management +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: System :: Archiving :: Packaging +Classifier: Topic :: System :: Systems Administration +Classifier: Topic :: Utilities +Requires-Python: >=3.9 +Description-Content-Type: text/x-rst +License-File: LICENSE +Provides-Extra: test +Requires-Dist: pytest!=8.1.*,>=6; extra == "test" +Requires-Dist: virtualenv>=13.0.0; extra == "test" +Requires-Dist: wheel>=0.44.0; extra == "test" +Requires-Dist: pip>=19.1; extra == "test" +Requires-Dist: packaging>=24.2; extra == "test" +Requires-Dist: jaraco.envs>=2.2; extra == "test" +Requires-Dist: pytest-xdist>=3; extra == "test" +Requires-Dist: jaraco.path>=3.7.2; extra == "test" +Requires-Dist: build[virtualenv]>=1.0.3; extra == "test" +Requires-Dist: filelock>=3.4.0; extra == "test" +Requires-Dist: ini2toml[lite]>=0.14; extra == "test" +Requires-Dist: tomli-w>=1.0.0; extra == "test" +Requires-Dist: pytest-timeout; extra == "test" +Requires-Dist: pytest-perf; sys_platform != "cygwin" and extra == "test" +Requires-Dist: jaraco.develop>=7.21; (python_version >= "3.9" and sys_platform != "cygwin") and extra == "test" +Requires-Dist: pytest-home>=0.5; extra == "test" +Requires-Dist: pytest-subprocess; extra == "test" +Requires-Dist: pyproject-hooks!=1.1; extra == "test" +Requires-Dist: jaraco.test>=5.5; extra == "test" +Provides-Extra: doc +Requires-Dist: sphinx>=3.5; extra == "doc" +Requires-Dist: jaraco.packaging>=9.3; extra == "doc" +Requires-Dist: rst.linker>=1.9; extra == "doc" +Requires-Dist: furo; extra == "doc" +Requires-Dist: sphinx-lint; extra == "doc" +Requires-Dist: jaraco.tidelift>=1.4; extra == "doc" +Requires-Dist: pygments-github-lexers==0.0.5; extra == "doc" +Requires-Dist: sphinx-favicon; extra == "doc" +Requires-Dist: sphinx-inline-tabs; extra == "doc" +Requires-Dist: sphinx-reredirects; extra == "doc" +Requires-Dist: sphinxcontrib-towncrier; extra == "doc" +Requires-Dist: sphinx-notfound-page<2,>=1; extra == "doc" +Requires-Dist: pyproject-hooks!=1.1; extra == "doc" +Requires-Dist: towncrier<24.7; extra == "doc" +Provides-Extra: ssl +Provides-Extra: certs +Provides-Extra: core +Requires-Dist: packaging>=24.2; extra == "core" +Requires-Dist: more_itertools>=8.8; extra == "core" +Requires-Dist: jaraco.text>=3.7; extra == "core" +Requires-Dist: importlib_metadata>=6; python_version < "3.10" and extra == "core" +Requires-Dist: tomli>=2.0.1; python_version < "3.11" and extra == "core" +Requires-Dist: wheel>=0.43.0; extra == "core" +Requires-Dist: platformdirs>=4.2.2; extra == "core" +Requires-Dist: jaraco.functools>=4; extra == "core" +Requires-Dist: more_itertools; extra == "core" +Provides-Extra: check +Requires-Dist: pytest-checkdocs>=2.4; extra == "check" +Requires-Dist: pytest-ruff>=0.2.1; sys_platform != "cygwin" and extra == "check" +Requires-Dist: ruff>=0.8.0; sys_platform != "cygwin" and extra == "check" +Provides-Extra: cover +Requires-Dist: pytest-cov; extra == "cover" +Provides-Extra: enabler +Requires-Dist: pytest-enabler>=2.2; extra == "enabler" +Provides-Extra: type +Requires-Dist: pytest-mypy; extra == "type" +Requires-Dist: mypy==1.14.*; extra == "type" +Requires-Dist: importlib_metadata>=7.0.2; python_version < "3.10" and extra == "type" +Requires-Dist: jaraco.develop>=7.21; sys_platform != "cygwin" and extra == "type" +Dynamic: license-file + +.. |pypi-version| image:: https://img.shields.io/pypi/v/setuptools.svg + :target: https://pypi.org/project/setuptools + +.. |py-version| image:: https://img.shields.io/pypi/pyversions/setuptools.svg + +.. |test-badge| image:: https://github.com/pypa/setuptools/actions/workflows/main.yml/badge.svg + :target: https://github.com/pypa/setuptools/actions?query=workflow%3A%22tests%22 + :alt: tests + +.. |ruff-badge| image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v2.json + :target: https://github.com/astral-sh/ruff + :alt: Ruff + +.. |docs-badge| image:: https://img.shields.io/readthedocs/setuptools/latest.svg + :target: https://setuptools.pypa.io + +.. |skeleton-badge| image:: https://img.shields.io/badge/skeleton-2025-informational + :target: https://blog.jaraco.com/skeleton + +.. |codecov-badge| image:: https://img.shields.io/codecov/c/github/pypa/setuptools/master.svg?logo=codecov&logoColor=white + :target: https://codecov.io/gh/pypa/setuptools + +.. |tidelift-badge| image:: https://tidelift.com/badges/github/pypa/setuptools?style=flat + :target: https://tidelift.com/subscription/pkg/pypi-setuptools?utm_source=pypi-setuptools&utm_medium=readme + +.. |discord-badge| image:: https://img.shields.io/discord/803025117553754132 + :target: https://discord.com/channels/803025117553754132/815945031150993468 + :alt: Discord + +|pypi-version| |py-version| |test-badge| |ruff-badge| |docs-badge| |skeleton-badge| |codecov-badge| |discord-badge| + +See the `Quickstart `_ +and the `User's Guide `_ for +instructions on how to use Setuptools. + +Questions and comments should be directed to `GitHub Discussions +`_. +Bug reports and especially tested patches may be +submitted directly to the `bug tracker +`_. + + +Code of Conduct +=============== + +Everyone interacting in the setuptools project's codebases, issue trackers, +chat rooms, and fora is expected to follow the +`PSF Code of Conduct `_. + + +For Enterprise +============== + +Available as part of the Tidelift Subscription. + +Setuptools and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use. + +`Learn more `_. diff --git a/.venv/lib/python3.12/site-packages/setuptools-78.1.0.dist-info/RECORD b/.venv/lib/python3.12/site-packages/setuptools-78.1.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..d929510cc5bb41d8dde979b656cb441aa71fb5f0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools-78.1.0.dist-info/RECORD @@ -0,0 +1,872 @@ +_distutils_hack/__init__.py,sha256=34HmvLo07j45Uvd2VR-2aRQ7lJD91sTK6zJgn5fphbQ,6755 +_distutils_hack/__pycache__/__init__.cpython-312.pyc,, +_distutils_hack/__pycache__/override.cpython-312.pyc,, +_distutils_hack/override.py,sha256=Eu_s-NF6VIZ4Cqd0tbbA5wtWky2IZPNd8et6GLt1mzo,44 +distutils-precedence.pth,sha256=JjjOniUA5XKl4N5_rtZmHrVp0baW_LoHsN0iPaX10iQ,151 +pkg_resources/__init__.py,sha256=-rh7XOnTxdGuC-_9FAyu5D6s8BL1UsBehxUtj7a-IVo,126203 +pkg_resources/__pycache__/__init__.cpython-312.pyc,, +pkg_resources/api_tests.txt,sha256=XEdvy4igHHrq2qNHNMHnlfO6XSQKNqOyLHbl6QcpfAI,12595 +pkg_resources/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pkg_resources/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pkg_resources/tests/__pycache__/__init__.cpython-312.pyc,, +pkg_resources/tests/__pycache__/test_find_distributions.cpython-312.pyc,, +pkg_resources/tests/__pycache__/test_integration_zope_interface.cpython-312.pyc,, +pkg_resources/tests/__pycache__/test_markers.cpython-312.pyc,, +pkg_resources/tests/__pycache__/test_pkg_resources.cpython-312.pyc,, +pkg_resources/tests/__pycache__/test_resources.cpython-312.pyc,, +pkg_resources/tests/__pycache__/test_working_set.cpython-312.pyc,, +pkg_resources/tests/data/my-test-package-source/__pycache__/setup.cpython-312.pyc,, +pkg_resources/tests/data/my-test-package-source/setup.cfg,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pkg_resources/tests/data/my-test-package-source/setup.py,sha256=1VobhAZbMb7M9mfhb_NE8PwDsvukoWLs9aUAS0pYhe8,105 +pkg_resources/tests/data/my-test-package-zip/my-test-package.zip,sha256=AYRcQ39GVePPnMT8TknP1gdDHyJnXhthESmpAjnzSCI,1809 +pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/PKG-INFO,sha256=JvWv9Io2PAuYwEEw2fBW4Qc5YvdbkscpKX1kmLzsoHk,187 +pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/SOURCES.txt,sha256=4ClkH8eTovZrdVrJFsVuxdbMEF--lBVSuKonDAPE5Jc,208 +pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/dependency_links.txt,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1 +pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/top_level.txt,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1 +pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1 +pkg_resources/tests/data/my-test-package_zipped-egg/my_test_package-1.0-py3.7.egg,sha256=ZTlMGxjRGiKDNkiA2c75jbQH2TWIteP00irF9gvczbo,843 +pkg_resources/tests/test_find_distributions.py,sha256=U91cov5L1COAIWLNq3Xy4plU7_MnOE1WtXMu6iV2waM,1972 +pkg_resources/tests/test_integration_zope_interface.py,sha256=nzVoK557KZQN0V3DIQ1sVeaCOgt4Kpl-CODAWsO7pmc,1652 +pkg_resources/tests/test_markers.py,sha256=0orKg7UMDf7fnuNQvRMOc-EF9EAP_JTQnk4mtGgbW50,241 +pkg_resources/tests/test_pkg_resources.py,sha256=5Mt4bJQhLCL8j8cC46Uv32Np2Xc1TTxLGawIfET55Fk,17111 +pkg_resources/tests/test_resources.py,sha256=K0LqMAUGpRQ9pUb9K0vyI7GesvtlQvTH074m-E2VQlo,31252 +pkg_resources/tests/test_working_set.py,sha256=lRtGJWIixSwSMSbjHgRxeJEQiLMRXcz3xzJL2qL7eXY,8602 +setuptools-78.1.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +setuptools-78.1.0.dist-info/METADATA,sha256=RESmtUmo67AuFzn0N1r3dWyEH5bwwxB3oYMnPHRivRA,6599 +setuptools-78.1.0.dist-info/RECORD,, +setuptools-78.1.0.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91 +setuptools-78.1.0.dist-info/entry_points.txt,sha256=zkgthpf_Fa9NVE9p6FKT3Xk9DR1faAcRU4coggsV7jA,2449 +setuptools-78.1.0.dist-info/licenses/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023 +setuptools-78.1.0.dist-info/top_level.txt,sha256=d9yL39v_W7qmKDDSH6sT4bE0j_Ls1M3P161OGgdsm4g,41 +setuptools/__init__.py,sha256=AQsMeRFWz9CQ9aBtcSkbB4Dn8t2w86-GPriklpoAjew,10406 +setuptools/__pycache__/__init__.cpython-312.pyc,, +setuptools/__pycache__/_core_metadata.cpython-312.pyc,, +setuptools/__pycache__/_entry_points.cpython-312.pyc,, +setuptools/__pycache__/_imp.cpython-312.pyc,, +setuptools/__pycache__/_importlib.cpython-312.pyc,, +setuptools/__pycache__/_itertools.cpython-312.pyc,, +setuptools/__pycache__/_normalization.cpython-312.pyc,, +setuptools/__pycache__/_path.cpython-312.pyc,, +setuptools/__pycache__/_reqs.cpython-312.pyc,, +setuptools/__pycache__/_shutil.cpython-312.pyc,, +setuptools/__pycache__/_static.cpython-312.pyc,, +setuptools/__pycache__/archive_util.cpython-312.pyc,, +setuptools/__pycache__/build_meta.cpython-312.pyc,, +setuptools/__pycache__/depends.cpython-312.pyc,, +setuptools/__pycache__/discovery.cpython-312.pyc,, +setuptools/__pycache__/dist.cpython-312.pyc,, +setuptools/__pycache__/errors.cpython-312.pyc,, +setuptools/__pycache__/extension.cpython-312.pyc,, +setuptools/__pycache__/glob.cpython-312.pyc,, +setuptools/__pycache__/installer.cpython-312.pyc,, +setuptools/__pycache__/launch.cpython-312.pyc,, +setuptools/__pycache__/logging.cpython-312.pyc,, +setuptools/__pycache__/modified.cpython-312.pyc,, +setuptools/__pycache__/monkey.cpython-312.pyc,, +setuptools/__pycache__/msvc.cpython-312.pyc,, +setuptools/__pycache__/namespaces.cpython-312.pyc,, +setuptools/__pycache__/package_index.cpython-312.pyc,, +setuptools/__pycache__/sandbox.cpython-312.pyc,, +setuptools/__pycache__/unicode_utils.cpython-312.pyc,, +setuptools/__pycache__/version.cpython-312.pyc,, +setuptools/__pycache__/warnings.cpython-312.pyc,, +setuptools/__pycache__/wheel.cpython-312.pyc,, +setuptools/__pycache__/windows_support.cpython-312.pyc,, +setuptools/_core_metadata.py,sha256=T7Tjp-WSoN881adev3R1wzXCPnkDHqbC2MgylN1yjS8,11978 +setuptools/_distutils/__init__.py,sha256=xGYuhWwLG07J0Q49BVnEjPy6wyDcd6veJMDJX7ljlyM,359 +setuptools/_distutils/__pycache__/__init__.cpython-312.pyc,, +setuptools/_distutils/__pycache__/_log.cpython-312.pyc,, +setuptools/_distutils/__pycache__/_macos_compat.cpython-312.pyc,, +setuptools/_distutils/__pycache__/_modified.cpython-312.pyc,, +setuptools/_distutils/__pycache__/_msvccompiler.cpython-312.pyc,, +setuptools/_distutils/__pycache__/archive_util.cpython-312.pyc,, +setuptools/_distutils/__pycache__/ccompiler.cpython-312.pyc,, +setuptools/_distutils/__pycache__/cmd.cpython-312.pyc,, +setuptools/_distutils/__pycache__/core.cpython-312.pyc,, +setuptools/_distutils/__pycache__/cygwinccompiler.cpython-312.pyc,, +setuptools/_distutils/__pycache__/debug.cpython-312.pyc,, +setuptools/_distutils/__pycache__/dep_util.cpython-312.pyc,, +setuptools/_distutils/__pycache__/dir_util.cpython-312.pyc,, +setuptools/_distutils/__pycache__/dist.cpython-312.pyc,, +setuptools/_distutils/__pycache__/errors.cpython-312.pyc,, +setuptools/_distutils/__pycache__/extension.cpython-312.pyc,, +setuptools/_distutils/__pycache__/fancy_getopt.cpython-312.pyc,, +setuptools/_distutils/__pycache__/file_util.cpython-312.pyc,, +setuptools/_distutils/__pycache__/filelist.cpython-312.pyc,, +setuptools/_distutils/__pycache__/log.cpython-312.pyc,, +setuptools/_distutils/__pycache__/spawn.cpython-312.pyc,, +setuptools/_distutils/__pycache__/sysconfig.cpython-312.pyc,, +setuptools/_distutils/__pycache__/text_file.cpython-312.pyc,, +setuptools/_distutils/__pycache__/unixccompiler.cpython-312.pyc,, +setuptools/_distutils/__pycache__/util.cpython-312.pyc,, +setuptools/_distutils/__pycache__/version.cpython-312.pyc,, +setuptools/_distutils/__pycache__/versionpredicate.cpython-312.pyc,, +setuptools/_distutils/__pycache__/zosccompiler.cpython-312.pyc,, +setuptools/_distutils/_log.py,sha256=i-lNTTcXS8TmWITJ6DODGvtW5z5tMattJQ76h8rZxQU,42 +setuptools/_distutils/_macos_compat.py,sha256=JzUGhF4E5yIITHbUaPobZEWjGHdrrcNV63z86S4RjBc,239 +setuptools/_distutils/_modified.py,sha256=RF1n1CexyDYV3lvGbeXS0s-XCJVboDOIUbA8wEQqYTY,3211 +setuptools/_distutils/_msvccompiler.py,sha256=9PSfSHxvJnHnQL6Sqz4Xcz7iaBIT62p6BheQzGsSlwo,335 +setuptools/_distutils/archive_util.py,sha256=Qw2z-Pt-NV8lNUQrzjs3XDGWCWHMPnqHLyt8TiD2XEA,8884 +setuptools/_distutils/ccompiler.py,sha256=FKVjqzGJ7c-FtouNjhLiaMPm5LKMZHHAruXf8LU216c,524 +setuptools/_distutils/cmd.py,sha256=hXtaRaH7QBnfNOIqEvCt47iwZzD9MVvBdhhdQctHsxM,22186 +setuptools/_distutils/command/__init__.py,sha256=GfFAzbBqk1qxSH4BdaKioKS4hRRnD44BAmwEN85C4u8,386 +setuptools/_distutils/command/__pycache__/__init__.cpython-312.pyc,, +setuptools/_distutils/command/__pycache__/_framework_compat.cpython-312.pyc,, +setuptools/_distutils/command/__pycache__/bdist.cpython-312.pyc,, +setuptools/_distutils/command/__pycache__/bdist_dumb.cpython-312.pyc,, +setuptools/_distutils/command/__pycache__/bdist_rpm.cpython-312.pyc,, +setuptools/_distutils/command/__pycache__/build.cpython-312.pyc,, +setuptools/_distutils/command/__pycache__/build_clib.cpython-312.pyc,, +setuptools/_distutils/command/__pycache__/build_ext.cpython-312.pyc,, +setuptools/_distutils/command/__pycache__/build_py.cpython-312.pyc,, +setuptools/_distutils/command/__pycache__/build_scripts.cpython-312.pyc,, +setuptools/_distutils/command/__pycache__/check.cpython-312.pyc,, +setuptools/_distutils/command/__pycache__/clean.cpython-312.pyc,, +setuptools/_distutils/command/__pycache__/config.cpython-312.pyc,, +setuptools/_distutils/command/__pycache__/install.cpython-312.pyc,, +setuptools/_distutils/command/__pycache__/install_data.cpython-312.pyc,, +setuptools/_distutils/command/__pycache__/install_egg_info.cpython-312.pyc,, +setuptools/_distutils/command/__pycache__/install_headers.cpython-312.pyc,, +setuptools/_distutils/command/__pycache__/install_lib.cpython-312.pyc,, +setuptools/_distutils/command/__pycache__/install_scripts.cpython-312.pyc,, +setuptools/_distutils/command/__pycache__/sdist.cpython-312.pyc,, +setuptools/_distutils/command/_framework_compat.py,sha256=0iZdSJYzGRWCCvzRDKE-R0-_yaAYvFMd1ylXb2eYXug,1609 +setuptools/_distutils/command/bdist.py,sha256=jWtk61R7fWNUUNxJV0thTZzU5n80L3Ay1waSiP9kiLA,5854 +setuptools/_distutils/command/bdist_dumb.py,sha256=Hx1jAqoZNxYIy4N5TLzUp6J5fi8Ls18py7UlLNFhO2E,4631 +setuptools/_distutils/command/bdist_rpm.py,sha256=nxcXXv5a7B-1ntWu4DbGmCtES4EBINrJaBQcRNAYCJI,21785 +setuptools/_distutils/command/build.py,sha256=SpHlagf0iNaKVyIhxDfhPFZ8X1-LAWOCQACy-yt2K0w,5923 +setuptools/_distutils/command/build_clib.py,sha256=aMqZcUfCbOAu_xr-A9iW-Q9YZHzpDGLRTezOgMQJmSQ,7777 +setuptools/_distutils/command/build_ext.py,sha256=zrrsu9HXnzV6bXYbJuZCK4SwVZMjKnl4pG1o3bNcxtc,32710 +setuptools/_distutils/command/build_py.py,sha256=Vfq-INemoMbg6f003BTy_Ufp8bjOZhmFIhpKMcfXLgs,16696 +setuptools/_distutils/command/build_scripts.py,sha256=tUpEzwTsnrP8qrNory3ldPB240QDCFkMp-pdYPs2wTk,5118 +setuptools/_distutils/command/check.py,sha256=yoNe2MPY4JcTM7rwoIQdfZ75q5Ri058I2coi-Gq9CjM,4946 +setuptools/_distutils/command/clean.py,sha256=dQAacOabwBXU9JoZ-1GFusq3eFltDaeXJFSYncqGbvE,2644 +setuptools/_distutils/command/config.py,sha256=BuUdPu91Vo9w44xzD1RQfiyXfSfVcNpeX3aeoKcGAOw,12818 +setuptools/_distutils/command/install.py,sha256=-JenB-mua4hc2RI_-W8F9PnP_J-OaFO7E0PJGKxLo1o,30072 +setuptools/_distutils/command/install_data.py,sha256=GzBlUWWKubTYJlP-L0auUriq9cL-5RKOcoyHTttKj0Q,2875 +setuptools/_distutils/command/install_egg_info.py,sha256=ffiLoU1ivQJ8q2_WL7ZygZbUcOsgdFLKL7otEIJWWkI,2868 +setuptools/_distutils/command/install_headers.py,sha256=5ciKCj8c3XKsYNKdkdMvnypaUCKcoWCDeeZij3fD-Z4,1272 +setuptools/_distutils/command/install_lib.py,sha256=2s9-m5-b1qKm51F28lB5L39Z6vv_GHMlv9dNBSupok0,8588 +setuptools/_distutils/command/install_scripts.py,sha256=M0pPdiaqB7TGmqTMujpGGeiL0Iq_CTeGjMFtrmDmwzM,2002 +setuptools/_distutils/command/sdist.py,sha256=cRIF6Ht1hJ6ayOOFVycMFBUNxjo94e_rFYPx4Hi8Ahc,19151 +setuptools/_distutils/compat/__init__.py,sha256=J20aXGjJ86Rg41xFLIWlcWCgZ9edMdJ9vvdNEQ87vPQ,522 +setuptools/_distutils/compat/__pycache__/__init__.cpython-312.pyc,, +setuptools/_distutils/compat/__pycache__/numpy.cpython-312.pyc,, +setuptools/_distutils/compat/__pycache__/py39.cpython-312.pyc,, +setuptools/_distutils/compat/numpy.py,sha256=UFgneZw9w97g4c-yGoAIOyLxUOWQ-fPRIhhfMs7_Ouc,167 +setuptools/_distutils/compat/py39.py,sha256=hOsD6lwZLqZoMnacNJ3P6nUA-LJQhEpVtYTzVH0o96M,1964 +setuptools/_distutils/compilers/C/__pycache__/base.cpython-312.pyc,, +setuptools/_distutils/compilers/C/__pycache__/cygwin.cpython-312.pyc,, +setuptools/_distutils/compilers/C/__pycache__/errors.cpython-312.pyc,, +setuptools/_distutils/compilers/C/__pycache__/msvc.cpython-312.pyc,, +setuptools/_distutils/compilers/C/__pycache__/unix.cpython-312.pyc,, +setuptools/_distutils/compilers/C/__pycache__/zos.cpython-312.pyc,, +setuptools/_distutils/compilers/C/base.py,sha256=XR1rBCStCquqm7QOYXD41-LfvsFcPpGxrwxeXzJyn_w,54876 +setuptools/_distutils/compilers/C/cygwin.py,sha256=DUlwQSb55aj7OdcmcddrmCmVEjEaxIiJ5hHUO3GBPNs,11844 +setuptools/_distutils/compilers/C/errors.py,sha256=sKOVzJajMUmNdfywo9UM_QQGsKFcclDhtI5TlCiXMLc,573 +setuptools/_distutils/compilers/C/msvc.py,sha256=elzG8v9jN5QytLMwLCdUdSuZ3eZ3R98VUvnm9Y2PBCA,21404 +setuptools/_distutils/compilers/C/tests/__pycache__/test_base.cpython-312.pyc,, +setuptools/_distutils/compilers/C/tests/__pycache__/test_cygwin.cpython-312.pyc,, +setuptools/_distutils/compilers/C/tests/__pycache__/test_mingw.cpython-312.pyc,, +setuptools/_distutils/compilers/C/tests/__pycache__/test_msvc.cpython-312.pyc,, +setuptools/_distutils/compilers/C/tests/__pycache__/test_unix.cpython-312.pyc,, +setuptools/_distutils/compilers/C/tests/test_base.py,sha256=rdhHc56bhXtm5NnN9BSHwr6c69UqzMItZQzlw2AsdMc,2706 +setuptools/_distutils/compilers/C/tests/test_cygwin.py,sha256=UgV2VgUXj3VulcbDc0UBWfEyJDx42tgSwS4LzHix3mY,2701 +setuptools/_distutils/compilers/C/tests/test_mingw.py,sha256=hCmwyywISpRoyOySbFHBL4TprWRV0mUWDKmOLO8XBXE,1900 +setuptools/_distutils/compilers/C/tests/test_msvc.py,sha256=DlGjmZ1mBSMXIgmlu80BKc7V-EJOZuYucwJwFh5dn28,4151 +setuptools/_distutils/compilers/C/tests/test_unix.py,sha256=ErbYWio7ejY2ZqQmPk4AwOu1HFW4-_-aZdUvGa1W2Fw,11834 +setuptools/_distutils/compilers/C/unix.py,sha256=l7CxY4rDJAECJo-vcv6io0SBmmPJ9JmN5mSmZcin2VU,16502 +setuptools/_distutils/compilers/C/zos.py,sha256=vnNeWLRZkdIkdZ-YyBnL8idTUfcCOn0tLMW5OBJ0ScU,6586 +setuptools/_distutils/core.py,sha256=GEHKaFC48T3o-_SmH4864GvKyx1IgbVC6ISIPVlx7a4,9364 +setuptools/_distutils/cygwinccompiler.py,sha256=mG_cU8SVZ4amD_VtF5vH6BXP0-kghGsDPbDSXrQ963c,594 +setuptools/_distutils/debug.py,sha256=N6MrTAqK6l9SVk6tWweR108PM8Ol7qNlfyV-nHcLhsY,139 +setuptools/_distutils/dep_util.py,sha256=xN75p6ZpHhMiHEc-rpL2XilJQynHnDNiafHteaZ4tjU,349 +setuptools/_distutils/dir_util.py,sha256=DXPUlfVVGsg9B-Jgg4At_j9T7vM60OgwNXkQHqTo7-I,7236 +setuptools/_distutils/dist.py,sha256=gW598UE0WMkzXQQ31Nr-8L7MPw0oIOz5OSSRzYZlwrM,55794 +setuptools/_distutils/errors.py,sha256=PPE2oDRh5y9Q1beKK9rhdvDaCzQhi4HCXs4KcqfqgZY,3092 +setuptools/_distutils/extension.py,sha256=Foyu4gULcPqm1_U9zrYYHxNk4NqglXv1rbsOk_QrSds,11155 +setuptools/_distutils/fancy_getopt.py,sha256=PjdO-bWCW0imV_UN-MGEw9R2GP2OiE8pHjITgmTAY3Q,17895 +setuptools/_distutils/file_util.py,sha256=YFQL_pD3hLuER9II_H6-hDC_YIGEookdd4wedLuiTW0,7978 +setuptools/_distutils/filelist.py,sha256=MBeSRJmPcKmDv8ooZgSU4BiQPZ0Khwv8l_jhD50XycI,15337 +setuptools/_distutils/log.py,sha256=VyBs5j7z4-K6XTEEBThUc9HyMpoPLGtQpERqbz5ylww,1200 +setuptools/_distutils/spawn.py,sha256=zseCh9sEifyp0I5Vg719JNIASlROJ2ehXqQnHlpt89Q,4086 +setuptools/_distutils/sysconfig.py,sha256=KeI8OHbMuEzHJ8Q0cBez9KZny8iRy6Z6Y0AkMz1jlsU,19728 +setuptools/_distutils/tests/__init__.py,sha256=j-IoPZEtQv3EOPuqNTwalr6GLyRjzCC-OOaNvZzmHsI,1485 +setuptools/_distutils/tests/__pycache__/__init__.cpython-312.pyc,, +setuptools/_distutils/tests/__pycache__/support.cpython-312.pyc,, +setuptools/_distutils/tests/__pycache__/test_archive_util.cpython-312.pyc,, +setuptools/_distutils/tests/__pycache__/test_bdist.cpython-312.pyc,, +setuptools/_distutils/tests/__pycache__/test_bdist_dumb.cpython-312.pyc,, +setuptools/_distutils/tests/__pycache__/test_bdist_rpm.cpython-312.pyc,, +setuptools/_distutils/tests/__pycache__/test_build.cpython-312.pyc,, +setuptools/_distutils/tests/__pycache__/test_build_clib.cpython-312.pyc,, +setuptools/_distutils/tests/__pycache__/test_build_ext.cpython-312.pyc,, +setuptools/_distutils/tests/__pycache__/test_build_py.cpython-312.pyc,, +setuptools/_distutils/tests/__pycache__/test_build_scripts.cpython-312.pyc,, +setuptools/_distutils/tests/__pycache__/test_check.cpython-312.pyc,, +setuptools/_distutils/tests/__pycache__/test_clean.cpython-312.pyc,, +setuptools/_distutils/tests/__pycache__/test_cmd.cpython-312.pyc,, +setuptools/_distutils/tests/__pycache__/test_config_cmd.cpython-312.pyc,, +setuptools/_distutils/tests/__pycache__/test_core.cpython-312.pyc,, +setuptools/_distutils/tests/__pycache__/test_dir_util.cpython-312.pyc,, +setuptools/_distutils/tests/__pycache__/test_dist.cpython-312.pyc,, +setuptools/_distutils/tests/__pycache__/test_extension.cpython-312.pyc,, +setuptools/_distutils/tests/__pycache__/test_file_util.cpython-312.pyc,, +setuptools/_distutils/tests/__pycache__/test_filelist.cpython-312.pyc,, +setuptools/_distutils/tests/__pycache__/test_install.cpython-312.pyc,, +setuptools/_distutils/tests/__pycache__/test_install_data.cpython-312.pyc,, +setuptools/_distutils/tests/__pycache__/test_install_headers.cpython-312.pyc,, +setuptools/_distutils/tests/__pycache__/test_install_lib.cpython-312.pyc,, +setuptools/_distutils/tests/__pycache__/test_install_scripts.cpython-312.pyc,, +setuptools/_distutils/tests/__pycache__/test_log.cpython-312.pyc,, +setuptools/_distutils/tests/__pycache__/test_modified.cpython-312.pyc,, +setuptools/_distutils/tests/__pycache__/test_sdist.cpython-312.pyc,, +setuptools/_distutils/tests/__pycache__/test_spawn.cpython-312.pyc,, +setuptools/_distutils/tests/__pycache__/test_sysconfig.cpython-312.pyc,, +setuptools/_distutils/tests/__pycache__/test_text_file.cpython-312.pyc,, +setuptools/_distutils/tests/__pycache__/test_util.cpython-312.pyc,, +setuptools/_distutils/tests/__pycache__/test_version.cpython-312.pyc,, +setuptools/_distutils/tests/__pycache__/test_versionpredicate.cpython-312.pyc,, +setuptools/_distutils/tests/__pycache__/unix_compat.cpython-312.pyc,, +setuptools/_distutils/tests/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_distutils/tests/compat/__pycache__/__init__.cpython-312.pyc,, +setuptools/_distutils/tests/compat/__pycache__/py39.cpython-312.pyc,, +setuptools/_distutils/tests/compat/py39.py,sha256=t0GBTM-30jX-9zCfkwlNBFtzzabemx6065mJ0d9_VRw,1026 +setuptools/_distutils/tests/support.py,sha256=tjsYsyxvpTK4NrkCseh2ujvDIGV0Mf_b5SI5fP2T0yM,4099 +setuptools/_distutils/tests/test_archive_util.py,sha256=jozimSwPBF-JoJfN_vDaiVGZp66BNcWZGh34FlW57DQ,11787 +setuptools/_distutils/tests/test_bdist.py,sha256=xNHxUsLlHsZQRwkzLb_iSD24s-9Mk-NX2ffBWwOyPyc,1396 +setuptools/_distutils/tests/test_bdist_dumb.py,sha256=QF05MHNhPOdZyh88Xpw8KsO64s7pRFkl8KL-RoV4XK0,2247 +setuptools/_distutils/tests/test_bdist_rpm.py,sha256=Hdm-pwWgyaoGdGbEcGZa8cRhGU45y8gHK8umOanTjik,3932 +setuptools/_distutils/tests/test_build.py,sha256=JJY5XpOZco25ZY0pstxl-iI8mHsWP0ujf5o8aOtuZYY,1742 +setuptools/_distutils/tests/test_build_clib.py,sha256=Mo1ZFb4C1VXBYOGvnallwN7YCnTtr24akLDO8Zi4CsY,4331 +setuptools/_distutils/tests/test_build_ext.py,sha256=QFO9qYVhWWdJu17HXc4x9RMnLZlhk0lAHi9HVppbuX4,22545 +setuptools/_distutils/tests/test_build_py.py,sha256=NsfmRrojOHBXNMqWR_mp5g4PLTgjhD7iZFUffGZFIdw,6882 +setuptools/_distutils/tests/test_build_scripts.py,sha256=cD-FRy-oX55sXRX5Ez5xQCaeHrWajyKc4Xuwv2fe48w,2880 +setuptools/_distutils/tests/test_check.py,sha256=hHSV07qf7YoSxGsTbbsUQ9tssZz5RRNdbrY1s2SwaFI,6226 +setuptools/_distutils/tests/test_clean.py,sha256=hPH6jfIpGFUrvWbF1txkiNVSNaAxt2wq5XjV499zO4E,1240 +setuptools/_distutils/tests/test_cmd.py,sha256=bgRB79mitoOKR1OiyZHnCogvGxt3pWkxeTqIC04lQWQ,3254 +setuptools/_distutils/tests/test_config_cmd.py,sha256=Zs6WX0IfxDvmuC19XzuVNnYCnTr9Y-hl73TAmDSBN4Y,2664 +setuptools/_distutils/tests/test_core.py,sha256=L7XKVAxa-MGoAZeANopnuK9fRKneYhkSQpgw8XQvcF8,3829 +setuptools/_distutils/tests/test_dir_util.py,sha256=E84lC-k4riVUwURyWaQ0Jqx2ui2-io-0RuJa3M7qkJs,4500 +setuptools/_distutils/tests/test_dist.py,sha256=a6wlc5fQJd5qQ6HOndzcupNhjTxvj6-_JLtpuYvaP1M,18793 +setuptools/_distutils/tests/test_extension.py,sha256=-YejLgZCuycFrOBd64pVH0JvwMc9NwhzHvQxvvjXHqk,3670 +setuptools/_distutils/tests/test_file_util.py,sha256=livjnl3FkilQlrB2rFdFQq9nvjEVZHynNya0bfzv_b4,3522 +setuptools/_distutils/tests/test_filelist.py,sha256=rJwkqCUfkGDgWlD22TozsT8ycbupMHB8DXqThzwT1T4,10766 +setuptools/_distutils/tests/test_install.py,sha256=TfCB0ykhIxydIC2Q4SuTAZzSHvteMHgrBL9whoSgK9Q,8618 +setuptools/_distutils/tests/test_install_data.py,sha256=vKq3K97k0hBAnOg38nmwEdf7cEDVr9rTVyCeJolgb4A,2464 +setuptools/_distutils/tests/test_install_headers.py,sha256=PVAYpo_tYl980Qf64DPOmmSvyefIHdU06f7VsJeZykE,936 +setuptools/_distutils/tests/test_install_lib.py,sha256=qri6Rl-maNTQrNDV8DbeXNl0hjsfRIKiI4rfZLrmWBI,3612 +setuptools/_distutils/tests/test_install_scripts.py,sha256=KE3v0cDkFW-90IOID-OmZZGM2mhy-ZkEuuW7UXS2SHw,1600 +setuptools/_distutils/tests/test_log.py,sha256=isFtOufloCyEdZaQOV7cVUr46GwtdVMj43mGBB5XH7k,323 +setuptools/_distutils/tests/test_modified.py,sha256=h1--bOWmtJo1bpVV6uRhdnS9br71CBiNDM1MDwSGpug,4221 +setuptools/_distutils/tests/test_sdist.py,sha256=cfzUhlCA418-1vH9ta3IBs26c_jUBbkJoFOK5GnAyNk,15062 +setuptools/_distutils/tests/test_spawn.py,sha256=eS8w9D7bTxyFLSyRahJWeuh8Kc1F8RWWiY_dSG5B5Bc,4803 +setuptools/_distutils/tests/test_sysconfig.py,sha256=lxM8LsUi1TomjDV4HoYK8u5nUoBkeNL60Uq8PY1DcwU,11986 +setuptools/_distutils/tests/test_text_file.py,sha256=WQWSB5AfdBDZaMA8BFgipJPnsJb_2SKMfL90fSkRVtw,3460 +setuptools/_distutils/tests/test_util.py,sha256=H9zlZ4z4Vh4TfjNYDBsxP7wguQLpxCfJYyOcm1yZU3c,7988 +setuptools/_distutils/tests/test_version.py,sha256=ahfg_mP8wRy1sgwY-_Px5hrjgf6_upTIpnCgpR4yWRk,2750 +setuptools/_distutils/tests/test_versionpredicate.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_distutils/tests/unix_compat.py,sha256=z-op6C2iVdX1aq5BIBR7cqOxijKE97alNwJqHNdLpoI,386 +setuptools/_distutils/text_file.py,sha256=z4dkOJBr9Bo2LG0TNqm8sD63LEEaKSSP0J0bWBrFG3c,12101 +setuptools/_distutils/unixccompiler.py,sha256=1bXJWH4fiu_A2WfriHzf88xjllQTXnnjUkZdRKs9cWU,212 +setuptools/_distutils/util.py,sha256=Njfnqk60zMdkiAjRnGcTWX3t49-obHapOlbNvyIl02I,18094 +setuptools/_distutils/version.py,sha256=vImT5-ECXkQ21oKL0XYFiTqK6NyM09cpzBNoA_34CQU,12619 +setuptools/_distutils/versionpredicate.py,sha256=qBWQ6wTj12ODytoTmIydefIY2jb4uY1sdbgbuLn-IJM,5205 +setuptools/_distutils/zosccompiler.py,sha256=svdiXZ2kdcwKrJKfhUhib03y8gz7aGZKukXH3I7YkBc,58 +setuptools/_entry_points.py,sha256=Y3QUE9JKFW_YyquDnpffNWSs6f3jKEt1e-dnx--9-Kw,2310 +setuptools/_imp.py,sha256=YY1EjZEN-0zYci1cxO10B_adAEOr7i8eK8JoCc9Ierc,2435 +setuptools/_importlib.py,sha256=aKIjcK0HKXNz2D-XTrxaixGn_juTkONwmu3dcheMOF0,223 +setuptools/_itertools.py,sha256=jWRfsIrpC7myooz3hDURj9GtvpswZeKXg2HakmEhNjo,657 +setuptools/_normalization.py,sha256=kAmGfrwjF5djydEfLLyKgjkXCbL_0_ZxUPO-DlLlmIY,5824 +setuptools/_path.py,sha256=cPv41v03HD7uEYqCIo-E_cGRfpPVr4lywBCiK-HSrCg,2685 +setuptools/_reqs.py,sha256=QI3C9uOBSNRccu208qPnixHx51nxCry7_nPTIJaSYxM,1438 +setuptools/_shutil.py,sha256=cAOllcoyMTXs5JLoybQi29yI5gABk82hepJyOBv2bMw,1496 +setuptools/_static.py,sha256=GTR79gESF1_JaK4trLkpDrEuCeEtPlwQW0MRv7VNQX4,4855 +setuptools/_vendor/__pycache__/typing_extensions.cpython-312.pyc,, +setuptools/_vendor/autocommand-2.2.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +setuptools/_vendor/autocommand-2.2.2.dist-info/LICENSE,sha256=reeNBJgtaZctREqOFKlPh6IzTdOFXMgDSOqOJAqg3y0,7634 +setuptools/_vendor/autocommand-2.2.2.dist-info/METADATA,sha256=OADZuR3O6iBlpu1ieTgzYul6w4uOVrk0P0BO5TGGAJk,15006 +setuptools/_vendor/autocommand-2.2.2.dist-info/RECORD,sha256=giu6ZrQVJvpUcYa4AiH4XaUNZSvuVJPb_l0UCFES8MM,1308 +setuptools/_vendor/autocommand-2.2.2.dist-info/WHEEL,sha256=2wepM1nk4DS4eFpYrW1TTqPcoGNfHhhO_i5m4cOimbo,92 +setuptools/_vendor/autocommand-2.2.2.dist-info/top_level.txt,sha256=AzfhgKKS8EdAwWUTSF8mgeVQbXOY9kokHB6kSqwwqu0,12 +setuptools/_vendor/autocommand/__init__.py,sha256=zko5Rnvolvb-UXjCx_2ArPTGBWwUK5QY4LIQIKYR7As,1037 +setuptools/_vendor/autocommand/__pycache__/__init__.cpython-312.pyc,, +setuptools/_vendor/autocommand/__pycache__/autoasync.cpython-312.pyc,, +setuptools/_vendor/autocommand/__pycache__/autocommand.cpython-312.pyc,, +setuptools/_vendor/autocommand/__pycache__/automain.cpython-312.pyc,, +setuptools/_vendor/autocommand/__pycache__/autoparse.cpython-312.pyc,, +setuptools/_vendor/autocommand/__pycache__/errors.cpython-312.pyc,, +setuptools/_vendor/autocommand/autoasync.py,sha256=AMdyrxNS4pqWJfP_xuoOcImOHWD-qT7x06wmKN1Vp-U,5680 +setuptools/_vendor/autocommand/autocommand.py,sha256=hmkEmQ72HtL55gnURVjDOnsfYlGd5lLXbvT4KG496Qw,2505 +setuptools/_vendor/autocommand/automain.py,sha256=A2b8i754Mxc_DjU9WFr6vqYDWlhz0cn8miu8d8EsxV8,2076 +setuptools/_vendor/autocommand/autoparse.py,sha256=WVWmZJPcbzUKXP40raQw_0HD8qPJ2V9VG1eFFmmnFxw,11642 +setuptools/_vendor/autocommand/errors.py,sha256=7aa3roh9Herd6nIKpQHNWEslWE8oq7GiHYVUuRqORnA,886 +setuptools/_vendor/backports.tarfile-1.2.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +setuptools/_vendor/backports.tarfile-1.2.0.dist-info/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023 +setuptools/_vendor/backports.tarfile-1.2.0.dist-info/METADATA,sha256=ghXFTq132dxaEIolxr3HK1mZqm9iyUmaRANZQSr6WlE,2020 +setuptools/_vendor/backports.tarfile-1.2.0.dist-info/RECORD,sha256=JYofHISeEXUGmlWl1s41ev3QTjTNXeJwk-Ss7HqdLOE,1360 +setuptools/_vendor/backports.tarfile-1.2.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/backports.tarfile-1.2.0.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92 +setuptools/_vendor/backports.tarfile-1.2.0.dist-info/top_level.txt,sha256=cGjaLMOoBR1FK0ApojtzWVmViTtJ7JGIK_HwXiEsvtU,10 +setuptools/_vendor/backports/__init__.py,sha256=iOEMwnlORWezdO8-2vxBIPSR37D7JGjluZ8f55vzxls,81 +setuptools/_vendor/backports/__pycache__/__init__.cpython-312.pyc,, +setuptools/_vendor/backports/tarfile/__init__.py,sha256=Pwf2qUIfB0SolJPCKcx3vz3UEu_aids4g4sAfxy94qg,108491 +setuptools/_vendor/backports/tarfile/__main__.py,sha256=Yw2oGT1afrz2eBskzdPYL8ReB_3liApmhFkN2EbDmc4,59 +setuptools/_vendor/backports/tarfile/__pycache__/__init__.cpython-312.pyc,, +setuptools/_vendor/backports/tarfile/__pycache__/__main__.cpython-312.pyc,, +setuptools/_vendor/backports/tarfile/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/backports/tarfile/compat/__pycache__/__init__.cpython-312.pyc,, +setuptools/_vendor/backports/tarfile/compat/__pycache__/py38.cpython-312.pyc,, +setuptools/_vendor/backports/tarfile/compat/py38.py,sha256=iYkyt_gvWjLzGUTJD9TuTfMMjOk-ersXZmRlvQYN2qE,568 +setuptools/_vendor/importlib_metadata-8.0.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +setuptools/_vendor/importlib_metadata-8.0.0.dist-info/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358 +setuptools/_vendor/importlib_metadata-8.0.0.dist-info/METADATA,sha256=anuQ7_7h4J1bSEzfcjIBakPi2cyVQ7y7jklLHsBeH1k,4648 +setuptools/_vendor/importlib_metadata-8.0.0.dist-info/RECORD,sha256=DY08buueu-hsrH1ghhVSQzwynanqUSSLYdAr4uXmQDA,2518 +setuptools/_vendor/importlib_metadata-8.0.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/importlib_metadata-8.0.0.dist-info/WHEEL,sha256=mguMlWGMX-VHnMpKOjjQidIo1ssRlCFu4a4mBpz1s2M,91 +setuptools/_vendor/importlib_metadata-8.0.0.dist-info/top_level.txt,sha256=CO3fD9yylANiXkrMo4qHLV_mqXL2sC5JFKgt1yWAT-A,19 +setuptools/_vendor/importlib_metadata/__init__.py,sha256=tZNB-23h8Bixi9uCrQqj9Yf0aeC--Josdy3IZRIQeB0,33798 +setuptools/_vendor/importlib_metadata/__pycache__/__init__.cpython-312.pyc,, +setuptools/_vendor/importlib_metadata/__pycache__/_adapters.cpython-312.pyc,, +setuptools/_vendor/importlib_metadata/__pycache__/_collections.cpython-312.pyc,, +setuptools/_vendor/importlib_metadata/__pycache__/_compat.cpython-312.pyc,, +setuptools/_vendor/importlib_metadata/__pycache__/_functools.cpython-312.pyc,, +setuptools/_vendor/importlib_metadata/__pycache__/_itertools.cpython-312.pyc,, +setuptools/_vendor/importlib_metadata/__pycache__/_meta.cpython-312.pyc,, +setuptools/_vendor/importlib_metadata/__pycache__/_text.cpython-312.pyc,, +setuptools/_vendor/importlib_metadata/__pycache__/diagnose.cpython-312.pyc,, +setuptools/_vendor/importlib_metadata/_adapters.py,sha256=rIhWTwBvYA1bV7i-5FfVX38qEXDTXFeS5cb5xJtP3ks,2317 +setuptools/_vendor/importlib_metadata/_collections.py,sha256=CJ0OTCHIjWA0ZIVS4voORAsn2R4R2cQBEtPsZEJpASY,743 +setuptools/_vendor/importlib_metadata/_compat.py,sha256=73QKrN9KNoaZzhbX5yPCCZa-FaALwXe8TPlDR72JgBU,1314 +setuptools/_vendor/importlib_metadata/_functools.py,sha256=PsY2-4rrKX4RVeRC1oGp1lB1pmC9eKN88_f-bD9uOoA,2895 +setuptools/_vendor/importlib_metadata/_itertools.py,sha256=cvr_2v8BRbxcIl5x5ldfqdHjhI8Yi8s8yk50G_nm6jQ,2068 +setuptools/_vendor/importlib_metadata/_meta.py,sha256=nxZ7C8GVlcBFAKWyVOn_dn7ot_twBcbm1NmvjIetBHI,1801 +setuptools/_vendor/importlib_metadata/_text.py,sha256=HCsFksZpJLeTP3NEk_ngrAeXVRRtTrtyh9eOABoRP4A,2166 +setuptools/_vendor/importlib_metadata/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/importlib_metadata/compat/__pycache__/__init__.cpython-312.pyc,, +setuptools/_vendor/importlib_metadata/compat/__pycache__/py311.cpython-312.pyc,, +setuptools/_vendor/importlib_metadata/compat/__pycache__/py39.cpython-312.pyc,, +setuptools/_vendor/importlib_metadata/compat/py311.py,sha256=uqm-K-uohyj1042TH4a9Er_I5o7667DvulcD-gC_fSA,608 +setuptools/_vendor/importlib_metadata/compat/py39.py,sha256=cPkMv6-0ilK-0Jw_Tkn0xYbOKJZc4WJKQHow0c2T44w,1102 +setuptools/_vendor/importlib_metadata/diagnose.py,sha256=nkSRMiowlmkhLYhKhvCg9glmt_11Cox-EmLzEbqYTa8,379 +setuptools/_vendor/importlib_metadata/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/inflect-7.3.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +setuptools/_vendor/inflect-7.3.1.dist-info/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023 +setuptools/_vendor/inflect-7.3.1.dist-info/METADATA,sha256=ZgMNY0WAZRs-U8wZiV2SMfjSKqBrMngXyDMs_CAwMwg,21079 +setuptools/_vendor/inflect-7.3.1.dist-info/RECORD,sha256=XXg0rBuiYSxoAQUP3lenuYsPNqz4jDwtTzdv2JEbMJE,943 +setuptools/_vendor/inflect-7.3.1.dist-info/WHEEL,sha256=y4mX-SOX4fYIkonsAGA5N0Oy-8_gI4FXw5HNI1xqvWg,91 +setuptools/_vendor/inflect-7.3.1.dist-info/top_level.txt,sha256=m52ujdp10CqT6jh1XQxZT6kEntcnv-7Tl7UiGNTzWZA,8 +setuptools/_vendor/inflect/__init__.py,sha256=Jxy1HJXZiZ85kHeLAhkmvz6EMTdFqBe-duvt34R6IOc,103796 +setuptools/_vendor/inflect/__pycache__/__init__.cpython-312.pyc,, +setuptools/_vendor/inflect/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/inflect/compat/__pycache__/__init__.cpython-312.pyc,, +setuptools/_vendor/inflect/compat/__pycache__/py38.cpython-312.pyc,, +setuptools/_vendor/inflect/compat/py38.py,sha256=oObVfVnWX9_OpnOuEJn1mFbJxVhwyR5epbiTNXDDaso,160 +setuptools/_vendor/inflect/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/jaraco.collections-5.1.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +setuptools/_vendor/jaraco.collections-5.1.0.dist-info/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023 +setuptools/_vendor/jaraco.collections-5.1.0.dist-info/METADATA,sha256=IMUaliNsA5X1Ox9MXUWOagch5R4Wwb_3M7erp29dBtg,3933 +setuptools/_vendor/jaraco.collections-5.1.0.dist-info/RECORD,sha256=HptivXDkpfom6VlMu4CGD_7KPev-6Hc9rvp3TNJZygY,873 +setuptools/_vendor/jaraco.collections-5.1.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/jaraco.collections-5.1.0.dist-info/WHEEL,sha256=Mdi9PDNwEZptOjTlUcAth7XJDFtKrHYaQMPulZeBCiQ,91 +setuptools/_vendor/jaraco.collections-5.1.0.dist-info/top_level.txt,sha256=0JnN3LfXH4LIRfXL-QFOGCJzQWZO3ELx4R1d_louoQM,7 +setuptools/_vendor/jaraco.context-5.3.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +setuptools/_vendor/jaraco.context-5.3.0.dist-info/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023 +setuptools/_vendor/jaraco.context-5.3.0.dist-info/METADATA,sha256=xDtguJej0tN9iEXCUvxEJh2a7xceIRVBEakBLSr__tY,4020 +setuptools/_vendor/jaraco.context-5.3.0.dist-info/RECORD,sha256=VRl7iKeEQyl7stgnp1uq50CzOJYlHYcoNdS0x17C9X4,641 +setuptools/_vendor/jaraco.context-5.3.0.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92 +setuptools/_vendor/jaraco.context-5.3.0.dist-info/top_level.txt,sha256=0JnN3LfXH4LIRfXL-QFOGCJzQWZO3ELx4R1d_louoQM,7 +setuptools/_vendor/jaraco.functools-4.0.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +setuptools/_vendor/jaraco.functools-4.0.1.dist-info/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023 +setuptools/_vendor/jaraco.functools-4.0.1.dist-info/METADATA,sha256=i4aUaQDX-jjdEQK5wevhegyx8JyLfin2HyvaSk3FHso,2891 +setuptools/_vendor/jaraco.functools-4.0.1.dist-info/RECORD,sha256=YyqnwE98S8wBwCevW5vHb-iVj0oYEDW5V6O9MBS6JIs,843 +setuptools/_vendor/jaraco.functools-4.0.1.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92 +setuptools/_vendor/jaraco.functools-4.0.1.dist-info/top_level.txt,sha256=0JnN3LfXH4LIRfXL-QFOGCJzQWZO3ELx4R1d_louoQM,7 +setuptools/_vendor/jaraco.text-3.12.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +setuptools/_vendor/jaraco.text-3.12.1.dist-info/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023 +setuptools/_vendor/jaraco.text-3.12.1.dist-info/METADATA,sha256=AzWdm6ViMfDOPoQMfLWn2zgBQSGJScyqeN29TcuWXVI,3658 +setuptools/_vendor/jaraco.text-3.12.1.dist-info/RECORD,sha256=gW2UV0HcokYJk4jKPu10_AZnrLqjb3C1WbJJTDl5sfY,1500 +setuptools/_vendor/jaraco.text-3.12.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/jaraco.text-3.12.1.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92 +setuptools/_vendor/jaraco.text-3.12.1.dist-info/top_level.txt,sha256=0JnN3LfXH4LIRfXL-QFOGCJzQWZO3ELx4R1d_louoQM,7 +setuptools/_vendor/jaraco/__pycache__/context.cpython-312.pyc,, +setuptools/_vendor/jaraco/collections/__init__.py,sha256=Pc1-SqjWm81ad1P0-GttpkwO_LWlnaY6gUq8gcKh2v0,26640 +setuptools/_vendor/jaraco/collections/__pycache__/__init__.cpython-312.pyc,, +setuptools/_vendor/jaraco/collections/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/jaraco/context.py,sha256=REoLIxDkO5MfEYowt_WoupNCRoxBS5v7YX2PbW8lIcs,9552 +setuptools/_vendor/jaraco/functools/__init__.py,sha256=hEAJaS2uSZRuF_JY4CxCHIYh79ZpxaPp9OiHyr9EJ1w,16642 +setuptools/_vendor/jaraco/functools/__init__.pyi,sha256=gk3dsgHzo5F_U74HzAvpNivFAPCkPJ1b2-yCd62dfnw,3878 +setuptools/_vendor/jaraco/functools/__pycache__/__init__.cpython-312.pyc,, +setuptools/_vendor/jaraco/functools/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/jaraco/text/Lorem ipsum.txt,sha256=N_7c_79zxOufBY9HZ3yzMgOkNv-TkOTTio4BydrSjgs,1335 +setuptools/_vendor/jaraco/text/__init__.py,sha256=Y2YUqXR_orUoDaY4SkPRe6ZZhb5HUHB_Ah9RCNsVyho,16250 +setuptools/_vendor/jaraco/text/__pycache__/__init__.cpython-312.pyc,, +setuptools/_vendor/jaraco/text/__pycache__/layouts.cpython-312.pyc,, +setuptools/_vendor/jaraco/text/__pycache__/show-newlines.cpython-312.pyc,, +setuptools/_vendor/jaraco/text/__pycache__/strip-prefix.cpython-312.pyc,, +setuptools/_vendor/jaraco/text/__pycache__/to-dvorak.cpython-312.pyc,, +setuptools/_vendor/jaraco/text/__pycache__/to-qwerty.cpython-312.pyc,, +setuptools/_vendor/jaraco/text/layouts.py,sha256=HTC8aSTLZ7uXipyOXapRMC158juecjK6RVwitfmZ9_w,643 +setuptools/_vendor/jaraco/text/show-newlines.py,sha256=WGQa65e8lyhb92LUOLqVn6KaCtoeVgVws6WtSRmLk6w,904 +setuptools/_vendor/jaraco/text/strip-prefix.py,sha256=NfVXV8JVNo6nqcuYASfMV7_y4Eo8zMQqlCOGvAnRIVw,412 +setuptools/_vendor/jaraco/text/to-dvorak.py,sha256=1SNcbSsvISpXXg-LnybIHHY-RUFOQr36zcHkY1pWFqw,119 +setuptools/_vendor/jaraco/text/to-qwerty.py,sha256=s4UMQUnPwFn_dB5uZC27BurHOQcYondBfzIpVL5pEzw,119 +setuptools/_vendor/more_itertools-10.3.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +setuptools/_vendor/more_itertools-10.3.0.dist-info/LICENSE,sha256=CfHIyelBrz5YTVlkHqm4fYPAyw_QB-te85Gn4mQ8GkY,1053 +setuptools/_vendor/more_itertools-10.3.0.dist-info/METADATA,sha256=BFO90O-fLNiVQMpj7oIS5ztzgJUUQZ3TA32P5HH3N-A,36293 +setuptools/_vendor/more_itertools-10.3.0.dist-info/RECORD,sha256=d8jnPgGNwP1-ntbICwWkQEVF9kH7CFIgzkKzaLWao9M,1259 +setuptools/_vendor/more_itertools-10.3.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/more_itertools-10.3.0.dist-info/WHEEL,sha256=rSgq_JpHF9fHR1lx53qwg_1-2LypZE_qmcuXbVUq948,81 +setuptools/_vendor/more_itertools/__init__.py,sha256=dtAbGjTDmn_ghiU5YXfhyDy0phAlXVdt5klZA5fUa-Q,149 +setuptools/_vendor/more_itertools/__init__.pyi,sha256=5B3eTzON1BBuOLob1vCflyEb2lSd6usXQQ-Cv-hXkeA,43 +setuptools/_vendor/more_itertools/__pycache__/__init__.cpython-312.pyc,, +setuptools/_vendor/more_itertools/__pycache__/more.cpython-312.pyc,, +setuptools/_vendor/more_itertools/__pycache__/recipes.cpython-312.pyc,, +setuptools/_vendor/more_itertools/more.py,sha256=1E5kzFncRKTDw0cYv1yRXMgDdunstLQd1QStcnL6U90,148370 +setuptools/_vendor/more_itertools/more.pyi,sha256=iXXeqt48Nxe8VGmIWpkVXuKpR2FYNuu2DU8nQLWCCu0,21484 +setuptools/_vendor/more_itertools/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/more_itertools/recipes.py,sha256=WedhhfhGVgr6zii8fIbGJVmRTw0ZKRiLKnYBDGJv4nY,28591 +setuptools/_vendor/more_itertools/recipes.pyi,sha256=T_mdGpcFdfrP3JSWbwzYP9JyNV-Go-7RPfpxfftAWlA,4617 +setuptools/_vendor/packaging-24.2.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +setuptools/_vendor/packaging-24.2.dist-info/LICENSE,sha256=ytHvW9NA1z4HS6YU0m996spceUDD2MNIUuZcSQlobEg,197 +setuptools/_vendor/packaging-24.2.dist-info/LICENSE.APACHE,sha256=DVQuDIgE45qn836wDaWnYhSdxoLXgpRRKH4RuTjpRZQ,10174 +setuptools/_vendor/packaging-24.2.dist-info/LICENSE.BSD,sha256=tw5-m3QvHMb5SLNMFqo5_-zpQZY2S8iP8NIYDwAo-sU,1344 +setuptools/_vendor/packaging-24.2.dist-info/METADATA,sha256=ohH86s6k5mIfQxY2TS0LcSfADeOFa4BiCC-bxZV-pNs,3204 +setuptools/_vendor/packaging-24.2.dist-info/RECORD,sha256=Y4DrXM0KY0ArfzhbAEa1LYFPwW3WEgEeL4iCqXe-A-M,2009 +setuptools/_vendor/packaging-24.2.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/packaging-24.2.dist-info/WHEEL,sha256=CpUCUxeHQbRN5UGRQHYRJorO5Af-Qy_fHMctcQ8DSGI,82 +setuptools/_vendor/packaging/__init__.py,sha256=dk4Ta_vmdVJxYHDcfyhvQNw8V3PgSBomKNXqg-D2JDY,494 +setuptools/_vendor/packaging/__pycache__/__init__.cpython-312.pyc,, +setuptools/_vendor/packaging/__pycache__/_elffile.cpython-312.pyc,, +setuptools/_vendor/packaging/__pycache__/_manylinux.cpython-312.pyc,, +setuptools/_vendor/packaging/__pycache__/_musllinux.cpython-312.pyc,, +setuptools/_vendor/packaging/__pycache__/_parser.cpython-312.pyc,, +setuptools/_vendor/packaging/__pycache__/_structures.cpython-312.pyc,, +setuptools/_vendor/packaging/__pycache__/_tokenizer.cpython-312.pyc,, +setuptools/_vendor/packaging/__pycache__/markers.cpython-312.pyc,, +setuptools/_vendor/packaging/__pycache__/metadata.cpython-312.pyc,, +setuptools/_vendor/packaging/__pycache__/requirements.cpython-312.pyc,, +setuptools/_vendor/packaging/__pycache__/specifiers.cpython-312.pyc,, +setuptools/_vendor/packaging/__pycache__/tags.cpython-312.pyc,, +setuptools/_vendor/packaging/__pycache__/utils.cpython-312.pyc,, +setuptools/_vendor/packaging/__pycache__/version.cpython-312.pyc,, +setuptools/_vendor/packaging/_elffile.py,sha256=cflAQAkE25tzhYmq_aCi72QfbT_tn891tPzfpbeHOwE,3306 +setuptools/_vendor/packaging/_manylinux.py,sha256=vl5OCoz4kx80H5rwXKeXWjl9WNISGmr4ZgTpTP9lU9c,9612 +setuptools/_vendor/packaging/_musllinux.py,sha256=p9ZqNYiOItGee8KcZFeHF_YcdhVwGHdK6r-8lgixvGQ,2694 +setuptools/_vendor/packaging/_parser.py,sha256=s_TvTvDNK0NrM2QB3VKThdWFM4Nc0P6JnkObkl3MjpM,10236 +setuptools/_vendor/packaging/_structures.py,sha256=q3eVNmbWJGG_S0Dit_S3Ao8qQqz_5PYTXFAKBZe5yr4,1431 +setuptools/_vendor/packaging/_tokenizer.py,sha256=J6v5H7Jzvb-g81xp_2QACKwO7LxHQA6ikryMU7zXwN8,5273 +setuptools/_vendor/packaging/licenses/__init__.py,sha256=1x5M1nEYjcgwEbLt0dXwz2ukjr18DiCzC0sraQqJ-Ww,5715 +setuptools/_vendor/packaging/licenses/__pycache__/__init__.cpython-312.pyc,, +setuptools/_vendor/packaging/licenses/__pycache__/_spdx.cpython-312.pyc,, +setuptools/_vendor/packaging/licenses/_spdx.py,sha256=oAm1ztPFwlsmCKe7lAAsv_OIOfS1cWDu9bNBkeu-2ns,48398 +setuptools/_vendor/packaging/markers.py,sha256=c89TNzB7ZdGYhkovm6PYmqGyHxXlYVaLW591PHUNKD8,10561 +setuptools/_vendor/packaging/metadata.py,sha256=YJibM7GYe4re8-0a3OlXmGS-XDgTEoO4tlBt2q25Bng,34762 +setuptools/_vendor/packaging/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/packaging/requirements.py,sha256=gYyRSAdbrIyKDY66ugIDUQjRMvxkH2ALioTmX3tnL6o,2947 +setuptools/_vendor/packaging/specifiers.py,sha256=GG1wPNMcL0fMJO68vF53wKMdwnfehDcaI-r9NpTfilA,40074 +setuptools/_vendor/packaging/tags.py,sha256=CFqrJzAzc2XNGexerH__T-Y5Iwq7WbsYXsiLERLWxY0,21014 +setuptools/_vendor/packaging/utils.py,sha256=0F3Hh9OFuRgrhTgGZUl5K22Fv1YP2tZl1z_2gO6kJiA,5050 +setuptools/_vendor/packaging/version.py,sha256=olfyuk_DPbflNkJ4wBWetXQ17c74x3DB501degUv7DY,16676 +setuptools/_vendor/platformdirs-4.2.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +setuptools/_vendor/platformdirs-4.2.2.dist-info/METADATA,sha256=zmsie01G1MtXR0wgIv5XpVeTO7idr0WWvfmxKsKWuGk,11429 +setuptools/_vendor/platformdirs-4.2.2.dist-info/RECORD,sha256=TCEddtQu1A78Os_Mhm2JEqcYr7yit-UYSUQjZtbpn-g,1642 +setuptools/_vendor/platformdirs-4.2.2.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/platformdirs-4.2.2.dist-info/WHEEL,sha256=zEMcRr9Kr03x1ozGwg5v9NQBKn3kndp6LSoSlVg-jhU,87 +setuptools/_vendor/platformdirs-4.2.2.dist-info/licenses/LICENSE,sha256=KeD9YukphQ6G6yjD_czwzv30-pSHkBHP-z0NS-1tTbY,1089 +setuptools/_vendor/platformdirs/__init__.py,sha256=EMGE8qeHRR9CzDFr8kL3tA8hdZZniYjXBVZd0UGTWK0,22225 +setuptools/_vendor/platformdirs/__main__.py,sha256=HnsUQHpiBaiTxwcmwVw-nFaPdVNZtQIdi1eWDtI-MzI,1493 +setuptools/_vendor/platformdirs/__pycache__/__init__.cpython-312.pyc,, +setuptools/_vendor/platformdirs/__pycache__/__main__.cpython-312.pyc,, +setuptools/_vendor/platformdirs/__pycache__/android.cpython-312.pyc,, +setuptools/_vendor/platformdirs/__pycache__/api.cpython-312.pyc,, +setuptools/_vendor/platformdirs/__pycache__/macos.cpython-312.pyc,, +setuptools/_vendor/platformdirs/__pycache__/unix.cpython-312.pyc,, +setuptools/_vendor/platformdirs/__pycache__/version.cpython-312.pyc,, +setuptools/_vendor/platformdirs/__pycache__/windows.cpython-312.pyc,, +setuptools/_vendor/platformdirs/android.py,sha256=xZXY9Jd46WOsxT2U6-5HsNtDZ-IQqxcEUrBLl3hYk4o,9016 +setuptools/_vendor/platformdirs/api.py,sha256=QBYdUac2eC521ek_y53uD1Dcq-lJX8IgSRVd4InC6uc,8996 +setuptools/_vendor/platformdirs/macos.py,sha256=wftsbsvq6nZ0WORXSiCrZNkRHz_WKuktl0a6mC7MFkI,5580 +setuptools/_vendor/platformdirs/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/platformdirs/unix.py,sha256=Cci9Wqt35dAMsg6HT9nRGHSBW5obb0pR3AE1JJnsCXg,10643 +setuptools/_vendor/platformdirs/version.py,sha256=r7F76tZRjgQKzrpx_I0_ZMQOMU-PS7eGnHD7zEK3KB0,411 +setuptools/_vendor/platformdirs/windows.py,sha256=IFpiohUBwxPtCzlyKwNtxyW4Jk8haa6W8o59mfrDXVo,10125 +setuptools/_vendor/tomli-2.0.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +setuptools/_vendor/tomli-2.0.1.dist-info/LICENSE,sha256=uAgWsNUwuKzLTCIReDeQmEpuO2GSLCte6S8zcqsnQv4,1072 +setuptools/_vendor/tomli-2.0.1.dist-info/METADATA,sha256=zPDceKmPwJGLWtZykrHixL7WVXWmJGzZ1jyRT5lCoPI,8875 +setuptools/_vendor/tomli-2.0.1.dist-info/RECORD,sha256=DLn5pFGh42WsVLTIhmLh2gy1SnLRalJY-wq_-dPhwCI,999 +setuptools/_vendor/tomli-2.0.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/tomli-2.0.1.dist-info/WHEEL,sha256=jPMR_Dzkc4X4icQtmz81lnNY_kAsfog7ry7qoRvYLXw,81 +setuptools/_vendor/tomli/__init__.py,sha256=JhUwV66DB1g4Hvt1UQCVMdfCu-IgAV8FXmvDU9onxd4,396 +setuptools/_vendor/tomli/__pycache__/__init__.cpython-312.pyc,, +setuptools/_vendor/tomli/__pycache__/_parser.cpython-312.pyc,, +setuptools/_vendor/tomli/__pycache__/_re.cpython-312.pyc,, +setuptools/_vendor/tomli/__pycache__/_types.cpython-312.pyc,, +setuptools/_vendor/tomli/_parser.py,sha256=g9-ENaALS-B8dokYpCuzUFalWlog7T-SIYMjLZSWrtM,22633 +setuptools/_vendor/tomli/_re.py,sha256=dbjg5ChZT23Ka9z9DHOXfdtSpPwUfdgMXnj8NOoly-w,2943 +setuptools/_vendor/tomli/_types.py,sha256=-GTG2VUqkpxwMqzmVO4F7ybKddIbAnuAHXfmWQcTi3Q,254 +setuptools/_vendor/tomli/py.typed,sha256=8PjyZ1aVoQpRVvt71muvuq5qE-jTFZkK-GLHkhdebmc,26 +setuptools/_vendor/typeguard-4.3.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +setuptools/_vendor/typeguard-4.3.0.dist-info/LICENSE,sha256=YWP3mH37ONa8MgzitwsvArhivEESZRbVUu8c1DJH51g,1130 +setuptools/_vendor/typeguard-4.3.0.dist-info/METADATA,sha256=z2dcHAp0TwhYCFU5Deh8x31nazElgujUz9tbuP0pjSE,3717 +setuptools/_vendor/typeguard-4.3.0.dist-info/RECORD,sha256=SKUZWVgkeDUidUKM7s1473fXmsna55bjmi6vJUAoJVI,2402 +setuptools/_vendor/typeguard-4.3.0.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92 +setuptools/_vendor/typeguard-4.3.0.dist-info/entry_points.txt,sha256=qp7NQ1aLtiSgMQqo6gWlfGpy0IIXzoMJmeQTLpzqFZQ,48 +setuptools/_vendor/typeguard-4.3.0.dist-info/top_level.txt,sha256=4z28AhuDodwRS_c1J_l8H51t5QuwfTseskYzlxp6grs,10 +setuptools/_vendor/typeguard/__init__.py,sha256=Onh4w38elPCjtlcU3JY9k3h70NjsxXIkAflmQn-Z0FY,2071 +setuptools/_vendor/typeguard/__pycache__/__init__.cpython-312.pyc,, +setuptools/_vendor/typeguard/__pycache__/_checkers.cpython-312.pyc,, +setuptools/_vendor/typeguard/__pycache__/_config.cpython-312.pyc,, +setuptools/_vendor/typeguard/__pycache__/_decorators.cpython-312.pyc,, +setuptools/_vendor/typeguard/__pycache__/_exceptions.cpython-312.pyc,, +setuptools/_vendor/typeguard/__pycache__/_functions.cpython-312.pyc,, +setuptools/_vendor/typeguard/__pycache__/_importhook.cpython-312.pyc,, +setuptools/_vendor/typeguard/__pycache__/_memo.cpython-312.pyc,, +setuptools/_vendor/typeguard/__pycache__/_pytest_plugin.cpython-312.pyc,, +setuptools/_vendor/typeguard/__pycache__/_suppression.cpython-312.pyc,, +setuptools/_vendor/typeguard/__pycache__/_transformer.cpython-312.pyc,, +setuptools/_vendor/typeguard/__pycache__/_union_transformer.cpython-312.pyc,, +setuptools/_vendor/typeguard/__pycache__/_utils.cpython-312.pyc,, +setuptools/_vendor/typeguard/_checkers.py,sha256=JRrgKicdOEfIBoNEtegYCEIlhpad-a1u1Em7GCj0WCI,31360 +setuptools/_vendor/typeguard/_config.py,sha256=nIz8QwDa-oFO3L9O8_6srzlmd99pSby2wOM4Wb7F_B0,2846 +setuptools/_vendor/typeguard/_decorators.py,sha256=v6dsIeWvPhExGLP_wXF-RmDUyjZf_Ak28g7gBJ_v0-0,9033 +setuptools/_vendor/typeguard/_exceptions.py,sha256=ZIPeiV-FBd5Emw2EaWd2Fvlsrwi4ocwT2fVGBIAtHcQ,1121 +setuptools/_vendor/typeguard/_functions.py,sha256=ibgSAKa5ptIm1eR9ARG0BSozAFJPFNASZqhPVyQeqig,10393 +setuptools/_vendor/typeguard/_importhook.py,sha256=ugjCDvFcdWMU7UugqlJG91IpVNpEIxtRr-99s0h1k7M,6389 +setuptools/_vendor/typeguard/_memo.py,sha256=1juQV_vxnD2JYKbSrebiQuj4oKHz6n67v9pYA-CCISg,1303 +setuptools/_vendor/typeguard/_pytest_plugin.py,sha256=-fcSqkv54rIfIF8pDavY5YQPkj4OX8GMt_lL7CQSD4I,4416 +setuptools/_vendor/typeguard/_suppression.py,sha256=VQfzxcwIbu3if0f7VBkKM7hkYOA7tNFw9a7jMBsmMg4,2266 +setuptools/_vendor/typeguard/_transformer.py,sha256=9Ha7_QhdwoUni_6hvdY-hZbuEergowHrNL2vzHIakFY,44937 +setuptools/_vendor/typeguard/_union_transformer.py,sha256=v_42r7-6HuRX2SoFwnyJ-E5PlxXpVeUJPJR1-HU9qSo,1354 +setuptools/_vendor/typeguard/_utils.py,sha256=5HhO1rPn5f1M6ymkVAEv7Xmlz1cX-j0OnTMlyHqqrR8,5270 +setuptools/_vendor/typeguard/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/typing_extensions-4.12.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +setuptools/_vendor/typing_extensions-4.12.2.dist-info/LICENSE,sha256=Oy-B_iHRgcSZxZolbI4ZaEVdZonSaaqFNzv7avQdo78,13936 +setuptools/_vendor/typing_extensions-4.12.2.dist-info/METADATA,sha256=BeUQIa8cnYbrjWx-N8TOznM9UGW5Gm2DicVpDtRA8W0,3018 +setuptools/_vendor/typing_extensions-4.12.2.dist-info/RECORD,sha256=dxAALYGXHmMqpqL8M9xddKr118quIgQKZdPjFQOwXuk,571 +setuptools/_vendor/typing_extensions-4.12.2.dist-info/WHEEL,sha256=EZbGkh7Ie4PoZfRQ8I0ZuP9VklN_TvcZ6DSE5Uar4z4,81 +setuptools/_vendor/typing_extensions.py,sha256=gwekpyG9DVG3lxWKX4ni8u7nk3We5slG98mA9F3DJQw,134451 +setuptools/_vendor/wheel-0.45.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +setuptools/_vendor/wheel-0.45.1.dist-info/LICENSE.txt,sha256=MMI2GGeRCPPo6h0qZYx8pBe9_IkcmO8aifpP8MmChlQ,1107 +setuptools/_vendor/wheel-0.45.1.dist-info/METADATA,sha256=mKz84H7m7jsxJyzeIcTVORiTb0NPMV39KvOIYhGgmjA,2313 +setuptools/_vendor/wheel-0.45.1.dist-info/RECORD,sha256=1jnxrHyZPDcVvULyfGFhiba4Z5L9_RsXr9dxcNbhaYQ,4900 +setuptools/_vendor/wheel-0.45.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/wheel-0.45.1.dist-info/WHEEL,sha256=CpUCUxeHQbRN5UGRQHYRJorO5Af-Qy_fHMctcQ8DSGI,82 +setuptools/_vendor/wheel-0.45.1.dist-info/entry_points.txt,sha256=rTY1BbkPHhkGMm4Q3F0pIzJBzW2kMxoG1oriffvGdA0,104 +setuptools/_vendor/wheel/__init__.py,sha256=mrxMnvdXACur_LWegbUfh5g5ysWZrd63UJn890wvGNk,59 +setuptools/_vendor/wheel/__main__.py,sha256=NkMUnuTCGcOkgY0IBLgBCVC_BGGcWORx2K8jYGS12UE,455 +setuptools/_vendor/wheel/__pycache__/__init__.cpython-312.pyc,, +setuptools/_vendor/wheel/__pycache__/__main__.cpython-312.pyc,, +setuptools/_vendor/wheel/__pycache__/_bdist_wheel.cpython-312.pyc,, +setuptools/_vendor/wheel/__pycache__/_setuptools_logging.cpython-312.pyc,, +setuptools/_vendor/wheel/__pycache__/bdist_wheel.cpython-312.pyc,, +setuptools/_vendor/wheel/__pycache__/macosx_libfile.cpython-312.pyc,, +setuptools/_vendor/wheel/__pycache__/metadata.cpython-312.pyc,, +setuptools/_vendor/wheel/__pycache__/util.cpython-312.pyc,, +setuptools/_vendor/wheel/__pycache__/wheelfile.cpython-312.pyc,, +setuptools/_vendor/wheel/_bdist_wheel.py,sha256=UghCQjSH_pVfcZh6oRjzSw_TQhcf3anSx1OkiLSL82M,21694 +setuptools/_vendor/wheel/_setuptools_logging.py,sha256=-5KC-lne0ilOUWIDfOkqapUWGMFZhuKYDIavIZiB5kM,781 +setuptools/_vendor/wheel/bdist_wheel.py,sha256=tpf9WufiSO1RuEMg5oPhIfSG8DMziCZ_4muCKF69Cqo,1107 +setuptools/_vendor/wheel/cli/__init__.py,sha256=Npq6_jKi03dhIcRnmbuFhwviVJxwO0tYEnEhWMv9cJo,4402 +setuptools/_vendor/wheel/cli/__pycache__/__init__.cpython-312.pyc,, +setuptools/_vendor/wheel/cli/__pycache__/convert.cpython-312.pyc,, +setuptools/_vendor/wheel/cli/__pycache__/pack.cpython-312.pyc,, +setuptools/_vendor/wheel/cli/__pycache__/tags.cpython-312.pyc,, +setuptools/_vendor/wheel/cli/__pycache__/unpack.cpython-312.pyc,, +setuptools/_vendor/wheel/cli/convert.py,sha256=Bi0ntEXb9nTllCxWeTRQ4j-nPs3szWSEKipG_GgnMkQ,12634 +setuptools/_vendor/wheel/cli/pack.py,sha256=CAFcHdBVulvsHYJlndKVO7KMI9JqBTZz5ii0PKxxCOs,3103 +setuptools/_vendor/wheel/cli/tags.py,sha256=lHw-LaWrkS5Jy_qWcw-6pSjeNM6yAjDnqKI3E5JTTCU,4760 +setuptools/_vendor/wheel/cli/unpack.py,sha256=Y_J7ynxPSoFFTT7H0fMgbBlVErwyDGcObgme5MBuz58,1021 +setuptools/_vendor/wheel/macosx_libfile.py,sha256=k1x7CE3LPtOVGqj6NXQ1nTGYVPaeRrhVzUG_KPq3zDs,16572 +setuptools/_vendor/wheel/metadata.py,sha256=JC4p7jlQZu2bUTAQ2fevkqLjg_X6gnNyRhLn6OUO1tc,6171 +setuptools/_vendor/wheel/util.py,sha256=aL7aibHwYUgfc8WlolL5tXdkV4DatbJxZHb1kwHFJAU,423 +setuptools/_vendor/wheel/vendored/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/wheel/vendored/__pycache__/__init__.cpython-312.pyc,, +setuptools/_vendor/wheel/vendored/packaging/LICENSE,sha256=ytHvW9NA1z4HS6YU0m996spceUDD2MNIUuZcSQlobEg,197 +setuptools/_vendor/wheel/vendored/packaging/LICENSE.APACHE,sha256=DVQuDIgE45qn836wDaWnYhSdxoLXgpRRKH4RuTjpRZQ,10174 +setuptools/_vendor/wheel/vendored/packaging/LICENSE.BSD,sha256=tw5-m3QvHMb5SLNMFqo5_-zpQZY2S8iP8NIYDwAo-sU,1344 +setuptools/_vendor/wheel/vendored/packaging/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/wheel/vendored/packaging/__pycache__/__init__.cpython-312.pyc,, +setuptools/_vendor/wheel/vendored/packaging/__pycache__/_elffile.cpython-312.pyc,, +setuptools/_vendor/wheel/vendored/packaging/__pycache__/_manylinux.cpython-312.pyc,, +setuptools/_vendor/wheel/vendored/packaging/__pycache__/_musllinux.cpython-312.pyc,, +setuptools/_vendor/wheel/vendored/packaging/__pycache__/_parser.cpython-312.pyc,, +setuptools/_vendor/wheel/vendored/packaging/__pycache__/_structures.cpython-312.pyc,, +setuptools/_vendor/wheel/vendored/packaging/__pycache__/_tokenizer.cpython-312.pyc,, +setuptools/_vendor/wheel/vendored/packaging/__pycache__/markers.cpython-312.pyc,, +setuptools/_vendor/wheel/vendored/packaging/__pycache__/requirements.cpython-312.pyc,, +setuptools/_vendor/wheel/vendored/packaging/__pycache__/specifiers.cpython-312.pyc,, +setuptools/_vendor/wheel/vendored/packaging/__pycache__/tags.cpython-312.pyc,, +setuptools/_vendor/wheel/vendored/packaging/__pycache__/utils.cpython-312.pyc,, +setuptools/_vendor/wheel/vendored/packaging/__pycache__/version.cpython-312.pyc,, +setuptools/_vendor/wheel/vendored/packaging/_elffile.py,sha256=hbmK8OD6Z7fY6hwinHEUcD1by7czkGiNYu7ShnFEk2k,3266 +setuptools/_vendor/wheel/vendored/packaging/_manylinux.py,sha256=P7sdR5_7XBY09LVYYPhHmydMJIIwPXWsh4olk74Uuj4,9588 +setuptools/_vendor/wheel/vendored/packaging/_musllinux.py,sha256=z1s8To2hQ0vpn_d-O2i5qxGwEK8WmGlLt3d_26V7NeY,2674 +setuptools/_vendor/wheel/vendored/packaging/_parser.py,sha256=4tT4emSl2qTaU7VTQE1Xa9o1jMPCsBezsYBxyNMUN-s,10347 +setuptools/_vendor/wheel/vendored/packaging/_structures.py,sha256=q3eVNmbWJGG_S0Dit_S3Ao8qQqz_5PYTXFAKBZe5yr4,1431 +setuptools/_vendor/wheel/vendored/packaging/_tokenizer.py,sha256=alCtbwXhOFAmFGZ6BQ-wCTSFoRAJ2z-ysIf7__MTJ_k,5292 +setuptools/_vendor/wheel/vendored/packaging/markers.py,sha256=_TSPI1BhJYO7Bp9AzTmHQxIqHEVXaTjmDh9G-w8qzPA,8232 +setuptools/_vendor/wheel/vendored/packaging/requirements.py,sha256=dgoBeVprPu2YE6Q8nGfwOPTjATHbRa_ZGLyXhFEln6Q,2933 +setuptools/_vendor/wheel/vendored/packaging/specifiers.py,sha256=IWSt0SrLSP72heWhAC8UL0eGvas7XIQHjqiViVfmPKE,39778 +setuptools/_vendor/wheel/vendored/packaging/tags.py,sha256=fedHXiOHkBxNZTXotXv8uXPmMFU9ae-TKBujgYHigcA,18950 +setuptools/_vendor/wheel/vendored/packaging/utils.py,sha256=XgdmP3yx9-wQEFjO7OvMj9RjEf5JlR5HFFR69v7SQ9E,5268 +setuptools/_vendor/wheel/vendored/packaging/version.py,sha256=PFJaYZDxBgyxkfYhH3SQw4qfE9ICCWrTmitvq14y3bs,16234 +setuptools/_vendor/wheel/vendored/vendor.txt,sha256=Z2ENjB1i5prfez8CdM1Sdr3c6Zxv2rRRolMpLmBncAE,16 +setuptools/_vendor/wheel/wheelfile.py,sha256=USCttNlJwafxt51YYFFKG7jnxz8dfhbyqAZL6jMTA9s,8411 +setuptools/_vendor/zipp-3.19.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +setuptools/_vendor/zipp-3.19.2.dist-info/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023 +setuptools/_vendor/zipp-3.19.2.dist-info/METADATA,sha256=UIrk_kMIHGSwsKKChYizqMw0MMZpPRZ2ZiVpQAsN_bE,3575 +setuptools/_vendor/zipp-3.19.2.dist-info/RECORD,sha256=8xby4D_ZrefrvAsVRwaEjiu4_VaLkJNRCfDY484rm_4,1039 +setuptools/_vendor/zipp-3.19.2.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/zipp-3.19.2.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92 +setuptools/_vendor/zipp-3.19.2.dist-info/top_level.txt,sha256=iAbdoSHfaGqBfVb2XuR9JqSQHCoOsOtG6y9C_LSpqFw,5 +setuptools/_vendor/zipp/__init__.py,sha256=QuI1g00G4fRAcGt-HqbV0oWIkmSgedCGGYsHHYzNa8A,13412 +setuptools/_vendor/zipp/__pycache__/__init__.cpython-312.pyc,, +setuptools/_vendor/zipp/__pycache__/glob.cpython-312.pyc,, +setuptools/_vendor/zipp/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/zipp/compat/__pycache__/__init__.cpython-312.pyc,, +setuptools/_vendor/zipp/compat/__pycache__/py310.cpython-312.pyc,, +setuptools/_vendor/zipp/compat/py310.py,sha256=eZpkW0zRtunkhEh8jjX3gCGe22emoKCBJw72Zt4RkhA,219 +setuptools/_vendor/zipp/glob.py,sha256=etWpnfEoRyfUvrUsi6sTiGmErvPwe6HzY6pT8jg_lUI,3082 +setuptools/archive_util.py,sha256=Tl_64hSTtc4y8x7xa98rFVUbG24oArpjzLAYGYP2_sI,7356 +setuptools/build_meta.py,sha256=rry-LowqvWFsxG6Qm5QWetHJGeETzRdiQ5-bs4bOkjo,20446 +setuptools/cli-32.exe,sha256=MqzBvFQxFsviz_EMuGd3LfLyVP8mNMhwrvC0bEtpb9s,11776 +setuptools/cli-64.exe,sha256=u7PeVwdinmpgoMI4zUd7KPB_AGaYL9qVP6b87DkHOko,14336 +setuptools/cli-arm64.exe,sha256=uafQjaiA36yLz1SOuksG-1m28JsX0zFIoPZhgyiSbGE,13824 +setuptools/cli.exe,sha256=MqzBvFQxFsviz_EMuGd3LfLyVP8mNMhwrvC0bEtpb9s,11776 +setuptools/command/__init__.py,sha256=wdSrlNR0P6nCz9_oFtCAiAkeFJMsZa1jPcpXT53f0SM,803 +setuptools/command/__pycache__/__init__.cpython-312.pyc,, +setuptools/command/__pycache__/_requirestxt.cpython-312.pyc,, +setuptools/command/__pycache__/alias.cpython-312.pyc,, +setuptools/command/__pycache__/bdist_egg.cpython-312.pyc,, +setuptools/command/__pycache__/bdist_rpm.cpython-312.pyc,, +setuptools/command/__pycache__/bdist_wheel.cpython-312.pyc,, +setuptools/command/__pycache__/build.cpython-312.pyc,, +setuptools/command/__pycache__/build_clib.cpython-312.pyc,, +setuptools/command/__pycache__/build_ext.cpython-312.pyc,, +setuptools/command/__pycache__/build_py.cpython-312.pyc,, +setuptools/command/__pycache__/develop.cpython-312.pyc,, +setuptools/command/__pycache__/dist_info.cpython-312.pyc,, +setuptools/command/__pycache__/easy_install.cpython-312.pyc,, +setuptools/command/__pycache__/editable_wheel.cpython-312.pyc,, +setuptools/command/__pycache__/egg_info.cpython-312.pyc,, +setuptools/command/__pycache__/install.cpython-312.pyc,, +setuptools/command/__pycache__/install_egg_info.cpython-312.pyc,, +setuptools/command/__pycache__/install_lib.cpython-312.pyc,, +setuptools/command/__pycache__/install_scripts.cpython-312.pyc,, +setuptools/command/__pycache__/rotate.cpython-312.pyc,, +setuptools/command/__pycache__/saveopts.cpython-312.pyc,, +setuptools/command/__pycache__/sdist.cpython-312.pyc,, +setuptools/command/__pycache__/setopt.cpython-312.pyc,, +setuptools/command/__pycache__/test.cpython-312.pyc,, +setuptools/command/_requirestxt.py,sha256=ItYMTJGh_i5TlQstX_nFopqEhkC4PJFadBL2Zd3V670,4228 +setuptools/command/alias.py,sha256=rDdrMt32DS6qf3K7tjZZyHD_dMKrm77AXcAtx-nBQ0I,2380 +setuptools/command/bdist_egg.py,sha256=3eDucQ4fdeYMsLO9PhBfY1JkcMLhZXgnAI_9FdFNsEE,16972 +setuptools/command/bdist_rpm.py,sha256=LyqI49w48SKk0FmuHsE9MLzX1SuXjL7YMNbZMFZqFII,1435 +setuptools/command/bdist_wheel.py,sha256=_LfGHB7CV_uyncqlOTSETEi2gjVCoPKuAXcyRFoq7Cs,22246 +setuptools/command/build.py,sha256=eI7STMERGGZEpzk1tvJN8p9IOjAAXMcGLzljv2mwI3M,6052 +setuptools/command/build_clib.py,sha256=AbgpPIF_3qL8fZr3JIebI-WHTMTBiMfrFkVQz8K40G4,4528 +setuptools/command/build_ext.py,sha256=bUH4M0NizaJJrv10wK-ZD3uY0TxCSZlYQDhiwwzHslM,18377 +setuptools/command/build_py.py,sha256=DCbjvB18kkL-xUK5rvlzm0C6twTeOxNhyvJDxxa7fII,15539 +setuptools/command/develop.py,sha256=zX22119sI1G1gfJ1gNCE4hkg2zbLKx0uUwvNmC5bIu8,6886 +setuptools/command/dist_info.py,sha256=HU752iLLmmYMHbsDBgz2ubRjkgJobugOp8H71LzzDys,3450 +setuptools/command/easy_install.py,sha256=0Z4kFlE78Ae2AfHXYTxZFUa2t3qlNqXCtQu4J1Nx8iA,87870 +setuptools/command/editable_wheel.py,sha256=3bBipRZA3E4poQ8LEWhMYEjHjCzqU_pIdO86C3t7oNY,35624 +setuptools/command/egg_info.py,sha256=WWUozR3DZCrWsTQhHXOygMiEUcrjLWphET0-Zsocsm4,25982 +setuptools/command/install.py,sha256=MmTGb8m1R8fJ0cc5FTWCF6uq-s1ZJmvpYm-N_CtqEaI,7046 +setuptools/command/install_egg_info.py,sha256=3I9IPCH7D59Sh-6aVYz-h6wwyxq-wkxrKwKg3nDdJqs,2075 +setuptools/command/install_lib.py,sha256=9n1_U83eHcERL_a_rv_LhHCkhXlLdqyZ4SdBow-9qcE,4319 +setuptools/command/install_scripts.py,sha256=tVOCj3e8OTIrkoL_bGbT5pOksdxZfQblH_bdI4DtVV4,2637 +setuptools/command/launcher manifest.xml,sha256=xlLbjWrB01tKC0-hlVkOKkiSPbzMml2eOPtJ_ucCnbE,628 +setuptools/command/rotate.py,sha256=XNd_BEEOWAJHW1FcLTMUWWl4QB6zAuk7b8VWQg3FHos,2187 +setuptools/command/saveopts.py,sha256=Np0PVb7SD7oTbu9Z9sosS7D-CkkIkU7x4glu5Es1tjA,692 +setuptools/command/sdist.py,sha256=JaQm2-ebXI2kvyrBjJKP8yNLPa5eMbMeis88CXBMYlk,7374 +setuptools/command/setopt.py,sha256=xZF2RCc4ABvE9eHHAzF50-fkQg3au8fcRUVVGd58k3U,5100 +setuptools/command/test.py,sha256=k7xcq7D7bEehgxarbw-dW3AtmGZORqz8HjKR6FGJ3jk,1343 +setuptools/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/compat/__pycache__/__init__.cpython-312.pyc,, +setuptools/compat/__pycache__/py310.cpython-312.pyc,, +setuptools/compat/__pycache__/py311.cpython-312.pyc,, +setuptools/compat/__pycache__/py312.cpython-312.pyc,, +setuptools/compat/__pycache__/py39.cpython-312.pyc,, +setuptools/compat/py310.py,sha256=8sqwWczIcrkzeAbhaim4pKVd4tXZdcqmebgdvzji0rc,141 +setuptools/compat/py311.py,sha256=e6tJAFwZEP82hmMBl10HYeSypelo_Ti2wTjKZVKLwOE,790 +setuptools/compat/py312.py,sha256=vYKVtdrdOTsO_R90dJkEXsFwfMJFuIFJflhIgHrjJ-Y,366 +setuptools/compat/py39.py,sha256=BJMtnkfcqyTfccqjYQxfoRtU2nTnWaEESBVkshTiXqY,493 +setuptools/config/NOTICE,sha256=Ld3wiBgpejuJ1D2V_2WdjahXQRCMkTbfo6TYVsBiO9g,493 +setuptools/config/__init__.py,sha256=aiPnL9BJn1O6MfmuNXyn8W2Lp8u9qizRVqwPiOdPIjY,1499 +setuptools/config/__pycache__/__init__.cpython-312.pyc,, +setuptools/config/__pycache__/_apply_pyprojecttoml.cpython-312.pyc,, +setuptools/config/__pycache__/expand.cpython-312.pyc,, +setuptools/config/__pycache__/pyprojecttoml.cpython-312.pyc,, +setuptools/config/__pycache__/setupcfg.cpython-312.pyc,, +setuptools/config/_apply_pyprojecttoml.py,sha256=SUyTw7A2btZ1lBuWKN5o42-Diyv95eGTiYJ3rZOnGSc,19120 +setuptools/config/_validate_pyproject/NOTICE,sha256=XTANv6ZDE4sBO3WsnK7uWR-VG4sO4kKIw0zNkmxHgMg,18737 +setuptools/config/_validate_pyproject/__init__.py,sha256=dnp6T7ePP1R5z4OuC7Fd2dkFlIrtIfizUfvpGJP6nz0,1042 +setuptools/config/_validate_pyproject/__pycache__/__init__.cpython-312.pyc,, +setuptools/config/_validate_pyproject/__pycache__/error_reporting.cpython-312.pyc,, +setuptools/config/_validate_pyproject/__pycache__/extra_validations.cpython-312.pyc,, +setuptools/config/_validate_pyproject/__pycache__/fastjsonschema_exceptions.cpython-312.pyc,, +setuptools/config/_validate_pyproject/__pycache__/fastjsonschema_validations.cpython-312.pyc,, +setuptools/config/_validate_pyproject/__pycache__/formats.cpython-312.pyc,, +setuptools/config/_validate_pyproject/error_reporting.py,sha256=meldD7nBQdolQhvG-43r1Ue-gU1n7ORAJR86vh3Rrvk,11813 +setuptools/config/_validate_pyproject/extra_validations.py,sha256=-GUG5S--ijY8WfXbdXPoHl6ywGsyEF9dtDpenSoJPHg,2858 +setuptools/config/_validate_pyproject/fastjsonschema_exceptions.py,sha256=w749JgqKi8clBFcObdcbZVqsmF4oJ_QByhZ1SGbUFNw,1612 +setuptools/config/_validate_pyproject/fastjsonschema_validations.py,sha256=FihD5ZcM6p77BPZ04CGqh3BEwVNoPMKJZJAyuJpkAU0,354682 +setuptools/config/_validate_pyproject/formats.py,sha256=TETokJBK9hjl-cVg1olsojkJwLxfP7_chgJQNmzAB98,13564 +setuptools/config/distutils.schema.json,sha256=Tcp32kRnhwORGw_9p6GEi08lj2h15tQRzOYBbzGmcBU,972 +setuptools/config/expand.py,sha256=JNAktRCsyyRB-rQodbPnCucmLWqcYvzCDC8Ebn2Z7xM,16041 +setuptools/config/pyprojecttoml.py,sha256=YMu5PdbJJI5azp6kR_boM1mflf5nqOA-InF4s6LnLgw,18320 +setuptools/config/setupcfg.py,sha256=VZDkwE7DYv45SbadJD8CwKrDtiXvjgllL8PYSvoRCyg,26575 +setuptools/config/setuptools.schema.json,sha256=dZBRuSEnZkatoVlt1kVwG8ocTeRdO7BD0xvOWKH54PY,16071 +setuptools/depends.py,sha256=jKYfjmt_2ZQYVghb8L9bU7LJ6erHJ5ze-K_fKV1BMXk,5965 +setuptools/discovery.py,sha256=-42c3XhwzkfodDKKP50C2YBzr11fncAgmUzBdBRb0-Q,21258 +setuptools/dist.py,sha256=RZz7aj9RxqSYriqgFoZOu-7KIV82cmlaMFx9owZrApQ,44897 +setuptools/errors.py,sha256=gY2x2PIaIgy01yRANRC-zcCwxDCqCScgJoCOZFe0yio,3024 +setuptools/extension.py,sha256=KCnv9p3tgm0ZVqtgE451fyILsm4hCyvOiUtOu787D-4,6683 +setuptools/glob.py,sha256=AC_B33DY8g-CHELxDsJrtwFrpiucSAZsakPFdSOQzhc,6062 +setuptools/gui-32.exe,sha256=hdrh6V13hF8stZvKw9Sv50u-TJGpvMW_SnHNQxBNvnw,11776 +setuptools/gui-64.exe,sha256=NHG2FA6txkEid9u-_j_vjDRaDxpZd2CGuAo2GMOoPjs,14336 +setuptools/gui-arm64.exe,sha256=5pT0dDQFyLWSb_RX22_n8aEt7HwWqcOGR4TT9OB64Jc,13824 +setuptools/gui.exe,sha256=hdrh6V13hF8stZvKw9Sv50u-TJGpvMW_SnHNQxBNvnw,11776 +setuptools/installer.py,sha256=_4Wegx4r3L05sMo3-IlqFp-OuxnWyBqjyMZ7LWQXmh8,5110 +setuptools/launch.py,sha256=IBb5lEv69CyuZ9ewIrmKlXh154kdLmP29LKfTMkximE,820 +setuptools/logging.py,sha256=W16iHJ1HcCXYQ0RxyrEfJ83FT4175tCtoYg-E6uSpVI,1261 +setuptools/modified.py,sha256=ZwbfBfCFP88ltvbv_dJDz-t1LsQjnM-JUpgZnnQZjjM,568 +setuptools/monkey.py,sha256=FwMWl2n1v2bHbeqBy-o9g8yUNaAkYFbszCbXe9d5Za8,3717 +setuptools/msvc.py,sha256=vmM0qL4rIzrtD9pia9ZEwtqZ4LbbrgL0dU0EANVYRm8,41631 +setuptools/namespaces.py,sha256=2GGqYY1BNDEhMtBc1rHTv7klgmNVRdksJeW-L1f--ys,3171 +setuptools/package_index.py,sha256=yHXj4Z_QaUeh8W6rwq08I5LxnyHrSkNf01uXHwdE8K0,39095 +setuptools/sandbox.py,sha256=fMqtcOuipHO6RKPh1YB5o7d985dLKo76Whp3vrIei2E,14906 +setuptools/script (dev).tmpl,sha256=RUzQzCQUaXtwdLtYHWYbIQmOaES5Brqq1FvUA_tu-5I,218 +setuptools/script.tmpl,sha256=WGTt5piezO27c-Dbx6l5Q4T3Ff20A5z7872hv3aAhYY,138 +setuptools/tests/__init__.py,sha256=AnBfls2iJbTDQzmMKeLRt-9lxhaOHUVOZEgXv89Uwvs,335 +setuptools/tests/__pycache__/__init__.cpython-312.pyc,, +setuptools/tests/__pycache__/contexts.cpython-312.pyc,, +setuptools/tests/__pycache__/environment.cpython-312.pyc,, +setuptools/tests/__pycache__/fixtures.cpython-312.pyc,, +setuptools/tests/__pycache__/mod_with_constant.cpython-312.pyc,, +setuptools/tests/__pycache__/namespaces.cpython-312.pyc,, +setuptools/tests/__pycache__/script-with-bom.cpython-312.pyc,, +setuptools/tests/__pycache__/server.cpython-312.pyc,, +setuptools/tests/__pycache__/test_archive_util.cpython-312.pyc,, +setuptools/tests/__pycache__/test_bdist_deprecations.cpython-312.pyc,, +setuptools/tests/__pycache__/test_bdist_egg.cpython-312.pyc,, +setuptools/tests/__pycache__/test_bdist_wheel.cpython-312.pyc,, +setuptools/tests/__pycache__/test_build.cpython-312.pyc,, +setuptools/tests/__pycache__/test_build_clib.cpython-312.pyc,, +setuptools/tests/__pycache__/test_build_ext.cpython-312.pyc,, +setuptools/tests/__pycache__/test_build_meta.cpython-312.pyc,, +setuptools/tests/__pycache__/test_build_py.cpython-312.pyc,, +setuptools/tests/__pycache__/test_config_discovery.cpython-312.pyc,, +setuptools/tests/__pycache__/test_core_metadata.cpython-312.pyc,, +setuptools/tests/__pycache__/test_depends.cpython-312.pyc,, +setuptools/tests/__pycache__/test_develop.cpython-312.pyc,, +setuptools/tests/__pycache__/test_dist.cpython-312.pyc,, +setuptools/tests/__pycache__/test_dist_info.cpython-312.pyc,, +setuptools/tests/__pycache__/test_distutils_adoption.cpython-312.pyc,, +setuptools/tests/__pycache__/test_easy_install.cpython-312.pyc,, +setuptools/tests/__pycache__/test_editable_install.cpython-312.pyc,, +setuptools/tests/__pycache__/test_egg_info.cpython-312.pyc,, +setuptools/tests/__pycache__/test_extern.cpython-312.pyc,, +setuptools/tests/__pycache__/test_find_packages.cpython-312.pyc,, +setuptools/tests/__pycache__/test_find_py_modules.cpython-312.pyc,, +setuptools/tests/__pycache__/test_glob.cpython-312.pyc,, +setuptools/tests/__pycache__/test_install_scripts.cpython-312.pyc,, +setuptools/tests/__pycache__/test_logging.cpython-312.pyc,, +setuptools/tests/__pycache__/test_manifest.cpython-312.pyc,, +setuptools/tests/__pycache__/test_namespaces.cpython-312.pyc,, +setuptools/tests/__pycache__/test_packageindex.cpython-312.pyc,, +setuptools/tests/__pycache__/test_sandbox.cpython-312.pyc,, +setuptools/tests/__pycache__/test_sdist.cpython-312.pyc,, +setuptools/tests/__pycache__/test_setopt.cpython-312.pyc,, +setuptools/tests/__pycache__/test_setuptools.cpython-312.pyc,, +setuptools/tests/__pycache__/test_shutil_wrapper.cpython-312.pyc,, +setuptools/tests/__pycache__/test_unicode_utils.cpython-312.pyc,, +setuptools/tests/__pycache__/test_virtualenv.cpython-312.pyc,, +setuptools/tests/__pycache__/test_warnings.cpython-312.pyc,, +setuptools/tests/__pycache__/test_wheel.cpython-312.pyc,, +setuptools/tests/__pycache__/test_windows_wrappers.cpython-312.pyc,, +setuptools/tests/__pycache__/text.cpython-312.pyc,, +setuptools/tests/__pycache__/textwrap.cpython-312.pyc,, +setuptools/tests/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/tests/compat/__pycache__/__init__.cpython-312.pyc,, +setuptools/tests/compat/__pycache__/py39.cpython-312.pyc,, +setuptools/tests/compat/py39.py,sha256=eUy7_F-6KRTOIKl-veshUu6I0EdTSdBZMh0EV0lZ1-g,135 +setuptools/tests/config/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/tests/config/__pycache__/__init__.cpython-312.pyc,, +setuptools/tests/config/__pycache__/test_apply_pyprojecttoml.cpython-312.pyc,, +setuptools/tests/config/__pycache__/test_expand.cpython-312.pyc,, +setuptools/tests/config/__pycache__/test_pyprojecttoml.cpython-312.pyc,, +setuptools/tests/config/__pycache__/test_pyprojecttoml_dynamic_deps.cpython-312.pyc,, +setuptools/tests/config/__pycache__/test_setupcfg.cpython-312.pyc,, +setuptools/tests/config/downloads/__init__.py,sha256=9ixnDEdyL_arKbUzfuiJftAj9bGxKz8M9alOFZMjx9Y,1827 +setuptools/tests/config/downloads/__pycache__/__init__.cpython-312.pyc,, +setuptools/tests/config/downloads/__pycache__/preload.cpython-312.pyc,, +setuptools/tests/config/downloads/preload.py,sha256=sIGGZpY3cmMpMwiJYYYYHG2ifZJkvJgEotRFtiulV1I,450 +setuptools/tests/config/setupcfg_examples.txt,sha256=cAbVvCbkFZuTUL6xRRzRgqyB0rLvJTfvw3D30glo2OE,1912 +setuptools/tests/config/test_apply_pyprojecttoml.py,sha256=l6nE4d8WLU_eSWRic7VSoqeKv9Bi7CZGHcEuB2ehk2w,28807 +setuptools/tests/config/test_expand.py,sha256=S0oT6JvgA_oujR4YS4RUuf5gmOt1CTQV66RQDzV8xd4,8933 +setuptools/tests/config/test_pyprojecttoml.py,sha256=0LefSljUhA6MqtJ5AVzLhomqZcYiFKdu_1ckDeMT1LY,12406 +setuptools/tests/config/test_pyprojecttoml_dynamic_deps.py,sha256=9W73-yLhZJmvCiO4rTiQoBpZT5wNA90Xbd5n2HCshd4,3271 +setuptools/tests/config/test_setupcfg.py,sha256=ZvN-O-2Dgon1adp6oM6il8JWdgT9y196fRvqESU5ELI,33427 +setuptools/tests/contexts.py,sha256=TAdZKxmmodx1ExMVo01o4QpRjpIpo4X3IWKq_BnjxpU,3480 +setuptools/tests/environment.py,sha256=95_UtTaRiuvwYC9eXKEHbn02kDtZysvZq3UZJmPUj1I,3102 +setuptools/tests/fixtures.py,sha256=-V7iD6BeE2E0Rw6dVvTOCm36JG8ZTTnrXhN0GISlgrg,5197 +setuptools/tests/indexes/test_links_priority/external.html,sha256=eL9euOuE93JKZdqlXxBOlHbKwIuNuIdq7GBRpsaPMcU,92 +setuptools/tests/indexes/test_links_priority/simple/foobar/index.html,sha256=DD-TKr7UU4zAjHHz4VexYDNSAzR27levSh1c-k3ZdLE,174 +setuptools/tests/integration/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/tests/integration/__pycache__/__init__.cpython-312.pyc,, +setuptools/tests/integration/__pycache__/helpers.cpython-312.pyc,, +setuptools/tests/integration/__pycache__/test_pip_install_sdist.cpython-312.pyc,, +setuptools/tests/integration/helpers.py,sha256=3PHcS9SCA-fwVJmUP2ad5NQOttJAETI5Nnoc_xroO5k,2522 +setuptools/tests/integration/test_pip_install_sdist.py,sha256=SFbvuYF_hDzt6OtsQ5GjFNnxmoJ_eElfvpYsiyyGJ-g,8256 +setuptools/tests/mod_with_constant.py,sha256=X_Kj80M55w1tmQ4f7uZY91ZTALo4hKVT6EHxgYocUMQ,22 +setuptools/tests/namespaces.py,sha256=HPcI3nR5MCFWXpaADIJ1fwKxymcQgBkuw87Ic5PUSAQ,2774 +setuptools/tests/script-with-bom.py,sha256=hRRgIizEULGiG_ZTNoMY46HhKhxpWfy5FGcD6Qbh5fc,18 +setuptools/tests/server.py,sha256=0FDZf0cSInCP5n1haK7AxHo3jD261RK7D3-RjP-F53k,2397 +setuptools/tests/test_archive_util.py,sha256=buuKdY8XkW26Pe3IKAoBRGHG0MDumnuNoPg2WsAQzIg,845 +setuptools/tests/test_bdist_deprecations.py,sha256=75Xq3gYn79LIIyusEltbHan0bEgAt2e_CaL7KLS8-KQ,775 +setuptools/tests/test_bdist_egg.py,sha256=6PaYN1F3JDbIh1uK0urv7yJFcx98z5dn9SOJ8Mv91l8,1957 +setuptools/tests/test_bdist_wheel.py,sha256=dZ9a7OT_UyRvLnoCi2KGEIbtzhEQjM3YutYMA6ZCezs,23083 +setuptools/tests/test_build.py,sha256=wJgMz2hwHADcLFg-nXrwRVhus7hjmAeEGgrpIQwCGnA,798 +setuptools/tests/test_build_clib.py,sha256=bX51XRAf4uO7IuHFpjePnoK8mE74N2gsoeEqF-ofgws,3123 +setuptools/tests/test_build_ext.py,sha256=e4ZSxsYPB5zq1KSqGEuATZ0t0PJQzMhjjkKJ-hIjcgc,10099 +setuptools/tests/test_build_meta.py,sha256=Iakpp9Micvhxi9_F2RPyY2NnCB1G90a38s4O5A3CuiE,34118 +setuptools/tests/test_build_py.py,sha256=gobME_Cvzf6Ugxq70iWfXekb_xyyT61khwjFq8zkwfw,14186 +setuptools/tests/test_config_discovery.py,sha256=FqV-lOtkqaI-ayzU2zocSdD5TaRAgCZnixNDilKA6FQ,22580 +setuptools/tests/test_core_metadata.py,sha256=vbVJ5_Lsx_hsO_GdB6nQEXJRjA2ydx6_qSbr5LpheAA,20881 +setuptools/tests/test_depends.py,sha256=yQBXoQbNQlJit6mbRVoz6Bb553f3sNrq02lZimNz5XY,424 +setuptools/tests/test_develop.py,sha256=CLzXZ8-b5-VFTuau4P4yXEdLx1UdyTFcOfrV0qyUIdE,5142 +setuptools/tests/test_dist.py,sha256=GFjyL2etAxvVM3q7NhFEGcXS5gyKj8VzbqcbKzpqbOk,8901 +setuptools/tests/test_dist_info.py,sha256=5kBRj9tuBsVreBsY22H2feMO_JQZsSoOZMU_MJfUevY,7077 +setuptools/tests/test_distutils_adoption.py,sha256=_eynrOfyEqXFEmjUJhzpe8GXPyTUPvNSObs4qAAmBy8,5987 +setuptools/tests/test_easy_install.py,sha256=jx4lpFyee0G432cdnwBow3AkL4ibw-0QILwldwv5SCI,53534 +setuptools/tests/test_editable_install.py,sha256=7eTEtpT0k7QeVyZg64eh3kZn-SjckuB9LcokOuV37DI,43383 +setuptools/tests/test_egg_info.py,sha256=QCzoUOkFocmbkwS6XU7F8WNzKE8CGEMRxYBqKLgfUrc,44866 +setuptools/tests/test_extern.py,sha256=rpKU6oCcksumLwf5TeKlDluFQ0TUfbPwTLQbpxcFrCU,296 +setuptools/tests/test_find_packages.py,sha256=CTLAcTzWGWBLCcd2aAsUVkvO3ibrlqexFBdDKOWPoq8,7819 +setuptools/tests/test_find_py_modules.py,sha256=zQjuhIG5TQN2SJPix9ARo4DL_w84Ln8QsHDUjjbrtAQ,2404 +setuptools/tests/test_glob.py,sha256=P3JvpH-kXQ4BZ3zvRF-zKxOgwyWzwIaQIz0WHdxS0kk,887 +setuptools/tests/test_install_scripts.py,sha256=scIrJ6a_ssKqg4vIBNaUjmAKHEYLUUZ9WKnPeKnE6gc,3433 +setuptools/tests/test_logging.py,sha256=zlE5DlldukC7Jc54FNvDV_7ux3ErAkrfrN5CSsnNOUQ,2099 +setuptools/tests/test_manifest.py,sha256=eMg65pIA52DizB6mpktSU-b8CjwaNCS5MSgL_V1LrFI,18562 +setuptools/tests/test_namespaces.py,sha256=Y6utoe5PHHqL_DlgawqB9F8XpsUDPvvw1sQMenK04e0,4515 +setuptools/tests/test_packageindex.py,sha256=qEjLHpSu2gAkegwEstzHQT-Om1uQIYjA8zeNzEX79uo,8775 +setuptools/tests/test_sandbox.py,sha256=shUWE7fLTWe7Jzdfi6NheBWauG3oUukbUV46cArD0u0,4330 +setuptools/tests/test_sdist.py,sha256=RYLvPa_nfyC1ZmoinzqMzJynTDG4RtPYC19_0LU6pvs,32872 +setuptools/tests/test_setopt.py,sha256=3VxxM4ATfP-P4AGnDjoWCnHr5-i9CSEQTFYU1-FTnvI,1365 +setuptools/tests/test_setuptools.py,sha256=_eIhqKf45-OtHqxRf20KndOZJlJdS0PuFLXBO3M-LN8,9008 +setuptools/tests/test_shutil_wrapper.py,sha256=g15E11PtZxG-InB2BWNFyH-svObXx2XcMhgMLJPuFnc,641 +setuptools/tests/test_unicode_utils.py,sha256=xWfEEl8jkQCt9othUTXJfFmdyATAFggJs2tTxjbumbw,316 +setuptools/tests/test_virtualenv.py,sha256=g-njC_9JTAs1YVx_1dGJ_Q6RlInO4qKVu9-XAgNb6TY,3730 +setuptools/tests/test_warnings.py,sha256=zwR2zcnCeCeDqILZlJOPAcuyPHoDvGu1OtOVYiLMk74,3347 +setuptools/tests/test_wheel.py,sha256=J-83W1KdXTgAjFZE3H-ytohhvDE1iqdbE5YF5jLQlGQ,19370 +setuptools/tests/test_windows_wrappers.py,sha256=aF6UTowN3yzCgdBh9nDQVvYIfSYogrTK776TEyXEBqg,7881 +setuptools/tests/text.py,sha256=a12197pMVTvB6FAWQ0ujT8fIQiLIWJlFAl1UCaDUDfg,123 +setuptools/tests/textwrap.py,sha256=FNNNq_MiaEJx88PnsbJQIRxmj1qmgcAOCXXRsODPJN4,98 +setuptools/unicode_utils.py,sha256=ukMGh8pEAw6F_Ezb-K5D3c-078RgA_GcF0oW6lg4lSs,3189 +setuptools/version.py,sha256=WJCeUuyq74Aok2TeK9-OexZOu8XrlQy7-y0BEuWNovQ,161 +setuptools/warnings.py,sha256=oY0Se5eOqje_FEyjTgonUc0XGwgsrI5cgm1kkwulz_w,3796 +setuptools/wheel.py,sha256=xkAtvgm7uPTyYV2zqVmQ0wA8kLwOyRT2Jes1zAy07Ks,8624 +setuptools/windows_support.py,sha256=wW4IYLM1Bv7Z1MaauP2xmPjyy-wkmQnXdyvXscAf9fw,726 diff --git a/.venv/lib/python3.12/site-packages/setuptools-78.1.0.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/setuptools-78.1.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..1eb3c49d99559863120cfb8433fc8738fba43ba9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools-78.1.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (78.1.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/.venv/lib/python3.12/site-packages/setuptools-78.1.0.dist-info/entry_points.txt b/.venv/lib/python3.12/site-packages/setuptools-78.1.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..0db0a6c8f1b8d9c0ad4a25db6892e29f8988fcf2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools-78.1.0.dist-info/entry_points.txt @@ -0,0 +1,51 @@ +[distutils.commands] +alias = setuptools.command.alias:alias +bdist_egg = setuptools.command.bdist_egg:bdist_egg +bdist_rpm = setuptools.command.bdist_rpm:bdist_rpm +bdist_wheel = setuptools.command.bdist_wheel:bdist_wheel +build = setuptools.command.build:build +build_clib = setuptools.command.build_clib:build_clib +build_ext = setuptools.command.build_ext:build_ext +build_py = setuptools.command.build_py:build_py +develop = setuptools.command.develop:develop +dist_info = setuptools.command.dist_info:dist_info +easy_install = setuptools.command.easy_install:easy_install +editable_wheel = setuptools.command.editable_wheel:editable_wheel +egg_info = setuptools.command.egg_info:egg_info +install = setuptools.command.install:install +install_egg_info = setuptools.command.install_egg_info:install_egg_info +install_lib = setuptools.command.install_lib:install_lib +install_scripts = setuptools.command.install_scripts:install_scripts +rotate = setuptools.command.rotate:rotate +saveopts = setuptools.command.saveopts:saveopts +sdist = setuptools.command.sdist:sdist +setopt = setuptools.command.setopt:setopt + +[distutils.setup_keywords] +dependency_links = setuptools.dist:assert_string_list +eager_resources = setuptools.dist:assert_string_list +entry_points = setuptools.dist:check_entry_points +exclude_package_data = setuptools.dist:check_package_data +extras_require = setuptools.dist:check_extras +include_package_data = setuptools.dist:assert_bool +install_requires = setuptools.dist:check_requirements +namespace_packages = setuptools.dist:check_nsp +package_data = setuptools.dist:check_package_data +packages = setuptools.dist:check_packages +python_requires = setuptools.dist:check_specifier +setup_requires = setuptools.dist:check_requirements +use_2to3 = setuptools.dist:invalid_unless_false +zip_safe = setuptools.dist:assert_bool + +[egg_info.writers] +PKG-INFO = setuptools.command.egg_info:write_pkg_info +dependency_links.txt = setuptools.command.egg_info:overwrite_arg +eager_resources.txt = setuptools.command.egg_info:overwrite_arg +entry_points.txt = setuptools.command.egg_info:write_entries +namespace_packages.txt = setuptools.command.egg_info:overwrite_arg +requires.txt = setuptools.command.egg_info:write_requirements +top_level.txt = setuptools.command.egg_info:write_toplevel_names + +[setuptools.finalize_distribution_options] +keywords = setuptools.dist:Distribution._finalize_setup_keywords +parent_finalize = setuptools.dist:_Distribution.finalize_options diff --git a/.venv/lib/python3.12/site-packages/setuptools-78.1.0.dist-info/licenses/LICENSE b/.venv/lib/python3.12/site-packages/setuptools-78.1.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1bb5a44356f00884a71ceeefd24ded6caaba2418 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools-78.1.0.dist-info/licenses/LICENSE @@ -0,0 +1,17 @@ +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.12/site-packages/setuptools-78.1.0.dist-info/top_level.txt b/.venv/lib/python3.12/site-packages/setuptools-78.1.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..b5ac1070294b478b7cc2ce677207ee08813bfa37 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools-78.1.0.dist-info/top_level.txt @@ -0,0 +1,3 @@ +_distutils_hack +pkg_resources +setuptools diff --git a/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_bdist_dumb.py b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_bdist_dumb.py new file mode 100644 index 0000000000000000000000000000000000000000..1fc51d244a78058329c56a618b092e466715e565 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_bdist_dumb.py @@ -0,0 +1,78 @@ +"""Tests for distutils.command.bdist_dumb.""" + +import os +import sys +import zipfile +from distutils.command.bdist_dumb import bdist_dumb +from distutils.core import Distribution +from distutils.tests import support + +import pytest + +SETUP_PY = """\ +from distutils.core import setup +import foo + +setup(name='foo', version='0.1', py_modules=['foo'], + url='xxx', author='xxx', author_email='xxx') + +""" + + +@support.combine_markers +@pytest.mark.usefixtures('save_env') +@pytest.mark.usefixtures('save_argv') +@pytest.mark.usefixtures('save_cwd') +class TestBuildDumb( + support.TempdirManager, +): + @pytest.mark.usefixtures('needs_zlib') + def test_simple_built(self): + # let's create a simple package + tmp_dir = self.mkdtemp() + pkg_dir = os.path.join(tmp_dir, 'foo') + os.mkdir(pkg_dir) + self.write_file((pkg_dir, 'setup.py'), SETUP_PY) + self.write_file((pkg_dir, 'foo.py'), '#') + self.write_file((pkg_dir, 'MANIFEST.in'), 'include foo.py') + self.write_file((pkg_dir, 'README'), '') + + dist = Distribution({ + 'name': 'foo', + 'version': '0.1', + 'py_modules': ['foo'], + 'url': 'xxx', + 'author': 'xxx', + 'author_email': 'xxx', + }) + dist.script_name = 'setup.py' + os.chdir(pkg_dir) + + sys.argv = ['setup.py'] + cmd = bdist_dumb(dist) + + # so the output is the same no matter + # what is the platform + cmd.format = 'zip' + + cmd.ensure_finalized() + cmd.run() + + # see what we have + dist_created = os.listdir(os.path.join(pkg_dir, 'dist')) + base = f"{dist.get_fullname()}.{cmd.plat_name}.zip" + + assert dist_created == [base] + + # now let's check what we have in the zip file + fp = zipfile.ZipFile(os.path.join('dist', base)) + try: + contents = fp.namelist() + finally: + fp.close() + + contents = sorted(filter(None, map(os.path.basename, contents))) + wanted = ['foo-0.1-py{}.{}.egg-info'.format(*sys.version_info[:2]), 'foo.py'] + if not sys.dont_write_bytecode: + wanted.append(f'foo.{sys.implementation.cache_tag}.pyc') + assert contents == sorted(wanted) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_bdist_rpm.py b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_bdist_rpm.py new file mode 100644 index 0000000000000000000000000000000000000000..75051430e224c8908e22601133a40f5f82ee455a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_bdist_rpm.py @@ -0,0 +1,127 @@ +"""Tests for distutils.command.bdist_rpm.""" + +import os +import shutil # noqa: F401 +import sys +from distutils.command.bdist_rpm import bdist_rpm +from distutils.core import Distribution +from distutils.tests import support + +import pytest +from test.support import requires_zlib + +SETUP_PY = """\ +from distutils.core import setup +import foo + +setup(name='foo', version='0.1', py_modules=['foo'], + url='xxx', author='xxx', author_email='xxx') + +""" + + +@pytest.fixture(autouse=True) +def sys_executable_encodable(): + try: + sys.executable.encode('UTF-8') + except UnicodeEncodeError: + pytest.skip("sys.executable is not encodable to UTF-8") + + +mac_woes = pytest.mark.skipif( + "not sys.platform.startswith('linux')", + reason='spurious sdtout/stderr output under macOS', +) + + +@pytest.mark.usefixtures('save_env') +@pytest.mark.usefixtures('save_argv') +@pytest.mark.usefixtures('save_cwd') +class TestBuildRpm( + support.TempdirManager, +): + @mac_woes + @requires_zlib() + @pytest.mark.skipif("not shutil.which('rpm')") + @pytest.mark.skipif("not shutil.which('rpmbuild')") + def test_quiet(self): + # let's create a package + tmp_dir = self.mkdtemp() + os.environ['HOME'] = tmp_dir # to confine dir '.rpmdb' creation + pkg_dir = os.path.join(tmp_dir, 'foo') + os.mkdir(pkg_dir) + self.write_file((pkg_dir, 'setup.py'), SETUP_PY) + self.write_file((pkg_dir, 'foo.py'), '#') + self.write_file((pkg_dir, 'MANIFEST.in'), 'include foo.py') + self.write_file((pkg_dir, 'README'), '') + + dist = Distribution({ + 'name': 'foo', + 'version': '0.1', + 'py_modules': ['foo'], + 'url': 'xxx', + 'author': 'xxx', + 'author_email': 'xxx', + }) + dist.script_name = 'setup.py' + os.chdir(pkg_dir) + + sys.argv = ['setup.py'] + cmd = bdist_rpm(dist) + cmd.fix_python = True + + # running in quiet mode + cmd.quiet = True + cmd.ensure_finalized() + cmd.run() + + dist_created = os.listdir(os.path.join(pkg_dir, 'dist')) + assert 'foo-0.1-1.noarch.rpm' in dist_created + + # bug #2945: upload ignores bdist_rpm files + assert ('bdist_rpm', 'any', 'dist/foo-0.1-1.src.rpm') in dist.dist_files + assert ('bdist_rpm', 'any', 'dist/foo-0.1-1.noarch.rpm') in dist.dist_files + + @mac_woes + @requires_zlib() + # https://bugs.python.org/issue1533164 + @pytest.mark.skipif("not shutil.which('rpm')") + @pytest.mark.skipif("not shutil.which('rpmbuild')") + def test_no_optimize_flag(self): + # let's create a package that breaks bdist_rpm + tmp_dir = self.mkdtemp() + os.environ['HOME'] = tmp_dir # to confine dir '.rpmdb' creation + pkg_dir = os.path.join(tmp_dir, 'foo') + os.mkdir(pkg_dir) + self.write_file((pkg_dir, 'setup.py'), SETUP_PY) + self.write_file((pkg_dir, 'foo.py'), '#') + self.write_file((pkg_dir, 'MANIFEST.in'), 'include foo.py') + self.write_file((pkg_dir, 'README'), '') + + dist = Distribution({ + 'name': 'foo', + 'version': '0.1', + 'py_modules': ['foo'], + 'url': 'xxx', + 'author': 'xxx', + 'author_email': 'xxx', + }) + dist.script_name = 'setup.py' + os.chdir(pkg_dir) + + sys.argv = ['setup.py'] + cmd = bdist_rpm(dist) + cmd.fix_python = True + + cmd.quiet = True + cmd.ensure_finalized() + cmd.run() + + dist_created = os.listdir(os.path.join(pkg_dir, 'dist')) + assert 'foo-0.1-1.noarch.rpm' in dist_created + + # bug #2945: upload ignores bdist_rpm files + assert ('bdist_rpm', 'any', 'dist/foo-0.1-1.src.rpm') in dist.dist_files + assert ('bdist_rpm', 'any', 'dist/foo-0.1-1.noarch.rpm') in dist.dist_files + + os.remove(os.path.join(pkg_dir, 'dist', 'foo-0.1-1.noarch.rpm')) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_build.py b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_build.py new file mode 100644 index 0000000000000000000000000000000000000000..f7fe69acd1ad39cf40d277afd6409648b18df146 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_build.py @@ -0,0 +1,49 @@ +"""Tests for distutils.command.build.""" + +import os +import sys +from distutils.command.build import build +from distutils.tests import support +from sysconfig import get_config_var, get_platform + + +class TestBuild(support.TempdirManager): + def test_finalize_options(self): + pkg_dir, dist = self.create_dist() + cmd = build(dist) + cmd.finalize_options() + + # if not specified, plat_name gets the current platform + assert cmd.plat_name == get_platform() + + # build_purelib is build + lib + wanted = os.path.join(cmd.build_base, 'lib') + assert cmd.build_purelib == wanted + + # build_platlib is 'build/lib.platform-cache_tag[-pydebug]' + # examples: + # build/lib.macosx-10.3-i386-cpython39 + plat_spec = f'.{cmd.plat_name}-{sys.implementation.cache_tag}' + if get_config_var('Py_GIL_DISABLED'): + plat_spec += 't' + if hasattr(sys, 'gettotalrefcount'): + assert cmd.build_platlib.endswith('-pydebug') + plat_spec += '-pydebug' + wanted = os.path.join(cmd.build_base, 'lib' + plat_spec) + assert cmd.build_platlib == wanted + + # by default, build_lib = build_purelib + assert cmd.build_lib == cmd.build_purelib + + # build_temp is build/temp. + wanted = os.path.join(cmd.build_base, 'temp' + plat_spec) + assert cmd.build_temp == wanted + + # build_scripts is build/scripts-x.x + wanted = os.path.join( + cmd.build_base, f'scripts-{sys.version_info.major}.{sys.version_info.minor}' + ) + assert cmd.build_scripts == wanted + + # executable is os.path.normpath(sys.executable) + assert cmd.executable == os.path.normpath(sys.executable) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_build_clib.py b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_build_clib.py new file mode 100644 index 0000000000000000000000000000000000000000..f76f26bcea04ebeaeba20d3c65881198f841c9b5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_build_clib.py @@ -0,0 +1,134 @@ +"""Tests for distutils.command.build_clib.""" + +import os +from distutils.command.build_clib import build_clib +from distutils.errors import DistutilsSetupError +from distutils.tests import missing_compiler_executable, support + +import pytest + + +class TestBuildCLib(support.TempdirManager): + def test_check_library_dist(self): + pkg_dir, dist = self.create_dist() + cmd = build_clib(dist) + + # 'libraries' option must be a list + with pytest.raises(DistutilsSetupError): + cmd.check_library_list('foo') + + # each element of 'libraries' must a 2-tuple + with pytest.raises(DistutilsSetupError): + cmd.check_library_list(['foo1', 'foo2']) + + # first element of each tuple in 'libraries' + # must be a string (the library name) + with pytest.raises(DistutilsSetupError): + cmd.check_library_list([(1, 'foo1'), ('name', 'foo2')]) + + # library name may not contain directory separators + with pytest.raises(DistutilsSetupError): + cmd.check_library_list( + [('name', 'foo1'), ('another/name', 'foo2')], + ) + + # second element of each tuple must be a dictionary (build info) + with pytest.raises(DistutilsSetupError): + cmd.check_library_list( + [('name', {}), ('another', 'foo2')], + ) + + # those work + libs = [('name', {}), ('name', {'ok': 'good'})] + cmd.check_library_list(libs) + + def test_get_source_files(self): + pkg_dir, dist = self.create_dist() + cmd = build_clib(dist) + + # "in 'libraries' option 'sources' must be present and must be + # a list of source filenames + cmd.libraries = [('name', {})] + with pytest.raises(DistutilsSetupError): + cmd.get_source_files() + + cmd.libraries = [('name', {'sources': 1})] + with pytest.raises(DistutilsSetupError): + cmd.get_source_files() + + cmd.libraries = [('name', {'sources': ['a', 'b']})] + assert cmd.get_source_files() == ['a', 'b'] + + cmd.libraries = [('name', {'sources': ('a', 'b')})] + assert cmd.get_source_files() == ['a', 'b'] + + cmd.libraries = [ + ('name', {'sources': ('a', 'b')}), + ('name2', {'sources': ['c', 'd']}), + ] + assert cmd.get_source_files() == ['a', 'b', 'c', 'd'] + + def test_build_libraries(self): + pkg_dir, dist = self.create_dist() + cmd = build_clib(dist) + + class FakeCompiler: + def compile(*args, **kw): + pass + + create_static_lib = compile + + cmd.compiler = FakeCompiler() + + # build_libraries is also doing a bit of typo checking + lib = [('name', {'sources': 'notvalid'})] + with pytest.raises(DistutilsSetupError): + cmd.build_libraries(lib) + + lib = [('name', {'sources': list()})] + cmd.build_libraries(lib) + + lib = [('name', {'sources': tuple()})] + cmd.build_libraries(lib) + + def test_finalize_options(self): + pkg_dir, dist = self.create_dist() + cmd = build_clib(dist) + + cmd.include_dirs = 'one-dir' + cmd.finalize_options() + assert cmd.include_dirs == ['one-dir'] + + cmd.include_dirs = None + cmd.finalize_options() + assert cmd.include_dirs == [] + + cmd.distribution.libraries = 'WONTWORK' + with pytest.raises(DistutilsSetupError): + cmd.finalize_options() + + @pytest.mark.skipif('platform.system() == "Windows"') + def test_run(self): + pkg_dir, dist = self.create_dist() + cmd = build_clib(dist) + + foo_c = os.path.join(pkg_dir, 'foo.c') + self.write_file(foo_c, 'int main(void) { return 1;}\n') + cmd.libraries = [('foo', {'sources': [foo_c]})] + + build_temp = os.path.join(pkg_dir, 'build') + os.mkdir(build_temp) + cmd.build_temp = build_temp + cmd.build_clib = build_temp + + # Before we run the command, we want to make sure + # all commands are present on the system. + ccmd = missing_compiler_executable() + if ccmd is not None: + self.skipTest(f'The {ccmd!r} command is not found') + + # this should work + cmd.run() + + # let's check the result + assert 'libfoo.a' in os.listdir(build_temp) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_build_ext.py b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_build_ext.py new file mode 100644 index 0000000000000000000000000000000000000000..dab0507f3d3ec104fb4acfe5b15f92661ff33a37 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_build_ext.py @@ -0,0 +1,628 @@ +import contextlib +import glob +import importlib +import os.path +import platform +import re +import shutil +import site +import subprocess +import sys +import tempfile +import textwrap +import time +from distutils import sysconfig +from distutils.command.build_ext import build_ext +from distutils.core import Distribution +from distutils.errors import ( + CompileError, + DistutilsPlatformError, + DistutilsSetupError, + UnknownFileError, +) +from distutils.extension import Extension +from distutils.tests import missing_compiler_executable +from distutils.tests.support import TempdirManager, copy_xxmodule_c, fixup_build_ext +from io import StringIO + +import jaraco.path +import path +import pytest +from test import support + +from .compat import py39 as import_helper + + +@pytest.fixture() +def user_site_dir(request): + self = request.instance + self.tmp_dir = self.mkdtemp() + self.tmp_path = path.Path(self.tmp_dir) + from distutils.command import build_ext + + orig_user_base = site.USER_BASE + + site.USER_BASE = self.mkdtemp() + build_ext.USER_BASE = site.USER_BASE + + # bpo-30132: On Windows, a .pdb file may be created in the current + # working directory. Create a temporary working directory to cleanup + # everything at the end of the test. + with self.tmp_path: + yield + + site.USER_BASE = orig_user_base + build_ext.USER_BASE = orig_user_base + + if sys.platform == 'cygwin': + time.sleep(1) + + +@contextlib.contextmanager +def safe_extension_import(name, path): + with import_helper.CleanImport(name): + with extension_redirect(name, path) as new_path: + with import_helper.DirsOnSysPath(new_path): + yield + + +@contextlib.contextmanager +def extension_redirect(mod, path): + """ + Tests will fail to tear down an extension module if it's been imported. + + Before importing, copy the file to a temporary directory that won't + be cleaned up. Yield the new path. + """ + if platform.system() != "Windows" and sys.platform != "cygwin": + yield path + return + with import_helper.DirsOnSysPath(path): + spec = importlib.util.find_spec(mod) + filename = os.path.basename(spec.origin) + trash_dir = tempfile.mkdtemp(prefix='deleteme') + dest = os.path.join(trash_dir, os.path.basename(filename)) + shutil.copy(spec.origin, dest) + yield trash_dir + # TODO: can the file be scheduled for deletion? + + +@pytest.mark.usefixtures('user_site_dir') +class TestBuildExt(TempdirManager): + def build_ext(self, *args, **kwargs): + return build_ext(*args, **kwargs) + + @pytest.mark.parametrize("copy_so", [False]) + def test_build_ext(self, copy_so): + missing_compiler_executable() + copy_xxmodule_c(self.tmp_dir) + xx_c = os.path.join(self.tmp_dir, 'xxmodule.c') + xx_ext = Extension('xx', [xx_c]) + if sys.platform != "win32": + if not copy_so: + xx_ext = Extension( + 'xx', + [xx_c], + library_dirs=['/usr/lib'], + libraries=['z'], + runtime_library_dirs=['/usr/lib'], + ) + elif sys.platform == 'linux': + libz_so = { + os.path.realpath(name) for name in glob.iglob('/usr/lib*/libz.so*') + } + libz_so = sorted(libz_so, key=lambda lib_path: len(lib_path)) + shutil.copyfile(libz_so[-1], '/tmp/libxx_z.so') + + xx_ext = Extension( + 'xx', + [xx_c], + library_dirs=['/tmp'], + libraries=['xx_z'], + runtime_library_dirs=['/tmp'], + ) + dist = Distribution({'name': 'xx', 'ext_modules': [xx_ext]}) + dist.package_dir = self.tmp_dir + cmd = self.build_ext(dist) + fixup_build_ext(cmd) + cmd.build_lib = self.tmp_dir + cmd.build_temp = self.tmp_dir + + old_stdout = sys.stdout + if not support.verbose: + # silence compiler output + sys.stdout = StringIO() + try: + cmd.ensure_finalized() + cmd.run() + finally: + sys.stdout = old_stdout + + with safe_extension_import('xx', self.tmp_dir): + self._test_xx(copy_so) + + if sys.platform == 'linux' and copy_so: + os.unlink('/tmp/libxx_z.so') + + @staticmethod + def _test_xx(copy_so): + import xx # type: ignore[import-not-found] # Module generated for tests + + for attr in ('error', 'foo', 'new', 'roj'): + assert hasattr(xx, attr) + + assert xx.foo(2, 5) == 7 + assert xx.foo(13, 15) == 28 + assert xx.new().demo() is None + if support.HAVE_DOCSTRINGS: + doc = 'This is a template module just for instruction.' + assert xx.__doc__ == doc + assert isinstance(xx.Null(), xx.Null) + assert isinstance(xx.Str(), xx.Str) + + if sys.platform == 'linux': + so_headers = subprocess.check_output( + ["readelf", "-d", xx.__file__], universal_newlines=True + ) + import pprint + + pprint.pprint(so_headers) + rpaths = [ + rpath + for line in so_headers.split("\n") + if "RPATH" in line or "RUNPATH" in line + for rpath in line.split()[2][1:-1].split(":") + ] + if not copy_so: + pprint.pprint(rpaths) + # Linked against a library in /usr/lib{,64} + assert "/usr/lib" not in rpaths and "/usr/lib64" not in rpaths + else: + # Linked against a library in /tmp + assert "/tmp" in rpaths + # The import is the real test here + + def test_solaris_enable_shared(self): + dist = Distribution({'name': 'xx'}) + cmd = self.build_ext(dist) + old = sys.platform + + sys.platform = 'sunos' # fooling finalize_options + from distutils.sysconfig import _config_vars + + old_var = _config_vars.get('Py_ENABLE_SHARED') + _config_vars['Py_ENABLE_SHARED'] = True + try: + cmd.ensure_finalized() + finally: + sys.platform = old + if old_var is None: + del _config_vars['Py_ENABLE_SHARED'] + else: + _config_vars['Py_ENABLE_SHARED'] = old_var + + # make sure we get some library dirs under solaris + assert len(cmd.library_dirs) > 0 + + def test_user_site(self): + import site + + dist = Distribution({'name': 'xx'}) + cmd = self.build_ext(dist) + + # making sure the user option is there + options = [name for name, short, label in cmd.user_options] + assert 'user' in options + + # setting a value + cmd.user = True + + # setting user based lib and include + lib = os.path.join(site.USER_BASE, 'lib') + incl = os.path.join(site.USER_BASE, 'include') + os.mkdir(lib) + os.mkdir(incl) + + # let's run finalize + cmd.ensure_finalized() + + # see if include_dirs and library_dirs + # were set + assert lib in cmd.library_dirs + assert lib in cmd.rpath + assert incl in cmd.include_dirs + + def test_optional_extension(self): + # this extension will fail, but let's ignore this failure + # with the optional argument. + modules = [Extension('foo', ['xxx'], optional=False)] + dist = Distribution({'name': 'xx', 'ext_modules': modules}) + cmd = self.build_ext(dist) + cmd.ensure_finalized() + with pytest.raises((UnknownFileError, CompileError)): + cmd.run() # should raise an error + + modules = [Extension('foo', ['xxx'], optional=True)] + dist = Distribution({'name': 'xx', 'ext_modules': modules}) + cmd = self.build_ext(dist) + cmd.ensure_finalized() + cmd.run() # should pass + + def test_finalize_options(self): + # Make sure Python's include directories (for Python.h, pyconfig.h, + # etc.) are in the include search path. + modules = [Extension('foo', ['xxx'], optional=False)] + dist = Distribution({'name': 'xx', 'ext_modules': modules}) + cmd = self.build_ext(dist) + cmd.finalize_options() + + py_include = sysconfig.get_python_inc() + for p in py_include.split(os.path.pathsep): + assert p in cmd.include_dirs + + plat_py_include = sysconfig.get_python_inc(plat_specific=True) + for p in plat_py_include.split(os.path.pathsep): + assert p in cmd.include_dirs + + # make sure cmd.libraries is turned into a list + # if it's a string + cmd = self.build_ext(dist) + cmd.libraries = 'my_lib, other_lib lastlib' + cmd.finalize_options() + assert cmd.libraries == ['my_lib', 'other_lib', 'lastlib'] + + # make sure cmd.library_dirs is turned into a list + # if it's a string + cmd = self.build_ext(dist) + cmd.library_dirs = f'my_lib_dir{os.pathsep}other_lib_dir' + cmd.finalize_options() + assert 'my_lib_dir' in cmd.library_dirs + assert 'other_lib_dir' in cmd.library_dirs + + # make sure rpath is turned into a list + # if it's a string + cmd = self.build_ext(dist) + cmd.rpath = f'one{os.pathsep}two' + cmd.finalize_options() + assert cmd.rpath == ['one', 'two'] + + # make sure cmd.link_objects is turned into a list + # if it's a string + cmd = build_ext(dist) + cmd.link_objects = 'one two,three' + cmd.finalize_options() + assert cmd.link_objects == ['one', 'two', 'three'] + + # XXX more tests to perform for win32 + + # make sure define is turned into 2-tuples + # strings if they are ','-separated strings + cmd = self.build_ext(dist) + cmd.define = 'one,two' + cmd.finalize_options() + assert cmd.define == [('one', '1'), ('two', '1')] + + # make sure undef is turned into a list of + # strings if they are ','-separated strings + cmd = self.build_ext(dist) + cmd.undef = 'one,two' + cmd.finalize_options() + assert cmd.undef == ['one', 'two'] + + # make sure swig_opts is turned into a list + cmd = self.build_ext(dist) + cmd.swig_opts = None + cmd.finalize_options() + assert cmd.swig_opts == [] + + cmd = self.build_ext(dist) + cmd.swig_opts = '1 2' + cmd.finalize_options() + assert cmd.swig_opts == ['1', '2'] + + def test_check_extensions_list(self): + dist = Distribution() + cmd = self.build_ext(dist) + cmd.finalize_options() + + # 'extensions' option must be a list of Extension instances + with pytest.raises(DistutilsSetupError): + cmd.check_extensions_list('foo') + + # each element of 'ext_modules' option must be an + # Extension instance or 2-tuple + exts = [('bar', 'foo', 'bar'), 'foo'] + with pytest.raises(DistutilsSetupError): + cmd.check_extensions_list(exts) + + # first element of each tuple in 'ext_modules' + # must be the extension name (a string) and match + # a python dotted-separated name + exts = [('foo-bar', '')] + with pytest.raises(DistutilsSetupError): + cmd.check_extensions_list(exts) + + # second element of each tuple in 'ext_modules' + # must be a dictionary (build info) + exts = [('foo.bar', '')] + with pytest.raises(DistutilsSetupError): + cmd.check_extensions_list(exts) + + # ok this one should pass + exts = [('foo.bar', {'sources': [''], 'libraries': 'foo', 'some': 'bar'})] + cmd.check_extensions_list(exts) + ext = exts[0] + assert isinstance(ext, Extension) + + # check_extensions_list adds in ext the values passed + # when they are in ('include_dirs', 'library_dirs', 'libraries' + # 'extra_objects', 'extra_compile_args', 'extra_link_args') + assert ext.libraries == 'foo' + assert not hasattr(ext, 'some') + + # 'macros' element of build info dict must be 1- or 2-tuple + exts = [ + ( + 'foo.bar', + { + 'sources': [''], + 'libraries': 'foo', + 'some': 'bar', + 'macros': [('1', '2', '3'), 'foo'], + }, + ) + ] + with pytest.raises(DistutilsSetupError): + cmd.check_extensions_list(exts) + + exts[0][1]['macros'] = [('1', '2'), ('3',)] + cmd.check_extensions_list(exts) + assert exts[0].undef_macros == ['3'] + assert exts[0].define_macros == [('1', '2')] + + def test_get_source_files(self): + modules = [Extension('foo', ['xxx'], optional=False)] + dist = Distribution({'name': 'xx', 'ext_modules': modules}) + cmd = self.build_ext(dist) + cmd.ensure_finalized() + assert cmd.get_source_files() == ['xxx'] + + def test_unicode_module_names(self): + modules = [ + Extension('foo', ['aaa'], optional=False), + Extension('föö', ['uuu'], optional=False), + ] + dist = Distribution({'name': 'xx', 'ext_modules': modules}) + cmd = self.build_ext(dist) + cmd.ensure_finalized() + assert re.search(r'foo(_d)?\..*', cmd.get_ext_filename(modules[0].name)) + assert re.search(r'föö(_d)?\..*', cmd.get_ext_filename(modules[1].name)) + assert cmd.get_export_symbols(modules[0]) == ['PyInit_foo'] + assert cmd.get_export_symbols(modules[1]) == ['PyInitU_f_1gaa'] + + def test_export_symbols__init__(self): + # https://github.com/python/cpython/issues/80074 + # https://github.com/pypa/setuptools/issues/4826 + modules = [ + Extension('foo.__init__', ['aaa']), + Extension('föö.__init__', ['uuu']), + ] + dist = Distribution({'name': 'xx', 'ext_modules': modules}) + cmd = self.build_ext(dist) + cmd.ensure_finalized() + assert cmd.get_export_symbols(modules[0]) == ['PyInit_foo'] + assert cmd.get_export_symbols(modules[1]) == ['PyInitU_f_1gaa'] + + def test_compiler_option(self): + # cmd.compiler is an option and + # should not be overridden by a compiler instance + # when the command is run + dist = Distribution() + cmd = self.build_ext(dist) + cmd.compiler = 'unix' + cmd.ensure_finalized() + cmd.run() + assert cmd.compiler == 'unix' + + def test_get_outputs(self): + missing_compiler_executable() + tmp_dir = self.mkdtemp() + c_file = os.path.join(tmp_dir, 'foo.c') + self.write_file(c_file, 'void PyInit_foo(void) {}\n') + ext = Extension('foo', [c_file], optional=False) + dist = Distribution({'name': 'xx', 'ext_modules': [ext]}) + cmd = self.build_ext(dist) + fixup_build_ext(cmd) + cmd.ensure_finalized() + assert len(cmd.get_outputs()) == 1 + + cmd.build_lib = os.path.join(self.tmp_dir, 'build') + cmd.build_temp = os.path.join(self.tmp_dir, 'tempt') + + # issue #5977 : distutils build_ext.get_outputs + # returns wrong result with --inplace + other_tmp_dir = os.path.realpath(self.mkdtemp()) + old_wd = os.getcwd() + os.chdir(other_tmp_dir) + try: + cmd.inplace = True + cmd.run() + so_file = cmd.get_outputs()[0] + finally: + os.chdir(old_wd) + assert os.path.exists(so_file) + ext_suffix = sysconfig.get_config_var('EXT_SUFFIX') + assert so_file.endswith(ext_suffix) + so_dir = os.path.dirname(so_file) + assert so_dir == other_tmp_dir + + cmd.inplace = False + cmd.compiler = None + cmd.run() + so_file = cmd.get_outputs()[0] + assert os.path.exists(so_file) + assert so_file.endswith(ext_suffix) + so_dir = os.path.dirname(so_file) + assert so_dir == cmd.build_lib + + # inplace = False, cmd.package = 'bar' + build_py = cmd.get_finalized_command('build_py') + build_py.package_dir = {'': 'bar'} + path = cmd.get_ext_fullpath('foo') + # checking that the last directory is the build_dir + path = os.path.split(path)[0] + assert path == cmd.build_lib + + # inplace = True, cmd.package = 'bar' + cmd.inplace = True + other_tmp_dir = os.path.realpath(self.mkdtemp()) + old_wd = os.getcwd() + os.chdir(other_tmp_dir) + try: + path = cmd.get_ext_fullpath('foo') + finally: + os.chdir(old_wd) + # checking that the last directory is bar + path = os.path.split(path)[0] + lastdir = os.path.split(path)[-1] + assert lastdir == 'bar' + + def test_ext_fullpath(self): + ext = sysconfig.get_config_var('EXT_SUFFIX') + # building lxml.etree inplace + # etree_c = os.path.join(self.tmp_dir, 'lxml.etree.c') + # etree_ext = Extension('lxml.etree', [etree_c]) + # dist = Distribution({'name': 'lxml', 'ext_modules': [etree_ext]}) + dist = Distribution() + cmd = self.build_ext(dist) + cmd.inplace = True + cmd.distribution.package_dir = {'': 'src'} + cmd.distribution.packages = ['lxml', 'lxml.html'] + curdir = os.getcwd() + wanted = os.path.join(curdir, 'src', 'lxml', 'etree' + ext) + path = cmd.get_ext_fullpath('lxml.etree') + assert wanted == path + + # building lxml.etree not inplace + cmd.inplace = False + cmd.build_lib = os.path.join(curdir, 'tmpdir') + wanted = os.path.join(curdir, 'tmpdir', 'lxml', 'etree' + ext) + path = cmd.get_ext_fullpath('lxml.etree') + assert wanted == path + + # building twisted.runner.portmap not inplace + build_py = cmd.get_finalized_command('build_py') + build_py.package_dir = {} + cmd.distribution.packages = ['twisted', 'twisted.runner.portmap'] + path = cmd.get_ext_fullpath('twisted.runner.portmap') + wanted = os.path.join(curdir, 'tmpdir', 'twisted', 'runner', 'portmap' + ext) + assert wanted == path + + # building twisted.runner.portmap inplace + cmd.inplace = True + path = cmd.get_ext_fullpath('twisted.runner.portmap') + wanted = os.path.join(curdir, 'twisted', 'runner', 'portmap' + ext) + assert wanted == path + + @pytest.mark.skipif('platform.system() != "Darwin"') + @pytest.mark.usefixtures('save_env') + def test_deployment_target_default(self): + # Issue 9516: Test that, in the absence of the environment variable, + # an extension module is compiled with the same deployment target as + # the interpreter. + self._try_compile_deployment_target('==', None) + + @pytest.mark.skipif('platform.system() != "Darwin"') + @pytest.mark.usefixtures('save_env') + def test_deployment_target_too_low(self): + # Issue 9516: Test that an extension module is not allowed to be + # compiled with a deployment target less than that of the interpreter. + with pytest.raises(DistutilsPlatformError): + self._try_compile_deployment_target('>', '10.1') + + @pytest.mark.skipif('platform.system() != "Darwin"') + @pytest.mark.usefixtures('save_env') + def test_deployment_target_higher_ok(self): # pragma: no cover + # Issue 9516: Test that an extension module can be compiled with a + # deployment target higher than that of the interpreter: the ext + # module may depend on some newer OS feature. + deptarget = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET') + if deptarget: + # increment the minor version number (i.e. 10.6 -> 10.7) + deptarget = [int(x) for x in deptarget.split('.')] + deptarget[-1] += 1 + deptarget = '.'.join(str(i) for i in deptarget) + self._try_compile_deployment_target('<', deptarget) + + def _try_compile_deployment_target(self, operator, target): # pragma: no cover + if target is None: + if os.environ.get('MACOSX_DEPLOYMENT_TARGET'): + del os.environ['MACOSX_DEPLOYMENT_TARGET'] + else: + os.environ['MACOSX_DEPLOYMENT_TARGET'] = target + + jaraco.path.build( + { + 'deptargetmodule.c': textwrap.dedent(f"""\ + #include + + int dummy; + + #if TARGET {operator} MAC_OS_X_VERSION_MIN_REQUIRED + #else + #error "Unexpected target" + #endif + + """), + }, + self.tmp_path, + ) + + # get the deployment target that the interpreter was built with + target = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET') + target = tuple(map(int, target.split('.')[0:2])) + # format the target value as defined in the Apple + # Availability Macros. We can't use the macro names since + # at least one value we test with will not exist yet. + if target[:2] < (10, 10): + # for 10.1 through 10.9.x -> "10n0" + tmpl = '{:02}{:01}0' + else: + # for 10.10 and beyond -> "10nn00" + if len(target) >= 2: + tmpl = '{:02}{:02}00' + else: + # 11 and later can have no minor version (11 instead of 11.0) + tmpl = '{:02}0000' + target = tmpl.format(*target) + deptarget_ext = Extension( + 'deptarget', + [self.tmp_path / 'deptargetmodule.c'], + extra_compile_args=[f'-DTARGET={target}'], + ) + dist = Distribution({'name': 'deptarget', 'ext_modules': [deptarget_ext]}) + dist.package_dir = self.tmp_dir + cmd = self.build_ext(dist) + cmd.build_lib = self.tmp_dir + cmd.build_temp = self.tmp_dir + + try: + old_stdout = sys.stdout + if not support.verbose: + # silence compiler output + sys.stdout = StringIO() + try: + cmd.ensure_finalized() + cmd.run() + finally: + sys.stdout = old_stdout + + except CompileError: + self.fail("Wrong deployment target during compilation") + + +class TestParallelBuildExt(TestBuildExt): + def build_ext(self, *args, **kwargs): + build_ext = super().build_ext(*args, **kwargs) + build_ext.parallel = True + return build_ext diff --git a/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_build_py.py b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_build_py.py new file mode 100644 index 0000000000000000000000000000000000000000..b316ed43a11836210caeb7177bd8890a1f61d1bb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_build_py.py @@ -0,0 +1,196 @@ +"""Tests for distutils.command.build_py.""" + +import os +import sys +from distutils.command.build_py import build_py +from distutils.core import Distribution +from distutils.errors import DistutilsFileError +from distutils.tests import support + +import jaraco.path +import pytest + + +@support.combine_markers +class TestBuildPy(support.TempdirManager): + def test_package_data(self): + sources = self.mkdtemp() + jaraco.path.build( + { + '__init__.py': "# Pretend this is a package.", + 'README.txt': 'Info about this package', + }, + sources, + ) + + destination = self.mkdtemp() + + dist = Distribution({"packages": ["pkg"], "package_dir": {"pkg": sources}}) + # script_name need not exist, it just need to be initialized + dist.script_name = os.path.join(sources, "setup.py") + dist.command_obj["build"] = support.DummyCommand( + force=False, build_lib=destination + ) + dist.packages = ["pkg"] + dist.package_data = {"pkg": ["README.txt"]} + dist.package_dir = {"pkg": sources} + + cmd = build_py(dist) + cmd.compile = True + cmd.ensure_finalized() + assert cmd.package_data == dist.package_data + + cmd.run() + + # This makes sure the list of outputs includes byte-compiled + # files for Python modules but not for package data files + # (there shouldn't *be* byte-code files for those!). + assert len(cmd.get_outputs()) == 3 + pkgdest = os.path.join(destination, "pkg") + files = os.listdir(pkgdest) + pycache_dir = os.path.join(pkgdest, "__pycache__") + assert "__init__.py" in files + assert "README.txt" in files + if sys.dont_write_bytecode: + assert not os.path.exists(pycache_dir) + else: + pyc_files = os.listdir(pycache_dir) + assert f"__init__.{sys.implementation.cache_tag}.pyc" in pyc_files + + def test_empty_package_dir(self): + # See bugs #1668596/#1720897 + sources = self.mkdtemp() + jaraco.path.build({'__init__.py': '', 'doc': {'testfile': ''}}, sources) + + os.chdir(sources) + dist = Distribution({ + "packages": ["pkg"], + "package_dir": {"pkg": ""}, + "package_data": {"pkg": ["doc/*"]}, + }) + # script_name need not exist, it just need to be initialized + dist.script_name = os.path.join(sources, "setup.py") + dist.script_args = ["build"] + dist.parse_command_line() + + try: + dist.run_commands() + except DistutilsFileError: + self.fail("failed package_data test when package_dir is ''") + + @pytest.mark.skipif('sys.dont_write_bytecode') + def test_byte_compile(self): + project_dir, dist = self.create_dist(py_modules=['boiledeggs']) + os.chdir(project_dir) + self.write_file('boiledeggs.py', 'import antigravity') + cmd = build_py(dist) + cmd.compile = True + cmd.build_lib = 'here' + cmd.finalize_options() + cmd.run() + + found = os.listdir(cmd.build_lib) + assert sorted(found) == ['__pycache__', 'boiledeggs.py'] + found = os.listdir(os.path.join(cmd.build_lib, '__pycache__')) + assert found == [f'boiledeggs.{sys.implementation.cache_tag}.pyc'] + + @pytest.mark.skipif('sys.dont_write_bytecode') + def test_byte_compile_optimized(self): + project_dir, dist = self.create_dist(py_modules=['boiledeggs']) + os.chdir(project_dir) + self.write_file('boiledeggs.py', 'import antigravity') + cmd = build_py(dist) + cmd.compile = False + cmd.optimize = 1 + cmd.build_lib = 'here' + cmd.finalize_options() + cmd.run() + + found = os.listdir(cmd.build_lib) + assert sorted(found) == ['__pycache__', 'boiledeggs.py'] + found = os.listdir(os.path.join(cmd.build_lib, '__pycache__')) + expect = f'boiledeggs.{sys.implementation.cache_tag}.opt-1.pyc' + assert sorted(found) == [expect] + + def test_dir_in_package_data(self): + """ + A directory in package_data should not be added to the filelist. + """ + # See bug 19286 + sources = self.mkdtemp() + jaraco.path.build( + { + 'pkg': { + '__init__.py': '', + 'doc': { + 'testfile': '', + # create a directory that could be incorrectly detected as a file + 'otherdir': {}, + }, + } + }, + sources, + ) + + os.chdir(sources) + dist = Distribution({"packages": ["pkg"], "package_data": {"pkg": ["doc/*"]}}) + # script_name need not exist, it just need to be initialized + dist.script_name = os.path.join(sources, "setup.py") + dist.script_args = ["build"] + dist.parse_command_line() + + try: + dist.run_commands() + except DistutilsFileError: + self.fail("failed package_data when data dir includes a dir") + + def test_dont_write_bytecode(self, caplog): + # makes sure byte_compile is not used + dist = self.create_dist()[1] + cmd = build_py(dist) + cmd.compile = True + cmd.optimize = 1 + + old_dont_write_bytecode = sys.dont_write_bytecode + sys.dont_write_bytecode = True + try: + cmd.byte_compile([]) + finally: + sys.dont_write_bytecode = old_dont_write_bytecode + + assert 'byte-compiling is disabled' in caplog.records[0].message + + def test_namespace_package_does_not_warn(self, caplog): + """ + Originally distutils implementation did not account for PEP 420 + and included warns for package directories that did not contain + ``__init__.py`` files. + After the acceptance of PEP 420, these warnings don't make more sense + so we want to ensure there are not displayed to not confuse the users. + """ + # Create a fake project structure with a package namespace: + tmp = self.mkdtemp() + jaraco.path.build({'ns': {'pkg': {'module.py': ''}}}, tmp) + os.chdir(tmp) + + # Configure the package: + attrs = { + "name": "ns.pkg", + "packages": ["ns", "ns.pkg"], + "script_name": "setup.py", + } + dist = Distribution(attrs) + + # Run code paths that would trigger the trap: + cmd = dist.get_command_obj("build_py") + cmd.finalize_options() + modules = cmd.find_all_modules() + assert len(modules) == 1 + module_path = modules[0][-1] + assert module_path.replace(os.sep, "/") == "ns/pkg/module.py" + + cmd.run() + + assert not any( + "package init file" in msg and "not found" in msg for msg in caplog.messages + ) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_build_scripts.py b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_build_scripts.py new file mode 100644 index 0000000000000000000000000000000000000000..3582f691ef578a419555c6ffbba6a619310517a6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_build_scripts.py @@ -0,0 +1,96 @@ +"""Tests for distutils.command.build_scripts.""" + +import os +import textwrap +from distutils import sysconfig +from distutils.command.build_scripts import build_scripts +from distutils.core import Distribution +from distutils.tests import support + +import jaraco.path + + +class TestBuildScripts(support.TempdirManager): + def test_default_settings(self): + cmd = self.get_build_scripts_cmd("/foo/bar", []) + assert not cmd.force + assert cmd.build_dir is None + + cmd.finalize_options() + + assert cmd.force + assert cmd.build_dir == "/foo/bar" + + def test_build(self): + source = self.mkdtemp() + target = self.mkdtemp() + expected = self.write_sample_scripts(source) + + cmd = self.get_build_scripts_cmd( + target, [os.path.join(source, fn) for fn in expected] + ) + cmd.finalize_options() + cmd.run() + + built = os.listdir(target) + for name in expected: + assert name in built + + def get_build_scripts_cmd(self, target, scripts): + import sys + + dist = Distribution() + dist.scripts = scripts + dist.command_obj["build"] = support.DummyCommand( + build_scripts=target, force=True, executable=sys.executable + ) + return build_scripts(dist) + + @staticmethod + def write_sample_scripts(dir): + spec = { + 'script1.py': textwrap.dedent(""" + #! /usr/bin/env python2.3 + # bogus script w/ Python sh-bang + pass + """).lstrip(), + 'script2.py': textwrap.dedent(""" + #!/usr/bin/python + # bogus script w/ Python sh-bang + pass + """).lstrip(), + 'shell.sh': textwrap.dedent(""" + #!/bin/sh + # bogus shell script w/ sh-bang + exit 0 + """).lstrip(), + } + jaraco.path.build(spec, dir) + return list(spec) + + def test_version_int(self): + source = self.mkdtemp() + target = self.mkdtemp() + expected = self.write_sample_scripts(source) + + cmd = self.get_build_scripts_cmd( + target, [os.path.join(source, fn) for fn in expected] + ) + cmd.finalize_options() + + # https://bugs.python.org/issue4524 + # + # On linux-g++-32 with command line `./configure --enable-ipv6 + # --with-suffix=3`, python is compiled okay but the build scripts + # failed when writing the name of the executable + old = sysconfig.get_config_vars().get('VERSION') + sysconfig._config_vars['VERSION'] = 4 + try: + cmd.run() + finally: + if old is not None: + sysconfig._config_vars['VERSION'] = old + + built = os.listdir(target) + for name in expected: + assert name in built diff --git a/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_check.py b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_check.py new file mode 100644 index 0000000000000000000000000000000000000000..b672b1f972b46f399eb5b2ef263da2548d52ef89 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_check.py @@ -0,0 +1,194 @@ +"""Tests for distutils.command.check.""" + +import os +import textwrap +from distutils.command.check import check +from distutils.errors import DistutilsSetupError +from distutils.tests import support + +import pytest + +try: + import pygments +except ImportError: + pygments = None + + +HERE = os.path.dirname(__file__) + + +@support.combine_markers +class TestCheck(support.TempdirManager): + def _run(self, metadata=None, cwd=None, **options): + if metadata is None: + metadata = {} + if cwd is not None: + old_dir = os.getcwd() + os.chdir(cwd) + pkg_info, dist = self.create_dist(**metadata) + cmd = check(dist) + cmd.initialize_options() + for name, value in options.items(): + setattr(cmd, name, value) + cmd.ensure_finalized() + cmd.run() + if cwd is not None: + os.chdir(old_dir) + return cmd + + def test_check_metadata(self): + # let's run the command with no metadata at all + # by default, check is checking the metadata + # should have some warnings + cmd = self._run() + assert cmd._warnings == 1 + + # now let's add the required fields + # and run it again, to make sure we don't get + # any warning anymore + metadata = { + 'url': 'xxx', + 'author': 'xxx', + 'author_email': 'xxx', + 'name': 'xxx', + 'version': 'xxx', + } + cmd = self._run(metadata) + assert cmd._warnings == 0 + + # now with the strict mode, we should + # get an error if there are missing metadata + with pytest.raises(DistutilsSetupError): + self._run({}, **{'strict': 1}) + + # and of course, no error when all metadata are present + cmd = self._run(metadata, strict=True) + assert cmd._warnings == 0 + + # now a test with non-ASCII characters + metadata = { + 'url': 'xxx', + 'author': '\u00c9ric', + 'author_email': 'xxx', + 'name': 'xxx', + 'version': 'xxx', + 'description': 'Something about esszet \u00df', + 'long_description': 'More things about esszet \u00df', + } + cmd = self._run(metadata) + assert cmd._warnings == 0 + + def test_check_author_maintainer(self): + for kind in ("author", "maintainer"): + # ensure no warning when author_email or maintainer_email is given + # (the spec allows these fields to take the form "Name ") + metadata = { + 'url': 'xxx', + kind + '_email': 'Name ', + 'name': 'xxx', + 'version': 'xxx', + } + cmd = self._run(metadata) + assert cmd._warnings == 0 + + # the check should not warn if only email is given + metadata[kind + '_email'] = 'name@email.com' + cmd = self._run(metadata) + assert cmd._warnings == 0 + + # the check should not warn if only the name is given + metadata[kind] = "Name" + del metadata[kind + '_email'] + cmd = self._run(metadata) + assert cmd._warnings == 0 + + def test_check_document(self): + pytest.importorskip('docutils') + pkg_info, dist = self.create_dist() + cmd = check(dist) + + # let's see if it detects broken rest + broken_rest = 'title\n===\n\ntest' + msgs = cmd._check_rst_data(broken_rest) + assert len(msgs) == 1 + + # and non-broken rest + rest = 'title\n=====\n\ntest' + msgs = cmd._check_rst_data(rest) + assert len(msgs) == 0 + + def test_check_restructuredtext(self): + pytest.importorskip('docutils') + # let's see if it detects broken rest in long_description + broken_rest = 'title\n===\n\ntest' + pkg_info, dist = self.create_dist(long_description=broken_rest) + cmd = check(dist) + cmd.check_restructuredtext() + assert cmd._warnings == 1 + + # let's see if we have an error with strict=True + metadata = { + 'url': 'xxx', + 'author': 'xxx', + 'author_email': 'xxx', + 'name': 'xxx', + 'version': 'xxx', + 'long_description': broken_rest, + } + with pytest.raises(DistutilsSetupError): + self._run(metadata, **{'strict': 1, 'restructuredtext': 1}) + + # and non-broken rest, including a non-ASCII character to test #12114 + metadata['long_description'] = 'title\n=====\n\ntest \u00df' + cmd = self._run(metadata, strict=True, restructuredtext=True) + assert cmd._warnings == 0 + + # check that includes work to test #31292 + metadata['long_description'] = 'title\n=====\n\n.. include:: includetest.rst' + cmd = self._run(metadata, cwd=HERE, strict=True, restructuredtext=True) + assert cmd._warnings == 0 + + def test_check_restructuredtext_with_syntax_highlight(self): + pytest.importorskip('docutils') + # Don't fail if there is a `code` or `code-block` directive + + example_rst_docs = [ + textwrap.dedent( + """\ + Here's some code: + + .. code:: python + + def foo(): + pass + """ + ), + textwrap.dedent( + """\ + Here's some code: + + .. code-block:: python + + def foo(): + pass + """ + ), + ] + + for rest_with_code in example_rst_docs: + pkg_info, dist = self.create_dist(long_description=rest_with_code) + cmd = check(dist) + cmd.check_restructuredtext() + msgs = cmd._check_rst_data(rest_with_code) + if pygments is not None: + assert len(msgs) == 0 + else: + assert len(msgs) == 1 + assert ( + str(msgs[0][1]) + == 'Cannot analyze code. Pygments package not found.' + ) + + def test_check_all(self): + with pytest.raises(DistutilsSetupError): + self._run({}, **{'strict': 1, 'restructuredtext': 1}) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_clean.py b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_clean.py new file mode 100644 index 0000000000000000000000000000000000000000..cc78f30f34b323845b977b9147c2153390774bd3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_clean.py @@ -0,0 +1,45 @@ +"""Tests for distutils.command.clean.""" + +import os +from distutils.command.clean import clean +from distutils.tests import support + + +class TestClean(support.TempdirManager): + def test_simple_run(self): + pkg_dir, dist = self.create_dist() + cmd = clean(dist) + + # let's add some elements clean should remove + dirs = [ + (d, os.path.join(pkg_dir, d)) + for d in ( + 'build_temp', + 'build_lib', + 'bdist_base', + 'build_scripts', + 'build_base', + ) + ] + + for name, path in dirs: + os.mkdir(path) + setattr(cmd, name, path) + if name == 'build_base': + continue + for f in ('one', 'two', 'three'): + self.write_file(os.path.join(path, f)) + + # let's run the command + cmd.all = 1 + cmd.ensure_finalized() + cmd.run() + + # make sure the files where removed + for _name, path in dirs: + assert not os.path.exists(path), f'{path} was not removed' + + # let's run the command again (should spit warnings but succeed) + cmd.all = 1 + cmd.ensure_finalized() + cmd.run() diff --git a/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_cmd.py b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_cmd.py new file mode 100644 index 0000000000000000000000000000000000000000..76e8f5989b3b102a32239436ff3b65f26e09e029 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_cmd.py @@ -0,0 +1,107 @@ +"""Tests for distutils.cmd.""" + +import os +from distutils import debug +from distutils.cmd import Command +from distutils.dist import Distribution +from distutils.errors import DistutilsOptionError + +import pytest + + +class MyCmd(Command): + def initialize_options(self): + pass + + +@pytest.fixture +def cmd(request): + return MyCmd(Distribution()) + + +class TestCommand: + def test_ensure_string_list(self, cmd): + cmd.not_string_list = ['one', 2, 'three'] + cmd.yes_string_list = ['one', 'two', 'three'] + cmd.not_string_list2 = object() + cmd.yes_string_list2 = 'ok' + cmd.ensure_string_list('yes_string_list') + cmd.ensure_string_list('yes_string_list2') + + with pytest.raises(DistutilsOptionError): + cmd.ensure_string_list('not_string_list') + + with pytest.raises(DistutilsOptionError): + cmd.ensure_string_list('not_string_list2') + + cmd.option1 = 'ok,dok' + cmd.ensure_string_list('option1') + assert cmd.option1 == ['ok', 'dok'] + + cmd.option2 = ['xxx', 'www'] + cmd.ensure_string_list('option2') + + cmd.option3 = ['ok', 2] + with pytest.raises(DistutilsOptionError): + cmd.ensure_string_list('option3') + + def test_make_file(self, cmd): + # making sure it raises when infiles is not a string or a list/tuple + with pytest.raises(TypeError): + cmd.make_file(infiles=True, outfile='', func='func', args=()) + + # making sure execute gets called properly + def _execute(func, args, exec_msg, level): + assert exec_msg == 'generating out from in' + + cmd.force = True + cmd.execute = _execute + cmd.make_file(infiles='in', outfile='out', func='func', args=()) + + def test_dump_options(self, cmd): + msgs = [] + + def _announce(msg, level): + msgs.append(msg) + + cmd.announce = _announce + cmd.option1 = 1 + cmd.option2 = 1 + cmd.user_options = [('option1', '', ''), ('option2', '', '')] + cmd.dump_options() + + wanted = ["command options for 'MyCmd':", ' option1 = 1', ' option2 = 1'] + assert msgs == wanted + + def test_ensure_string(self, cmd): + cmd.option1 = 'ok' + cmd.ensure_string('option1') + + cmd.option2 = None + cmd.ensure_string('option2', 'xxx') + assert hasattr(cmd, 'option2') + + cmd.option3 = 1 + with pytest.raises(DistutilsOptionError): + cmd.ensure_string('option3') + + def test_ensure_filename(self, cmd): + cmd.option1 = __file__ + cmd.ensure_filename('option1') + cmd.option2 = 'xxx' + with pytest.raises(DistutilsOptionError): + cmd.ensure_filename('option2') + + def test_ensure_dirname(self, cmd): + cmd.option1 = os.path.dirname(__file__) or os.curdir + cmd.ensure_dirname('option1') + cmd.option2 = 'xxx' + with pytest.raises(DistutilsOptionError): + cmd.ensure_dirname('option2') + + def test_debug_print(self, cmd, capsys, monkeypatch): + cmd.debug_print('xxx') + assert capsys.readouterr().out == '' + monkeypatch.setattr(debug, 'DEBUG', True) + cmd.debug_print('xxx') + assert capsys.readouterr().out == 'xxx\n' diff --git a/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_config_cmd.py b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_config_cmd.py new file mode 100644 index 0000000000000000000000000000000000000000..ebee2ef93f0bc9d422984e2e4872665b1be3a1de --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_config_cmd.py @@ -0,0 +1,87 @@ +"""Tests for distutils.command.config.""" + +import os +import sys +from distutils._log import log +from distutils.command.config import config, dump_file +from distutils.tests import missing_compiler_executable, support + +import more_itertools +import path +import pytest + + +@pytest.fixture(autouse=True) +def info_log(request, monkeypatch): + self = request.instance + self._logs = [] + monkeypatch.setattr(log, 'info', self._info) + + +@support.combine_markers +class TestConfig(support.TempdirManager): + def _info(self, msg, *args): + for line in msg.splitlines(): + self._logs.append(line) + + def test_dump_file(self): + this_file = path.Path(__file__).with_suffix('.py') + with this_file.open(encoding='utf-8') as f: + numlines = more_itertools.ilen(f) + + dump_file(this_file, 'I am the header') + assert len(self._logs) == numlines + 1 + + @pytest.mark.skipif('platform.system() == "Windows"') + def test_search_cpp(self): + cmd = missing_compiler_executable(['preprocessor']) + if cmd is not None: + self.skipTest(f'The {cmd!r} command is not found') + pkg_dir, dist = self.create_dist() + cmd = config(dist) + cmd._check_compiler() + compiler = cmd.compiler + if sys.platform[:3] == "aix" and "xlc" in compiler.preprocessor[0].lower(): + self.skipTest( + 'xlc: The -E option overrides the -P, -o, and -qsyntaxonly options' + ) + + # simple pattern searches + match = cmd.search_cpp(pattern='xxx', body='/* xxx */') + assert match == 0 + + match = cmd.search_cpp(pattern='_configtest', body='/* xxx */') + assert match == 1 + + def test_finalize_options(self): + # finalize_options does a bit of transformation + # on options + pkg_dir, dist = self.create_dist() + cmd = config(dist) + cmd.include_dirs = f'one{os.pathsep}two' + cmd.libraries = 'one' + cmd.library_dirs = f'three{os.pathsep}four' + cmd.ensure_finalized() + + assert cmd.include_dirs == ['one', 'two'] + assert cmd.libraries == ['one'] + assert cmd.library_dirs == ['three', 'four'] + + def test_clean(self): + # _clean removes files + tmp_dir = self.mkdtemp() + f1 = os.path.join(tmp_dir, 'one') + f2 = os.path.join(tmp_dir, 'two') + + self.write_file(f1, 'xxx') + self.write_file(f2, 'xxx') + + for f in (f1, f2): + assert os.path.exists(f) + + pkg_dir, dist = self.create_dist() + cmd = config(dist) + cmd._clean(f1, f2) + + for f in (f1, f2): + assert not os.path.exists(f) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_core.py b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_core.py new file mode 100644 index 0000000000000000000000000000000000000000..bad3fb7e8318d3ee73ecabe20ed98c279f606a77 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_core.py @@ -0,0 +1,130 @@ +"""Tests for distutils.core.""" + +import distutils.core +import io +import os +import sys +from distutils.dist import Distribution + +import pytest + +# setup script that uses __file__ +setup_using___file__ = """\ + +__file__ + +from distutils.core import setup +setup() +""" + +setup_prints_cwd = """\ + +import os +print(os.getcwd()) + +from distutils.core import setup +setup() +""" + +setup_does_nothing = """\ +from distutils.core import setup +setup() +""" + + +setup_defines_subclass = """\ +from distutils.core import setup +from distutils.command.install import install as _install + +class install(_install): + sub_commands = _install.sub_commands + ['cmd'] + +setup(cmdclass={'install': install}) +""" + +setup_within_if_main = """\ +from distutils.core import setup + +def main(): + return setup(name="setup_within_if_main") + +if __name__ == "__main__": + main() +""" + + +@pytest.fixture(autouse=True) +def save_stdout(monkeypatch): + monkeypatch.setattr(sys, 'stdout', sys.stdout) + + +@pytest.fixture +def temp_file(tmp_path): + return tmp_path / 'file' + + +@pytest.mark.usefixtures('save_env') +@pytest.mark.usefixtures('save_argv') +class TestCore: + def test_run_setup_provides_file(self, temp_file): + # Make sure the script can use __file__; if that's missing, the test + # setup.py script will raise NameError. + temp_file.write_text(setup_using___file__, encoding='utf-8') + distutils.core.run_setup(temp_file) + + def test_run_setup_preserves_sys_argv(self, temp_file): + # Make sure run_setup does not clobber sys.argv + argv_copy = sys.argv.copy() + temp_file.write_text(setup_does_nothing, encoding='utf-8') + distutils.core.run_setup(temp_file) + assert sys.argv == argv_copy + + def test_run_setup_defines_subclass(self, temp_file): + # Make sure the script can use __file__; if that's missing, the test + # setup.py script will raise NameError. + temp_file.write_text(setup_defines_subclass, encoding='utf-8') + dist = distutils.core.run_setup(temp_file) + install = dist.get_command_obj('install') + assert 'cmd' in install.sub_commands + + def test_run_setup_uses_current_dir(self, tmp_path): + """ + Test that the setup script is run with the current directory + as its own current directory. + """ + sys.stdout = io.StringIO() + cwd = os.getcwd() + + # Create a directory and write the setup.py file there: + setup_py = tmp_path / 'setup.py' + setup_py.write_text(setup_prints_cwd, encoding='utf-8') + distutils.core.run_setup(setup_py) + + output = sys.stdout.getvalue() + if output.endswith("\n"): + output = output[:-1] + assert cwd == output + + def test_run_setup_within_if_main(self, temp_file): + temp_file.write_text(setup_within_if_main, encoding='utf-8') + dist = distutils.core.run_setup(temp_file, stop_after="config") + assert isinstance(dist, Distribution) + assert dist.get_name() == "setup_within_if_main" + + def test_run_commands(self, temp_file): + sys.argv = ['setup.py', 'build'] + temp_file.write_text(setup_within_if_main, encoding='utf-8') + dist = distutils.core.run_setup(temp_file, stop_after="commandline") + assert 'build' not in dist.have_run + distutils.core.run_commands(dist) + assert 'build' in dist.have_run + + def test_debug_mode(self, capsys, monkeypatch): + # this covers the code called when DEBUG is set + sys.argv = ['setup.py', '--name'] + distutils.core.setup(name='bar') + assert capsys.readouterr().out == 'bar\n' + monkeypatch.setattr(distutils.core, 'DEBUG', True) + distutils.core.setup(name='bar') + wanted = "options (after parsing config files):\n" + assert capsys.readouterr().out.startswith(wanted) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_dir_util.py b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_dir_util.py new file mode 100644 index 0000000000000000000000000000000000000000..326cb346145ec7e3a1dd0384c33d4125131feaae --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_dir_util.py @@ -0,0 +1,139 @@ +"""Tests for distutils.dir_util.""" + +import os +import pathlib +import stat +import sys +import unittest.mock as mock +from distutils import dir_util, errors +from distutils.dir_util import ( + copy_tree, + create_tree, + ensure_relative, + mkpath, + remove_tree, +) +from distutils.tests import support + +import jaraco.path +import path +import pytest + + +@pytest.fixture(autouse=True) +def stuff(request, monkeypatch, distutils_managed_tempdir): + self = request.instance + tmp_dir = self.mkdtemp() + self.root_target = os.path.join(tmp_dir, 'deep') + self.target = os.path.join(self.root_target, 'here') + self.target2 = os.path.join(tmp_dir, 'deep2') + + +class TestDirUtil(support.TempdirManager): + def test_mkpath_remove_tree_verbosity(self, caplog): + mkpath(self.target, verbose=False) + assert not caplog.records + remove_tree(self.root_target, verbose=False) + + mkpath(self.target, verbose=True) + wanted = [f'creating {self.target}'] + assert caplog.messages == wanted + caplog.clear() + + remove_tree(self.root_target, verbose=True) + wanted = [f"removing '{self.root_target}' (and everything under it)"] + assert caplog.messages == wanted + + @pytest.mark.skipif("platform.system() == 'Windows'") + def test_mkpath_with_custom_mode(self): + # Get and set the current umask value for testing mode bits. + umask = os.umask(0o002) + os.umask(umask) + mkpath(self.target, 0o700) + assert stat.S_IMODE(os.stat(self.target).st_mode) == 0o700 & ~umask + mkpath(self.target2, 0o555) + assert stat.S_IMODE(os.stat(self.target2).st_mode) == 0o555 & ~umask + + def test_create_tree_verbosity(self, caplog): + create_tree(self.root_target, ['one', 'two', 'three'], verbose=False) + assert caplog.messages == [] + remove_tree(self.root_target, verbose=False) + + wanted = [f'creating {self.root_target}'] + create_tree(self.root_target, ['one', 'two', 'three'], verbose=True) + assert caplog.messages == wanted + + remove_tree(self.root_target, verbose=False) + + def test_copy_tree_verbosity(self, caplog): + mkpath(self.target, verbose=False) + + copy_tree(self.target, self.target2, verbose=False) + assert caplog.messages == [] + + remove_tree(self.root_target, verbose=False) + + mkpath(self.target, verbose=False) + a_file = path.Path(self.target) / 'ok.txt' + jaraco.path.build({'ok.txt': 'some content'}, self.target) + + wanted = [f'copying {a_file} -> {self.target2}'] + copy_tree(self.target, self.target2, verbose=True) + assert caplog.messages == wanted + + remove_tree(self.root_target, verbose=False) + remove_tree(self.target2, verbose=False) + + def test_copy_tree_skips_nfs_temp_files(self): + mkpath(self.target, verbose=False) + + jaraco.path.build({'ok.txt': 'some content', '.nfs123abc': ''}, self.target) + + copy_tree(self.target, self.target2) + assert os.listdir(self.target2) == ['ok.txt'] + + remove_tree(self.root_target, verbose=False) + remove_tree(self.target2, verbose=False) + + def test_ensure_relative(self): + if os.sep == '/': + assert ensure_relative('/home/foo') == 'home/foo' + assert ensure_relative('some/path') == 'some/path' + else: # \\ + assert ensure_relative('c:\\home\\foo') == 'c:home\\foo' + assert ensure_relative('home\\foo') == 'home\\foo' + + def test_copy_tree_exception_in_listdir(self): + """ + An exception in listdir should raise a DistutilsFileError + """ + with ( + mock.patch("os.listdir", side_effect=OSError()), + pytest.raises(errors.DistutilsFileError), + ): + src = self.tempdirs[-1] + dir_util.copy_tree(src, None) + + def test_mkpath_exception_uncached(self, monkeypatch, tmp_path): + """ + Caching should not remember failed attempts. + + pypa/distutils#304 + """ + + class FailPath(pathlib.Path): + def mkdir(self, *args, **kwargs): + raise OSError("Failed to create directory") + + if sys.version_info < (3, 12): + _flavour = pathlib.Path()._flavour + + target = tmp_path / 'foodir' + + with pytest.raises(errors.DistutilsFileError): + mkpath(FailPath(target)) + + assert not target.exists() + + mkpath(target) + assert target.exists() diff --git a/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_dist.py b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_dist.py new file mode 100644 index 0000000000000000000000000000000000000000..2c5beebe64eb9d747088cf117082a546330b29f3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_dist.py @@ -0,0 +1,552 @@ +"""Tests for distutils.dist.""" + +import email +import email.generator +import email.policy +import functools +import io +import os +import sys +import textwrap +import unittest.mock as mock +import warnings +from distutils.cmd import Command +from distutils.dist import Distribution, fix_help_options +from distutils.tests import support +from typing import ClassVar + +import jaraco.path +import pytest + +pydistutils_cfg = '.' * (os.name == 'posix') + 'pydistutils.cfg' + + +class test_dist(Command): + """Sample distutils extension command.""" + + user_options: ClassVar[list[tuple[str, str, str]]] = [ + ("sample-option=", "S", "help text"), + ] + + def initialize_options(self): + self.sample_option = None + + +class TestDistribution(Distribution): + """Distribution subclasses that avoids the default search for + configuration files. + + The ._config_files attribute must be set before + .parse_config_files() is called. + """ + + def find_config_files(self): + return self._config_files + + +@pytest.fixture +def clear_argv(): + del sys.argv[1:] + + +@support.combine_markers +@pytest.mark.usefixtures('save_env') +@pytest.mark.usefixtures('save_argv') +class TestDistributionBehavior(support.TempdirManager): + def create_distribution(self, configfiles=()): + d = TestDistribution() + d._config_files = configfiles + d.parse_config_files() + d.parse_command_line() + return d + + def test_command_packages_unspecified(self, clear_argv): + sys.argv.append("build") + d = self.create_distribution() + assert d.get_command_packages() == ["distutils.command"] + + def test_command_packages_cmdline(self, clear_argv): + from distutils.tests.test_dist import test_dist + + sys.argv.extend([ + "--command-packages", + "foo.bar,distutils.tests", + "test_dist", + "-Ssometext", + ]) + d = self.create_distribution() + # let's actually try to load our test command: + assert d.get_command_packages() == [ + "distutils.command", + "foo.bar", + "distutils.tests", + ] + cmd = d.get_command_obj("test_dist") + assert isinstance(cmd, test_dist) + assert cmd.sample_option == "sometext" + + @pytest.mark.skipif( + 'distutils' not in Distribution.parse_config_files.__module__, + reason='Cannot test when virtualenv has monkey-patched Distribution', + ) + def test_venv_install_options(self, tmp_path, clear_argv): + sys.argv.append("install") + file = str(tmp_path / 'file') + + fakepath = '/somedir' + + jaraco.path.build({ + file: f""" + [install] + install-base = {fakepath} + install-platbase = {fakepath} + install-lib = {fakepath} + install-platlib = {fakepath} + install-purelib = {fakepath} + install-headers = {fakepath} + install-scripts = {fakepath} + install-data = {fakepath} + prefix = {fakepath} + exec-prefix = {fakepath} + home = {fakepath} + user = {fakepath} + root = {fakepath} + """, + }) + + # Base case: Not in a Virtual Environment + with mock.patch.multiple(sys, prefix='/a', base_prefix='/a'): + d = self.create_distribution([file]) + + option_tuple = (file, fakepath) + + result_dict = { + 'install_base': option_tuple, + 'install_platbase': option_tuple, + 'install_lib': option_tuple, + 'install_platlib': option_tuple, + 'install_purelib': option_tuple, + 'install_headers': option_tuple, + 'install_scripts': option_tuple, + 'install_data': option_tuple, + 'prefix': option_tuple, + 'exec_prefix': option_tuple, + 'home': option_tuple, + 'user': option_tuple, + 'root': option_tuple, + } + + assert sorted(d.command_options.get('install').keys()) == sorted( + result_dict.keys() + ) + + for key, value in d.command_options.get('install').items(): + assert value == result_dict[key] + + # Test case: In a Virtual Environment + with mock.patch.multiple(sys, prefix='/a', base_prefix='/b'): + d = self.create_distribution([file]) + + for key in result_dict.keys(): + assert key not in d.command_options.get('install', {}) + + def test_command_packages_configfile(self, tmp_path, clear_argv): + sys.argv.append("build") + file = str(tmp_path / "file") + jaraco.path.build({ + file: """ + [global] + command_packages = foo.bar, splat + """, + }) + + d = self.create_distribution([file]) + assert d.get_command_packages() == ["distutils.command", "foo.bar", "splat"] + + # ensure command line overrides config: + sys.argv[1:] = ["--command-packages", "spork", "build"] + d = self.create_distribution([file]) + assert d.get_command_packages() == ["distutils.command", "spork"] + + # Setting --command-packages to '' should cause the default to + # be used even if a config file specified something else: + sys.argv[1:] = ["--command-packages", "", "build"] + d = self.create_distribution([file]) + assert d.get_command_packages() == ["distutils.command"] + + def test_empty_options(self, request): + # an empty options dictionary should not stay in the + # list of attributes + + # catching warnings + warns = [] + + def _warn(msg): + warns.append(msg) + + request.addfinalizer( + functools.partial(setattr, warnings, 'warn', warnings.warn) + ) + warnings.warn = _warn + dist = Distribution( + attrs={ + 'author': 'xxx', + 'name': 'xxx', + 'version': 'xxx', + 'url': 'xxxx', + 'options': {}, + } + ) + + assert len(warns) == 0 + assert 'options' not in dir(dist) + + def test_finalize_options(self): + attrs = {'keywords': 'one,two', 'platforms': 'one,two'} + + dist = Distribution(attrs=attrs) + dist.finalize_options() + + # finalize_option splits platforms and keywords + assert dist.metadata.platforms == ['one', 'two'] + assert dist.metadata.keywords == ['one', 'two'] + + attrs = {'keywords': 'foo bar', 'platforms': 'foo bar'} + dist = Distribution(attrs=attrs) + dist.finalize_options() + assert dist.metadata.platforms == ['foo bar'] + assert dist.metadata.keywords == ['foo bar'] + + def test_get_command_packages(self): + dist = Distribution() + assert dist.command_packages is None + cmds = dist.get_command_packages() + assert cmds == ['distutils.command'] + assert dist.command_packages == ['distutils.command'] + + dist.command_packages = 'one,two' + cmds = dist.get_command_packages() + assert cmds == ['distutils.command', 'one', 'two'] + + def test_announce(self): + # make sure the level is known + dist = Distribution() + with pytest.raises(TypeError): + dist.announce('ok', level='ok2') + + def test_find_config_files_disable(self, temp_home): + # Ticket #1180: Allow user to disable their home config file. + jaraco.path.build({pydistutils_cfg: '[distutils]\n'}, temp_home) + + d = Distribution() + all_files = d.find_config_files() + + d = Distribution(attrs={'script_args': ['--no-user-cfg']}) + files = d.find_config_files() + + # make sure --no-user-cfg disables the user cfg file + assert len(all_files) - 1 == len(files) + + def test_script_args_list_coercion(self): + d = Distribution(attrs={'script_args': ('build', '--no-user-cfg')}) + + # make sure script_args is a list even if it started as a different iterable + assert d.script_args == ['build', '--no-user-cfg'] + + @pytest.mark.skipif( + 'platform.system() == "Windows"', + reason='Windows does not honor chmod 000', + ) + def test_find_config_files_permission_error(self, fake_home): + """ + Finding config files should not fail when directory is inaccessible. + """ + fake_home.joinpath(pydistutils_cfg).write_text('', encoding='utf-8') + fake_home.chmod(0o000) + Distribution().find_config_files() + + +@pytest.mark.usefixtures('save_env') +@pytest.mark.usefixtures('save_argv') +class TestMetadata(support.TempdirManager): + def format_metadata(self, dist): + sio = io.StringIO() + dist.metadata.write_pkg_file(sio) + return sio.getvalue() + + def test_simple_metadata(self): + attrs = {"name": "package", "version": "1.0"} + dist = Distribution(attrs) + meta = self.format_metadata(dist) + assert "Metadata-Version: 1.0" in meta + assert "provides:" not in meta.lower() + assert "requires:" not in meta.lower() + assert "obsoletes:" not in meta.lower() + + def test_provides(self): + attrs = { + "name": "package", + "version": "1.0", + "provides": ["package", "package.sub"], + } + dist = Distribution(attrs) + assert dist.metadata.get_provides() == ["package", "package.sub"] + assert dist.get_provides() == ["package", "package.sub"] + meta = self.format_metadata(dist) + assert "Metadata-Version: 1.1" in meta + assert "requires:" not in meta.lower() + assert "obsoletes:" not in meta.lower() + + def test_provides_illegal(self): + with pytest.raises(ValueError): + Distribution( + {"name": "package", "version": "1.0", "provides": ["my.pkg (splat)"]}, + ) + + def test_requires(self): + attrs = { + "name": "package", + "version": "1.0", + "requires": ["other", "another (==1.0)"], + } + dist = Distribution(attrs) + assert dist.metadata.get_requires() == ["other", "another (==1.0)"] + assert dist.get_requires() == ["other", "another (==1.0)"] + meta = self.format_metadata(dist) + assert "Metadata-Version: 1.1" in meta + assert "provides:" not in meta.lower() + assert "Requires: other" in meta + assert "Requires: another (==1.0)" in meta + assert "obsoletes:" not in meta.lower() + + def test_requires_illegal(self): + with pytest.raises(ValueError): + Distribution( + {"name": "package", "version": "1.0", "requires": ["my.pkg (splat)"]}, + ) + + def test_requires_to_list(self): + attrs = {"name": "package", "requires": iter(["other"])} + dist = Distribution(attrs) + assert isinstance(dist.metadata.requires, list) + + def test_obsoletes(self): + attrs = { + "name": "package", + "version": "1.0", + "obsoletes": ["other", "another (<1.0)"], + } + dist = Distribution(attrs) + assert dist.metadata.get_obsoletes() == ["other", "another (<1.0)"] + assert dist.get_obsoletes() == ["other", "another (<1.0)"] + meta = self.format_metadata(dist) + assert "Metadata-Version: 1.1" in meta + assert "provides:" not in meta.lower() + assert "requires:" not in meta.lower() + assert "Obsoletes: other" in meta + assert "Obsoletes: another (<1.0)" in meta + + def test_obsoletes_illegal(self): + with pytest.raises(ValueError): + Distribution( + {"name": "package", "version": "1.0", "obsoletes": ["my.pkg (splat)"]}, + ) + + def test_obsoletes_to_list(self): + attrs = {"name": "package", "obsoletes": iter(["other"])} + dist = Distribution(attrs) + assert isinstance(dist.metadata.obsoletes, list) + + def test_classifier(self): + attrs = { + 'name': 'Boa', + 'version': '3.0', + 'classifiers': ['Programming Language :: Python :: 3'], + } + dist = Distribution(attrs) + assert dist.get_classifiers() == ['Programming Language :: Python :: 3'] + meta = self.format_metadata(dist) + assert 'Metadata-Version: 1.1' in meta + + def test_classifier_invalid_type(self, caplog): + attrs = { + 'name': 'Boa', + 'version': '3.0', + 'classifiers': ('Programming Language :: Python :: 3',), + } + d = Distribution(attrs) + # should have warning about passing a non-list + assert 'should be a list' in caplog.messages[0] + # should be converted to a list + assert isinstance(d.metadata.classifiers, list) + assert d.metadata.classifiers == list(attrs['classifiers']) + + def test_keywords(self): + attrs = { + 'name': 'Monty', + 'version': '1.0', + 'keywords': ['spam', 'eggs', 'life of brian'], + } + dist = Distribution(attrs) + assert dist.get_keywords() == ['spam', 'eggs', 'life of brian'] + + def test_keywords_invalid_type(self, caplog): + attrs = { + 'name': 'Monty', + 'version': '1.0', + 'keywords': ('spam', 'eggs', 'life of brian'), + } + d = Distribution(attrs) + # should have warning about passing a non-list + assert 'should be a list' in caplog.messages[0] + # should be converted to a list + assert isinstance(d.metadata.keywords, list) + assert d.metadata.keywords == list(attrs['keywords']) + + def test_platforms(self): + attrs = { + 'name': 'Monty', + 'version': '1.0', + 'platforms': ['GNU/Linux', 'Some Evil Platform'], + } + dist = Distribution(attrs) + assert dist.get_platforms() == ['GNU/Linux', 'Some Evil Platform'] + + def test_platforms_invalid_types(self, caplog): + attrs = { + 'name': 'Monty', + 'version': '1.0', + 'platforms': ('GNU/Linux', 'Some Evil Platform'), + } + d = Distribution(attrs) + # should have warning about passing a non-list + assert 'should be a list' in caplog.messages[0] + # should be converted to a list + assert isinstance(d.metadata.platforms, list) + assert d.metadata.platforms == list(attrs['platforms']) + + def test_download_url(self): + attrs = { + 'name': 'Boa', + 'version': '3.0', + 'download_url': 'http://example.org/boa', + } + dist = Distribution(attrs) + meta = self.format_metadata(dist) + assert 'Metadata-Version: 1.1' in meta + + def test_long_description(self): + long_desc = textwrap.dedent( + """\ + example:: + We start here + and continue here + and end here.""" + ) + attrs = {"name": "package", "version": "1.0", "long_description": long_desc} + + dist = Distribution(attrs) + meta = self.format_metadata(dist) + meta = meta.replace('\n' + 8 * ' ', '\n') + assert long_desc in meta + + def test_custom_pydistutils(self, temp_home): + """ + pydistutils.cfg is found + """ + jaraco.path.build({pydistutils_cfg: ''}, temp_home) + config_path = temp_home / pydistutils_cfg + + assert str(config_path) in Distribution().find_config_files() + + def test_extra_pydistutils(self, monkeypatch, tmp_path): + jaraco.path.build({'overrides.cfg': ''}, tmp_path) + filename = tmp_path / 'overrides.cfg' + monkeypatch.setenv('DIST_EXTRA_CONFIG', str(filename)) + assert str(filename) in Distribution().find_config_files() + + def test_fix_help_options(self): + help_tuples = [('a', 'b', 'c', 'd'), (1, 2, 3, 4)] + fancy_options = fix_help_options(help_tuples) + assert fancy_options[0] == ('a', 'b', 'c') + assert fancy_options[1] == (1, 2, 3) + + def test_show_help(self, request, capsys): + # smoke test, just makes sure some help is displayed + dist = Distribution() + sys.argv = [] + dist.help = True + dist.script_name = 'setup.py' + dist.parse_command_line() + + output = [ + line for line in capsys.readouterr().out.split('\n') if line.strip() != '' + ] + assert output + + def test_read_metadata(self): + attrs = { + "name": "package", + "version": "1.0", + "long_description": "desc", + "description": "xxx", + "download_url": "http://example.com", + "keywords": ['one', 'two'], + "requires": ['foo'], + } + + dist = Distribution(attrs) + metadata = dist.metadata + + # write it then reloads it + PKG_INFO = io.StringIO() + metadata.write_pkg_file(PKG_INFO) + PKG_INFO.seek(0) + metadata.read_pkg_file(PKG_INFO) + + assert metadata.name == "package" + assert metadata.version == "1.0" + assert metadata.description == "xxx" + assert metadata.download_url == 'http://example.com' + assert metadata.keywords == ['one', 'two'] + assert metadata.platforms is None + assert metadata.obsoletes is None + assert metadata.requires == ['foo'] + + def test_round_trip_through_email_generator(self): + """ + In pypa/setuptools#4033, it was shown that once PKG-INFO is + re-generated using ``email.generator.Generator``, some control + characters might cause problems. + """ + # Given a PKG-INFO file ... + attrs = { + "name": "package", + "version": "1.0", + "long_description": "hello\x0b\nworld\n", + } + dist = Distribution(attrs) + metadata = dist.metadata + + with io.StringIO() as buffer: + metadata.write_pkg_file(buffer) + msg = buffer.getvalue() + + # ... when it is read and re-written using stdlib's email library, + orig = email.message_from_string(msg) + policy = email.policy.EmailPolicy( + utf8=True, + mangle_from_=False, + max_line_length=0, + ) + with io.StringIO() as buffer: + email.generator.Generator(buffer, policy=policy).flatten(orig) + + buffer.seek(0) + regen = email.message_from_file(buffer) + + # ... then it should be the same as the original + # (except for the specific line break characters) + orig_desc = set(orig["Description"].splitlines()) + regen_desc = set(regen["Description"].splitlines()) + assert regen_desc == orig_desc diff --git a/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_extension.py b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_extension.py new file mode 100644 index 0000000000000000000000000000000000000000..5e8e768223ea40d7a629111db181a946cf8ca5b0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_extension.py @@ -0,0 +1,117 @@ +"""Tests for distutils.extension.""" + +import os +import pathlib +import warnings +from distutils.extension import Extension, read_setup_file + +import pytest +from test.support.warnings_helper import check_warnings + + +class TestExtension: + def test_read_setup_file(self): + # trying to read a Setup file + # (sample extracted from the PyGame project) + setup = os.path.join(os.path.dirname(__file__), 'Setup.sample') + + exts = read_setup_file(setup) + names = [ext.name for ext in exts] + names.sort() + + # here are the extensions read_setup_file should have created + # out of the file + wanted = [ + '_arraysurfarray', + '_camera', + '_numericsndarray', + '_numericsurfarray', + 'base', + 'bufferproxy', + 'cdrom', + 'color', + 'constants', + 'display', + 'draw', + 'event', + 'fastevent', + 'font', + 'gfxdraw', + 'image', + 'imageext', + 'joystick', + 'key', + 'mask', + 'mixer', + 'mixer_music', + 'mouse', + 'movie', + 'overlay', + 'pixelarray', + 'pypm', + 'rect', + 'rwobject', + 'scrap', + 'surface', + 'surflock', + 'time', + 'transform', + ] + + assert names == wanted + + def test_extension_init(self): + # the first argument, which is the name, must be a string + with pytest.raises(TypeError): + Extension(1, []) + ext = Extension('name', []) + assert ext.name == 'name' + + # the second argument, which is the list of files, must + # be an iterable of strings or PathLike objects, and not a string + with pytest.raises(TypeError): + Extension('name', 'file') + with pytest.raises(TypeError): + Extension('name', ['file', 1]) + ext = Extension('name', ['file1', 'file2']) + assert ext.sources == ['file1', 'file2'] + ext = Extension('name', [pathlib.Path('file1'), pathlib.Path('file2')]) + assert ext.sources == ['file1', 'file2'] + + # any non-string iterable of strings or PathLike objects should work + ext = Extension('name', ('file1', 'file2')) # tuple + assert ext.sources == ['file1', 'file2'] + ext = Extension('name', {'file1', 'file2'}) # set + assert sorted(ext.sources) == ['file1', 'file2'] + ext = Extension('name', iter(['file1', 'file2'])) # iterator + assert ext.sources == ['file1', 'file2'] + ext = Extension('name', [pathlib.Path('file1'), 'file2']) # mixed types + assert ext.sources == ['file1', 'file2'] + + # others arguments have defaults + for attr in ( + 'include_dirs', + 'define_macros', + 'undef_macros', + 'library_dirs', + 'libraries', + 'runtime_library_dirs', + 'extra_objects', + 'extra_compile_args', + 'extra_link_args', + 'export_symbols', + 'swig_opts', + 'depends', + ): + assert getattr(ext, attr) == [] + + assert ext.language is None + assert ext.optional is None + + # if there are unknown keyword options, warn about them + with check_warnings() as w: + warnings.simplefilter('always') + ext = Extension('name', ['file1', 'file2'], chic=True) + + assert len(w.warnings) == 1 + assert str(w.warnings[0].message) == "Unknown Extension options: 'chic'" diff --git a/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_file_util.py b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_file_util.py new file mode 100644 index 0000000000000000000000000000000000000000..a75d4a0317dc717c24f67127370aa87089eeba1a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_file_util.py @@ -0,0 +1,95 @@ +"""Tests for distutils.file_util.""" + +import errno +import os +import unittest.mock as mock +from distutils.errors import DistutilsFileError +from distutils.file_util import copy_file, move_file + +import jaraco.path +import pytest + + +@pytest.fixture(autouse=True) +def stuff(request, tmp_path): + self = request.instance + self.source = tmp_path / 'f1' + self.target = tmp_path / 'f2' + self.target_dir = tmp_path / 'd1' + + +class TestFileUtil: + def test_move_file_verbosity(self, caplog): + jaraco.path.build({self.source: 'some content'}) + + move_file(self.source, self.target, verbose=False) + assert not caplog.messages + + # back to original state + move_file(self.target, self.source, verbose=False) + + move_file(self.source, self.target, verbose=True) + wanted = [f'moving {self.source} -> {self.target}'] + assert caplog.messages == wanted + + # back to original state + move_file(self.target, self.source, verbose=False) + + caplog.clear() + # now the target is a dir + os.mkdir(self.target_dir) + move_file(self.source, self.target_dir, verbose=True) + wanted = [f'moving {self.source} -> {self.target_dir}'] + assert caplog.messages == wanted + + def test_move_file_exception_unpacking_rename(self): + # see issue 22182 + with ( + mock.patch("os.rename", side_effect=OSError("wrong", 1)), + pytest.raises(DistutilsFileError), + ): + jaraco.path.build({self.source: 'spam eggs'}) + move_file(self.source, self.target, verbose=False) + + def test_move_file_exception_unpacking_unlink(self): + # see issue 22182 + with ( + mock.patch("os.rename", side_effect=OSError(errno.EXDEV, "wrong")), + mock.patch("os.unlink", side_effect=OSError("wrong", 1)), + pytest.raises(DistutilsFileError), + ): + jaraco.path.build({self.source: 'spam eggs'}) + move_file(self.source, self.target, verbose=False) + + def test_copy_file_hard_link(self): + jaraco.path.build({self.source: 'some content'}) + # Check first that copy_file() will not fall back on copying the file + # instead of creating the hard link. + try: + os.link(self.source, self.target) + except OSError as e: + self.skipTest(f'os.link: {e}') + else: + self.target.unlink() + st = os.stat(self.source) + copy_file(self.source, self.target, link='hard') + st2 = os.stat(self.source) + st3 = os.stat(self.target) + assert os.path.samestat(st, st2), (st, st2) + assert os.path.samestat(st2, st3), (st2, st3) + assert self.source.read_text(encoding='utf-8') == 'some content' + + def test_copy_file_hard_link_failure(self): + # If hard linking fails, copy_file() falls back on copying file + # (some special filesystems don't support hard linking even under + # Unix, see issue #8876). + jaraco.path.build({self.source: 'some content'}) + st = os.stat(self.source) + with mock.patch("os.link", side_effect=OSError(0, "linking unsupported")): + copy_file(self.source, self.target, link='hard') + st2 = os.stat(self.source) + st3 = os.stat(self.target) + assert os.path.samestat(st, st2), (st, st2) + assert not os.path.samestat(st2, st3), (st2, st3) + for fn in (self.source, self.target): + assert fn.read_text(encoding='utf-8') == 'some content' diff --git a/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_filelist.py b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_filelist.py new file mode 100644 index 0000000000000000000000000000000000000000..130e6fb53b0bd9670bdcfe6d4bc7fcf8fd90416e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_filelist.py @@ -0,0 +1,336 @@ +"""Tests for distutils.filelist.""" + +import logging +import os +import re +from distutils import debug, filelist +from distutils.errors import DistutilsTemplateError +from distutils.filelist import FileList, glob_to_re, translate_pattern + +import jaraco.path +import pytest + +from .compat import py39 as os_helper + +MANIFEST_IN = """\ +include ok +include xo +exclude xo +include foo.tmp +include buildout.cfg +global-include *.x +global-include *.txt +global-exclude *.tmp +recursive-include f *.oo +recursive-exclude global *.x +graft dir +prune dir3 +""" + + +def make_local_path(s): + """Converts '/' in a string to os.sep""" + return s.replace('/', os.sep) + + +class TestFileList: + def assertNoWarnings(self, caplog): + warnings = [rec for rec in caplog.records if rec.levelno == logging.WARNING] + assert not warnings + caplog.clear() + + def assertWarnings(self, caplog): + warnings = [rec for rec in caplog.records if rec.levelno == logging.WARNING] + assert warnings + caplog.clear() + + def test_glob_to_re(self): + sep = os.sep + if os.sep == '\\': + sep = re.escape(os.sep) + + for glob, regex in ( + # simple cases + ('foo*', r'(?s:foo[^%(sep)s]*)\Z'), + ('foo?', r'(?s:foo[^%(sep)s])\Z'), + ('foo??', r'(?s:foo[^%(sep)s][^%(sep)s])\Z'), + # special cases + (r'foo\\*', r'(?s:foo\\\\[^%(sep)s]*)\Z'), + (r'foo\\\*', r'(?s:foo\\\\\\[^%(sep)s]*)\Z'), + ('foo????', r'(?s:foo[^%(sep)s][^%(sep)s][^%(sep)s][^%(sep)s])\Z'), + (r'foo\\??', r'(?s:foo\\\\[^%(sep)s][^%(sep)s])\Z'), + ): + regex = regex % {'sep': sep} + assert glob_to_re(glob) == regex + + def test_process_template_line(self): + # testing all MANIFEST.in template patterns + file_list = FileList() + mlp = make_local_path + + # simulated file list + file_list.allfiles = [ + 'foo.tmp', + 'ok', + 'xo', + 'four.txt', + 'buildout.cfg', + # filelist does not filter out VCS directories, + # it's sdist that does + mlp('.hg/last-message.txt'), + mlp('global/one.txt'), + mlp('global/two.txt'), + mlp('global/files.x'), + mlp('global/here.tmp'), + mlp('f/o/f.oo'), + mlp('dir/graft-one'), + mlp('dir/dir2/graft2'), + mlp('dir3/ok'), + mlp('dir3/sub/ok.txt'), + ] + + for line in MANIFEST_IN.split('\n'): + if line.strip() == '': + continue + file_list.process_template_line(line) + + wanted = [ + 'ok', + 'buildout.cfg', + 'four.txt', + mlp('.hg/last-message.txt'), + mlp('global/one.txt'), + mlp('global/two.txt'), + mlp('f/o/f.oo'), + mlp('dir/graft-one'), + mlp('dir/dir2/graft2'), + ] + + assert file_list.files == wanted + + def test_debug_print(self, capsys, monkeypatch): + file_list = FileList() + file_list.debug_print('xxx') + assert capsys.readouterr().out == '' + + monkeypatch.setattr(debug, 'DEBUG', True) + file_list.debug_print('xxx') + assert capsys.readouterr().out == 'xxx\n' + + def test_set_allfiles(self): + file_list = FileList() + files = ['a', 'b', 'c'] + file_list.set_allfiles(files) + assert file_list.allfiles == files + + def test_remove_duplicates(self): + file_list = FileList() + file_list.files = ['a', 'b', 'a', 'g', 'c', 'g'] + # files must be sorted beforehand (sdist does it) + file_list.sort() + file_list.remove_duplicates() + assert file_list.files == ['a', 'b', 'c', 'g'] + + def test_translate_pattern(self): + # not regex + assert hasattr(translate_pattern('a', anchor=True, is_regex=False), 'search') + + # is a regex + regex = re.compile('a') + assert translate_pattern(regex, anchor=True, is_regex=True) == regex + + # plain string flagged as regex + assert hasattr(translate_pattern('a', anchor=True, is_regex=True), 'search') + + # glob support + assert translate_pattern('*.py', anchor=True, is_regex=False).search( + 'filelist.py' + ) + + def test_exclude_pattern(self): + # return False if no match + file_list = FileList() + assert not file_list.exclude_pattern('*.py') + + # return True if files match + file_list = FileList() + file_list.files = ['a.py', 'b.py'] + assert file_list.exclude_pattern('*.py') + + # test excludes + file_list = FileList() + file_list.files = ['a.py', 'a.txt'] + file_list.exclude_pattern('*.py') + assert file_list.files == ['a.txt'] + + def test_include_pattern(self): + # return False if no match + file_list = FileList() + file_list.set_allfiles([]) + assert not file_list.include_pattern('*.py') + + # return True if files match + file_list = FileList() + file_list.set_allfiles(['a.py', 'b.txt']) + assert file_list.include_pattern('*.py') + + # test * matches all files + file_list = FileList() + assert file_list.allfiles is None + file_list.set_allfiles(['a.py', 'b.txt']) + file_list.include_pattern('*') + assert file_list.allfiles == ['a.py', 'b.txt'] + + def test_process_template(self, caplog): + mlp = make_local_path + # invalid lines + file_list = FileList() + for action in ( + 'include', + 'exclude', + 'global-include', + 'global-exclude', + 'recursive-include', + 'recursive-exclude', + 'graft', + 'prune', + 'blarg', + ): + with pytest.raises(DistutilsTemplateError): + file_list.process_template_line(action) + + # include + file_list = FileList() + file_list.set_allfiles(['a.py', 'b.txt', mlp('d/c.py')]) + + file_list.process_template_line('include *.py') + assert file_list.files == ['a.py'] + self.assertNoWarnings(caplog) + + file_list.process_template_line('include *.rb') + assert file_list.files == ['a.py'] + self.assertWarnings(caplog) + + # exclude + file_list = FileList() + file_list.files = ['a.py', 'b.txt', mlp('d/c.py')] + + file_list.process_template_line('exclude *.py') + assert file_list.files == ['b.txt', mlp('d/c.py')] + self.assertNoWarnings(caplog) + + file_list.process_template_line('exclude *.rb') + assert file_list.files == ['b.txt', mlp('d/c.py')] + self.assertWarnings(caplog) + + # global-include + file_list = FileList() + file_list.set_allfiles(['a.py', 'b.txt', mlp('d/c.py')]) + + file_list.process_template_line('global-include *.py') + assert file_list.files == ['a.py', mlp('d/c.py')] + self.assertNoWarnings(caplog) + + file_list.process_template_line('global-include *.rb') + assert file_list.files == ['a.py', mlp('d/c.py')] + self.assertWarnings(caplog) + + # global-exclude + file_list = FileList() + file_list.files = ['a.py', 'b.txt', mlp('d/c.py')] + + file_list.process_template_line('global-exclude *.py') + assert file_list.files == ['b.txt'] + self.assertNoWarnings(caplog) + + file_list.process_template_line('global-exclude *.rb') + assert file_list.files == ['b.txt'] + self.assertWarnings(caplog) + + # recursive-include + file_list = FileList() + file_list.set_allfiles(['a.py', mlp('d/b.py'), mlp('d/c.txt'), mlp('d/d/e.py')]) + + file_list.process_template_line('recursive-include d *.py') + assert file_list.files == [mlp('d/b.py'), mlp('d/d/e.py')] + self.assertNoWarnings(caplog) + + file_list.process_template_line('recursive-include e *.py') + assert file_list.files == [mlp('d/b.py'), mlp('d/d/e.py')] + self.assertWarnings(caplog) + + # recursive-exclude + file_list = FileList() + file_list.files = ['a.py', mlp('d/b.py'), mlp('d/c.txt'), mlp('d/d/e.py')] + + file_list.process_template_line('recursive-exclude d *.py') + assert file_list.files == ['a.py', mlp('d/c.txt')] + self.assertNoWarnings(caplog) + + file_list.process_template_line('recursive-exclude e *.py') + assert file_list.files == ['a.py', mlp('d/c.txt')] + self.assertWarnings(caplog) + + # graft + file_list = FileList() + file_list.set_allfiles(['a.py', mlp('d/b.py'), mlp('d/d/e.py'), mlp('f/f.py')]) + + file_list.process_template_line('graft d') + assert file_list.files == [mlp('d/b.py'), mlp('d/d/e.py')] + self.assertNoWarnings(caplog) + + file_list.process_template_line('graft e') + assert file_list.files == [mlp('d/b.py'), mlp('d/d/e.py')] + self.assertWarnings(caplog) + + # prune + file_list = FileList() + file_list.files = ['a.py', mlp('d/b.py'), mlp('d/d/e.py'), mlp('f/f.py')] + + file_list.process_template_line('prune d') + assert file_list.files == ['a.py', mlp('f/f.py')] + self.assertNoWarnings(caplog) + + file_list.process_template_line('prune e') + assert file_list.files == ['a.py', mlp('f/f.py')] + self.assertWarnings(caplog) + + +class TestFindAll: + @os_helper.skip_unless_symlink + def test_missing_symlink(self, temp_cwd): + os.symlink('foo', 'bar') + assert filelist.findall() == [] + + def test_basic_discovery(self, temp_cwd): + """ + When findall is called with no parameters or with + '.' as the parameter, the dot should be omitted from + the results. + """ + jaraco.path.build({'foo': {'file1.txt': ''}, 'bar': {'file2.txt': ''}}) + file1 = os.path.join('foo', 'file1.txt') + file2 = os.path.join('bar', 'file2.txt') + expected = [file2, file1] + assert sorted(filelist.findall()) == expected + + def test_non_local_discovery(self, tmp_path): + """ + When findall is called with another path, the full + path name should be returned. + """ + jaraco.path.build({'file1.txt': ''}, tmp_path) + expected = [str(tmp_path / 'file1.txt')] + assert filelist.findall(tmp_path) == expected + + @os_helper.skip_unless_symlink + def test_symlink_loop(self, tmp_path): + jaraco.path.build( + { + 'link-to-parent': jaraco.path.Symlink('.'), + 'somefile': '', + }, + tmp_path, + ) + files = filelist.findall(tmp_path) + assert len(files) == 1 diff --git a/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_install.py b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_install.py new file mode 100644 index 0000000000000000000000000000000000000000..b3ffb2e668ac5a042c5a2889d7b51b5755b73157 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_install.py @@ -0,0 +1,245 @@ +"""Tests for distutils.command.install.""" + +import logging +import os +import pathlib +import site +import sys +from distutils import sysconfig +from distutils.command import install as install_module +from distutils.command.build_ext import build_ext +from distutils.command.install import INSTALL_SCHEMES, install +from distutils.core import Distribution +from distutils.errors import DistutilsOptionError +from distutils.extension import Extension +from distutils.tests import missing_compiler_executable, support +from distutils.util import is_mingw + +import pytest + + +def _make_ext_name(modname): + return modname + sysconfig.get_config_var('EXT_SUFFIX') + + +@support.combine_markers +@pytest.mark.usefixtures('save_env') +class TestInstall( + support.TempdirManager, +): + @pytest.mark.xfail( + 'platform.system() == "Windows" and sys.version_info > (3, 11)', + reason="pypa/distutils#148", + ) + def test_home_installation_scheme(self): + # This ensure two things: + # - that --home generates the desired set of directory names + # - test --home is supported on all platforms + builddir = self.mkdtemp() + destination = os.path.join(builddir, "installation") + + dist = Distribution({"name": "foopkg"}) + # script_name need not exist, it just need to be initialized + dist.script_name = os.path.join(builddir, "setup.py") + dist.command_obj["build"] = support.DummyCommand( + build_base=builddir, + build_lib=os.path.join(builddir, "lib"), + ) + + cmd = install(dist) + cmd.home = destination + cmd.ensure_finalized() + + assert cmd.install_base == destination + assert cmd.install_platbase == destination + + def check_path(got, expected): + got = os.path.normpath(got) + expected = os.path.normpath(expected) + assert got == expected + + impl_name = sys.implementation.name.replace("cpython", "python") + libdir = os.path.join(destination, "lib", impl_name) + check_path(cmd.install_lib, libdir) + _platlibdir = getattr(sys, "platlibdir", "lib") + platlibdir = os.path.join(destination, _platlibdir, impl_name) + check_path(cmd.install_platlib, platlibdir) + check_path(cmd.install_purelib, libdir) + check_path( + cmd.install_headers, + os.path.join(destination, "include", impl_name, "foopkg"), + ) + check_path(cmd.install_scripts, os.path.join(destination, "bin")) + check_path(cmd.install_data, destination) + + def test_user_site(self, monkeypatch): + # test install with --user + # preparing the environment for the test + self.tmpdir = self.mkdtemp() + orig_site = site.USER_SITE + orig_base = site.USER_BASE + monkeypatch.setattr(site, 'USER_BASE', os.path.join(self.tmpdir, 'B')) + monkeypatch.setattr(site, 'USER_SITE', os.path.join(self.tmpdir, 'S')) + monkeypatch.setattr(install_module, 'USER_BASE', site.USER_BASE) + monkeypatch.setattr(install_module, 'USER_SITE', site.USER_SITE) + + def _expanduser(path): + if path.startswith('~'): + return os.path.normpath(self.tmpdir + path[1:]) + return path + + monkeypatch.setattr(os.path, 'expanduser', _expanduser) + + for key in ('nt_user', 'posix_user'): + assert key in INSTALL_SCHEMES + + dist = Distribution({'name': 'xx'}) + cmd = install(dist) + + # making sure the user option is there + options = [name for name, short, label in cmd.user_options] + assert 'user' in options + + # setting a value + cmd.user = True + + # user base and site shouldn't be created yet + assert not os.path.exists(site.USER_BASE) + assert not os.path.exists(site.USER_SITE) + + # let's run finalize + cmd.ensure_finalized() + + # now they should + assert os.path.exists(site.USER_BASE) + assert os.path.exists(site.USER_SITE) + + assert 'userbase' in cmd.config_vars + assert 'usersite' in cmd.config_vars + + actual_headers = os.path.relpath(cmd.install_headers, site.USER_BASE) + if os.name == 'nt' and not is_mingw(): + site_path = os.path.relpath(os.path.dirname(orig_site), orig_base) + include = os.path.join(site_path, 'Include') + else: + include = sysconfig.get_python_inc(0, '') + expect_headers = os.path.join(include, 'xx') + + assert os.path.normcase(actual_headers) == os.path.normcase(expect_headers) + + def test_handle_extra_path(self): + dist = Distribution({'name': 'xx', 'extra_path': 'path,dirs'}) + cmd = install(dist) + + # two elements + cmd.handle_extra_path() + assert cmd.extra_path == ['path', 'dirs'] + assert cmd.extra_dirs == 'dirs' + assert cmd.path_file == 'path' + + # one element + cmd.extra_path = ['path'] + cmd.handle_extra_path() + assert cmd.extra_path == ['path'] + assert cmd.extra_dirs == 'path' + assert cmd.path_file == 'path' + + # none + dist.extra_path = cmd.extra_path = None + cmd.handle_extra_path() + assert cmd.extra_path is None + assert cmd.extra_dirs == '' + assert cmd.path_file is None + + # three elements (no way !) + cmd.extra_path = 'path,dirs,again' + with pytest.raises(DistutilsOptionError): + cmd.handle_extra_path() + + def test_finalize_options(self): + dist = Distribution({'name': 'xx'}) + cmd = install(dist) + + # must supply either prefix/exec-prefix/home or + # install-base/install-platbase -- not both + cmd.prefix = 'prefix' + cmd.install_base = 'base' + with pytest.raises(DistutilsOptionError): + cmd.finalize_options() + + # must supply either home or prefix/exec-prefix -- not both + cmd.install_base = None + cmd.home = 'home' + with pytest.raises(DistutilsOptionError): + cmd.finalize_options() + + # can't combine user with prefix/exec_prefix/home or + # install_(plat)base + cmd.prefix = None + cmd.user = 'user' + with pytest.raises(DistutilsOptionError): + cmd.finalize_options() + + def test_record(self): + install_dir = self.mkdtemp() + project_dir, dist = self.create_dist(py_modules=['hello'], scripts=['sayhi']) + os.chdir(project_dir) + self.write_file('hello.py', "def main(): print('o hai')") + self.write_file('sayhi', 'from hello import main; main()') + + cmd = install(dist) + dist.command_obj['install'] = cmd + cmd.root = install_dir + cmd.record = os.path.join(project_dir, 'filelist') + cmd.ensure_finalized() + cmd.run() + + content = pathlib.Path(cmd.record).read_text(encoding='utf-8') + + found = [pathlib.Path(line).name for line in content.splitlines()] + expected = [ + 'hello.py', + f'hello.{sys.implementation.cache_tag}.pyc', + 'sayhi', + 'UNKNOWN-0.0.0-py{}.{}.egg-info'.format(*sys.version_info[:2]), + ] + assert found == expected + + def test_record_extensions(self): + cmd = missing_compiler_executable() + if cmd is not None: + pytest.skip(f'The {cmd!r} command is not found') + install_dir = self.mkdtemp() + project_dir, dist = self.create_dist( + ext_modules=[Extension('xx', ['xxmodule.c'])] + ) + os.chdir(project_dir) + support.copy_xxmodule_c(project_dir) + + buildextcmd = build_ext(dist) + support.fixup_build_ext(buildextcmd) + buildextcmd.ensure_finalized() + + cmd = install(dist) + dist.command_obj['install'] = cmd + dist.command_obj['build_ext'] = buildextcmd + cmd.root = install_dir + cmd.record = os.path.join(project_dir, 'filelist') + cmd.ensure_finalized() + cmd.run() + + content = pathlib.Path(cmd.record).read_text(encoding='utf-8') + + found = [pathlib.Path(line).name for line in content.splitlines()] + expected = [ + _make_ext_name('xx'), + 'UNKNOWN-0.0.0-py{}.{}.egg-info'.format(*sys.version_info[:2]), + ] + assert found == expected + + def test_debug_mode(self, caplog, monkeypatch): + # this covers the code called when DEBUG is set + monkeypatch.setattr(install_module, 'DEBUG', True) + caplog.set_level(logging.DEBUG) + self.test_record() + assert any(rec for rec in caplog.records if rec.levelno == logging.DEBUG) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_install_data.py b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_install_data.py new file mode 100644 index 0000000000000000000000000000000000000000..c800f86c645d86fcb11aa3bef1513325ef163132 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_install_data.py @@ -0,0 +1,74 @@ +"""Tests for distutils.command.install_data.""" + +import os +import pathlib +from distutils.command.install_data import install_data +from distutils.tests import support + +import pytest + + +@pytest.mark.usefixtures('save_env') +class TestInstallData( + support.TempdirManager, +): + def test_simple_run(self): + pkg_dir, dist = self.create_dist() + cmd = install_data(dist) + cmd.install_dir = inst = os.path.join(pkg_dir, 'inst') + + # data_files can contain + # - simple files + # - a Path object + # - a tuple with a path, and a list of file + one = os.path.join(pkg_dir, 'one') + self.write_file(one, 'xxx') + inst2 = os.path.join(pkg_dir, 'inst2') + two = os.path.join(pkg_dir, 'two') + self.write_file(two, 'xxx') + three = pathlib.Path(pkg_dir) / 'three' + self.write_file(three, 'xxx') + + cmd.data_files = [one, (inst2, [two]), three] + assert cmd.get_inputs() == [one, (inst2, [two]), three] + + # let's run the command + cmd.ensure_finalized() + cmd.run() + + # let's check the result + assert len(cmd.get_outputs()) == 3 + rthree = os.path.split(one)[-1] + assert os.path.exists(os.path.join(inst, rthree)) + rtwo = os.path.split(two)[-1] + assert os.path.exists(os.path.join(inst2, rtwo)) + rone = os.path.split(one)[-1] + assert os.path.exists(os.path.join(inst, rone)) + cmd.outfiles = [] + + # let's try with warn_dir one + cmd.warn_dir = True + cmd.ensure_finalized() + cmd.run() + + # let's check the result + assert len(cmd.get_outputs()) == 3 + assert os.path.exists(os.path.join(inst, rthree)) + assert os.path.exists(os.path.join(inst2, rtwo)) + assert os.path.exists(os.path.join(inst, rone)) + cmd.outfiles = [] + + # now using root and empty dir + cmd.root = os.path.join(pkg_dir, 'root') + inst5 = os.path.join(pkg_dir, 'inst5') + four = os.path.join(cmd.install_dir, 'four') + self.write_file(four, 'xx') + cmd.data_files = [one, (inst2, [two]), three, ('inst5', [four]), (inst5, [])] + cmd.ensure_finalized() + cmd.run() + + # let's check the result + assert len(cmd.get_outputs()) == 5 + assert os.path.exists(os.path.join(inst, rthree)) + assert os.path.exists(os.path.join(inst2, rtwo)) + assert os.path.exists(os.path.join(inst, rone)) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_install_headers.py b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_install_headers.py new file mode 100644 index 0000000000000000000000000000000000000000..2c74f06b976f3c3ea977667a5c16c0e7f201a558 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_install_headers.py @@ -0,0 +1,33 @@ +"""Tests for distutils.command.install_headers.""" + +import os +from distutils.command.install_headers import install_headers +from distutils.tests import support + +import pytest + + +@pytest.mark.usefixtures('save_env') +class TestInstallHeaders( + support.TempdirManager, +): + def test_simple_run(self): + # we have two headers + header_list = self.mkdtemp() + header1 = os.path.join(header_list, 'header1') + header2 = os.path.join(header_list, 'header2') + self.write_file(header1) + self.write_file(header2) + headers = [header1, header2] + + pkg_dir, dist = self.create_dist(headers=headers) + cmd = install_headers(dist) + assert cmd.get_inputs() == headers + + # let's run the command + cmd.install_dir = os.path.join(pkg_dir, 'inst') + cmd.ensure_finalized() + cmd.run() + + # let's check the results + assert len(cmd.get_outputs()) == 2 diff --git a/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_install_lib.py b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_install_lib.py new file mode 100644 index 0000000000000000000000000000000000000000..f685a579560ea70bceea221de0e54485975ce180 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_install_lib.py @@ -0,0 +1,110 @@ +"""Tests for distutils.command.install_data.""" + +import importlib.util +import os +import sys +from distutils.command.install_lib import install_lib +from distutils.errors import DistutilsOptionError +from distutils.extension import Extension +from distutils.tests import support + +import pytest + + +@support.combine_markers +@pytest.mark.usefixtures('save_env') +class TestInstallLib( + support.TempdirManager, +): + def test_finalize_options(self): + dist = self.create_dist()[1] + cmd = install_lib(dist) + + cmd.finalize_options() + assert cmd.compile == 1 + assert cmd.optimize == 0 + + # optimize must be 0, 1, or 2 + cmd.optimize = 'foo' + with pytest.raises(DistutilsOptionError): + cmd.finalize_options() + cmd.optimize = '4' + with pytest.raises(DistutilsOptionError): + cmd.finalize_options() + + cmd.optimize = '2' + cmd.finalize_options() + assert cmd.optimize == 2 + + @pytest.mark.skipif('sys.dont_write_bytecode') + def test_byte_compile(self): + project_dir, dist = self.create_dist() + os.chdir(project_dir) + cmd = install_lib(dist) + cmd.compile = cmd.optimize = 1 + + f = os.path.join(project_dir, 'foo.py') + self.write_file(f, '# python file') + cmd.byte_compile([f]) + pyc_file = importlib.util.cache_from_source('foo.py', optimization='') + pyc_opt_file = importlib.util.cache_from_source( + 'foo.py', optimization=cmd.optimize + ) + assert os.path.exists(pyc_file) + assert os.path.exists(pyc_opt_file) + + def test_get_outputs(self): + project_dir, dist = self.create_dist() + os.chdir(project_dir) + os.mkdir('spam') + cmd = install_lib(dist) + + # setting up a dist environment + cmd.compile = cmd.optimize = 1 + cmd.install_dir = self.mkdtemp() + f = os.path.join(project_dir, 'spam', '__init__.py') + self.write_file(f, '# python package') + cmd.distribution.ext_modules = [Extension('foo', ['xxx'])] + cmd.distribution.packages = ['spam'] + cmd.distribution.script_name = 'setup.py' + + # get_outputs should return 4 elements: spam/__init__.py and .pyc, + # foo.import-tag-abiflags.so / foo.pyd + outputs = cmd.get_outputs() + assert len(outputs) == 4, outputs + + def test_get_inputs(self): + project_dir, dist = self.create_dist() + os.chdir(project_dir) + os.mkdir('spam') + cmd = install_lib(dist) + + # setting up a dist environment + cmd.compile = cmd.optimize = 1 + cmd.install_dir = self.mkdtemp() + f = os.path.join(project_dir, 'spam', '__init__.py') + self.write_file(f, '# python package') + cmd.distribution.ext_modules = [Extension('foo', ['xxx'])] + cmd.distribution.packages = ['spam'] + cmd.distribution.script_name = 'setup.py' + + # get_inputs should return 2 elements: spam/__init__.py and + # foo.import-tag-abiflags.so / foo.pyd + inputs = cmd.get_inputs() + assert len(inputs) == 2, inputs + + def test_dont_write_bytecode(self, caplog): + # makes sure byte_compile is not used + dist = self.create_dist()[1] + cmd = install_lib(dist) + cmd.compile = True + cmd.optimize = 1 + + old_dont_write_bytecode = sys.dont_write_bytecode + sys.dont_write_bytecode = True + try: + cmd.byte_compile([]) + finally: + sys.dont_write_bytecode = old_dont_write_bytecode + + assert 'byte-compiling is disabled' in caplog.messages[0] diff --git a/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_install_scripts.py b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_install_scripts.py new file mode 100644 index 0000000000000000000000000000000000000000..868b1c22521f23a5dd398e4636c94330d4c238ac --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_install_scripts.py @@ -0,0 +1,52 @@ +"""Tests for distutils.command.install_scripts.""" + +import os +from distutils.command.install_scripts import install_scripts +from distutils.core import Distribution +from distutils.tests import support + +from . import test_build_scripts + + +class TestInstallScripts(support.TempdirManager): + def test_default_settings(self): + dist = Distribution() + dist.command_obj["build"] = support.DummyCommand(build_scripts="/foo/bar") + dist.command_obj["install"] = support.DummyCommand( + install_scripts="/splat/funk", + force=True, + skip_build=True, + ) + cmd = install_scripts(dist) + assert not cmd.force + assert not cmd.skip_build + assert cmd.build_dir is None + assert cmd.install_dir is None + + cmd.finalize_options() + + assert cmd.force + assert cmd.skip_build + assert cmd.build_dir == "/foo/bar" + assert cmd.install_dir == "/splat/funk" + + def test_installation(self): + source = self.mkdtemp() + + expected = test_build_scripts.TestBuildScripts.write_sample_scripts(source) + + target = self.mkdtemp() + dist = Distribution() + dist.command_obj["build"] = support.DummyCommand(build_scripts=source) + dist.command_obj["install"] = support.DummyCommand( + install_scripts=target, + force=True, + skip_build=True, + ) + cmd = install_scripts(dist) + cmd.finalize_options() + cmd.run() + + installed = os.listdir(target) + for name in expected: + assert name in installed diff --git a/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_log.py b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_log.py new file mode 100644 index 0000000000000000000000000000000000000000..d67779fc9fa0f58a010929d5a456890c6dde3376 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_log.py @@ -0,0 +1,12 @@ +"""Tests for distutils.log""" + +import logging +from distutils._log import log + + +class TestLog: + def test_non_ascii(self, caplog): + caplog.set_level(logging.DEBUG) + log.debug('Dεbug\tMėssãge') + log.fatal('Fαtal\tÈrrōr') + assert caplog.messages == ['Dεbug\tMėssãge', 'Fαtal\tÈrrōr'] diff --git a/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_modified.py b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_modified.py new file mode 100644 index 0000000000000000000000000000000000000000..e35cec2d6f1a8d27619e33c253f0a83f0f72a75d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_modified.py @@ -0,0 +1,126 @@ +"""Tests for distutils._modified.""" + +import os +import types +from distutils._modified import newer, newer_group, newer_pairwise, newer_pairwise_group +from distutils.errors import DistutilsFileError +from distutils.tests import support + +import pytest + + +class TestDepUtil(support.TempdirManager): + def test_newer(self): + tmpdir = self.mkdtemp() + new_file = os.path.join(tmpdir, 'new') + old_file = os.path.abspath(__file__) + + # Raise DistutilsFileError if 'new_file' does not exist. + with pytest.raises(DistutilsFileError): + newer(new_file, old_file) + + # Return true if 'new_file' exists and is more recently modified than + # 'old_file', or if 'new_file' exists and 'old_file' doesn't. + self.write_file(new_file) + assert newer(new_file, 'I_dont_exist') + assert newer(new_file, old_file) + + # Return false if both exist and 'old_file' is the same age or younger + # than 'new_file'. + assert not newer(old_file, new_file) + + def _setup_1234(self): + tmpdir = self.mkdtemp() + sources = os.path.join(tmpdir, 'sources') + targets = os.path.join(tmpdir, 'targets') + os.mkdir(sources) + os.mkdir(targets) + one = os.path.join(sources, 'one') + two = os.path.join(sources, 'two') + three = os.path.abspath(__file__) # I am the old file + four = os.path.join(targets, 'four') + self.write_file(one) + self.write_file(two) + self.write_file(four) + return one, two, three, four + + def test_newer_pairwise(self): + one, two, three, four = self._setup_1234() + + assert newer_pairwise([one, two], [three, four]) == ([one], [three]) + + def test_newer_pairwise_mismatch(self): + one, two, three, four = self._setup_1234() + + with pytest.raises(ValueError): + newer_pairwise([one], [three, four]) + + with pytest.raises(ValueError): + newer_pairwise([one, two], [three]) + + def test_newer_pairwise_empty(self): + assert newer_pairwise([], []) == ([], []) + + def test_newer_pairwise_fresh(self): + one, two, three, four = self._setup_1234() + + assert newer_pairwise([one, three], [two, four]) == ([], []) + + def test_newer_group(self): + tmpdir = self.mkdtemp() + sources = os.path.join(tmpdir, 'sources') + os.mkdir(sources) + one = os.path.join(sources, 'one') + two = os.path.join(sources, 'two') + three = os.path.join(sources, 'three') + old_file = os.path.abspath(__file__) + + # return true if 'old_file' is out-of-date with respect to any file + # listed in 'sources'. + self.write_file(one) + self.write_file(two) + self.write_file(three) + assert newer_group([one, two, three], old_file) + assert not newer_group([one, two, old_file], three) + + # missing handling + os.remove(one) + with pytest.raises(OSError): + newer_group([one, two, old_file], three) + + assert not newer_group([one, two, old_file], three, missing='ignore') + + assert newer_group([one, two, old_file], three, missing='newer') + + +@pytest.fixture +def groups_target(tmp_path): + """ + Set up some older sources, a target, and newer sources. + + Returns a simple namespace with these values. + """ + filenames = ['older.c', 'older.h', 'target.o', 'newer.c', 'newer.h'] + paths = [tmp_path / name for name in filenames] + + for mtime, path in enumerate(paths): + path.write_text('', encoding='utf-8') + + # make sure modification times are sequential + os.utime(path, (mtime, mtime)) + + return types.SimpleNamespace(older=paths[:2], target=paths[2], newer=paths[3:]) + + +def test_newer_pairwise_group(groups_target): + older = newer_pairwise_group([groups_target.older], [groups_target.target]) + newer = newer_pairwise_group([groups_target.newer], [groups_target.target]) + assert older == ([], []) + assert newer == ([groups_target.newer], [groups_target.target]) + + +def test_newer_group_no_sources_no_target(tmp_path): + """ + Consider no sources and no target "newer". + """ + assert newer_group([], str(tmp_path / 'does-not-exist')) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_sdist.py b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_sdist.py new file mode 100644 index 0000000000000000000000000000000000000000..6b1a376b262162aa7c8d3d989709c05b38563d6c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_sdist.py @@ -0,0 +1,470 @@ +"""Tests for distutils.command.sdist.""" + +import os +import pathlib +import shutil # noqa: F401 +import tarfile +import zipfile +from distutils.archive_util import ARCHIVE_FORMATS +from distutils.command.sdist import sdist, show_formats +from distutils.core import Distribution +from distutils.errors import DistutilsOptionError +from distutils.filelist import FileList +from os.path import join +from textwrap import dedent + +import jaraco.path +import path +import pytest +from more_itertools import ilen + +from . import support +from .unix_compat import grp, pwd, require_uid_0, require_unix_id + +SETUP_PY = """ +from distutils.core import setup +import somecode + +setup(name='fake') +""" + +MANIFEST = """\ +# file GENERATED by distutils, do NOT edit +README +buildout.cfg +inroot.txt +setup.py +data%(sep)sdata.dt +scripts%(sep)sscript.py +some%(sep)sfile.txt +some%(sep)sother_file.txt +somecode%(sep)s__init__.py +somecode%(sep)sdoc.dat +somecode%(sep)sdoc.txt +""" + + +@pytest.fixture(autouse=True) +def project_dir(request, distutils_managed_tempdir): + self = request.instance + self.tmp_dir = self.mkdtemp() + jaraco.path.build( + { + 'somecode': { + '__init__.py': '#', + }, + 'README': 'xxx', + 'setup.py': SETUP_PY, + }, + self.tmp_dir, + ) + with path.Path(self.tmp_dir): + yield + + +def clean_lines(filepath): + with pathlib.Path(filepath).open(encoding='utf-8') as f: + yield from filter(None, map(str.strip, f)) + + +class TestSDist(support.TempdirManager): + def get_cmd(self, metadata=None): + """Returns a cmd""" + if metadata is None: + metadata = { + 'name': 'ns.fake--pkg', + 'version': '1.0', + 'url': 'xxx', + 'author': 'xxx', + 'author_email': 'xxx', + } + dist = Distribution(metadata) + dist.script_name = 'setup.py' + dist.packages = ['somecode'] + dist.include_package_data = True + cmd = sdist(dist) + cmd.dist_dir = 'dist' + return dist, cmd + + @pytest.mark.usefixtures('needs_zlib') + def test_prune_file_list(self): + # this test creates a project with some VCS dirs and an NFS rename + # file, then launches sdist to check they get pruned on all systems + + # creating VCS directories with some files in them + os.mkdir(join(self.tmp_dir, 'somecode', '.svn')) + self.write_file((self.tmp_dir, 'somecode', '.svn', 'ok.py'), 'xxx') + + os.mkdir(join(self.tmp_dir, 'somecode', '.hg')) + self.write_file((self.tmp_dir, 'somecode', '.hg', 'ok'), 'xxx') + + os.mkdir(join(self.tmp_dir, 'somecode', '.git')) + self.write_file((self.tmp_dir, 'somecode', '.git', 'ok'), 'xxx') + + self.write_file((self.tmp_dir, 'somecode', '.nfs0001'), 'xxx') + + # now building a sdist + dist, cmd = self.get_cmd() + + # zip is available universally + # (tar might not be installed under win32) + cmd.formats = ['zip'] + + cmd.ensure_finalized() + cmd.run() + + # now let's check what we have + dist_folder = join(self.tmp_dir, 'dist') + files = os.listdir(dist_folder) + assert files == ['ns_fake_pkg-1.0.zip'] + + zip_file = zipfile.ZipFile(join(dist_folder, 'ns_fake_pkg-1.0.zip')) + try: + content = zip_file.namelist() + finally: + zip_file.close() + + # making sure everything has been pruned correctly + expected = [ + '', + 'PKG-INFO', + 'README', + 'setup.py', + 'somecode/', + 'somecode/__init__.py', + ] + assert sorted(content) == ['ns_fake_pkg-1.0/' + x for x in expected] + + @pytest.mark.usefixtures('needs_zlib') + @pytest.mark.skipif("not shutil.which('tar')") + @pytest.mark.skipif("not shutil.which('gzip')") + def test_make_distribution(self): + # now building a sdist + dist, cmd = self.get_cmd() + + # creating a gztar then a tar + cmd.formats = ['gztar', 'tar'] + cmd.ensure_finalized() + cmd.run() + + # making sure we have two files + dist_folder = join(self.tmp_dir, 'dist') + result = os.listdir(dist_folder) + result.sort() + assert result == ['ns_fake_pkg-1.0.tar', 'ns_fake_pkg-1.0.tar.gz'] + + os.remove(join(dist_folder, 'ns_fake_pkg-1.0.tar')) + os.remove(join(dist_folder, 'ns_fake_pkg-1.0.tar.gz')) + + # now trying a tar then a gztar + cmd.formats = ['tar', 'gztar'] + + cmd.ensure_finalized() + cmd.run() + + result = os.listdir(dist_folder) + result.sort() + assert result == ['ns_fake_pkg-1.0.tar', 'ns_fake_pkg-1.0.tar.gz'] + + @pytest.mark.usefixtures('needs_zlib') + def test_add_defaults(self): + # https://bugs.python.org/issue2279 + + # add_default should also include + # data_files and package_data + dist, cmd = self.get_cmd() + + # filling data_files by pointing files + # in package_data + dist.package_data = {'': ['*.cfg', '*.dat'], 'somecode': ['*.txt']} + self.write_file((self.tmp_dir, 'somecode', 'doc.txt'), '#') + self.write_file((self.tmp_dir, 'somecode', 'doc.dat'), '#') + + # adding some data in data_files + data_dir = join(self.tmp_dir, 'data') + os.mkdir(data_dir) + self.write_file((data_dir, 'data.dt'), '#') + some_dir = join(self.tmp_dir, 'some') + os.mkdir(some_dir) + # make sure VCS directories are pruned (#14004) + hg_dir = join(self.tmp_dir, '.hg') + os.mkdir(hg_dir) + self.write_file((hg_dir, 'last-message.txt'), '#') + # a buggy regex used to prevent this from working on windows (#6884) + self.write_file((self.tmp_dir, 'buildout.cfg'), '#') + self.write_file((self.tmp_dir, 'inroot.txt'), '#') + self.write_file((some_dir, 'file.txt'), '#') + self.write_file((some_dir, 'other_file.txt'), '#') + + dist.data_files = [ + ('data', ['data/data.dt', 'buildout.cfg', 'inroot.txt', 'notexisting']), + 'some/file.txt', + 'some/other_file.txt', + ] + + # adding a script + script_dir = join(self.tmp_dir, 'scripts') + os.mkdir(script_dir) + self.write_file((script_dir, 'script.py'), '#') + dist.scripts = [join('scripts', 'script.py')] + + cmd.formats = ['zip'] + cmd.use_defaults = True + + cmd.ensure_finalized() + cmd.run() + + # now let's check what we have + dist_folder = join(self.tmp_dir, 'dist') + files = os.listdir(dist_folder) + assert files == ['ns_fake_pkg-1.0.zip'] + + zip_file = zipfile.ZipFile(join(dist_folder, 'ns_fake_pkg-1.0.zip')) + try: + content = zip_file.namelist() + finally: + zip_file.close() + + # making sure everything was added + expected = [ + '', + 'PKG-INFO', + 'README', + 'buildout.cfg', + 'data/', + 'data/data.dt', + 'inroot.txt', + 'scripts/', + 'scripts/script.py', + 'setup.py', + 'some/', + 'some/file.txt', + 'some/other_file.txt', + 'somecode/', + 'somecode/__init__.py', + 'somecode/doc.dat', + 'somecode/doc.txt', + ] + assert sorted(content) == ['ns_fake_pkg-1.0/' + x for x in expected] + + # checking the MANIFEST + manifest = pathlib.Path(self.tmp_dir, 'MANIFEST').read_text(encoding='utf-8') + assert manifest == MANIFEST % {'sep': os.sep} + + @staticmethod + def warnings(messages, prefix='warning: '): + return [msg for msg in messages if msg.startswith(prefix)] + + @pytest.mark.usefixtures('needs_zlib') + def test_metadata_check_option(self, caplog): + # testing the `medata-check` option + dist, cmd = self.get_cmd(metadata={}) + + # this should raise some warnings ! + # with the `check` subcommand + cmd.ensure_finalized() + cmd.run() + assert len(self.warnings(caplog.messages, 'warning: check: ')) == 1 + + # trying with a complete set of metadata + caplog.clear() + dist, cmd = self.get_cmd() + cmd.ensure_finalized() + cmd.metadata_check = False + cmd.run() + assert len(self.warnings(caplog.messages, 'warning: check: ')) == 0 + + def test_show_formats(self, capsys): + show_formats() + + # the output should be a header line + one line per format + num_formats = len(ARCHIVE_FORMATS.keys()) + output = [ + line + for line in capsys.readouterr().out.split('\n') + if line.strip().startswith('--formats=') + ] + assert len(output) == num_formats + + def test_finalize_options(self): + dist, cmd = self.get_cmd() + cmd.finalize_options() + + # default options set by finalize + assert cmd.manifest == 'MANIFEST' + assert cmd.template == 'MANIFEST.in' + assert cmd.dist_dir == 'dist' + + # formats has to be a string splitable on (' ', ',') or + # a stringlist + cmd.formats = 1 + with pytest.raises(DistutilsOptionError): + cmd.finalize_options() + cmd.formats = ['zip'] + cmd.finalize_options() + + # formats has to be known + cmd.formats = 'supazipa' + with pytest.raises(DistutilsOptionError): + cmd.finalize_options() + + # the following tests make sure there is a nice error message instead + # of a traceback when parsing an invalid manifest template + + def _check_template(self, content, caplog): + dist, cmd = self.get_cmd() + os.chdir(self.tmp_dir) + self.write_file('MANIFEST.in', content) + cmd.ensure_finalized() + cmd.filelist = FileList() + cmd.read_template() + assert len(self.warnings(caplog.messages)) == 1 + + def test_invalid_template_unknown_command(self, caplog): + self._check_template('taunt knights *', caplog) + + def test_invalid_template_wrong_arguments(self, caplog): + # this manifest command takes one argument + self._check_template('prune', caplog) + + @pytest.mark.skipif("platform.system() != 'Windows'") + def test_invalid_template_wrong_path(self, caplog): + # on Windows, trailing slashes are not allowed + # this used to crash instead of raising a warning: #8286 + self._check_template('include examples/', caplog) + + @pytest.mark.usefixtures('needs_zlib') + def test_get_file_list(self): + # make sure MANIFEST is recalculated + dist, cmd = self.get_cmd() + + # filling data_files by pointing files in package_data + dist.package_data = {'somecode': ['*.txt']} + self.write_file((self.tmp_dir, 'somecode', 'doc.txt'), '#') + cmd.formats = ['gztar'] + cmd.ensure_finalized() + cmd.run() + + assert ilen(clean_lines(cmd.manifest)) == 5 + + # adding a file + self.write_file((self.tmp_dir, 'somecode', 'doc2.txt'), '#') + + # make sure build_py is reinitialized, like a fresh run + build_py = dist.get_command_obj('build_py') + build_py.finalized = False + build_py.ensure_finalized() + + cmd.run() + + manifest2 = list(clean_lines(cmd.manifest)) + + # do we have the new file in MANIFEST ? + assert len(manifest2) == 6 + assert 'doc2.txt' in manifest2[-1] + + @pytest.mark.usefixtures('needs_zlib') + def test_manifest_marker(self): + # check that autogenerated MANIFESTs have a marker + dist, cmd = self.get_cmd() + cmd.ensure_finalized() + cmd.run() + + assert ( + next(clean_lines(cmd.manifest)) + == '# file GENERATED by distutils, do NOT edit' + ) + + @pytest.mark.usefixtures('needs_zlib') + def test_manifest_comments(self): + # make sure comments don't cause exceptions or wrong includes + contents = dedent( + """\ + # bad.py + #bad.py + good.py + """ + ) + dist, cmd = self.get_cmd() + cmd.ensure_finalized() + self.write_file((self.tmp_dir, cmd.manifest), contents) + self.write_file((self.tmp_dir, 'good.py'), '# pick me!') + self.write_file((self.tmp_dir, 'bad.py'), "# don't pick me!") + self.write_file((self.tmp_dir, '#bad.py'), "# don't pick me!") + cmd.run() + assert cmd.filelist.files == ['good.py'] + + @pytest.mark.usefixtures('needs_zlib') + def test_manual_manifest(self): + # check that a MANIFEST without a marker is left alone + dist, cmd = self.get_cmd() + cmd.formats = ['gztar'] + cmd.ensure_finalized() + self.write_file((self.tmp_dir, cmd.manifest), 'README.manual') + self.write_file( + (self.tmp_dir, 'README.manual'), + 'This project maintains its MANIFEST file itself.', + ) + cmd.run() + assert cmd.filelist.files == ['README.manual'] + + assert list(clean_lines(cmd.manifest)) == ['README.manual'] + + archive_name = join(self.tmp_dir, 'dist', 'ns_fake_pkg-1.0.tar.gz') + archive = tarfile.open(archive_name) + try: + filenames = [tarinfo.name for tarinfo in archive] + finally: + archive.close() + assert sorted(filenames) == [ + 'ns_fake_pkg-1.0', + 'ns_fake_pkg-1.0/PKG-INFO', + 'ns_fake_pkg-1.0/README.manual', + ] + + @pytest.mark.usefixtures('needs_zlib') + @require_unix_id + @require_uid_0 + @pytest.mark.skipif("not shutil.which('tar')") + @pytest.mark.skipif("not shutil.which('gzip')") + def test_make_distribution_owner_group(self): + # now building a sdist + dist, cmd = self.get_cmd() + + # creating a gztar and specifying the owner+group + cmd.formats = ['gztar'] + cmd.owner = pwd.getpwuid(0)[0] + cmd.group = grp.getgrgid(0)[0] + cmd.ensure_finalized() + cmd.run() + + # making sure we have the good rights + archive_name = join(self.tmp_dir, 'dist', 'ns_fake_pkg-1.0.tar.gz') + archive = tarfile.open(archive_name) + try: + for member in archive.getmembers(): + assert member.uid == 0 + assert member.gid == 0 + finally: + archive.close() + + # building a sdist again + dist, cmd = self.get_cmd() + + # creating a gztar + cmd.formats = ['gztar'] + cmd.ensure_finalized() + cmd.run() + + # making sure we have the good rights + archive_name = join(self.tmp_dir, 'dist', 'ns_fake_pkg-1.0.tar.gz') + archive = tarfile.open(archive_name) + + # note that we are not testing the group ownership here + # because, depending on the platforms and the container + # rights (see #7408) + try: + for member in archive.getmembers(): + assert member.uid == os.getuid() + finally: + archive.close() diff --git a/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_spawn.py b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_spawn.py new file mode 100644 index 0000000000000000000000000000000000000000..3b9fc926f6ffc41673630fbf5775e6f4ad638b18 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_spawn.py @@ -0,0 +1,141 @@ +"""Tests for distutils.spawn.""" + +import os +import stat +import sys +import unittest.mock as mock +from distutils.errors import DistutilsExecError +from distutils.spawn import find_executable, spawn +from distutils.tests import support + +import path +import pytest +from test.support import unix_shell + +from .compat import py39 as os_helper + + +class TestSpawn(support.TempdirManager): + @pytest.mark.skipif("os.name not in ('nt', 'posix')") + def test_spawn(self): + tmpdir = self.mkdtemp() + + # creating something executable + # through the shell that returns 1 + if sys.platform != 'win32': + exe = os.path.join(tmpdir, 'foo.sh') + self.write_file(exe, f'#!{unix_shell}\nexit 1') + else: + exe = os.path.join(tmpdir, 'foo.bat') + self.write_file(exe, 'exit 1') + + os.chmod(exe, 0o777) + with pytest.raises(DistutilsExecError): + spawn([exe]) + + # now something that works + if sys.platform != 'win32': + exe = os.path.join(tmpdir, 'foo.sh') + self.write_file(exe, f'#!{unix_shell}\nexit 0') + else: + exe = os.path.join(tmpdir, 'foo.bat') + self.write_file(exe, 'exit 0') + + os.chmod(exe, 0o777) + spawn([exe]) # should work without any error + + def test_find_executable(self, tmp_path): + program_path = self._make_executable(tmp_path, '.exe') + program = program_path.name + program_noeext = program_path.with_suffix('').name + filename = str(program_path) + tmp_dir = path.Path(tmp_path) + + # test path parameter + rv = find_executable(program, path=tmp_dir) + assert rv == filename + + if sys.platform == 'win32': + # test without ".exe" extension + rv = find_executable(program_noeext, path=tmp_dir) + assert rv == filename + + # test find in the current directory + with tmp_dir: + rv = find_executable(program) + assert rv == program + + # test non-existent program + dont_exist_program = "dontexist_" + program + rv = find_executable(dont_exist_program, path=tmp_dir) + assert rv is None + + # PATH='': no match, except in the current directory + with os_helper.EnvironmentVarGuard() as env: + env['PATH'] = '' + with ( + mock.patch( + 'distutils.spawn.os.confstr', return_value=tmp_dir, create=True + ), + mock.patch('distutils.spawn.os.defpath', tmp_dir), + ): + rv = find_executable(program) + assert rv is None + + # look in current directory + with tmp_dir: + rv = find_executable(program) + assert rv == program + + # PATH=':': explicitly looks in the current directory + with os_helper.EnvironmentVarGuard() as env: + env['PATH'] = os.pathsep + with ( + mock.patch('distutils.spawn.os.confstr', return_value='', create=True), + mock.patch('distutils.spawn.os.defpath', ''), + ): + rv = find_executable(program) + assert rv is None + + # look in current directory + with tmp_dir: + rv = find_executable(program) + assert rv == program + + # missing PATH: test os.confstr("CS_PATH") and os.defpath + with os_helper.EnvironmentVarGuard() as env: + env.pop('PATH', None) + + # without confstr + with ( + mock.patch( + 'distutils.spawn.os.confstr', side_effect=ValueError, create=True + ), + mock.patch('distutils.spawn.os.defpath', tmp_dir), + ): + rv = find_executable(program) + assert rv == filename + + # with confstr + with ( + mock.patch( + 'distutils.spawn.os.confstr', return_value=tmp_dir, create=True + ), + mock.patch('distutils.spawn.os.defpath', ''), + ): + rv = find_executable(program) + assert rv == filename + + @staticmethod + def _make_executable(tmp_path, ext): + # Give the temporary program a suffix regardless of platform. + # It's needed on Windows and not harmful on others. + program = tmp_path.joinpath('program').with_suffix(ext) + program.write_text("", encoding='utf-8') + program.chmod(stat.S_IXUSR) + return program + + def test_spawn_missing_exe(self): + with pytest.raises(DistutilsExecError) as ctx: + spawn(['does-not-exist']) + assert "command 'does-not-exist' failed" in str(ctx.value) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_sysconfig.py b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_sysconfig.py new file mode 100644 index 0000000000000000000000000000000000000000..43d77c23fad426be237b9f91a6d98d7c36233d84 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_sysconfig.py @@ -0,0 +1,319 @@ +"""Tests for distutils.sysconfig.""" + +import contextlib +import distutils +import os +import pathlib +import subprocess +import sys +from distutils import sysconfig +from distutils.ccompiler import new_compiler # noqa: F401 +from distutils.unixccompiler import UnixCCompiler + +import jaraco.envs +import path +import pytest +from jaraco.text import trim +from test.support import swap_item + + +def _gen_makefile(root, contents): + jaraco.path.build({'Makefile': trim(contents)}, root) + return root / 'Makefile' + + +@pytest.mark.usefixtures('save_env') +class TestSysconfig: + def test_get_config_h_filename(self): + config_h = sysconfig.get_config_h_filename() + assert os.path.isfile(config_h) + + @pytest.mark.skipif("platform.system() == 'Windows'") + @pytest.mark.skipif("sys.implementation.name != 'cpython'") + def test_get_makefile_filename(self): + makefile = sysconfig.get_makefile_filename() + assert os.path.isfile(makefile) + + def test_get_python_lib(self, tmp_path): + assert sysconfig.get_python_lib() != sysconfig.get_python_lib(prefix=tmp_path) + + def test_get_config_vars(self): + cvars = sysconfig.get_config_vars() + assert isinstance(cvars, dict) + assert cvars + + @pytest.mark.skipif('sysconfig.IS_PYPY') + @pytest.mark.skipif('sysconfig.python_build') + @pytest.mark.xfail('platform.system() == "Windows"') + def test_srcdir_simple(self): + # See #15364. + srcdir = pathlib.Path(sysconfig.get_config_var('srcdir')) + + assert srcdir.absolute() + assert srcdir.is_dir() + + makefile = pathlib.Path(sysconfig.get_makefile_filename()) + assert makefile.parent.samefile(srcdir) + + @pytest.mark.skipif('sysconfig.IS_PYPY') + @pytest.mark.skipif('not sysconfig.python_build') + def test_srcdir_python_build(self): + # See #15364. + srcdir = pathlib.Path(sysconfig.get_config_var('srcdir')) + + # The python executable has not been installed so srcdir + # should be a full source checkout. + Python_h = srcdir.joinpath('Include', 'Python.h') + assert Python_h.is_file() + assert sysconfig._is_python_source_dir(srcdir) + assert sysconfig._is_python_source_dir(str(srcdir)) + + def test_srcdir_independent_of_cwd(self): + """ + srcdir should be independent of the current working directory + """ + # See #15364. + srcdir = sysconfig.get_config_var('srcdir') + with path.Path('..'): + srcdir2 = sysconfig.get_config_var('srcdir') + assert srcdir == srcdir2 + + def customize_compiler(self): + # make sure AR gets caught + class compiler: + compiler_type = 'unix' + executables = UnixCCompiler.executables + + def __init__(self): + self.exes = {} + + def set_executables(self, **kw): + for k, v in kw.items(): + self.exes[k] = v + + sysconfig_vars = { + 'AR': 'sc_ar', + 'CC': 'sc_cc', + 'CXX': 'sc_cxx', + 'ARFLAGS': '--sc-arflags', + 'CFLAGS': '--sc-cflags', + 'CCSHARED': '--sc-ccshared', + 'LDSHARED': 'sc_ldshared', + 'SHLIB_SUFFIX': 'sc_shutil_suffix', + } + + comp = compiler() + with contextlib.ExitStack() as cm: + for key, value in sysconfig_vars.items(): + cm.enter_context(swap_item(sysconfig._config_vars, key, value)) + sysconfig.customize_compiler(comp) + + return comp + + @pytest.mark.skipif("not isinstance(new_compiler(), UnixCCompiler)") + @pytest.mark.usefixtures('disable_macos_customization') + def test_customize_compiler(self): + # Make sure that sysconfig._config_vars is initialized + sysconfig.get_config_vars() + + os.environ['AR'] = 'env_ar' + os.environ['CC'] = 'env_cc' + os.environ['CPP'] = 'env_cpp' + os.environ['CXX'] = 'env_cxx --env-cxx-flags' + os.environ['LDSHARED'] = 'env_ldshared' + os.environ['LDFLAGS'] = '--env-ldflags' + os.environ['ARFLAGS'] = '--env-arflags' + os.environ['CFLAGS'] = '--env-cflags' + os.environ['CPPFLAGS'] = '--env-cppflags' + os.environ['RANLIB'] = 'env_ranlib' + + comp = self.customize_compiler() + assert comp.exes['archiver'] == 'env_ar --env-arflags' + assert comp.exes['preprocessor'] == 'env_cpp --env-cppflags' + assert comp.exes['compiler'] == 'env_cc --env-cflags --env-cppflags' + assert comp.exes['compiler_so'] == ( + 'env_cc --env-cflags --env-cppflags --sc-ccshared' + ) + assert ( + comp.exes['compiler_cxx'] + == 'env_cxx --env-cxx-flags --sc-cflags --env-cppflags' + ) + assert comp.exes['linker_exe'] == 'env_cc' + assert comp.exes['linker_so'] == ( + 'env_ldshared --env-ldflags --env-cflags --env-cppflags' + ) + assert comp.shared_lib_extension == 'sc_shutil_suffix' + + if sys.platform == "darwin": + assert comp.exes['ranlib'] == 'env_ranlib' + else: + assert 'ranlib' not in comp.exes + + del os.environ['AR'] + del os.environ['CC'] + del os.environ['CPP'] + del os.environ['CXX'] + del os.environ['LDSHARED'] + del os.environ['LDFLAGS'] + del os.environ['ARFLAGS'] + del os.environ['CFLAGS'] + del os.environ['CPPFLAGS'] + del os.environ['RANLIB'] + + comp = self.customize_compiler() + assert comp.exes['archiver'] == 'sc_ar --sc-arflags' + assert comp.exes['preprocessor'] == 'sc_cc -E' + assert comp.exes['compiler'] == 'sc_cc --sc-cflags' + assert comp.exes['compiler_so'] == 'sc_cc --sc-cflags --sc-ccshared' + assert comp.exes['compiler_cxx'] == 'sc_cxx --sc-cflags' + assert comp.exes['linker_exe'] == 'sc_cc' + assert comp.exes['linker_so'] == 'sc_ldshared' + assert comp.shared_lib_extension == 'sc_shutil_suffix' + assert 'ranlib' not in comp.exes + + def test_parse_makefile_base(self, tmp_path): + makefile = _gen_makefile( + tmp_path, + """ + CONFIG_ARGS= '--arg1=optarg1' 'ENV=LIB' + VAR=$OTHER + OTHER=foo + """, + ) + d = sysconfig.parse_makefile(makefile) + assert d == {'CONFIG_ARGS': "'--arg1=optarg1' 'ENV=LIB'", 'OTHER': 'foo'} + + def test_parse_makefile_literal_dollar(self, tmp_path): + makefile = _gen_makefile( + tmp_path, + """ + CONFIG_ARGS= '--arg1=optarg1' 'ENV=\\$$LIB' + VAR=$OTHER + OTHER=foo + """, + ) + d = sysconfig.parse_makefile(makefile) + assert d == {'CONFIG_ARGS': r"'--arg1=optarg1' 'ENV=\$LIB'", 'OTHER': 'foo'} + + def test_sysconfig_module(self): + import sysconfig as global_sysconfig + + assert global_sysconfig.get_config_var('CFLAGS') == sysconfig.get_config_var( + 'CFLAGS' + ) + assert global_sysconfig.get_config_var('LDFLAGS') == sysconfig.get_config_var( + 'LDFLAGS' + ) + + # On macOS, binary installers support extension module building on + # various levels of the operating system with differing Xcode + # configurations, requiring customization of some of the + # compiler configuration directives to suit the environment on + # the installed machine. Some of these customizations may require + # running external programs and are thus deferred until needed by + # the first extension module build. Only + # the Distutils version of sysconfig is used for extension module + # builds, which happens earlier in the Distutils tests. This may + # cause the following tests to fail since no tests have caused + # the global version of sysconfig to call the customization yet. + # The solution for now is to simply skip this test in this case. + # The longer-term solution is to only have one version of sysconfig. + @pytest.mark.skipif("sysconfig.get_config_var('CUSTOMIZED_OSX_COMPILER')") + def test_sysconfig_compiler_vars(self): + import sysconfig as global_sysconfig + + if sysconfig.get_config_var('CUSTOMIZED_OSX_COMPILER'): + pytest.skip('compiler flags customized') + assert global_sysconfig.get_config_var('LDSHARED') == sysconfig.get_config_var( + 'LDSHARED' + ) + assert global_sysconfig.get_config_var('CC') == sysconfig.get_config_var('CC') + + @pytest.mark.skipif("not sysconfig.get_config_var('EXT_SUFFIX')") + def test_SO_deprecation(self): + with pytest.warns(DeprecationWarning): + sysconfig.get_config_var('SO') + + def test_customize_compiler_before_get_config_vars(self, tmp_path): + # Issue #21923: test that a Distribution compiler + # instance can be called without an explicit call to + # get_config_vars(). + jaraco.path.build( + { + 'file': trim(""" + from distutils.core import Distribution + config = Distribution().get_command_obj('config') + # try_compile may pass or it may fail if no compiler + # is found but it should not raise an exception. + rc = config.try_compile('int x;') + """) + }, + tmp_path, + ) + p = subprocess.Popen( + [sys.executable, tmp_path / 'file'], + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + universal_newlines=True, + encoding='utf-8', + ) + outs, errs = p.communicate() + assert 0 == p.returncode, "Subprocess failed: " + outs + + def test_parse_config_h(self): + config_h = sysconfig.get_config_h_filename() + input = {} + with open(config_h, encoding="utf-8") as f: + result = sysconfig.parse_config_h(f, g=input) + assert input is result + with open(config_h, encoding="utf-8") as f: + result = sysconfig.parse_config_h(f) + assert isinstance(result, dict) + + @pytest.mark.skipif("platform.system() != 'Windows'") + @pytest.mark.skipif("sys.implementation.name != 'cpython'") + def test_win_ext_suffix(self): + assert sysconfig.get_config_var("EXT_SUFFIX").endswith(".pyd") + assert sysconfig.get_config_var("EXT_SUFFIX") != ".pyd" + + @pytest.mark.skipif("platform.system() != 'Windows'") + @pytest.mark.skipif("sys.implementation.name != 'cpython'") + @pytest.mark.skipif( + '\\PCbuild\\'.casefold() not in sys.executable.casefold(), + reason='Need sys.executable to be in a source tree', + ) + def test_win_build_venv_from_source_tree(self, tmp_path): + """Ensure distutils.sysconfig detects venvs from source tree builds.""" + env = jaraco.envs.VEnv() + env.create_opts = env.clean_opts + env.root = tmp_path + env.ensure_env() + cmd = [ + env.exe(), + "-c", + "import distutils.sysconfig; print(distutils.sysconfig.python_build)", + ] + distutils_path = os.path.dirname(os.path.dirname(distutils.__file__)) + out = subprocess.check_output( + cmd, env={**os.environ, "PYTHONPATH": distutils_path} + ) + assert out == "True" + + def test_get_python_inc_missing_config_dir(self, monkeypatch): + """ + In portable Python installations, the sysconfig will be broken, + pointing to the directories where the installation was built and + not where it currently is. In this case, ensure that the missing + directory isn't used for get_python_inc. + + See pypa/distutils#178. + """ + + def override(name): + if name == 'INCLUDEPY': + return '/does-not-exist' + return sysconfig.get_config_var(name) + + monkeypatch.setattr(sysconfig, 'get_config_var', override) + + assert os.path.exists(sysconfig.get_python_inc()) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_text_file.py b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_text_file.py new file mode 100644 index 0000000000000000000000000000000000000000..f51115656135cd3f348a45d4a14f97eeee47fb98 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_text_file.py @@ -0,0 +1,127 @@ +"""Tests for distutils.text_file.""" + +from distutils.tests import support +from distutils.text_file import TextFile + +import jaraco.path +import path + +TEST_DATA = """# test file + +line 3 \\ +# intervening comment + continues on next line +""" + + +class TestTextFile(support.TempdirManager): + def test_class(self): + # old tests moved from text_file.__main__ + # so they are really called by the buildbots + + # result 1: no fancy options + result1 = [ + '# test file\n', + '\n', + 'line 3 \\\n', + '# intervening comment\n', + ' continues on next line\n', + ] + + # result 2: just strip comments + result2 = ["\n", "line 3 \\\n", " continues on next line\n"] + + # result 3: just strip blank lines + result3 = [ + "# test file\n", + "line 3 \\\n", + "# intervening comment\n", + " continues on next line\n", + ] + + # result 4: default, strip comments, blank lines, + # and trailing whitespace + result4 = ["line 3 \\", " continues on next line"] + + # result 5: strip comments and blanks, plus join lines (but don't + # "collapse" joined lines + result5 = ["line 3 continues on next line"] + + # result 6: strip comments and blanks, plus join lines (and + # "collapse" joined lines + result6 = ["line 3 continues on next line"] + + def test_input(count, description, file, expected_result): + result = file.readlines() + assert result == expected_result + + tmp_path = path.Path(self.mkdtemp()) + filename = tmp_path / 'test.txt' + jaraco.path.build({filename.name: TEST_DATA}, tmp_path) + + in_file = TextFile( + filename, + strip_comments=False, + skip_blanks=False, + lstrip_ws=False, + rstrip_ws=False, + ) + try: + test_input(1, "no processing", in_file, result1) + finally: + in_file.close() + + in_file = TextFile( + filename, + strip_comments=True, + skip_blanks=False, + lstrip_ws=False, + rstrip_ws=False, + ) + try: + test_input(2, "strip comments", in_file, result2) + finally: + in_file.close() + + in_file = TextFile( + filename, + strip_comments=False, + skip_blanks=True, + lstrip_ws=False, + rstrip_ws=False, + ) + try: + test_input(3, "strip blanks", in_file, result3) + finally: + in_file.close() + + in_file = TextFile(filename) + try: + test_input(4, "default processing", in_file, result4) + finally: + in_file.close() + + in_file = TextFile( + filename, + strip_comments=True, + skip_blanks=True, + join_lines=True, + rstrip_ws=True, + ) + try: + test_input(5, "join lines without collapsing", in_file, result5) + finally: + in_file.close() + + in_file = TextFile( + filename, + strip_comments=True, + skip_blanks=True, + join_lines=True, + rstrip_ws=True, + collapse_join=True, + ) + try: + test_input(6, "join lines with collapsing", in_file, result6) + finally: + in_file.close() diff --git a/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_util.py b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..00c9743ed0a2664039060ef149d30f165bf2f465 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_util.py @@ -0,0 +1,243 @@ +"""Tests for distutils.util.""" + +import email +import email.generator +import email.policy +import io +import os +import pathlib +import sys +import sysconfig as stdlib_sysconfig +import unittest.mock as mock +from copy import copy +from distutils import sysconfig, util +from distutils.errors import DistutilsByteCompileError, DistutilsPlatformError +from distutils.util import ( + byte_compile, + change_root, + check_environ, + convert_path, + get_host_platform, + get_platform, + grok_environment_error, + rfc822_escape, + split_quoted, + strtobool, +) + +import pytest + + +@pytest.fixture(autouse=True) +def environment(monkeypatch): + monkeypatch.setattr(os, 'name', os.name) + monkeypatch.setattr(sys, 'platform', sys.platform) + monkeypatch.setattr(sys, 'version', sys.version) + monkeypatch.setattr(os, 'sep', os.sep) + monkeypatch.setattr(os.path, 'join', os.path.join) + monkeypatch.setattr(os.path, 'isabs', os.path.isabs) + monkeypatch.setattr(os.path, 'splitdrive', os.path.splitdrive) + monkeypatch.setattr(sysconfig, '_config_vars', copy(sysconfig._config_vars)) + + +@pytest.mark.usefixtures('save_env') +class TestUtil: + def test_get_host_platform(self): + with mock.patch('os.name', 'nt'): + with mock.patch('sys.version', '... [... (ARM64)]'): + assert get_host_platform() == 'win-arm64' + with mock.patch('sys.version', '... [... (ARM)]'): + assert get_host_platform() == 'win-arm32' + + with mock.patch('sys.version_info', (3, 9, 0, 'final', 0)): + assert get_host_platform() == stdlib_sysconfig.get_platform() + + def test_get_platform(self): + with mock.patch('os.name', 'nt'): + with mock.patch.dict('os.environ', {'VSCMD_ARG_TGT_ARCH': 'x86'}): + assert get_platform() == 'win32' + with mock.patch.dict('os.environ', {'VSCMD_ARG_TGT_ARCH': 'x64'}): + assert get_platform() == 'win-amd64' + with mock.patch.dict('os.environ', {'VSCMD_ARG_TGT_ARCH': 'arm'}): + assert get_platform() == 'win-arm32' + with mock.patch.dict('os.environ', {'VSCMD_ARG_TGT_ARCH': 'arm64'}): + assert get_platform() == 'win-arm64' + + def test_convert_path(self): + expected = os.sep.join(('', 'home', 'to', 'my', 'stuff')) + assert convert_path('/home/to/my/stuff') == expected + assert convert_path(pathlib.Path('/home/to/my/stuff')) == expected + assert convert_path('.') == os.curdir + + def test_change_root(self): + # linux/mac + os.name = 'posix' + + def _isabs(path): + return path[0] == '/' + + os.path.isabs = _isabs + + def _join(*path): + return '/'.join(path) + + os.path.join = _join + + assert change_root('/root', '/old/its/here') == '/root/old/its/here' + assert change_root('/root', 'its/here') == '/root/its/here' + + # windows + os.name = 'nt' + os.sep = '\\' + + def _isabs(path): + return path.startswith('c:\\') + + os.path.isabs = _isabs + + def _splitdrive(path): + if path.startswith('c:'): + return ('', path.replace('c:', '')) + return ('', path) + + os.path.splitdrive = _splitdrive + + def _join(*path): + return '\\'.join(path) + + os.path.join = _join + + assert ( + change_root('c:\\root', 'c:\\old\\its\\here') == 'c:\\root\\old\\its\\here' + ) + assert change_root('c:\\root', 'its\\here') == 'c:\\root\\its\\here' + + # BugsBunny os (it's a great os) + os.name = 'BugsBunny' + with pytest.raises(DistutilsPlatformError): + change_root('c:\\root', 'its\\here') + + # XXX platforms to be covered: mac + + def test_check_environ(self): + util.check_environ.cache_clear() + os.environ.pop('HOME', None) + + check_environ() + + assert os.environ['PLAT'] == get_platform() + + @pytest.mark.skipif("os.name != 'posix'") + def test_check_environ_getpwuid(self): + util.check_environ.cache_clear() + os.environ.pop('HOME', None) + + import pwd + + # only set pw_dir field, other fields are not used + result = pwd.struct_passwd(( + None, + None, + None, + None, + None, + '/home/distutils', + None, + )) + with mock.patch.object(pwd, 'getpwuid', return_value=result): + check_environ() + assert os.environ['HOME'] == '/home/distutils' + + util.check_environ.cache_clear() + os.environ.pop('HOME', None) + + # bpo-10496: Catch pwd.getpwuid() error + with mock.patch.object(pwd, 'getpwuid', side_effect=KeyError): + check_environ() + assert 'HOME' not in os.environ + + def test_split_quoted(self): + assert split_quoted('""one"" "two" \'three\' \\four') == [ + 'one', + 'two', + 'three', + 'four', + ] + + def test_strtobool(self): + yes = ('y', 'Y', 'yes', 'True', 't', 'true', 'True', 'On', 'on', '1') + no = ('n', 'no', 'f', 'false', 'off', '0', 'Off', 'No', 'N') + + for y in yes: + assert strtobool(y) + + for n in no: + assert not strtobool(n) + + indent = 8 * ' ' + + @pytest.mark.parametrize( + "given,wanted", + [ + # 0x0b, 0x0c, ..., etc are also considered a line break by Python + ("hello\x0b\nworld\n", f"hello\x0b{indent}\n{indent}world\n{indent}"), + ("hello\x1eworld", f"hello\x1e{indent}world"), + ("", ""), + ( + "I am a\npoor\nlonesome\nheader\n", + f"I am a\n{indent}poor\n{indent}lonesome\n{indent}header\n{indent}", + ), + ], + ) + def test_rfc822_escape(self, given, wanted): + """ + We want to ensure a multi-line header parses correctly. + + For interoperability, the escaped value should also "round-trip" over + `email.generator.Generator.flatten` and `email.message_from_*` + (see pypa/setuptools#4033). + + The main issue is that internally `email.policy.EmailPolicy` uses + `splitlines` which will split on some control chars. If all the new lines + are not prefixed with spaces, the parser will interrupt reading + the current header and produce an incomplete value, while + incorrectly interpreting the rest of the headers as part of the payload. + """ + res = rfc822_escape(given) + + policy = email.policy.EmailPolicy( + utf8=True, + mangle_from_=False, + max_line_length=0, + ) + with io.StringIO() as buffer: + raw = f"header: {res}\nother-header: 42\n\npayload\n" + orig = email.message_from_string(raw) + email.generator.Generator(buffer, policy=policy).flatten(orig) + buffer.seek(0) + regen = email.message_from_file(buffer) + + for msg in (orig, regen): + assert msg.get_payload() == "payload\n" + assert msg["other-header"] == "42" + # Generator may replace control chars with `\n` + assert set(msg["header"].splitlines()) == set(res.splitlines()) + + assert res == wanted + + def test_dont_write_bytecode(self): + # makes sure byte_compile raise a DistutilsError + # if sys.dont_write_bytecode is True + old_dont_write_bytecode = sys.dont_write_bytecode + sys.dont_write_bytecode = True + try: + with pytest.raises(DistutilsByteCompileError): + byte_compile([]) + finally: + sys.dont_write_bytecode = old_dont_write_bytecode + + def test_grok_environment_error(self): + # test obsolete function to ensure backward compat (#4931) + exc = OSError("Unable to find batch file") + msg = grok_environment_error(exc) + assert msg == "error: Unable to find batch file" diff --git a/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_version.py b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_version.py new file mode 100644 index 0000000000000000000000000000000000000000..b68f0977249aa23aafbf31cf74a0e4127f777d05 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_version.py @@ -0,0 +1,80 @@ +"""Tests for distutils.version.""" + +import distutils +from distutils.version import LooseVersion, StrictVersion + +import pytest + + +@pytest.fixture(autouse=True) +def suppress_deprecation(): + with distutils.version.suppress_known_deprecation(): + yield + + +class TestVersion: + def test_prerelease(self): + version = StrictVersion('1.2.3a1') + assert version.version == (1, 2, 3) + assert version.prerelease == ('a', 1) + assert str(version) == '1.2.3a1' + + version = StrictVersion('1.2.0') + assert str(version) == '1.2' + + def test_cmp_strict(self): + versions = ( + ('1.5.1', '1.5.2b2', -1), + ('161', '3.10a', ValueError), + ('8.02', '8.02', 0), + ('3.4j', '1996.07.12', ValueError), + ('3.2.pl0', '3.1.1.6', ValueError), + ('2g6', '11g', ValueError), + ('0.9', '2.2', -1), + ('1.2.1', '1.2', 1), + ('1.1', '1.2.2', -1), + ('1.2', '1.1', 1), + ('1.2.1', '1.2.2', -1), + ('1.2.2', '1.2', 1), + ('1.2', '1.2.2', -1), + ('0.4.0', '0.4', 0), + ('1.13++', '5.5.kw', ValueError), + ) + + for v1, v2, wanted in versions: + try: + res = StrictVersion(v1)._cmp(StrictVersion(v2)) + except ValueError: + if wanted is ValueError: + continue + else: + raise AssertionError(f"cmp({v1}, {v2}) shouldn't raise ValueError") + assert res == wanted, f'cmp({v1}, {v2}) should be {wanted}, got {res}' + res = StrictVersion(v1)._cmp(v2) + assert res == wanted, f'cmp({v1}, {v2}) should be {wanted}, got {res}' + res = StrictVersion(v1)._cmp(object()) + assert res is NotImplemented, ( + f'cmp({v1}, {v2}) should be NotImplemented, got {res}' + ) + + def test_cmp(self): + versions = ( + ('1.5.1', '1.5.2b2', -1), + ('161', '3.10a', 1), + ('8.02', '8.02', 0), + ('3.4j', '1996.07.12', -1), + ('3.2.pl0', '3.1.1.6', 1), + ('2g6', '11g', -1), + ('0.960923', '2.2beta29', -1), + ('1.13++', '5.5.kw', -1), + ) + + for v1, v2, wanted in versions: + res = LooseVersion(v1)._cmp(LooseVersion(v2)) + assert res == wanted, f'cmp({v1}, {v2}) should be {wanted}, got {res}' + res = LooseVersion(v1)._cmp(v2) + assert res == wanted, f'cmp({v1}, {v2}) should be {wanted}, got {res}' + res = LooseVersion(v1)._cmp(object()) + assert res is NotImplemented, ( + f'cmp({v1}, {v2}) should be NotImplemented, got {res}' + ) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_versionpredicate.py b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/test_versionpredicate.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/unix_compat.py b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/unix_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..a5d9ee45ccc639794d29ba0a5fd24f781ee5ecf5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_distutils/tests/unix_compat.py @@ -0,0 +1,17 @@ +import sys + +try: + import grp + import pwd +except ImportError: + grp = pwd = None + +import pytest + +UNIX_ID_SUPPORT = grp and pwd +UID_0_SUPPORT = UNIX_ID_SUPPORT and sys.platform != "cygwin" + +require_unix_id = pytest.mark.skipif( + not UNIX_ID_SUPPORT, reason="Requires grp and pwd support" +) +require_uid_0 = pytest.mark.skipif(not UID_0_SUPPORT, reason="Requires UID 0 support") diff --git a/.venv/lib/python3.12/site-packages/setuptools/_distutils/text_file.py b/.venv/lib/python3.12/site-packages/setuptools/_distutils/text_file.py new file mode 100644 index 0000000000000000000000000000000000000000..89d9048d5902950516c3541ad212bff7b6cb2045 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_distutils/text_file.py @@ -0,0 +1,286 @@ +"""text_file + +provides the TextFile class, which gives an interface to text files +that (optionally) takes care of stripping comments, ignoring blank +lines, and joining lines with backslashes.""" + +import sys + + +class TextFile: + """Provides a file-like object that takes care of all the things you + commonly want to do when processing a text file that has some + line-by-line syntax: strip comments (as long as "#" is your + comment character), skip blank lines, join adjacent lines by + escaping the newline (ie. backslash at end of line), strip + leading and/or trailing whitespace. All of these are optional + and independently controllable. + + Provides a 'warn()' method so you can generate warning messages that + report physical line number, even if the logical line in question + spans multiple physical lines. Also provides 'unreadline()' for + implementing line-at-a-time lookahead. + + Constructor is called as: + + TextFile (filename=None, file=None, **options) + + It bombs (RuntimeError) if both 'filename' and 'file' are None; + 'filename' should be a string, and 'file' a file object (or + something that provides 'readline()' and 'close()' methods). It is + recommended that you supply at least 'filename', so that TextFile + can include it in warning messages. If 'file' is not supplied, + TextFile creates its own using 'io.open()'. + + The options are all boolean, and affect the value returned by + 'readline()': + strip_comments [default: true] + strip from "#" to end-of-line, as well as any whitespace + leading up to the "#" -- unless it is escaped by a backslash + lstrip_ws [default: false] + strip leading whitespace from each line before returning it + rstrip_ws [default: true] + strip trailing whitespace (including line terminator!) from + each line before returning it + skip_blanks [default: true} + skip lines that are empty *after* stripping comments and + whitespace. (If both lstrip_ws and rstrip_ws are false, + then some lines may consist of solely whitespace: these will + *not* be skipped, even if 'skip_blanks' is true.) + join_lines [default: false] + if a backslash is the last non-newline character on a line + after stripping comments and whitespace, join the following line + to it to form one "logical line"; if N consecutive lines end + with a backslash, then N+1 physical lines will be joined to + form one logical line. + collapse_join [default: false] + strip leading whitespace from lines that are joined to their + predecessor; only matters if (join_lines and not lstrip_ws) + errors [default: 'strict'] + error handler used to decode the file content + + Note that since 'rstrip_ws' can strip the trailing newline, the + semantics of 'readline()' must differ from those of the builtin file + object's 'readline()' method! In particular, 'readline()' returns + None for end-of-file: an empty string might just be a blank line (or + an all-whitespace line), if 'rstrip_ws' is true but 'skip_blanks' is + not.""" + + default_options = { + 'strip_comments': 1, + 'skip_blanks': 1, + 'lstrip_ws': 0, + 'rstrip_ws': 1, + 'join_lines': 0, + 'collapse_join': 0, + 'errors': 'strict', + } + + def __init__(self, filename=None, file=None, **options): + """Construct a new TextFile object. At least one of 'filename' + (a string) and 'file' (a file-like object) must be supplied. + They keyword argument options are described above and affect + the values returned by 'readline()'.""" + if filename is None and file is None: + raise RuntimeError( + "you must supply either or both of 'filename' and 'file'" + ) + + # set values for all options -- either from client option hash + # or fallback to default_options + for opt in self.default_options.keys(): + if opt in options: + setattr(self, opt, options[opt]) + else: + setattr(self, opt, self.default_options[opt]) + + # sanity check client option hash + for opt in options.keys(): + if opt not in self.default_options: + raise KeyError(f"invalid TextFile option '{opt}'") + + if file is None: + self.open(filename) + else: + self.filename = filename + self.file = file + self.current_line = 0 # assuming that file is at BOF! + + # 'linebuf' is a stack of lines that will be emptied before we + # actually read from the file; it's only populated by an + # 'unreadline()' operation + self.linebuf = [] + + def open(self, filename): + """Open a new file named 'filename'. This overrides both the + 'filename' and 'file' arguments to the constructor.""" + self.filename = filename + self.file = open(self.filename, errors=self.errors, encoding='utf-8') + self.current_line = 0 + + def close(self): + """Close the current file and forget everything we know about it + (filename, current line number).""" + file = self.file + self.file = None + self.filename = None + self.current_line = None + file.close() + + def gen_error(self, msg, line=None): + outmsg = [] + if line is None: + line = self.current_line + outmsg.append(self.filename + ", ") + if isinstance(line, (list, tuple)): + outmsg.append("lines {}-{}: ".format(*line)) + else: + outmsg.append(f"line {int(line)}: ") + outmsg.append(str(msg)) + return "".join(outmsg) + + def error(self, msg, line=None): + raise ValueError("error: " + self.gen_error(msg, line)) + + def warn(self, msg, line=None): + """Print (to stderr) a warning message tied to the current logical + line in the current file. If the current logical line in the + file spans multiple physical lines, the warning refers to the + whole range, eg. "lines 3-5". If 'line' supplied, it overrides + the current line number; it may be a list or tuple to indicate a + range of physical lines, or an integer for a single physical + line.""" + sys.stderr.write("warning: " + self.gen_error(msg, line) + "\n") + + def readline(self): # noqa: C901 + """Read and return a single logical line from the current file (or + from an internal buffer if lines have previously been "unread" + with 'unreadline()'). If the 'join_lines' option is true, this + may involve reading multiple physical lines concatenated into a + single string. Updates the current line number, so calling + 'warn()' after 'readline()' emits a warning about the physical + line(s) just read. Returns None on end-of-file, since the empty + string can occur if 'rstrip_ws' is true but 'strip_blanks' is + not.""" + # If any "unread" lines waiting in 'linebuf', return the top + # one. (We don't actually buffer read-ahead data -- lines only + # get put in 'linebuf' if the client explicitly does an + # 'unreadline()'. + if self.linebuf: + line = self.linebuf[-1] + del self.linebuf[-1] + return line + + buildup_line = '' + + while True: + # read the line, make it None if EOF + line = self.file.readline() + if line == '': + line = None + + if self.strip_comments and line: + # Look for the first "#" in the line. If none, never + # mind. If we find one and it's the first character, or + # is not preceded by "\", then it starts a comment -- + # strip the comment, strip whitespace before it, and + # carry on. Otherwise, it's just an escaped "#", so + # unescape it (and any other escaped "#"'s that might be + # lurking in there) and otherwise leave the line alone. + + pos = line.find("#") + if pos == -1: # no "#" -- no comments + pass + + # It's definitely a comment -- either "#" is the first + # character, or it's elsewhere and unescaped. + elif pos == 0 or line[pos - 1] != "\\": + # Have to preserve the trailing newline, because it's + # the job of a later step (rstrip_ws) to remove it -- + # and if rstrip_ws is false, we'd better preserve it! + # (NB. this means that if the final line is all comment + # and has no trailing newline, we will think that it's + # EOF; I think that's OK.) + eol = (line[-1] == '\n') and '\n' or '' + line = line[0:pos] + eol + + # If all that's left is whitespace, then skip line + # *now*, before we try to join it to 'buildup_line' -- + # that way constructs like + # hello \\ + # # comment that should be ignored + # there + # result in "hello there". + if line.strip() == "": + continue + else: # it's an escaped "#" + line = line.replace("\\#", "#") + + # did previous line end with a backslash? then accumulate + if self.join_lines and buildup_line: + # oops: end of file + if line is None: + self.warn("continuation line immediately precedes end-of-file") + return buildup_line + + if self.collapse_join: + line = line.lstrip() + line = buildup_line + line + + # careful: pay attention to line number when incrementing it + if isinstance(self.current_line, list): + self.current_line[1] = self.current_line[1] + 1 + else: + self.current_line = [self.current_line, self.current_line + 1] + # just an ordinary line, read it as usual + else: + if line is None: # eof + return None + + # still have to be careful about incrementing the line number! + if isinstance(self.current_line, list): + self.current_line = self.current_line[1] + 1 + else: + self.current_line = self.current_line + 1 + + # strip whitespace however the client wants (leading and + # trailing, or one or the other, or neither) + if self.lstrip_ws and self.rstrip_ws: + line = line.strip() + elif self.lstrip_ws: + line = line.lstrip() + elif self.rstrip_ws: + line = line.rstrip() + + # blank line (whether we rstrip'ed or not)? skip to next line + # if appropriate + if line in ('', '\n') and self.skip_blanks: + continue + + if self.join_lines: + if line[-1] == '\\': + buildup_line = line[:-1] + continue + + if line[-2:] == '\\\n': + buildup_line = line[0:-2] + '\n' + continue + + # well, I guess there's some actual content there: return it + return line + + def readlines(self): + """Read and return the list of all logical lines remaining in the + current file.""" + lines = [] + while True: + line = self.readline() + if line is None: + return lines + lines.append(line) + + def unreadline(self, line): + """Push 'line' (a string) onto an internal buffer that will be + checked by future 'readline()' calls. Handy for implementing + a parser with line-at-a-time lookahead.""" + self.linebuf.append(line) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_distutils/unixccompiler.py b/.venv/lib/python3.12/site-packages/setuptools/_distutils/unixccompiler.py new file mode 100644 index 0000000000000000000000000000000000000000..20b8ce6b9bba21bd709b77249bdcae5b4119e9ca --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_distutils/unixccompiler.py @@ -0,0 +1,9 @@ +import importlib + +from .compilers.C import unix + +UnixCCompiler = unix.Compiler + +# ensure import of unixccompiler implies ccompiler imported +# (pypa/setuptools#4871) +importlib.import_module('distutils.ccompiler') diff --git a/.venv/lib/python3.12/site-packages/setuptools/_distutils/util.py b/.venv/lib/python3.12/site-packages/setuptools/_distutils/util.py new file mode 100644 index 0000000000000000000000000000000000000000..6dbe049f4274f7177295491d7f433e8ca303df48 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_distutils/util.py @@ -0,0 +1,518 @@ +"""distutils.util + +Miscellaneous utility functions -- anything that doesn't fit into +one of the other *util.py modules. +""" + +from __future__ import annotations + +import functools +import importlib.util +import os +import pathlib +import re +import string +import subprocess +import sys +import sysconfig +import tempfile +from collections.abc import Callable, Iterable, Mapping +from typing import TYPE_CHECKING, AnyStr + +from jaraco.functools import pass_none + +from ._log import log +from ._modified import newer +from .errors import DistutilsByteCompileError, DistutilsPlatformError +from .spawn import spawn + +if TYPE_CHECKING: + from typing_extensions import TypeVarTuple, Unpack + + _Ts = TypeVarTuple("_Ts") + + +def get_host_platform() -> str: + """ + Return a string that identifies the current platform. Use this + function to distinguish platform-specific build directories and + platform-specific built distributions. + """ + + # This function initially exposed platforms as defined in Python 3.9 + # even with older Python versions when distutils was split out. + # Now it delegates to stdlib sysconfig. + + return sysconfig.get_platform() + + +def get_platform() -> str: + if os.name == 'nt': + TARGET_TO_PLAT = { + 'x86': 'win32', + 'x64': 'win-amd64', + 'arm': 'win-arm32', + 'arm64': 'win-arm64', + } + target = os.environ.get('VSCMD_ARG_TGT_ARCH') + return TARGET_TO_PLAT.get(target) or get_host_platform() + return get_host_platform() + + +if sys.platform == 'darwin': + _syscfg_macosx_ver = None # cache the version pulled from sysconfig +MACOSX_VERSION_VAR = 'MACOSX_DEPLOYMENT_TARGET' + + +def _clear_cached_macosx_ver(): + """For testing only. Do not call.""" + global _syscfg_macosx_ver + _syscfg_macosx_ver = None + + +def get_macosx_target_ver_from_syscfg(): + """Get the version of macOS latched in the Python interpreter configuration. + Returns the version as a string or None if can't obtain one. Cached.""" + global _syscfg_macosx_ver + if _syscfg_macosx_ver is None: + from distutils import sysconfig + + ver = sysconfig.get_config_var(MACOSX_VERSION_VAR) or '' + if ver: + _syscfg_macosx_ver = ver + return _syscfg_macosx_ver + + +def get_macosx_target_ver(): + """Return the version of macOS for which we are building. + + The target version defaults to the version in sysconfig latched at time + the Python interpreter was built, unless overridden by an environment + variable. If neither source has a value, then None is returned""" + + syscfg_ver = get_macosx_target_ver_from_syscfg() + env_ver = os.environ.get(MACOSX_VERSION_VAR) + + if env_ver: + # Validate overridden version against sysconfig version, if have both. + # Ensure that the deployment target of the build process is not less + # than 10.3 if the interpreter was built for 10.3 or later. This + # ensures extension modules are built with correct compatibility + # values, specifically LDSHARED which can use + # '-undefined dynamic_lookup' which only works on >= 10.3. + if ( + syscfg_ver + and split_version(syscfg_ver) >= [10, 3] + and split_version(env_ver) < [10, 3] + ): + my_msg = ( + '$' + MACOSX_VERSION_VAR + ' mismatch: ' + f'now "{env_ver}" but "{syscfg_ver}" during configure; ' + 'must use 10.3 or later' + ) + raise DistutilsPlatformError(my_msg) + return env_ver + return syscfg_ver + + +def split_version(s: str) -> list[int]: + """Convert a dot-separated string into a list of numbers for comparisons""" + return [int(n) for n in s.split('.')] + + +@pass_none +def convert_path(pathname: str | os.PathLike[str]) -> str: + r""" + Allow for pathlib.Path inputs, coax to a native path string. + + If None is passed, will just pass it through as + Setuptools relies on this behavior. + + >>> convert_path(None) is None + True + + Removes empty paths. + + >>> convert_path('foo/./bar').replace('\\', '/') + 'foo/bar' + """ + return os.fspath(pathlib.PurePath(pathname)) + + +def change_root( + new_root: AnyStr | os.PathLike[AnyStr], pathname: AnyStr | os.PathLike[AnyStr] +) -> AnyStr: + """Return 'pathname' with 'new_root' prepended. If 'pathname' is + relative, this is equivalent to "os.path.join(new_root,pathname)". + Otherwise, it requires making 'pathname' relative and then joining the + two, which is tricky on DOS/Windows and Mac OS. + """ + if os.name == 'posix': + if not os.path.isabs(pathname): + return os.path.join(new_root, pathname) + else: + return os.path.join(new_root, pathname[1:]) + + elif os.name == 'nt': + (drive, path) = os.path.splitdrive(pathname) + if path[0] == os.sep: + path = path[1:] + return os.path.join(new_root, path) + + raise DistutilsPlatformError(f"nothing known about platform '{os.name}'") + + +@functools.lru_cache +def check_environ() -> None: + """Ensure that 'os.environ' has all the environment variables we + guarantee that users can use in config files, command-line options, + etc. Currently this includes: + HOME - user's home directory (Unix only) + PLAT - description of the current platform, including hardware + and OS (see 'get_platform()') + """ + if os.name == 'posix' and 'HOME' not in os.environ: + try: + import pwd + + os.environ['HOME'] = pwd.getpwuid(os.getuid())[5] + except (ImportError, KeyError): + # bpo-10496: if the current user identifier doesn't exist in the + # password database, do nothing + pass + + if 'PLAT' not in os.environ: + os.environ['PLAT'] = get_platform() + + +def subst_vars(s, local_vars: Mapping[str, object]) -> str: + """ + Perform variable substitution on 'string'. + Variables are indicated by format-style braces ("{var}"). + Variable is substituted by the value found in the 'local_vars' + dictionary or in 'os.environ' if it's not in 'local_vars'. + 'os.environ' is first checked/augmented to guarantee that it contains + certain values: see 'check_environ()'. Raise ValueError for any + variables not found in either 'local_vars' or 'os.environ'. + """ + check_environ() + lookup = dict(os.environ) + lookup.update((name, str(value)) for name, value in local_vars.items()) + try: + return _subst_compat(s).format_map(lookup) + except KeyError as var: + raise ValueError(f"invalid variable {var}") + + +def _subst_compat(s): + """ + Replace shell/Perl-style variable substitution with + format-style. For compatibility. + """ + + def _subst(match): + return f'{{{match.group(1)}}}' + + repl = re.sub(r'\$([a-zA-Z_][a-zA-Z_0-9]*)', _subst, s) + if repl != s: + import warnings + + warnings.warn( + "shell/Perl-style substitutions are deprecated", + DeprecationWarning, + ) + return repl + + +def grok_environment_error(exc: object, prefix: str = "error: ") -> str: + # Function kept for backward compatibility. + # Used to try clever things with EnvironmentErrors, + # but nowadays str(exception) produces good messages. + return prefix + str(exc) + + +# Needed by 'split_quoted()' +_wordchars_re = _squote_re = _dquote_re = None + + +def _init_regex(): + global _wordchars_re, _squote_re, _dquote_re + _wordchars_re = re.compile(rf'[^\\\'\"{string.whitespace} ]*') + _squote_re = re.compile(r"'(?:[^'\\]|\\.)*'") + _dquote_re = re.compile(r'"(?:[^"\\]|\\.)*"') + + +def split_quoted(s: str) -> list[str]: + """Split a string up according to Unix shell-like rules for quotes and + backslashes. In short: words are delimited by spaces, as long as those + spaces are not escaped by a backslash, or inside a quoted string. + Single and double quotes are equivalent, and the quote characters can + be backslash-escaped. The backslash is stripped from any two-character + escape sequence, leaving only the escaped character. The quote + characters are stripped from any quoted string. Returns a list of + words. + """ + + # This is a nice algorithm for splitting up a single string, since it + # doesn't require character-by-character examination. It was a little + # bit of a brain-bender to get it working right, though... + if _wordchars_re is None: + _init_regex() + + s = s.strip() + words = [] + pos = 0 + + while s: + m = _wordchars_re.match(s, pos) + end = m.end() + if end == len(s): + words.append(s[:end]) + break + + if s[end] in string.whitespace: + # unescaped, unquoted whitespace: now + # we definitely have a word delimiter + words.append(s[:end]) + s = s[end:].lstrip() + pos = 0 + + elif s[end] == '\\': + # preserve whatever is being escaped; + # will become part of the current word + s = s[:end] + s[end + 1 :] + pos = end + 1 + + else: + if s[end] == "'": # slurp singly-quoted string + m = _squote_re.match(s, end) + elif s[end] == '"': # slurp doubly-quoted string + m = _dquote_re.match(s, end) + else: + raise RuntimeError(f"this can't happen (bad char '{s[end]}')") + + if m is None: + raise ValueError(f"bad string (mismatched {s[end]} quotes?)") + + (beg, end) = m.span() + s = s[:beg] + s[beg + 1 : end - 1] + s[end:] + pos = m.end() - 2 + + if pos >= len(s): + words.append(s) + break + + return words + + +# split_quoted () + + +def execute( + func: Callable[[Unpack[_Ts]], object], + args: tuple[Unpack[_Ts]], + msg: object = None, + verbose: bool = False, + dry_run: bool = False, +) -> None: + """ + Perform some action that affects the outside world (e.g. by + writing to the filesystem). Such actions are special because they + are disabled by the 'dry_run' flag. This method handles that + complication; simply supply the + function to call and an argument tuple for it (to embody the + "external action" being performed) and an optional message to + emit. + """ + if msg is None: + msg = f"{func.__name__}{args!r}" + if msg[-2:] == ',)': # correct for singleton tuple + msg = msg[0:-2] + ')' + + log.info(msg) + if not dry_run: + func(*args) + + +def strtobool(val: str) -> bool: + """Convert a string representation of truth to true (1) or false (0). + + True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values + are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if + 'val' is anything else. + """ + val = val.lower() + if val in ('y', 'yes', 't', 'true', 'on', '1'): + return True + elif val in ('n', 'no', 'f', 'false', 'off', '0'): + return False + else: + raise ValueError(f"invalid truth value {val!r}") + + +def byte_compile( # noqa: C901 + py_files: Iterable[str], + optimize: int = 0, + force: bool = False, + prefix: str | None = None, + base_dir: str | None = None, + verbose: bool = True, + dry_run: bool = False, + direct: bool | None = None, +) -> None: + """Byte-compile a collection of Python source files to .pyc + files in a __pycache__ subdirectory. 'py_files' is a list + of files to compile; any files that don't end in ".py" are silently + skipped. 'optimize' must be one of the following: + 0 - don't optimize + 1 - normal optimization (like "python -O") + 2 - extra optimization (like "python -OO") + If 'force' is true, all files are recompiled regardless of + timestamps. + + The source filename encoded in each bytecode file defaults to the + filenames listed in 'py_files'; you can modify these with 'prefix' and + 'basedir'. 'prefix' is a string that will be stripped off of each + source filename, and 'base_dir' is a directory name that will be + prepended (after 'prefix' is stripped). You can supply either or both + (or neither) of 'prefix' and 'base_dir', as you wish. + + If 'dry_run' is true, doesn't actually do anything that would + affect the filesystem. + + Byte-compilation is either done directly in this interpreter process + with the standard py_compile module, or indirectly by writing a + temporary script and executing it. Normally, you should let + 'byte_compile()' figure out to use direct compilation or not (see + the source for details). The 'direct' flag is used by the script + generated in indirect mode; unless you know what you're doing, leave + it set to None. + """ + + # nothing is done if sys.dont_write_bytecode is True + if sys.dont_write_bytecode: + raise DistutilsByteCompileError('byte-compiling is disabled.') + + # First, if the caller didn't force us into direct or indirect mode, + # figure out which mode we should be in. We take a conservative + # approach: choose direct mode *only* if the current interpreter is + # in debug mode and optimize is 0. If we're not in debug mode (-O + # or -OO), we don't know which level of optimization this + # interpreter is running with, so we can't do direct + # byte-compilation and be certain that it's the right thing. Thus, + # always compile indirectly if the current interpreter is in either + # optimize mode, or if either optimization level was requested by + # the caller. + if direct is None: + direct = __debug__ and optimize == 0 + + # "Indirect" byte-compilation: write a temporary script and then + # run it with the appropriate flags. + if not direct: + (script_fd, script_name) = tempfile.mkstemp(".py") + log.info("writing byte-compilation script '%s'", script_name) + if not dry_run: + script = os.fdopen(script_fd, "w", encoding='utf-8') + + with script: + script.write( + """\ +from distutils.util import byte_compile +files = [ +""" + ) + + # XXX would be nice to write absolute filenames, just for + # safety's sake (script should be more robust in the face of + # chdir'ing before running it). But this requires abspath'ing + # 'prefix' as well, and that breaks the hack in build_lib's + # 'byte_compile()' method that carefully tacks on a trailing + # slash (os.sep really) to make sure the prefix here is "just + # right". This whole prefix business is rather delicate -- the + # problem is that it's really a directory, but I'm treating it + # as a dumb string, so trailing slashes and so forth matter. + + script.write(",\n".join(map(repr, py_files)) + "]\n") + script.write( + f""" +byte_compile(files, optimize={optimize!r}, force={force!r}, + prefix={prefix!r}, base_dir={base_dir!r}, + verbose={verbose!r}, dry_run=False, + direct=True) +""" + ) + + cmd = [sys.executable] + cmd.extend(subprocess._optim_args_from_interpreter_flags()) + cmd.append(script_name) + spawn(cmd, dry_run=dry_run) + execute(os.remove, (script_name,), f"removing {script_name}", dry_run=dry_run) + + # "Direct" byte-compilation: use the py_compile module to compile + # right here, right now. Note that the script generated in indirect + # mode simply calls 'byte_compile()' in direct mode, a weird sort of + # cross-process recursion. Hey, it works! + else: + from py_compile import compile + + for file in py_files: + if file[-3:] != ".py": + # This lets us be lazy and not filter filenames in + # the "install_lib" command. + continue + + # Terminology from the py_compile module: + # cfile - byte-compiled file + # dfile - purported source filename (same as 'file' by default) + if optimize >= 0: + opt = '' if optimize == 0 else optimize + cfile = importlib.util.cache_from_source(file, optimization=opt) + else: + cfile = importlib.util.cache_from_source(file) + dfile = file + if prefix: + if file[: len(prefix)] != prefix: + raise ValueError( + f"invalid prefix: filename {file!r} doesn't start with {prefix!r}" + ) + dfile = dfile[len(prefix) :] + if base_dir: + dfile = os.path.join(base_dir, dfile) + + cfile_base = os.path.basename(cfile) + if direct: + if force or newer(file, cfile): + log.info("byte-compiling %s to %s", file, cfile_base) + if not dry_run: + compile(file, cfile, dfile) + else: + log.debug("skipping byte-compilation of %s to %s", file, cfile_base) + + +def rfc822_escape(header: str) -> str: + """Return a version of the string escaped for inclusion in an + RFC-822 header, by ensuring there are 8 spaces space after each newline. + """ + indent = 8 * " " + lines = header.splitlines(keepends=True) + + # Emulate the behaviour of `str.split` + # (the terminal line break in `splitlines` does not result in an extra line): + ends_in_newline = lines and lines[-1].splitlines()[0] != lines[-1] + suffix = indent if ends_in_newline else "" + + return indent.join(lines) + suffix + + +def is_mingw() -> bool: + """Returns True if the current platform is mingw. + + Python compiled with Mingw-w64 has sys.platform == 'win32' and + get_platform() starts with 'mingw'. + """ + return sys.platform == 'win32' and get_platform().startswith('mingw') + + +def is_freethreaded(): + """Return True if the Python interpreter is built with free threading support.""" + return bool(sysconfig.get_config_var('Py_GIL_DISABLED')) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_distutils/version.py b/.venv/lib/python3.12/site-packages/setuptools/_distutils/version.py new file mode 100644 index 0000000000000000000000000000000000000000..2223ee9c8cab2495034a57d4585625feb81a8330 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_distutils/version.py @@ -0,0 +1,348 @@ +# +# distutils/version.py +# +# Implements multiple version numbering conventions for the +# Python Module Distribution Utilities. +# +# $Id$ +# + +"""Provides classes to represent module version numbers (one class for +each style of version numbering). There are currently two such classes +implemented: StrictVersion and LooseVersion. + +Every version number class implements the following interface: + * the 'parse' method takes a string and parses it to some internal + representation; if the string is an invalid version number, + 'parse' raises a ValueError exception + * the class constructor takes an optional string argument which, + if supplied, is passed to 'parse' + * __str__ reconstructs the string that was passed to 'parse' (or + an equivalent string -- ie. one that will generate an equivalent + version number instance) + * __repr__ generates Python code to recreate the version number instance + * _cmp compares the current instance with either another instance + of the same class or a string (which will be parsed to an instance + of the same class, thus must follow the same rules) +""" + +import contextlib +import re +import warnings + + +@contextlib.contextmanager +def suppress_known_deprecation(): + with warnings.catch_warnings(record=True) as ctx: + warnings.filterwarnings( + action='default', + category=DeprecationWarning, + message="distutils Version classes are deprecated.", + ) + yield ctx + + +class Version: + """Abstract base class for version numbering classes. Just provides + constructor (__init__) and reproducer (__repr__), because those + seem to be the same for all version numbering classes; and route + rich comparisons to _cmp. + """ + + def __init__(self, vstring=None): + if vstring: + self.parse(vstring) + warnings.warn( + "distutils Version classes are deprecated. Use packaging.version instead.", + DeprecationWarning, + stacklevel=2, + ) + + def __repr__(self): + return f"{self.__class__.__name__} ('{self}')" + + def __eq__(self, other): + c = self._cmp(other) + if c is NotImplemented: + return c + return c == 0 + + def __lt__(self, other): + c = self._cmp(other) + if c is NotImplemented: + return c + return c < 0 + + def __le__(self, other): + c = self._cmp(other) + if c is NotImplemented: + return c + return c <= 0 + + def __gt__(self, other): + c = self._cmp(other) + if c is NotImplemented: + return c + return c > 0 + + def __ge__(self, other): + c = self._cmp(other) + if c is NotImplemented: + return c + return c >= 0 + + +# Interface for version-number classes -- must be implemented +# by the following classes (the concrete ones -- Version should +# be treated as an abstract class). +# __init__ (string) - create and take same action as 'parse' +# (string parameter is optional) +# parse (string) - convert a string representation to whatever +# internal representation is appropriate for +# this style of version numbering +# __str__ (self) - convert back to a string; should be very similar +# (if not identical to) the string supplied to parse +# __repr__ (self) - generate Python code to recreate +# the instance +# _cmp (self, other) - compare two version numbers ('other' may +# be an unparsed version string, or another +# instance of your version class) + + +class StrictVersion(Version): + """Version numbering for anal retentives and software idealists. + Implements the standard interface for version number classes as + described above. A version number consists of two or three + dot-separated numeric components, with an optional "pre-release" tag + on the end. The pre-release tag consists of the letter 'a' or 'b' + followed by a number. If the numeric components of two version + numbers are equal, then one with a pre-release tag will always + be deemed earlier (lesser) than one without. + + The following are valid version numbers (shown in the order that + would be obtained by sorting according to the supplied cmp function): + + 0.4 0.4.0 (these two are equivalent) + 0.4.1 + 0.5a1 + 0.5b3 + 0.5 + 0.9.6 + 1.0 + 1.0.4a3 + 1.0.4b1 + 1.0.4 + + The following are examples of invalid version numbers: + + 1 + 2.7.2.2 + 1.3.a4 + 1.3pl1 + 1.3c4 + + The rationale for this version numbering system will be explained + in the distutils documentation. + """ + + version_re = re.compile( + r'^(\d+) \. (\d+) (\. (\d+))? ([ab](\d+))?$', re.VERBOSE | re.ASCII + ) + + def parse(self, vstring): + match = self.version_re.match(vstring) + if not match: + raise ValueError(f"invalid version number '{vstring}'") + + (major, minor, patch, prerelease, prerelease_num) = match.group(1, 2, 4, 5, 6) + + if patch: + self.version = tuple(map(int, [major, minor, patch])) + else: + self.version = tuple(map(int, [major, minor])) + (0,) + + if prerelease: + self.prerelease = (prerelease[0], int(prerelease_num)) + else: + self.prerelease = None + + def __str__(self): + if self.version[2] == 0: + vstring = '.'.join(map(str, self.version[0:2])) + else: + vstring = '.'.join(map(str, self.version)) + + if self.prerelease: + vstring = vstring + self.prerelease[0] + str(self.prerelease[1]) + + return vstring + + def _cmp(self, other): + if isinstance(other, str): + with suppress_known_deprecation(): + other = StrictVersion(other) + elif not isinstance(other, StrictVersion): + return NotImplemented + + if self.version == other.version: + # versions match; pre-release drives the comparison + return self._cmp_prerelease(other) + + return -1 if self.version < other.version else 1 + + def _cmp_prerelease(self, other): + """ + case 1: self has prerelease, other doesn't; other is greater + case 2: self doesn't have prerelease, other does: self is greater + case 3: both or neither have prerelease: compare them! + """ + if self.prerelease and not other.prerelease: + return -1 + elif not self.prerelease and other.prerelease: + return 1 + + if self.prerelease == other.prerelease: + return 0 + elif self.prerelease < other.prerelease: + return -1 + else: + return 1 + + +# end class StrictVersion + + +# The rules according to Greg Stein: +# 1) a version number has 1 or more numbers separated by a period or by +# sequences of letters. If only periods, then these are compared +# left-to-right to determine an ordering. +# 2) sequences of letters are part of the tuple for comparison and are +# compared lexicographically +# 3) recognize the numeric components may have leading zeroes +# +# The LooseVersion class below implements these rules: a version number +# string is split up into a tuple of integer and string components, and +# comparison is a simple tuple comparison. This means that version +# numbers behave in a predictable and obvious way, but a way that might +# not necessarily be how people *want* version numbers to behave. There +# wouldn't be a problem if people could stick to purely numeric version +# numbers: just split on period and compare the numbers as tuples. +# However, people insist on putting letters into their version numbers; +# the most common purpose seems to be: +# - indicating a "pre-release" version +# ('alpha', 'beta', 'a', 'b', 'pre', 'p') +# - indicating a post-release patch ('p', 'pl', 'patch') +# but of course this can't cover all version number schemes, and there's +# no way to know what a programmer means without asking him. +# +# The problem is what to do with letters (and other non-numeric +# characters) in a version number. The current implementation does the +# obvious and predictable thing: keep them as strings and compare +# lexically within a tuple comparison. This has the desired effect if +# an appended letter sequence implies something "post-release": +# eg. "0.99" < "0.99pl14" < "1.0", and "5.001" < "5.001m" < "5.002". +# +# However, if letters in a version number imply a pre-release version, +# the "obvious" thing isn't correct. Eg. you would expect that +# "1.5.1" < "1.5.2a2" < "1.5.2", but under the tuple/lexical comparison +# implemented here, this just isn't so. +# +# Two possible solutions come to mind. The first is to tie the +# comparison algorithm to a particular set of semantic rules, as has +# been done in the StrictVersion class above. This works great as long +# as everyone can go along with bondage and discipline. Hopefully a +# (large) subset of Python module programmers will agree that the +# particular flavour of bondage and discipline provided by StrictVersion +# provides enough benefit to be worth using, and will submit their +# version numbering scheme to its domination. The free-thinking +# anarchists in the lot will never give in, though, and something needs +# to be done to accommodate them. +# +# Perhaps a "moderately strict" version class could be implemented that +# lets almost anything slide (syntactically), and makes some heuristic +# assumptions about non-digits in version number strings. This could +# sink into special-case-hell, though; if I was as talented and +# idiosyncratic as Larry Wall, I'd go ahead and implement a class that +# somehow knows that "1.2.1" < "1.2.2a2" < "1.2.2" < "1.2.2pl3", and is +# just as happy dealing with things like "2g6" and "1.13++". I don't +# think I'm smart enough to do it right though. +# +# In any case, I've coded the test suite for this module (see +# ../test/test_version.py) specifically to fail on things like comparing +# "1.2a2" and "1.2". That's not because the *code* is doing anything +# wrong, it's because the simple, obvious design doesn't match my +# complicated, hairy expectations for real-world version numbers. It +# would be a snap to fix the test suite to say, "Yep, LooseVersion does +# the Right Thing" (ie. the code matches the conception). But I'd rather +# have a conception that matches common notions about version numbers. + + +class LooseVersion(Version): + """Version numbering for anarchists and software realists. + Implements the standard interface for version number classes as + described above. A version number consists of a series of numbers, + separated by either periods or strings of letters. When comparing + version numbers, the numeric components will be compared + numerically, and the alphabetic components lexically. The following + are all valid version numbers, in no particular order: + + 1.5.1 + 1.5.2b2 + 161 + 3.10a + 8.02 + 3.4j + 1996.07.12 + 3.2.pl0 + 3.1.1.6 + 2g6 + 11g + 0.960923 + 2.2beta29 + 1.13++ + 5.5.kw + 2.0b1pl0 + + In fact, there is no such thing as an invalid version number under + this scheme; the rules for comparison are simple and predictable, + but may not always give the results you want (for some definition + of "want"). + """ + + component_re = re.compile(r'(\d+ | [a-z]+ | \.)', re.VERBOSE) + + def parse(self, vstring): + # I've given up on thinking I can reconstruct the version string + # from the parsed tuple -- so I just store the string here for + # use by __str__ + self.vstring = vstring + components = [x for x in self.component_re.split(vstring) if x and x != '.'] + for i, obj in enumerate(components): + try: + components[i] = int(obj) + except ValueError: + pass + + self.version = components + + def __str__(self): + return self.vstring + + def __repr__(self): + return f"LooseVersion ('{self}')" + + def _cmp(self, other): + if isinstance(other, str): + other = LooseVersion(other) + elif not isinstance(other, LooseVersion): + return NotImplemented + + if self.version == other.version: + return 0 + if self.version < other.version: + return -1 + if self.version > other.version: + return 1 + + +# end class LooseVersion diff --git a/.venv/lib/python3.12/site-packages/setuptools/_distutils/versionpredicate.py b/.venv/lib/python3.12/site-packages/setuptools/_distutils/versionpredicate.py new file mode 100644 index 0000000000000000000000000000000000000000..fe31b0ed8ef843080ea64df9f58a398d317434ad --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_distutils/versionpredicate.py @@ -0,0 +1,175 @@ +"""Module for parsing and testing package version predicate strings.""" + +import operator +import re + +from . import version + +re_validPackage = re.compile(r"(?i)^\s*([a-z_]\w*(?:\.[a-z_]\w*)*)(.*)", re.ASCII) +# (package) (rest) + +re_paren = re.compile(r"^\s*\((.*)\)\s*$") # (list) inside of parentheses +re_splitComparison = re.compile(r"^\s*(<=|>=|<|>|!=|==)\s*([^\s,]+)\s*$") +# (comp) (version) + + +def splitUp(pred): + """Parse a single version comparison. + + Return (comparison string, StrictVersion) + """ + res = re_splitComparison.match(pred) + if not res: + raise ValueError(f"bad package restriction syntax: {pred!r}") + comp, verStr = res.groups() + with version.suppress_known_deprecation(): + other = version.StrictVersion(verStr) + return (comp, other) + + +compmap = { + "<": operator.lt, + "<=": operator.le, + "==": operator.eq, + ">": operator.gt, + ">=": operator.ge, + "!=": operator.ne, +} + + +class VersionPredicate: + """Parse and test package version predicates. + + >>> v = VersionPredicate('pyepat.abc (>1.0, <3333.3a1, !=1555.1b3)') + + The `name` attribute provides the full dotted name that is given:: + + >>> v.name + 'pyepat.abc' + + The str() of a `VersionPredicate` provides a normalized + human-readable version of the expression:: + + >>> print(v) + pyepat.abc (> 1.0, < 3333.3a1, != 1555.1b3) + + The `satisfied_by()` method can be used to determine with a given + version number is included in the set described by the version + restrictions:: + + >>> v.satisfied_by('1.1') + True + >>> v.satisfied_by('1.4') + True + >>> v.satisfied_by('1.0') + False + >>> v.satisfied_by('4444.4') + False + >>> v.satisfied_by('1555.1b3') + False + + `VersionPredicate` is flexible in accepting extra whitespace:: + + >>> v = VersionPredicate(' pat( == 0.1 ) ') + >>> v.name + 'pat' + >>> v.satisfied_by('0.1') + True + >>> v.satisfied_by('0.2') + False + + If any version numbers passed in do not conform to the + restrictions of `StrictVersion`, a `ValueError` is raised:: + + >>> v = VersionPredicate('p1.p2.p3.p4(>=1.0, <=1.3a1, !=1.2zb3)') + Traceback (most recent call last): + ... + ValueError: invalid version number '1.2zb3' + + It the module or package name given does not conform to what's + allowed as a legal module or package name, `ValueError` is + raised:: + + >>> v = VersionPredicate('foo-bar') + Traceback (most recent call last): + ... + ValueError: expected parenthesized list: '-bar' + + >>> v = VersionPredicate('foo bar (12.21)') + Traceback (most recent call last): + ... + ValueError: expected parenthesized list: 'bar (12.21)' + + """ + + def __init__(self, versionPredicateStr): + """Parse a version predicate string.""" + # Fields: + # name: package name + # pred: list of (comparison string, StrictVersion) + + versionPredicateStr = versionPredicateStr.strip() + if not versionPredicateStr: + raise ValueError("empty package restriction") + match = re_validPackage.match(versionPredicateStr) + if not match: + raise ValueError(f"bad package name in {versionPredicateStr!r}") + self.name, paren = match.groups() + paren = paren.strip() + if paren: + match = re_paren.match(paren) + if not match: + raise ValueError(f"expected parenthesized list: {paren!r}") + str = match.groups()[0] + self.pred = [splitUp(aPred) for aPred in str.split(",")] + if not self.pred: + raise ValueError(f"empty parenthesized list in {versionPredicateStr!r}") + else: + self.pred = [] + + def __str__(self): + if self.pred: + seq = [cond + " " + str(ver) for cond, ver in self.pred] + return self.name + " (" + ", ".join(seq) + ")" + else: + return self.name + + def satisfied_by(self, version): + """True if version is compatible with all the predicates in self. + The parameter version must be acceptable to the StrictVersion + constructor. It may be either a string or StrictVersion. + """ + for cond, ver in self.pred: + if not compmap[cond](version, ver): + return False + return True + + +_provision_rx = None + + +def split_provision(value): + """Return the name and optional version number of a provision. + + The version number, if given, will be returned as a `StrictVersion` + instance, otherwise it will be `None`. + + >>> split_provision('mypkg') + ('mypkg', None) + >>> split_provision(' mypkg( 1.2 ) ') + ('mypkg', StrictVersion ('1.2')) + """ + global _provision_rx + if _provision_rx is None: + _provision_rx = re.compile( + r"([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*)(?:\s*\(\s*([^)\s]+)\s*\))?$", re.ASCII + ) + value = value.strip() + m = _provision_rx.match(value) + if not m: + raise ValueError(f"illegal provides specification: {value!r}") + ver = m.group(2) or None + if ver: + with version.suppress_known_deprecation(): + ver = version.StrictVersion(ver) + return m.group(1), ver diff --git a/.venv/lib/python3.12/site-packages/setuptools/_distutils/zosccompiler.py b/.venv/lib/python3.12/site-packages/setuptools/_distutils/zosccompiler.py new file mode 100644 index 0000000000000000000000000000000000000000..e49630ac6ed8cad62c4d2ff8361758519e6dc83b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_distutils/zosccompiler.py @@ -0,0 +1,3 @@ +from .compilers.C import zos + +zOSCCompiler = zos.Compiler diff --git a/.venv/lib/python3.12/site-packages/setuptools/_entry_points.py b/.venv/lib/python3.12/site-packages/setuptools/_entry_points.py new file mode 100644 index 0000000000000000000000000000000000000000..e785fc7df8d51241a38675902fe5e5b78a0cc29c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_entry_points.py @@ -0,0 +1,90 @@ +import functools +import itertools +import operator + +from jaraco.functools import pass_none +from jaraco.text import yield_lines +from more_itertools import consume + +from ._importlib import metadata +from ._itertools import ensure_unique +from .errors import OptionError + + +def ensure_valid(ep): + """ + Exercise one of the dynamic properties to trigger + the pattern match. + """ + try: + ep.extras + except (AttributeError, AssertionError) as ex: + # Why both? See https://github.com/python/importlib_metadata/issues/488 + msg = ( + f"Problems to parse {ep}.\nPlease ensure entry-point follows the spec: " + "https://packaging.python.org/en/latest/specifications/entry-points/" + ) + raise OptionError(msg) from ex + + +def load_group(value, group): + """ + Given a value of an entry point or series of entry points, + return each as an EntryPoint. + """ + # normalize to a single sequence of lines + lines = yield_lines(value) + text = f'[{group}]\n' + '\n'.join(lines) + return metadata.EntryPoints._from_text(text) + + +def by_group_and_name(ep): + return ep.group, ep.name + + +def validate(eps: metadata.EntryPoints): + """ + Ensure entry points are unique by group and name and validate each. + """ + consume(map(ensure_valid, ensure_unique(eps, key=by_group_and_name))) + return eps + + +@functools.singledispatch +def load(eps): + """ + Given a Distribution.entry_points, produce EntryPoints. + """ + groups = itertools.chain.from_iterable( + load_group(value, group) for group, value in eps.items() + ) + return validate(metadata.EntryPoints(groups)) + + +@load.register(str) +def _(eps): + r""" + >>> ep, = load('[console_scripts]\nfoo=bar') + >>> ep.group + 'console_scripts' + >>> ep.name + 'foo' + >>> ep.value + 'bar' + """ + return validate(metadata.EntryPoints(metadata.EntryPoints._from_text(eps))) + + +load.register(type(None), lambda x: x) + + +@pass_none +def render(eps: metadata.EntryPoints): + by_group = operator.attrgetter('group') + groups = itertools.groupby(sorted(eps, key=by_group), by_group) + + return '\n'.join(f'[{group}]\n{render_items(items)}\n' for group, items in groups) + + +def render_items(eps): + return '\n'.join(f'{ep.name} = {ep.value}' for ep in sorted(eps)) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_imp.py b/.venv/lib/python3.12/site-packages/setuptools/_imp.py new file mode 100644 index 0000000000000000000000000000000000000000..f1d9f29218987d4f830f2d57aca9e3f74d00a095 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_imp.py @@ -0,0 +1,87 @@ +""" +Re-implementation of find_module and get_frozen_object +from the deprecated imp module. +""" + +import importlib.machinery +import importlib.util +import os +import tokenize +from importlib.util import module_from_spec + +PY_SOURCE = 1 +PY_COMPILED = 2 +C_EXTENSION = 3 +C_BUILTIN = 6 +PY_FROZEN = 7 + + +def find_spec(module, paths): + finder = ( + importlib.machinery.PathFinder().find_spec + if isinstance(paths, list) + else importlib.util.find_spec + ) + return finder(module, paths) + + +def find_module(module, paths=None): + """Just like 'imp.find_module()', but with package support""" + spec = find_spec(module, paths) + if spec is None: + raise ImportError(f"Can't find {module}") + if not spec.has_location and hasattr(spec, 'submodule_search_locations'): + spec = importlib.util.spec_from_loader('__init__.py', spec.loader) + + kind = -1 + file = None + static = isinstance(spec.loader, type) + if ( + spec.origin == 'frozen' + or static + and issubclass(spec.loader, importlib.machinery.FrozenImporter) + ): + kind = PY_FROZEN + path = None # imp compabilty + suffix = mode = '' # imp compatibility + elif ( + spec.origin == 'built-in' + or static + and issubclass(spec.loader, importlib.machinery.BuiltinImporter) + ): + kind = C_BUILTIN + path = None # imp compabilty + suffix = mode = '' # imp compatibility + elif spec.has_location: + path = spec.origin + suffix = os.path.splitext(path)[1] + mode = 'r' if suffix in importlib.machinery.SOURCE_SUFFIXES else 'rb' + + if suffix in importlib.machinery.SOURCE_SUFFIXES: + kind = PY_SOURCE + file = tokenize.open(path) + elif suffix in importlib.machinery.BYTECODE_SUFFIXES: + kind = PY_COMPILED + file = open(path, 'rb') + elif suffix in importlib.machinery.EXTENSION_SUFFIXES: + kind = C_EXTENSION + + else: + path = None + suffix = mode = '' + + return file, path, (suffix, mode, kind) + + +def get_frozen_object(module, paths=None): + spec = find_spec(module, paths) + if not spec: + raise ImportError(f"Can't find {module}") + return spec.loader.get_code(module) + + +def get_module(module, paths, info): + spec = find_spec(module, paths) + if not spec: + raise ImportError(f"Can't find {module}") + return module_from_spec(spec) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_importlib.py b/.venv/lib/python3.12/site-packages/setuptools/_importlib.py new file mode 100644 index 0000000000000000000000000000000000000000..ce0fd52653b56c9c2cb2b2c7bfb35e3ec3c61408 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_importlib.py @@ -0,0 +1,9 @@ +import sys + +if sys.version_info < (3, 10): + import importlib_metadata as metadata # pragma: no cover +else: + import importlib.metadata as metadata # noqa: F401 + + +import importlib.resources as resources # noqa: F401 diff --git a/.venv/lib/python3.12/site-packages/setuptools/_itertools.py b/.venv/lib/python3.12/site-packages/setuptools/_itertools.py new file mode 100644 index 0000000000000000000000000000000000000000..d6ca841353ce39ac4361013f5c8160d69028d0d8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_itertools.py @@ -0,0 +1,23 @@ +from more_itertools import consume # noqa: F401 + + +# copied from jaraco.itertools 6.1 +def ensure_unique(iterable, key=lambda x: x): + """ + Wrap an iterable to raise a ValueError if non-unique values are encountered. + + >>> list(ensure_unique('abc')) + ['a', 'b', 'c'] + >>> consume(ensure_unique('abca')) + Traceback (most recent call last): + ... + ValueError: Duplicate element 'a' encountered. + """ + seen = set() + seen_add = seen.add + for element in iterable: + k = key(element) + if k in seen: + raise ValueError(f"Duplicate element {element!r} encountered.") + seen_add(k) + yield element diff --git a/.venv/lib/python3.12/site-packages/setuptools/_normalization.py b/.venv/lib/python3.12/site-packages/setuptools/_normalization.py new file mode 100644 index 0000000000000000000000000000000000000000..0937a4faf8cf2358ed1ec8a4f12b8260e493fd24 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_normalization.py @@ -0,0 +1,179 @@ +""" +Helpers for normalization as expected in wheel/sdist/module file names +and core metadata +""" + +import re +from typing import TYPE_CHECKING + +import packaging + +# https://packaging.python.org/en/latest/specifications/core-metadata/#name +_VALID_NAME = re.compile(r"^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$", re.I) +_UNSAFE_NAME_CHARS = re.compile(r"[^A-Z0-9._-]+", re.I) +_NON_ALPHANUMERIC = re.compile(r"[^A-Z0-9]+", re.I) +_PEP440_FALLBACK = re.compile(r"^v?(?P(?:[0-9]+!)?[0-9]+(?:\.[0-9]+)*)", re.I) + + +def safe_identifier(name: str) -> str: + """Make a string safe to be used as Python identifier. + >>> safe_identifier("12abc") + '_12abc' + >>> safe_identifier("__editable__.myns.pkg-78.9.3_local") + '__editable___myns_pkg_78_9_3_local' + """ + safe = re.sub(r'\W|^(?=\d)', '_', name) + assert safe.isidentifier() + return safe + + +def safe_name(component: str) -> str: + """Escape a component used as a project name according to Core Metadata. + >>> safe_name("hello world") + 'hello-world' + >>> safe_name("hello?world") + 'hello-world' + >>> safe_name("hello_world") + 'hello_world' + """ + # See pkg_resources.safe_name + return _UNSAFE_NAME_CHARS.sub("-", component) + + +def safe_version(version: str) -> str: + """Convert an arbitrary string into a valid version string. + Can still raise an ``InvalidVersion`` exception. + To avoid exceptions use ``best_effort_version``. + >>> safe_version("1988 12 25") + '1988.12.25' + >>> safe_version("v0.2.1") + '0.2.1' + >>> safe_version("v0.2?beta") + '0.2b0' + >>> safe_version("v0.2 beta") + '0.2b0' + >>> safe_version("ubuntu lts") + Traceback (most recent call last): + ... + packaging.version.InvalidVersion: Invalid version: 'ubuntu.lts' + """ + v = version.replace(' ', '.') + try: + return str(packaging.version.Version(v)) + except packaging.version.InvalidVersion: + attempt = _UNSAFE_NAME_CHARS.sub("-", v) + return str(packaging.version.Version(attempt)) + + +def best_effort_version(version: str) -> str: + """Convert an arbitrary string into a version-like string. + Fallback when ``safe_version`` is not safe enough. + >>> best_effort_version("v0.2 beta") + '0.2b0' + >>> best_effort_version("ubuntu lts") + '0.dev0+sanitized.ubuntu.lts' + >>> best_effort_version("0.23ubuntu1") + '0.23.dev0+sanitized.ubuntu1' + >>> best_effort_version("0.23-") + '0.23.dev0+sanitized' + >>> best_effort_version("0.-_") + '0.dev0+sanitized' + >>> best_effort_version("42.+?1") + '42.dev0+sanitized.1' + """ + # See pkg_resources._forgiving_version + try: + return safe_version(version) + except packaging.version.InvalidVersion: + v = version.replace(' ', '.') + match = _PEP440_FALLBACK.search(v) + if match: + safe = match["safe"] + rest = v[len(safe) :] + else: + safe = "0" + rest = version + safe_rest = _NON_ALPHANUMERIC.sub(".", rest).strip(".") + local = f"sanitized.{safe_rest}".strip(".") + return safe_version(f"{safe}.dev0+{local}") + + +def safe_extra(extra: str) -> str: + """Normalize extra name according to PEP 685 + >>> safe_extra("_FrIeNdLy-._.-bArD") + 'friendly-bard' + >>> safe_extra("FrIeNdLy-._.-bArD__._-") + 'friendly-bard' + """ + return _NON_ALPHANUMERIC.sub("-", extra).strip("-").lower() + + +def filename_component(value: str) -> str: + """Normalize each component of a filename (e.g. distribution/version part of wheel) + Note: ``value`` needs to be already normalized. + >>> filename_component("my-pkg") + 'my_pkg' + """ + return value.replace("-", "_").strip("_") + + +def filename_component_broken(value: str) -> str: + """ + Produce the incorrect filename component for compatibility. + + See pypa/setuptools#4167 for detailed analysis. + + TODO: replace this with filename_component after pip 24 is + nearly-ubiquitous. + + >>> filename_component_broken('foo_bar-baz') + 'foo-bar-baz' + """ + return value.replace('_', '-') + + +def safer_name(value: str) -> str: + """Like ``safe_name`` but can be used as filename component for wheel""" + # See bdist_wheel.safer_name + return ( + # Per https://packaging.python.org/en/latest/specifications/name-normalization/#name-normalization + re.sub(r"[-_.]+", "-", safe_name(value)) + .lower() + # Per https://packaging.python.org/en/latest/specifications/binary-distribution-format/#escaping-and-unicode + .replace("-", "_") + ) + + +def safer_best_effort_version(value: str) -> str: + """Like ``best_effort_version`` but can be used as filename component for wheel""" + # See bdist_wheel.safer_verion + # TODO: Replace with only safe_version in the future (no need for best effort) + return filename_component(best_effort_version(value)) + + +def _missing_canonicalize_license_expression(expression: str) -> str: + """ + Defer import error to affect only users that actually use it + https://github.com/pypa/setuptools/issues/4894 + >>> _missing_canonicalize_license_expression("a OR b") + Traceback (most recent call last): + ... + ImportError: ...Cannot import `packaging.licenses`... + """ + raise ImportError( + "Cannot import `packaging.licenses`." + """ + Setuptools>=77.0.0 requires "packaging>=24.2" to work properly. + Please make sure you have a suitable version installed. + """ + ) + + +try: + from packaging.licenses import ( + canonicalize_license_expression as _canonicalize_license_expression, + ) +except ImportError: # pragma: nocover + if not TYPE_CHECKING: + # XXX: pyright is still upset even with # pyright: ignore[reportAssignmentType] + _canonicalize_license_expression = _missing_canonicalize_license_expression diff --git a/.venv/lib/python3.12/site-packages/setuptools/_path.py b/.venv/lib/python3.12/site-packages/setuptools/_path.py new file mode 100644 index 0000000000000000000000000000000000000000..0d99b0f539ff5f819b167013c48726180cd83d49 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_path.py @@ -0,0 +1,84 @@ +from __future__ import annotations + +import contextlib +import os +import sys +from typing import TYPE_CHECKING, TypeVar, Union + +from more_itertools import unique_everseen + +if TYPE_CHECKING: + from typing_extensions import TypeAlias + +StrPath: TypeAlias = Union[str, os.PathLike[str]] # Same as _typeshed.StrPath +StrPathT = TypeVar("StrPathT", bound=Union[str, os.PathLike[str]]) + + +def ensure_directory(path): + """Ensure that the parent directory of `path` exists""" + dirname = os.path.dirname(path) + os.makedirs(dirname, exist_ok=True) + + +def same_path(p1: StrPath, p2: StrPath) -> bool: + """Differs from os.path.samefile because it does not require paths to exist. + Purely string based (no comparison between i-nodes). + >>> same_path("a/b", "./a/b") + True + >>> same_path("a/b", "a/./b") + True + >>> same_path("a/b", "././a/b") + True + >>> same_path("a/b", "./a/b/c/..") + True + >>> same_path("a/b", "../a/b/c") + False + >>> same_path("a", "a/b") + False + """ + return normpath(p1) == normpath(p2) + + +def normpath(filename: StrPath) -> str: + """Normalize a file/dir name for comparison purposes.""" + # See pkg_resources.normalize_path for notes about cygwin + file = os.path.abspath(filename) if sys.platform == 'cygwin' else filename + return os.path.normcase(os.path.realpath(os.path.normpath(file))) + + +@contextlib.contextmanager +def paths_on_pythonpath(paths): + """ + Add the indicated paths to the head of the PYTHONPATH environment + variable so that subprocesses will also see the packages at + these paths. + + Do this in a context that restores the value on exit. + + >>> getfixture('monkeypatch').setenv('PYTHONPATH', 'anything') + >>> with paths_on_pythonpath(['foo', 'bar']): + ... assert 'foo' in os.environ['PYTHONPATH'] + ... assert 'anything' in os.environ['PYTHONPATH'] + >>> os.environ['PYTHONPATH'] + 'anything' + + >>> getfixture('monkeypatch').delenv('PYTHONPATH') + >>> with paths_on_pythonpath(['foo', 'bar']): + ... assert 'foo' in os.environ['PYTHONPATH'] + >>> os.environ.get('PYTHONPATH') + """ + nothing = object() + orig_pythonpath = os.environ.get('PYTHONPATH', nothing) + current_pythonpath = os.environ.get('PYTHONPATH', '') + try: + prefix = os.pathsep.join(unique_everseen(paths)) + to_join = filter(None, [prefix, current_pythonpath]) + new_path = os.pathsep.join(to_join) + if new_path: + os.environ['PYTHONPATH'] = new_path + yield + finally: + if orig_pythonpath is nothing: + os.environ.pop('PYTHONPATH', None) + else: + os.environ['PYTHONPATH'] = orig_pythonpath diff --git a/.venv/lib/python3.12/site-packages/setuptools/_reqs.py b/.venv/lib/python3.12/site-packages/setuptools/_reqs.py new file mode 100644 index 0000000000000000000000000000000000000000..c793be4d6eb3991d7b4ada615201a01cbfbbefd5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_reqs.py @@ -0,0 +1,42 @@ +from __future__ import annotations + +from collections.abc import Iterable, Iterator +from functools import lru_cache +from typing import TYPE_CHECKING, Callable, TypeVar, Union, overload + +import jaraco.text as text +from packaging.requirements import Requirement + +if TYPE_CHECKING: + from typing_extensions import TypeAlias + +_T = TypeVar("_T") +_StrOrIter: TypeAlias = Union[str, Iterable[str]] + + +parse_req: Callable[[str], Requirement] = lru_cache()(Requirement) +# Setuptools parses the same requirement many times +# (e.g. first for validation than for normalisation), +# so it might be worth to cache. + + +def parse_strings(strs: _StrOrIter) -> Iterator[str]: + """ + Yield requirement strings for each specification in `strs`. + + `strs` must be a string, or a (possibly-nested) iterable thereof. + """ + return text.join_continuation(map(text.drop_comment, text.yield_lines(strs))) + + +# These overloads are only needed because of a mypy false-positive, pyright gets it right +# https://github.com/python/mypy/issues/3737 +@overload +def parse(strs: _StrOrIter) -> Iterator[Requirement]: ... +@overload +def parse(strs: _StrOrIter, parser: Callable[[str], _T]) -> Iterator[_T]: ... +def parse(strs: _StrOrIter, parser: Callable[[str], _T] = parse_req) -> Iterator[_T]: # type: ignore[assignment] + """ + Replacement for ``pkg_resources.parse_requirements`` that uses ``packaging``. + """ + return map(parser, parse_strings(strs)) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_shutil.py b/.venv/lib/python3.12/site-packages/setuptools/_shutil.py new file mode 100644 index 0000000000000000000000000000000000000000..6acbb4281fc986587f52a83395dc63912a863caf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_shutil.py @@ -0,0 +1,53 @@ +"""Convenience layer on top of stdlib's shutil and os""" + +import os +import stat +from typing import Callable, TypeVar + +from .compat import py311 + +from distutils import log + +try: + from os import chmod # pyright: ignore[reportAssignmentType] + # Losing type-safety w/ pyright, but that's ok +except ImportError: # pragma: no cover + # Jython compatibility + def chmod(*args: object, **kwargs: object) -> None: # type: ignore[misc] # Mypy reuses the imported definition anyway + pass + + +_T = TypeVar("_T") + + +def attempt_chmod_verbose(path, mode): + log.debug("changing mode of %s to %o", path, mode) + try: + chmod(path, mode) + except OSError as e: # pragma: no cover + log.debug("chmod failed: %s", e) + + +# Must match shutil._OnExcCallback +def _auto_chmod( + func: Callable[..., _T], arg: str, exc: BaseException +) -> _T: # pragma: no cover + """shutils onexc callback to automatically call chmod for certain functions.""" + # Only retry for scenarios known to have an issue + if func in [os.unlink, os.remove] and os.name == 'nt': + attempt_chmod_verbose(arg, stat.S_IWRITE) + return func(arg) + raise exc + + +def rmtree(path, ignore_errors=False, onexc=_auto_chmod): + """ + Similar to ``shutil.rmtree`` but automatically executes ``chmod`` + for well know Windows failure scenarios. + """ + return py311.shutil_rmtree(path, ignore_errors, onexc) + + +def rmdir(path, **opts): + if os.path.isdir(path): + rmtree(path, **opts) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_static.py b/.venv/lib/python3.12/site-packages/setuptools/_static.py new file mode 100644 index 0000000000000000000000000000000000000000..af35862cf8b759a0e60110ce9e92bfdb1b49bc5f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_static.py @@ -0,0 +1,188 @@ +from functools import wraps +from typing import TypeVar + +import packaging.specifiers + +from .warnings import SetuptoolsDeprecationWarning + + +class Static: + """ + Wrapper for built-in object types that are allow setuptools to identify + static core metadata (in opposition to ``Dynamic``, as defined :pep:`643`). + + The trick is to mark values with :class:`Static` when they come from + ``pyproject.toml`` or ``setup.cfg``, so if any plugin overwrite the value + with a built-in, setuptools will be able to recognise the change. + + We inherit from built-in classes, so that we don't need to change the existing + code base to deal with the new types. + We also should strive for immutability objects to avoid changes after the + initial parsing. + """ + + _mutated_: bool = False # TODO: Remove after deprecation warning is solved + + +def _prevent_modification(target: type, method: str, copying: str) -> None: + """ + Because setuptools is very flexible we cannot fully prevent + plugins and user customizations from modifying static values that were + parsed from config files. + But we can attempt to block "in-place" mutations and identify when they + were done. + """ + fn = getattr(target, method, None) + if fn is None: + return + + @wraps(fn) + def _replacement(self: Static, *args, **kwargs): + # TODO: After deprecation period raise NotImplementedError instead of warning + # which obviated the existence and checks of the `_mutated_` attribute. + self._mutated_ = True + SetuptoolsDeprecationWarning.emit( + "Direct modification of value will be disallowed", + f""" + In an effort to implement PEP 643, direct/in-place changes of static values + that come from configuration files are deprecated. + If you need to modify this value, please first create a copy with {copying} + and make sure conform to all relevant standards when overriding setuptools + functionality (https://packaging.python.org/en/latest/specifications/). + """, + due_date=(2025, 10, 10), # Initially introduced in 2024-09-06 + ) + return fn(self, *args, **kwargs) + + _replacement.__doc__ = "" # otherwise doctest may fail. + setattr(target, method, _replacement) + + +class Str(str, Static): + pass + + +class Tuple(tuple, Static): + pass + + +class List(list, Static): + """ + :meta private: + >>> x = List([1, 2, 3]) + >>> is_static(x) + True + >>> x += [0] # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + SetuptoolsDeprecationWarning: Direct modification ... + >>> is_static(x) # no longer static after modification + False + >>> y = list(x) + >>> y.clear() + >>> y + [] + >>> y == x + False + >>> is_static(List(y)) + True + """ + + +# Make `List` immutable-ish +# (certain places of setuptools/distutils issue a warn if we use tuple instead of list) +for _method in ( + '__delitem__', + '__iadd__', + '__setitem__', + 'append', + 'clear', + 'extend', + 'insert', + 'remove', + 'reverse', + 'pop', +): + _prevent_modification(List, _method, "`list(value)`") + + +class Dict(dict, Static): + """ + :meta private: + >>> x = Dict({'a': 1, 'b': 2}) + >>> is_static(x) + True + >>> x['c'] = 0 # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + SetuptoolsDeprecationWarning: Direct modification ... + >>> x._mutated_ + True + >>> is_static(x) # no longer static after modification + False + >>> y = dict(x) + >>> y.popitem() + ('b', 2) + >>> y == x + False + >>> is_static(Dict(y)) + True + """ + + +# Make `Dict` immutable-ish (we cannot inherit from types.MappingProxyType): +for _method in ( + '__delitem__', + '__ior__', + '__setitem__', + 'clear', + 'pop', + 'popitem', + 'setdefault', + 'update', +): + _prevent_modification(Dict, _method, "`dict(value)`") + + +class SpecifierSet(packaging.specifiers.SpecifierSet, Static): + """Not exactly a built-in type but useful for ``requires-python``""" + + +T = TypeVar("T") + + +def noop(value: T) -> T: + """ + >>> noop(42) + 42 + """ + return value + + +_CONVERSIONS = {str: Str, tuple: Tuple, list: List, dict: Dict} + + +def attempt_conversion(value: T) -> T: + """ + >>> is_static(attempt_conversion("hello")) + True + >>> is_static(object()) + False + """ + return _CONVERSIONS.get(type(value), noop)(value) # type: ignore[call-overload] + + +def is_static(value: object) -> bool: + """ + >>> is_static(a := Dict({'a': 1})) + True + >>> is_static(dict(a)) + False + >>> is_static(b := List([1, 2, 3])) + True + >>> is_static(list(b)) + False + """ + return isinstance(value, Static) and not value._mutated_ + + +EMPTY_LIST = List() +EMPTY_DICT = Dict() diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/__pycache__/typing_extensions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/__pycache__/typing_extensions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b3aa28850c8368046d3f32d70485509cffec5a6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/__pycache__/typing_extensions.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1b27cc3e90b8ac1cd2540b7da10d65fdb3cbfdfbe39eb5d081940ba7c94327e1 +size 139507 diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/LICENSE b/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b49c3af060ce6326b8d91b9b73e76456ea0d9d2b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/LICENSE @@ -0,0 +1,166 @@ +GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. + diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/METADATA b/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..32214fb4400035788bfe5c0de42dad106a4f54f1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/METADATA @@ -0,0 +1,420 @@ +Metadata-Version: 2.1 +Name: autocommand +Version: 2.2.2 +Summary: A library to create a command-line program from a function +Home-page: https://github.com/Lucretiel/autocommand +Author: Nathan West +License: LGPLv3 +Project-URL: Homepage, https://github.com/Lucretiel/autocommand +Project-URL: Bug Tracker, https://github.com/Lucretiel/autocommand/issues +Platform: any +Classifier: Development Status :: 6 - Mature +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3) +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Topic :: Software Development +Classifier: Topic :: Software Development :: Libraries +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Requires-Python: >=3.7 +Description-Content-Type: text/markdown +License-File: LICENSE + +[![PyPI version](https://badge.fury.io/py/autocommand.svg)](https://badge.fury.io/py/autocommand) + +# autocommand + +A library to automatically generate and run simple argparse parsers from function signatures. + +## Installation + +Autocommand is installed via pip: + +``` +$ pip install autocommand +``` + +## Usage + +Autocommand turns a function into a command-line program. It converts the function's parameter signature into command-line arguments, and automatically runs the function if the module was called as `__main__`. In effect, it lets your create a smart main function. + +```python +from autocommand import autocommand + +# This program takes exactly one argument and echos it. +@autocommand(__name__) +def echo(thing): + print(thing) +``` + +``` +$ python echo.py hello +hello +$ python echo.py -h +usage: echo [-h] thing + +positional arguments: + thing + +optional arguments: + -h, --help show this help message and exit +$ python echo.py hello world # too many arguments +usage: echo.py [-h] thing +echo.py: error: unrecognized arguments: world +``` + +As you can see, autocommand converts the signature of the function into an argument spec. When you run the file as a program, autocommand collects the command-line arguments and turns them into function arguments. The function is executed with these arguments, and then the program exits with the return value of the function, via `sys.exit`. Autocommand also automatically creates a usage message, which can be invoked with `-h` or `--help`, and automatically prints an error message when provided with invalid arguments. + +### Types + +You can use a type annotation to give an argument a type. Any type (or in fact any callable) that returns an object when given a string argument can be used, though there are a few special cases that are described later. + +```python +@autocommand(__name__) +def net_client(host, port: int): + ... +``` + +Autocommand will catch `TypeErrors` raised by the type during argument parsing, so you can supply a callable and do some basic argument validation as well. + +### Trailing Arguments + +You can add a `*args` parameter to your function to give it trailing arguments. The command will collect 0 or more trailing arguments and supply them to `args` as a tuple. If a type annotation is supplied, the type is applied to each argument. + +```python +# Write the contents of each file, one by one +@autocommand(__name__) +def cat(*files): + for filename in files: + with open(filename) as file: + for line in file: + print(line.rstrip()) +``` + +``` +$ python cat.py -h +usage: ipython [-h] [file [file ...]] + +positional arguments: + file + +optional arguments: + -h, --help show this help message and exit +``` + +### Options + +To create `--option` switches, just assign a default. Autocommand will automatically create `--long` and `-s`hort switches. + +```python +@autocommand(__name__) +def do_with_config(argument, config='~/foo.conf'): + pass +``` + +``` +$ python example.py -h +usage: example.py [-h] [-c CONFIG] argument + +positional arguments: + argument + +optional arguments: + -h, --help show this help message and exit + -c CONFIG, --config CONFIG +``` + +The option's type is automatically deduced from the default, unless one is explicitly given in an annotation: + +```python +@autocommand(__name__) +def http_connect(host, port=80): + print('{}:{}'.format(host, port)) +``` + +``` +$ python http.py -h +usage: http.py [-h] [-p PORT] host + +positional arguments: + host + +optional arguments: + -h, --help show this help message and exit + -p PORT, --port PORT +$ python http.py localhost +localhost:80 +$ python http.py localhost -p 8080 +localhost:8080 +$ python http.py localhost -p blah +usage: http.py [-h] [-p PORT] host +http.py: error: argument -p/--port: invalid int value: 'blah' +``` + +#### None + +If an option is given a default value of `None`, it reads in a value as normal, but supplies `None` if the option isn't provided. + +#### Switches + +If an argument is given a default value of `True` or `False`, or +given an explicit `bool` type, it becomes an option switch. + +```python + @autocommand(__name__) + def example(verbose=False, quiet=False): + pass +``` + +``` +$ python example.py -h +usage: example.py [-h] [-v] [-q] + +optional arguments: + -h, --help show this help message and exit + -v, --verbose + -q, --quiet +``` + +Autocommand attempts to do the "correct thing" in these cases- if the default is `True`, then supplying the switch makes the argument `False`; if the type is `bool` and the default is some other `True` value, then supplying the switch makes the argument `False`, while not supplying the switch makes the argument the default value. + +Autocommand also supports the creation of switch inverters. Pass `add_nos=True` to `autocommand` to enable this. + +``` + @autocommand(__name__, add_nos=True) + def example(verbose=False): + pass +``` + +``` +$ python example.py -h +usage: ipython [-h] [-v] [--no-verbose] + +optional arguments: + -h, --help show this help message and exit + -v, --verbose + --no-verbose +``` + +Using the `--no-` version of a switch will pass the opposite value in as a function argument. If multiple switches are present, the last one takes precedence. + +#### Files + +If the default value is a file object, such as `sys.stdout`, then autocommand just looks for a string, for a file path. It doesn't do any special checking on the string, though (such as checking if the file exists); it's better to let the client decide how to handle errors in this case. Instead, it provides a special context manager called `smart_open`, which behaves exactly like `open` if a filename or other openable type is provided, but also lets you use already open files: + +```python +from autocommand import autocommand, smart_open +import sys + +# Write the contents of stdin, or a file, to stdout +@autocommand(__name__) +def write_out(infile=sys.stdin): + with smart_open(infile) as f: + for line in f: + print(line.rstrip()) + # If a file was opened, it is closed here. If it was just stdin, it is untouched. +``` + +``` +$ echo "Hello World!" | python write_out.py | tee hello.txt +Hello World! +$ python write_out.py --infile hello.txt +Hello World! +``` + +### Descriptions and docstrings + +The `autocommand` decorator accepts `description` and `epilog` kwargs, corresponding to the `description `_ and `epilog `_ of the `ArgumentParser`. If no description is given, but the decorated function has a docstring, then it is taken as the `description` for the `ArgumentParser`. You can also provide both the description and epilog in the docstring by splitting it into two sections with 4 or more - characters. + +```python +@autocommand(__name__) +def copy(infile=sys.stdin, outfile=sys.stdout): + ''' + Copy an the contents of a file (or stdin) to another file (or stdout) + ---------- + Some extra documentation in the epilog + ''' + with smart_open(infile) as istr: + with smart_open(outfile, 'w') as ostr: + for line in istr: + ostr.write(line) +``` + +``` +$ python copy.py -h +usage: copy.py [-h] [-i INFILE] [-o OUTFILE] + +Copy an the contents of a file (or stdin) to another file (or stdout) + +optional arguments: + -h, --help show this help message and exit + -i INFILE, --infile INFILE + -o OUTFILE, --outfile OUTFILE + +Some extra documentation in the epilog +$ echo "Hello World" | python copy.py --outfile hello.txt +$ python copy.py --infile hello.txt --outfile hello2.txt +$ python copy.py --infile hello2.txt +Hello World +``` + +### Parameter descriptions + +You can also attach description text to individual parameters in the annotation. To attach both a type and a description, supply them both in any order in a tuple + +```python +@autocommand(__name__) +def copy_net( + infile: 'The name of the file to send', + host: 'The host to send the file to', + port: (int, 'The port to connect to')): + + ''' + Copy a file over raw TCP to a remote destination. + ''' + # Left as an exercise to the reader +``` + +### Decorators and wrappers + +Autocommand automatically follows wrapper chains created by `@functools.wraps`. This means that you can apply other wrapping decorators to your main function, and autocommand will still correctly detect the signature. + +```python +from functools import wraps +from autocommand import autocommand + +def print_yielded(func): + ''' + Convert a generator into a function that prints all yielded elements + ''' + @wraps(func) + def wrapper(*args, **kwargs): + for thing in func(*args, **kwargs): + print(thing) + return wrapper + +@autocommand(__name__, + description= 'Print all the values from START to STOP, inclusive, in steps of STEP', + epilog= 'STOP and STEP default to 1') +@print_yielded +def seq(stop, start=1, step=1): + for i in range(start, stop + 1, step): + yield i +``` + +``` +$ seq.py -h +usage: seq.py [-h] [-s START] [-S STEP] stop + +Print all the values from START to STOP, inclusive, in steps of STEP + +positional arguments: + stop + +optional arguments: + -h, --help show this help message and exit + -s START, --start START + -S STEP, --step STEP + +STOP and STEP default to 1 +``` + +Even though autocommand is being applied to the `wrapper` returned by `print_yielded`, it still retreives the signature of the underlying `seq` function to create the argument parsing. + +### Custom Parser + +While autocommand's automatic parser generator is a powerful convenience, it doesn't cover all of the different features that argparse provides. If you need these features, you can provide your own parser as a kwarg to `autocommand`: + +```python +from argparse import ArgumentParser +from autocommand import autocommand + +parser = ArgumentParser() +# autocommand can't do optional positonal parameters +parser.add_argument('arg', nargs='?') +# or mutually exclusive options +group = parser.add_mutually_exclusive_group() +group.add_argument('-v', '--verbose', action='store_true') +group.add_argument('-q', '--quiet', action='store_true') + +@autocommand(__name__, parser=parser) +def main(arg, verbose, quiet): + print(arg, verbose, quiet) +``` + +``` +$ python parser.py -h +usage: write_file.py [-h] [-v | -q] [arg] + +positional arguments: + arg + +optional arguments: + -h, --help show this help message and exit + -v, --verbose + -q, --quiet +$ python parser.py +None False False +$ python parser.py hello +hello False False +$ python parser.py -v +None True False +$ python parser.py -q +None False True +$ python parser.py -vq +usage: parser.py [-h] [-v | -q] [arg] +parser.py: error: argument -q/--quiet: not allowed with argument -v/--verbose +``` + +Any parser should work fine, so long as each of the parser's arguments has a corresponding parameter in the decorated main function. The order of parameters doesn't matter, as long as they are all present. Note that when using a custom parser, autocommand doesn't modify the parser or the retrieved arguments. This means that no description/epilog will be added, and the function's type annotations and defaults (if present) will be ignored. + +## Testing and Library use + +The decorated function is only called and exited from if the first argument to `autocommand` is `'__main__'` or `True`. If it is neither of these values, or no argument is given, then a new main function is created by the decorator. This function has the signature `main(argv=None)`, and is intended to be called with arguments as if via `main(sys.argv[1:])`. The function has the attributes `parser` and `main`, which are the generated `ArgumentParser` and the original main function that was decorated. This is to facilitate testing and library use of your main. Calling the function triggers a `parse_args()` with the supplied arguments, and returns the result of the main function. Note that, while it returns instead of calling `sys.exit`, the `parse_args()` function will raise a `SystemExit` in the event of a parsing error or `-h/--help` argument. + +```python + @autocommand() + def test_prog(arg1, arg2: int, quiet=False, verbose=False): + if not quiet: + print(arg1, arg2) + if verbose: + print("LOUD NOISES") + + return 0 + + print(test_prog(['-v', 'hello', '80'])) +``` + +``` +$ python test_prog.py +hello 80 +LOUD NOISES +0 +``` + +If the function is called with no arguments, `sys.argv[1:]` is used. This is to allow the autocommand function to be used as a setuptools entry point. + +## Exceptions and limitations + +- There are a few possible exceptions that `autocommand` can raise. All of them derive from `autocommand.AutocommandError`. + + - If an invalid annotation is given (that is, it isn't a `type`, `str`, `(type, str)`, or `(str, type)`, an `AnnotationError` is raised. The `type` may be any callable, as described in the `Types`_ section. + - If the function has a `**kwargs` parameter, a `KWargError` is raised. + - If, somehow, the function has a positional-only parameter, a `PositionalArgError` is raised. This means that the argument doesn't have a name, which is currently not possible with a plain `def` or `lambda`, though many built-in functions have this kind of parameter. + +- There are a few argparse features that are not supported by autocommand. + + - It isn't possible to have an optional positional argument (as opposed to a `--option`). POSIX thinks this is bad form anyway. + - It isn't possible to have mutually exclusive arguments or options + - It isn't possible to have subcommands or subparsers, though I'm working on a few solutions involving classes or nested function definitions to allow this. + +## Development + +Autocommand cannot be important from the project root; this is to enforce separation of concerns and prevent accidental importing of `setup.py` or tests. To develop, install the project in editable mode: + +``` +$ python setup.py develop +``` + +This will create a link to the source files in the deployment directory, so that any source changes are reflected when it is imported. diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/RECORD b/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..e6e12ea51e18b270be6c5103c8cb1f6ef62f9e4a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/RECORD @@ -0,0 +1,18 @@ +autocommand-2.2.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +autocommand-2.2.2.dist-info/LICENSE,sha256=reeNBJgtaZctREqOFKlPh6IzTdOFXMgDSOqOJAqg3y0,7634 +autocommand-2.2.2.dist-info/METADATA,sha256=OADZuR3O6iBlpu1ieTgzYul6w4uOVrk0P0BO5TGGAJk,15006 +autocommand-2.2.2.dist-info/RECORD,, +autocommand-2.2.2.dist-info/WHEEL,sha256=2wepM1nk4DS4eFpYrW1TTqPcoGNfHhhO_i5m4cOimbo,92 +autocommand-2.2.2.dist-info/top_level.txt,sha256=AzfhgKKS8EdAwWUTSF8mgeVQbXOY9kokHB6kSqwwqu0,12 +autocommand/__init__.py,sha256=zko5Rnvolvb-UXjCx_2ArPTGBWwUK5QY4LIQIKYR7As,1037 +autocommand/__pycache__/__init__.cpython-312.pyc,, +autocommand/__pycache__/autoasync.cpython-312.pyc,, +autocommand/__pycache__/autocommand.cpython-312.pyc,, +autocommand/__pycache__/automain.cpython-312.pyc,, +autocommand/__pycache__/autoparse.cpython-312.pyc,, +autocommand/__pycache__/errors.cpython-312.pyc,, +autocommand/autoasync.py,sha256=AMdyrxNS4pqWJfP_xuoOcImOHWD-qT7x06wmKN1Vp-U,5680 +autocommand/autocommand.py,sha256=hmkEmQ72HtL55gnURVjDOnsfYlGd5lLXbvT4KG496Qw,2505 +autocommand/automain.py,sha256=A2b8i754Mxc_DjU9WFr6vqYDWlhz0cn8miu8d8EsxV8,2076 +autocommand/autoparse.py,sha256=WVWmZJPcbzUKXP40raQw_0HD8qPJ2V9VG1eFFmmnFxw,11642 +autocommand/errors.py,sha256=7aa3roh9Herd6nIKpQHNWEslWE8oq7GiHYVUuRqORnA,886 diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..57e3d840d59a650ac5bccbad5baeec47d155f0ad --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.38.4) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/top_level.txt b/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..dda5158ff6d263927861b19ef5a5d183d2aa77ed --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/top_level.txt @@ -0,0 +1 @@ +autocommand diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand/__init__.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..73fbfca6b36927c6371839df3dfe733bebb2066f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand/__init__.py @@ -0,0 +1,27 @@ +# Copyright 2014-2016 Nathan West +# +# This file is part of autocommand. +# +# autocommand is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# autocommand is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with autocommand. If not, see . + +# flake8 flags all these imports as unused, hence the NOQAs everywhere. + +from .automain import automain # NOQA +from .autoparse import autoparse, smart_open # NOQA +from .autocommand import autocommand # NOQA + +try: + from .autoasync import autoasync # NOQA +except ImportError: # pragma: no cover + pass diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..901b9907df6809a54db22f1543c152d2dbb5c82c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand/__pycache__/autoasync.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand/__pycache__/autoasync.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5c8f1d447d2d5a26be99e94861ac392393dfe4a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand/__pycache__/autoasync.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand/__pycache__/autocommand.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand/__pycache__/autocommand.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97ff3f3786c6dd09b8b6c27bf39efd5850192c58 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand/__pycache__/autocommand.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand/__pycache__/automain.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand/__pycache__/automain.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8757b997124e8910b1f027dd9110980f975b3adf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand/__pycache__/automain.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand/__pycache__/autoparse.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand/__pycache__/autoparse.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..44b29befc795101a95ff0f338308005956638150 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand/__pycache__/autoparse.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand/__pycache__/errors.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand/__pycache__/errors.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b70abc035732daca018953496c6a98aa5b39d875 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand/__pycache__/errors.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand/autoasync.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand/autoasync.py new file mode 100644 index 0000000000000000000000000000000000000000..688f7e05544bb5b4914d290c9bfe73bb99f4e06a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand/autoasync.py @@ -0,0 +1,142 @@ +# Copyright 2014-2015 Nathan West +# +# This file is part of autocommand. +# +# autocommand is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# autocommand is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with autocommand. If not, see . + +from asyncio import get_event_loop, iscoroutine +from functools import wraps +from inspect import signature + + +async def _run_forever_coro(coro, args, kwargs, loop): + ''' + This helper function launches an async main function that was tagged with + forever=True. There are two possibilities: + + - The function is a normal function, which handles initializing the event + loop, which is then run forever + - The function is a coroutine, which needs to be scheduled in the event + loop, which is then run forever + - There is also the possibility that the function is a normal function + wrapping a coroutine function + + The function is therefore called unconditionally and scheduled in the event + loop if the return value is a coroutine object. + + The reason this is a separate function is to make absolutely sure that all + the objects created are garbage collected after all is said and done; we + do this to ensure that any exceptions raised in the tasks are collected + ASAP. + ''' + + # Personal note: I consider this an antipattern, as it relies on the use of + # unowned resources. The setup function dumps some stuff into the event + # loop where it just whirls in the ether without a well defined owner or + # lifetime. For this reason, there's a good chance I'll remove the + # forever=True feature from autoasync at some point in the future. + thing = coro(*args, **kwargs) + if iscoroutine(thing): + await thing + + +def autoasync(coro=None, *, loop=None, forever=False, pass_loop=False): + ''' + Convert an asyncio coroutine into a function which, when called, is + evaluted in an event loop, and the return value returned. This is intented + to make it easy to write entry points into asyncio coroutines, which + otherwise need to be explictly evaluted with an event loop's + run_until_complete. + + If `loop` is given, it is used as the event loop to run the coro in. If it + is None (the default), the loop is retreived using asyncio.get_event_loop. + This call is defered until the decorated function is called, so that + callers can install custom event loops or event loop policies after + @autoasync is applied. + + If `forever` is True, the loop is run forever after the decorated coroutine + is finished. Use this for servers created with asyncio.start_server and the + like. + + If `pass_loop` is True, the event loop object is passed into the coroutine + as the `loop` kwarg when the wrapper function is called. In this case, the + wrapper function's __signature__ is updated to remove this parameter, so + that autoparse can still be used on it without generating a parameter for + `loop`. + + This coroutine can be called with ( @autoasync(...) ) or without + ( @autoasync ) arguments. + + Examples: + + @autoasync + def get_file(host, port): + reader, writer = yield from asyncio.open_connection(host, port) + data = reader.read() + sys.stdout.write(data.decode()) + + get_file(host, port) + + @autoasync(forever=True, pass_loop=True) + def server(host, port, loop): + yield_from loop.create_server(Proto, host, port) + + server('localhost', 8899) + + ''' + if coro is None: + return lambda c: autoasync( + c, loop=loop, + forever=forever, + pass_loop=pass_loop) + + # The old and new signatures are required to correctly bind the loop + # parameter in 100% of cases, even if it's a positional parameter. + # NOTE: A future release will probably require the loop parameter to be + # a kwonly parameter. + if pass_loop: + old_sig = signature(coro) + new_sig = old_sig.replace(parameters=( + param for name, param in old_sig.parameters.items() + if name != "loop")) + + @wraps(coro) + def autoasync_wrapper(*args, **kwargs): + # Defer the call to get_event_loop so that, if a custom policy is + # installed after the autoasync decorator, it is respected at call time + local_loop = get_event_loop() if loop is None else loop + + # Inject the 'loop' argument. We have to use this signature binding to + # ensure it's injected in the correct place (positional, keyword, etc) + if pass_loop: + bound_args = old_sig.bind_partial() + bound_args.arguments.update( + loop=local_loop, + **new_sig.bind(*args, **kwargs).arguments) + args, kwargs = bound_args.args, bound_args.kwargs + + if forever: + local_loop.create_task(_run_forever_coro( + coro, args, kwargs, local_loop + )) + local_loop.run_forever() + else: + return local_loop.run_until_complete(coro(*args, **kwargs)) + + # Attach the updated signature. This allows 'pass_loop' to be used with + # autoparse + if pass_loop: + autoasync_wrapper.__signature__ = new_sig + + return autoasync_wrapper diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand/autocommand.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand/autocommand.py new file mode 100644 index 0000000000000000000000000000000000000000..097e86de0720126a1390d728f7e50a4f89cac77f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand/autocommand.py @@ -0,0 +1,70 @@ +# Copyright 2014-2015 Nathan West +# +# This file is part of autocommand. +# +# autocommand is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# autocommand is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with autocommand. If not, see . + +from .autoparse import autoparse +from .automain import automain +try: + from .autoasync import autoasync +except ImportError: # pragma: no cover + pass + + +def autocommand( + module, *, + description=None, + epilog=None, + add_nos=False, + parser=None, + loop=None, + forever=False, + pass_loop=False): + + if callable(module): + raise TypeError('autocommand requires a module name argument') + + def autocommand_decorator(func): + # Step 1: if requested, run it all in an asyncio event loop. autoasync + # patches the __signature__ of the decorated function, so that in the + # event that pass_loop is True, the `loop` parameter of the original + # function will *not* be interpreted as a command-line argument by + # autoparse + if loop is not None or forever or pass_loop: + func = autoasync( + func, + loop=None if loop is True else loop, + pass_loop=pass_loop, + forever=forever) + + # Step 2: create parser. We do this second so that the arguments are + # parsed and passed *before* entering the asyncio event loop, if it + # exists. This simplifies the stack trace and ensures errors are + # reported earlier. It also ensures that errors raised during parsing & + # passing are still raised if `forever` is True. + func = autoparse( + func, + description=description, + epilog=epilog, + add_nos=add_nos, + parser=parser) + + # Step 3: call the function automatically if __name__ == '__main__' (or + # if True was provided) + func = automain(module)(func) + + return func + + return autocommand_decorator diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand/automain.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand/automain.py new file mode 100644 index 0000000000000000000000000000000000000000..6cc45db66a1c1dbf1bedb993683b0700d0510643 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand/automain.py @@ -0,0 +1,59 @@ +# Copyright 2014-2015 Nathan West +# +# This file is part of autocommand. +# +# autocommand is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# autocommand is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with autocommand. If not, see . + +import sys +from .errors import AutocommandError + + +class AutomainRequiresModuleError(AutocommandError, TypeError): + pass + + +def automain(module, *, args=(), kwargs=None): + ''' + This decorator automatically invokes a function if the module is being run + as the "__main__" module. Optionally, provide args or kwargs with which to + call the function. If `module` is "__main__", the function is called, and + the program is `sys.exit`ed with the return value. You can also pass `True` + to cause the function to be called unconditionally. If the function is not + called, it is returned unchanged by the decorator. + + Usage: + + @automain(__name__) # Pass __name__ to check __name__=="__main__" + def main(): + ... + + If __name__ is "__main__" here, the main function is called, and then + sys.exit called with the return value. + ''' + + # Check that @automain(...) was called, rather than @automain + if callable(module): + raise AutomainRequiresModuleError(module) + + if module == '__main__' or module is True: + if kwargs is None: + kwargs = {} + + # Use a function definition instead of a lambda for a neater traceback + def automain_decorator(main): + sys.exit(main(*args, **kwargs)) + + return automain_decorator + else: + return lambda main: main diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand/autoparse.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand/autoparse.py new file mode 100644 index 0000000000000000000000000000000000000000..0276a3fae10eb367af326543bcd69e62432b2f7b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand/autoparse.py @@ -0,0 +1,333 @@ +# Copyright 2014-2015 Nathan West +# +# This file is part of autocommand. +# +# autocommand is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# autocommand is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with autocommand. If not, see . + +import sys +from re import compile as compile_regex +from inspect import signature, getdoc, Parameter +from argparse import ArgumentParser +from contextlib import contextmanager +from functools import wraps +from io import IOBase +from autocommand.errors import AutocommandError + + +_empty = Parameter.empty + + +class AnnotationError(AutocommandError): + '''Annotation error: annotation must be a string, type, or tuple of both''' + + +class PositionalArgError(AutocommandError): + ''' + Postional Arg Error: autocommand can't handle postional-only parameters + ''' + + +class KWArgError(AutocommandError): + '''kwarg Error: autocommand can't handle a **kwargs parameter''' + + +class DocstringError(AutocommandError): + '''Docstring error''' + + +class TooManySplitsError(DocstringError): + ''' + The docstring had too many ---- section splits. Currently we only support + using up to a single split, to split the docstring into description and + epilog parts. + ''' + + +def _get_type_description(annotation): + ''' + Given an annotation, return the (type, description) for the parameter. + If you provide an annotation that is somehow both a string and a callable, + the behavior is undefined. + ''' + if annotation is _empty: + return None, None + elif callable(annotation): + return annotation, None + elif isinstance(annotation, str): + return None, annotation + elif isinstance(annotation, tuple): + try: + arg1, arg2 = annotation + except ValueError as e: + raise AnnotationError(annotation) from e + else: + if callable(arg1) and isinstance(arg2, str): + return arg1, arg2 + elif isinstance(arg1, str) and callable(arg2): + return arg2, arg1 + + raise AnnotationError(annotation) + + +def _add_arguments(param, parser, used_char_args, add_nos): + ''' + Add the argument(s) to an ArgumentParser (using add_argument) for a given + parameter. used_char_args is the set of -short options currently already in + use, and is updated (if necessary) by this function. If add_nos is True, + this will also add an inverse switch for all boolean options. For + instance, for the boolean parameter "verbose", this will create --verbose + and --no-verbose. + ''' + + # Impl note: This function is kept separate from make_parser because it's + # already very long and I wanted to separate out as much as possible into + # its own call scope, to prevent even the possibility of suble mutation + # bugs. + if param.kind is param.POSITIONAL_ONLY: + raise PositionalArgError(param) + elif param.kind is param.VAR_KEYWORD: + raise KWArgError(param) + + # These are the kwargs for the add_argument function. + arg_spec = {} + is_option = False + + # Get the type and default from the annotation. + arg_type, description = _get_type_description(param.annotation) + + # Get the default value + default = param.default + + # If there is no explicit type, and the default is present and not None, + # infer the type from the default. + if arg_type is None and default not in {_empty, None}: + arg_type = type(default) + + # Add default. The presence of a default means this is an option, not an + # argument. + if default is not _empty: + arg_spec['default'] = default + is_option = True + + # Add the type + if arg_type is not None: + # Special case for bool: make it just a --switch + if arg_type is bool: + if not default or default is _empty: + arg_spec['action'] = 'store_true' + else: + arg_spec['action'] = 'store_false' + + # Switches are always options + is_option = True + + # Special case for file types: make it a string type, for filename + elif isinstance(default, IOBase): + arg_spec['type'] = str + + # TODO: special case for list type. + # - How to specificy type of list members? + # - param: [int] + # - param: int =[] + # - action='append' vs nargs='*' + + else: + arg_spec['type'] = arg_type + + # nargs: if the signature includes *args, collect them as trailing CLI + # arguments in a list. *args can't have a default value, so it can never be + # an option. + if param.kind is param.VAR_POSITIONAL: + # TODO: consider depluralizing metavar/name here. + arg_spec['nargs'] = '*' + + # Add description. + if description is not None: + arg_spec['help'] = description + + # Get the --flags + flags = [] + name = param.name + + if is_option: + # Add the first letter as a -short option. + for letter in name[0], name[0].swapcase(): + if letter not in used_char_args: + used_char_args.add(letter) + flags.append('-{}'.format(letter)) + break + + # If the parameter is a --long option, or is a -short option that + # somehow failed to get a flag, add it. + if len(name) > 1 or not flags: + flags.append('--{}'.format(name)) + + arg_spec['dest'] = name + else: + flags.append(name) + + parser.add_argument(*flags, **arg_spec) + + # Create the --no- version for boolean switches + if add_nos and arg_type is bool: + parser.add_argument( + '--no-{}'.format(name), + action='store_const', + dest=name, + const=default if default is not _empty else False) + + +def make_parser(func_sig, description, epilog, add_nos): + ''' + Given the signature of a function, create an ArgumentParser + ''' + parser = ArgumentParser(description=description, epilog=epilog) + + used_char_args = {'h'} + + # Arange the params so that single-character arguments are first. This + # esnures they don't have to get --long versions. sorted is stable, so the + # parameters will otherwise still be in relative order. + params = sorted( + func_sig.parameters.values(), + key=lambda param: len(param.name) > 1) + + for param in params: + _add_arguments(param, parser, used_char_args, add_nos) + + return parser + + +_DOCSTRING_SPLIT = compile_regex(r'\n\s*-{4,}\s*\n') + + +def parse_docstring(docstring): + ''' + Given a docstring, parse it into a description and epilog part + ''' + if docstring is None: + return '', '' + + parts = _DOCSTRING_SPLIT.split(docstring) + + if len(parts) == 1: + return docstring, '' + elif len(parts) == 2: + return parts[0], parts[1] + else: + raise TooManySplitsError() + + +def autoparse( + func=None, *, + description=None, + epilog=None, + add_nos=False, + parser=None): + ''' + This decorator converts a function that takes normal arguments into a + function which takes a single optional argument, argv, parses it using an + argparse.ArgumentParser, and calls the underlying function with the parsed + arguments. If it is not given, sys.argv[1:] is used. This is so that the + function can be used as a setuptools entry point, as well as a normal main + function. sys.argv[1:] is not evaluated until the function is called, to + allow injecting different arguments for testing. + + It uses the argument signature of the function to create an + ArgumentParser. Parameters without defaults become positional parameters, + while parameters *with* defaults become --options. Use annotations to set + the type of the parameter. + + The `desctiption` and `epilog` parameters corrospond to the same respective + argparse parameters. If no description is given, it defaults to the + decorated functions's docstring, if present. + + If add_nos is True, every boolean option (that is, every parameter with a + default of True/False or a type of bool) will have a --no- version created + as well, which inverts the option. For instance, the --verbose option will + have a --no-verbose counterpart. These are not mutually exclusive- + whichever one appears last in the argument list will have precedence. + + If a parser is given, it is used instead of one generated from the function + signature. In this case, no parser is created; instead, the given parser is + used to parse the argv argument. The parser's results' argument names must + match up with the parameter names of the decorated function. + + The decorated function is attached to the result as the `func` attribute, + and the parser is attached as the `parser` attribute. + ''' + + # If @autoparse(...) is used instead of @autoparse + if func is None: + return lambda f: autoparse( + f, description=description, + epilog=epilog, + add_nos=add_nos, + parser=parser) + + func_sig = signature(func) + + docstr_description, docstr_epilog = parse_docstring(getdoc(func)) + + if parser is None: + parser = make_parser( + func_sig, + description or docstr_description, + epilog or docstr_epilog, + add_nos) + + @wraps(func) + def autoparse_wrapper(argv=None): + if argv is None: + argv = sys.argv[1:] + + # Get empty argument binding, to fill with parsed arguments. This + # object does all the heavy lifting of turning named arguments into + # into correctly bound *args and **kwargs. + parsed_args = func_sig.bind_partial() + parsed_args.arguments.update(vars(parser.parse_args(argv))) + + return func(*parsed_args.args, **parsed_args.kwargs) + + # TODO: attach an updated __signature__ to autoparse_wrapper, just in case. + + # Attach the wrapped function and parser, and return the wrapper. + autoparse_wrapper.func = func + autoparse_wrapper.parser = parser + return autoparse_wrapper + + +@contextmanager +def smart_open(filename_or_file, *args, **kwargs): + ''' + This context manager allows you to open a filename, if you want to default + some already-existing file object, like sys.stdout, which shouldn't be + closed at the end of the context. If the filename argument is a str, bytes, + or int, the file object is created via a call to open with the given *args + and **kwargs, sent to the context, and closed at the end of the context, + just like "with open(filename) as f:". If it isn't one of the openable + types, the object simply sent to the context unchanged, and left unclosed + at the end of the context. Example: + + def work_with_file(name=sys.stdout): + with smart_open(name) as f: + # Works correctly if name is a str filename or sys.stdout + print("Some stuff", file=f) + # If it was a filename, f is closed at the end here. + ''' + if isinstance(filename_or_file, (str, bytes, int)): + with open(filename_or_file, *args, **kwargs) as file: + yield file + else: + yield filename_or_file diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand/errors.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..2570607399a3ae13cb92db65a9171d955d3248c6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/autocommand/errors.py @@ -0,0 +1,23 @@ +# Copyright 2014-2016 Nathan West +# +# This file is part of autocommand. +# +# autocommand is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# autocommand is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with autocommand. If not, see . + + +class AutocommandError(Exception): + '''Base class for autocommand exceptions''' + pass + +# Individual modules will define errors specific to that module. diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/LICENSE b/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1bb5a44356f00884a71ceeefd24ded6caaba2418 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/LICENSE @@ -0,0 +1,17 @@ +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.12/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/METADATA b/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..db0a2dcdbe5f55f5815b2eaa243c507d0bdad002 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/METADATA @@ -0,0 +1,46 @@ +Metadata-Version: 2.1 +Name: backports.tarfile +Version: 1.2.0 +Summary: Backport of CPython tarfile module +Author-email: "Jason R. Coombs" +Project-URL: Homepage, https://github.com/jaraco/backports.tarfile +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Requires-Python: >=3.8 +Description-Content-Type: text/x-rst +License-File: LICENSE +Provides-Extra: docs +Requires-Dist: sphinx >=3.5 ; extra == 'docs' +Requires-Dist: jaraco.packaging >=9.3 ; extra == 'docs' +Requires-Dist: rst.linker >=1.9 ; extra == 'docs' +Requires-Dist: furo ; extra == 'docs' +Requires-Dist: sphinx-lint ; extra == 'docs' +Provides-Extra: testing +Requires-Dist: pytest !=8.1.*,>=6 ; extra == 'testing' +Requires-Dist: pytest-checkdocs >=2.4 ; extra == 'testing' +Requires-Dist: pytest-cov ; extra == 'testing' +Requires-Dist: pytest-enabler >=2.2 ; extra == 'testing' +Requires-Dist: jaraco.test ; extra == 'testing' +Requires-Dist: pytest !=8.0.* ; extra == 'testing' + +.. image:: https://img.shields.io/pypi/v/backports.tarfile.svg + :target: https://pypi.org/project/backports.tarfile + +.. image:: https://img.shields.io/pypi/pyversions/backports.tarfile.svg + +.. image:: https://github.com/jaraco/backports.tarfile/actions/workflows/main.yml/badge.svg + :target: https://github.com/jaraco/backports.tarfile/actions?query=workflow%3A%22tests%22 + :alt: tests + +.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v2.json + :target: https://github.com/astral-sh/ruff + :alt: Ruff + +.. .. image:: https://readthedocs.org/projects/backportstarfile/badge/?version=latest +.. :target: https://backportstarfile.readthedocs.io/en/latest/?badge=latest + +.. image:: https://img.shields.io/badge/skeleton-2024-informational + :target: https://blog.jaraco.com/skeleton diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/RECORD b/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..536dc2f09ed8a2e9b04f98b82625101bb9f74715 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/RECORD @@ -0,0 +1,17 @@ +backports.tarfile-1.2.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +backports.tarfile-1.2.0.dist-info/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023 +backports.tarfile-1.2.0.dist-info/METADATA,sha256=ghXFTq132dxaEIolxr3HK1mZqm9iyUmaRANZQSr6WlE,2020 +backports.tarfile-1.2.0.dist-info/RECORD,, +backports.tarfile-1.2.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +backports.tarfile-1.2.0.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92 +backports.tarfile-1.2.0.dist-info/top_level.txt,sha256=cGjaLMOoBR1FK0ApojtzWVmViTtJ7JGIK_HwXiEsvtU,10 +backports/__init__.py,sha256=iOEMwnlORWezdO8-2vxBIPSR37D7JGjluZ8f55vzxls,81 +backports/__pycache__/__init__.cpython-312.pyc,, +backports/tarfile/__init__.py,sha256=Pwf2qUIfB0SolJPCKcx3vz3UEu_aids4g4sAfxy94qg,108491 +backports/tarfile/__main__.py,sha256=Yw2oGT1afrz2eBskzdPYL8ReB_3liApmhFkN2EbDmc4,59 +backports/tarfile/__pycache__/__init__.cpython-312.pyc,, +backports/tarfile/__pycache__/__main__.cpython-312.pyc,, +backports/tarfile/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +backports/tarfile/compat/__pycache__/__init__.cpython-312.pyc,, +backports/tarfile/compat/__pycache__/py38.cpython-312.pyc,, +backports/tarfile/compat/py38.py,sha256=iYkyt_gvWjLzGUTJD9TuTfMMjOk-ersXZmRlvQYN2qE,568 diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/REQUESTED b/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..bab98d675883cc7567a79df485cd7b4f015e376f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.43.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/top_level.txt b/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..99d2be5b64d7dc414f8ab9c002de06456b4bada2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/top_level.txt @@ -0,0 +1 @@ +backports diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports/__init__.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0d1f7edf5dc6343538563a8caa7de6829752c4f9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports/__init__.py @@ -0,0 +1 @@ +__path__ = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21473c5c92dd978a8d96aaf7470d3ab65e3009ac Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports/tarfile/__init__.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports/tarfile/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8c16881cb3ae1ea6e729b62bb2e5d625faa3f5fe --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports/tarfile/__init__.py @@ -0,0 +1,2937 @@ +#------------------------------------------------------------------- +# tarfile.py +#------------------------------------------------------------------- +# Copyright (C) 2002 Lars Gustaebel +# All rights reserved. +# +# 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. +# +"""Read from and write to tar format archives. +""" + +version = "0.9.0" +__author__ = "Lars Gust\u00e4bel (lars@gustaebel.de)" +__credits__ = "Gustavo Niemeyer, Niels Gust\u00e4bel, Richard Townsend." + +#--------- +# Imports +#--------- +from builtins import open as bltn_open +import sys +import os +import io +import shutil +import stat +import time +import struct +import copy +import re + +from .compat.py38 import removesuffix + +try: + import pwd +except ImportError: + pwd = None +try: + import grp +except ImportError: + grp = None + +# os.symlink on Windows prior to 6.0 raises NotImplementedError +# OSError (winerror=1314) will be raised if the caller does not hold the +# SeCreateSymbolicLinkPrivilege privilege +symlink_exception = (AttributeError, NotImplementedError, OSError) + +# from tarfile import * +__all__ = ["TarFile", "TarInfo", "is_tarfile", "TarError", "ReadError", + "CompressionError", "StreamError", "ExtractError", "HeaderError", + "ENCODING", "USTAR_FORMAT", "GNU_FORMAT", "PAX_FORMAT", + "DEFAULT_FORMAT", "open","fully_trusted_filter", "data_filter", + "tar_filter", "FilterError", "AbsoluteLinkError", + "OutsideDestinationError", "SpecialFileError", "AbsolutePathError", + "LinkOutsideDestinationError"] + + +#--------------------------------------------------------- +# tar constants +#--------------------------------------------------------- +NUL = b"\0" # the null character +BLOCKSIZE = 512 # length of processing blocks +RECORDSIZE = BLOCKSIZE * 20 # length of records +GNU_MAGIC = b"ustar \0" # magic gnu tar string +POSIX_MAGIC = b"ustar\x0000" # magic posix tar string + +LENGTH_NAME = 100 # maximum length of a filename +LENGTH_LINK = 100 # maximum length of a linkname +LENGTH_PREFIX = 155 # maximum length of the prefix field + +REGTYPE = b"0" # regular file +AREGTYPE = b"\0" # regular file +LNKTYPE = b"1" # link (inside tarfile) +SYMTYPE = b"2" # symbolic link +CHRTYPE = b"3" # character special device +BLKTYPE = b"4" # block special device +DIRTYPE = b"5" # directory +FIFOTYPE = b"6" # fifo special device +CONTTYPE = b"7" # contiguous file + +GNUTYPE_LONGNAME = b"L" # GNU tar longname +GNUTYPE_LONGLINK = b"K" # GNU tar longlink +GNUTYPE_SPARSE = b"S" # GNU tar sparse file + +XHDTYPE = b"x" # POSIX.1-2001 extended header +XGLTYPE = b"g" # POSIX.1-2001 global header +SOLARIS_XHDTYPE = b"X" # Solaris extended header + +USTAR_FORMAT = 0 # POSIX.1-1988 (ustar) format +GNU_FORMAT = 1 # GNU tar format +PAX_FORMAT = 2 # POSIX.1-2001 (pax) format +DEFAULT_FORMAT = PAX_FORMAT + +#--------------------------------------------------------- +# tarfile constants +#--------------------------------------------------------- +# File types that tarfile supports: +SUPPORTED_TYPES = (REGTYPE, AREGTYPE, LNKTYPE, + SYMTYPE, DIRTYPE, FIFOTYPE, + CONTTYPE, CHRTYPE, BLKTYPE, + GNUTYPE_LONGNAME, GNUTYPE_LONGLINK, + GNUTYPE_SPARSE) + +# File types that will be treated as a regular file. +REGULAR_TYPES = (REGTYPE, AREGTYPE, + CONTTYPE, GNUTYPE_SPARSE) + +# File types that are part of the GNU tar format. +GNU_TYPES = (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK, + GNUTYPE_SPARSE) + +# Fields from a pax header that override a TarInfo attribute. +PAX_FIELDS = ("path", "linkpath", "size", "mtime", + "uid", "gid", "uname", "gname") + +# Fields from a pax header that are affected by hdrcharset. +PAX_NAME_FIELDS = {"path", "linkpath", "uname", "gname"} + +# Fields in a pax header that are numbers, all other fields +# are treated as strings. +PAX_NUMBER_FIELDS = { + "atime": float, + "ctime": float, + "mtime": float, + "uid": int, + "gid": int, + "size": int +} + +#--------------------------------------------------------- +# initialization +#--------------------------------------------------------- +if os.name == "nt": + ENCODING = "utf-8" +else: + ENCODING = sys.getfilesystemencoding() + +#--------------------------------------------------------- +# Some useful functions +#--------------------------------------------------------- + +def stn(s, length, encoding, errors): + """Convert a string to a null-terminated bytes object. + """ + if s is None: + raise ValueError("metadata cannot contain None") + s = s.encode(encoding, errors) + return s[:length] + (length - len(s)) * NUL + +def nts(s, encoding, errors): + """Convert a null-terminated bytes object to a string. + """ + p = s.find(b"\0") + if p != -1: + s = s[:p] + return s.decode(encoding, errors) + +def nti(s): + """Convert a number field to a python number. + """ + # There are two possible encodings for a number field, see + # itn() below. + if s[0] in (0o200, 0o377): + n = 0 + for i in range(len(s) - 1): + n <<= 8 + n += s[i + 1] + if s[0] == 0o377: + n = -(256 ** (len(s) - 1) - n) + else: + try: + s = nts(s, "ascii", "strict") + n = int(s.strip() or "0", 8) + except ValueError: + raise InvalidHeaderError("invalid header") + return n + +def itn(n, digits=8, format=DEFAULT_FORMAT): + """Convert a python number to a number field. + """ + # POSIX 1003.1-1988 requires numbers to be encoded as a string of + # octal digits followed by a null-byte, this allows values up to + # (8**(digits-1))-1. GNU tar allows storing numbers greater than + # that if necessary. A leading 0o200 or 0o377 byte indicate this + # particular encoding, the following digits-1 bytes are a big-endian + # base-256 representation. This allows values up to (256**(digits-1))-1. + # A 0o200 byte indicates a positive number, a 0o377 byte a negative + # number. + original_n = n + n = int(n) + if 0 <= n < 8 ** (digits - 1): + s = bytes("%0*o" % (digits - 1, n), "ascii") + NUL + elif format == GNU_FORMAT and -256 ** (digits - 1) <= n < 256 ** (digits - 1): + if n >= 0: + s = bytearray([0o200]) + else: + s = bytearray([0o377]) + n = 256 ** digits + n + + for i in range(digits - 1): + s.insert(1, n & 0o377) + n >>= 8 + else: + raise ValueError("overflow in number field") + + return s + +def calc_chksums(buf): + """Calculate the checksum for a member's header by summing up all + characters except for the chksum field which is treated as if + it was filled with spaces. According to the GNU tar sources, + some tars (Sun and NeXT) calculate chksum with signed char, + which will be different if there are chars in the buffer with + the high bit set. So we calculate two checksums, unsigned and + signed. + """ + unsigned_chksum = 256 + sum(struct.unpack_from("148B8x356B", buf)) + signed_chksum = 256 + sum(struct.unpack_from("148b8x356b", buf)) + return unsigned_chksum, signed_chksum + +def copyfileobj(src, dst, length=None, exception=OSError, bufsize=None): + """Copy length bytes from fileobj src to fileobj dst. + If length is None, copy the entire content. + """ + bufsize = bufsize or 16 * 1024 + if length == 0: + return + if length is None: + shutil.copyfileobj(src, dst, bufsize) + return + + blocks, remainder = divmod(length, bufsize) + for b in range(blocks): + buf = src.read(bufsize) + if len(buf) < bufsize: + raise exception("unexpected end of data") + dst.write(buf) + + if remainder != 0: + buf = src.read(remainder) + if len(buf) < remainder: + raise exception("unexpected end of data") + dst.write(buf) + return + +def _safe_print(s): + encoding = getattr(sys.stdout, 'encoding', None) + if encoding is not None: + s = s.encode(encoding, 'backslashreplace').decode(encoding) + print(s, end=' ') + + +class TarError(Exception): + """Base exception.""" + pass +class ExtractError(TarError): + """General exception for extract errors.""" + pass +class ReadError(TarError): + """Exception for unreadable tar archives.""" + pass +class CompressionError(TarError): + """Exception for unavailable compression methods.""" + pass +class StreamError(TarError): + """Exception for unsupported operations on stream-like TarFiles.""" + pass +class HeaderError(TarError): + """Base exception for header errors.""" + pass +class EmptyHeaderError(HeaderError): + """Exception for empty headers.""" + pass +class TruncatedHeaderError(HeaderError): + """Exception for truncated headers.""" + pass +class EOFHeaderError(HeaderError): + """Exception for end of file headers.""" + pass +class InvalidHeaderError(HeaderError): + """Exception for invalid headers.""" + pass +class SubsequentHeaderError(HeaderError): + """Exception for missing and invalid extended headers.""" + pass + +#--------------------------- +# internal stream interface +#--------------------------- +class _LowLevelFile: + """Low-level file object. Supports reading and writing. + It is used instead of a regular file object for streaming + access. + """ + + def __init__(self, name, mode): + mode = { + "r": os.O_RDONLY, + "w": os.O_WRONLY | os.O_CREAT | os.O_TRUNC, + }[mode] + if hasattr(os, "O_BINARY"): + mode |= os.O_BINARY + self.fd = os.open(name, mode, 0o666) + + def close(self): + os.close(self.fd) + + def read(self, size): + return os.read(self.fd, size) + + def write(self, s): + os.write(self.fd, s) + +class _Stream: + """Class that serves as an adapter between TarFile and + a stream-like object. The stream-like object only + needs to have a read() or write() method that works with bytes, + and the method is accessed blockwise. + Use of gzip or bzip2 compression is possible. + A stream-like object could be for example: sys.stdin.buffer, + sys.stdout.buffer, a socket, a tape device etc. + + _Stream is intended to be used only internally. + """ + + def __init__(self, name, mode, comptype, fileobj, bufsize, + compresslevel): + """Construct a _Stream object. + """ + self._extfileobj = True + if fileobj is None: + fileobj = _LowLevelFile(name, mode) + self._extfileobj = False + + if comptype == '*': + # Enable transparent compression detection for the + # stream interface + fileobj = _StreamProxy(fileobj) + comptype = fileobj.getcomptype() + + self.name = name or "" + self.mode = mode + self.comptype = comptype + self.fileobj = fileobj + self.bufsize = bufsize + self.buf = b"" + self.pos = 0 + self.closed = False + + try: + if comptype == "gz": + try: + import zlib + except ImportError: + raise CompressionError("zlib module is not available") from None + self.zlib = zlib + self.crc = zlib.crc32(b"") + if mode == "r": + self.exception = zlib.error + self._init_read_gz() + else: + self._init_write_gz(compresslevel) + + elif comptype == "bz2": + try: + import bz2 + except ImportError: + raise CompressionError("bz2 module is not available") from None + if mode == "r": + self.dbuf = b"" + self.cmp = bz2.BZ2Decompressor() + self.exception = OSError + else: + self.cmp = bz2.BZ2Compressor(compresslevel) + + elif comptype == "xz": + try: + import lzma + except ImportError: + raise CompressionError("lzma module is not available") from None + if mode == "r": + self.dbuf = b"" + self.cmp = lzma.LZMADecompressor() + self.exception = lzma.LZMAError + else: + self.cmp = lzma.LZMACompressor() + + elif comptype != "tar": + raise CompressionError("unknown compression type %r" % comptype) + + except: + if not self._extfileobj: + self.fileobj.close() + self.closed = True + raise + + def __del__(self): + if hasattr(self, "closed") and not self.closed: + self.close() + + def _init_write_gz(self, compresslevel): + """Initialize for writing with gzip compression. + """ + self.cmp = self.zlib.compressobj(compresslevel, + self.zlib.DEFLATED, + -self.zlib.MAX_WBITS, + self.zlib.DEF_MEM_LEVEL, + 0) + timestamp = struct.pack(" self.bufsize: + self.fileobj.write(self.buf[:self.bufsize]) + self.buf = self.buf[self.bufsize:] + + def close(self): + """Close the _Stream object. No operation should be + done on it afterwards. + """ + if self.closed: + return + + self.closed = True + try: + if self.mode == "w" and self.comptype != "tar": + self.buf += self.cmp.flush() + + if self.mode == "w" and self.buf: + self.fileobj.write(self.buf) + self.buf = b"" + if self.comptype == "gz": + self.fileobj.write(struct.pack("= 0: + blocks, remainder = divmod(pos - self.pos, self.bufsize) + for i in range(blocks): + self.read(self.bufsize) + self.read(remainder) + else: + raise StreamError("seeking backwards is not allowed") + return self.pos + + def read(self, size): + """Return the next size number of bytes from the stream.""" + assert size is not None + buf = self._read(size) + self.pos += len(buf) + return buf + + def _read(self, size): + """Return size bytes from the stream. + """ + if self.comptype == "tar": + return self.__read(size) + + c = len(self.dbuf) + t = [self.dbuf] + while c < size: + # Skip underlying buffer to avoid unaligned double buffering. + if self.buf: + buf = self.buf + self.buf = b"" + else: + buf = self.fileobj.read(self.bufsize) + if not buf: + break + try: + buf = self.cmp.decompress(buf) + except self.exception as e: + raise ReadError("invalid compressed data") from e + t.append(buf) + c += len(buf) + t = b"".join(t) + self.dbuf = t[size:] + return t[:size] + + def __read(self, size): + """Return size bytes from stream. If internal buffer is empty, + read another block from the stream. + """ + c = len(self.buf) + t = [self.buf] + while c < size: + buf = self.fileobj.read(self.bufsize) + if not buf: + break + t.append(buf) + c += len(buf) + t = b"".join(t) + self.buf = t[size:] + return t[:size] +# class _Stream + +class _StreamProxy(object): + """Small proxy class that enables transparent compression + detection for the Stream interface (mode 'r|*'). + """ + + def __init__(self, fileobj): + self.fileobj = fileobj + self.buf = self.fileobj.read(BLOCKSIZE) + + def read(self, size): + self.read = self.fileobj.read + return self.buf + + def getcomptype(self): + if self.buf.startswith(b"\x1f\x8b\x08"): + return "gz" + elif self.buf[0:3] == b"BZh" and self.buf[4:10] == b"1AY&SY": + return "bz2" + elif self.buf.startswith((b"\x5d\x00\x00\x80", b"\xfd7zXZ")): + return "xz" + else: + return "tar" + + def close(self): + self.fileobj.close() +# class StreamProxy + +#------------------------ +# Extraction file object +#------------------------ +class _FileInFile(object): + """A thin wrapper around an existing file object that + provides a part of its data as an individual file + object. + """ + + def __init__(self, fileobj, offset, size, name, blockinfo=None): + self.fileobj = fileobj + self.offset = offset + self.size = size + self.position = 0 + self.name = name + self.closed = False + + if blockinfo is None: + blockinfo = [(0, size)] + + # Construct a map with data and zero blocks. + self.map_index = 0 + self.map = [] + lastpos = 0 + realpos = self.offset + for offset, size in blockinfo: + if offset > lastpos: + self.map.append((False, lastpos, offset, None)) + self.map.append((True, offset, offset + size, realpos)) + realpos += size + lastpos = offset + size + if lastpos < self.size: + self.map.append((False, lastpos, self.size, None)) + + def flush(self): + pass + + @property + def mode(self): + return 'rb' + + def readable(self): + return True + + def writable(self): + return False + + def seekable(self): + return self.fileobj.seekable() + + def tell(self): + """Return the current file position. + """ + return self.position + + def seek(self, position, whence=io.SEEK_SET): + """Seek to a position in the file. + """ + if whence == io.SEEK_SET: + self.position = min(max(position, 0), self.size) + elif whence == io.SEEK_CUR: + if position < 0: + self.position = max(self.position + position, 0) + else: + self.position = min(self.position + position, self.size) + elif whence == io.SEEK_END: + self.position = max(min(self.size + position, self.size), 0) + else: + raise ValueError("Invalid argument") + return self.position + + def read(self, size=None): + """Read data from the file. + """ + if size is None: + size = self.size - self.position + else: + size = min(size, self.size - self.position) + + buf = b"" + while size > 0: + while True: + data, start, stop, offset = self.map[self.map_index] + if start <= self.position < stop: + break + else: + self.map_index += 1 + if self.map_index == len(self.map): + self.map_index = 0 + length = min(size, stop - self.position) + if data: + self.fileobj.seek(offset + (self.position - start)) + b = self.fileobj.read(length) + if len(b) != length: + raise ReadError("unexpected end of data") + buf += b + else: + buf += NUL * length + size -= length + self.position += length + return buf + + def readinto(self, b): + buf = self.read(len(b)) + b[:len(buf)] = buf + return len(buf) + + def close(self): + self.closed = True +#class _FileInFile + +class ExFileObject(io.BufferedReader): + + def __init__(self, tarfile, tarinfo): + fileobj = _FileInFile(tarfile.fileobj, tarinfo.offset_data, + tarinfo.size, tarinfo.name, tarinfo.sparse) + super().__init__(fileobj) +#class ExFileObject + + +#----------------------------- +# extraction filters (PEP 706) +#----------------------------- + +class FilterError(TarError): + pass + +class AbsolutePathError(FilterError): + def __init__(self, tarinfo): + self.tarinfo = tarinfo + super().__init__(f'member {tarinfo.name!r} has an absolute path') + +class OutsideDestinationError(FilterError): + def __init__(self, tarinfo, path): + self.tarinfo = tarinfo + self._path = path + super().__init__(f'{tarinfo.name!r} would be extracted to {path!r}, ' + + 'which is outside the destination') + +class SpecialFileError(FilterError): + def __init__(self, tarinfo): + self.tarinfo = tarinfo + super().__init__(f'{tarinfo.name!r} is a special file') + +class AbsoluteLinkError(FilterError): + def __init__(self, tarinfo): + self.tarinfo = tarinfo + super().__init__(f'{tarinfo.name!r} is a link to an absolute path') + +class LinkOutsideDestinationError(FilterError): + def __init__(self, tarinfo, path): + self.tarinfo = tarinfo + self._path = path + super().__init__(f'{tarinfo.name!r} would link to {path!r}, ' + + 'which is outside the destination') + +def _get_filtered_attrs(member, dest_path, for_data=True): + new_attrs = {} + name = member.name + dest_path = os.path.realpath(dest_path) + # Strip leading / (tar's directory separator) from filenames. + # Include os.sep (target OS directory separator) as well. + if name.startswith(('/', os.sep)): + name = new_attrs['name'] = member.path.lstrip('/' + os.sep) + if os.path.isabs(name): + # Path is absolute even after stripping. + # For example, 'C:/foo' on Windows. + raise AbsolutePathError(member) + # Ensure we stay in the destination + target_path = os.path.realpath(os.path.join(dest_path, name)) + if os.path.commonpath([target_path, dest_path]) != dest_path: + raise OutsideDestinationError(member, target_path) + # Limit permissions (no high bits, and go-w) + mode = member.mode + if mode is not None: + # Strip high bits & group/other write bits + mode = mode & 0o755 + if for_data: + # For data, handle permissions & file types + if member.isreg() or member.islnk(): + if not mode & 0o100: + # Clear executable bits if not executable by user + mode &= ~0o111 + # Ensure owner can read & write + mode |= 0o600 + elif member.isdir() or member.issym(): + # Ignore mode for directories & symlinks + mode = None + else: + # Reject special files + raise SpecialFileError(member) + if mode != member.mode: + new_attrs['mode'] = mode + if for_data: + # Ignore ownership for 'data' + if member.uid is not None: + new_attrs['uid'] = None + if member.gid is not None: + new_attrs['gid'] = None + if member.uname is not None: + new_attrs['uname'] = None + if member.gname is not None: + new_attrs['gname'] = None + # Check link destination for 'data' + if member.islnk() or member.issym(): + if os.path.isabs(member.linkname): + raise AbsoluteLinkError(member) + if member.issym(): + target_path = os.path.join(dest_path, + os.path.dirname(name), + member.linkname) + else: + target_path = os.path.join(dest_path, + member.linkname) + target_path = os.path.realpath(target_path) + if os.path.commonpath([target_path, dest_path]) != dest_path: + raise LinkOutsideDestinationError(member, target_path) + return new_attrs + +def fully_trusted_filter(member, dest_path): + return member + +def tar_filter(member, dest_path): + new_attrs = _get_filtered_attrs(member, dest_path, False) + if new_attrs: + return member.replace(**new_attrs, deep=False) + return member + +def data_filter(member, dest_path): + new_attrs = _get_filtered_attrs(member, dest_path, True) + if new_attrs: + return member.replace(**new_attrs, deep=False) + return member + +_NAMED_FILTERS = { + "fully_trusted": fully_trusted_filter, + "tar": tar_filter, + "data": data_filter, +} + +#------------------ +# Exported Classes +#------------------ + +# Sentinel for replace() defaults, meaning "don't change the attribute" +_KEEP = object() + +class TarInfo(object): + """Informational class which holds the details about an + archive member given by a tar header block. + TarInfo objects are returned by TarFile.getmember(), + TarFile.getmembers() and TarFile.gettarinfo() and are + usually created internally. + """ + + __slots__ = dict( + name = 'Name of the archive member.', + mode = 'Permission bits.', + uid = 'User ID of the user who originally stored this member.', + gid = 'Group ID of the user who originally stored this member.', + size = 'Size in bytes.', + mtime = 'Time of last modification.', + chksum = 'Header checksum.', + type = ('File type. type is usually one of these constants: ' + 'REGTYPE, AREGTYPE, LNKTYPE, SYMTYPE, DIRTYPE, FIFOTYPE, ' + 'CONTTYPE, CHRTYPE, BLKTYPE, GNUTYPE_SPARSE.'), + linkname = ('Name of the target file name, which is only present ' + 'in TarInfo objects of type LNKTYPE and SYMTYPE.'), + uname = 'User name.', + gname = 'Group name.', + devmajor = 'Device major number.', + devminor = 'Device minor number.', + offset = 'The tar header starts here.', + offset_data = "The file's data starts here.", + pax_headers = ('A dictionary containing key-value pairs of an ' + 'associated pax extended header.'), + sparse = 'Sparse member information.', + _tarfile = None, + _sparse_structs = None, + _link_target = None, + ) + + def __init__(self, name=""): + """Construct a TarInfo object. name is the optional name + of the member. + """ + self.name = name # member name + self.mode = 0o644 # file permissions + self.uid = 0 # user id + self.gid = 0 # group id + self.size = 0 # file size + self.mtime = 0 # modification time + self.chksum = 0 # header checksum + self.type = REGTYPE # member type + self.linkname = "" # link name + self.uname = "" # user name + self.gname = "" # group name + self.devmajor = 0 # device major number + self.devminor = 0 # device minor number + + self.offset = 0 # the tar header starts here + self.offset_data = 0 # the file's data starts here + + self.sparse = None # sparse member information + self.pax_headers = {} # pax header information + + @property + def tarfile(self): + import warnings + warnings.warn( + 'The undocumented "tarfile" attribute of TarInfo objects ' + + 'is deprecated and will be removed in Python 3.16', + DeprecationWarning, stacklevel=2) + return self._tarfile + + @tarfile.setter + def tarfile(self, tarfile): + import warnings + warnings.warn( + 'The undocumented "tarfile" attribute of TarInfo objects ' + + 'is deprecated and will be removed in Python 3.16', + DeprecationWarning, stacklevel=2) + self._tarfile = tarfile + + @property + def path(self): + 'In pax headers, "name" is called "path".' + return self.name + + @path.setter + def path(self, name): + self.name = name + + @property + def linkpath(self): + 'In pax headers, "linkname" is called "linkpath".' + return self.linkname + + @linkpath.setter + def linkpath(self, linkname): + self.linkname = linkname + + def __repr__(self): + return "<%s %r at %#x>" % (self.__class__.__name__,self.name,id(self)) + + def replace(self, *, + name=_KEEP, mtime=_KEEP, mode=_KEEP, linkname=_KEEP, + uid=_KEEP, gid=_KEEP, uname=_KEEP, gname=_KEEP, + deep=True, _KEEP=_KEEP): + """Return a deep copy of self with the given attributes replaced. + """ + if deep: + result = copy.deepcopy(self) + else: + result = copy.copy(self) + if name is not _KEEP: + result.name = name + if mtime is not _KEEP: + result.mtime = mtime + if mode is not _KEEP: + result.mode = mode + if linkname is not _KEEP: + result.linkname = linkname + if uid is not _KEEP: + result.uid = uid + if gid is not _KEEP: + result.gid = gid + if uname is not _KEEP: + result.uname = uname + if gname is not _KEEP: + result.gname = gname + return result + + def get_info(self): + """Return the TarInfo's attributes as a dictionary. + """ + if self.mode is None: + mode = None + else: + mode = self.mode & 0o7777 + info = { + "name": self.name, + "mode": mode, + "uid": self.uid, + "gid": self.gid, + "size": self.size, + "mtime": self.mtime, + "chksum": self.chksum, + "type": self.type, + "linkname": self.linkname, + "uname": self.uname, + "gname": self.gname, + "devmajor": self.devmajor, + "devminor": self.devminor + } + + if info["type"] == DIRTYPE and not info["name"].endswith("/"): + info["name"] += "/" + + return info + + def tobuf(self, format=DEFAULT_FORMAT, encoding=ENCODING, errors="surrogateescape"): + """Return a tar header as a string of 512 byte blocks. + """ + info = self.get_info() + for name, value in info.items(): + if value is None: + raise ValueError("%s may not be None" % name) + + if format == USTAR_FORMAT: + return self.create_ustar_header(info, encoding, errors) + elif format == GNU_FORMAT: + return self.create_gnu_header(info, encoding, errors) + elif format == PAX_FORMAT: + return self.create_pax_header(info, encoding) + else: + raise ValueError("invalid format") + + def create_ustar_header(self, info, encoding, errors): + """Return the object as a ustar header block. + """ + info["magic"] = POSIX_MAGIC + + if len(info["linkname"].encode(encoding, errors)) > LENGTH_LINK: + raise ValueError("linkname is too long") + + if len(info["name"].encode(encoding, errors)) > LENGTH_NAME: + info["prefix"], info["name"] = self._posix_split_name(info["name"], encoding, errors) + + return self._create_header(info, USTAR_FORMAT, encoding, errors) + + def create_gnu_header(self, info, encoding, errors): + """Return the object as a GNU header block sequence. + """ + info["magic"] = GNU_MAGIC + + buf = b"" + if len(info["linkname"].encode(encoding, errors)) > LENGTH_LINK: + buf += self._create_gnu_long_header(info["linkname"], GNUTYPE_LONGLINK, encoding, errors) + + if len(info["name"].encode(encoding, errors)) > LENGTH_NAME: + buf += self._create_gnu_long_header(info["name"], GNUTYPE_LONGNAME, encoding, errors) + + return buf + self._create_header(info, GNU_FORMAT, encoding, errors) + + def create_pax_header(self, info, encoding): + """Return the object as a ustar header block. If it cannot be + represented this way, prepend a pax extended header sequence + with supplement information. + """ + info["magic"] = POSIX_MAGIC + pax_headers = self.pax_headers.copy() + + # Test string fields for values that exceed the field length or cannot + # be represented in ASCII encoding. + for name, hname, length in ( + ("name", "path", LENGTH_NAME), ("linkname", "linkpath", LENGTH_LINK), + ("uname", "uname", 32), ("gname", "gname", 32)): + + if hname in pax_headers: + # The pax header has priority. + continue + + # Try to encode the string as ASCII. + try: + info[name].encode("ascii", "strict") + except UnicodeEncodeError: + pax_headers[hname] = info[name] + continue + + if len(info[name]) > length: + pax_headers[hname] = info[name] + + # Test number fields for values that exceed the field limit or values + # that like to be stored as float. + for name, digits in (("uid", 8), ("gid", 8), ("size", 12), ("mtime", 12)): + needs_pax = False + + val = info[name] + val_is_float = isinstance(val, float) + val_int = round(val) if val_is_float else val + if not 0 <= val_int < 8 ** (digits - 1): + # Avoid overflow. + info[name] = 0 + needs_pax = True + elif val_is_float: + # Put rounded value in ustar header, and full + # precision value in pax header. + info[name] = val_int + needs_pax = True + + # The existing pax header has priority. + if needs_pax and name not in pax_headers: + pax_headers[name] = str(val) + + # Create a pax extended header if necessary. + if pax_headers: + buf = self._create_pax_generic_header(pax_headers, XHDTYPE, encoding) + else: + buf = b"" + + return buf + self._create_header(info, USTAR_FORMAT, "ascii", "replace") + + @classmethod + def create_pax_global_header(cls, pax_headers): + """Return the object as a pax global header block sequence. + """ + return cls._create_pax_generic_header(pax_headers, XGLTYPE, "utf-8") + + def _posix_split_name(self, name, encoding, errors): + """Split a name longer than 100 chars into a prefix + and a name part. + """ + components = name.split("/") + for i in range(1, len(components)): + prefix = "/".join(components[:i]) + name = "/".join(components[i:]) + if len(prefix.encode(encoding, errors)) <= LENGTH_PREFIX and \ + len(name.encode(encoding, errors)) <= LENGTH_NAME: + break + else: + raise ValueError("name is too long") + + return prefix, name + + @staticmethod + def _create_header(info, format, encoding, errors): + """Return a header block. info is a dictionary with file + information, format must be one of the *_FORMAT constants. + """ + has_device_fields = info.get("type") in (CHRTYPE, BLKTYPE) + if has_device_fields: + devmajor = itn(info.get("devmajor", 0), 8, format) + devminor = itn(info.get("devminor", 0), 8, format) + else: + devmajor = stn("", 8, encoding, errors) + devminor = stn("", 8, encoding, errors) + + # None values in metadata should cause ValueError. + # itn()/stn() do this for all fields except type. + filetype = info.get("type", REGTYPE) + if filetype is None: + raise ValueError("TarInfo.type must not be None") + + parts = [ + stn(info.get("name", ""), 100, encoding, errors), + itn(info.get("mode", 0) & 0o7777, 8, format), + itn(info.get("uid", 0), 8, format), + itn(info.get("gid", 0), 8, format), + itn(info.get("size", 0), 12, format), + itn(info.get("mtime", 0), 12, format), + b" ", # checksum field + filetype, + stn(info.get("linkname", ""), 100, encoding, errors), + info.get("magic", POSIX_MAGIC), + stn(info.get("uname", ""), 32, encoding, errors), + stn(info.get("gname", ""), 32, encoding, errors), + devmajor, + devminor, + stn(info.get("prefix", ""), 155, encoding, errors) + ] + + buf = struct.pack("%ds" % BLOCKSIZE, b"".join(parts)) + chksum = calc_chksums(buf[-BLOCKSIZE:])[0] + buf = buf[:-364] + bytes("%06o\0" % chksum, "ascii") + buf[-357:] + return buf + + @staticmethod + def _create_payload(payload): + """Return the string payload filled with zero bytes + up to the next 512 byte border. + """ + blocks, remainder = divmod(len(payload), BLOCKSIZE) + if remainder > 0: + payload += (BLOCKSIZE - remainder) * NUL + return payload + + @classmethod + def _create_gnu_long_header(cls, name, type, encoding, errors): + """Return a GNUTYPE_LONGNAME or GNUTYPE_LONGLINK sequence + for name. + """ + name = name.encode(encoding, errors) + NUL + + info = {} + info["name"] = "././@LongLink" + info["type"] = type + info["size"] = len(name) + info["magic"] = GNU_MAGIC + + # create extended header + name blocks. + return cls._create_header(info, USTAR_FORMAT, encoding, errors) + \ + cls._create_payload(name) + + @classmethod + def _create_pax_generic_header(cls, pax_headers, type, encoding): + """Return a POSIX.1-2008 extended or global header sequence + that contains a list of keyword, value pairs. The values + must be strings. + """ + # Check if one of the fields contains surrogate characters and thereby + # forces hdrcharset=BINARY, see _proc_pax() for more information. + binary = False + for keyword, value in pax_headers.items(): + try: + value.encode("utf-8", "strict") + except UnicodeEncodeError: + binary = True + break + + records = b"" + if binary: + # Put the hdrcharset field at the beginning of the header. + records += b"21 hdrcharset=BINARY\n" + + for keyword, value in pax_headers.items(): + keyword = keyword.encode("utf-8") + if binary: + # Try to restore the original byte representation of 'value'. + # Needless to say, that the encoding must match the string. + value = value.encode(encoding, "surrogateescape") + else: + value = value.encode("utf-8") + + l = len(keyword) + len(value) + 3 # ' ' + '=' + '\n' + n = p = 0 + while True: + n = l + len(str(p)) + if n == p: + break + p = n + records += bytes(str(p), "ascii") + b" " + keyword + b"=" + value + b"\n" + + # We use a hardcoded "././@PaxHeader" name like star does + # instead of the one that POSIX recommends. + info = {} + info["name"] = "././@PaxHeader" + info["type"] = type + info["size"] = len(records) + info["magic"] = POSIX_MAGIC + + # Create pax header + record blocks. + return cls._create_header(info, USTAR_FORMAT, "ascii", "replace") + \ + cls._create_payload(records) + + @classmethod + def frombuf(cls, buf, encoding, errors): + """Construct a TarInfo object from a 512 byte bytes object. + """ + if len(buf) == 0: + raise EmptyHeaderError("empty header") + if len(buf) != BLOCKSIZE: + raise TruncatedHeaderError("truncated header") + if buf.count(NUL) == BLOCKSIZE: + raise EOFHeaderError("end of file header") + + chksum = nti(buf[148:156]) + if chksum not in calc_chksums(buf): + raise InvalidHeaderError("bad checksum") + + obj = cls() + obj.name = nts(buf[0:100], encoding, errors) + obj.mode = nti(buf[100:108]) + obj.uid = nti(buf[108:116]) + obj.gid = nti(buf[116:124]) + obj.size = nti(buf[124:136]) + obj.mtime = nti(buf[136:148]) + obj.chksum = chksum + obj.type = buf[156:157] + obj.linkname = nts(buf[157:257], encoding, errors) + obj.uname = nts(buf[265:297], encoding, errors) + obj.gname = nts(buf[297:329], encoding, errors) + obj.devmajor = nti(buf[329:337]) + obj.devminor = nti(buf[337:345]) + prefix = nts(buf[345:500], encoding, errors) + + # Old V7 tar format represents a directory as a regular + # file with a trailing slash. + if obj.type == AREGTYPE and obj.name.endswith("/"): + obj.type = DIRTYPE + + # The old GNU sparse format occupies some of the unused + # space in the buffer for up to 4 sparse structures. + # Save them for later processing in _proc_sparse(). + if obj.type == GNUTYPE_SPARSE: + pos = 386 + structs = [] + for i in range(4): + try: + offset = nti(buf[pos:pos + 12]) + numbytes = nti(buf[pos + 12:pos + 24]) + except ValueError: + break + structs.append((offset, numbytes)) + pos += 24 + isextended = bool(buf[482]) + origsize = nti(buf[483:495]) + obj._sparse_structs = (structs, isextended, origsize) + + # Remove redundant slashes from directories. + if obj.isdir(): + obj.name = obj.name.rstrip("/") + + # Reconstruct a ustar longname. + if prefix and obj.type not in GNU_TYPES: + obj.name = prefix + "/" + obj.name + return obj + + @classmethod + def fromtarfile(cls, tarfile): + """Return the next TarInfo object from TarFile object + tarfile. + """ + buf = tarfile.fileobj.read(BLOCKSIZE) + obj = cls.frombuf(buf, tarfile.encoding, tarfile.errors) + obj.offset = tarfile.fileobj.tell() - BLOCKSIZE + return obj._proc_member(tarfile) + + #-------------------------------------------------------------------------- + # The following are methods that are called depending on the type of a + # member. The entry point is _proc_member() which can be overridden in a + # subclass to add custom _proc_*() methods. A _proc_*() method MUST + # implement the following + # operations: + # 1. Set self.offset_data to the position where the data blocks begin, + # if there is data that follows. + # 2. Set tarfile.offset to the position where the next member's header will + # begin. + # 3. Return self or another valid TarInfo object. + def _proc_member(self, tarfile): + """Choose the right processing method depending on + the type and call it. + """ + if self.type in (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK): + return self._proc_gnulong(tarfile) + elif self.type == GNUTYPE_SPARSE: + return self._proc_sparse(tarfile) + elif self.type in (XHDTYPE, XGLTYPE, SOLARIS_XHDTYPE): + return self._proc_pax(tarfile) + else: + return self._proc_builtin(tarfile) + + def _proc_builtin(self, tarfile): + """Process a builtin type or an unknown type which + will be treated as a regular file. + """ + self.offset_data = tarfile.fileobj.tell() + offset = self.offset_data + if self.isreg() or self.type not in SUPPORTED_TYPES: + # Skip the following data blocks. + offset += self._block(self.size) + tarfile.offset = offset + + # Patch the TarInfo object with saved global + # header information. + self._apply_pax_info(tarfile.pax_headers, tarfile.encoding, tarfile.errors) + + # Remove redundant slashes from directories. This is to be consistent + # with frombuf(). + if self.isdir(): + self.name = self.name.rstrip("/") + + return self + + def _proc_gnulong(self, tarfile): + """Process the blocks that hold a GNU longname + or longlink member. + """ + buf = tarfile.fileobj.read(self._block(self.size)) + + # Fetch the next header and process it. + try: + next = self.fromtarfile(tarfile) + except HeaderError as e: + raise SubsequentHeaderError(str(e)) from None + + # Patch the TarInfo object from the next header with + # the longname information. + next.offset = self.offset + if self.type == GNUTYPE_LONGNAME: + next.name = nts(buf, tarfile.encoding, tarfile.errors) + elif self.type == GNUTYPE_LONGLINK: + next.linkname = nts(buf, tarfile.encoding, tarfile.errors) + + # Remove redundant slashes from directories. This is to be consistent + # with frombuf(). + if next.isdir(): + next.name = removesuffix(next.name, "/") + + return next + + def _proc_sparse(self, tarfile): + """Process a GNU sparse header plus extra headers. + """ + # We already collected some sparse structures in frombuf(). + structs, isextended, origsize = self._sparse_structs + del self._sparse_structs + + # Collect sparse structures from extended header blocks. + while isextended: + buf = tarfile.fileobj.read(BLOCKSIZE) + pos = 0 + for i in range(21): + try: + offset = nti(buf[pos:pos + 12]) + numbytes = nti(buf[pos + 12:pos + 24]) + except ValueError: + break + if offset and numbytes: + structs.append((offset, numbytes)) + pos += 24 + isextended = bool(buf[504]) + self.sparse = structs + + self.offset_data = tarfile.fileobj.tell() + tarfile.offset = self.offset_data + self._block(self.size) + self.size = origsize + return self + + def _proc_pax(self, tarfile): + """Process an extended or global header as described in + POSIX.1-2008. + """ + # Read the header information. + buf = tarfile.fileobj.read(self._block(self.size)) + + # A pax header stores supplemental information for either + # the following file (extended) or all following files + # (global). + if self.type == XGLTYPE: + pax_headers = tarfile.pax_headers + else: + pax_headers = tarfile.pax_headers.copy() + + # Check if the pax header contains a hdrcharset field. This tells us + # the encoding of the path, linkpath, uname and gname fields. Normally, + # these fields are UTF-8 encoded but since POSIX.1-2008 tar + # implementations are allowed to store them as raw binary strings if + # the translation to UTF-8 fails. + match = re.search(br"\d+ hdrcharset=([^\n]+)\n", buf) + if match is not None: + pax_headers["hdrcharset"] = match.group(1).decode("utf-8") + + # For the time being, we don't care about anything other than "BINARY". + # The only other value that is currently allowed by the standard is + # "ISO-IR 10646 2000 UTF-8" in other words UTF-8. + hdrcharset = pax_headers.get("hdrcharset") + if hdrcharset == "BINARY": + encoding = tarfile.encoding + else: + encoding = "utf-8" + + # Parse pax header information. A record looks like that: + # "%d %s=%s\n" % (length, keyword, value). length is the size + # of the complete record including the length field itself and + # the newline. keyword and value are both UTF-8 encoded strings. + regex = re.compile(br"(\d+) ([^=]+)=") + pos = 0 + while match := regex.match(buf, pos): + length, keyword = match.groups() + length = int(length) + if length == 0: + raise InvalidHeaderError("invalid header") + value = buf[match.end(2) + 1:match.start(1) + length - 1] + + # Normally, we could just use "utf-8" as the encoding and "strict" + # as the error handler, but we better not take the risk. For + # example, GNU tar <= 1.23 is known to store filenames it cannot + # translate to UTF-8 as raw strings (unfortunately without a + # hdrcharset=BINARY header). + # We first try the strict standard encoding, and if that fails we + # fall back on the user's encoding and error handler. + keyword = self._decode_pax_field(keyword, "utf-8", "utf-8", + tarfile.errors) + if keyword in PAX_NAME_FIELDS: + value = self._decode_pax_field(value, encoding, tarfile.encoding, + tarfile.errors) + else: + value = self._decode_pax_field(value, "utf-8", "utf-8", + tarfile.errors) + + pax_headers[keyword] = value + pos += length + + # Fetch the next header. + try: + next = self.fromtarfile(tarfile) + except HeaderError as e: + raise SubsequentHeaderError(str(e)) from None + + # Process GNU sparse information. + if "GNU.sparse.map" in pax_headers: + # GNU extended sparse format version 0.1. + self._proc_gnusparse_01(next, pax_headers) + + elif "GNU.sparse.size" in pax_headers: + # GNU extended sparse format version 0.0. + self._proc_gnusparse_00(next, pax_headers, buf) + + elif pax_headers.get("GNU.sparse.major") == "1" and pax_headers.get("GNU.sparse.minor") == "0": + # GNU extended sparse format version 1.0. + self._proc_gnusparse_10(next, pax_headers, tarfile) + + if self.type in (XHDTYPE, SOLARIS_XHDTYPE): + # Patch the TarInfo object with the extended header info. + next._apply_pax_info(pax_headers, tarfile.encoding, tarfile.errors) + next.offset = self.offset + + if "size" in pax_headers: + # If the extended header replaces the size field, + # we need to recalculate the offset where the next + # header starts. + offset = next.offset_data + if next.isreg() or next.type not in SUPPORTED_TYPES: + offset += next._block(next.size) + tarfile.offset = offset + + return next + + def _proc_gnusparse_00(self, next, pax_headers, buf): + """Process a GNU tar extended sparse header, version 0.0. + """ + offsets = [] + for match in re.finditer(br"\d+ GNU.sparse.offset=(\d+)\n", buf): + offsets.append(int(match.group(1))) + numbytes = [] + for match in re.finditer(br"\d+ GNU.sparse.numbytes=(\d+)\n", buf): + numbytes.append(int(match.group(1))) + next.sparse = list(zip(offsets, numbytes)) + + def _proc_gnusparse_01(self, next, pax_headers): + """Process a GNU tar extended sparse header, version 0.1. + """ + sparse = [int(x) for x in pax_headers["GNU.sparse.map"].split(",")] + next.sparse = list(zip(sparse[::2], sparse[1::2])) + + def _proc_gnusparse_10(self, next, pax_headers, tarfile): + """Process a GNU tar extended sparse header, version 1.0. + """ + fields = None + sparse = [] + buf = tarfile.fileobj.read(BLOCKSIZE) + fields, buf = buf.split(b"\n", 1) + fields = int(fields) + while len(sparse) < fields * 2: + if b"\n" not in buf: + buf += tarfile.fileobj.read(BLOCKSIZE) + number, buf = buf.split(b"\n", 1) + sparse.append(int(number)) + next.offset_data = tarfile.fileobj.tell() + next.sparse = list(zip(sparse[::2], sparse[1::2])) + + def _apply_pax_info(self, pax_headers, encoding, errors): + """Replace fields with supplemental information from a previous + pax extended or global header. + """ + for keyword, value in pax_headers.items(): + if keyword == "GNU.sparse.name": + setattr(self, "path", value) + elif keyword == "GNU.sparse.size": + setattr(self, "size", int(value)) + elif keyword == "GNU.sparse.realsize": + setattr(self, "size", int(value)) + elif keyword in PAX_FIELDS: + if keyword in PAX_NUMBER_FIELDS: + try: + value = PAX_NUMBER_FIELDS[keyword](value) + except ValueError: + value = 0 + if keyword == "path": + value = value.rstrip("/") + setattr(self, keyword, value) + + self.pax_headers = pax_headers.copy() + + def _decode_pax_field(self, value, encoding, fallback_encoding, fallback_errors): + """Decode a single field from a pax record. + """ + try: + return value.decode(encoding, "strict") + except UnicodeDecodeError: + return value.decode(fallback_encoding, fallback_errors) + + def _block(self, count): + """Round up a byte count by BLOCKSIZE and return it, + e.g. _block(834) => 1024. + """ + blocks, remainder = divmod(count, BLOCKSIZE) + if remainder: + blocks += 1 + return blocks * BLOCKSIZE + + def isreg(self): + 'Return True if the Tarinfo object is a regular file.' + return self.type in REGULAR_TYPES + + def isfile(self): + 'Return True if the Tarinfo object is a regular file.' + return self.isreg() + + def isdir(self): + 'Return True if it is a directory.' + return self.type == DIRTYPE + + def issym(self): + 'Return True if it is a symbolic link.' + return self.type == SYMTYPE + + def islnk(self): + 'Return True if it is a hard link.' + return self.type == LNKTYPE + + def ischr(self): + 'Return True if it is a character device.' + return self.type == CHRTYPE + + def isblk(self): + 'Return True if it is a block device.' + return self.type == BLKTYPE + + def isfifo(self): + 'Return True if it is a FIFO.' + return self.type == FIFOTYPE + + def issparse(self): + return self.sparse is not None + + def isdev(self): + 'Return True if it is one of character device, block device or FIFO.' + return self.type in (CHRTYPE, BLKTYPE, FIFOTYPE) +# class TarInfo + +class TarFile(object): + """The TarFile Class provides an interface to tar archives. + """ + + debug = 0 # May be set from 0 (no msgs) to 3 (all msgs) + + dereference = False # If true, add content of linked file to the + # tar file, else the link. + + ignore_zeros = False # If true, skips empty or invalid blocks and + # continues processing. + + errorlevel = 1 # If 0, fatal errors only appear in debug + # messages (if debug >= 0). If > 0, errors + # are passed to the caller as exceptions. + + format = DEFAULT_FORMAT # The format to use when creating an archive. + + encoding = ENCODING # Encoding for 8-bit character strings. + + errors = None # Error handler for unicode conversion. + + tarinfo = TarInfo # The default TarInfo class to use. + + fileobject = ExFileObject # The file-object for extractfile(). + + extraction_filter = None # The default filter for extraction. + + def __init__(self, name=None, mode="r", fileobj=None, format=None, + tarinfo=None, dereference=None, ignore_zeros=None, encoding=None, + errors="surrogateescape", pax_headers=None, debug=None, + errorlevel=None, copybufsize=None, stream=False): + """Open an (uncompressed) tar archive 'name'. 'mode' is either 'r' to + read from an existing archive, 'a' to append data to an existing + file or 'w' to create a new file overwriting an existing one. 'mode' + defaults to 'r'. + If 'fileobj' is given, it is used for reading or writing data. If it + can be determined, 'mode' is overridden by 'fileobj's mode. + 'fileobj' is not closed, when TarFile is closed. + """ + modes = {"r": "rb", "a": "r+b", "w": "wb", "x": "xb"} + if mode not in modes: + raise ValueError("mode must be 'r', 'a', 'w' or 'x'") + self.mode = mode + self._mode = modes[mode] + + if not fileobj: + if self.mode == "a" and not os.path.exists(name): + # Create nonexistent files in append mode. + self.mode = "w" + self._mode = "wb" + fileobj = bltn_open(name, self._mode) + self._extfileobj = False + else: + if (name is None and hasattr(fileobj, "name") and + isinstance(fileobj.name, (str, bytes))): + name = fileobj.name + if hasattr(fileobj, "mode"): + self._mode = fileobj.mode + self._extfileobj = True + self.name = os.path.abspath(name) if name else None + self.fileobj = fileobj + + self.stream = stream + + # Init attributes. + if format is not None: + self.format = format + if tarinfo is not None: + self.tarinfo = tarinfo + if dereference is not None: + self.dereference = dereference + if ignore_zeros is not None: + self.ignore_zeros = ignore_zeros + if encoding is not None: + self.encoding = encoding + self.errors = errors + + if pax_headers is not None and self.format == PAX_FORMAT: + self.pax_headers = pax_headers + else: + self.pax_headers = {} + + if debug is not None: + self.debug = debug + if errorlevel is not None: + self.errorlevel = errorlevel + + # Init datastructures. + self.copybufsize = copybufsize + self.closed = False + self.members = [] # list of members as TarInfo objects + self._loaded = False # flag if all members have been read + self.offset = self.fileobj.tell() + # current position in the archive file + self.inodes = {} # dictionary caching the inodes of + # archive members already added + + try: + if self.mode == "r": + self.firstmember = None + self.firstmember = self.next() + + if self.mode == "a": + # Move to the end of the archive, + # before the first empty block. + while True: + self.fileobj.seek(self.offset) + try: + tarinfo = self.tarinfo.fromtarfile(self) + self.members.append(tarinfo) + except EOFHeaderError: + self.fileobj.seek(self.offset) + break + except HeaderError as e: + raise ReadError(str(e)) from None + + if self.mode in ("a", "w", "x"): + self._loaded = True + + if self.pax_headers: + buf = self.tarinfo.create_pax_global_header(self.pax_headers.copy()) + self.fileobj.write(buf) + self.offset += len(buf) + except: + if not self._extfileobj: + self.fileobj.close() + self.closed = True + raise + + #-------------------------------------------------------------------------- + # Below are the classmethods which act as alternate constructors to the + # TarFile class. The open() method is the only one that is needed for + # public use; it is the "super"-constructor and is able to select an + # adequate "sub"-constructor for a particular compression using the mapping + # from OPEN_METH. + # + # This concept allows one to subclass TarFile without losing the comfort of + # the super-constructor. A sub-constructor is registered and made available + # by adding it to the mapping in OPEN_METH. + + @classmethod + def open(cls, name=None, mode="r", fileobj=None, bufsize=RECORDSIZE, **kwargs): + r"""Open a tar archive for reading, writing or appending. Return + an appropriate TarFile class. + + mode: + 'r' or 'r:\*' open for reading with transparent compression + 'r:' open for reading exclusively uncompressed + 'r:gz' open for reading with gzip compression + 'r:bz2' open for reading with bzip2 compression + 'r:xz' open for reading with lzma compression + 'a' or 'a:' open for appending, creating the file if necessary + 'w' or 'w:' open for writing without compression + 'w:gz' open for writing with gzip compression + 'w:bz2' open for writing with bzip2 compression + 'w:xz' open for writing with lzma compression + + 'x' or 'x:' create a tarfile exclusively without compression, raise + an exception if the file is already created + 'x:gz' create a gzip compressed tarfile, raise an exception + if the file is already created + 'x:bz2' create a bzip2 compressed tarfile, raise an exception + if the file is already created + 'x:xz' create an lzma compressed tarfile, raise an exception + if the file is already created + + 'r|\*' open a stream of tar blocks with transparent compression + 'r|' open an uncompressed stream of tar blocks for reading + 'r|gz' open a gzip compressed stream of tar blocks + 'r|bz2' open a bzip2 compressed stream of tar blocks + 'r|xz' open an lzma compressed stream of tar blocks + 'w|' open an uncompressed stream for writing + 'w|gz' open a gzip compressed stream for writing + 'w|bz2' open a bzip2 compressed stream for writing + 'w|xz' open an lzma compressed stream for writing + """ + + if not name and not fileobj: + raise ValueError("nothing to open") + + if mode in ("r", "r:*"): + # Find out which *open() is appropriate for opening the file. + def not_compressed(comptype): + return cls.OPEN_METH[comptype] == 'taropen' + error_msgs = [] + for comptype in sorted(cls.OPEN_METH, key=not_compressed): + func = getattr(cls, cls.OPEN_METH[comptype]) + if fileobj is not None: + saved_pos = fileobj.tell() + try: + return func(name, "r", fileobj, **kwargs) + except (ReadError, CompressionError) as e: + error_msgs.append(f'- method {comptype}: {e!r}') + if fileobj is not None: + fileobj.seek(saved_pos) + continue + error_msgs_summary = '\n'.join(error_msgs) + raise ReadError(f"file could not be opened successfully:\n{error_msgs_summary}") + + elif ":" in mode: + filemode, comptype = mode.split(":", 1) + filemode = filemode or "r" + comptype = comptype or "tar" + + # Select the *open() function according to + # given compression. + if comptype in cls.OPEN_METH: + func = getattr(cls, cls.OPEN_METH[comptype]) + else: + raise CompressionError("unknown compression type %r" % comptype) + return func(name, filemode, fileobj, **kwargs) + + elif "|" in mode: + filemode, comptype = mode.split("|", 1) + filemode = filemode or "r" + comptype = comptype or "tar" + + if filemode not in ("r", "w"): + raise ValueError("mode must be 'r' or 'w'") + + compresslevel = kwargs.pop("compresslevel", 9) + stream = _Stream(name, filemode, comptype, fileobj, bufsize, + compresslevel) + try: + t = cls(name, filemode, stream, **kwargs) + except: + stream.close() + raise + t._extfileobj = False + return t + + elif mode in ("a", "w", "x"): + return cls.taropen(name, mode, fileobj, **kwargs) + + raise ValueError("undiscernible mode") + + @classmethod + def taropen(cls, name, mode="r", fileobj=None, **kwargs): + """Open uncompressed tar archive name for reading or writing. + """ + if mode not in ("r", "a", "w", "x"): + raise ValueError("mode must be 'r', 'a', 'w' or 'x'") + return cls(name, mode, fileobj, **kwargs) + + @classmethod + def gzopen(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs): + """Open gzip compressed tar archive name for reading or writing. + Appending is not allowed. + """ + if mode not in ("r", "w", "x"): + raise ValueError("mode must be 'r', 'w' or 'x'") + + try: + from gzip import GzipFile + except ImportError: + raise CompressionError("gzip module is not available") from None + + try: + fileobj = GzipFile(name, mode + "b", compresslevel, fileobj) + except OSError as e: + if fileobj is not None and mode == 'r': + raise ReadError("not a gzip file") from e + raise + + try: + t = cls.taropen(name, mode, fileobj, **kwargs) + except OSError as e: + fileobj.close() + if mode == 'r': + raise ReadError("not a gzip file") from e + raise + except: + fileobj.close() + raise + t._extfileobj = False + return t + + @classmethod + def bz2open(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs): + """Open bzip2 compressed tar archive name for reading or writing. + Appending is not allowed. + """ + if mode not in ("r", "w", "x"): + raise ValueError("mode must be 'r', 'w' or 'x'") + + try: + from bz2 import BZ2File + except ImportError: + raise CompressionError("bz2 module is not available") from None + + fileobj = BZ2File(fileobj or name, mode, compresslevel=compresslevel) + + try: + t = cls.taropen(name, mode, fileobj, **kwargs) + except (OSError, EOFError) as e: + fileobj.close() + if mode == 'r': + raise ReadError("not a bzip2 file") from e + raise + except: + fileobj.close() + raise + t._extfileobj = False + return t + + @classmethod + def xzopen(cls, name, mode="r", fileobj=None, preset=None, **kwargs): + """Open lzma compressed tar archive name for reading or writing. + Appending is not allowed. + """ + if mode not in ("r", "w", "x"): + raise ValueError("mode must be 'r', 'w' or 'x'") + + try: + from lzma import LZMAFile, LZMAError + except ImportError: + raise CompressionError("lzma module is not available") from None + + fileobj = LZMAFile(fileobj or name, mode, preset=preset) + + try: + t = cls.taropen(name, mode, fileobj, **kwargs) + except (LZMAError, EOFError) as e: + fileobj.close() + if mode == 'r': + raise ReadError("not an lzma file") from e + raise + except: + fileobj.close() + raise + t._extfileobj = False + return t + + # All *open() methods are registered here. + OPEN_METH = { + "tar": "taropen", # uncompressed tar + "gz": "gzopen", # gzip compressed tar + "bz2": "bz2open", # bzip2 compressed tar + "xz": "xzopen" # lzma compressed tar + } + + #-------------------------------------------------------------------------- + # The public methods which TarFile provides: + + def close(self): + """Close the TarFile. In write-mode, two finishing zero blocks are + appended to the archive. + """ + if self.closed: + return + + self.closed = True + try: + if self.mode in ("a", "w", "x"): + self.fileobj.write(NUL * (BLOCKSIZE * 2)) + self.offset += (BLOCKSIZE * 2) + # fill up the end with zero-blocks + # (like option -b20 for tar does) + blocks, remainder = divmod(self.offset, RECORDSIZE) + if remainder > 0: + self.fileobj.write(NUL * (RECORDSIZE - remainder)) + finally: + if not self._extfileobj: + self.fileobj.close() + + def getmember(self, name): + """Return a TarInfo object for member 'name'. If 'name' can not be + found in the archive, KeyError is raised. If a member occurs more + than once in the archive, its last occurrence is assumed to be the + most up-to-date version. + """ + tarinfo = self._getmember(name.rstrip('/')) + if tarinfo is None: + raise KeyError("filename %r not found" % name) + return tarinfo + + def getmembers(self): + """Return the members of the archive as a list of TarInfo objects. The + list has the same order as the members in the archive. + """ + self._check() + if not self._loaded: # if we want to obtain a list of + self._load() # all members, we first have to + # scan the whole archive. + return self.members + + def getnames(self): + """Return the members of the archive as a list of their names. It has + the same order as the list returned by getmembers(). + """ + return [tarinfo.name for tarinfo in self.getmembers()] + + def gettarinfo(self, name=None, arcname=None, fileobj=None): + """Create a TarInfo object from the result of os.stat or equivalent + on an existing file. The file is either named by 'name', or + specified as a file object 'fileobj' with a file descriptor. If + given, 'arcname' specifies an alternative name for the file in the + archive, otherwise, the name is taken from the 'name' attribute of + 'fileobj', or the 'name' argument. The name should be a text + string. + """ + self._check("awx") + + # When fileobj is given, replace name by + # fileobj's real name. + if fileobj is not None: + name = fileobj.name + + # Building the name of the member in the archive. + # Backward slashes are converted to forward slashes, + # Absolute paths are turned to relative paths. + if arcname is None: + arcname = name + drv, arcname = os.path.splitdrive(arcname) + arcname = arcname.replace(os.sep, "/") + arcname = arcname.lstrip("/") + + # Now, fill the TarInfo object with + # information specific for the file. + tarinfo = self.tarinfo() + tarinfo._tarfile = self # To be removed in 3.16. + + # Use os.stat or os.lstat, depending on if symlinks shall be resolved. + if fileobj is None: + if not self.dereference: + statres = os.lstat(name) + else: + statres = os.stat(name) + else: + statres = os.fstat(fileobj.fileno()) + linkname = "" + + stmd = statres.st_mode + if stat.S_ISREG(stmd): + inode = (statres.st_ino, statres.st_dev) + if not self.dereference and statres.st_nlink > 1 and \ + inode in self.inodes and arcname != self.inodes[inode]: + # Is it a hardlink to an already + # archived file? + type = LNKTYPE + linkname = self.inodes[inode] + else: + # The inode is added only if its valid. + # For win32 it is always 0. + type = REGTYPE + if inode[0]: + self.inodes[inode] = arcname + elif stat.S_ISDIR(stmd): + type = DIRTYPE + elif stat.S_ISFIFO(stmd): + type = FIFOTYPE + elif stat.S_ISLNK(stmd): + type = SYMTYPE + linkname = os.readlink(name) + elif stat.S_ISCHR(stmd): + type = CHRTYPE + elif stat.S_ISBLK(stmd): + type = BLKTYPE + else: + return None + + # Fill the TarInfo object with all + # information we can get. + tarinfo.name = arcname + tarinfo.mode = stmd + tarinfo.uid = statres.st_uid + tarinfo.gid = statres.st_gid + if type == REGTYPE: + tarinfo.size = statres.st_size + else: + tarinfo.size = 0 + tarinfo.mtime = statres.st_mtime + tarinfo.type = type + tarinfo.linkname = linkname + if pwd: + try: + tarinfo.uname = pwd.getpwuid(tarinfo.uid)[0] + except KeyError: + pass + if grp: + try: + tarinfo.gname = grp.getgrgid(tarinfo.gid)[0] + except KeyError: + pass + + if type in (CHRTYPE, BLKTYPE): + if hasattr(os, "major") and hasattr(os, "minor"): + tarinfo.devmajor = os.major(statres.st_rdev) + tarinfo.devminor = os.minor(statres.st_rdev) + return tarinfo + + def list(self, verbose=True, *, members=None): + """Print a table of contents to sys.stdout. If 'verbose' is False, only + the names of the members are printed. If it is True, an 'ls -l'-like + output is produced. 'members' is optional and must be a subset of the + list returned by getmembers(). + """ + # Convert tarinfo type to stat type. + type2mode = {REGTYPE: stat.S_IFREG, SYMTYPE: stat.S_IFLNK, + FIFOTYPE: stat.S_IFIFO, CHRTYPE: stat.S_IFCHR, + DIRTYPE: stat.S_IFDIR, BLKTYPE: stat.S_IFBLK} + self._check() + + if members is None: + members = self + for tarinfo in members: + if verbose: + if tarinfo.mode is None: + _safe_print("??????????") + else: + modetype = type2mode.get(tarinfo.type, 0) + _safe_print(stat.filemode(modetype | tarinfo.mode)) + _safe_print("%s/%s" % (tarinfo.uname or tarinfo.uid, + tarinfo.gname or tarinfo.gid)) + if tarinfo.ischr() or tarinfo.isblk(): + _safe_print("%10s" % + ("%d,%d" % (tarinfo.devmajor, tarinfo.devminor))) + else: + _safe_print("%10d" % tarinfo.size) + if tarinfo.mtime is None: + _safe_print("????-??-?? ??:??:??") + else: + _safe_print("%d-%02d-%02d %02d:%02d:%02d" \ + % time.localtime(tarinfo.mtime)[:6]) + + _safe_print(tarinfo.name + ("/" if tarinfo.isdir() else "")) + + if verbose: + if tarinfo.issym(): + _safe_print("-> " + tarinfo.linkname) + if tarinfo.islnk(): + _safe_print("link to " + tarinfo.linkname) + print() + + def add(self, name, arcname=None, recursive=True, *, filter=None): + """Add the file 'name' to the archive. 'name' may be any type of file + (directory, fifo, symbolic link, etc.). If given, 'arcname' + specifies an alternative name for the file in the archive. + Directories are added recursively by default. This can be avoided by + setting 'recursive' to False. 'filter' is a function + that expects a TarInfo object argument and returns the changed + TarInfo object, if it returns None the TarInfo object will be + excluded from the archive. + """ + self._check("awx") + + if arcname is None: + arcname = name + + # Skip if somebody tries to archive the archive... + if self.name is not None and os.path.abspath(name) == self.name: + self._dbg(2, "tarfile: Skipped %r" % name) + return + + self._dbg(1, name) + + # Create a TarInfo object from the file. + tarinfo = self.gettarinfo(name, arcname) + + if tarinfo is None: + self._dbg(1, "tarfile: Unsupported type %r" % name) + return + + # Change or exclude the TarInfo object. + if filter is not None: + tarinfo = filter(tarinfo) + if tarinfo is None: + self._dbg(2, "tarfile: Excluded %r" % name) + return + + # Append the tar header and data to the archive. + if tarinfo.isreg(): + with bltn_open(name, "rb") as f: + self.addfile(tarinfo, f) + + elif tarinfo.isdir(): + self.addfile(tarinfo) + if recursive: + for f in sorted(os.listdir(name)): + self.add(os.path.join(name, f), os.path.join(arcname, f), + recursive, filter=filter) + + else: + self.addfile(tarinfo) + + def addfile(self, tarinfo, fileobj=None): + """Add the TarInfo object 'tarinfo' to the archive. If 'tarinfo' represents + a non zero-size regular file, the 'fileobj' argument should be a binary file, + and tarinfo.size bytes are read from it and added to the archive. + You can create TarInfo objects directly, or by using gettarinfo(). + """ + self._check("awx") + + if fileobj is None and tarinfo.isreg() and tarinfo.size != 0: + raise ValueError("fileobj not provided for non zero-size regular file") + + tarinfo = copy.copy(tarinfo) + + buf = tarinfo.tobuf(self.format, self.encoding, self.errors) + self.fileobj.write(buf) + self.offset += len(buf) + bufsize=self.copybufsize + # If there's data to follow, append it. + if fileobj is not None: + copyfileobj(fileobj, self.fileobj, tarinfo.size, bufsize=bufsize) + blocks, remainder = divmod(tarinfo.size, BLOCKSIZE) + if remainder > 0: + self.fileobj.write(NUL * (BLOCKSIZE - remainder)) + blocks += 1 + self.offset += blocks * BLOCKSIZE + + self.members.append(tarinfo) + + def _get_filter_function(self, filter): + if filter is None: + filter = self.extraction_filter + if filter is None: + import warnings + warnings.warn( + 'Python 3.14 will, by default, filter extracted tar ' + + 'archives and reject files or modify their metadata. ' + + 'Use the filter argument to control this behavior.', + DeprecationWarning, stacklevel=3) + return fully_trusted_filter + if isinstance(filter, str): + raise TypeError( + 'String names are not supported for ' + + 'TarFile.extraction_filter. Use a function such as ' + + 'tarfile.data_filter directly.') + return filter + if callable(filter): + return filter + try: + return _NAMED_FILTERS[filter] + except KeyError: + raise ValueError(f"filter {filter!r} not found") from None + + def extractall(self, path=".", members=None, *, numeric_owner=False, + filter=None): + """Extract all members from the archive to the current working + directory and set owner, modification time and permissions on + directories afterwards. 'path' specifies a different directory + to extract to. 'members' is optional and must be a subset of the + list returned by getmembers(). If 'numeric_owner' is True, only + the numbers for user/group names are used and not the names. + + The 'filter' function will be called on each member just + before extraction. + It can return a changed TarInfo or None to skip the member. + String names of common filters are accepted. + """ + directories = [] + + filter_function = self._get_filter_function(filter) + if members is None: + members = self + + for member in members: + tarinfo = self._get_extract_tarinfo(member, filter_function, path) + if tarinfo is None: + continue + if tarinfo.isdir(): + # For directories, delay setting attributes until later, + # since permissions can interfere with extraction and + # extracting contents can reset mtime. + directories.append(tarinfo) + self._extract_one(tarinfo, path, set_attrs=not tarinfo.isdir(), + numeric_owner=numeric_owner) + + # Reverse sort directories. + directories.sort(key=lambda a: a.name, reverse=True) + + # Set correct owner, mtime and filemode on directories. + for tarinfo in directories: + dirpath = os.path.join(path, tarinfo.name) + try: + self.chown(tarinfo, dirpath, numeric_owner=numeric_owner) + self.utime(tarinfo, dirpath) + self.chmod(tarinfo, dirpath) + except ExtractError as e: + self._handle_nonfatal_error(e) + + def extract(self, member, path="", set_attrs=True, *, numeric_owner=False, + filter=None): + """Extract a member from the archive to the current working directory, + using its full name. Its file information is extracted as accurately + as possible. 'member' may be a filename or a TarInfo object. You can + specify a different directory using 'path'. File attributes (owner, + mtime, mode) are set unless 'set_attrs' is False. If 'numeric_owner' + is True, only the numbers for user/group names are used and not + the names. + + The 'filter' function will be called before extraction. + It can return a changed TarInfo or None to skip the member. + String names of common filters are accepted. + """ + filter_function = self._get_filter_function(filter) + tarinfo = self._get_extract_tarinfo(member, filter_function, path) + if tarinfo is not None: + self._extract_one(tarinfo, path, set_attrs, numeric_owner) + + def _get_extract_tarinfo(self, member, filter_function, path): + """Get filtered TarInfo (or None) from member, which might be a str""" + if isinstance(member, str): + tarinfo = self.getmember(member) + else: + tarinfo = member + + unfiltered = tarinfo + try: + tarinfo = filter_function(tarinfo, path) + except (OSError, FilterError) as e: + self._handle_fatal_error(e) + except ExtractError as e: + self._handle_nonfatal_error(e) + if tarinfo is None: + self._dbg(2, "tarfile: Excluded %r" % unfiltered.name) + return None + # Prepare the link target for makelink(). + if tarinfo.islnk(): + tarinfo = copy.copy(tarinfo) + tarinfo._link_target = os.path.join(path, tarinfo.linkname) + return tarinfo + + def _extract_one(self, tarinfo, path, set_attrs, numeric_owner): + """Extract from filtered tarinfo to disk""" + self._check("r") + + try: + self._extract_member(tarinfo, os.path.join(path, tarinfo.name), + set_attrs=set_attrs, + numeric_owner=numeric_owner) + except OSError as e: + self._handle_fatal_error(e) + except ExtractError as e: + self._handle_nonfatal_error(e) + + def _handle_nonfatal_error(self, e): + """Handle non-fatal error (ExtractError) according to errorlevel""" + if self.errorlevel > 1: + raise + else: + self._dbg(1, "tarfile: %s" % e) + + def _handle_fatal_error(self, e): + """Handle "fatal" error according to self.errorlevel""" + if self.errorlevel > 0: + raise + elif isinstance(e, OSError): + if e.filename is None: + self._dbg(1, "tarfile: %s" % e.strerror) + else: + self._dbg(1, "tarfile: %s %r" % (e.strerror, e.filename)) + else: + self._dbg(1, "tarfile: %s %s" % (type(e).__name__, e)) + + def extractfile(self, member): + """Extract a member from the archive as a file object. 'member' may be + a filename or a TarInfo object. If 'member' is a regular file or + a link, an io.BufferedReader object is returned. For all other + existing members, None is returned. If 'member' does not appear + in the archive, KeyError is raised. + """ + self._check("r") + + if isinstance(member, str): + tarinfo = self.getmember(member) + else: + tarinfo = member + + if tarinfo.isreg() or tarinfo.type not in SUPPORTED_TYPES: + # Members with unknown types are treated as regular files. + return self.fileobject(self, tarinfo) + + elif tarinfo.islnk() or tarinfo.issym(): + if isinstance(self.fileobj, _Stream): + # A small but ugly workaround for the case that someone tries + # to extract a (sym)link as a file-object from a non-seekable + # stream of tar blocks. + raise StreamError("cannot extract (sym)link as file object") + else: + # A (sym)link's file object is its target's file object. + return self.extractfile(self._find_link_target(tarinfo)) + else: + # If there's no data associated with the member (directory, chrdev, + # blkdev, etc.), return None instead of a file object. + return None + + def _extract_member(self, tarinfo, targetpath, set_attrs=True, + numeric_owner=False): + """Extract the TarInfo object tarinfo to a physical + file called targetpath. + """ + # Fetch the TarInfo object for the given name + # and build the destination pathname, replacing + # forward slashes to platform specific separators. + targetpath = targetpath.rstrip("/") + targetpath = targetpath.replace("/", os.sep) + + # Create all upper directories. + upperdirs = os.path.dirname(targetpath) + if upperdirs and not os.path.exists(upperdirs): + # Create directories that are not part of the archive with + # default permissions. + os.makedirs(upperdirs, exist_ok=True) + + if tarinfo.islnk() or tarinfo.issym(): + self._dbg(1, "%s -> %s" % (tarinfo.name, tarinfo.linkname)) + else: + self._dbg(1, tarinfo.name) + + if tarinfo.isreg(): + self.makefile(tarinfo, targetpath) + elif tarinfo.isdir(): + self.makedir(tarinfo, targetpath) + elif tarinfo.isfifo(): + self.makefifo(tarinfo, targetpath) + elif tarinfo.ischr() or tarinfo.isblk(): + self.makedev(tarinfo, targetpath) + elif tarinfo.islnk() or tarinfo.issym(): + self.makelink(tarinfo, targetpath) + elif tarinfo.type not in SUPPORTED_TYPES: + self.makeunknown(tarinfo, targetpath) + else: + self.makefile(tarinfo, targetpath) + + if set_attrs: + self.chown(tarinfo, targetpath, numeric_owner) + if not tarinfo.issym(): + self.chmod(tarinfo, targetpath) + self.utime(tarinfo, targetpath) + + #-------------------------------------------------------------------------- + # Below are the different file methods. They are called via + # _extract_member() when extract() is called. They can be replaced in a + # subclass to implement other functionality. + + def makedir(self, tarinfo, targetpath): + """Make a directory called targetpath. + """ + try: + if tarinfo.mode is None: + # Use the system's default mode + os.mkdir(targetpath) + else: + # Use a safe mode for the directory, the real mode is set + # later in _extract_member(). + os.mkdir(targetpath, 0o700) + except FileExistsError: + if not os.path.isdir(targetpath): + raise + + def makefile(self, tarinfo, targetpath): + """Make a file called targetpath. + """ + source = self.fileobj + source.seek(tarinfo.offset_data) + bufsize = self.copybufsize + with bltn_open(targetpath, "wb") as target: + if tarinfo.sparse is not None: + for offset, size in tarinfo.sparse: + target.seek(offset) + copyfileobj(source, target, size, ReadError, bufsize) + target.seek(tarinfo.size) + target.truncate() + else: + copyfileobj(source, target, tarinfo.size, ReadError, bufsize) + + def makeunknown(self, tarinfo, targetpath): + """Make a file from a TarInfo object with an unknown type + at targetpath. + """ + self.makefile(tarinfo, targetpath) + self._dbg(1, "tarfile: Unknown file type %r, " \ + "extracted as regular file." % tarinfo.type) + + def makefifo(self, tarinfo, targetpath): + """Make a fifo called targetpath. + """ + if hasattr(os, "mkfifo"): + os.mkfifo(targetpath) + else: + raise ExtractError("fifo not supported by system") + + def makedev(self, tarinfo, targetpath): + """Make a character or block device called targetpath. + """ + if not hasattr(os, "mknod") or not hasattr(os, "makedev"): + raise ExtractError("special devices not supported by system") + + mode = tarinfo.mode + if mode is None: + # Use mknod's default + mode = 0o600 + if tarinfo.isblk(): + mode |= stat.S_IFBLK + else: + mode |= stat.S_IFCHR + + os.mknod(targetpath, mode, + os.makedev(tarinfo.devmajor, tarinfo.devminor)) + + def makelink(self, tarinfo, targetpath): + """Make a (symbolic) link called targetpath. If it cannot be created + (platform limitation), we try to make a copy of the referenced file + instead of a link. + """ + try: + # For systems that support symbolic and hard links. + if tarinfo.issym(): + if os.path.lexists(targetpath): + # Avoid FileExistsError on following os.symlink. + os.unlink(targetpath) + os.symlink(tarinfo.linkname, targetpath) + else: + if os.path.exists(tarinfo._link_target): + os.link(tarinfo._link_target, targetpath) + else: + self._extract_member(self._find_link_target(tarinfo), + targetpath) + except symlink_exception: + try: + self._extract_member(self._find_link_target(tarinfo), + targetpath) + except KeyError: + raise ExtractError("unable to resolve link inside archive") from None + + def chown(self, tarinfo, targetpath, numeric_owner): + """Set owner of targetpath according to tarinfo. If numeric_owner + is True, use .gid/.uid instead of .gname/.uname. If numeric_owner + is False, fall back to .gid/.uid when the search based on name + fails. + """ + if hasattr(os, "geteuid") and os.geteuid() == 0: + # We have to be root to do so. + g = tarinfo.gid + u = tarinfo.uid + if not numeric_owner: + try: + if grp and tarinfo.gname: + g = grp.getgrnam(tarinfo.gname)[2] + except KeyError: + pass + try: + if pwd and tarinfo.uname: + u = pwd.getpwnam(tarinfo.uname)[2] + except KeyError: + pass + if g is None: + g = -1 + if u is None: + u = -1 + try: + if tarinfo.issym() and hasattr(os, "lchown"): + os.lchown(targetpath, u, g) + else: + os.chown(targetpath, u, g) + except (OSError, OverflowError) as e: + # OverflowError can be raised if an ID doesn't fit in 'id_t' + raise ExtractError("could not change owner") from e + + def chmod(self, tarinfo, targetpath): + """Set file permissions of targetpath according to tarinfo. + """ + if tarinfo.mode is None: + return + try: + os.chmod(targetpath, tarinfo.mode) + except OSError as e: + raise ExtractError("could not change mode") from e + + def utime(self, tarinfo, targetpath): + """Set modification time of targetpath according to tarinfo. + """ + mtime = tarinfo.mtime + if mtime is None: + return + if not hasattr(os, 'utime'): + return + try: + os.utime(targetpath, (mtime, mtime)) + except OSError as e: + raise ExtractError("could not change modification time") from e + + #-------------------------------------------------------------------------- + def next(self): + """Return the next member of the archive as a TarInfo object, when + TarFile is opened for reading. Return None if there is no more + available. + """ + self._check("ra") + if self.firstmember is not None: + m = self.firstmember + self.firstmember = None + return m + + # Advance the file pointer. + if self.offset != self.fileobj.tell(): + if self.offset == 0: + return None + self.fileobj.seek(self.offset - 1) + if not self.fileobj.read(1): + raise ReadError("unexpected end of data") + + # Read the next block. + tarinfo = None + while True: + try: + tarinfo = self.tarinfo.fromtarfile(self) + except EOFHeaderError as e: + if self.ignore_zeros: + self._dbg(2, "0x%X: %s" % (self.offset, e)) + self.offset += BLOCKSIZE + continue + except InvalidHeaderError as e: + if self.ignore_zeros: + self._dbg(2, "0x%X: %s" % (self.offset, e)) + self.offset += BLOCKSIZE + continue + elif self.offset == 0: + raise ReadError(str(e)) from None + except EmptyHeaderError: + if self.offset == 0: + raise ReadError("empty file") from None + except TruncatedHeaderError as e: + if self.offset == 0: + raise ReadError(str(e)) from None + except SubsequentHeaderError as e: + raise ReadError(str(e)) from None + except Exception as e: + try: + import zlib + if isinstance(e, zlib.error): + raise ReadError(f'zlib error: {e}') from None + else: + raise e + except ImportError: + raise e + break + + if tarinfo is not None: + # if streaming the file we do not want to cache the tarinfo + if not self.stream: + self.members.append(tarinfo) + else: + self._loaded = True + + return tarinfo + + #-------------------------------------------------------------------------- + # Little helper methods: + + def _getmember(self, name, tarinfo=None, normalize=False): + """Find an archive member by name from bottom to top. + If tarinfo is given, it is used as the starting point. + """ + # Ensure that all members have been loaded. + members = self.getmembers() + + # Limit the member search list up to tarinfo. + skipping = False + if tarinfo is not None: + try: + index = members.index(tarinfo) + except ValueError: + # The given starting point might be a (modified) copy. + # We'll later skip members until we find an equivalent. + skipping = True + else: + # Happy fast path + members = members[:index] + + if normalize: + name = os.path.normpath(name) + + for member in reversed(members): + if skipping: + if tarinfo.offset == member.offset: + skipping = False + continue + if normalize: + member_name = os.path.normpath(member.name) + else: + member_name = member.name + + if name == member_name: + return member + + if skipping: + # Starting point was not found + raise ValueError(tarinfo) + + def _load(self): + """Read through the entire archive file and look for readable + members. This should not run if the file is set to stream. + """ + if not self.stream: + while self.next() is not None: + pass + self._loaded = True + + def _check(self, mode=None): + """Check if TarFile is still open, and if the operation's mode + corresponds to TarFile's mode. + """ + if self.closed: + raise OSError("%s is closed" % self.__class__.__name__) + if mode is not None and self.mode not in mode: + raise OSError("bad operation for mode %r" % self.mode) + + def _find_link_target(self, tarinfo): + """Find the target member of a symlink or hardlink member in the + archive. + """ + if tarinfo.issym(): + # Always search the entire archive. + linkname = "/".join(filter(None, (os.path.dirname(tarinfo.name), tarinfo.linkname))) + limit = None + else: + # Search the archive before the link, because a hard link is + # just a reference to an already archived file. + linkname = tarinfo.linkname + limit = tarinfo + + member = self._getmember(linkname, tarinfo=limit, normalize=True) + if member is None: + raise KeyError("linkname %r not found" % linkname) + return member + + def __iter__(self): + """Provide an iterator object. + """ + if self._loaded: + yield from self.members + return + + # Yield items using TarFile's next() method. + # When all members have been read, set TarFile as _loaded. + index = 0 + # Fix for SF #1100429: Under rare circumstances it can + # happen that getmembers() is called during iteration, + # which will have already exhausted the next() method. + if self.firstmember is not None: + tarinfo = self.next() + index += 1 + yield tarinfo + + while True: + if index < len(self.members): + tarinfo = self.members[index] + elif not self._loaded: + tarinfo = self.next() + if not tarinfo: + self._loaded = True + return + else: + return + index += 1 + yield tarinfo + + def _dbg(self, level, msg): + """Write debugging output to sys.stderr. + """ + if level <= self.debug: + print(msg, file=sys.stderr) + + def __enter__(self): + self._check() + return self + + def __exit__(self, type, value, traceback): + if type is None: + self.close() + else: + # An exception occurred. We must not call close() because + # it would try to write end-of-archive blocks and padding. + if not self._extfileobj: + self.fileobj.close() + self.closed = True + +#-------------------- +# exported functions +#-------------------- + +def is_tarfile(name): + """Return True if name points to a tar archive that we + are able to handle, else return False. + + 'name' should be a string, file, or file-like object. + """ + try: + if hasattr(name, "read"): + pos = name.tell() + t = open(fileobj=name) + name.seek(pos) + else: + t = open(name) + t.close() + return True + except TarError: + return False + +open = TarFile.open + + +def main(): + import argparse + + description = 'A simple command-line interface for tarfile module.' + parser = argparse.ArgumentParser(description=description) + parser.add_argument('-v', '--verbose', action='store_true', default=False, + help='Verbose output') + parser.add_argument('--filter', metavar='', + choices=_NAMED_FILTERS, + help='Filter for extraction') + + group = parser.add_mutually_exclusive_group(required=True) + group.add_argument('-l', '--list', metavar='', + help='Show listing of a tarfile') + group.add_argument('-e', '--extract', nargs='+', + metavar=('', ''), + help='Extract tarfile into target dir') + group.add_argument('-c', '--create', nargs='+', + metavar=('', ''), + help='Create tarfile from sources') + group.add_argument('-t', '--test', metavar='', + help='Test if a tarfile is valid') + + args = parser.parse_args() + + if args.filter and args.extract is None: + parser.exit(1, '--filter is only valid for extraction\n') + + if args.test is not None: + src = args.test + if is_tarfile(src): + with open(src, 'r') as tar: + tar.getmembers() + print(tar.getmembers(), file=sys.stderr) + if args.verbose: + print('{!r} is a tar archive.'.format(src)) + else: + parser.exit(1, '{!r} is not a tar archive.\n'.format(src)) + + elif args.list is not None: + src = args.list + if is_tarfile(src): + with TarFile.open(src, 'r:*') as tf: + tf.list(verbose=args.verbose) + else: + parser.exit(1, '{!r} is not a tar archive.\n'.format(src)) + + elif args.extract is not None: + if len(args.extract) == 1: + src = args.extract[0] + curdir = os.curdir + elif len(args.extract) == 2: + src, curdir = args.extract + else: + parser.exit(1, parser.format_help()) + + if is_tarfile(src): + with TarFile.open(src, 'r:*') as tf: + tf.extractall(path=curdir, filter=args.filter) + if args.verbose: + if curdir == '.': + msg = '{!r} file is extracted.'.format(src) + else: + msg = ('{!r} file is extracted ' + 'into {!r} directory.').format(src, curdir) + print(msg) + else: + parser.exit(1, '{!r} is not a tar archive.\n'.format(src)) + + elif args.create is not None: + tar_name = args.create.pop(0) + _, ext = os.path.splitext(tar_name) + compressions = { + # gz + '.gz': 'gz', + '.tgz': 'gz', + # xz + '.xz': 'xz', + '.txz': 'xz', + # bz2 + '.bz2': 'bz2', + '.tbz': 'bz2', + '.tbz2': 'bz2', + '.tb2': 'bz2', + } + tar_mode = 'w:' + compressions[ext] if ext in compressions else 'w' + tar_files = args.create + + with TarFile.open(tar_name, tar_mode) as tf: + for file_name in tar_files: + tf.add(file_name) + + if args.verbose: + print('{!r} file created.'.format(tar_name)) + +if __name__ == '__main__': + main() diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports/tarfile/__main__.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports/tarfile/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..daf55090862ae43283b6552073549ac3ab2ad50a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports/tarfile/__main__.py @@ -0,0 +1,5 @@ +from . import main + + +if __name__ == '__main__': + main() diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports/tarfile/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports/tarfile/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7721458be8f2e5a7253e31c326e084daca073625 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports/tarfile/__pycache__/__init__.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1a46580c284ed36ea1f8370dc1aab2209c5949211bc3a781ef7dd727d78d3bbf +size 121270 diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports/tarfile/__pycache__/__main__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports/tarfile/__pycache__/__main__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b100a1cdc01d3db8bb8828499c3a38c621796f8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports/tarfile/__pycache__/__main__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports/tarfile/compat/__init__.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports/tarfile/compat/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports/tarfile/compat/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports/tarfile/compat/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f40c9b951e40503ac5991d7146420caee4525913 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports/tarfile/compat/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports/tarfile/compat/__pycache__/py38.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports/tarfile/compat/__pycache__/py38.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f87254741d37e9bea60a985b639d3b7fee804c40 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports/tarfile/compat/__pycache__/py38.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports/tarfile/compat/py38.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports/tarfile/compat/py38.py new file mode 100644 index 0000000000000000000000000000000000000000..20fbbfc1c095baf9f8c72902b24296b50ad3ab9d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/backports/tarfile/compat/py38.py @@ -0,0 +1,24 @@ +import sys + + +if sys.version_info < (3, 9): + + def removesuffix(self, suffix): + # suffix='' should not call self[:-0]. + if suffix and self.endswith(suffix): + return self[: -len(suffix)] + else: + return self[:] + + def removeprefix(self, prefix): + if self.startswith(prefix): + return self[len(prefix) :] + else: + return self[:] +else: + + def removesuffix(self, suffix): + return self.removesuffix(suffix) + + def removeprefix(self, prefix): + return self.removeprefix(prefix) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.dist-info/LICENSE b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.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.12/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.dist-info/METADATA b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..85513e8a9f651c99f4a1fa372ba7768255bfa1c9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.dist-info/METADATA @@ -0,0 +1,129 @@ +Metadata-Version: 2.1 +Name: importlib_metadata +Version: 8.0.0 +Summary: Read metadata from Python packages +Author-email: "Jason R. Coombs" +Project-URL: Source, https://github.com/python/importlib_metadata +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Requires-Python: >=3.8 +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: zipp >=0.5 +Requires-Dist: typing-extensions >=3.6.4 ; python_version < "3.8" +Provides-Extra: doc +Requires-Dist: sphinx >=3.5 ; extra == 'doc' +Requires-Dist: jaraco.packaging >=9.3 ; extra == 'doc' +Requires-Dist: rst.linker >=1.9 ; extra == 'doc' +Requires-Dist: furo ; extra == 'doc' +Requires-Dist: sphinx-lint ; extra == 'doc' +Requires-Dist: jaraco.tidelift >=1.4 ; extra == 'doc' +Provides-Extra: perf +Requires-Dist: ipython ; extra == 'perf' +Provides-Extra: test +Requires-Dist: pytest !=8.1.*,>=6 ; extra == 'test' +Requires-Dist: pytest-checkdocs >=2.4 ; extra == 'test' +Requires-Dist: pytest-cov ; extra == 'test' +Requires-Dist: pytest-mypy ; extra == 'test' +Requires-Dist: pytest-enabler >=2.2 ; extra == 'test' +Requires-Dist: pytest-ruff >=0.2.1 ; extra == 'test' +Requires-Dist: packaging ; extra == 'test' +Requires-Dist: pyfakefs ; extra == 'test' +Requires-Dist: flufl.flake8 ; extra == 'test' +Requires-Dist: pytest-perf >=0.9.2 ; extra == 'test' +Requires-Dist: jaraco.test >=5.4 ; extra == 'test' +Requires-Dist: importlib-resources >=1.3 ; (python_version < "3.9") and extra == 'test' + +.. image:: https://img.shields.io/pypi/v/importlib_metadata.svg + :target: https://pypi.org/project/importlib_metadata + +.. image:: https://img.shields.io/pypi/pyversions/importlib_metadata.svg + +.. image:: https://github.com/python/importlib_metadata/actions/workflows/main.yml/badge.svg + :target: https://github.com/python/importlib_metadata/actions?query=workflow%3A%22tests%22 + :alt: tests + +.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v2.json + :target: https://github.com/astral-sh/ruff + :alt: Ruff + +.. image:: https://readthedocs.org/projects/importlib-metadata/badge/?version=latest + :target: https://importlib-metadata.readthedocs.io/en/latest/?badge=latest + +.. image:: https://img.shields.io/badge/skeleton-2024-informational + :target: https://blog.jaraco.com/skeleton + +.. image:: https://tidelift.com/badges/package/pypi/importlib-metadata + :target: https://tidelift.com/subscription/pkg/pypi-importlib-metadata?utm_source=pypi-importlib-metadata&utm_medium=readme + +Library to access the metadata for a Python package. + +This package supplies third-party access to the functionality of +`importlib.metadata `_ +including improvements added to subsequent Python versions. + + +Compatibility +============= + +New features are introduced in this third-party library and later merged +into CPython. The following table indicates which versions of this library +were contributed to different versions in the standard library: + +.. list-table:: + :header-rows: 1 + + * - importlib_metadata + - stdlib + * - 7.0 + - 3.13 + * - 6.5 + - 3.12 + * - 4.13 + - 3.11 + * - 4.6 + - 3.10 + * - 1.4 + - 3.8 + + +Usage +===== + +See the `online documentation `_ +for usage details. + +`Finder authors +`_ can +also add support for custom package installers. See the above documentation +for details. + + +Caveats +======= + +This project primarily supports third-party packages installed by PyPA +tools (or other conforming packages). It does not support: + +- Packages in the stdlib. +- Packages installed without metadata. + +Project details +=============== + + * Project home: https://github.com/python/importlib_metadata + * Report bugs at: https://github.com/python/importlib_metadata/issues + * Code hosting: https://github.com/python/importlib_metadata + * Documentation: https://importlib-metadata.readthedocs.io/ + +For Enterprise +============== + +Available as part of the Tidelift Subscription. + +This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use. + +`Learn more `_. diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.dist-info/RECORD b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..07b7dc51dbf8da033f8cd0eb05a52ecfe26dcbeb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.dist-info/RECORD @@ -0,0 +1,32 @@ +importlib_metadata-8.0.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +importlib_metadata-8.0.0.dist-info/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358 +importlib_metadata-8.0.0.dist-info/METADATA,sha256=anuQ7_7h4J1bSEzfcjIBakPi2cyVQ7y7jklLHsBeH1k,4648 +importlib_metadata-8.0.0.dist-info/RECORD,, +importlib_metadata-8.0.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +importlib_metadata-8.0.0.dist-info/WHEEL,sha256=mguMlWGMX-VHnMpKOjjQidIo1ssRlCFu4a4mBpz1s2M,91 +importlib_metadata-8.0.0.dist-info/top_level.txt,sha256=CO3fD9yylANiXkrMo4qHLV_mqXL2sC5JFKgt1yWAT-A,19 +importlib_metadata/__init__.py,sha256=tZNB-23h8Bixi9uCrQqj9Yf0aeC--Josdy3IZRIQeB0,33798 +importlib_metadata/__pycache__/__init__.cpython-312.pyc,, +importlib_metadata/__pycache__/_adapters.cpython-312.pyc,, +importlib_metadata/__pycache__/_collections.cpython-312.pyc,, +importlib_metadata/__pycache__/_compat.cpython-312.pyc,, +importlib_metadata/__pycache__/_functools.cpython-312.pyc,, +importlib_metadata/__pycache__/_itertools.cpython-312.pyc,, +importlib_metadata/__pycache__/_meta.cpython-312.pyc,, +importlib_metadata/__pycache__/_text.cpython-312.pyc,, +importlib_metadata/__pycache__/diagnose.cpython-312.pyc,, +importlib_metadata/_adapters.py,sha256=rIhWTwBvYA1bV7i-5FfVX38qEXDTXFeS5cb5xJtP3ks,2317 +importlib_metadata/_collections.py,sha256=CJ0OTCHIjWA0ZIVS4voORAsn2R4R2cQBEtPsZEJpASY,743 +importlib_metadata/_compat.py,sha256=73QKrN9KNoaZzhbX5yPCCZa-FaALwXe8TPlDR72JgBU,1314 +importlib_metadata/_functools.py,sha256=PsY2-4rrKX4RVeRC1oGp1lB1pmC9eKN88_f-bD9uOoA,2895 +importlib_metadata/_itertools.py,sha256=cvr_2v8BRbxcIl5x5ldfqdHjhI8Yi8s8yk50G_nm6jQ,2068 +importlib_metadata/_meta.py,sha256=nxZ7C8GVlcBFAKWyVOn_dn7ot_twBcbm1NmvjIetBHI,1801 +importlib_metadata/_text.py,sha256=HCsFksZpJLeTP3NEk_ngrAeXVRRtTrtyh9eOABoRP4A,2166 +importlib_metadata/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +importlib_metadata/compat/__pycache__/__init__.cpython-312.pyc,, +importlib_metadata/compat/__pycache__/py311.cpython-312.pyc,, +importlib_metadata/compat/__pycache__/py39.cpython-312.pyc,, +importlib_metadata/compat/py311.py,sha256=uqm-K-uohyj1042TH4a9Er_I5o7667DvulcD-gC_fSA,608 +importlib_metadata/compat/py39.py,sha256=cPkMv6-0ilK-0Jw_Tkn0xYbOKJZc4WJKQHow0c2T44w,1102 +importlib_metadata/diagnose.py,sha256=nkSRMiowlmkhLYhKhvCg9glmt_11Cox-EmLzEbqYTa8,379 +importlib_metadata/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.dist-info/REQUESTED b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..edf4ec7c70d7dbfc16600ff1b368daf1097c5dc7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.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.12/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.dist-info/top_level.txt b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..bbb07547a19c30031d13c45cf01cba61dc434e47 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.dist-info/top_level.txt @@ -0,0 +1 @@ +importlib_metadata diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/__init__.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ed4813551ac238bfb9b5a48f4476463355415d27 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/__init__.py @@ -0,0 +1,1083 @@ +from __future__ import annotations + +import os +import re +import abc +import sys +import json +import zipp +import email +import types +import inspect +import pathlib +import operator +import textwrap +import functools +import itertools +import posixpath +import collections + +from . import _meta +from .compat import py39, py311 +from ._collections import FreezableDefaultDict, Pair +from ._compat import ( + NullFinder, + install, +) +from ._functools import method_cache, pass_none +from ._itertools import always_iterable, unique_everseen +from ._meta import PackageMetadata, SimplePath + +from contextlib import suppress +from importlib import import_module +from importlib.abc import MetaPathFinder +from itertools import starmap +from typing import Any, Iterable, List, Mapping, Match, Optional, Set, cast + +__all__ = [ + 'Distribution', + 'DistributionFinder', + 'PackageMetadata', + 'PackageNotFoundError', + 'distribution', + 'distributions', + 'entry_points', + 'files', + 'metadata', + 'packages_distributions', + 'requires', + 'version', +] + + +class PackageNotFoundError(ModuleNotFoundError): + """The package was not found.""" + + def __str__(self) -> str: + return f"No package metadata was found for {self.name}" + + @property + def name(self) -> str: # type: ignore[override] + (name,) = self.args + return name + + +class Sectioned: + """ + A simple entry point config parser for performance + + >>> for item in Sectioned.read(Sectioned._sample): + ... print(item) + Pair(name='sec1', value='# comments ignored') + Pair(name='sec1', value='a = 1') + Pair(name='sec1', value='b = 2') + Pair(name='sec2', value='a = 2') + + >>> res = Sectioned.section_pairs(Sectioned._sample) + >>> item = next(res) + >>> item.name + 'sec1' + >>> item.value + Pair(name='a', value='1') + >>> item = next(res) + >>> item.value + Pair(name='b', value='2') + >>> item = next(res) + >>> item.name + 'sec2' + >>> item.value + Pair(name='a', value='2') + >>> list(res) + [] + """ + + _sample = textwrap.dedent( + """ + [sec1] + # comments ignored + a = 1 + b = 2 + + [sec2] + a = 2 + """ + ).lstrip() + + @classmethod + def section_pairs(cls, text): + return ( + section._replace(value=Pair.parse(section.value)) + for section in cls.read(text, filter_=cls.valid) + if section.name is not None + ) + + @staticmethod + def read(text, filter_=None): + lines = filter(filter_, map(str.strip, text.splitlines())) + name = None + for value in lines: + section_match = value.startswith('[') and value.endswith(']') + if section_match: + name = value.strip('[]') + continue + yield Pair(name, value) + + @staticmethod + def valid(line: str): + return line and not line.startswith('#') + + +class EntryPoint: + """An entry point as defined by Python packaging conventions. + + See `the packaging docs on entry points + `_ + for more information. + + >>> ep = EntryPoint( + ... name=None, group=None, value='package.module:attr [extra1, extra2]') + >>> ep.module + 'package.module' + >>> ep.attr + 'attr' + >>> ep.extras + ['extra1', 'extra2'] + """ + + pattern = re.compile( + r'(?P[\w.]+)\s*' + r'(:\s*(?P[\w.]+)\s*)?' + r'((?P\[.*\])\s*)?$' + ) + """ + A regular expression describing the syntax for an entry point, + which might look like: + + - module + - package.module + - package.module:attribute + - package.module:object.attribute + - package.module:attr [extra1, extra2] + + Other combinations are possible as well. + + The expression is lenient about whitespace around the ':', + following the attr, and following any extras. + """ + + name: str + value: str + group: str + + dist: Optional[Distribution] = None + + def __init__(self, name: str, value: str, group: str) -> None: + vars(self).update(name=name, value=value, group=group) + + def load(self) -> Any: + """Load the entry point from its definition. If only a module + is indicated by the value, return that module. Otherwise, + return the named object. + """ + match = cast(Match, self.pattern.match(self.value)) + module = import_module(match.group('module')) + attrs = filter(None, (match.group('attr') or '').split('.')) + return functools.reduce(getattr, attrs, module) + + @property + def module(self) -> str: + match = self.pattern.match(self.value) + assert match is not None + return match.group('module') + + @property + def attr(self) -> str: + match = self.pattern.match(self.value) + assert match is not None + return match.group('attr') + + @property + def extras(self) -> List[str]: + match = self.pattern.match(self.value) + assert match is not None + return re.findall(r'\w+', match.group('extras') or '') + + def _for(self, dist): + vars(self).update(dist=dist) + return self + + def matches(self, **params): + """ + EntryPoint matches the given parameters. + + >>> ep = EntryPoint(group='foo', name='bar', value='bing:bong [extra1, extra2]') + >>> ep.matches(group='foo') + True + >>> ep.matches(name='bar', value='bing:bong [extra1, extra2]') + True + >>> ep.matches(group='foo', name='other') + False + >>> ep.matches() + True + >>> ep.matches(extras=['extra1', 'extra2']) + True + >>> ep.matches(module='bing') + True + >>> ep.matches(attr='bong') + True + """ + attrs = (getattr(self, param) for param in params) + return all(map(operator.eq, params.values(), attrs)) + + def _key(self): + return self.name, self.value, self.group + + def __lt__(self, other): + return self._key() < other._key() + + def __eq__(self, other): + return self._key() == other._key() + + def __setattr__(self, name, value): + raise AttributeError("EntryPoint objects are immutable.") + + def __repr__(self): + return ( + f'EntryPoint(name={self.name!r}, value={self.value!r}, ' + f'group={self.group!r})' + ) + + def __hash__(self) -> int: + return hash(self._key()) + + +class EntryPoints(tuple): + """ + An immutable collection of selectable EntryPoint objects. + """ + + __slots__ = () + + def __getitem__(self, name: str) -> EntryPoint: # type: ignore[override] + """ + Get the EntryPoint in self matching name. + """ + try: + return next(iter(self.select(name=name))) + except StopIteration: + raise KeyError(name) + + def __repr__(self): + """ + Repr with classname and tuple constructor to + signal that we deviate from regular tuple behavior. + """ + return '%s(%r)' % (self.__class__.__name__, tuple(self)) + + def select(self, **params) -> EntryPoints: + """ + Select entry points from self that match the + given parameters (typically group and/or name). + """ + return EntryPoints(ep for ep in self if py39.ep_matches(ep, **params)) + + @property + def names(self) -> Set[str]: + """ + Return the set of all names of all entry points. + """ + return {ep.name for ep in self} + + @property + def groups(self) -> Set[str]: + """ + Return the set of all groups of all entry points. + """ + return {ep.group for ep in self} + + @classmethod + def _from_text_for(cls, text, dist): + return cls(ep._for(dist) for ep in cls._from_text(text)) + + @staticmethod + def _from_text(text): + return ( + EntryPoint(name=item.value.name, value=item.value.value, group=item.name) + for item in Sectioned.section_pairs(text or '') + ) + + +class PackagePath(pathlib.PurePosixPath): + """A reference to a path in a package""" + + hash: Optional[FileHash] + size: int + dist: Distribution + + def read_text(self, encoding: str = 'utf-8') -> str: # type: ignore[override] + return self.locate().read_text(encoding=encoding) + + def read_binary(self) -> bytes: + return self.locate().read_bytes() + + def locate(self) -> SimplePath: + """Return a path-like object for this path""" + return self.dist.locate_file(self) + + +class FileHash: + def __init__(self, spec: str) -> None: + self.mode, _, self.value = spec.partition('=') + + def __repr__(self) -> str: + return f'' + + +class Distribution(metaclass=abc.ABCMeta): + """ + An abstract Python distribution package. + + Custom providers may derive from this class and define + the abstract methods to provide a concrete implementation + for their environment. Some providers may opt to override + the default implementation of some properties to bypass + the file-reading mechanism. + """ + + @abc.abstractmethod + def read_text(self, filename) -> Optional[str]: + """Attempt to load metadata file given by the name. + + Python distribution metadata is organized by blobs of text + typically represented as "files" in the metadata directory + (e.g. package-1.0.dist-info). These files include things + like: + + - METADATA: The distribution metadata including fields + like Name and Version and Description. + - entry_points.txt: A series of entry points as defined in + `the entry points spec `_. + - RECORD: A record of files according to + `this recording spec `_. + + A package may provide any set of files, including those + not listed here or none at all. + + :param filename: The name of the file in the distribution info. + :return: The text if found, otherwise None. + """ + + @abc.abstractmethod + def locate_file(self, path: str | os.PathLike[str]) -> SimplePath: + """ + Given a path to a file in this distribution, return a SimplePath + to it. + """ + + @classmethod + def from_name(cls, name: str) -> Distribution: + """Return the Distribution for the given package name. + + :param name: The name of the distribution package to search for. + :return: The Distribution instance (or subclass thereof) for the named + package, if found. + :raises PackageNotFoundError: When the named package's distribution + metadata cannot be found. + :raises ValueError: When an invalid value is supplied for name. + """ + if not name: + raise ValueError("A distribution name is required.") + try: + return next(iter(cls.discover(name=name))) + except StopIteration: + raise PackageNotFoundError(name) + + @classmethod + def discover( + cls, *, context: Optional[DistributionFinder.Context] = None, **kwargs + ) -> Iterable[Distribution]: + """Return an iterable of Distribution objects for all packages. + + Pass a ``context`` or pass keyword arguments for constructing + a context. + + :context: A ``DistributionFinder.Context`` object. + :return: Iterable of Distribution objects for packages matching + the context. + """ + if context and kwargs: + raise ValueError("cannot accept context and kwargs") + context = context or DistributionFinder.Context(**kwargs) + return itertools.chain.from_iterable( + resolver(context) for resolver in cls._discover_resolvers() + ) + + @staticmethod + def at(path: str | os.PathLike[str]) -> Distribution: + """Return a Distribution for the indicated metadata path. + + :param path: a string or path-like object + :return: a concrete Distribution instance for the path + """ + return PathDistribution(pathlib.Path(path)) + + @staticmethod + def _discover_resolvers(): + """Search the meta_path for resolvers (MetadataPathFinders).""" + declared = ( + getattr(finder, 'find_distributions', None) for finder in sys.meta_path + ) + return filter(None, declared) + + @property + def metadata(self) -> _meta.PackageMetadata: + """Return the parsed metadata for this Distribution. + + The returned object will have keys that name the various bits of + metadata per the + `Core metadata specifications `_. + + Custom providers may provide the METADATA file or override this + property. + """ + # deferred for performance (python/cpython#109829) + from . import _adapters + + opt_text = ( + self.read_text('METADATA') + or self.read_text('PKG-INFO') + # This last clause is here to support old egg-info files. Its + # effect is to just end up using the PathDistribution's self._path + # (which points to the egg-info file) attribute unchanged. + or self.read_text('') + ) + text = cast(str, opt_text) + return _adapters.Message(email.message_from_string(text)) + + @property + def name(self) -> str: + """Return the 'Name' metadata for the distribution package.""" + return self.metadata['Name'] + + @property + def _normalized_name(self): + """Return a normalized version of the name.""" + return Prepared.normalize(self.name) + + @property + def version(self) -> str: + """Return the 'Version' metadata for the distribution package.""" + return self.metadata['Version'] + + @property + def entry_points(self) -> EntryPoints: + """ + Return EntryPoints for this distribution. + + Custom providers may provide the ``entry_points.txt`` file + or override this property. + """ + return EntryPoints._from_text_for(self.read_text('entry_points.txt'), self) + + @property + def files(self) -> Optional[List[PackagePath]]: + """Files in this distribution. + + :return: List of PackagePath for this distribution or None + + Result is `None` if the metadata file that enumerates files + (i.e. RECORD for dist-info, or installed-files.txt or + SOURCES.txt for egg-info) is missing. + Result may be empty if the metadata exists but is empty. + + Custom providers are recommended to provide a "RECORD" file (in + ``read_text``) or override this property to allow for callers to be + able to resolve filenames provided by the package. + """ + + def make_file(name, hash=None, size_str=None): + result = PackagePath(name) + result.hash = FileHash(hash) if hash else None + result.size = int(size_str) if size_str else None + result.dist = self + return result + + @pass_none + def make_files(lines): + # Delay csv import, since Distribution.files is not as widely used + # as other parts of importlib.metadata + import csv + + return starmap(make_file, csv.reader(lines)) + + @pass_none + def skip_missing_files(package_paths): + return list(filter(lambda path: path.locate().exists(), package_paths)) + + return skip_missing_files( + make_files( + self._read_files_distinfo() + or self._read_files_egginfo_installed() + or self._read_files_egginfo_sources() + ) + ) + + def _read_files_distinfo(self): + """ + Read the lines of RECORD. + """ + text = self.read_text('RECORD') + return text and text.splitlines() + + def _read_files_egginfo_installed(self): + """ + Read installed-files.txt and return lines in a similar + CSV-parsable format as RECORD: each file must be placed + relative to the site-packages directory and must also be + quoted (since file names can contain literal commas). + + This file is written when the package is installed by pip, + but it might not be written for other installation methods. + Assume the file is accurate if it exists. + """ + text = self.read_text('installed-files.txt') + # Prepend the .egg-info/ subdir to the lines in this file. + # But this subdir is only available from PathDistribution's + # self._path. + subdir = getattr(self, '_path', None) + if not text or not subdir: + return + + paths = ( + py311.relative_fix((subdir / name).resolve()) + .relative_to(self.locate_file('').resolve(), walk_up=True) + .as_posix() + for name in text.splitlines() + ) + return map('"{}"'.format, paths) + + def _read_files_egginfo_sources(self): + """ + Read SOURCES.txt and return lines in a similar CSV-parsable + format as RECORD: each file name must be quoted (since it + might contain literal commas). + + Note that SOURCES.txt is not a reliable source for what + files are installed by a package. This file is generated + for a source archive, and the files that are present + there (e.g. setup.py) may not correctly reflect the files + that are present after the package has been installed. + """ + text = self.read_text('SOURCES.txt') + return text and map('"{}"'.format, text.splitlines()) + + @property + def requires(self) -> Optional[List[str]]: + """Generated requirements specified for this Distribution""" + reqs = self._read_dist_info_reqs() or self._read_egg_info_reqs() + return reqs and list(reqs) + + def _read_dist_info_reqs(self): + return self.metadata.get_all('Requires-Dist') + + def _read_egg_info_reqs(self): + source = self.read_text('requires.txt') + return pass_none(self._deps_from_requires_text)(source) + + @classmethod + def _deps_from_requires_text(cls, source): + return cls._convert_egg_info_reqs_to_simple_reqs(Sectioned.read(source)) + + @staticmethod + def _convert_egg_info_reqs_to_simple_reqs(sections): + """ + Historically, setuptools would solicit and store 'extra' + requirements, including those with environment markers, + in separate sections. More modern tools expect each + dependency to be defined separately, with any relevant + extras and environment markers attached directly to that + requirement. This method converts the former to the + latter. See _test_deps_from_requires_text for an example. + """ + + def make_condition(name): + return name and f'extra == "{name}"' + + def quoted_marker(section): + section = section or '' + extra, sep, markers = section.partition(':') + if extra and markers: + markers = f'({markers})' + conditions = list(filter(None, [markers, make_condition(extra)])) + return '; ' + ' and '.join(conditions) if conditions else '' + + def url_req_space(req): + """ + PEP 508 requires a space between the url_spec and the quoted_marker. + Ref python/importlib_metadata#357. + """ + # '@' is uniquely indicative of a url_req. + return ' ' * ('@' in req) + + for section in sections: + space = url_req_space(section.value) + yield section.value + space + quoted_marker(section.name) + + @property + def origin(self): + return self._load_json('direct_url.json') + + def _load_json(self, filename): + return pass_none(json.loads)( + self.read_text(filename), + object_hook=lambda data: types.SimpleNamespace(**data), + ) + + +class DistributionFinder(MetaPathFinder): + """ + A MetaPathFinder capable of discovering installed distributions. + + Custom providers should implement this interface in order to + supply metadata. + """ + + class Context: + """ + Keyword arguments presented by the caller to + ``distributions()`` or ``Distribution.discover()`` + to narrow the scope of a search for distributions + in all DistributionFinders. + + Each DistributionFinder may expect any parameters + and should attempt to honor the canonical + parameters defined below when appropriate. + + This mechanism gives a custom provider a means to + solicit additional details from the caller beyond + "name" and "path" when searching distributions. + For example, imagine a provider that exposes suites + of packages in either a "public" or "private" ``realm``. + A caller may wish to query only for distributions in + a particular realm and could call + ``distributions(realm="private")`` to signal to the + custom provider to only include distributions from that + realm. + """ + + name = None + """ + Specific name for which a distribution finder should match. + A name of ``None`` matches all distributions. + """ + + def __init__(self, **kwargs): + vars(self).update(kwargs) + + @property + def path(self) -> List[str]: + """ + The sequence of directory path that a distribution finder + should search. + + Typically refers to Python installed package paths such as + "site-packages" directories and defaults to ``sys.path``. + """ + return vars(self).get('path', sys.path) + + @abc.abstractmethod + def find_distributions(self, context=Context()) -> Iterable[Distribution]: + """ + Find distributions. + + Return an iterable of all Distribution instances capable of + loading the metadata for packages matching the ``context``, + a DistributionFinder.Context instance. + """ + + +class FastPath: + """ + Micro-optimized class for searching a root for children. + + Root is a path on the file system that may contain metadata + directories either as natural directories or within a zip file. + + >>> FastPath('').children() + ['...'] + + FastPath objects are cached and recycled for any given root. + + >>> FastPath('foobar') is FastPath('foobar') + True + """ + + @functools.lru_cache() # type: ignore + def __new__(cls, root): + return super().__new__(cls) + + def __init__(self, root): + self.root = root + + def joinpath(self, child): + return pathlib.Path(self.root, child) + + def children(self): + with suppress(Exception): + return os.listdir(self.root or '.') + with suppress(Exception): + return self.zip_children() + return [] + + def zip_children(self): + zip_path = zipp.Path(self.root) + names = zip_path.root.namelist() + self.joinpath = zip_path.joinpath + + return dict.fromkeys(child.split(posixpath.sep, 1)[0] for child in names) + + def search(self, name): + return self.lookup(self.mtime).search(name) + + @property + def mtime(self): + with suppress(OSError): + return os.stat(self.root).st_mtime + self.lookup.cache_clear() + + @method_cache + def lookup(self, mtime): + return Lookup(self) + + +class Lookup: + """ + A micro-optimized class for searching a (fast) path for metadata. + """ + + def __init__(self, path: FastPath): + """ + Calculate all of the children representing metadata. + + From the children in the path, calculate early all of the + children that appear to represent metadata (infos) or legacy + metadata (eggs). + """ + + base = os.path.basename(path.root).lower() + base_is_egg = base.endswith(".egg") + self.infos = FreezableDefaultDict(list) + self.eggs = FreezableDefaultDict(list) + + for child in path.children(): + low = child.lower() + if low.endswith((".dist-info", ".egg-info")): + # rpartition is faster than splitext and suitable for this purpose. + name = low.rpartition(".")[0].partition("-")[0] + normalized = Prepared.normalize(name) + self.infos[normalized].append(path.joinpath(child)) + elif base_is_egg and low == "egg-info": + name = base.rpartition(".")[0].partition("-")[0] + legacy_normalized = Prepared.legacy_normalize(name) + self.eggs[legacy_normalized].append(path.joinpath(child)) + + self.infos.freeze() + self.eggs.freeze() + + def search(self, prepared: Prepared): + """ + Yield all infos and eggs matching the Prepared query. + """ + infos = ( + self.infos[prepared.normalized] + if prepared + else itertools.chain.from_iterable(self.infos.values()) + ) + eggs = ( + self.eggs[prepared.legacy_normalized] + if prepared + else itertools.chain.from_iterable(self.eggs.values()) + ) + return itertools.chain(infos, eggs) + + +class Prepared: + """ + A prepared search query for metadata on a possibly-named package. + + Pre-calculates the normalization to prevent repeated operations. + + >>> none = Prepared(None) + >>> none.normalized + >>> none.legacy_normalized + >>> bool(none) + False + >>> sample = Prepared('Sample__Pkg-name.foo') + >>> sample.normalized + 'sample_pkg_name_foo' + >>> sample.legacy_normalized + 'sample__pkg_name.foo' + >>> bool(sample) + True + """ + + normalized = None + legacy_normalized = None + + def __init__(self, name: Optional[str]): + self.name = name + if name is None: + return + self.normalized = self.normalize(name) + self.legacy_normalized = self.legacy_normalize(name) + + @staticmethod + def normalize(name): + """ + PEP 503 normalization plus dashes as underscores. + """ + return re.sub(r"[-_.]+", "-", name).lower().replace('-', '_') + + @staticmethod + def legacy_normalize(name): + """ + Normalize the package name as found in the convention in + older packaging tools versions and specs. + """ + return name.lower().replace('-', '_') + + def __bool__(self): + return bool(self.name) + + +@install +class MetadataPathFinder(NullFinder, DistributionFinder): + """A degenerate finder for distribution packages on the file system. + + This finder supplies only a find_distributions() method for versions + of Python that do not have a PathFinder find_distributions(). + """ + + @classmethod + def find_distributions( + cls, context=DistributionFinder.Context() + ) -> Iterable[PathDistribution]: + """ + Find distributions. + + Return an iterable of all Distribution instances capable of + loading the metadata for packages matching ``context.name`` + (or all names if ``None`` indicated) along the paths in the list + of directories ``context.path``. + """ + found = cls._search_paths(context.name, context.path) + return map(PathDistribution, found) + + @classmethod + def _search_paths(cls, name, paths): + """Find metadata directories in paths heuristically.""" + prepared = Prepared(name) + return itertools.chain.from_iterable( + path.search(prepared) for path in map(FastPath, paths) + ) + + @classmethod + def invalidate_caches(cls) -> None: + FastPath.__new__.cache_clear() + + +class PathDistribution(Distribution): + def __init__(self, path: SimplePath) -> None: + """Construct a distribution. + + :param path: SimplePath indicating the metadata directory. + """ + self._path = path + + def read_text(self, filename: str | os.PathLike[str]) -> Optional[str]: + with suppress( + FileNotFoundError, + IsADirectoryError, + KeyError, + NotADirectoryError, + PermissionError, + ): + return self._path.joinpath(filename).read_text(encoding='utf-8') + + return None + + read_text.__doc__ = Distribution.read_text.__doc__ + + def locate_file(self, path: str | os.PathLike[str]) -> SimplePath: + return self._path.parent / path + + @property + def _normalized_name(self): + """ + Performance optimization: where possible, resolve the + normalized name from the file system path. + """ + stem = os.path.basename(str(self._path)) + return ( + pass_none(Prepared.normalize)(self._name_from_stem(stem)) + or super()._normalized_name + ) + + @staticmethod + def _name_from_stem(stem): + """ + >>> PathDistribution._name_from_stem('foo-3.0.egg-info') + 'foo' + >>> PathDistribution._name_from_stem('CherryPy-3.0.dist-info') + 'CherryPy' + >>> PathDistribution._name_from_stem('face.egg-info') + 'face' + >>> PathDistribution._name_from_stem('foo.bar') + """ + filename, ext = os.path.splitext(stem) + if ext not in ('.dist-info', '.egg-info'): + return + name, sep, rest = filename.partition('-') + return name + + +def distribution(distribution_name: str) -> Distribution: + """Get the ``Distribution`` instance for the named package. + + :param distribution_name: The name of the distribution package as a string. + :return: A ``Distribution`` instance (or subclass thereof). + """ + return Distribution.from_name(distribution_name) + + +def distributions(**kwargs) -> Iterable[Distribution]: + """Get all ``Distribution`` instances in the current environment. + + :return: An iterable of ``Distribution`` instances. + """ + return Distribution.discover(**kwargs) + + +def metadata(distribution_name: str) -> _meta.PackageMetadata: + """Get the metadata for the named package. + + :param distribution_name: The name of the distribution package to query. + :return: A PackageMetadata containing the parsed metadata. + """ + return Distribution.from_name(distribution_name).metadata + + +def version(distribution_name: str) -> str: + """Get the version string for the named package. + + :param distribution_name: The name of the distribution package to query. + :return: The version string for the package as defined in the package's + "Version" metadata key. + """ + return distribution(distribution_name).version + + +_unique = functools.partial( + unique_everseen, + key=py39.normalized_name, +) +""" +Wrapper for ``distributions`` to return unique distributions by name. +""" + + +def entry_points(**params) -> EntryPoints: + """Return EntryPoint objects for all installed packages. + + Pass selection parameters (group or name) to filter the + result to entry points matching those properties (see + EntryPoints.select()). + + :return: EntryPoints for all installed packages. + """ + eps = itertools.chain.from_iterable( + dist.entry_points for dist in _unique(distributions()) + ) + return EntryPoints(eps).select(**params) + + +def files(distribution_name: str) -> Optional[List[PackagePath]]: + """Return a list of files for the named package. + + :param distribution_name: The name of the distribution package to query. + :return: List of files composing the distribution. + """ + return distribution(distribution_name).files + + +def requires(distribution_name: str) -> Optional[List[str]]: + """ + Return a list of requirements for the named package. + + :return: An iterable of requirements, suitable for + packaging.requirement.Requirement. + """ + return distribution(distribution_name).requires + + +def packages_distributions() -> Mapping[str, List[str]]: + """ + Return a mapping of top-level packages to their + distributions. + + >>> import collections.abc + >>> pkgs = packages_distributions() + >>> all(isinstance(dist, collections.abc.Sequence) for dist in pkgs.values()) + True + """ + pkg_to_dist = collections.defaultdict(list) + for dist in distributions(): + for pkg in _top_level_declared(dist) or _top_level_inferred(dist): + pkg_to_dist[pkg].append(dist.metadata['Name']) + return dict(pkg_to_dist) + + +def _top_level_declared(dist): + return (dist.read_text('top_level.txt') or '').split() + + +def _topmost(name: PackagePath) -> Optional[str]: + """ + Return the top-most parent as long as there is a parent. + """ + top, *rest = name.parts + return top if rest else None + + +def _get_toplevel_name(name: PackagePath) -> str: + """ + Infer a possibly importable module name from a name presumed on + sys.path. + + >>> _get_toplevel_name(PackagePath('foo.py')) + 'foo' + >>> _get_toplevel_name(PackagePath('foo')) + 'foo' + >>> _get_toplevel_name(PackagePath('foo.pyc')) + 'foo' + >>> _get_toplevel_name(PackagePath('foo/__init__.py')) + 'foo' + >>> _get_toplevel_name(PackagePath('foo.pth')) + 'foo.pth' + >>> _get_toplevel_name(PackagePath('foo.dist-info')) + 'foo.dist-info' + """ + return _topmost(name) or ( + # python/typeshed#10328 + inspect.getmodulename(name) # type: ignore + or str(name) + ) + + +def _top_level_inferred(dist): + opt_names = set(map(_get_toplevel_name, always_iterable(dist.files))) + + def importable_name(name): + return '.' not in name + + return filter(importable_name, opt_names) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e6096a3330c089f5e12357370e39c6a52186a852 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_adapters.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_adapters.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d84c8ebde2275c52196a0cc7f3c8fa9785cf9f6d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_adapters.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_collections.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_collections.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ed937cdafc235ca5a3f4aa371382a377f668bb3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_collections.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_compat.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_compat.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2f0fd522bf994e00a8d7b22bd199e674546dc786 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_compat.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_functools.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_functools.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..28ab0a4aaa364111f63af113fb6d5fb68f4139f4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_functools.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_itertools.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_itertools.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1c7bf5496953471f1f296df94cf494af16e004e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_itertools.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_meta.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_meta.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b0a6de0a51ea07fcb574096e8abb70ff03fba9c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_meta.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_text.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_text.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8754dfe5bd85f68c53fca99cc67466639db2e320 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_text.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/diagnose.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/diagnose.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1382ed98c4379c826347e4fd889728a4959eae3f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/diagnose.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/_adapters.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/_adapters.py new file mode 100644 index 0000000000000000000000000000000000000000..6223263ed53f22fc25c09de06789718d2cd3b6ea --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/_adapters.py @@ -0,0 +1,83 @@ +import re +import textwrap +import email.message + +from ._text import FoldedCase + + +class Message(email.message.Message): + multiple_use_keys = set( + map( + FoldedCase, + [ + 'Classifier', + 'Obsoletes-Dist', + 'Platform', + 'Project-URL', + 'Provides-Dist', + 'Provides-Extra', + 'Requires-Dist', + 'Requires-External', + 'Supported-Platform', + 'Dynamic', + ], + ) + ) + """ + Keys that may be indicated multiple times per PEP 566. + """ + + def __new__(cls, orig: email.message.Message): + res = super().__new__(cls) + vars(res).update(vars(orig)) + return res + + def __init__(self, *args, **kwargs): + self._headers = self._repair_headers() + + # suppress spurious error from mypy + def __iter__(self): + return super().__iter__() + + def __getitem__(self, item): + """ + Override parent behavior to typical dict behavior. + + ``email.message.Message`` will emit None values for missing + keys. Typical mappings, including this ``Message``, will raise + a key error for missing keys. + + Ref python/importlib_metadata#371. + """ + res = super().__getitem__(item) + if res is None: + raise KeyError(item) + return res + + def _repair_headers(self): + def redent(value): + "Correct for RFC822 indentation" + if not value or '\n' not in value: + return value + return textwrap.dedent(' ' * 8 + value) + + headers = [(key, redent(value)) for key, value in vars(self)['_headers']] + if self._payload: + headers.append(('Description', self.get_payload())) + return headers + + @property + def json(self): + """ + Convert PackageMetadata to a JSON-compatible format + per PEP 0566. + """ + + def transform(key): + value = self.get_all(key) if key in self.multiple_use_keys else self[key] + if key == 'Keywords': + value = re.split(r'\s+', value) + tk = key.lower().replace('-', '_') + return tk, value + + return dict(map(transform, map(FoldedCase, self))) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/_collections.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/_collections.py new file mode 100644 index 0000000000000000000000000000000000000000..cf0954e1a30546d781bf25781ec716ef92a77e32 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/_collections.py @@ -0,0 +1,30 @@ +import collections + + +# from jaraco.collections 3.3 +class FreezableDefaultDict(collections.defaultdict): + """ + Often it is desirable to prevent the mutation of + a default dict after its initial construction, such + as to prevent mutation during iteration. + + >>> dd = FreezableDefaultDict(list) + >>> dd[0].append('1') + >>> dd.freeze() + >>> dd[1] + [] + >>> len(dd) + 1 + """ + + def __missing__(self, key): + return getattr(self, '_frozen', super().__missing__)(key) + + def freeze(self): + self._frozen = lambda key: self.default_factory() + + +class Pair(collections.namedtuple('Pair', 'name value')): + @classmethod + def parse(cls, text): + return cls(*map(str.strip, text.split("=", 1))) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/_compat.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..df312b1cbbf18a337278df0e618fb9e8c862e5f6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/_compat.py @@ -0,0 +1,57 @@ +import sys +import platform + + +__all__ = ['install', 'NullFinder'] + + +def install(cls): + """ + Class decorator for installation on sys.meta_path. + + Adds the backport DistributionFinder to sys.meta_path and + attempts to disable the finder functionality of the stdlib + DistributionFinder. + """ + sys.meta_path.append(cls()) + disable_stdlib_finder() + return cls + + +def disable_stdlib_finder(): + """ + Give the backport primacy for discovering path-based distributions + by monkey-patching the stdlib O_O. + + See #91 for more background for rationale on this sketchy + behavior. + """ + + def matches(finder): + return getattr( + finder, '__module__', None + ) == '_frozen_importlib_external' and hasattr(finder, 'find_distributions') + + for finder in filter(matches, sys.meta_path): # pragma: nocover + del finder.find_distributions + + +class NullFinder: + """ + A "Finder" (aka "MetaPathFinder") that never finds any modules, + but may find distributions. + """ + + @staticmethod + def find_spec(*args, **kwargs): + return None + + +def pypy_partial(val): + """ + Adjust for variable stacklevel on partial under PyPy. + + Workaround for #327. + """ + is_pypy = platform.python_implementation() == 'PyPy' + return val + is_pypy diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/_functools.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/_functools.py new file mode 100644 index 0000000000000000000000000000000000000000..71f66bd03cb713a2190853bdf7170c4ea80d2425 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/_functools.py @@ -0,0 +1,104 @@ +import types +import functools + + +# from jaraco.functools 3.3 +def method_cache(method, cache_wrapper=None): + """ + Wrap lru_cache to support storing the cache data in the object instances. + + Abstracts the common paradigm where the method explicitly saves an + underscore-prefixed protected property on first call and returns that + subsequently. + + >>> class MyClass: + ... calls = 0 + ... + ... @method_cache + ... def method(self, value): + ... self.calls += 1 + ... return value + + >>> a = MyClass() + >>> a.method(3) + 3 + >>> for x in range(75): + ... res = a.method(x) + >>> a.calls + 75 + + Note that the apparent behavior will be exactly like that of lru_cache + except that the cache is stored on each instance, so values in one + instance will not flush values from another, and when an instance is + deleted, so are the cached values for that instance. + + >>> b = MyClass() + >>> for x in range(35): + ... res = b.method(x) + >>> b.calls + 35 + >>> a.method(0) + 0 + >>> a.calls + 75 + + Note that if method had been decorated with ``functools.lru_cache()``, + a.calls would have been 76 (due to the cached value of 0 having been + flushed by the 'b' instance). + + Clear the cache with ``.cache_clear()`` + + >>> a.method.cache_clear() + + Same for a method that hasn't yet been called. + + >>> c = MyClass() + >>> c.method.cache_clear() + + Another cache wrapper may be supplied: + + >>> cache = functools.lru_cache(maxsize=2) + >>> MyClass.method2 = method_cache(lambda self: 3, cache_wrapper=cache) + >>> a = MyClass() + >>> a.method2() + 3 + + Caution - do not subsequently wrap the method with another decorator, such + as ``@property``, which changes the semantics of the function. + + See also + http://code.activestate.com/recipes/577452-a-memoize-decorator-for-instance-methods/ + for another implementation and additional justification. + """ + cache_wrapper = cache_wrapper or functools.lru_cache() + + def wrapper(self, *args, **kwargs): + # it's the first call, replace the method with a cached, bound method + bound_method = types.MethodType(method, self) + cached_method = cache_wrapper(bound_method) + setattr(self, method.__name__, cached_method) + return cached_method(*args, **kwargs) + + # Support cache clear even before cache has been created. + wrapper.cache_clear = lambda: None + + return wrapper + + +# From jaraco.functools 3.3 +def pass_none(func): + """ + Wrap func so it's not called if its first param is None + + >>> print_text = pass_none(print) + >>> print_text('text') + text + >>> print_text(None) + """ + + @functools.wraps(func) + def wrapper(param, *args, **kwargs): + if param is not None: + return func(param, *args, **kwargs) + + return wrapper diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/_itertools.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/_itertools.py new file mode 100644 index 0000000000000000000000000000000000000000..d4ca9b9140e3f085b36609bb8dfdaea79c78e144 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/_itertools.py @@ -0,0 +1,73 @@ +from itertools import filterfalse + + +def unique_everseen(iterable, key=None): + "List unique elements, preserving order. Remember all elements ever seen." + # unique_everseen('AAAABBBCCDAABBB') --> A B C D + # unique_everseen('ABBCcAD', str.lower) --> A B C D + seen = set() + seen_add = seen.add + if key is None: + for element in filterfalse(seen.__contains__, iterable): + seen_add(element) + yield element + else: + for element in iterable: + k = key(element) + if k not in seen: + seen_add(k) + yield element + + +# copied from more_itertools 8.8 +def always_iterable(obj, base_type=(str, bytes)): + """If *obj* is iterable, return an iterator over its items:: + + >>> obj = (1, 2, 3) + >>> list(always_iterable(obj)) + [1, 2, 3] + + If *obj* is not iterable, return a one-item iterable containing *obj*:: + + >>> obj = 1 + >>> list(always_iterable(obj)) + [1] + + If *obj* is ``None``, return an empty iterable: + + >>> obj = None + >>> list(always_iterable(None)) + [] + + By default, binary and text strings are not considered iterable:: + + >>> obj = 'foo' + >>> list(always_iterable(obj)) + ['foo'] + + If *base_type* is set, objects for which ``isinstance(obj, base_type)`` + returns ``True`` won't be considered iterable. + + >>> obj = {'a': 1} + >>> list(always_iterable(obj)) # Iterate over the dict's keys + ['a'] + >>> list(always_iterable(obj, base_type=dict)) # Treat dicts as a unit + [{'a': 1}] + + Set *base_type* to ``None`` to avoid any special handling and treat objects + Python considers iterable as iterable: + + >>> obj = 'foo' + >>> list(always_iterable(obj, base_type=None)) + ['f', 'o', 'o'] + """ + if obj is None: + return iter(()) + + if (base_type is not None) and isinstance(obj, base_type): + return iter((obj,)) + + try: + return iter(obj) + except TypeError: + return iter((obj,)) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/_meta.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/_meta.py new file mode 100644 index 0000000000000000000000000000000000000000..1927d0f624d82f2fa12f81c80cce91279f039e84 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/_meta.py @@ -0,0 +1,67 @@ +from __future__ import annotations + +import os +from typing import Protocol +from typing import Any, Dict, Iterator, List, Optional, TypeVar, Union, overload + + +_T = TypeVar("_T") + + +class PackageMetadata(Protocol): + def __len__(self) -> int: ... # pragma: no cover + + def __contains__(self, item: str) -> bool: ... # pragma: no cover + + def __getitem__(self, key: str) -> str: ... # pragma: no cover + + def __iter__(self) -> Iterator[str]: ... # pragma: no cover + + @overload + def get( + self, name: str, failobj: None = None + ) -> Optional[str]: ... # pragma: no cover + + @overload + def get(self, name: str, failobj: _T) -> Union[str, _T]: ... # pragma: no cover + + # overload per python/importlib_metadata#435 + @overload + def get_all( + self, name: str, failobj: None = None + ) -> Optional[List[Any]]: ... # pragma: no cover + + @overload + def get_all(self, name: str, failobj: _T) -> Union[List[Any], _T]: + """ + Return all values associated with a possibly multi-valued key. + """ + + @property + def json(self) -> Dict[str, Union[str, List[str]]]: + """ + A JSON-compatible form of the metadata. + """ + + +class SimplePath(Protocol): + """ + A minimal subset of pathlib.Path required by Distribution. + """ + + def joinpath( + self, other: Union[str, os.PathLike[str]] + ) -> SimplePath: ... # pragma: no cover + + def __truediv__( + self, other: Union[str, os.PathLike[str]] + ) -> SimplePath: ... # pragma: no cover + + @property + def parent(self) -> SimplePath: ... # pragma: no cover + + def read_text(self, encoding=None) -> str: ... # pragma: no cover + + def read_bytes(self) -> bytes: ... # pragma: no cover + + def exists(self) -> bool: ... # pragma: no cover diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/_text.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/_text.py new file mode 100644 index 0000000000000000000000000000000000000000..c88cfbb2349c6401336bc5ba6623f51afd1eb59d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/_text.py @@ -0,0 +1,99 @@ +import re + +from ._functools import method_cache + + +# from jaraco.text 3.5 +class FoldedCase(str): + """ + A case insensitive string class; behaves just like str + except compares equal when the only variation is case. + + >>> s = FoldedCase('hello world') + + >>> s == 'Hello World' + True + + >>> 'Hello World' == s + True + + >>> s != 'Hello World' + False + + >>> s.index('O') + 4 + + >>> s.split('O') + ['hell', ' w', 'rld'] + + >>> sorted(map(FoldedCase, ['GAMMA', 'alpha', 'Beta'])) + ['alpha', 'Beta', 'GAMMA'] + + Sequence membership is straightforward. + + >>> "Hello World" in [s] + True + >>> s in ["Hello World"] + True + + You may test for set inclusion, but candidate and elements + must both be folded. + + >>> FoldedCase("Hello World") in {s} + True + >>> s in {FoldedCase("Hello World")} + True + + String inclusion works as long as the FoldedCase object + is on the right. + + >>> "hello" in FoldedCase("Hello World") + True + + But not if the FoldedCase object is on the left: + + >>> FoldedCase('hello') in 'Hello World' + False + + In that case, use in_: + + >>> FoldedCase('hello').in_('Hello World') + True + + >>> FoldedCase('hello') > FoldedCase('Hello') + False + """ + + def __lt__(self, other): + return self.lower() < other.lower() + + def __gt__(self, other): + return self.lower() > other.lower() + + def __eq__(self, other): + return self.lower() == other.lower() + + def __ne__(self, other): + return self.lower() != other.lower() + + def __hash__(self): + return hash(self.lower()) + + def __contains__(self, other): + return super().lower().__contains__(other.lower()) + + def in_(self, other): + "Does self appear in other?" + return self in FoldedCase(other) + + # cache lower since it's likely to be called frequently. + @method_cache + def lower(self): + return super().lower() + + def index(self, sub): + return self.lower().index(sub.lower()) + + def split(self, splitter=' ', maxsplit=0): + pattern = re.compile(re.escape(splitter), re.I) + return pattern.split(self, maxsplit) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/compat/__init__.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/compat/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/compat/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/compat/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf0cfcbe6cc1d377c4becb2aaee469d2deeac8ea Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/compat/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/compat/__pycache__/py311.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/compat/__pycache__/py311.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5bde3be9ec346d8046d83c560b01918bbb416dbd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/compat/__pycache__/py311.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/compat/__pycache__/py39.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/compat/__pycache__/py39.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a90a71abb777bc5654def0233a208ddf007fa7a5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/compat/__pycache__/py39.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/compat/py311.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/compat/py311.py new file mode 100644 index 0000000000000000000000000000000000000000..3a5327436f9b1d9eae371e321c491a270634b3cf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/compat/py311.py @@ -0,0 +1,22 @@ +import os +import pathlib +import sys +import types + + +def wrap(path): # pragma: no cover + """ + Workaround for https://github.com/python/cpython/issues/84538 + to add backward compatibility for walk_up=True. + An example affected package is dask-labextension, which uses + jupyter-packaging to install JupyterLab javascript files outside + of site-packages. + """ + + def relative_to(root, *, walk_up=False): + return pathlib.Path(os.path.relpath(path, root)) + + return types.SimpleNamespace(relative_to=relative_to) + + +relative_fix = wrap if sys.version_info < (3, 12) else lambda x: x diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/compat/py39.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/compat/py39.py new file mode 100644 index 0000000000000000000000000000000000000000..1f15bd97e6aa028d3e86734dd08c0eb5c06d79bc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/compat/py39.py @@ -0,0 +1,36 @@ +""" +Compatibility layer with Python 3.8/3.9 +""" + +from typing import TYPE_CHECKING, Any, Optional + +if TYPE_CHECKING: # pragma: no cover + # Prevent circular imports on runtime. + from .. import Distribution, EntryPoint +else: + Distribution = EntryPoint = Any + + +def normalized_name(dist: Distribution) -> Optional[str]: + """ + Honor name normalization for distributions that don't provide ``_normalized_name``. + """ + try: + return dist._normalized_name + except AttributeError: + from .. import Prepared # -> delay to prevent circular imports. + + return Prepared.normalize(getattr(dist, "name", None) or dist.metadata['Name']) + + +def ep_matches(ep: EntryPoint, **params) -> bool: + """ + Workaround for ``EntryPoint`` objects without the ``matches`` method. + """ + try: + return ep.matches(**params) + except AttributeError: + from .. import EntryPoint # -> delay to prevent circular imports. + + # Reconstruct the EntryPoint object to make sure it is compatible. + return EntryPoint(ep.name, ep.value, ep.group).matches(**params) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/diagnose.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/diagnose.py new file mode 100644 index 0000000000000000000000000000000000000000..e405471ac4d94371b1ee9b1622227ff76b337180 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/diagnose.py @@ -0,0 +1,21 @@ +import sys + +from . import Distribution + + +def inspect(path): + print("Inspecting", path) + dists = list(Distribution.discover(path=[path])) + if not dists: + return + print("Found", len(dists), "packages:", end=' ') + print(', '.join(dist.name for dist in dists)) + + +def run(): + for path in sys.path: + inspect(path) + + +if __name__ == '__main__': + run() diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/py.typed b/.venv/lib/python3.12/site-packages/setuptools/_vendor/importlib_metadata/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/inflect-7.3.1.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/setuptools/_vendor/inflect-7.3.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/inflect-7.3.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/inflect-7.3.1.dist-info/LICENSE b/.venv/lib/python3.12/site-packages/setuptools/_vendor/inflect-7.3.1.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1bb5a44356f00884a71ceeefd24ded6caaba2418 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/inflect-7.3.1.dist-info/LICENSE @@ -0,0 +1,17 @@ +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.12/site-packages/setuptools/_vendor/inflect-7.3.1.dist-info/METADATA b/.venv/lib/python3.12/site-packages/setuptools/_vendor/inflect-7.3.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..9a2097a54aaaf21e7f46235a3ccf362213032ca9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/inflect-7.3.1.dist-info/METADATA @@ -0,0 +1,591 @@ +Metadata-Version: 2.1 +Name: inflect +Version: 7.3.1 +Summary: Correctly generate plurals, singular nouns, ordinals, indefinite articles +Author-email: Paul Dyson +Maintainer-email: "Jason R. Coombs" +Project-URL: Source, https://github.com/jaraco/inflect +Keywords: plural,inflect,participle +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Natural Language :: English +Classifier: Operating System :: OS Independent +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: Text Processing :: Linguistic +Requires-Python: >=3.8 +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: more-itertools >=8.5.0 +Requires-Dist: typeguard >=4.0.1 +Requires-Dist: typing-extensions ; python_version < "3.9" +Provides-Extra: doc +Requires-Dist: sphinx >=3.5 ; extra == 'doc' +Requires-Dist: jaraco.packaging >=9.3 ; extra == 'doc' +Requires-Dist: rst.linker >=1.9 ; extra == 'doc' +Requires-Dist: furo ; extra == 'doc' +Requires-Dist: sphinx-lint ; extra == 'doc' +Requires-Dist: jaraco.tidelift >=1.4 ; extra == 'doc' +Provides-Extra: test +Requires-Dist: pytest !=8.1.*,>=6 ; extra == 'test' +Requires-Dist: pytest-checkdocs >=2.4 ; extra == 'test' +Requires-Dist: pytest-cov ; extra == 'test' +Requires-Dist: pytest-mypy ; extra == 'test' +Requires-Dist: pytest-enabler >=2.2 ; extra == 'test' +Requires-Dist: pytest-ruff >=0.2.1 ; extra == 'test' +Requires-Dist: pygments ; extra == 'test' + +.. image:: https://img.shields.io/pypi/v/inflect.svg + :target: https://pypi.org/project/inflect + +.. image:: https://img.shields.io/pypi/pyversions/inflect.svg + +.. image:: https://github.com/jaraco/inflect/actions/workflows/main.yml/badge.svg + :target: https://github.com/jaraco/inflect/actions?query=workflow%3A%22tests%22 + :alt: tests + +.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v2.json + :target: https://github.com/astral-sh/ruff + :alt: Ruff + +.. image:: https://readthedocs.org/projects/inflect/badge/?version=latest + :target: https://inflect.readthedocs.io/en/latest/?badge=latest + +.. image:: https://img.shields.io/badge/skeleton-2024-informational + :target: https://blog.jaraco.com/skeleton + +.. image:: https://tidelift.com/badges/package/pypi/inflect + :target: https://tidelift.com/subscription/pkg/pypi-inflect?utm_source=pypi-inflect&utm_medium=readme + +NAME +==== + +inflect.py - Correctly generate plurals, singular nouns, ordinals, indefinite articles; convert numbers to words. + +SYNOPSIS +======== + +.. code-block:: python + + import inflect + + p = inflect.engine() + + # METHODS: + + # plural plural_noun plural_verb plural_adj singular_noun no num + # compare compare_nouns compare_nouns compare_adjs + # a an + # present_participle + # ordinal number_to_words + # join + # inflect classical gender + # defnoun defverb defadj defa defan + + + # UNCONDITIONALLY FORM THE PLURAL + + print("The plural of ", word, " is ", p.plural(word)) + + + # CONDITIONALLY FORM THE PLURAL + + print("I saw", cat_count, p.plural("cat", cat_count)) + + + # FORM PLURALS FOR SPECIFIC PARTS OF SPEECH + + print( + p.plural_noun("I", N1), + p.plural_verb("saw", N1), + p.plural_adj("my", N2), + p.plural_noun("saw", N2), + ) + + + # FORM THE SINGULAR OF PLURAL NOUNS + + print("The singular of ", word, " is ", p.singular_noun(word)) + + # SELECT THE GENDER OF SINGULAR PRONOUNS + + print(p.singular_noun("they")) # 'it' + p.gender("feminine") + print(p.singular_noun("they")) # 'she' + + + # DEAL WITH "0/1/N" -> "no/1/N" TRANSLATION: + + print("There ", p.plural_verb("was", errors), p.no(" error", errors)) + + + # USE DEFAULT COUNTS: + + print( + p.num(N1, ""), + p.plural("I"), + p.plural_verb(" saw"), + p.num(N2), + p.plural_noun(" saw"), + ) + print("There ", p.num(errors, ""), p.plural_verb("was"), p.no(" error")) + + + # COMPARE TWO WORDS "NUMBER-INSENSITIVELY": + + if p.compare(word1, word2): + print("same") + if p.compare_nouns(word1, word2): + print("same noun") + if p.compare_verbs(word1, word2): + print("same verb") + if p.compare_adjs(word1, word2): + print("same adj.") + + + # ADD CORRECT "a" OR "an" FOR A GIVEN WORD: + + print("Did you want ", p.a(thing), " or ", p.an(idea)) + + + # CONVERT NUMERALS INTO ORDINALS (i.e. 1->1st, 2->2nd, 3->3rd, etc.) + + print("It was", p.ordinal(position), " from the left\n") + + # CONVERT NUMERALS TO WORDS (i.e. 1->"one", 101->"one hundred and one", etc.) + # RETURNS A SINGLE STRING... + + words = p.number_to_words(1234) + # "one thousand, two hundred and thirty-four" + words = p.number_to_words(p.ordinal(1234)) + # "one thousand, two hundred and thirty-fourth" + + + # GET BACK A LIST OF STRINGS, ONE FOR EACH "CHUNK"... + + words = p.number_to_words(1234, wantlist=True) + # ("one thousand","two hundred and thirty-four") + + + # OPTIONAL PARAMETERS CHANGE TRANSLATION: + + words = p.number_to_words(12345, group=1) + # "one, two, three, four, five" + + words = p.number_to_words(12345, group=2) + # "twelve, thirty-four, five" + + words = p.number_to_words(12345, group=3) + # "one twenty-three, forty-five" + + words = p.number_to_words(1234, andword="") + # "one thousand, two hundred thirty-four" + + words = p.number_to_words(1234, andword=", plus") + # "one thousand, two hundred, plus thirty-four" + # TODO: I get no comma before plus: check perl + + words = p.number_to_words(555_1202, group=1, zero="oh") + # "five, five, five, one, two, oh, two" + + words = p.number_to_words(555_1202, group=1, one="unity") + # "five, five, five, unity, two, oh, two" + + words = p.number_to_words(123.456, group=1, decimal="mark") + # "one two three mark four five six" + # TODO: DOCBUG: perl gives commas here as do I + + # LITERAL STYLE ONLY NAMES NUMBERS LESS THAN A CERTAIN THRESHOLD... + + words = p.number_to_words(9, threshold=10) # "nine" + words = p.number_to_words(10, threshold=10) # "ten" + words = p.number_to_words(11, threshold=10) # "11" + words = p.number_to_words(1000, threshold=10) # "1,000" + + # JOIN WORDS INTO A LIST: + + mylist = p.join(("apple", "banana", "carrot")) + # "apple, banana, and carrot" + + mylist = p.join(("apple", "banana")) + # "apple and banana" + + mylist = p.join(("apple", "banana", "carrot"), final_sep="") + # "apple, banana and carrot" + + + # REQUIRE "CLASSICAL" PLURALS (EG: "focus"->"foci", "cherub"->"cherubim") + + p.classical() # USE ALL CLASSICAL PLURALS + + p.classical(all=True) # USE ALL CLASSICAL PLURALS + p.classical(all=False) # SWITCH OFF CLASSICAL MODE + + p.classical(zero=True) # "no error" INSTEAD OF "no errors" + p.classical(zero=False) # "no errors" INSTEAD OF "no error" + + p.classical(herd=True) # "2 buffalo" INSTEAD OF "2 buffalos" + p.classical(herd=False) # "2 buffalos" INSTEAD OF "2 buffalo" + + p.classical(persons=True) # "2 chairpersons" INSTEAD OF "2 chairpeople" + p.classical(persons=False) # "2 chairpeople" INSTEAD OF "2 chairpersons" + + p.classical(ancient=True) # "2 formulae" INSTEAD OF "2 formulas" + p.classical(ancient=False) # "2 formulas" INSTEAD OF "2 formulae" + + + # INTERPOLATE "plural()", "plural_noun()", "plural_verb()", "plural_adj()", "singular_noun()", + # a()", "an()", "num()" AND "ordinal()" WITHIN STRINGS: + + print(p.inflect("The plural of {0} is plural('{0}')".format(word))) + print(p.inflect("The singular of {0} is singular_noun('{0}')".format(word))) + print(p.inflect("I saw {0} plural('cat',{0})".format(cat_count))) + print( + p.inflect( + "plural('I',{0}) " + "plural_verb('saw',{0}) " + "plural('a',{1}) " + "plural_noun('saw',{1})".format(N1, N2) + ) + ) + print( + p.inflect( + "num({0}, False)plural('I') " + "plural_verb('saw') " + "num({1}, False)plural('a') " + "plural_noun('saw')".format(N1, N2) + ) + ) + print(p.inflect("I saw num({0}) plural('cat')\nnum()".format(cat_count))) + print(p.inflect("There plural_verb('was',{0}) no('error',{0})".format(errors))) + print(p.inflect("There num({0}, False)plural_verb('was') no('error')".format(errors))) + print(p.inflect("Did you want a('{0}') or an('{1}')".format(thing, idea))) + print(p.inflect("It was ordinal('{0}') from the left".format(position))) + + + # ADD USER-DEFINED INFLECTIONS (OVERRIDING INBUILT RULES): + + p.defnoun("VAX", "VAXen") # SINGULAR => PLURAL + + p.defverb( + "will", # 1ST PERSON SINGULAR + "shall", # 1ST PERSON PLURAL + "will", # 2ND PERSON SINGULAR + "will", # 2ND PERSON PLURAL + "will", # 3RD PERSON SINGULAR + "will", # 3RD PERSON PLURAL + ) + + p.defadj("hir", "their") # SINGULAR => PLURAL + + p.defa("h") # "AY HALWAYS SEZ 'HAITCH'!" + + p.defan("horrendous.*") # "AN HORRENDOUS AFFECTATION" + + +DESCRIPTION +=========== + +The methods of the class ``engine`` in module ``inflect.py`` provide plural +inflections, singular noun inflections, "a"/"an" selection for English words, +and manipulation of numbers as words. + +Plural forms of all nouns, most verbs, and some adjectives are +provided. Where appropriate, "classical" variants (for example: "brother" -> +"brethren", "dogma" -> "dogmata", etc.) are also provided. + +Single forms of nouns are also provided. The gender of singular pronouns +can be chosen (for example "they" -> "it" or "she" or "he" or "they"). + +Pronunciation-based "a"/"an" selection is provided for all English +words, and most initialisms. + +It is also possible to inflect numerals (1,2,3) to ordinals (1st, 2nd, 3rd) +and to English words ("one", "two", "three"). + +In generating these inflections, ``inflect.py`` follows the Oxford +English Dictionary and the guidelines in Fowler's Modern English +Usage, preferring the former where the two disagree. + +The module is built around standard British spelling, but is designed +to cope with common American variants as well. Slang, jargon, and +other English dialects are *not* explicitly catered for. + +Where two or more inflected forms exist for a single word (typically a +"classical" form and a "modern" form), ``inflect.py`` prefers the +more common form (typically the "modern" one), unless "classical" +processing has been specified +(see `MODERN VS CLASSICAL INFLECTIONS`). + +FORMING PLURALS AND SINGULARS +============================= + +Inflecting Plurals and Singulars +-------------------------------- + +All of the ``plural...`` plural inflection methods take the word to be +inflected as their first argument and return the corresponding inflection. +Note that all such methods expect the *singular* form of the word. The +results of passing a plural form are undefined (and unlikely to be correct). +Similarly, the ``si...`` singular inflection method expects the *plural* +form of the word. + +The ``plural...`` methods also take an optional second argument, +which indicates the grammatical "number" of the word (or of another word +with which the word being inflected must agree). If the "number" argument is +supplied and is not ``1`` (or ``"one"`` or ``"a"``, or some other adjective that +implies the singular), the plural form of the word is returned. If the +"number" argument *does* indicate singularity, the (uninflected) word +itself is returned. If the number argument is omitted, the plural form +is returned unconditionally. + +The ``si...`` method takes a second argument in a similar fashion. If it is +some form of the number ``1``, or is omitted, the singular form is returned. +Otherwise the plural is returned unaltered. + + +The various methods of ``inflect.engine`` are: + + + +``plural_noun(word, count=None)`` + + The method ``plural_noun()`` takes a *singular* English noun or + pronoun and returns its plural. Pronouns in the nominative ("I" -> + "we") and accusative ("me" -> "us") cases are handled, as are + possessive pronouns ("mine" -> "ours"). + + +``plural_verb(word, count=None)`` + + The method ``plural_verb()`` takes the *singular* form of a + conjugated verb (that is, one which is already in the correct "person" + and "mood") and returns the corresponding plural conjugation. + + +``plural_adj(word, count=None)`` + + The method ``plural_adj()`` takes the *singular* form of + certain types of adjectives and returns the corresponding plural form. + Adjectives that are correctly handled include: "numerical" adjectives + ("a" -> "some"), demonstrative adjectives ("this" -> "these", "that" -> + "those"), and possessives ("my" -> "our", "cat's" -> "cats'", "child's" + -> "childrens'", etc.) + + +``plural(word, count=None)`` + + The method ``plural()`` takes a *singular* English noun, + pronoun, verb, or adjective and returns its plural form. Where a word + has more than one inflection depending on its part of speech (for + example, the noun "thought" inflects to "thoughts", the verb "thought" + to "thought"), the (singular) noun sense is preferred to the (singular) + verb sense. + + Hence ``plural("knife")`` will return "knives" ("knife" having been treated + as a singular noun), whereas ``plural("knifes")`` will return "knife" + ("knifes" having been treated as a 3rd person singular verb). + + The inherent ambiguity of such cases suggests that, + where the part of speech is known, ``plural_noun``, ``plural_verb``, and + ``plural_adj`` should be used in preference to ``plural``. + + +``singular_noun(word, count=None)`` + + The method ``singular_noun()`` takes a *plural* English noun or + pronoun and returns its singular. Pronouns in the nominative ("we" -> + "I") and accusative ("us" -> "me") cases are handled, as are + possessive pronouns ("ours" -> "mine"). When third person + singular pronouns are returned they take the neuter gender by default + ("they" -> "it"), not ("they"-> "she") nor ("they" -> "he"). This can be + changed with ``gender()``. + +Note that all these methods ignore any whitespace surrounding the +word being inflected, but preserve that whitespace when the result is +returned. For example, ``plural(" cat ")`` returns " cats ". + + +``gender(genderletter)`` + + The third person plural pronoun takes the same form for the female, male and + neuter (e.g. "they"). The singular however, depends upon gender (e.g. "she", + "he", "it" and "they" -- "they" being the gender neutral form.) By default + ``singular_noun`` returns the neuter form, however, the gender can be selected with + the ``gender`` method. Pass the first letter of the gender to + ``gender`` to return the f(eminine), m(asculine), n(euter) or t(hey) + form of the singular. e.g. + gender('f') followed by singular_noun('themselves') returns 'herself'. + +Numbered plurals +---------------- + +The ``plural...`` methods return only the inflected word, not the count that +was used to inflect it. Thus, in order to produce "I saw 3 ducks", it +is necessary to use: + +.. code-block:: python + + print("I saw", N, p.plural_noun(animal, N)) + +Since the usual purpose of producing a plural is to make it agree with +a preceding count, inflect.py provides a method +(``no(word, count)``) which, given a word and a(n optional) count, returns the +count followed by the correctly inflected word. Hence the previous +example can be rewritten: + +.. code-block:: python + + print("I saw ", p.no(animal, N)) + +In addition, if the count is zero (or some other term which implies +zero, such as ``"zero"``, ``"nil"``, etc.) the count is replaced by the +word "no". Hence, if ``N`` had the value zero, the previous example +would print (the somewhat more elegant):: + + I saw no animals + +rather than:: + + I saw 0 animals + +Note that the name of the method is a pun: the method +returns either a number (a *No.*) or a ``"no"``, in front of the +inflected word. + + +Reducing the number of counts required +-------------------------------------- + +In some contexts, the need to supply an explicit count to the various +``plural...`` methods makes for tiresome repetition. For example: + +.. code-block:: python + + print( + plural_adj("This", errors), + plural_noun(" error", errors), + plural_verb(" was", errors), + " fatal.", + ) + +inflect.py therefore provides a method +(``num(count=None, show=None)``) which may be used to set a persistent "default number" +value. If such a value is set, it is subsequently used whenever an +optional second "number" argument is omitted. The default value thus set +can subsequently be removed by calling ``num()`` with no arguments. +Hence we could rewrite the previous example: + +.. code-block:: python + + p.num(errors) + print(p.plural_adj("This"), p.plural_noun(" error"), p.plural_verb(" was"), "fatal.") + p.num() + +Normally, ``num()`` returns its first argument, so that it may also +be "inlined" in contexts like: + +.. code-block:: python + + print(p.num(errors), p.plural_noun(" error"), p.plural_verb(" was"), " detected.") + if severity > 1: + print( + p.plural_adj("This"), p.plural_noun(" error"), p.plural_verb(" was"), "fatal." + ) + +However, in certain contexts (see `INTERPOLATING INFLECTIONS IN STRINGS`) +it is preferable that ``num()`` return an empty string. Hence ``num()`` +provides an optional second argument. If that argument is supplied (that is, if +it is defined) and evaluates to false, ``num`` returns an empty string +instead of its first argument. For example: + +.. code-block:: python + + print(p.num(errors, 0), p.no("error"), p.plural_verb(" was"), " detected.") + if severity > 1: + print( + p.plural_adj("This"), p.plural_noun(" error"), p.plural_verb(" was"), "fatal." + ) + + + +Number-insensitive equality +--------------------------- + +inflect.py also provides a solution to the problem +of comparing words of differing plurality through the methods +``compare(word1, word2)``, ``compare_nouns(word1, word2)``, +``compare_verbs(word1, word2)``, and ``compare_adjs(word1, word2)``. +Each of these methods takes two strings, and compares them +using the corresponding plural-inflection method (``plural()``, ``plural_noun()``, +``plural_verb()``, and ``plural_adj()`` respectively). + +The comparison returns true if: + +- the strings are equal, or +- one string is equal to a plural form of the other, or +- the strings are two different plural forms of the one word. + + +Hence all of the following return true: + +.. code-block:: python + + p.compare("index", "index") # RETURNS "eq" + p.compare("index", "indexes") # RETURNS "s:p" + p.compare("index", "indices") # RETURNS "s:p" + p.compare("indexes", "index") # RETURNS "p:s" + p.compare("indices", "index") # RETURNS "p:s" + p.compare("indices", "indexes") # RETURNS "p:p" + p.compare("indexes", "indices") # RETURNS "p:p" + p.compare("indices", "indices") # RETURNS "eq" + +As indicated by the comments in the previous example, the actual value +returned by the various ``compare`` methods encodes which of the +three equality rules succeeded: "eq" is returned if the strings were +identical, "s:p" if the strings were singular and plural respectively, +"p:s" for plural and singular, and "p:p" for two distinct plurals. +Inequality is indicated by returning an empty string. + +It should be noted that two distinct singular words which happen to take +the same plural form are *not* considered equal, nor are cases where +one (singular) word's plural is the other (plural) word's singular. +Hence all of the following return false: + +.. code-block:: python + + p.compare("base", "basis") # ALTHOUGH BOTH -> "bases" + p.compare("syrinx", "syringe") # ALTHOUGH BOTH -> "syringes" + p.compare("she", "he") # ALTHOUGH BOTH -> "they" + + p.compare("opus", "operas") # ALTHOUGH "opus" -> "opera" -> "operas" + p.compare("taxi", "taxes") # ALTHOUGH "taxi" -> "taxis" -> "taxes" + +Note too that, although the comparison is "number-insensitive" it is *not* +case-insensitive (that is, ``plural("time","Times")`` returns false. To obtain +both number and case insensitivity, use the ``lower()`` method on both strings +(that is, ``plural("time".lower(), "Times".lower())`` returns true). + +Related Functionality +===================== + +Shout out to these libraries that provide related functionality: + +* `WordSet `_ + parses identifiers like variable names into sets of words suitable for re-assembling + in another form. + +* `word2number `_ converts words to + a number. + + +For Enterprise +============== + +Available as part of the Tidelift Subscription. + +This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use. + +`Learn more `_. diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/inflect-7.3.1.dist-info/RECORD b/.venv/lib/python3.12/site-packages/setuptools/_vendor/inflect-7.3.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..73ff576be5f4bf4cc1caa75633e475150b69cf2f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/inflect-7.3.1.dist-info/RECORD @@ -0,0 +1,13 @@ +inflect-7.3.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +inflect-7.3.1.dist-info/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023 +inflect-7.3.1.dist-info/METADATA,sha256=ZgMNY0WAZRs-U8wZiV2SMfjSKqBrMngXyDMs_CAwMwg,21079 +inflect-7.3.1.dist-info/RECORD,, +inflect-7.3.1.dist-info/WHEEL,sha256=y4mX-SOX4fYIkonsAGA5N0Oy-8_gI4FXw5HNI1xqvWg,91 +inflect-7.3.1.dist-info/top_level.txt,sha256=m52ujdp10CqT6jh1XQxZT6kEntcnv-7Tl7UiGNTzWZA,8 +inflect/__init__.py,sha256=Jxy1HJXZiZ85kHeLAhkmvz6EMTdFqBe-duvt34R6IOc,103796 +inflect/__pycache__/__init__.cpython-312.pyc,, +inflect/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +inflect/compat/__pycache__/__init__.cpython-312.pyc,, +inflect/compat/__pycache__/py38.cpython-312.pyc,, +inflect/compat/py38.py,sha256=oObVfVnWX9_OpnOuEJn1mFbJxVhwyR5epbiTNXDDaso,160 +inflect/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/inflect-7.3.1.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/setuptools/_vendor/inflect-7.3.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..564c6724e4bdf48d3dc10e804a73f100414c6533 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/inflect-7.3.1.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (70.2.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/inflect-7.3.1.dist-info/top_level.txt b/.venv/lib/python3.12/site-packages/setuptools/_vendor/inflect-7.3.1.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..0fd75fab3e9e94881f61ee5eb66aef862e637a36 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/inflect-7.3.1.dist-info/top_level.txt @@ -0,0 +1 @@ +inflect diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/inflect/__init__.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/inflect/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3eec27f4c67f24db167393895a6eaf0a9aa16d35 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/inflect/__init__.py @@ -0,0 +1,3986 @@ +""" +inflect: english language inflection + - correctly generate plurals, ordinals, indefinite articles + - convert numbers to words + +Copyright (C) 2010 Paul Dyson + +Based upon the Perl module +`Lingua::EN::Inflect `_. + +methods: + classical inflect + plural plural_noun plural_verb plural_adj singular_noun no num a an + compare compare_nouns compare_verbs compare_adjs + present_participle + ordinal + number_to_words + join + defnoun defverb defadj defa defan + +INFLECTIONS: + classical inflect + plural plural_noun plural_verb plural_adj singular_noun compare + no num a an present_participle + +PLURALS: + classical inflect + plural plural_noun plural_verb plural_adj singular_noun no num + compare compare_nouns compare_verbs compare_adjs + +COMPARISONS: + classical + compare compare_nouns compare_verbs compare_adjs + +ARTICLES: + classical inflect num a an + +NUMERICAL: + ordinal number_to_words + +USER_DEFINED: + defnoun defverb defadj defa defan + +Exceptions: + UnknownClassicalModeError + BadNumValueError + BadChunkingOptionError + NumOutOfRangeError + BadUserDefinedPatternError + BadRcFileError + BadGenderError + +""" + +from __future__ import annotations + +import ast +import collections +import contextlib +import functools +import itertools +import re +from numbers import Number +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + Iterable, + List, + Literal, + Match, + Optional, + Sequence, + Tuple, + Union, + cast, +) + +from more_itertools import windowed_complete +from typeguard import typechecked + +from .compat.py38 import Annotated + + +class UnknownClassicalModeError(Exception): + pass + + +class BadNumValueError(Exception): + pass + + +class BadChunkingOptionError(Exception): + pass + + +class NumOutOfRangeError(Exception): + pass + + +class BadUserDefinedPatternError(Exception): + pass + + +class BadRcFileError(Exception): + pass + + +class BadGenderError(Exception): + pass + + +def enclose(s: str) -> str: + return f"(?:{s})" + + +def joinstem(cutpoint: Optional[int] = 0, words: Optional[Iterable[str]] = None) -> str: + """ + Join stem of each word in words into a string for regex. + + Each word is truncated at cutpoint. + + Cutpoint is usually negative indicating the number of letters to remove + from the end of each word. + + >>> joinstem(-2, ["ephemeris", "iris", ".*itis"]) + '(?:ephemer|ir|.*it)' + + >>> joinstem(None, ["ephemeris"]) + '(?:ephemeris)' + + >>> joinstem(5, None) + '(?:)' + """ + return enclose("|".join(w[:cutpoint] for w in words or [])) + + +def bysize(words: Iterable[str]) -> Dict[int, set]: + """ + From a list of words, return a dict of sets sorted by word length. + + >>> words = ['ant', 'cat', 'dog', 'pig', 'frog', 'goat', 'horse', 'elephant'] + >>> ret = bysize(words) + >>> sorted(ret[3]) + ['ant', 'cat', 'dog', 'pig'] + >>> ret[5] + {'horse'} + """ + res: Dict[int, set] = collections.defaultdict(set) + for w in words: + res[len(w)].add(w) + return res + + +def make_pl_si_lists( + lst: Iterable[str], + plending: str, + siendingsize: Optional[int], + dojoinstem: bool = True, +): + """ + given a list of singular words: lst + + an ending to append to make the plural: plending + + the number of characters to remove from the singular + before appending plending: siendingsize + + a flag whether to create a joinstem: dojoinstem + + return: + a list of pluralised words: si_list (called si because this is what you need to + look for to make the singular) + + the pluralised words as a dict of sets sorted by word length: si_bysize + the singular words as a dict of sets sorted by word length: pl_bysize + if dojoinstem is True: a regular expression that matches any of the stems: stem + """ + if siendingsize is not None: + siendingsize = -siendingsize + si_list = [w[:siendingsize] + plending for w in lst] + pl_bysize = bysize(lst) + si_bysize = bysize(si_list) + if dojoinstem: + stem = joinstem(siendingsize, lst) + return si_list, si_bysize, pl_bysize, stem + else: + return si_list, si_bysize, pl_bysize + + +# 1. PLURALS + +pl_sb_irregular_s = { + "corpus": "corpuses|corpora", + "opus": "opuses|opera", + "genus": "genera", + "mythos": "mythoi", + "penis": "penises|penes", + "testis": "testes", + "atlas": "atlases|atlantes", + "yes": "yeses", +} + +pl_sb_irregular = { + "child": "children", + "chili": "chilis|chilies", + "brother": "brothers|brethren", + "infinity": "infinities|infinity", + "loaf": "loaves", + "lore": "lores|lore", + "hoof": "hoofs|hooves", + "beef": "beefs|beeves", + "thief": "thiefs|thieves", + "money": "monies", + "mongoose": "mongooses", + "ox": "oxen", + "cow": "cows|kine", + "graffito": "graffiti", + "octopus": "octopuses|octopodes", + "genie": "genies|genii", + "ganglion": "ganglions|ganglia", + "trilby": "trilbys", + "turf": "turfs|turves", + "numen": "numina", + "atman": "atmas", + "occiput": "occiputs|occipita", + "sabretooth": "sabretooths", + "sabertooth": "sabertooths", + "lowlife": "lowlifes", + "flatfoot": "flatfoots", + "tenderfoot": "tenderfoots", + "romany": "romanies", + "jerry": "jerries", + "mary": "maries", + "talouse": "talouses", + "rom": "roma", + "carmen": "carmina", +} + +pl_sb_irregular.update(pl_sb_irregular_s) +# pl_sb_irregular_keys = enclose('|'.join(pl_sb_irregular.keys())) + +pl_sb_irregular_caps = { + "Romany": "Romanies", + "Jerry": "Jerrys", + "Mary": "Marys", + "Rom": "Roma", +} + +pl_sb_irregular_compound = {"prima donna": "prima donnas|prime donne"} + +si_sb_irregular = {v: k for (k, v) in pl_sb_irregular.items()} +for k in list(si_sb_irregular): + if "|" in k: + k1, k2 = k.split("|") + si_sb_irregular[k1] = si_sb_irregular[k2] = si_sb_irregular[k] + del si_sb_irregular[k] +si_sb_irregular_caps = {v: k for (k, v) in pl_sb_irregular_caps.items()} +si_sb_irregular_compound = {v: k for (k, v) in pl_sb_irregular_compound.items()} +for k in list(si_sb_irregular_compound): + if "|" in k: + k1, k2 = k.split("|") + si_sb_irregular_compound[k1] = si_sb_irregular_compound[k2] = ( + si_sb_irregular_compound[k] + ) + del si_sb_irregular_compound[k] + +# si_sb_irregular_keys = enclose('|'.join(si_sb_irregular.keys())) + +# Z's that don't double + +pl_sb_z_zes_list = ("quartz", "topaz") +pl_sb_z_zes_bysize = bysize(pl_sb_z_zes_list) + +pl_sb_ze_zes_list = ("snooze",) +pl_sb_ze_zes_bysize = bysize(pl_sb_ze_zes_list) + + +# CLASSICAL "..is" -> "..ides" + +pl_sb_C_is_ides_complete = [ + # GENERAL WORDS... + "ephemeris", + "iris", + "clitoris", + "chrysalis", + "epididymis", +] + +pl_sb_C_is_ides_endings = [ + # INFLAMATIONS... + "itis" +] + +pl_sb_C_is_ides = joinstem( + -2, pl_sb_C_is_ides_complete + [f".*{w}" for w in pl_sb_C_is_ides_endings] +) + +pl_sb_C_is_ides_list = pl_sb_C_is_ides_complete + pl_sb_C_is_ides_endings + +( + si_sb_C_is_ides_list, + si_sb_C_is_ides_bysize, + pl_sb_C_is_ides_bysize, +) = make_pl_si_lists(pl_sb_C_is_ides_list, "ides", 2, dojoinstem=False) + + +# CLASSICAL "..a" -> "..ata" + +pl_sb_C_a_ata_list = ( + "anathema", + "bema", + "carcinoma", + "charisma", + "diploma", + "dogma", + "drama", + "edema", + "enema", + "enigma", + "lemma", + "lymphoma", + "magma", + "melisma", + "miasma", + "oedema", + "sarcoma", + "schema", + "soma", + "stigma", + "stoma", + "trauma", + "gumma", + "pragma", +) + +( + si_sb_C_a_ata_list, + si_sb_C_a_ata_bysize, + pl_sb_C_a_ata_bysize, + pl_sb_C_a_ata, +) = make_pl_si_lists(pl_sb_C_a_ata_list, "ata", 1) + +# UNCONDITIONAL "..a" -> "..ae" + +pl_sb_U_a_ae_list = ( + "alumna", + "alga", + "vertebra", + "persona", + "vita", +) +( + si_sb_U_a_ae_list, + si_sb_U_a_ae_bysize, + pl_sb_U_a_ae_bysize, + pl_sb_U_a_ae, +) = make_pl_si_lists(pl_sb_U_a_ae_list, "e", None) + +# CLASSICAL "..a" -> "..ae" + +pl_sb_C_a_ae_list = ( + "amoeba", + "antenna", + "formula", + "hyperbola", + "medusa", + "nebula", + "parabola", + "abscissa", + "hydra", + "nova", + "lacuna", + "aurora", + "umbra", + "flora", + "fauna", +) +( + si_sb_C_a_ae_list, + si_sb_C_a_ae_bysize, + pl_sb_C_a_ae_bysize, + pl_sb_C_a_ae, +) = make_pl_si_lists(pl_sb_C_a_ae_list, "e", None) + + +# CLASSICAL "..en" -> "..ina" + +pl_sb_C_en_ina_list = ("stamen", "foramen", "lumen") + +( + si_sb_C_en_ina_list, + si_sb_C_en_ina_bysize, + pl_sb_C_en_ina_bysize, + pl_sb_C_en_ina, +) = make_pl_si_lists(pl_sb_C_en_ina_list, "ina", 2) + + +# UNCONDITIONAL "..um" -> "..a" + +pl_sb_U_um_a_list = ( + "bacterium", + "agendum", + "desideratum", + "erratum", + "stratum", + "datum", + "ovum", + "extremum", + "candelabrum", +) +( + si_sb_U_um_a_list, + si_sb_U_um_a_bysize, + pl_sb_U_um_a_bysize, + pl_sb_U_um_a, +) = make_pl_si_lists(pl_sb_U_um_a_list, "a", 2) + +# CLASSICAL "..um" -> "..a" + +pl_sb_C_um_a_list = ( + "maximum", + "minimum", + "momentum", + "optimum", + "quantum", + "cranium", + "curriculum", + "dictum", + "phylum", + "aquarium", + "compendium", + "emporium", + "encomium", + "gymnasium", + "honorarium", + "interregnum", + "lustrum", + "memorandum", + "millennium", + "rostrum", + "spectrum", + "speculum", + "stadium", + "trapezium", + "ultimatum", + "medium", + "vacuum", + "velum", + "consortium", + "arboretum", +) + +( + si_sb_C_um_a_list, + si_sb_C_um_a_bysize, + pl_sb_C_um_a_bysize, + pl_sb_C_um_a, +) = make_pl_si_lists(pl_sb_C_um_a_list, "a", 2) + + +# UNCONDITIONAL "..us" -> "i" + +pl_sb_U_us_i_list = ( + "alumnus", + "alveolus", + "bacillus", + "bronchus", + "locus", + "nucleus", + "stimulus", + "meniscus", + "sarcophagus", +) +( + si_sb_U_us_i_list, + si_sb_U_us_i_bysize, + pl_sb_U_us_i_bysize, + pl_sb_U_us_i, +) = make_pl_si_lists(pl_sb_U_us_i_list, "i", 2) + +# CLASSICAL "..us" -> "..i" + +pl_sb_C_us_i_list = ( + "focus", + "radius", + "genius", + "incubus", + "succubus", + "nimbus", + "fungus", + "nucleolus", + "stylus", + "torus", + "umbilicus", + "uterus", + "hippopotamus", + "cactus", +) + +( + si_sb_C_us_i_list, + si_sb_C_us_i_bysize, + pl_sb_C_us_i_bysize, + pl_sb_C_us_i, +) = make_pl_si_lists(pl_sb_C_us_i_list, "i", 2) + + +# CLASSICAL "..us" -> "..us" (ASSIMILATED 4TH DECLENSION LATIN NOUNS) + +pl_sb_C_us_us = ( + "status", + "apparatus", + "prospectus", + "sinus", + "hiatus", + "impetus", + "plexus", +) +pl_sb_C_us_us_bysize = bysize(pl_sb_C_us_us) + +# UNCONDITIONAL "..on" -> "a" + +pl_sb_U_on_a_list = ( + "criterion", + "perihelion", + "aphelion", + "phenomenon", + "prolegomenon", + "noumenon", + "organon", + "asyndeton", + "hyperbaton", +) +( + si_sb_U_on_a_list, + si_sb_U_on_a_bysize, + pl_sb_U_on_a_bysize, + pl_sb_U_on_a, +) = make_pl_si_lists(pl_sb_U_on_a_list, "a", 2) + +# CLASSICAL "..on" -> "..a" + +pl_sb_C_on_a_list = ("oxymoron",) + +( + si_sb_C_on_a_list, + si_sb_C_on_a_bysize, + pl_sb_C_on_a_bysize, + pl_sb_C_on_a, +) = make_pl_si_lists(pl_sb_C_on_a_list, "a", 2) + + +# CLASSICAL "..o" -> "..i" (BUT NORMALLY -> "..os") + +pl_sb_C_o_i = [ + "solo", + "soprano", + "basso", + "alto", + "contralto", + "tempo", + "piano", + "virtuoso", +] # list not tuple so can concat for pl_sb_U_o_os + +pl_sb_C_o_i_bysize = bysize(pl_sb_C_o_i) +si_sb_C_o_i_bysize = bysize([f"{w[:-1]}i" for w in pl_sb_C_o_i]) + +pl_sb_C_o_i_stems = joinstem(-1, pl_sb_C_o_i) + +# ALWAYS "..o" -> "..os" + +pl_sb_U_o_os_complete = {"ado", "ISO", "NATO", "NCO", "NGO", "oto"} +si_sb_U_o_os_complete = {f"{w}s" for w in pl_sb_U_o_os_complete} + + +pl_sb_U_o_os_endings = [ + "aficionado", + "aggro", + "albino", + "allegro", + "ammo", + "Antananarivo", + "archipelago", + "armadillo", + "auto", + "avocado", + "Bamako", + "Barquisimeto", + "bimbo", + "bingo", + "Biro", + "bolero", + "Bolzano", + "bongo", + "Boto", + "burro", + "Cairo", + "canto", + "cappuccino", + "casino", + "cello", + "Chicago", + "Chimango", + "cilantro", + "cochito", + "coco", + "Colombo", + "Colorado", + "commando", + "concertino", + "contango", + "credo", + "crescendo", + "cyano", + "demo", + "ditto", + "Draco", + "dynamo", + "embryo", + "Esperanto", + "espresso", + "euro", + "falsetto", + "Faro", + "fiasco", + "Filipino", + "flamenco", + "furioso", + "generalissimo", + "Gestapo", + "ghetto", + "gigolo", + "gizmo", + "Greensboro", + "gringo", + "Guaiabero", + "guano", + "gumbo", + "gyro", + "hairdo", + "hippo", + "Idaho", + "impetigo", + "inferno", + "info", + "intermezzo", + "intertrigo", + "Iquico", + "jumbo", + "junto", + "Kakapo", + "kilo", + "Kinkimavo", + "Kokako", + "Kosovo", + "Lesotho", + "libero", + "libido", + "libretto", + "lido", + "Lilo", + "limbo", + "limo", + "lineno", + "lingo", + "lino", + "livedo", + "loco", + "logo", + "lumbago", + "macho", + "macro", + "mafioso", + "magneto", + "magnifico", + "Majuro", + "Malabo", + "manifesto", + "Maputo", + "Maracaibo", + "medico", + "memo", + "metro", + "Mexico", + "micro", + "Milano", + "Monaco", + "mono", + "Montenegro", + "Morocco", + "Muqdisho", + "myo", + "neutrino", + "Ningbo", + "octavo", + "oregano", + "Orinoco", + "Orlando", + "Oslo", + "panto", + "Paramaribo", + "Pardusco", + "pedalo", + "photo", + "pimento", + "pinto", + "pleco", + "Pluto", + "pogo", + "polo", + "poncho", + "Porto-Novo", + "Porto", + "pro", + "psycho", + "pueblo", + "quarto", + "Quito", + "repo", + "rhino", + "risotto", + "rococo", + "rondo", + "Sacramento", + "saddo", + "sago", + "salvo", + "Santiago", + "Sapporo", + "Sarajevo", + "scherzando", + "scherzo", + "silo", + "sirocco", + "sombrero", + "staccato", + "sterno", + "stucco", + "stylo", + "sumo", + "Taiko", + "techno", + "terrazzo", + "testudo", + "timpano", + "tiro", + "tobacco", + "Togo", + "Tokyo", + "torero", + "Torino", + "Toronto", + "torso", + "tremolo", + "typo", + "tyro", + "ufo", + "UNESCO", + "vaquero", + "vermicello", + "verso", + "vibrato", + "violoncello", + "Virgo", + "weirdo", + "WHO", + "WTO", + "Yamoussoukro", + "yo-yo", + "zero", + "Zibo", +] + pl_sb_C_o_i + +pl_sb_U_o_os_bysize = bysize(pl_sb_U_o_os_endings) +si_sb_U_o_os_bysize = bysize([f"{w}s" for w in pl_sb_U_o_os_endings]) + + +# UNCONDITIONAL "..ch" -> "..chs" + +pl_sb_U_ch_chs_list = ("czech", "eunuch", "stomach") + +( + si_sb_U_ch_chs_list, + si_sb_U_ch_chs_bysize, + pl_sb_U_ch_chs_bysize, + pl_sb_U_ch_chs, +) = make_pl_si_lists(pl_sb_U_ch_chs_list, "s", None) + + +# UNCONDITIONAL "..[ei]x" -> "..ices" + +pl_sb_U_ex_ices_list = ("codex", "murex", "silex") +( + si_sb_U_ex_ices_list, + si_sb_U_ex_ices_bysize, + pl_sb_U_ex_ices_bysize, + pl_sb_U_ex_ices, +) = make_pl_si_lists(pl_sb_U_ex_ices_list, "ices", 2) + +pl_sb_U_ix_ices_list = ("radix", "helix") +( + si_sb_U_ix_ices_list, + si_sb_U_ix_ices_bysize, + pl_sb_U_ix_ices_bysize, + pl_sb_U_ix_ices, +) = make_pl_si_lists(pl_sb_U_ix_ices_list, "ices", 2) + +# CLASSICAL "..[ei]x" -> "..ices" + +pl_sb_C_ex_ices_list = ( + "vortex", + "vertex", + "cortex", + "latex", + "pontifex", + "apex", + "index", + "simplex", +) + +( + si_sb_C_ex_ices_list, + si_sb_C_ex_ices_bysize, + pl_sb_C_ex_ices_bysize, + pl_sb_C_ex_ices, +) = make_pl_si_lists(pl_sb_C_ex_ices_list, "ices", 2) + + +pl_sb_C_ix_ices_list = ("appendix",) + +( + si_sb_C_ix_ices_list, + si_sb_C_ix_ices_bysize, + pl_sb_C_ix_ices_bysize, + pl_sb_C_ix_ices, +) = make_pl_si_lists(pl_sb_C_ix_ices_list, "ices", 2) + + +# ARABIC: ".." -> "..i" + +pl_sb_C_i_list = ("afrit", "afreet", "efreet") + +(si_sb_C_i_list, si_sb_C_i_bysize, pl_sb_C_i_bysize, pl_sb_C_i) = make_pl_si_lists( + pl_sb_C_i_list, "i", None +) + + +# HEBREW: ".." -> "..im" + +pl_sb_C_im_list = ("goy", "seraph", "cherub") + +(si_sb_C_im_list, si_sb_C_im_bysize, pl_sb_C_im_bysize, pl_sb_C_im) = make_pl_si_lists( + pl_sb_C_im_list, "im", None +) + + +# UNCONDITIONAL "..man" -> "..mans" + +pl_sb_U_man_mans_list = """ + ataman caiman cayman ceriman + desman dolman farman harman hetman + human leman ottoman shaman talisman +""".split() +pl_sb_U_man_mans_caps_list = """ + Alabaman Bahaman Burman German + Hiroshiman Liman Nakayaman Norman Oklahoman + Panaman Roman Selman Sonaman Tacoman Yakiman + Yokohaman Yuman +""".split() + +( + si_sb_U_man_mans_list, + si_sb_U_man_mans_bysize, + pl_sb_U_man_mans_bysize, +) = make_pl_si_lists(pl_sb_U_man_mans_list, "s", None, dojoinstem=False) +( + si_sb_U_man_mans_caps_list, + si_sb_U_man_mans_caps_bysize, + pl_sb_U_man_mans_caps_bysize, +) = make_pl_si_lists(pl_sb_U_man_mans_caps_list, "s", None, dojoinstem=False) + +# UNCONDITIONAL "..louse" -> "..lice" +pl_sb_U_louse_lice_list = ("booklouse", "grapelouse", "louse", "woodlouse") + +( + si_sb_U_louse_lice_list, + si_sb_U_louse_lice_bysize, + pl_sb_U_louse_lice_bysize, +) = make_pl_si_lists(pl_sb_U_louse_lice_list, "lice", 5, dojoinstem=False) + +pl_sb_uninflected_s_complete = [ + # PAIRS OR GROUPS SUBSUMED TO A SINGULAR... + "breeches", + "britches", + "pajamas", + "pyjamas", + "clippers", + "gallows", + "hijinks", + "headquarters", + "pliers", + "scissors", + "testes", + "herpes", + "pincers", + "shears", + "proceedings", + "trousers", + # UNASSIMILATED LATIN 4th DECLENSION + "cantus", + "coitus", + "nexus", + # RECENT IMPORTS... + "contretemps", + "corps", + "debris", + "siemens", + # DISEASES + "mumps", + # MISCELLANEOUS OTHERS... + "diabetes", + "jackanapes", + "series", + "species", + "subspecies", + "rabies", + "chassis", + "innings", + "news", + "mews", + "haggis", +] + +pl_sb_uninflected_s_endings = [ + # RECENT IMPORTS... + "ois", + # DISEASES + "measles", +] + +pl_sb_uninflected_s = pl_sb_uninflected_s_complete + [ + f".*{w}" for w in pl_sb_uninflected_s_endings +] + +pl_sb_uninflected_herd = ( + # DON'T INFLECT IN CLASSICAL MODE, OTHERWISE NORMAL INFLECTION + "wildebeest", + "swine", + "eland", + "bison", + "buffalo", + "cattle", + "elk", + "rhinoceros", + "zucchini", + "caribou", + "dace", + "grouse", + "guinea fowl", + "guinea-fowl", + "haddock", + "hake", + "halibut", + "herring", + "mackerel", + "pickerel", + "pike", + "roe", + "seed", + "shad", + "snipe", + "teal", + "turbot", + "water fowl", + "water-fowl", +) + +pl_sb_uninflected_complete = [ + # SOME FISH AND HERD ANIMALS + "tuna", + "salmon", + "mackerel", + "trout", + "bream", + "sea-bass", + "sea bass", + "carp", + "cod", + "flounder", + "whiting", + "moose", + # OTHER ODDITIES + "graffiti", + "djinn", + "samuri", + "offspring", + "pence", + "quid", + "hertz", +] + pl_sb_uninflected_s_complete +# SOME WORDS ENDING IN ...s (OFTEN PAIRS TAKEN AS A WHOLE) + +pl_sb_uninflected_caps = [ + # ALL NATIONALS ENDING IN -ese + "Portuguese", + "Amoyese", + "Borghese", + "Congoese", + "Faroese", + "Foochowese", + "Genevese", + "Genoese", + "Gilbertese", + "Hottentotese", + "Kiplingese", + "Kongoese", + "Lucchese", + "Maltese", + "Nankingese", + "Niasese", + "Pekingese", + "Piedmontese", + "Pistoiese", + "Sarawakese", + "Shavese", + "Vermontese", + "Wenchowese", + "Yengeese", +] + + +pl_sb_uninflected_endings = [ + # UNCOUNTABLE NOUNS + "butter", + "cash", + "furniture", + "information", + # SOME FISH AND HERD ANIMALS + "fish", + "deer", + "sheep", + # ALL NATIONALS ENDING IN -ese + "nese", + "rese", + "lese", + "mese", + # DISEASES + "pox", + # OTHER ODDITIES + "craft", +] + pl_sb_uninflected_s_endings +# SOME WORDS ENDING IN ...s (OFTEN PAIRS TAKEN AS A WHOLE) + + +pl_sb_uninflected_bysize = bysize(pl_sb_uninflected_endings) + + +# SINGULAR WORDS ENDING IN ...s (ALL INFLECT WITH ...es) + +pl_sb_singular_s_complete = [ + "acropolis", + "aegis", + "alias", + "asbestos", + "bathos", + "bias", + "bronchitis", + "bursitis", + "caddis", + "cannabis", + "canvas", + "chaos", + "cosmos", + "dais", + "digitalis", + "epidermis", + "ethos", + "eyas", + "gas", + "glottis", + "hubris", + "ibis", + "lens", + "mantis", + "marquis", + "metropolis", + "pathos", + "pelvis", + "polis", + "rhinoceros", + "sassafras", + "trellis", +] + pl_sb_C_is_ides_complete + + +pl_sb_singular_s_endings = ["ss", "us"] + pl_sb_C_is_ides_endings + +pl_sb_singular_s_bysize = bysize(pl_sb_singular_s_endings) + +si_sb_singular_s_complete = [f"{w}es" for w in pl_sb_singular_s_complete] +si_sb_singular_s_endings = [f"{w}es" for w in pl_sb_singular_s_endings] +si_sb_singular_s_bysize = bysize(si_sb_singular_s_endings) + +pl_sb_singular_s_es = ["[A-Z].*es"] + +pl_sb_singular_s = enclose( + "|".join( + pl_sb_singular_s_complete + + [f".*{w}" for w in pl_sb_singular_s_endings] + + pl_sb_singular_s_es + ) +) + + +# PLURALS ENDING IN uses -> use + + +si_sb_ois_oi_case = ("Bolshois", "Hanois") + +si_sb_uses_use_case = ("Betelgeuses", "Duses", "Meuses", "Syracuses", "Toulouses") + +si_sb_uses_use = ( + "abuses", + "applauses", + "blouses", + "carouses", + "causes", + "chartreuses", + "clauses", + "contuses", + "douses", + "excuses", + "fuses", + "grouses", + "hypotenuses", + "masseuses", + "menopauses", + "misuses", + "muses", + "overuses", + "pauses", + "peruses", + "profuses", + "recluses", + "reuses", + "ruses", + "souses", + "spouses", + "suffuses", + "transfuses", + "uses", +) + +si_sb_ies_ie_case = ( + "Addies", + "Aggies", + "Allies", + "Amies", + "Angies", + "Annies", + "Annmaries", + "Archies", + "Arties", + "Aussies", + "Barbies", + "Barries", + "Basies", + "Bennies", + "Bernies", + "Berties", + "Bessies", + "Betties", + "Billies", + "Blondies", + "Bobbies", + "Bonnies", + "Bowies", + "Brandies", + "Bries", + "Brownies", + "Callies", + "Carnegies", + "Carries", + "Cassies", + "Charlies", + "Cheries", + "Christies", + "Connies", + "Curies", + "Dannies", + "Debbies", + "Dixies", + "Dollies", + "Donnies", + "Drambuies", + "Eddies", + "Effies", + "Ellies", + "Elsies", + "Eries", + "Ernies", + "Essies", + "Eugenies", + "Fannies", + "Flossies", + "Frankies", + "Freddies", + "Gillespies", + "Goldies", + "Gracies", + "Guthries", + "Hallies", + "Hatties", + "Hetties", + "Hollies", + "Jackies", + "Jamies", + "Janies", + "Jannies", + "Jeanies", + "Jeannies", + "Jennies", + "Jessies", + "Jimmies", + "Jodies", + "Johnies", + "Johnnies", + "Josies", + "Julies", + "Kalgoorlies", + "Kathies", + "Katies", + "Kellies", + "Kewpies", + "Kristies", + "Laramies", + "Lassies", + "Lauries", + "Leslies", + "Lessies", + "Lillies", + "Lizzies", + "Lonnies", + "Lories", + "Lorries", + "Lotties", + "Louies", + "Mackenzies", + "Maggies", + "Maisies", + "Mamies", + "Marcies", + "Margies", + "Maries", + "Marjories", + "Matties", + "McKenzies", + "Melanies", + "Mickies", + "Millies", + "Minnies", + "Mollies", + "Mounties", + "Nannies", + "Natalies", + "Nellies", + "Netties", + "Ollies", + "Ozzies", + "Pearlies", + "Pottawatomies", + "Reggies", + "Richies", + "Rickies", + "Robbies", + "Ronnies", + "Rosalies", + "Rosemaries", + "Rosies", + "Roxies", + "Rushdies", + "Ruthies", + "Sadies", + "Sallies", + "Sammies", + "Scotties", + "Selassies", + "Sherries", + "Sophies", + "Stacies", + "Stefanies", + "Stephanies", + "Stevies", + "Susies", + "Sylvies", + "Tammies", + "Terries", + "Tessies", + "Tommies", + "Tracies", + "Trekkies", + "Valaries", + "Valeries", + "Valkyries", + "Vickies", + "Virgies", + "Willies", + "Winnies", + "Wylies", + "Yorkies", +) + +si_sb_ies_ie = ( + "aeries", + "baggies", + "belies", + "biggies", + "birdies", + "bogies", + "bonnies", + "boogies", + "bookies", + "bourgeoisies", + "brownies", + "budgies", + "caddies", + "calories", + "camaraderies", + "cockamamies", + "collies", + "cookies", + "coolies", + "cooties", + "coteries", + "crappies", + "curies", + "cutesies", + "dogies", + "eyries", + "floozies", + "footsies", + "freebies", + "genies", + "goalies", + "groupies", + "hies", + "jalousies", + "junkies", + "kiddies", + "laddies", + "lassies", + "lies", + "lingeries", + "magpies", + "menageries", + "mommies", + "movies", + "neckties", + "newbies", + "nighties", + "oldies", + "organdies", + "overlies", + "pies", + "pinkies", + "pixies", + "potpies", + "prairies", + "quickies", + "reveries", + "rookies", + "rotisseries", + "softies", + "sorties", + "species", + "stymies", + "sweeties", + "ties", + "underlies", + "unties", + "veggies", + "vies", + "yuppies", + "zombies", +) + + +si_sb_oes_oe_case = ( + "Chloes", + "Crusoes", + "Defoes", + "Faeroes", + "Ivanhoes", + "Joes", + "McEnroes", + "Moes", + "Monroes", + "Noes", + "Poes", + "Roscoes", + "Tahoes", + "Tippecanoes", + "Zoes", +) + +si_sb_oes_oe = ( + "aloes", + "backhoes", + "canoes", + "does", + "floes", + "foes", + "hoes", + "mistletoes", + "oboes", + "pekoes", + "roes", + "sloes", + "throes", + "tiptoes", + "toes", + "woes", +) + +si_sb_z_zes = ("quartzes", "topazes") + +si_sb_zzes_zz = ("buzzes", "fizzes", "frizzes", "razzes") + +si_sb_ches_che_case = ( + "Andromaches", + "Apaches", + "Blanches", + "Comanches", + "Nietzsches", + "Porsches", + "Roches", +) + +si_sb_ches_che = ( + "aches", + "avalanches", + "backaches", + "bellyaches", + "caches", + "cloches", + "creches", + "douches", + "earaches", + "fiches", + "headaches", + "heartaches", + "microfiches", + "niches", + "pastiches", + "psyches", + "quiches", + "stomachaches", + "toothaches", + "tranches", +) + +si_sb_xes_xe = ("annexes", "axes", "deluxes", "pickaxes") + +si_sb_sses_sse_case = ("Hesses", "Jesses", "Larousses", "Matisses") +si_sb_sses_sse = ( + "bouillabaisses", + "crevasses", + "demitasses", + "impasses", + "mousses", + "posses", +) + +si_sb_ves_ve_case = ( + # *[nwl]ives -> [nwl]live + "Clives", + "Palmolives", +) +si_sb_ves_ve = ( + # *[^d]eaves -> eave + "interweaves", + "weaves", + # *[nwl]ives -> [nwl]live + "olives", + # *[eoa]lves -> [eoa]lve + "bivalves", + "dissolves", + "resolves", + "salves", + "twelves", + "valves", +) + + +plverb_special_s = enclose( + "|".join( + [pl_sb_singular_s] + + pl_sb_uninflected_s + + list(pl_sb_irregular_s) + + ["(.*[csx])is", "(.*)ceps", "[A-Z].*s"] + ) +) + +_pl_sb_postfix_adj_defn = ( + ("general", enclose(r"(?!major|lieutenant|brigadier|adjutant|.*star)\S+")), + ("martial", enclose("court")), + ("force", enclose("pound")), +) + +pl_sb_postfix_adj: Iterable[str] = ( + enclose(val + f"(?=(?:-|\\s+){key})") for key, val in _pl_sb_postfix_adj_defn +) + +pl_sb_postfix_adj_stems = f"({'|'.join(pl_sb_postfix_adj)})(.*)" + + +# PLURAL WORDS ENDING IS es GO TO SINGULAR is + +si_sb_es_is = ( + "amanuenses", + "amniocenteses", + "analyses", + "antitheses", + "apotheoses", + "arterioscleroses", + "atheroscleroses", + "axes", + # 'bases', # bases -> basis + "catalyses", + "catharses", + "chasses", + "cirrhoses", + "cocces", + "crises", + "diagnoses", + "dialyses", + "diereses", + "electrolyses", + "emphases", + "exegeses", + "geneses", + "halitoses", + "hydrolyses", + "hypnoses", + "hypotheses", + "hystereses", + "metamorphoses", + "metastases", + "misdiagnoses", + "mitoses", + "mononucleoses", + "narcoses", + "necroses", + "nemeses", + "neuroses", + "oases", + "osmoses", + "osteoporoses", + "paralyses", + "parentheses", + "parthenogeneses", + "periphrases", + "photosyntheses", + "probosces", + "prognoses", + "prophylaxes", + "prostheses", + "preces", + "psoriases", + "psychoanalyses", + "psychokineses", + "psychoses", + "scleroses", + "scolioses", + "sepses", + "silicoses", + "symbioses", + "synopses", + "syntheses", + "taxes", + "telekineses", + "theses", + "thromboses", + "tuberculoses", + "urinalyses", +) + +pl_prep_list = """ + about above across after among around at athwart before behind + below beneath beside besides between betwixt beyond but by + during except for from in into near of off on onto out over + since till to under until unto upon with""".split() + +pl_prep_list_da = pl_prep_list + ["de", "du", "da"] + +pl_prep_bysize = bysize(pl_prep_list_da) + +pl_prep = enclose("|".join(pl_prep_list_da)) + +pl_sb_prep_dual_compound = rf"(.*?)((?:-|\s+)(?:{pl_prep})(?:-|\s+))a(?:-|\s+)(.*)" + + +singular_pronoun_genders = { + "neuter", + "feminine", + "masculine", + "gender-neutral", + "feminine or masculine", + "masculine or feminine", +} + +pl_pron_nom = { + # NOMINATIVE REFLEXIVE + "i": "we", + "myself": "ourselves", + "you": "you", + "yourself": "yourselves", + "she": "they", + "herself": "themselves", + "he": "they", + "himself": "themselves", + "it": "they", + "itself": "themselves", + "they": "they", + "themself": "themselves", + # POSSESSIVE + "mine": "ours", + "yours": "yours", + "hers": "theirs", + "his": "theirs", + "its": "theirs", + "theirs": "theirs", +} + +si_pron: Dict[str, Dict[str, Union[str, Dict[str, str]]]] = { + "nom": {v: k for (k, v) in pl_pron_nom.items()} +} +si_pron["nom"]["we"] = "I" + + +pl_pron_acc = { + # ACCUSATIVE REFLEXIVE + "me": "us", + "myself": "ourselves", + "you": "you", + "yourself": "yourselves", + "her": "them", + "herself": "themselves", + "him": "them", + "himself": "themselves", + "it": "them", + "itself": "themselves", + "them": "them", + "themself": "themselves", +} + +pl_pron_acc_keys = enclose("|".join(pl_pron_acc)) +pl_pron_acc_keys_bysize = bysize(pl_pron_acc) + +si_pron["acc"] = {v: k for (k, v) in pl_pron_acc.items()} + +for _thecase, _plur, _gend, _sing in ( + ("nom", "they", "neuter", "it"), + ("nom", "they", "feminine", "she"), + ("nom", "they", "masculine", "he"), + ("nom", "they", "gender-neutral", "they"), + ("nom", "they", "feminine or masculine", "she or he"), + ("nom", "they", "masculine or feminine", "he or she"), + ("nom", "themselves", "neuter", "itself"), + ("nom", "themselves", "feminine", "herself"), + ("nom", "themselves", "masculine", "himself"), + ("nom", "themselves", "gender-neutral", "themself"), + ("nom", "themselves", "feminine or masculine", "herself or himself"), + ("nom", "themselves", "masculine or feminine", "himself or herself"), + ("nom", "theirs", "neuter", "its"), + ("nom", "theirs", "feminine", "hers"), + ("nom", "theirs", "masculine", "his"), + ("nom", "theirs", "gender-neutral", "theirs"), + ("nom", "theirs", "feminine or masculine", "hers or his"), + ("nom", "theirs", "masculine or feminine", "his or hers"), + ("acc", "them", "neuter", "it"), + ("acc", "them", "feminine", "her"), + ("acc", "them", "masculine", "him"), + ("acc", "them", "gender-neutral", "them"), + ("acc", "them", "feminine or masculine", "her or him"), + ("acc", "them", "masculine or feminine", "him or her"), + ("acc", "themselves", "neuter", "itself"), + ("acc", "themselves", "feminine", "herself"), + ("acc", "themselves", "masculine", "himself"), + ("acc", "themselves", "gender-neutral", "themself"), + ("acc", "themselves", "feminine or masculine", "herself or himself"), + ("acc", "themselves", "masculine or feminine", "himself or herself"), +): + try: + si_pron[_thecase][_plur][_gend] = _sing # type: ignore + except TypeError: + si_pron[_thecase][_plur] = {} + si_pron[_thecase][_plur][_gend] = _sing # type: ignore + + +si_pron_acc_keys = enclose("|".join(si_pron["acc"])) +si_pron_acc_keys_bysize = bysize(si_pron["acc"]) + + +def get_si_pron(thecase, word, gender) -> str: + try: + sing = si_pron[thecase][word] + except KeyError: + raise # not a pronoun + try: + return sing[gender] # has several types due to gender + except TypeError: + return cast(str, sing) # answer independent of gender + + +# These dictionaries group verbs by first, second and third person +# conjugations. + +plverb_irregular_pres = { + "am": "are", + "are": "are", + "is": "are", + "was": "were", + "were": "were", + "have": "have", + "has": "have", + "do": "do", + "does": "do", +} + +plverb_ambiguous_pres = { + "act": "act", + "acts": "act", + "blame": "blame", + "blames": "blame", + "can": "can", + "must": "must", + "fly": "fly", + "flies": "fly", + "copy": "copy", + "copies": "copy", + "drink": "drink", + "drinks": "drink", + "fight": "fight", + "fights": "fight", + "fire": "fire", + "fires": "fire", + "like": "like", + "likes": "like", + "look": "look", + "looks": "look", + "make": "make", + "makes": "make", + "reach": "reach", + "reaches": "reach", + "run": "run", + "runs": "run", + "sink": "sink", + "sinks": "sink", + "sleep": "sleep", + "sleeps": "sleep", + "view": "view", + "views": "view", +} + +plverb_ambiguous_pres_keys = re.compile( + rf"^({enclose('|'.join(plverb_ambiguous_pres))})((\s.*)?)$", re.IGNORECASE +) + + +plverb_irregular_non_pres = ( + "did", + "had", + "ate", + "made", + "put", + "spent", + "fought", + "sank", + "gave", + "sought", + "shall", + "could", + "ought", + "should", +) + +plverb_ambiguous_non_pres = re.compile( + r"^((?:thought|saw|bent|will|might|cut))((\s.*)?)$", re.IGNORECASE +) + +# "..oes" -> "..oe" (the rest are "..oes" -> "o") + +pl_v_oes_oe = ("canoes", "floes", "oboes", "roes", "throes", "woes") +pl_v_oes_oe_endings_size4 = ("hoes", "toes") +pl_v_oes_oe_endings_size5 = ("shoes",) + + +pl_count_zero = ("0", "no", "zero", "nil") + + +pl_count_one = ("1", "a", "an", "one", "each", "every", "this", "that") + +pl_adj_special = {"a": "some", "an": "some", "this": "these", "that": "those"} + +pl_adj_special_keys = re.compile( + rf"^({enclose('|'.join(pl_adj_special))})$", re.IGNORECASE +) + +pl_adj_poss = { + "my": "our", + "your": "your", + "its": "their", + "her": "their", + "his": "their", + "their": "their", +} + +pl_adj_poss_keys = re.compile(rf"^({enclose('|'.join(pl_adj_poss))})$", re.IGNORECASE) + + +# 2. INDEFINITE ARTICLES + +# THIS PATTERN MATCHES STRINGS OF CAPITALS STARTING WITH A "VOWEL-SOUND" +# CONSONANT FOLLOWED BY ANOTHER CONSONANT, AND WHICH ARE NOT LIKELY +# TO BE REAL WORDS (OH, ALL RIGHT THEN, IT'S JUST MAGIC!) + +A_abbrev = re.compile( + r""" +^(?! FJO | [HLMNS]Y. | RY[EO] | SQU + | ( F[LR]? | [HL] | MN? | N | RH? | S[CHKLMNPTVW]? | X(YL)?) [AEIOU]) +[FHLMNRSX][A-Z] +""", + re.VERBOSE, +) + +# THIS PATTERN CODES THE BEGINNINGS OF ALL ENGLISH WORDS BEGINING WITH A +# 'y' FOLLOWED BY A CONSONANT. ANY OTHER Y-CONSONANT PREFIX THEREFORE +# IMPLIES AN ABBREVIATION. + +A_y_cons = re.compile(r"^(y(b[lor]|cl[ea]|fere|gg|p[ios]|rou|tt))", re.IGNORECASE) + +# EXCEPTIONS TO EXCEPTIONS + +A_explicit_a = re.compile(r"^((?:unabomber|unanimous|US))", re.IGNORECASE) + +A_explicit_an = re.compile( + r"^((?:euler|hour(?!i)|heir|honest|hono[ur]|mpeg))", re.IGNORECASE +) + +A_ordinal_an = re.compile(r"^([aefhilmnorsx]-?th)", re.IGNORECASE) + +A_ordinal_a = re.compile(r"^([bcdgjkpqtuvwyz]-?th)", re.IGNORECASE) + + +# NUMERICAL INFLECTIONS + +nth = { + 0: "th", + 1: "st", + 2: "nd", + 3: "rd", + 4: "th", + 5: "th", + 6: "th", + 7: "th", + 8: "th", + 9: "th", + 11: "th", + 12: "th", + 13: "th", +} +nth_suff = set(nth.values()) + +ordinal = dict( + ty="tieth", + one="first", + two="second", + three="third", + five="fifth", + eight="eighth", + nine="ninth", + twelve="twelfth", +) + +ordinal_suff = re.compile(rf"({'|'.join(ordinal)})\Z") + + +# NUMBERS + +unit = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] +teen = [ + "ten", + "eleven", + "twelve", + "thirteen", + "fourteen", + "fifteen", + "sixteen", + "seventeen", + "eighteen", + "nineteen", +] +ten = [ + "", + "", + "twenty", + "thirty", + "forty", + "fifty", + "sixty", + "seventy", + "eighty", + "ninety", +] +mill = [ + " ", + " thousand", + " million", + " billion", + " trillion", + " quadrillion", + " quintillion", + " sextillion", + " septillion", + " octillion", + " nonillion", + " decillion", +] + + +# SUPPORT CLASSICAL PLURALIZATIONS + +def_classical = dict( + all=False, zero=False, herd=False, names=True, persons=False, ancient=False +) + +all_classical = {k: True for k in def_classical} +no_classical = {k: False for k in def_classical} + + +# Maps strings to built-in constant types +string_to_constant = {"True": True, "False": False, "None": None} + + +# Pre-compiled regular expression objects +DOLLAR_DIGITS = re.compile(r"\$(\d+)") +FUNCTION_CALL = re.compile(r"((\w+)\([^)]*\)*)", re.IGNORECASE) +PARTITION_WORD = re.compile(r"\A(\s*)(.+?)(\s*)\Z") +PL_SB_POSTFIX_ADJ_STEMS_RE = re.compile( + rf"^(?:{pl_sb_postfix_adj_stems})$", re.IGNORECASE +) +PL_SB_PREP_DUAL_COMPOUND_RE = re.compile( + rf"^(?:{pl_sb_prep_dual_compound})$", re.IGNORECASE +) +DENOMINATOR = re.compile(r"(?P.+)( (per|a) .+)") +PLVERB_SPECIAL_S_RE = re.compile(rf"^({plverb_special_s})$") +WHITESPACE = re.compile(r"\s") +ENDS_WITH_S = re.compile(r"^(.*[^s])s$", re.IGNORECASE) +ENDS_WITH_APOSTROPHE_S = re.compile(r"^(.*)'s?$") +INDEFINITE_ARTICLE_TEST = re.compile(r"\A(\s*)(?:an?\s+)?(.+?)(\s*)\Z", re.IGNORECASE) +SPECIAL_AN = re.compile(r"^[aefhilmnorsx]$", re.IGNORECASE) +SPECIAL_A = re.compile(r"^[bcdgjkpqtuvwyz]$", re.IGNORECASE) +SPECIAL_ABBREV_AN = re.compile(r"^[aefhilmnorsx][.-]", re.IGNORECASE) +SPECIAL_ABBREV_A = re.compile(r"^[a-z][.-]", re.IGNORECASE) +CONSONANTS = re.compile(r"^[^aeiouy]", re.IGNORECASE) +ARTICLE_SPECIAL_EU = re.compile(r"^e[uw]", re.IGNORECASE) +ARTICLE_SPECIAL_ONCE = re.compile(r"^onc?e\b", re.IGNORECASE) +ARTICLE_SPECIAL_ONETIME = re.compile(r"^onetime\b", re.IGNORECASE) +ARTICLE_SPECIAL_UNIT = re.compile(r"^uni([^nmd]|mo)", re.IGNORECASE) +ARTICLE_SPECIAL_UBA = re.compile(r"^u[bcfghjkqrst][aeiou]", re.IGNORECASE) +ARTICLE_SPECIAL_UKR = re.compile(r"^ukr", re.IGNORECASE) +SPECIAL_CAPITALS = re.compile(r"^U[NK][AIEO]?") +VOWELS = re.compile(r"^[aeiou]", re.IGNORECASE) + +DIGIT_GROUP = re.compile(r"(\d)") +TWO_DIGITS = re.compile(r"(\d)(\d)") +THREE_DIGITS = re.compile(r"(\d)(\d)(\d)") +THREE_DIGITS_WORD = re.compile(r"(\d)(\d)(\d)(?=\D*\Z)") +TWO_DIGITS_WORD = re.compile(r"(\d)(\d)(?=\D*\Z)") +ONE_DIGIT_WORD = re.compile(r"(\d)(?=\D*\Z)") + +FOUR_DIGIT_COMMA = re.compile(r"(\d)(\d{3}(?:,|\Z))") +NON_DIGIT = re.compile(r"\D") +WHITESPACES_COMMA = re.compile(r"\s+,") +COMMA_WORD = re.compile(r", (\S+)\s+\Z") +WHITESPACES = re.compile(r"\s+") + + +PRESENT_PARTICIPLE_REPLACEMENTS = ( + (re.compile(r"ie$"), r"y"), + ( + re.compile(r"ue$"), + r"u", + ), # TODO: isn't ue$ -> u encompassed in the following rule? + (re.compile(r"([auy])e$"), r"\g<1>"), + (re.compile(r"ski$"), r"ski"), + (re.compile(r"[^b]i$"), r""), + (re.compile(r"^(are|were)$"), r"be"), + (re.compile(r"^(had)$"), r"hav"), + (re.compile(r"^(hoe)$"), r"\g<1>"), + (re.compile(r"([^e])e$"), r"\g<1>"), + (re.compile(r"er$"), r"er"), + (re.compile(r"([^aeiou][aeiouy]([bdgmnprst]))$"), r"\g<1>\g<2>"), +) + +DIGIT = re.compile(r"\d") + + +class Words(str): + lowered: str + split_: List[str] + first: str + last: str + + def __init__(self, orig) -> None: + self.lowered = self.lower() + self.split_ = self.split() + self.first = self.split_[0] + self.last = self.split_[-1] + + +Falsish = Any # ideally, falsish would only validate on bool(value) is False + + +_STATIC_TYPE_CHECKING = TYPE_CHECKING +# ^-- Workaround for typeguard AST manipulation: +# https://github.com/agronholm/typeguard/issues/353#issuecomment-1556306554 + +if _STATIC_TYPE_CHECKING: # pragma: no cover + Word = Annotated[str, "String with at least 1 character"] +else: + + class _WordMeta(type): # Too dynamic to be supported by mypy... + def __instancecheck__(self, instance: Any) -> bool: + return isinstance(instance, str) and len(instance) >= 1 + + class Word(metaclass=_WordMeta): # type: ignore[no-redef] + """String with at least 1 character""" + + +class engine: + def __init__(self) -> None: + self.classical_dict = def_classical.copy() + self.persistent_count: Optional[int] = None + self.mill_count = 0 + self.pl_sb_user_defined: List[Optional[Word]] = [] + self.pl_v_user_defined: List[Optional[Word]] = [] + self.pl_adj_user_defined: List[Optional[Word]] = [] + self.si_sb_user_defined: List[Optional[Word]] = [] + self.A_a_user_defined: List[Optional[Word]] = [] + self.thegender = "neuter" + self.__number_args: Optional[Dict[str, str]] = None + + @property + def _number_args(self): + return cast(Dict[str, str], self.__number_args) + + @_number_args.setter + def _number_args(self, val): + self.__number_args = val + + @typechecked + def defnoun(self, singular: Optional[Word], plural: Optional[Word]) -> int: + """ + Set the noun plural of singular to plural. + + """ + self.checkpat(singular) + self.checkpatplural(plural) + self.pl_sb_user_defined.extend((singular, plural)) + self.si_sb_user_defined.extend((plural, singular)) + return 1 + + @typechecked + def defverb( + self, + s1: Optional[Word], + p1: Optional[Word], + s2: Optional[Word], + p2: Optional[Word], + s3: Optional[Word], + p3: Optional[Word], + ) -> int: + """ + Set the verb plurals for s1, s2 and s3 to p1, p2 and p3 respectively. + + Where 1, 2 and 3 represent the 1st, 2nd and 3rd person forms of the verb. + + """ + self.checkpat(s1) + self.checkpat(s2) + self.checkpat(s3) + self.checkpatplural(p1) + self.checkpatplural(p2) + self.checkpatplural(p3) + self.pl_v_user_defined.extend((s1, p1, s2, p2, s3, p3)) + return 1 + + @typechecked + def defadj(self, singular: Optional[Word], plural: Optional[Word]) -> int: + """ + Set the adjective plural of singular to plural. + + """ + self.checkpat(singular) + self.checkpatplural(plural) + self.pl_adj_user_defined.extend((singular, plural)) + return 1 + + @typechecked + def defa(self, pattern: Optional[Word]) -> int: + """ + Define the indefinite article as 'a' for words matching pattern. + + """ + self.checkpat(pattern) + self.A_a_user_defined.extend((pattern, "a")) + return 1 + + @typechecked + def defan(self, pattern: Optional[Word]) -> int: + """ + Define the indefinite article as 'an' for words matching pattern. + + """ + self.checkpat(pattern) + self.A_a_user_defined.extend((pattern, "an")) + return 1 + + def checkpat(self, pattern: Optional[Word]) -> None: + """ + check for errors in a regex pattern + """ + if pattern is None: + return + try: + re.match(pattern, "") + except re.error as err: + raise BadUserDefinedPatternError(pattern) from err + + def checkpatplural(self, pattern: Optional[Word]) -> None: + """ + check for errors in a regex replace pattern + """ + return + + @typechecked + def ud_match(self, word: Word, wordlist: Sequence[Optional[Word]]) -> Optional[str]: + for i in range(len(wordlist) - 2, -2, -2): # backwards through even elements + mo = re.search(rf"^{wordlist[i]}$", word, re.IGNORECASE) + if mo: + if wordlist[i + 1] is None: + return None + pl = DOLLAR_DIGITS.sub( + r"\\1", cast(Word, wordlist[i + 1]) + ) # change $n to \n for expand + return mo.expand(pl) + return None + + def classical(self, **kwargs) -> None: + """ + turn classical mode on and off for various categories + + turn on all classical modes: + classical() + classical(all=True) + + turn on or off specific claassical modes: + e.g. + classical(herd=True) + classical(names=False) + + By default all classical modes are off except names. + + unknown value in args or key in kwargs raises + exception: UnknownClasicalModeError + + """ + if not kwargs: + self.classical_dict = all_classical.copy() + return + if "all" in kwargs: + if kwargs["all"]: + self.classical_dict = all_classical.copy() + else: + self.classical_dict = no_classical.copy() + + for k, v in kwargs.items(): + if k in def_classical: + self.classical_dict[k] = v + else: + raise UnknownClassicalModeError + + def num( + self, count: Optional[int] = None, show: Optional[int] = None + ) -> str: # (;$count,$show) + """ + Set the number to be used in other method calls. + + Returns count. + + Set show to False to return '' instead. + + """ + if count is not None: + try: + self.persistent_count = int(count) + except ValueError as err: + raise BadNumValueError from err + if (show is None) or show: + return str(count) + else: + self.persistent_count = None + return "" + + def gender(self, gender: str) -> None: + """ + set the gender for the singular of plural pronouns + + can be one of: + 'neuter' ('they' -> 'it') + 'feminine' ('they' -> 'she') + 'masculine' ('they' -> 'he') + 'gender-neutral' ('they' -> 'they') + 'feminine or masculine' ('they' -> 'she or he') + 'masculine or feminine' ('they' -> 'he or she') + """ + if gender in singular_pronoun_genders: + self.thegender = gender + else: + raise BadGenderError + + def _get_value_from_ast(self, obj): + """ + Return the value of the ast object. + """ + if isinstance(obj, ast.Num): + return obj.n + elif isinstance(obj, ast.Str): + return obj.s + elif isinstance(obj, ast.List): + return [self._get_value_from_ast(e) for e in obj.elts] + elif isinstance(obj, ast.Tuple): + return tuple([self._get_value_from_ast(e) for e in obj.elts]) + + # None, True and False are NameConstants in Py3.4 and above. + elif isinstance(obj, ast.NameConstant): + return obj.value + + # Probably passed a variable name. + # Or passed a single word without wrapping it in quotes as an argument + # ex: p.inflect("I plural(see)") instead of p.inflect("I plural('see')") + raise NameError(f"name '{obj.id}' is not defined") + + def _string_to_substitute( + self, mo: Match, methods_dict: Dict[str, Callable] + ) -> str: + """ + Return the string to be substituted for the match. + """ + matched_text, f_name = mo.groups() + # matched_text is the complete match string. e.g. plural_noun(cat) + # f_name is the function name. e.g. plural_noun + + # Return matched_text if function name is not in methods_dict + if f_name not in methods_dict: + return matched_text + + # Parse the matched text + a_tree = ast.parse(matched_text) + + # get the args and kwargs from ast objects + args_list = [ + self._get_value_from_ast(a) + for a in a_tree.body[0].value.args # type: ignore[attr-defined] + ] + kwargs_list = { + kw.arg: self._get_value_from_ast(kw.value) + for kw in a_tree.body[0].value.keywords # type: ignore[attr-defined] + } + + # Call the corresponding function + return methods_dict[f_name](*args_list, **kwargs_list) + + # 0. PERFORM GENERAL INFLECTIONS IN A STRING + + @typechecked + def inflect(self, text: Word) -> str: + """ + Perform inflections in a string. + + e.g. inflect('The plural of cat is plural(cat)') returns + 'The plural of cat is cats' + + can use plural, plural_noun, plural_verb, plural_adj, + singular_noun, a, an, no, ordinal, number_to_words, + and prespart + + """ + save_persistent_count = self.persistent_count + + # Dictionary of allowed methods + methods_dict: Dict[str, Callable] = { + "plural": self.plural, + "plural_adj": self.plural_adj, + "plural_noun": self.plural_noun, + "plural_verb": self.plural_verb, + "singular_noun": self.singular_noun, + "a": self.a, + "an": self.a, + "no": self.no, + "ordinal": self.ordinal, + "number_to_words": self.number_to_words, + "present_participle": self.present_participle, + "num": self.num, + } + + # Regular expression to find Python's function call syntax + output = FUNCTION_CALL.sub( + lambda mo: self._string_to_substitute(mo, methods_dict), text + ) + self.persistent_count = save_persistent_count + return output + + # ## PLURAL SUBROUTINES + + def postprocess(self, orig: str, inflected) -> str: + inflected = str(inflected) + if "|" in inflected: + word_options = inflected.split("|") + # When two parts of a noun need to be pluralized + if len(word_options[0].split(" ")) == len(word_options[1].split(" ")): + result = inflected.split("|")[self.classical_dict["all"]].split(" ") + # When only the last part of the noun needs to be pluralized + else: + result = inflected.split(" ") + for index, word in enumerate(result): + if "|" in word: + result[index] = word.split("|")[self.classical_dict["all"]] + else: + result = inflected.split(" ") + + # Try to fix word wise capitalization + for index, word in enumerate(orig.split(" ")): + if word == "I": + # Is this the only word for exceptions like this + # Where the original is fully capitalized + # without 'meaning' capitalization? + # Also this fails to handle a capitalizaion in context + continue + if word.capitalize() == word: + result[index] = result[index].capitalize() + if word == word.upper(): + result[index] = result[index].upper() + return " ".join(result) + + def partition_word(self, text: str) -> Tuple[str, str, str]: + mo = PARTITION_WORD.search(text) + if mo: + return mo.group(1), mo.group(2), mo.group(3) + else: + return "", "", "" + + @typechecked + def plural(self, text: Word, count: Optional[Union[str, int, Any]] = None) -> str: + """ + Return the plural of text. + + If count supplied, then return text if count is one of: + 1, a, an, one, each, every, this, that + + otherwise return the plural. + + Whitespace at the start and end is preserved. + + """ + pre, word, post = self.partition_word(text) + if not word: + return text + plural = self.postprocess( + word, + self._pl_special_adjective(word, count) + or self._pl_special_verb(word, count) + or self._plnoun(word, count), + ) + return f"{pre}{plural}{post}" + + @typechecked + def plural_noun( + self, text: Word, count: Optional[Union[str, int, Any]] = None + ) -> str: + """ + Return the plural of text, where text is a noun. + + If count supplied, then return text if count is one of: + 1, a, an, one, each, every, this, that + + otherwise return the plural. + + Whitespace at the start and end is preserved. + + """ + pre, word, post = self.partition_word(text) + if not word: + return text + plural = self.postprocess(word, self._plnoun(word, count)) + return f"{pre}{plural}{post}" + + @typechecked + def plural_verb( + self, text: Word, count: Optional[Union[str, int, Any]] = None + ) -> str: + """ + Return the plural of text, where text is a verb. + + If count supplied, then return text if count is one of: + 1, a, an, one, each, every, this, that + + otherwise return the plural. + + Whitespace at the start and end is preserved. + + """ + pre, word, post = self.partition_word(text) + if not word: + return text + plural = self.postprocess( + word, + self._pl_special_verb(word, count) or self._pl_general_verb(word, count), + ) + return f"{pre}{plural}{post}" + + @typechecked + def plural_adj( + self, text: Word, count: Optional[Union[str, int, Any]] = None + ) -> str: + """ + Return the plural of text, where text is an adjective. + + If count supplied, then return text if count is one of: + 1, a, an, one, each, every, this, that + + otherwise return the plural. + + Whitespace at the start and end is preserved. + + """ + pre, word, post = self.partition_word(text) + if not word: + return text + plural = self.postprocess(word, self._pl_special_adjective(word, count) or word) + return f"{pre}{plural}{post}" + + @typechecked + def compare(self, word1: Word, word2: Word) -> Union[str, bool]: + """ + compare word1 and word2 for equality regardless of plurality + + return values: + eq - the strings are equal + p:s - word1 is the plural of word2 + s:p - word2 is the plural of word1 + p:p - word1 and word2 are two different plural forms of the one word + False - otherwise + + >>> compare = engine().compare + >>> compare("egg", "eggs") + 's:p' + >>> compare('egg', 'egg') + 'eq' + + Words should not be empty. + + >>> compare('egg', '') + Traceback (most recent call last): + ... + typeguard.TypeCheckError:...is not an instance of inflect.Word + """ + norms = self.plural_noun, self.plural_verb, self.plural_adj + results = (self._plequal(word1, word2, norm) for norm in norms) + return next(filter(None, results), False) + + @typechecked + def compare_nouns(self, word1: Word, word2: Word) -> Union[str, bool]: + """ + compare word1 and word2 for equality regardless of plurality + word1 and word2 are to be treated as nouns + + return values: + eq - the strings are equal + p:s - word1 is the plural of word2 + s:p - word2 is the plural of word1 + p:p - word1 and word2 are two different plural forms of the one word + False - otherwise + + """ + return self._plequal(word1, word2, self.plural_noun) + + @typechecked + def compare_verbs(self, word1: Word, word2: Word) -> Union[str, bool]: + """ + compare word1 and word2 for equality regardless of plurality + word1 and word2 are to be treated as verbs + + return values: + eq - the strings are equal + p:s - word1 is the plural of word2 + s:p - word2 is the plural of word1 + p:p - word1 and word2 are two different plural forms of the one word + False - otherwise + + """ + return self._plequal(word1, word2, self.plural_verb) + + @typechecked + def compare_adjs(self, word1: Word, word2: Word) -> Union[str, bool]: + """ + compare word1 and word2 for equality regardless of plurality + word1 and word2 are to be treated as adjectives + + return values: + eq - the strings are equal + p:s - word1 is the plural of word2 + s:p - word2 is the plural of word1 + p:p - word1 and word2 are two different plural forms of the one word + False - otherwise + + """ + return self._plequal(word1, word2, self.plural_adj) + + @typechecked + def singular_noun( + self, + text: Word, + count: Optional[Union[int, str, Any]] = None, + gender: Optional[str] = None, + ) -> Union[str, Literal[False]]: + """ + Return the singular of text, where text is a plural noun. + + If count supplied, then return the singular if count is one of: + 1, a, an, one, each, every, this, that or if count is None + + otherwise return text unchanged. + + Whitespace at the start and end is preserved. + + >>> p = engine() + >>> p.singular_noun('horses') + 'horse' + >>> p.singular_noun('knights') + 'knight' + + Returns False when a singular noun is passed. + + >>> p.singular_noun('horse') + False + >>> p.singular_noun('knight') + False + >>> p.singular_noun('soldier') + False + + """ + pre, word, post = self.partition_word(text) + if not word: + return text + sing = self._sinoun(word, count=count, gender=gender) + if sing is not False: + plural = self.postprocess(word, sing) + return f"{pre}{plural}{post}" + return False + + def _plequal(self, word1: str, word2: str, pl) -> Union[str, bool]: # noqa: C901 + classval = self.classical_dict.copy() + self.classical_dict = all_classical.copy() + if word1 == word2: + return "eq" + if word1 == pl(word2): + return "p:s" + if pl(word1) == word2: + return "s:p" + self.classical_dict = no_classical.copy() + if word1 == pl(word2): + return "p:s" + if pl(word1) == word2: + return "s:p" + self.classical_dict = classval.copy() + + if pl == self.plural or pl == self.plural_noun: + if self._pl_check_plurals_N(word1, word2): + return "p:p" + if self._pl_check_plurals_N(word2, word1): + return "p:p" + if pl == self.plural or pl == self.plural_adj: + if self._pl_check_plurals_adj(word1, word2): + return "p:p" + return False + + def _pl_reg_plurals(self, pair: str, stems: str, end1: str, end2: str) -> bool: + pattern = rf"({stems})({end1}\|\1{end2}|{end2}\|\1{end1})" + return bool(re.search(pattern, pair)) + + def _pl_check_plurals_N(self, word1: str, word2: str) -> bool: + stem_endings = ( + (pl_sb_C_a_ata, "as", "ata"), + (pl_sb_C_is_ides, "is", "ides"), + (pl_sb_C_a_ae, "s", "e"), + (pl_sb_C_en_ina, "ens", "ina"), + (pl_sb_C_um_a, "ums", "a"), + (pl_sb_C_us_i, "uses", "i"), + (pl_sb_C_on_a, "ons", "a"), + (pl_sb_C_o_i_stems, "os", "i"), + (pl_sb_C_ex_ices, "exes", "ices"), + (pl_sb_C_ix_ices, "ixes", "ices"), + (pl_sb_C_i, "s", "i"), + (pl_sb_C_im, "s", "im"), + (".*eau", "s", "x"), + (".*ieu", "s", "x"), + (".*tri", "xes", "ces"), + (".{2,}[yia]n", "xes", "ges"), + ) + + words = map(Words, (word1, word2)) + pair = "|".join(word.last for word in words) + + return ( + pair in pl_sb_irregular_s.values() + or pair in pl_sb_irregular.values() + or pair in pl_sb_irregular_caps.values() + or any( + self._pl_reg_plurals(pair, stems, end1, end2) + for stems, end1, end2 in stem_endings + ) + ) + + def _pl_check_plurals_adj(self, word1: str, word2: str) -> bool: + word1a = word1[: word1.rfind("'")] if word1.endswith(("'s", "'")) else "" + word2a = word2[: word2.rfind("'")] if word2.endswith(("'s", "'")) else "" + + return ( + bool(word1a) + and bool(word2a) + and ( + self._pl_check_plurals_N(word1a, word2a) + or self._pl_check_plurals_N(word2a, word1a) + ) + ) + + def get_count(self, count: Optional[Union[str, int]] = None) -> Union[str, int]: + if count is None and self.persistent_count is not None: + count = self.persistent_count + + if count is not None: + count = ( + 1 + if ( + (str(count) in pl_count_one) + or ( + self.classical_dict["zero"] + and str(count).lower() in pl_count_zero + ) + ) + else 2 + ) + else: + count = "" + return count + + # @profile + def _plnoun( # noqa: C901 + self, word: str, count: Optional[Union[str, int]] = None + ) -> str: + count = self.get_count(count) + + # DEFAULT TO PLURAL + + if count == 1: + return word + + # HANDLE USER-DEFINED NOUNS + + value = self.ud_match(word, self.pl_sb_user_defined) + if value is not None: + return value + + # HANDLE EMPTY WORD, SINGULAR COUNT AND UNINFLECTED PLURALS + + if word == "": + return word + + word = Words(word) + + if word.last.lower() in pl_sb_uninflected_complete: + if len(word.split_) >= 3: + return self._handle_long_compounds(word, count=2) or word + return word + + if word in pl_sb_uninflected_caps: + return word + + for k, v in pl_sb_uninflected_bysize.items(): + if word.lowered[-k:] in v: + return word + + if self.classical_dict["herd"] and word.last.lower() in pl_sb_uninflected_herd: + return word + + # HANDLE COMPOUNDS ("Governor General", "mother-in-law", "aide-de-camp", ETC.) + + mo = PL_SB_POSTFIX_ADJ_STEMS_RE.search(word) + if mo and mo.group(2) != "": + return f"{self._plnoun(mo.group(1), 2)}{mo.group(2)}" + + if " a " in word.lowered or "-a-" in word.lowered: + mo = PL_SB_PREP_DUAL_COMPOUND_RE.search(word) + if mo and mo.group(2) != "" and mo.group(3) != "": + return ( + f"{self._plnoun(mo.group(1), 2)}" + f"{mo.group(2)}" + f"{self._plnoun(mo.group(3))}" + ) + + if len(word.split_) >= 3: + handled_words = self._handle_long_compounds(word, count=2) + if handled_words is not None: + return handled_words + + # only pluralize denominators in units + mo = DENOMINATOR.search(word.lowered) + if mo: + index = len(mo.group("denominator")) + return f"{self._plnoun(word[:index])}{word[index:]}" + + # handle units given in degrees (only accept if + # there is no more than one word following) + # degree Celsius => degrees Celsius but degree + # fahrenheit hour => degree fahrenheit hours + if len(word.split_) >= 2 and word.split_[-2] == "degree": + return " ".join([self._plnoun(word.first)] + word.split_[1:]) + + with contextlib.suppress(ValueError): + return self._handle_prepositional_phrase( + word.lowered, + functools.partial(self._plnoun, count=2), + '-', + ) + + # HANDLE PRONOUNS + + for k, v in pl_pron_acc_keys_bysize.items(): + if word.lowered[-k:] in v: # ends with accusative pronoun + for pk, pv in pl_prep_bysize.items(): + if word.lowered[:pk] in pv: # starts with a prep + if word.lowered.split() == [ + word.lowered[:pk], + word.lowered[-k:], + ]: + # only whitespace in between + return word.lowered[:-k] + pl_pron_acc[word.lowered[-k:]] + + try: + return pl_pron_nom[word.lowered] + except KeyError: + pass + + try: + return pl_pron_acc[word.lowered] + except KeyError: + pass + + # HANDLE ISOLATED IRREGULAR PLURALS + + if word.last in pl_sb_irregular_caps: + llen = len(word.last) + return f"{word[:-llen]}{pl_sb_irregular_caps[word.last]}" + + lowered_last = word.last.lower() + if lowered_last in pl_sb_irregular: + llen = len(lowered_last) + return f"{word[:-llen]}{pl_sb_irregular[lowered_last]}" + + dash_split = word.lowered.split('-') + if (" ".join(dash_split[-2:])).lower() in pl_sb_irregular_compound: + llen = len( + " ".join(dash_split[-2:]) + ) # TODO: what if 2 spaces between these words? + return ( + f"{word[:-llen]}" + f"{pl_sb_irregular_compound[(' '.join(dash_split[-2:])).lower()]}" + ) + + if word.lowered[-3:] == "quy": + return f"{word[:-1]}ies" + + if word.lowered[-6:] == "person": + if self.classical_dict["persons"]: + return f"{word}s" + else: + return f"{word[:-4]}ople" + + # HANDLE FAMILIES OF IRREGULAR PLURALS + + if word.lowered[-3:] == "man": + for k, v in pl_sb_U_man_mans_bysize.items(): + if word.lowered[-k:] in v: + return f"{word}s" + for k, v in pl_sb_U_man_mans_caps_bysize.items(): + if word[-k:] in v: + return f"{word}s" + return f"{word[:-3]}men" + if word.lowered[-5:] == "mouse": + return f"{word[:-5]}mice" + if word.lowered[-5:] == "louse": + v = pl_sb_U_louse_lice_bysize.get(len(word)) + if v and word.lowered in v: + return f"{word[:-5]}lice" + return f"{word}s" + if word.lowered[-5:] == "goose": + return f"{word[:-5]}geese" + if word.lowered[-5:] == "tooth": + return f"{word[:-5]}teeth" + if word.lowered[-4:] == "foot": + return f"{word[:-4]}feet" + if word.lowered[-4:] == "taco": + return f"{word[:-5]}tacos" + + if word.lowered == "die": + return "dice" + + # HANDLE UNASSIMILATED IMPORTS + + if word.lowered[-4:] == "ceps": + return word + if word.lowered[-4:] == "zoon": + return f"{word[:-2]}a" + if word.lowered[-3:] in ("cis", "sis", "xis"): + return f"{word[:-2]}es" + + for lastlet, d, numend, post in ( + ("h", pl_sb_U_ch_chs_bysize, None, "s"), + ("x", pl_sb_U_ex_ices_bysize, -2, "ices"), + ("x", pl_sb_U_ix_ices_bysize, -2, "ices"), + ("m", pl_sb_U_um_a_bysize, -2, "a"), + ("s", pl_sb_U_us_i_bysize, -2, "i"), + ("n", pl_sb_U_on_a_bysize, -2, "a"), + ("a", pl_sb_U_a_ae_bysize, None, "e"), + ): + if word.lowered[-1] == lastlet: # this test to add speed + for k, v in d.items(): + if word.lowered[-k:] in v: + return word[:numend] + post + + # HANDLE INCOMPLETELY ASSIMILATED IMPORTS + + if self.classical_dict["ancient"]: + if word.lowered[-4:] == "trix": + return f"{word[:-1]}ces" + if word.lowered[-3:] in ("eau", "ieu"): + return f"{word}x" + if word.lowered[-3:] in ("ynx", "inx", "anx") and len(word) > 4: + return f"{word[:-1]}ges" + + for lastlet, d, numend, post in ( + ("n", pl_sb_C_en_ina_bysize, -2, "ina"), + ("x", pl_sb_C_ex_ices_bysize, -2, "ices"), + ("x", pl_sb_C_ix_ices_bysize, -2, "ices"), + ("m", pl_sb_C_um_a_bysize, -2, "a"), + ("s", pl_sb_C_us_i_bysize, -2, "i"), + ("s", pl_sb_C_us_us_bysize, None, ""), + ("a", pl_sb_C_a_ae_bysize, None, "e"), + ("a", pl_sb_C_a_ata_bysize, None, "ta"), + ("s", pl_sb_C_is_ides_bysize, -1, "des"), + ("o", pl_sb_C_o_i_bysize, -1, "i"), + ("n", pl_sb_C_on_a_bysize, -2, "a"), + ): + if word.lowered[-1] == lastlet: # this test to add speed + for k, v in d.items(): + if word.lowered[-k:] in v: + return word[:numend] + post + + for d, numend, post in ( + (pl_sb_C_i_bysize, None, "i"), + (pl_sb_C_im_bysize, None, "im"), + ): + for k, v in d.items(): + if word.lowered[-k:] in v: + return word[:numend] + post + + # HANDLE SINGULAR NOUNS ENDING IN ...s OR OTHER SILIBANTS + + if lowered_last in pl_sb_singular_s_complete: + return f"{word}es" + + for k, v in pl_sb_singular_s_bysize.items(): + if word.lowered[-k:] in v: + return f"{word}es" + + if word.lowered[-2:] == "es" and word[0] == word[0].upper(): + return f"{word}es" + + if word.lowered[-1] == "z": + for k, v in pl_sb_z_zes_bysize.items(): + if word.lowered[-k:] in v: + return f"{word}es" + + if word.lowered[-2:-1] != "z": + return f"{word}zes" + + if word.lowered[-2:] == "ze": + for k, v in pl_sb_ze_zes_bysize.items(): + if word.lowered[-k:] in v: + return f"{word}s" + + if word.lowered[-2:] in ("ch", "sh", "zz", "ss") or word.lowered[-1] == "x": + return f"{word}es" + + # HANDLE ...f -> ...ves + + if word.lowered[-3:] in ("elf", "alf", "olf"): + return f"{word[:-1]}ves" + if word.lowered[-3:] == "eaf" and word.lowered[-4:-3] != "d": + return f"{word[:-1]}ves" + if word.lowered[-4:] in ("nife", "life", "wife"): + return f"{word[:-2]}ves" + if word.lowered[-3:] == "arf": + return f"{word[:-1]}ves" + + # HANDLE ...y + + if word.lowered[-1] == "y": + if word.lowered[-2:-1] in "aeiou" or len(word) == 1: + return f"{word}s" + + if self.classical_dict["names"]: + if word.lowered[-1] == "y" and word[0] == word[0].upper(): + return f"{word}s" + + return f"{word[:-1]}ies" + + # HANDLE ...o + + if lowered_last in pl_sb_U_o_os_complete: + return f"{word}s" + + for k, v in pl_sb_U_o_os_bysize.items(): + if word.lowered[-k:] in v: + return f"{word}s" + + if word.lowered[-2:] in ("ao", "eo", "io", "oo", "uo"): + return f"{word}s" + + if word.lowered[-1] == "o": + return f"{word}es" + + # OTHERWISE JUST ADD ...s + + return f"{word}s" + + @classmethod + def _handle_prepositional_phrase(cls, phrase, transform, sep): + """ + Given a word or phrase possibly separated by sep, parse out + the prepositional phrase and apply the transform to the word + preceding the prepositional phrase. + + Raise ValueError if the pivot is not found or if at least two + separators are not found. + + >>> engine._handle_prepositional_phrase("man-of-war", str.upper, '-') + 'MAN-of-war' + >>> engine._handle_prepositional_phrase("man of war", str.upper, ' ') + 'MAN of war' + """ + parts = phrase.split(sep) + if len(parts) < 3: + raise ValueError("Cannot handle words with fewer than two separators") + + pivot = cls._find_pivot(parts, pl_prep_list_da) + + transformed = transform(parts[pivot - 1]) or parts[pivot - 1] + return " ".join( + parts[: pivot - 1] + [sep.join([transformed, parts[pivot], ''])] + ) + " ".join(parts[(pivot + 1) :]) + + def _handle_long_compounds(self, word: Words, count: int) -> Union[str, None]: + """ + Handles the plural and singular for compound `Words` that + have three or more words, based on the given count. + + >>> engine()._handle_long_compounds(Words("pair of scissors"), 2) + 'pairs of scissors' + >>> engine()._handle_long_compounds(Words("men beyond hills"), 1) + 'man beyond hills' + """ + inflection = self._sinoun if count == 1 else self._plnoun + solutions = ( # type: ignore + " ".join( + itertools.chain( + leader, + [inflection(cand, count), prep], # type: ignore + trailer, + ) + ) + for leader, (cand, prep), trailer in windowed_complete(word.split_, 2) + if prep in pl_prep_list_da # type: ignore + ) + return next(solutions, None) + + @staticmethod + def _find_pivot(words, candidates): + pivots = ( + index for index in range(1, len(words) - 1) if words[index] in candidates + ) + try: + return next(pivots) + except StopIteration: + raise ValueError("No pivot found") from None + + def _pl_special_verb( # noqa: C901 + self, word: str, count: Optional[Union[str, int]] = None + ) -> Union[str, bool]: + if self.classical_dict["zero"] and str(count).lower() in pl_count_zero: + return False + count = self.get_count(count) + + if count == 1: + return word + + # HANDLE USER-DEFINED VERBS + + value = self.ud_match(word, self.pl_v_user_defined) + if value is not None: + return value + + # HANDLE IRREGULAR PRESENT TENSE (SIMPLE AND COMPOUND) + + try: + words = Words(word) + except IndexError: + return False # word is '' + + if words.first in plverb_irregular_pres: + return f"{plverb_irregular_pres[words.first]}{words[len(words.first) :]}" + + # HANDLE IRREGULAR FUTURE, PRETERITE AND PERFECT TENSES + + if words.first in plverb_irregular_non_pres: + return word + + # HANDLE PRESENT NEGATIONS (SIMPLE AND COMPOUND) + + if words.first.endswith("n't") and words.first[:-3] in plverb_irregular_pres: + return ( + f"{plverb_irregular_pres[words.first[:-3]]}n't" + f"{words[len(words.first) :]}" + ) + + if words.first.endswith("n't"): + return word + + # HANDLE SPECIAL CASES + + mo = PLVERB_SPECIAL_S_RE.search(word) + if mo: + return False + if WHITESPACE.search(word): + return False + + if words.lowered == "quizzes": + return "quiz" + + # HANDLE STANDARD 3RD PERSON (CHOP THE ...(e)s OFF SINGLE WORDS) + + if ( + words.lowered[-4:] in ("ches", "shes", "zzes", "sses") + or words.lowered[-3:] == "xes" + ): + return words[:-2] + + if words.lowered[-3:] == "ies" and len(words) > 3: + return words.lowered[:-3] + "y" + + if ( + words.last.lower() in pl_v_oes_oe + or words.lowered[-4:] in pl_v_oes_oe_endings_size4 + or words.lowered[-5:] in pl_v_oes_oe_endings_size5 + ): + return words[:-1] + + if words.lowered.endswith("oes") and len(words) > 3: + return words.lowered[:-2] + + mo = ENDS_WITH_S.search(words) + if mo: + return mo.group(1) + + # OTHERWISE, A REGULAR VERB (HANDLE ELSEWHERE) + + return False + + def _pl_general_verb( + self, word: str, count: Optional[Union[str, int]] = None + ) -> str: + count = self.get_count(count) + + if count == 1: + return word + + # HANDLE AMBIGUOUS PRESENT TENSES (SIMPLE AND COMPOUND) + + mo = plverb_ambiguous_pres_keys.search(word) + if mo: + return f"{plverb_ambiguous_pres[mo.group(1).lower()]}{mo.group(2)}" + + # HANDLE AMBIGUOUS PRETERITE AND PERFECT TENSES + + mo = plverb_ambiguous_non_pres.search(word) + if mo: + return word + + # OTHERWISE, 1st OR 2ND PERSON IS UNINFLECTED + + return word + + def _pl_special_adjective( + self, word: str, count: Optional[Union[str, int]] = None + ) -> Union[str, bool]: + count = self.get_count(count) + + if count == 1: + return word + + # HANDLE USER-DEFINED ADJECTIVES + + value = self.ud_match(word, self.pl_adj_user_defined) + if value is not None: + return value + + # HANDLE KNOWN CASES + + mo = pl_adj_special_keys.search(word) + if mo: + return pl_adj_special[mo.group(1).lower()] + + # HANDLE POSSESSIVES + + mo = pl_adj_poss_keys.search(word) + if mo: + return pl_adj_poss[mo.group(1).lower()] + + mo = ENDS_WITH_APOSTROPHE_S.search(word) + if mo: + pl = self.plural_noun(mo.group(1)) + trailing_s = "" if pl[-1] == "s" else "s" + return f"{pl}'{trailing_s}" + + # OTHERWISE, NO IDEA + + return False + + # @profile + def _sinoun( # noqa: C901 + self, + word: str, + count: Optional[Union[str, int]] = None, + gender: Optional[str] = None, + ) -> Union[str, bool]: + count = self.get_count(count) + + # DEFAULT TO PLURAL + + if count == 2: + return word + + # SET THE GENDER + + try: + if gender is None: + gender = self.thegender + elif gender not in singular_pronoun_genders: + raise BadGenderError + except (TypeError, IndexError) as err: + raise BadGenderError from err + + # HANDLE USER-DEFINED NOUNS + + value = self.ud_match(word, self.si_sb_user_defined) + if value is not None: + return value + + # HANDLE EMPTY WORD, SINGULAR COUNT AND UNINFLECTED PLURALS + + if word == "": + return word + + if word in si_sb_ois_oi_case: + return word[:-1] + + words = Words(word) + + if words.last.lower() in pl_sb_uninflected_complete: + if len(words.split_) >= 3: + return self._handle_long_compounds(words, count=1) or word + return word + + if word in pl_sb_uninflected_caps: + return word + + for k, v in pl_sb_uninflected_bysize.items(): + if words.lowered[-k:] in v: + return word + + if self.classical_dict["herd"] and words.last.lower() in pl_sb_uninflected_herd: + return word + + if words.last.lower() in pl_sb_C_us_us: + return word if self.classical_dict["ancient"] else False + + # HANDLE COMPOUNDS ("Governor General", "mother-in-law", "aide-de-camp", ETC.) + + mo = PL_SB_POSTFIX_ADJ_STEMS_RE.search(word) + if mo and mo.group(2) != "": + return f"{self._sinoun(mo.group(1), 1, gender=gender)}{mo.group(2)}" + + with contextlib.suppress(ValueError): + return self._handle_prepositional_phrase( + words.lowered, + functools.partial(self._sinoun, count=1, gender=gender), + ' ', + ) + + with contextlib.suppress(ValueError): + return self._handle_prepositional_phrase( + words.lowered, + functools.partial(self._sinoun, count=1, gender=gender), + '-', + ) + + # HANDLE PRONOUNS + + for k, v in si_pron_acc_keys_bysize.items(): + if words.lowered[-k:] in v: # ends with accusative pronoun + for pk, pv in pl_prep_bysize.items(): + if words.lowered[:pk] in pv: # starts with a prep + if words.lowered.split() == [ + words.lowered[:pk], + words.lowered[-k:], + ]: + # only whitespace in between + return words.lowered[:-k] + get_si_pron( + "acc", words.lowered[-k:], gender + ) + + try: + return get_si_pron("nom", words.lowered, gender) + except KeyError: + pass + + try: + return get_si_pron("acc", words.lowered, gender) + except KeyError: + pass + + # HANDLE ISOLATED IRREGULAR PLURALS + + if words.last in si_sb_irregular_caps: + llen = len(words.last) + return f"{word[:-llen]}{si_sb_irregular_caps[words.last]}" + + if words.last.lower() in si_sb_irregular: + llen = len(words.last.lower()) + return f"{word[:-llen]}{si_sb_irregular[words.last.lower()]}" + + dash_split = words.lowered.split("-") + if (" ".join(dash_split[-2:])).lower() in si_sb_irregular_compound: + llen = len( + " ".join(dash_split[-2:]) + ) # TODO: what if 2 spaces between these words? + return "{}{}".format( + word[:-llen], + si_sb_irregular_compound[(" ".join(dash_split[-2:])).lower()], + ) + + if words.lowered[-5:] == "quies": + return word[:-3] + "y" + + if words.lowered[-7:] == "persons": + return word[:-1] + if words.lowered[-6:] == "people": + return word[:-4] + "rson" + + # HANDLE FAMILIES OF IRREGULAR PLURALS + + if words.lowered[-4:] == "mans": + for k, v in si_sb_U_man_mans_bysize.items(): + if words.lowered[-k:] in v: + return word[:-1] + for k, v in si_sb_U_man_mans_caps_bysize.items(): + if word[-k:] in v: + return word[:-1] + if words.lowered[-3:] == "men": + return word[:-3] + "man" + if words.lowered[-4:] == "mice": + return word[:-4] + "mouse" + if words.lowered[-4:] == "lice": + v = si_sb_U_louse_lice_bysize.get(len(word)) + if v and words.lowered in v: + return word[:-4] + "louse" + if words.lowered[-5:] == "geese": + return word[:-5] + "goose" + if words.lowered[-5:] == "teeth": + return word[:-5] + "tooth" + if words.lowered[-4:] == "feet": + return word[:-4] + "foot" + + if words.lowered == "dice": + return "die" + + # HANDLE UNASSIMILATED IMPORTS + + if words.lowered[-4:] == "ceps": + return word + if words.lowered[-3:] == "zoa": + return word[:-1] + "on" + + for lastlet, d, unass_numend, post in ( + ("s", si_sb_U_ch_chs_bysize, -1, ""), + ("s", si_sb_U_ex_ices_bysize, -4, "ex"), + ("s", si_sb_U_ix_ices_bysize, -4, "ix"), + ("a", si_sb_U_um_a_bysize, -1, "um"), + ("i", si_sb_U_us_i_bysize, -1, "us"), + ("a", si_sb_U_on_a_bysize, -1, "on"), + ("e", si_sb_U_a_ae_bysize, -1, ""), + ): + if words.lowered[-1] == lastlet: # this test to add speed + for k, v in d.items(): + if words.lowered[-k:] in v: + return word[:unass_numend] + post + + # HANDLE INCOMPLETELY ASSIMILATED IMPORTS + + if self.classical_dict["ancient"]: + if words.lowered[-6:] == "trices": + return word[:-3] + "x" + if words.lowered[-4:] in ("eaux", "ieux"): + return word[:-1] + if words.lowered[-5:] in ("ynges", "inges", "anges") and len(word) > 6: + return word[:-3] + "x" + + for lastlet, d, class_numend, post in ( + ("a", si_sb_C_en_ina_bysize, -3, "en"), + ("s", si_sb_C_ex_ices_bysize, -4, "ex"), + ("s", si_sb_C_ix_ices_bysize, -4, "ix"), + ("a", si_sb_C_um_a_bysize, -1, "um"), + ("i", si_sb_C_us_i_bysize, -1, "us"), + ("s", pl_sb_C_us_us_bysize, None, ""), + ("e", si_sb_C_a_ae_bysize, -1, ""), + ("a", si_sb_C_a_ata_bysize, -2, ""), + ("s", si_sb_C_is_ides_bysize, -3, "s"), + ("i", si_sb_C_o_i_bysize, -1, "o"), + ("a", si_sb_C_on_a_bysize, -1, "on"), + ("m", si_sb_C_im_bysize, -2, ""), + ("i", si_sb_C_i_bysize, -1, ""), + ): + if words.lowered[-1] == lastlet: # this test to add speed + for k, v in d.items(): + if words.lowered[-k:] in v: + return word[:class_numend] + post + + # HANDLE PLURLS ENDING IN uses -> use + + if ( + words.lowered[-6:] == "houses" + or word in si_sb_uses_use_case + or words.last.lower() in si_sb_uses_use + ): + return word[:-1] + + # HANDLE PLURLS ENDING IN ies -> ie + + if word in si_sb_ies_ie_case or words.last.lower() in si_sb_ies_ie: + return word[:-1] + + # HANDLE PLURLS ENDING IN oes -> oe + + if ( + words.lowered[-5:] == "shoes" + or word in si_sb_oes_oe_case + or words.last.lower() in si_sb_oes_oe + ): + return word[:-1] + + # HANDLE SINGULAR NOUNS ENDING IN ...s OR OTHER SILIBANTS + + if word in si_sb_sses_sse_case or words.last.lower() in si_sb_sses_sse: + return word[:-1] + + if words.last.lower() in si_sb_singular_s_complete: + return word[:-2] + + for k, v in si_sb_singular_s_bysize.items(): + if words.lowered[-k:] in v: + return word[:-2] + + if words.lowered[-4:] == "eses" and word[0] == word[0].upper(): + return word[:-2] + + if words.last.lower() in si_sb_z_zes: + return word[:-2] + + if words.last.lower() in si_sb_zzes_zz: + return word[:-2] + + if words.lowered[-4:] == "zzes": + return word[:-3] + + if word in si_sb_ches_che_case or words.last.lower() in si_sb_ches_che: + return word[:-1] + + if words.lowered[-4:] in ("ches", "shes"): + return word[:-2] + + if words.last.lower() in si_sb_xes_xe: + return word[:-1] + + if words.lowered[-3:] == "xes": + return word[:-2] + + # HANDLE ...f -> ...ves + + if word in si_sb_ves_ve_case or words.last.lower() in si_sb_ves_ve: + return word[:-1] + + if words.lowered[-3:] == "ves": + if words.lowered[-5:-3] in ("el", "al", "ol"): + return word[:-3] + "f" + if words.lowered[-5:-3] == "ea" and word[-6:-5] != "d": + return word[:-3] + "f" + if words.lowered[-5:-3] in ("ni", "li", "wi"): + return word[:-3] + "fe" + if words.lowered[-5:-3] == "ar": + return word[:-3] + "f" + + # HANDLE ...y + + if words.lowered[-2:] == "ys": + if len(words.lowered) > 2 and words.lowered[-3] in "aeiou": + return word[:-1] + + if self.classical_dict["names"]: + if words.lowered[-2:] == "ys" and word[0] == word[0].upper(): + return word[:-1] + + if words.lowered[-3:] == "ies": + return word[:-3] + "y" + + # HANDLE ...o + + if words.lowered[-2:] == "os": + if words.last.lower() in si_sb_U_o_os_complete: + return word[:-1] + + for k, v in si_sb_U_o_os_bysize.items(): + if words.lowered[-k:] in v: + return word[:-1] + + if words.lowered[-3:] in ("aos", "eos", "ios", "oos", "uos"): + return word[:-1] + + if words.lowered[-3:] == "oes": + return word[:-2] + + # UNASSIMILATED IMPORTS FINAL RULE + + if word in si_sb_es_is: + return word[:-2] + "is" + + # OTHERWISE JUST REMOVE ...s + + if words.lowered[-1] == "s": + return word[:-1] + + # COULD NOT FIND SINGULAR + + return False + + # ADJECTIVES + + @typechecked + def a(self, text: Word, count: Optional[Union[int, str, Any]] = 1) -> str: + """ + Return the appropriate indefinite article followed by text. + + The indefinite article is either 'a' or 'an'. + + If count is not one, then return count followed by text + instead of 'a' or 'an'. + + Whitespace at the start and end is preserved. + + """ + mo = INDEFINITE_ARTICLE_TEST.search(text) + if mo: + word = mo.group(2) + if not word: + return text + pre = mo.group(1) + post = mo.group(3) + result = self._indef_article(word, count) + return f"{pre}{result}{post}" + return "" + + an = a + + _indef_article_cases = ( + # HANDLE ORDINAL FORMS + (A_ordinal_a, "a"), + (A_ordinal_an, "an"), + # HANDLE SPECIAL CASES + (A_explicit_an, "an"), + (SPECIAL_AN, "an"), + (SPECIAL_A, "a"), + # HANDLE ABBREVIATIONS + (A_abbrev, "an"), + (SPECIAL_ABBREV_AN, "an"), + (SPECIAL_ABBREV_A, "a"), + # HANDLE CONSONANTS + (CONSONANTS, "a"), + # HANDLE SPECIAL VOWEL-FORMS + (ARTICLE_SPECIAL_EU, "a"), + (ARTICLE_SPECIAL_ONCE, "a"), + (ARTICLE_SPECIAL_ONETIME, "a"), + (ARTICLE_SPECIAL_UNIT, "a"), + (ARTICLE_SPECIAL_UBA, "a"), + (ARTICLE_SPECIAL_UKR, "a"), + (A_explicit_a, "a"), + # HANDLE SPECIAL CAPITALS + (SPECIAL_CAPITALS, "a"), + # HANDLE VOWELS + (VOWELS, "an"), + # HANDLE y... + # (BEFORE CERTAIN CONSONANTS IMPLIES (UNNATURALIZED) "i.." SOUND) + (A_y_cons, "an"), + ) + + def _indef_article(self, word: str, count: Union[int, str, Any]) -> str: + mycount = self.get_count(count) + + if mycount != 1: + return f"{count} {word}" + + # HANDLE USER-DEFINED VARIANTS + + value = self.ud_match(word, self.A_a_user_defined) + if value is not None: + return f"{value} {word}" + + matches = ( + f'{article} {word}' + for regexen, article in self._indef_article_cases + if regexen.search(word) + ) + + # OTHERWISE, GUESS "a" + fallback = f'a {word}' + return next(matches, fallback) + + # 2. TRANSLATE ZERO-QUANTIFIED $word TO "no plural($word)" + + @typechecked + def no(self, text: Word, count: Optional[Union[int, str]] = None) -> str: + """ + If count is 0, no, zero or nil, return 'no' followed by the plural + of text. + + If count is one of: + 1, a, an, one, each, every, this, that + return count followed by text. + + Otherwise return count follow by the plural of text. + + In the return value count is always followed by a space. + + Whitespace at the start and end is preserved. + + """ + if count is None and self.persistent_count is not None: + count = self.persistent_count + + if count is None: + count = 0 + mo = PARTITION_WORD.search(text) + if mo: + pre = mo.group(1) + word = mo.group(2) + post = mo.group(3) + else: + pre = "" + word = "" + post = "" + + if str(count).lower() in pl_count_zero: + count = 'no' + return f"{pre}{count} {self.plural(word, count)}{post}" + + # PARTICIPLES + + @typechecked + def present_participle(self, word: Word) -> str: + """ + Return the present participle for word. + + word is the 3rd person singular verb. + + """ + plv = self.plural_verb(word, 2) + ans = plv + + for regexen, repl in PRESENT_PARTICIPLE_REPLACEMENTS: + ans, num = regexen.subn(repl, plv) + if num: + return f"{ans}ing" + return f"{ans}ing" + + # NUMERICAL INFLECTIONS + + @typechecked + def ordinal(self, num: Union[Number, Word]) -> str: + """ + Return the ordinal of num. + + >>> ordinal = engine().ordinal + >>> ordinal(1) + '1st' + >>> ordinal('one') + 'first' + """ + if DIGIT.match(str(num)): + if isinstance(num, (float, int)) and int(num) == num: + n = int(num) + else: + if "." in str(num): + try: + # numbers after decimal, + # so only need last one for ordinal + n = int(str(num)[-1]) + + except ValueError: # ends with '.', so need to use whole string + n = int(str(num)[:-1]) + else: + n = int(num) # type: ignore + try: + post = nth[n % 100] + except KeyError: + post = nth[n % 10] + return f"{num}{post}" + else: + return self._sub_ord(num) + + def millfn(self, ind: int = 0) -> str: + if ind > len(mill) - 1: + raise NumOutOfRangeError + return mill[ind] + + def unitfn(self, units: int, mindex: int = 0) -> str: + return f"{unit[units]}{self.millfn(mindex)}" + + def tenfn(self, tens, units, mindex=0) -> str: + if tens != 1: + tens_part = ten[tens] + if tens and units: + hyphen = "-" + else: + hyphen = "" + unit_part = unit[units] + mill_part = self.millfn(mindex) + return f"{tens_part}{hyphen}{unit_part}{mill_part}" + return f"{teen[units]}{mill[mindex]}" + + def hundfn(self, hundreds: int, tens: int, units: int, mindex: int) -> str: + if hundreds: + andword = f" {self._number_args['andword']} " if tens or units else "" + # use unit not unitfn as simpler + return ( + f"{unit[hundreds]} hundred{andword}" + f"{self.tenfn(tens, units)}{self.millfn(mindex)}, " + ) + if tens or units: + return f"{self.tenfn(tens, units)}{self.millfn(mindex)}, " + return "" + + def group1sub(self, mo: Match) -> str: + units = int(mo.group(1)) + if units == 1: + return f" {self._number_args['one']}, " + elif units: + return f"{unit[units]}, " + else: + return f" {self._number_args['zero']}, " + + def group1bsub(self, mo: Match) -> str: + units = int(mo.group(1)) + if units: + return f"{unit[units]}, " + else: + return f" {self._number_args['zero']}, " + + def group2sub(self, mo: Match) -> str: + tens = int(mo.group(1)) + units = int(mo.group(2)) + if tens: + return f"{self.tenfn(tens, units)}, " + if units: + return f" {self._number_args['zero']} {unit[units]}, " + return f" {self._number_args['zero']} {self._number_args['zero']}, " + + def group3sub(self, mo: Match) -> str: + hundreds = int(mo.group(1)) + tens = int(mo.group(2)) + units = int(mo.group(3)) + if hundreds == 1: + hunword = f" {self._number_args['one']}" + elif hundreds: + hunword = str(unit[hundreds]) + else: + hunword = f" {self._number_args['zero']}" + if tens: + tenword = self.tenfn(tens, units) + elif units: + tenword = f" {self._number_args['zero']} {unit[units]}" + else: + tenword = f" {self._number_args['zero']} {self._number_args['zero']}" + return f"{hunword} {tenword}, " + + def hundsub(self, mo: Match) -> str: + ret = self.hundfn( + int(mo.group(1)), int(mo.group(2)), int(mo.group(3)), self.mill_count + ) + self.mill_count += 1 + return ret + + def tensub(self, mo: Match) -> str: + return f"{self.tenfn(int(mo.group(1)), int(mo.group(2)), self.mill_count)}, " + + def unitsub(self, mo: Match) -> str: + return f"{self.unitfn(int(mo.group(1)), self.mill_count)}, " + + def enword(self, num: str, group: int) -> str: + # import pdb + # pdb.set_trace() + + if group == 1: + num = DIGIT_GROUP.sub(self.group1sub, num) + elif group == 2: + num = TWO_DIGITS.sub(self.group2sub, num) + num = DIGIT_GROUP.sub(self.group1bsub, num, 1) + elif group == 3: + num = THREE_DIGITS.sub(self.group3sub, num) + num = TWO_DIGITS.sub(self.group2sub, num, 1) + num = DIGIT_GROUP.sub(self.group1sub, num, 1) + elif int(num) == 0: + num = self._number_args["zero"] + elif int(num) == 1: + num = self._number_args["one"] + else: + num = num.lstrip().lstrip("0") + self.mill_count = 0 + # surely there's a better way to do the next bit + mo = THREE_DIGITS_WORD.search(num) + while mo: + num = THREE_DIGITS_WORD.sub(self.hundsub, num, 1) + mo = THREE_DIGITS_WORD.search(num) + num = TWO_DIGITS_WORD.sub(self.tensub, num, 1) + num = ONE_DIGIT_WORD.sub(self.unitsub, num, 1) + return num + + @staticmethod + def _sub_ord(val): + new = ordinal_suff.sub(lambda match: ordinal[match.group(1)], val) + return new + "th" * (new == val) + + @classmethod + def _chunk_num(cls, num, decimal, group): + if decimal: + max_split = -1 if group != 0 else 1 + chunks = num.split(".", max_split) + else: + chunks = [num] + return cls._remove_last_blank(chunks) + + @staticmethod + def _remove_last_blank(chunks): + """ + Remove the last item from chunks if it's a blank string. + + Return the resultant chunks and whether the last item was removed. + """ + removed = chunks[-1] == "" + result = chunks[:-1] if removed else chunks + return result, removed + + @staticmethod + def _get_sign(num): + return {'+': 'plus', '-': 'minus'}.get(num.lstrip()[0], '') + + @typechecked + def number_to_words( # noqa: C901 + self, + num: Union[Number, Word], + wantlist: bool = False, + group: int = 0, + comma: Union[Falsish, str] = ",", + andword: str = "and", + zero: str = "zero", + one: str = "one", + decimal: Union[Falsish, str] = "point", + threshold: Optional[int] = None, + ) -> Union[str, List[str]]: + """ + Return a number in words. + + group = 1, 2 or 3 to group numbers before turning into words + comma: define comma + + andword: + word for 'and'. Can be set to ''. + e.g. "one hundred and one" vs "one hundred one" + + zero: word for '0' + one: word for '1' + decimal: word for decimal point + threshold: numbers above threshold not turned into words + + parameters not remembered from last call. Departure from Perl version. + """ + self._number_args = {"andword": andword, "zero": zero, "one": one} + num = str(num) + + # Handle "stylistic" conversions (up to a given threshold)... + if threshold is not None and float(num) > threshold: + spnum = num.split(".", 1) + while comma: + (spnum[0], n) = FOUR_DIGIT_COMMA.subn(r"\1,\2", spnum[0]) + if n == 0: + break + try: + return f"{spnum[0]}.{spnum[1]}" + except IndexError: + return str(spnum[0]) + + if group < 0 or group > 3: + raise BadChunkingOptionError + + sign = self._get_sign(num) + + if num in nth_suff: + num = zero + + myord = num[-2:] in nth_suff + if myord: + num = num[:-2] + + chunks, finalpoint = self._chunk_num(num, decimal, group) + + loopstart = chunks[0] == "" + first: bool | None = not loopstart + + def _handle_chunk(chunk): + nonlocal first + + # remove all non numeric \D + chunk = NON_DIGIT.sub("", chunk) + if chunk == "": + chunk = "0" + + if group == 0 and not first: + chunk = self.enword(chunk, 1) + else: + chunk = self.enword(chunk, group) + + if chunk[-2:] == ", ": + chunk = chunk[:-2] + chunk = WHITESPACES_COMMA.sub(",", chunk) + + if group == 0 and first: + chunk = COMMA_WORD.sub(f" {andword} \\1", chunk) + chunk = WHITESPACES.sub(" ", chunk) + # chunk = re.sub(r"(\A\s|\s\Z)", self.blankfn, chunk) + chunk = chunk.strip() + if first: + first = None + return chunk + + chunks[loopstart:] = map(_handle_chunk, chunks[loopstart:]) + + numchunks = [] + if first != 0: + numchunks = chunks[0].split(f"{comma} ") + + if myord and numchunks: + numchunks[-1] = self._sub_ord(numchunks[-1]) + + for chunk in chunks[1:]: + numchunks.append(decimal) + numchunks.extend(chunk.split(f"{comma} ")) + + if finalpoint: + numchunks.append(decimal) + + if wantlist: + return [sign] * bool(sign) + numchunks + + signout = f"{sign} " if sign else "" + valout = ( + ', '.join(numchunks) + if group + else ''.join(self._render(numchunks, decimal, comma)) + ) + return signout + valout + + @staticmethod + def _render(chunks, decimal, comma): + first_item = chunks.pop(0) + yield first_item + first = decimal is None or not first_item.endswith(decimal) + for nc in chunks: + if nc == decimal: + first = False + elif first: + yield comma + yield f" {nc}" + + @typechecked + def join( + self, + words: Optional[Sequence[Word]], + sep: Optional[str] = None, + sep_spaced: bool = True, + final_sep: Optional[str] = None, + conj: str = "and", + conj_spaced: bool = True, + ) -> str: + """ + Join words into a list. + + e.g. join(['ant', 'bee', 'fly']) returns 'ant, bee, and fly' + + options: + conj: replacement for 'and' + sep: separator. default ',', unless ',' is in the list then ';' + final_sep: final separator. default ',', unless ',' is in the list then ';' + conj_spaced: boolean. Should conj have spaces around it + + """ + if not words: + return "" + if len(words) == 1: + return words[0] + + if conj_spaced: + if conj == "": + conj = " " + else: + conj = f" {conj} " + + if len(words) == 2: + return f"{words[0]}{conj}{words[1]}" + + if sep is None: + if "," in "".join(words): + sep = ";" + else: + sep = "," + if final_sep is None: + final_sep = sep + + final_sep = f"{final_sep}{conj}" + + if sep_spaced: + sep += " " + + return f"{sep.join(words[0:-1])}{final_sep}{words[-1]}" diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/inflect/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/inflect/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..11ac46673db517ad774bf4815b8d7266712a0b13 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/inflect/__pycache__/__init__.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:95cdee3a265244a9efe06c223421be025fac77c383ce607ed777f872bbaa2d80 +size 113085 diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/inflect/compat/__init__.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/inflect/compat/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/inflect/compat/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/inflect/compat/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9f24f49780c549dff4d200e0f6c2d1500137a29 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/inflect/compat/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/inflect/compat/__pycache__/py38.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/inflect/compat/__pycache__/py38.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b85cf161e5a3c24ddd40c5926b4614d6f2dca7c6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/inflect/compat/__pycache__/py38.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/inflect/compat/py38.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/inflect/compat/py38.py new file mode 100644 index 0000000000000000000000000000000000000000..a2d01bd98f4ae3d9236d0e6ec3b89faa9ca706ae --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/inflect/compat/py38.py @@ -0,0 +1,7 @@ +import sys + + +if sys.version_info > (3, 9): + from typing import Annotated +else: # pragma: no cover + from typing_extensions import Annotated # noqa: F401 diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/inflect/py.typed b/.venv/lib/python3.12/site-packages/setuptools/_vendor/inflect/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/LICENSE b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1bb5a44356f00884a71ceeefd24ded6caaba2418 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/LICENSE @@ -0,0 +1,17 @@ +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.12/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/METADATA b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..fe6ca5ad880ff2a77c81a94ed84ee60c742e298f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/METADATA @@ -0,0 +1,85 @@ +Metadata-Version: 2.1 +Name: jaraco.collections +Version: 5.1.0 +Summary: Collection objects similar to those in stdlib by jaraco +Author-email: "Jason R. Coombs" +Project-URL: Source, https://github.com/jaraco/jaraco.collections +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Requires-Python: >=3.8 +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: jaraco.text +Provides-Extra: check +Requires-Dist: pytest-checkdocs >=2.4 ; extra == 'check' +Requires-Dist: pytest-ruff >=0.2.1 ; (sys_platform != "cygwin") and extra == 'check' +Provides-Extra: cover +Requires-Dist: pytest-cov ; extra == 'cover' +Provides-Extra: doc +Requires-Dist: sphinx >=3.5 ; extra == 'doc' +Requires-Dist: jaraco.packaging >=9.3 ; extra == 'doc' +Requires-Dist: rst.linker >=1.9 ; extra == 'doc' +Requires-Dist: furo ; extra == 'doc' +Requires-Dist: sphinx-lint ; extra == 'doc' +Requires-Dist: jaraco.tidelift >=1.4 ; extra == 'doc' +Provides-Extra: enabler +Requires-Dist: pytest-enabler >=2.2 ; extra == 'enabler' +Provides-Extra: test +Requires-Dist: pytest !=8.1.*,>=6 ; extra == 'test' +Provides-Extra: type +Requires-Dist: pytest-mypy ; extra == 'type' + +.. image:: https://img.shields.io/pypi/v/jaraco.collections.svg + :target: https://pypi.org/project/jaraco.collections + +.. image:: https://img.shields.io/pypi/pyversions/jaraco.collections.svg + +.. image:: https://github.com/jaraco/jaraco.collections/actions/workflows/main.yml/badge.svg + :target: https://github.com/jaraco/jaraco.collections/actions?query=workflow%3A%22tests%22 + :alt: tests + +.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v2.json + :target: https://github.com/astral-sh/ruff + :alt: Ruff + +.. image:: https://readthedocs.org/projects/jaracocollections/badge/?version=latest + :target: https://jaracocollections.readthedocs.io/en/latest/?badge=latest + +.. image:: https://img.shields.io/badge/skeleton-2024-informational + :target: https://blog.jaraco.com/skeleton + +.. image:: https://tidelift.com/badges/package/pypi/jaraco.collections + :target: https://tidelift.com/subscription/pkg/pypi-jaraco.collections?utm_source=pypi-jaraco.collections&utm_medium=readme + +Models and classes to supplement the stdlib 'collections' module. + +See the docs, linked above, for descriptions and usage examples. + +Highlights include: + +- RangeMap: A mapping that accepts a range of values for keys. +- Projection: A subset over an existing mapping. +- KeyTransformingDict: Generalized mapping with keys transformed by a function. +- FoldedCaseKeyedDict: A dict whose string keys are case-insensitive. +- BijectiveMap: A map where keys map to values and values back to their keys. +- ItemsAsAttributes: A mapping mix-in exposing items as attributes. +- IdentityOverrideMap: A map whose keys map by default to themselves unless overridden. +- FrozenDict: A hashable, immutable map. +- Enumeration: An object whose keys are enumerated. +- Everything: A container that contains all things. +- Least, Greatest: Objects that are always less than or greater than any other. +- pop_all: Return all items from the mutable sequence and remove them from that sequence. +- DictStack: A stack of dicts, great for sharing scopes. +- WeightedLookup: A specialized RangeMap for selecting an item by weights. + +For Enterprise +============== + +Available as part of the Tidelift Subscription. + +This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use. + +`Learn more `_. diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/RECORD b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..48b957ec88588e68cf23d25ebf6f5f6b1cfcf43b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/RECORD @@ -0,0 +1,10 @@ +jaraco.collections-5.1.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +jaraco.collections-5.1.0.dist-info/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023 +jaraco.collections-5.1.0.dist-info/METADATA,sha256=IMUaliNsA5X1Ox9MXUWOagch5R4Wwb_3M7erp29dBtg,3933 +jaraco.collections-5.1.0.dist-info/RECORD,, +jaraco.collections-5.1.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +jaraco.collections-5.1.0.dist-info/WHEEL,sha256=Mdi9PDNwEZptOjTlUcAth7XJDFtKrHYaQMPulZeBCiQ,91 +jaraco.collections-5.1.0.dist-info/top_level.txt,sha256=0JnN3LfXH4LIRfXL-QFOGCJzQWZO3ELx4R1d_louoQM,7 +jaraco/collections/__init__.py,sha256=Pc1-SqjWm81ad1P0-GttpkwO_LWlnaY6gUq8gcKh2v0,26640 +jaraco/collections/__pycache__/__init__.cpython-312.pyc,, +jaraco/collections/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/REQUESTED b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..50e1e84e4a3fa44387f2798f8f465963bc3fc406 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (73.0.1) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/top_level.txt b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..f6205a5f19a533fd30f90a433e610325ff02f989 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/top_level.txt @@ -0,0 +1 @@ +jaraco diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.context-5.3.0.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.context-5.3.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.context-5.3.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.context-5.3.0.dist-info/LICENSE b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.context-5.3.0.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1bb5a44356f00884a71ceeefd24ded6caaba2418 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.context-5.3.0.dist-info/LICENSE @@ -0,0 +1,17 @@ +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.12/site-packages/setuptools/_vendor/jaraco.context-5.3.0.dist-info/METADATA b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.context-5.3.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..a36f7c5e82d796eadf667ad461fae3bb5cea0b4a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.context-5.3.0.dist-info/METADATA @@ -0,0 +1,75 @@ +Metadata-Version: 2.1 +Name: jaraco.context +Version: 5.3.0 +Summary: Useful decorators and context managers +Home-page: https://github.com/jaraco/jaraco.context +Author: Jason R. Coombs +Author-email: jaraco@jaraco.com +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Requires-Python: >=3.8 +License-File: LICENSE +Requires-Dist: backports.tarfile ; python_version < "3.12" +Provides-Extra: docs +Requires-Dist: sphinx >=3.5 ; extra == 'docs' +Requires-Dist: jaraco.packaging >=9.3 ; extra == 'docs' +Requires-Dist: rst.linker >=1.9 ; extra == 'docs' +Requires-Dist: furo ; extra == 'docs' +Requires-Dist: sphinx-lint ; extra == 'docs' +Requires-Dist: jaraco.tidelift >=1.4 ; extra == 'docs' +Provides-Extra: testing +Requires-Dist: pytest !=8.1.1,>=6 ; extra == 'testing' +Requires-Dist: pytest-checkdocs >=2.4 ; extra == 'testing' +Requires-Dist: pytest-cov ; extra == 'testing' +Requires-Dist: pytest-mypy ; extra == 'testing' +Requires-Dist: pytest-enabler >=2.2 ; extra == 'testing' +Requires-Dist: pytest-ruff >=0.2.1 ; extra == 'testing' +Requires-Dist: portend ; extra == 'testing' + +.. image:: https://img.shields.io/pypi/v/jaraco.context.svg + :target: https://pypi.org/project/jaraco.context + +.. image:: https://img.shields.io/pypi/pyversions/jaraco.context.svg + +.. image:: https://github.com/jaraco/jaraco.context/actions/workflows/main.yml/badge.svg + :target: https://github.com/jaraco/jaraco.context/actions?query=workflow%3A%22tests%22 + :alt: tests + +.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v2.json + :target: https://github.com/astral-sh/ruff + :alt: Ruff + +.. image:: https://readthedocs.org/projects/jaracocontext/badge/?version=latest + :target: https://jaracocontext.readthedocs.io/en/latest/?badge=latest + +.. image:: https://img.shields.io/badge/skeleton-2024-informational + :target: https://blog.jaraco.com/skeleton + +.. image:: https://tidelift.com/badges/package/pypi/jaraco.context + :target: https://tidelift.com/subscription/pkg/pypi-jaraco.context?utm_source=pypi-jaraco.context&utm_medium=readme + + +Highlights +========== + +See the docs linked from the badge above for the full details, but here are some features that may be of interest. + +- ``ExceptionTrap`` provides a general-purpose wrapper for trapping exceptions and then acting on the outcome. Includes ``passes`` and ``raises`` decorators to replace the result of a wrapped function by a boolean indicating the outcome of the exception trap. See `this keyring commit `_ for an example of it in production. +- ``suppress`` simply enables ``contextlib.suppress`` as a decorator. +- ``on_interrupt`` is a decorator used by CLI entry points to affect the handling of a ``KeyboardInterrupt``. Inspired by `Lucretiel/autocommand#18 `_. +- ``pushd`` is similar to pytest's ``monkeypatch.chdir`` or path's `default context `_, changes the current working directory for the duration of the context. +- ``tarball`` will download a tarball, extract it, change directory, yield, then clean up after. Convenient when working with web assets. +- ``null`` is there for those times when one code branch needs a context and the other doesn't; this null context provides symmetry across those branches. + + +For Enterprise +============== + +Available as part of the Tidelift Subscription. + +This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use. + +`Learn more `_. diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.context-5.3.0.dist-info/RECORD b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.context-5.3.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..09d191f214a1b83403df2ba891b21f5be94134dc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.context-5.3.0.dist-info/RECORD @@ -0,0 +1,8 @@ +jaraco.context-5.3.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +jaraco.context-5.3.0.dist-info/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023 +jaraco.context-5.3.0.dist-info/METADATA,sha256=xDtguJej0tN9iEXCUvxEJh2a7xceIRVBEakBLSr__tY,4020 +jaraco.context-5.3.0.dist-info/RECORD,, +jaraco.context-5.3.0.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92 +jaraco.context-5.3.0.dist-info/top_level.txt,sha256=0JnN3LfXH4LIRfXL-QFOGCJzQWZO3ELx4R1d_louoQM,7 +jaraco/__pycache__/context.cpython-312.pyc,, +jaraco/context.py,sha256=REoLIxDkO5MfEYowt_WoupNCRoxBS5v7YX2PbW8lIcs,9552 diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.context-5.3.0.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.context-5.3.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..bab98d675883cc7567a79df485cd7b4f015e376f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.context-5.3.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.43.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.context-5.3.0.dist-info/top_level.txt b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.context-5.3.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..f6205a5f19a533fd30f90a433e610325ff02f989 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.context-5.3.0.dist-info/top_level.txt @@ -0,0 +1 @@ +jaraco diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.functools-4.0.1.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.functools-4.0.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.functools-4.0.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.functools-4.0.1.dist-info/LICENSE b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.functools-4.0.1.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1bb5a44356f00884a71ceeefd24ded6caaba2418 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.functools-4.0.1.dist-info/LICENSE @@ -0,0 +1,17 @@ +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.12/site-packages/setuptools/_vendor/jaraco.functools-4.0.1.dist-info/METADATA b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.functools-4.0.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..c865140ab2971d078e8605fa22d8e4a27c2fecff --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.functools-4.0.1.dist-info/METADATA @@ -0,0 +1,64 @@ +Metadata-Version: 2.1 +Name: jaraco.functools +Version: 4.0.1 +Summary: Functools like those found in stdlib +Author-email: "Jason R. Coombs" +Project-URL: Homepage, https://github.com/jaraco/jaraco.functools +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Requires-Python: >=3.8 +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: more-itertools +Provides-Extra: docs +Requires-Dist: sphinx >=3.5 ; extra == 'docs' +Requires-Dist: sphinx <7.2.5 ; extra == 'docs' +Requires-Dist: jaraco.packaging >=9.3 ; extra == 'docs' +Requires-Dist: rst.linker >=1.9 ; extra == 'docs' +Requires-Dist: furo ; extra == 'docs' +Requires-Dist: sphinx-lint ; extra == 'docs' +Requires-Dist: jaraco.tidelift >=1.4 ; extra == 'docs' +Provides-Extra: testing +Requires-Dist: pytest >=6 ; extra == 'testing' +Requires-Dist: pytest-checkdocs >=2.4 ; extra == 'testing' +Requires-Dist: pytest-cov ; extra == 'testing' +Requires-Dist: pytest-enabler >=2.2 ; extra == 'testing' +Requires-Dist: pytest-ruff >=0.2.1 ; extra == 'testing' +Requires-Dist: jaraco.classes ; extra == 'testing' +Requires-Dist: pytest-mypy ; (platform_python_implementation != "PyPy") and extra == 'testing' + +.. image:: https://img.shields.io/pypi/v/jaraco.functools.svg + :target: https://pypi.org/project/jaraco.functools + +.. image:: https://img.shields.io/pypi/pyversions/jaraco.functools.svg + +.. image:: https://github.com/jaraco/jaraco.functools/actions/workflows/main.yml/badge.svg + :target: https://github.com/jaraco/jaraco.functools/actions?query=workflow%3A%22tests%22 + :alt: tests + +.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v2.json + :target: https://github.com/astral-sh/ruff + :alt: Ruff + +.. image:: https://readthedocs.org/projects/jaracofunctools/badge/?version=latest + :target: https://jaracofunctools.readthedocs.io/en/latest/?badge=latest + +.. image:: https://img.shields.io/badge/skeleton-2024-informational + :target: https://blog.jaraco.com/skeleton + +.. image:: https://tidelift.com/badges/package/pypi/jaraco.functools + :target: https://tidelift.com/subscription/pkg/pypi-jaraco.functools?utm_source=pypi-jaraco.functools&utm_medium=readme + +Additional functools in the spirit of stdlib's functools. + +For Enterprise +============== + +Available as part of the Tidelift Subscription. + +This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use. + +`Learn more `_. diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.functools-4.0.1.dist-info/RECORD b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.functools-4.0.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..ef3bc21e929e6881fc560bdef1505ed44bf838e1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.functools-4.0.1.dist-info/RECORD @@ -0,0 +1,10 @@ +jaraco.functools-4.0.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +jaraco.functools-4.0.1.dist-info/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023 +jaraco.functools-4.0.1.dist-info/METADATA,sha256=i4aUaQDX-jjdEQK5wevhegyx8JyLfin2HyvaSk3FHso,2891 +jaraco.functools-4.0.1.dist-info/RECORD,, +jaraco.functools-4.0.1.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92 +jaraco.functools-4.0.1.dist-info/top_level.txt,sha256=0JnN3LfXH4LIRfXL-QFOGCJzQWZO3ELx4R1d_louoQM,7 +jaraco/functools/__init__.py,sha256=hEAJaS2uSZRuF_JY4CxCHIYh79ZpxaPp9OiHyr9EJ1w,16642 +jaraco/functools/__init__.pyi,sha256=gk3dsgHzo5F_U74HzAvpNivFAPCkPJ1b2-yCd62dfnw,3878 +jaraco/functools/__pycache__/__init__.cpython-312.pyc,, +jaraco/functools/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.functools-4.0.1.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.functools-4.0.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..bab98d675883cc7567a79df485cd7b4f015e376f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.functools-4.0.1.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.43.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.functools-4.0.1.dist-info/top_level.txt b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.functools-4.0.1.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..f6205a5f19a533fd30f90a433e610325ff02f989 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.functools-4.0.1.dist-info/top_level.txt @@ -0,0 +1 @@ +jaraco diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/LICENSE b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1bb5a44356f00884a71ceeefd24ded6caaba2418 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/LICENSE @@ -0,0 +1,17 @@ +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.12/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/METADATA b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..0258a380f4acb6abb3b9e8d1bea70836b69a2559 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/METADATA @@ -0,0 +1,95 @@ +Metadata-Version: 2.1 +Name: jaraco.text +Version: 3.12.1 +Summary: Module for text manipulation +Author-email: "Jason R. Coombs" +Project-URL: Homepage, https://github.com/jaraco/jaraco.text +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Requires-Python: >=3.8 +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: jaraco.functools +Requires-Dist: jaraco.context >=4.1 +Requires-Dist: autocommand +Requires-Dist: inflect +Requires-Dist: more-itertools +Requires-Dist: importlib-resources ; python_version < "3.9" +Provides-Extra: doc +Requires-Dist: sphinx >=3.5 ; extra == 'doc' +Requires-Dist: jaraco.packaging >=9.3 ; extra == 'doc' +Requires-Dist: rst.linker >=1.9 ; extra == 'doc' +Requires-Dist: furo ; extra == 'doc' +Requires-Dist: sphinx-lint ; extra == 'doc' +Requires-Dist: jaraco.tidelift >=1.4 ; extra == 'doc' +Provides-Extra: test +Requires-Dist: pytest !=8.1.*,>=6 ; extra == 'test' +Requires-Dist: pytest-checkdocs >=2.4 ; extra == 'test' +Requires-Dist: pytest-cov ; extra == 'test' +Requires-Dist: pytest-mypy ; extra == 'test' +Requires-Dist: pytest-enabler >=2.2 ; extra == 'test' +Requires-Dist: pytest-ruff >=0.2.1 ; extra == 'test' +Requires-Dist: pathlib2 ; (python_version < "3.10") and extra == 'test' + +.. image:: https://img.shields.io/pypi/v/jaraco.text.svg + :target: https://pypi.org/project/jaraco.text + +.. image:: https://img.shields.io/pypi/pyversions/jaraco.text.svg + +.. image:: https://github.com/jaraco/jaraco.text/actions/workflows/main.yml/badge.svg + :target: https://github.com/jaraco/jaraco.text/actions?query=workflow%3A%22tests%22 + :alt: tests + +.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v2.json + :target: https://github.com/astral-sh/ruff + :alt: Ruff + +.. image:: https://readthedocs.org/projects/jaracotext/badge/?version=latest + :target: https://jaracotext.readthedocs.io/en/latest/?badge=latest + +.. image:: https://img.shields.io/badge/skeleton-2024-informational + :target: https://blog.jaraco.com/skeleton + +.. image:: https://tidelift.com/badges/package/pypi/jaraco.text + :target: https://tidelift.com/subscription/pkg/pypi-jaraco.text?utm_source=pypi-jaraco.text&utm_medium=readme + + +This package provides handy routines for dealing with text, such as +wrapping, substitution, trimming, stripping, prefix and suffix removal, +line continuation, indentation, comment processing, identifier processing, +values parsing, case insensitive comparison, and more. See the docs +(linked in the badge above) for the detailed documentation and examples. + +Layouts +======= + +One of the features of this package is the layouts module, which +provides a simple example of translating keystrokes from one keyboard +layout to another:: + + echo qwerty | python -m jaraco.text.to-dvorak + ',.pyf + echo "',.pyf" | python -m jaraco.text.to-qwerty + qwerty + +Newline Reporting +================= + +Need to know what newlines appear in a file? + +:: + + $ python -m jaraco.text.show-newlines README.rst + newline is '\n' + +For Enterprise +============== + +Available as part of the Tidelift Subscription. + +This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use. + +`Learn more `_. diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/RECORD b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..19e2d8402af9356a13a1335ef2b71222b0aadeec --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/RECORD @@ -0,0 +1,20 @@ +jaraco.text-3.12.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +jaraco.text-3.12.1.dist-info/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023 +jaraco.text-3.12.1.dist-info/METADATA,sha256=AzWdm6ViMfDOPoQMfLWn2zgBQSGJScyqeN29TcuWXVI,3658 +jaraco.text-3.12.1.dist-info/RECORD,, +jaraco.text-3.12.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +jaraco.text-3.12.1.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92 +jaraco.text-3.12.1.dist-info/top_level.txt,sha256=0JnN3LfXH4LIRfXL-QFOGCJzQWZO3ELx4R1d_louoQM,7 +jaraco/text/Lorem ipsum.txt,sha256=N_7c_79zxOufBY9HZ3yzMgOkNv-TkOTTio4BydrSjgs,1335 +jaraco/text/__init__.py,sha256=Y2YUqXR_orUoDaY4SkPRe6ZZhb5HUHB_Ah9RCNsVyho,16250 +jaraco/text/__pycache__/__init__.cpython-312.pyc,, +jaraco/text/__pycache__/layouts.cpython-312.pyc,, +jaraco/text/__pycache__/show-newlines.cpython-312.pyc,, +jaraco/text/__pycache__/strip-prefix.cpython-312.pyc,, +jaraco/text/__pycache__/to-dvorak.cpython-312.pyc,, +jaraco/text/__pycache__/to-qwerty.cpython-312.pyc,, +jaraco/text/layouts.py,sha256=HTC8aSTLZ7uXipyOXapRMC158juecjK6RVwitfmZ9_w,643 +jaraco/text/show-newlines.py,sha256=WGQa65e8lyhb92LUOLqVn6KaCtoeVgVws6WtSRmLk6w,904 +jaraco/text/strip-prefix.py,sha256=NfVXV8JVNo6nqcuYASfMV7_y4Eo8zMQqlCOGvAnRIVw,412 +jaraco/text/to-dvorak.py,sha256=1SNcbSsvISpXXg-LnybIHHY-RUFOQr36zcHkY1pWFqw,119 +jaraco/text/to-qwerty.py,sha256=s4UMQUnPwFn_dB5uZC27BurHOQcYondBfzIpVL5pEzw,119 diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/REQUESTED b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..bab98d675883cc7567a79df485cd7b4f015e376f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.43.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/top_level.txt b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..f6205a5f19a533fd30f90a433e610325ff02f989 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/top_level.txt @@ -0,0 +1 @@ +jaraco diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/__pycache__/context.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/__pycache__/context.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f612da530be960b7e60faf790198f9152772ef07 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/__pycache__/context.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/collections/__init__.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/collections/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0d501cf9e9cef5859f3c1bf844bc7280ce1e7aaa --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/collections/__init__.py @@ -0,0 +1,1091 @@ +from __future__ import annotations + +import collections.abc +import copy +import functools +import itertools +import operator +import random +import re +from collections.abc import Container, Iterable, Mapping +from typing import TYPE_CHECKING, Any, Callable, Dict, TypeVar, Union, overload + +import jaraco.text + +if TYPE_CHECKING: + from _operator import _SupportsComparison + + from _typeshed import SupportsKeysAndGetItem + from typing_extensions import Self + + _RangeMapKT = TypeVar('_RangeMapKT', bound=_SupportsComparison) +else: + # _SupportsComparison doesn't exist at runtime, + # but _RangeMapKT is used in RangeMap's superclass' type parameters + _RangeMapKT = TypeVar('_RangeMapKT') + +_T = TypeVar('_T') +_VT = TypeVar('_VT') + +_Matchable = Union[Callable, Container, Iterable, re.Pattern] + + +def _dispatch(obj: _Matchable) -> Callable: + # can't rely on singledispatch for Union[Container, Iterable] + # due to ambiguity + # (https://peps.python.org/pep-0443/#abstract-base-classes). + if isinstance(obj, re.Pattern): + return obj.fullmatch + # mypy issue: https://github.com/python/mypy/issues/11071 + if not isinstance(obj, Callable): # type: ignore[arg-type] + if not isinstance(obj, Container): + obj = set(obj) # type: ignore[arg-type] + obj = obj.__contains__ + return obj # type: ignore[return-value] + + +class Projection(collections.abc.Mapping): + """ + Project a set of keys over a mapping + + >>> sample = {'a': 1, 'b': 2, 'c': 3} + >>> prj = Projection(['a', 'c', 'd'], sample) + >>> dict(prj) + {'a': 1, 'c': 3} + + Projection also accepts an iterable or callable or pattern. + + >>> iter_prj = Projection(iter('acd'), sample) + >>> call_prj = Projection(lambda k: ord(k) in (97, 99, 100), sample) + >>> pat_prj = Projection(re.compile(r'[acd]'), sample) + >>> prj == iter_prj == call_prj == pat_prj + True + + Keys should only appear if they were specified and exist in the space. + Order is retained. + + >>> list(prj) + ['a', 'c'] + + Attempting to access a key not in the projection + results in a KeyError. + + >>> prj['b'] + Traceback (most recent call last): + ... + KeyError: 'b' + + Use the projection to update another dict. + + >>> target = {'a': 2, 'b': 2} + >>> target.update(prj) + >>> target + {'a': 1, 'b': 2, 'c': 3} + + Projection keeps a reference to the original dict, so + modifying the original dict may modify the Projection. + + >>> del sample['a'] + >>> dict(prj) + {'c': 3} + """ + + def __init__(self, keys: _Matchable, space: Mapping): + self._match = _dispatch(keys) + self._space = space + + def __getitem__(self, key): + if not self._match(key): + raise KeyError(key) + return self._space[key] + + def _keys_resolved(self): + return filter(self._match, self._space) + + def __iter__(self): + return self._keys_resolved() + + def __len__(self): + return len(tuple(self._keys_resolved())) + + +class Mask(Projection): + """ + The inverse of a :class:`Projection`, masking out keys. + + >>> sample = {'a': 1, 'b': 2, 'c': 3} + >>> msk = Mask(['a', 'c', 'd'], sample) + >>> dict(msk) + {'b': 2} + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + # self._match = compose(operator.not_, self._match) + self._match = lambda key, orig=self._match: not orig(key) + + +def dict_map(function, dictionary): + """ + Return a new dict with function applied to values of dictionary. + + >>> dict_map(lambda x: x+1, dict(a=1, b=2)) + {'a': 2, 'b': 3} + """ + return dict((key, function(value)) for key, value in dictionary.items()) + + +class RangeMap(Dict[_RangeMapKT, _VT]): + """ + A dictionary-like object that uses the keys as bounds for a range. + Inclusion of the value for that range is determined by the + key_match_comparator, which defaults to less-than-or-equal. + A value is returned for a key if it is the first key that matches in + the sorted list of keys. + + One may supply keyword parameters to be passed to the sort function used + to sort keys (i.e. key, reverse) as sort_params. + + Create a map that maps 1-3 -> 'a', 4-6 -> 'b' + + >>> r = RangeMap({3: 'a', 6: 'b'}) # boy, that was easy + >>> r[1], r[2], r[3], r[4], r[5], r[6] + ('a', 'a', 'a', 'b', 'b', 'b') + + Even float values should work so long as the comparison operator + supports it. + + >>> r[4.5] + 'b' + + Notice that the way rangemap is defined, it must be open-ended + on one side. + + >>> r[0] + 'a' + >>> r[-1] + 'a' + + One can close the open-end of the RangeMap by using undefined_value + + >>> r = RangeMap({0: RangeMap.undefined_value, 3: 'a', 6: 'b'}) + >>> r[0] + Traceback (most recent call last): + ... + KeyError: 0 + + One can get the first or last elements in the range by using RangeMap.Item + + >>> last_item = RangeMap.Item(-1) + >>> r[last_item] + 'b' + + .last_item is a shortcut for Item(-1) + + >>> r[RangeMap.last_item] + 'b' + + Sometimes it's useful to find the bounds for a RangeMap + + >>> r.bounds() + (0, 6) + + RangeMap supports .get(key, default) + + >>> r.get(0, 'not found') + 'not found' + + >>> r.get(7, 'not found') + 'not found' + + One often wishes to define the ranges by their left-most values, + which requires use of sort params and a key_match_comparator. + + >>> r = RangeMap({1: 'a', 4: 'b'}, + ... sort_params=dict(reverse=True), + ... key_match_comparator=operator.ge) + >>> r[1], r[2], r[3], r[4], r[5], r[6] + ('a', 'a', 'a', 'b', 'b', 'b') + + That wasn't nearly as easy as before, so an alternate constructor + is provided: + + >>> r = RangeMap.left({1: 'a', 4: 'b', 7: RangeMap.undefined_value}) + >>> r[1], r[2], r[3], r[4], r[5], r[6] + ('a', 'a', 'a', 'b', 'b', 'b') + + """ + + def __init__( + self, + source: ( + SupportsKeysAndGetItem[_RangeMapKT, _VT] | Iterable[tuple[_RangeMapKT, _VT]] + ), + sort_params: Mapping[str, Any] = {}, + key_match_comparator: Callable[[_RangeMapKT, _RangeMapKT], bool] = operator.le, + ): + dict.__init__(self, source) + self.sort_params = sort_params + self.match = key_match_comparator + + @classmethod + def left( + cls, + source: ( + SupportsKeysAndGetItem[_RangeMapKT, _VT] | Iterable[tuple[_RangeMapKT, _VT]] + ), + ) -> Self: + return cls( + source, sort_params=dict(reverse=True), key_match_comparator=operator.ge + ) + + def __getitem__(self, item: _RangeMapKT) -> _VT: + sorted_keys = sorted(self.keys(), **self.sort_params) + if isinstance(item, RangeMap.Item): + result = self.__getitem__(sorted_keys[item]) + else: + key = self._find_first_match_(sorted_keys, item) + result = dict.__getitem__(self, key) + if result is RangeMap.undefined_value: + raise KeyError(key) + return result + + @overload # type: ignore[override] # Signature simplified over dict and Mapping + def get(self, key: _RangeMapKT, default: _T) -> _VT | _T: ... + @overload + def get(self, key: _RangeMapKT, default: None = None) -> _VT | None: ... + def get(self, key: _RangeMapKT, default: _T | None = None) -> _VT | _T | None: + """ + Return the value for key if key is in the dictionary, else default. + If default is not given, it defaults to None, so that this method + never raises a KeyError. + """ + try: + return self[key] + except KeyError: + return default + + def _find_first_match_( + self, keys: Iterable[_RangeMapKT], item: _RangeMapKT + ) -> _RangeMapKT: + is_match = functools.partial(self.match, item) + matches = filter(is_match, keys) + try: + return next(matches) + except StopIteration: + raise KeyError(item) from None + + def bounds(self) -> tuple[_RangeMapKT, _RangeMapKT]: + sorted_keys = sorted(self.keys(), **self.sort_params) + return (sorted_keys[RangeMap.first_item], sorted_keys[RangeMap.last_item]) + + # some special values for the RangeMap + undefined_value = type('RangeValueUndefined', (), {})() + + class Item(int): + """RangeMap Item""" + + first_item = Item(0) + last_item = Item(-1) + + +def __identity(x): + return x + + +def sorted_items(d, key=__identity, reverse=False): + """ + Return the items of the dictionary sorted by the keys. + + >>> sample = dict(foo=20, bar=42, baz=10) + >>> tuple(sorted_items(sample)) + (('bar', 42), ('baz', 10), ('foo', 20)) + + >>> reverse_string = lambda s: ''.join(reversed(s)) + >>> tuple(sorted_items(sample, key=reverse_string)) + (('foo', 20), ('bar', 42), ('baz', 10)) + + >>> tuple(sorted_items(sample, reverse=True)) + (('foo', 20), ('baz', 10), ('bar', 42)) + """ + + # wrap the key func so it operates on the first element of each item + def pairkey_key(item): + return key(item[0]) + + return sorted(d.items(), key=pairkey_key, reverse=reverse) + + +class KeyTransformingDict(dict): + """ + A dict subclass that transforms the keys before they're used. + Subclasses may override the default transform_key to customize behavior. + """ + + @staticmethod + def transform_key(key): # pragma: nocover + return key + + def __init__(self, *args, **kargs): + super().__init__() + # build a dictionary using the default constructs + d = dict(*args, **kargs) + # build this dictionary using transformed keys. + for item in d.items(): + self.__setitem__(*item) + + def __setitem__(self, key, val): + key = self.transform_key(key) + super().__setitem__(key, val) + + def __getitem__(self, key): + key = self.transform_key(key) + return super().__getitem__(key) + + def __contains__(self, key): + key = self.transform_key(key) + return super().__contains__(key) + + def __delitem__(self, key): + key = self.transform_key(key) + return super().__delitem__(key) + + def get(self, key, *args, **kwargs): + key = self.transform_key(key) + return super().get(key, *args, **kwargs) + + def setdefault(self, key, *args, **kwargs): + key = self.transform_key(key) + return super().setdefault(key, *args, **kwargs) + + def pop(self, key, *args, **kwargs): + key = self.transform_key(key) + return super().pop(key, *args, **kwargs) + + def matching_key_for(self, key): + """ + Given a key, return the actual key stored in self that matches. + Raise KeyError if the key isn't found. + """ + try: + return next(e_key for e_key in self.keys() if e_key == key) + except StopIteration as err: + raise KeyError(key) from err + + +class FoldedCaseKeyedDict(KeyTransformingDict): + """ + A case-insensitive dictionary (keys are compared as insensitive + if they are strings). + + >>> d = FoldedCaseKeyedDict() + >>> d['heLlo'] = 'world' + >>> list(d.keys()) == ['heLlo'] + True + >>> list(d.values()) == ['world'] + True + >>> d['hello'] == 'world' + True + >>> 'hello' in d + True + >>> 'HELLO' in d + True + >>> print(repr(FoldedCaseKeyedDict({'heLlo': 'world'}))) + {'heLlo': 'world'} + >>> d = FoldedCaseKeyedDict({'heLlo': 'world'}) + >>> print(d['hello']) + world + >>> print(d['Hello']) + world + >>> list(d.keys()) + ['heLlo'] + >>> d = FoldedCaseKeyedDict({'heLlo': 'world', 'Hello': 'world'}) + >>> list(d.values()) + ['world'] + >>> key, = d.keys() + >>> key in ['heLlo', 'Hello'] + True + >>> del d['HELLO'] + >>> d + {} + + get should work + + >>> d['Sumthin'] = 'else' + >>> d.get('SUMTHIN') + 'else' + >>> d.get('OTHER', 'thing') + 'thing' + >>> del d['sumthin'] + + setdefault should also work + + >>> d['This'] = 'that' + >>> print(d.setdefault('this', 'other')) + that + >>> len(d) + 1 + >>> print(d['this']) + that + >>> print(d.setdefault('That', 'other')) + other + >>> print(d['THAT']) + other + + Make it pop! + + >>> print(d.pop('THAT')) + other + + To retrieve the key in its originally-supplied form, use matching_key_for + + >>> print(d.matching_key_for('this')) + This + + >>> d.matching_key_for('missing') + Traceback (most recent call last): + ... + KeyError: 'missing' + """ + + @staticmethod + def transform_key(key): + return jaraco.text.FoldedCase(key) + + +class DictAdapter: + """ + Provide a getitem interface for attributes of an object. + + Let's say you want to get at the string.lowercase property in a formatted + string. It's easy with DictAdapter. + + >>> import string + >>> print("lowercase is %(ascii_lowercase)s" % DictAdapter(string)) + lowercase is abcdefghijklmnopqrstuvwxyz + """ + + def __init__(self, wrapped_ob): + self.object = wrapped_ob + + def __getitem__(self, name): + return getattr(self.object, name) + + +class ItemsAsAttributes: + """ + Mix-in class to enable a mapping object to provide items as + attributes. + + >>> C = type('C', (dict, ItemsAsAttributes), dict()) + >>> i = C() + >>> i['foo'] = 'bar' + >>> i.foo + 'bar' + + Natural attribute access takes precedence + + >>> i.foo = 'henry' + >>> i.foo + 'henry' + + But as you might expect, the mapping functionality is preserved. + + >>> i['foo'] + 'bar' + + A normal attribute error should be raised if an attribute is + requested that doesn't exist. + + >>> i.missing + Traceback (most recent call last): + ... + AttributeError: 'C' object has no attribute 'missing' + + It also works on dicts that customize __getitem__ + + >>> missing_func = lambda self, key: 'missing item' + >>> C = type( + ... 'C', + ... (dict, ItemsAsAttributes), + ... dict(__missing__ = missing_func), + ... ) + >>> i = C() + >>> i.missing + 'missing item' + >>> i.foo + 'missing item' + """ + + def __getattr__(self, key): + try: + return getattr(super(), key) + except AttributeError as e: + # attempt to get the value from the mapping (return self[key]) + # but be careful not to lose the original exception context. + noval = object() + + def _safe_getitem(cont, key, missing_result): + try: + return cont[key] + except KeyError: + return missing_result + + result = _safe_getitem(self, key, noval) + if result is not noval: + return result + # raise the original exception, but use the original class + # name, not 'super'. + (message,) = e.args + message = message.replace('super', self.__class__.__name__, 1) + e.args = (message,) + raise + + +def invert_map(map): + """ + Given a dictionary, return another dictionary with keys and values + switched. If any of the values resolve to the same key, raises + a ValueError. + + >>> numbers = dict(a=1, b=2, c=3) + >>> letters = invert_map(numbers) + >>> letters[1] + 'a' + >>> numbers['d'] = 3 + >>> invert_map(numbers) + Traceback (most recent call last): + ... + ValueError: Key conflict in inverted mapping + """ + res = dict((v, k) for k, v in map.items()) + if not len(res) == len(map): + raise ValueError('Key conflict in inverted mapping') + return res + + +class IdentityOverrideMap(dict): + """ + A dictionary that by default maps each key to itself, but otherwise + acts like a normal dictionary. + + >>> d = IdentityOverrideMap() + >>> d[42] + 42 + >>> d['speed'] = 'speedo' + >>> print(d['speed']) + speedo + """ + + def __missing__(self, key): + return key + + +class DictStack(list, collections.abc.MutableMapping): + """ + A stack of dictionaries that behaves as a view on those dictionaries, + giving preference to the last. + + >>> stack = DictStack([dict(a=1, c=2), dict(b=2, a=2)]) + >>> stack['a'] + 2 + >>> stack['b'] + 2 + >>> stack['c'] + 2 + >>> len(stack) + 3 + >>> stack.push(dict(a=3)) + >>> stack['a'] + 3 + >>> stack['a'] = 4 + >>> set(stack.keys()) == set(['a', 'b', 'c']) + True + >>> set(stack.items()) == set([('a', 4), ('b', 2), ('c', 2)]) + True + >>> dict(**stack) == dict(stack) == dict(a=4, c=2, b=2) + True + >>> d = stack.pop() + >>> stack['a'] + 2 + >>> d = stack.pop() + >>> stack['a'] + 1 + >>> stack.get('b', None) + >>> 'c' in stack + True + >>> del stack['c'] + >>> dict(stack) + {'a': 1} + """ + + def __iter__(self): + dicts = list.__iter__(self) + return iter(set(itertools.chain.from_iterable(c.keys() for c in dicts))) + + def __getitem__(self, key): + for scope in reversed(tuple(list.__iter__(self))): + if key in scope: + return scope[key] + raise KeyError(key) + + push = list.append + + def __contains__(self, other): + return collections.abc.Mapping.__contains__(self, other) + + def __len__(self): + return len(list(iter(self))) + + def __setitem__(self, key, item): + last = list.__getitem__(self, -1) + return last.__setitem__(key, item) + + def __delitem__(self, key): + last = list.__getitem__(self, -1) + return last.__delitem__(key) + + # workaround for mypy confusion + def pop(self, *args, **kwargs): + return list.pop(self, *args, **kwargs) + + +class BijectiveMap(dict): + """ + A Bijective Map (two-way mapping). + + Implemented as a simple dictionary of 2x the size, mapping values back + to keys. + + Note, this implementation may be incomplete. If there's not a test for + your use case below, it's likely to fail, so please test and send pull + requests or patches for additional functionality needed. + + + >>> m = BijectiveMap() + >>> m['a'] = 'b' + >>> m == {'a': 'b', 'b': 'a'} + True + >>> print(m['b']) + a + + >>> m['c'] = 'd' + >>> len(m) + 2 + + Some weird things happen if you map an item to itself or overwrite a + single key of a pair, so it's disallowed. + + >>> m['e'] = 'e' + Traceback (most recent call last): + ValueError: Key cannot map to itself + + >>> m['d'] = 'e' + Traceback (most recent call last): + ValueError: Key/Value pairs may not overlap + + >>> m['e'] = 'd' + Traceback (most recent call last): + ValueError: Key/Value pairs may not overlap + + >>> print(m.pop('d')) + c + + >>> 'c' in m + False + + >>> m = BijectiveMap(dict(a='b')) + >>> len(m) + 1 + >>> print(m['b']) + a + + >>> m = BijectiveMap() + >>> m.update(a='b') + >>> m['b'] + 'a' + + >>> del m['b'] + >>> len(m) + 0 + >>> 'a' in m + False + """ + + def __init__(self, *args, **kwargs): + super().__init__() + self.update(*args, **kwargs) + + def __setitem__(self, item, value): + if item == value: + raise ValueError("Key cannot map to itself") + overlap = ( + item in self + and self[item] != value + or value in self + and self[value] != item + ) + if overlap: + raise ValueError("Key/Value pairs may not overlap") + super().__setitem__(item, value) + super().__setitem__(value, item) + + def __delitem__(self, item): + self.pop(item) + + def __len__(self): + return super().__len__() // 2 + + def pop(self, key, *args, **kwargs): + mirror = self[key] + super().__delitem__(mirror) + return super().pop(key, *args, **kwargs) + + def update(self, *args, **kwargs): + # build a dictionary using the default constructs + d = dict(*args, **kwargs) + # build this dictionary using transformed keys. + for item in d.items(): + self.__setitem__(*item) + + +class FrozenDict(collections.abc.Mapping, collections.abc.Hashable): + """ + An immutable mapping. + + >>> a = FrozenDict(a=1, b=2) + >>> b = FrozenDict(a=1, b=2) + >>> a == b + True + + >>> a == dict(a=1, b=2) + True + >>> dict(a=1, b=2) == a + True + >>> 'a' in a + True + >>> type(hash(a)) is type(0) + True + >>> set(iter(a)) == {'a', 'b'} + True + >>> len(a) + 2 + >>> a['a'] == a.get('a') == 1 + True + + >>> a['c'] = 3 + Traceback (most recent call last): + ... + TypeError: 'FrozenDict' object does not support item assignment + + >>> a.update(y=3) + Traceback (most recent call last): + ... + AttributeError: 'FrozenDict' object has no attribute 'update' + + Copies should compare equal + + >>> copy.copy(a) == a + True + + Copies should be the same type + + >>> isinstance(copy.copy(a), FrozenDict) + True + + FrozenDict supplies .copy(), even though + collections.abc.Mapping doesn't demand it. + + >>> a.copy() == a + True + >>> a.copy() is not a + True + """ + + __slots__ = ['__data'] + + def __new__(cls, *args, **kwargs): + self = super().__new__(cls) + self.__data = dict(*args, **kwargs) + return self + + # Container + def __contains__(self, key): + return key in self.__data + + # Hashable + def __hash__(self): + return hash(tuple(sorted(self.__data.items()))) + + # Mapping + def __iter__(self): + return iter(self.__data) + + def __len__(self): + return len(self.__data) + + def __getitem__(self, key): + return self.__data[key] + + # override get for efficiency provided by dict + def get(self, *args, **kwargs): + return self.__data.get(*args, **kwargs) + + # override eq to recognize underlying implementation + def __eq__(self, other): + if isinstance(other, FrozenDict): + other = other.__data + return self.__data.__eq__(other) + + def copy(self): + "Return a shallow copy of self" + return copy.copy(self) + + +class Enumeration(ItemsAsAttributes, BijectiveMap): + """ + A convenient way to provide enumerated values + + >>> e = Enumeration('a b c') + >>> e['a'] + 0 + + >>> e.a + 0 + + >>> e[1] + 'b' + + >>> set(e.names) == set('abc') + True + + >>> set(e.codes) == set(range(3)) + True + + >>> e.get('d') is None + True + + Codes need not start with 0 + + >>> e = Enumeration('a b c', range(1, 4)) + >>> e['a'] + 1 + + >>> e[3] + 'c' + """ + + def __init__(self, names, codes=None): + if isinstance(names, str): + names = names.split() + if codes is None: + codes = itertools.count() + super().__init__(zip(names, codes)) + + @property + def names(self): + return (key for key in self if isinstance(key, str)) + + @property + def codes(self): + return (self[name] for name in self.names) + + +class Everything: + """ + A collection "containing" every possible thing. + + >>> 'foo' in Everything() + True + + >>> import random + >>> random.randint(1, 999) in Everything() + True + + >>> random.choice([None, 'foo', 42, ('a', 'b', 'c')]) in Everything() + True + """ + + def __contains__(self, other): + return True + + +class InstrumentedDict(collections.UserDict): + """ + Instrument an existing dictionary with additional + functionality, but always reference and mutate + the original dictionary. + + >>> orig = {'a': 1, 'b': 2} + >>> inst = InstrumentedDict(orig) + >>> inst['a'] + 1 + >>> inst['c'] = 3 + >>> orig['c'] + 3 + >>> inst.keys() == orig.keys() + True + """ + + def __init__(self, data): + super().__init__() + self.data = data + + +class Least: + """ + A value that is always lesser than any other + + >>> least = Least() + >>> 3 < least + False + >>> 3 > least + True + >>> least < 3 + True + >>> least <= 3 + True + >>> least > 3 + False + >>> 'x' > least + True + >>> None > least + True + """ + + def __le__(self, other): + return True + + __lt__ = __le__ + + def __ge__(self, other): + return False + + __gt__ = __ge__ + + +class Greatest: + """ + A value that is always greater than any other + + >>> greatest = Greatest() + >>> 3 < greatest + True + >>> 3 > greatest + False + >>> greatest < 3 + False + >>> greatest > 3 + True + >>> greatest >= 3 + True + >>> 'x' > greatest + False + >>> None > greatest + False + """ + + def __ge__(self, other): + return True + + __gt__ = __ge__ + + def __le__(self, other): + return False + + __lt__ = __le__ + + +def pop_all(items): + """ + Clear items in place and return a copy of items. + + >>> items = [1, 2, 3] + >>> popped = pop_all(items) + >>> popped is items + False + >>> popped + [1, 2, 3] + >>> items + [] + """ + result, items[:] = items[:], [] + return result + + +class FreezableDefaultDict(collections.defaultdict): + """ + Often it is desirable to prevent the mutation of + a default dict after its initial construction, such + as to prevent mutation during iteration. + + >>> dd = FreezableDefaultDict(list) + >>> dd[0].append('1') + >>> dd.freeze() + >>> dd[1] + [] + >>> len(dd) + 1 + """ + + def __missing__(self, key): + return getattr(self, '_frozen', super().__missing__)(key) + + def freeze(self): + self._frozen = lambda key: self.default_factory() + + +class Accumulator: + def __init__(self, initial=0): + self.val = initial + + def __call__(self, val): + self.val += val + return self.val + + +class WeightedLookup(RangeMap): + """ + Given parameters suitable for a dict representing keys + and a weighted proportion, return a RangeMap representing + spans of values proportial to the weights: + + >>> even = WeightedLookup(a=1, b=1) + + [0, 1) -> a + [1, 2) -> b + + >>> lk = WeightedLookup(a=1, b=2) + + [0, 1) -> a + [1, 3) -> b + + >>> lk[.5] + 'a' + >>> lk[1.5] + 'b' + + Adds ``.random()`` to select a random weighted value: + + >>> lk.random() in ['a', 'b'] + True + + >>> choices = [lk.random() for x in range(1000)] + + Statistically speaking, choices should be .5 a:b + >>> ratio = choices.count('a') / choices.count('b') + >>> .4 < ratio < .6 + True + """ + + def __init__(self, *args, **kwargs): + raw = dict(*args, **kwargs) + + # allocate keys by weight + indexes = map(Accumulator(), raw.values()) + super().__init__(zip(indexes, raw.keys()), key_match_comparator=operator.lt) + + def random(self): + lower, upper = self.bounds() + selector = random.random() * upper + return self[selector] diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/collections/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/collections/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70d863052221343bc63fe5e6add6e27579a57db0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/collections/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/collections/py.typed b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/collections/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/context.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/context.py new file mode 100644 index 0000000000000000000000000000000000000000..61b27135df1fc5504622ad69875249c87947e453 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/context.py @@ -0,0 +1,361 @@ +from __future__ import annotations + +import contextlib +import functools +import operator +import os +import shutil +import subprocess +import sys +import tempfile +import urllib.request +import warnings +from typing import Iterator + + +if sys.version_info < (3, 12): + from backports import tarfile +else: + import tarfile + + +@contextlib.contextmanager +def pushd(dir: str | os.PathLike) -> Iterator[str | os.PathLike]: + """ + >>> tmp_path = getfixture('tmp_path') + >>> with pushd(tmp_path): + ... assert os.getcwd() == os.fspath(tmp_path) + >>> assert os.getcwd() != os.fspath(tmp_path) + """ + + orig = os.getcwd() + os.chdir(dir) + try: + yield dir + finally: + os.chdir(orig) + + +@contextlib.contextmanager +def tarball( + url, target_dir: str | os.PathLike | None = None +) -> Iterator[str | os.PathLike]: + """ + Get a tarball, extract it, yield, then clean up. + + >>> import urllib.request + >>> url = getfixture('tarfile_served') + >>> target = getfixture('tmp_path') / 'out' + >>> tb = tarball(url, target_dir=target) + >>> import pathlib + >>> with tb as extracted: + ... contents = pathlib.Path(extracted, 'contents.txt').read_text(encoding='utf-8') + >>> assert not os.path.exists(extracted) + """ + if target_dir is None: + target_dir = os.path.basename(url).replace('.tar.gz', '').replace('.tgz', '') + # In the tar command, use --strip-components=1 to strip the first path and + # then + # use -C to cause the files to be extracted to {target_dir}. This ensures + # that we always know where the files were extracted. + os.mkdir(target_dir) + try: + req = urllib.request.urlopen(url) + with tarfile.open(fileobj=req, mode='r|*') as tf: + tf.extractall(path=target_dir, filter=strip_first_component) + yield target_dir + finally: + shutil.rmtree(target_dir) + + +def strip_first_component( + member: tarfile.TarInfo, + path, +) -> tarfile.TarInfo: + _, member.name = member.name.split('/', 1) + return member + + +def _compose(*cmgrs): + """ + Compose any number of dependent context managers into a single one. + + The last, innermost context manager may take arbitrary arguments, but + each successive context manager should accept the result from the + previous as a single parameter. + + Like :func:`jaraco.functools.compose`, behavior works from right to + left, so the context manager should be indicated from outermost to + innermost. + + Example, to create a context manager to change to a temporary + directory: + + >>> temp_dir_as_cwd = _compose(pushd, temp_dir) + >>> with temp_dir_as_cwd() as dir: + ... assert os.path.samefile(os.getcwd(), dir) + """ + + def compose_two(inner, outer): + def composed(*args, **kwargs): + with inner(*args, **kwargs) as saved, outer(saved) as res: + yield res + + return contextlib.contextmanager(composed) + + return functools.reduce(compose_two, reversed(cmgrs)) + + +tarball_cwd = _compose(pushd, tarball) + + +@contextlib.contextmanager +def tarball_context(*args, **kwargs): + warnings.warn( + "tarball_context is deprecated. Use tarball or tarball_cwd instead.", + DeprecationWarning, + stacklevel=2, + ) + pushd_ctx = kwargs.pop('pushd', pushd) + with tarball(*args, **kwargs) as tball, pushd_ctx(tball) as dir: + yield dir + + +def infer_compression(url): + """ + Given a URL or filename, infer the compression code for tar. + + >>> infer_compression('http://foo/bar.tar.gz') + 'z' + >>> infer_compression('http://foo/bar.tgz') + 'z' + >>> infer_compression('file.bz') + 'j' + >>> infer_compression('file.xz') + 'J' + """ + warnings.warn( + "infer_compression is deprecated with no replacement", + DeprecationWarning, + stacklevel=2, + ) + # cheat and just assume it's the last two characters + compression_indicator = url[-2:] + mapping = dict(gz='z', bz='j', xz='J') + # Assume 'z' (gzip) if no match + return mapping.get(compression_indicator, 'z') + + +@contextlib.contextmanager +def temp_dir(remover=shutil.rmtree): + """ + Create a temporary directory context. Pass a custom remover + to override the removal behavior. + + >>> import pathlib + >>> with temp_dir() as the_dir: + ... assert os.path.isdir(the_dir) + ... _ = pathlib.Path(the_dir).joinpath('somefile').write_text('contents', encoding='utf-8') + >>> assert not os.path.exists(the_dir) + """ + temp_dir = tempfile.mkdtemp() + try: + yield temp_dir + finally: + remover(temp_dir) + + +@contextlib.contextmanager +def repo_context(url, branch=None, quiet=True, dest_ctx=temp_dir): + """ + Check out the repo indicated by url. + + If dest_ctx is supplied, it should be a context manager + to yield the target directory for the check out. + """ + exe = 'git' if 'git' in url else 'hg' + with dest_ctx() as repo_dir: + cmd = [exe, 'clone', url, repo_dir] + if branch: + cmd.extend(['--branch', branch]) + devnull = open(os.path.devnull, 'w') + stdout = devnull if quiet else None + subprocess.check_call(cmd, stdout=stdout) + yield repo_dir + + +def null(): + """ + A null context suitable to stand in for a meaningful context. + + >>> with null() as value: + ... assert value is None + + This context is most useful when dealing with two or more code + branches but only some need a context. Wrap the others in a null + context to provide symmetry across all options. + """ + warnings.warn( + "null is deprecated. Use contextlib.nullcontext", + DeprecationWarning, + stacklevel=2, + ) + return contextlib.nullcontext() + + +class ExceptionTrap: + """ + A context manager that will catch certain exceptions and provide an + indication they occurred. + + >>> with ExceptionTrap() as trap: + ... raise Exception() + >>> bool(trap) + True + + >>> with ExceptionTrap() as trap: + ... pass + >>> bool(trap) + False + + >>> with ExceptionTrap(ValueError) as trap: + ... raise ValueError("1 + 1 is not 3") + >>> bool(trap) + True + >>> trap.value + ValueError('1 + 1 is not 3') + >>> trap.tb + + + >>> with ExceptionTrap(ValueError) as trap: + ... raise Exception() + Traceback (most recent call last): + ... + Exception + + >>> bool(trap) + False + """ + + exc_info = None, None, None + + def __init__(self, exceptions=(Exception,)): + self.exceptions = exceptions + + def __enter__(self): + return self + + @property + def type(self): + return self.exc_info[0] + + @property + def value(self): + return self.exc_info[1] + + @property + def tb(self): + return self.exc_info[2] + + def __exit__(self, *exc_info): + type = exc_info[0] + matches = type and issubclass(type, self.exceptions) + if matches: + self.exc_info = exc_info + return matches + + def __bool__(self): + return bool(self.type) + + def raises(self, func, *, _test=bool): + """ + Wrap func and replace the result with the truth + value of the trap (True if an exception occurred). + + First, give the decorator an alias to support Python 3.8 + Syntax. + + >>> raises = ExceptionTrap(ValueError).raises + + Now decorate a function that always fails. + + >>> @raises + ... def fail(): + ... raise ValueError('failed') + >>> fail() + True + """ + + @functools.wraps(func) + def wrapper(*args, **kwargs): + with ExceptionTrap(self.exceptions) as trap: + func(*args, **kwargs) + return _test(trap) + + return wrapper + + def passes(self, func): + """ + Wrap func and replace the result with the truth + value of the trap (True if no exception). + + First, give the decorator an alias to support Python 3.8 + Syntax. + + >>> passes = ExceptionTrap(ValueError).passes + + Now decorate a function that always fails. + + >>> @passes + ... def fail(): + ... raise ValueError('failed') + + >>> fail() + False + """ + return self.raises(func, _test=operator.not_) + + +class suppress(contextlib.suppress, contextlib.ContextDecorator): + """ + A version of contextlib.suppress with decorator support. + + >>> @suppress(KeyError) + ... def key_error(): + ... {}[''] + >>> key_error() + """ + + +class on_interrupt(contextlib.ContextDecorator): + """ + Replace a KeyboardInterrupt with SystemExit(1) + + >>> def do_interrupt(): + ... raise KeyboardInterrupt() + >>> on_interrupt('error')(do_interrupt)() + Traceback (most recent call last): + ... + SystemExit: 1 + >>> on_interrupt('error', code=255)(do_interrupt)() + Traceback (most recent call last): + ... + SystemExit: 255 + >>> on_interrupt('suppress')(do_interrupt)() + >>> with __import__('pytest').raises(KeyboardInterrupt): + ... on_interrupt('ignore')(do_interrupt)() + """ + + def __init__(self, action='error', /, code=1): + self.action = action + self.code = code + + def __enter__(self): + return self + + def __exit__(self, exctype, excinst, exctb): + if exctype is not KeyboardInterrupt or self.action == 'ignore': + return + elif self.action == 'error': + raise SystemExit(self.code) from excinst + return self.action == 'suppress' diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/functools/__init__.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/functools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ca6c22fa9ba2777507118fbfa38bc29ac2d84964 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/functools/__init__.py @@ -0,0 +1,633 @@ +import collections.abc +import functools +import inspect +import itertools +import operator +import time +import types +import warnings + +import more_itertools + + +def compose(*funcs): + """ + Compose any number of unary functions into a single unary function. + + >>> import textwrap + >>> expected = str.strip(textwrap.dedent(compose.__doc__)) + >>> strip_and_dedent = compose(str.strip, textwrap.dedent) + >>> strip_and_dedent(compose.__doc__) == expected + True + + Compose also allows the innermost function to take arbitrary arguments. + + >>> round_three = lambda x: round(x, ndigits=3) + >>> f = compose(round_three, int.__truediv__) + >>> [f(3*x, x+1) for x in range(1,10)] + [1.5, 2.0, 2.25, 2.4, 2.5, 2.571, 2.625, 2.667, 2.7] + """ + + def compose_two(f1, f2): + return lambda *args, **kwargs: f1(f2(*args, **kwargs)) + + return functools.reduce(compose_two, funcs) + + +def once(func): + """ + Decorate func so it's only ever called the first time. + + This decorator can ensure that an expensive or non-idempotent function + will not be expensive on subsequent calls and is idempotent. + + >>> add_three = once(lambda a: a+3) + >>> add_three(3) + 6 + >>> add_three(9) + 6 + >>> add_three('12') + 6 + + To reset the stored value, simply clear the property ``saved_result``. + + >>> del add_three.saved_result + >>> add_three(9) + 12 + >>> add_three(8) + 12 + + Or invoke 'reset()' on it. + + >>> add_three.reset() + >>> add_three(-3) + 0 + >>> add_three(0) + 0 + """ + + @functools.wraps(func) + def wrapper(*args, **kwargs): + if not hasattr(wrapper, 'saved_result'): + wrapper.saved_result = func(*args, **kwargs) + return wrapper.saved_result + + wrapper.reset = lambda: vars(wrapper).__delitem__('saved_result') + return wrapper + + +def method_cache(method, cache_wrapper=functools.lru_cache()): + """ + Wrap lru_cache to support storing the cache data in the object instances. + + Abstracts the common paradigm where the method explicitly saves an + underscore-prefixed protected property on first call and returns that + subsequently. + + >>> class MyClass: + ... calls = 0 + ... + ... @method_cache + ... def method(self, value): + ... self.calls += 1 + ... return value + + >>> a = MyClass() + >>> a.method(3) + 3 + >>> for x in range(75): + ... res = a.method(x) + >>> a.calls + 75 + + Note that the apparent behavior will be exactly like that of lru_cache + except that the cache is stored on each instance, so values in one + instance will not flush values from another, and when an instance is + deleted, so are the cached values for that instance. + + >>> b = MyClass() + >>> for x in range(35): + ... res = b.method(x) + >>> b.calls + 35 + >>> a.method(0) + 0 + >>> a.calls + 75 + + Note that if method had been decorated with ``functools.lru_cache()``, + a.calls would have been 76 (due to the cached value of 0 having been + flushed by the 'b' instance). + + Clear the cache with ``.cache_clear()`` + + >>> a.method.cache_clear() + + Same for a method that hasn't yet been called. + + >>> c = MyClass() + >>> c.method.cache_clear() + + Another cache wrapper may be supplied: + + >>> cache = functools.lru_cache(maxsize=2) + >>> MyClass.method2 = method_cache(lambda self: 3, cache_wrapper=cache) + >>> a = MyClass() + >>> a.method2() + 3 + + Caution - do not subsequently wrap the method with another decorator, such + as ``@property``, which changes the semantics of the function. + + See also + http://code.activestate.com/recipes/577452-a-memoize-decorator-for-instance-methods/ + for another implementation and additional justification. + """ + + def wrapper(self, *args, **kwargs): + # it's the first call, replace the method with a cached, bound method + bound_method = types.MethodType(method, self) + cached_method = cache_wrapper(bound_method) + setattr(self, method.__name__, cached_method) + return cached_method(*args, **kwargs) + + # Support cache clear even before cache has been created. + wrapper.cache_clear = lambda: None + + return _special_method_cache(method, cache_wrapper) or wrapper + + +def _special_method_cache(method, cache_wrapper): + """ + Because Python treats special methods differently, it's not + possible to use instance attributes to implement the cached + methods. + + Instead, install the wrapper method under a different name + and return a simple proxy to that wrapper. + + https://github.com/jaraco/jaraco.functools/issues/5 + """ + name = method.__name__ + special_names = '__getattr__', '__getitem__' + + if name not in special_names: + return None + + wrapper_name = '__cached' + name + + def proxy(self, /, *args, **kwargs): + if wrapper_name not in vars(self): + bound = types.MethodType(method, self) + cache = cache_wrapper(bound) + setattr(self, wrapper_name, cache) + else: + cache = getattr(self, wrapper_name) + return cache(*args, **kwargs) + + return proxy + + +def apply(transform): + """ + Decorate a function with a transform function that is + invoked on results returned from the decorated function. + + >>> @apply(reversed) + ... def get_numbers(start): + ... "doc for get_numbers" + ... return range(start, start+3) + >>> list(get_numbers(4)) + [6, 5, 4] + >>> get_numbers.__doc__ + 'doc for get_numbers' + """ + + def wrap(func): + return functools.wraps(func)(compose(transform, func)) + + return wrap + + +def result_invoke(action): + r""" + Decorate a function with an action function that is + invoked on the results returned from the decorated + function (for its side effect), then return the original + result. + + >>> @result_invoke(print) + ... def add_two(a, b): + ... return a + b + >>> x = add_two(2, 3) + 5 + >>> x + 5 + """ + + def wrap(func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + result = func(*args, **kwargs) + action(result) + return result + + return wrapper + + return wrap + + +def invoke(f, /, *args, **kwargs): + """ + Call a function for its side effect after initialization. + + The benefit of using the decorator instead of simply invoking a function + after defining it is that it makes explicit the author's intent for the + function to be called immediately. Whereas if one simply calls the + function immediately, it's less obvious if that was intentional or + incidental. It also avoids repeating the name - the two actions, defining + the function and calling it immediately are modeled separately, but linked + by the decorator construct. + + The benefit of having a function construct (opposed to just invoking some + behavior inline) is to serve as a scope in which the behavior occurs. It + avoids polluting the global namespace with local variables, provides an + anchor on which to attach documentation (docstring), keeps the behavior + logically separated (instead of conceptually separated or not separated at + all), and provides potential to re-use the behavior for testing or other + purposes. + + This function is named as a pithy way to communicate, "call this function + primarily for its side effect", or "while defining this function, also + take it aside and call it". It exists because there's no Python construct + for "define and call" (nor should there be, as decorators serve this need + just fine). The behavior happens immediately and synchronously. + + >>> @invoke + ... def func(): print("called") + called + >>> func() + called + + Use functools.partial to pass parameters to the initial call + + >>> @functools.partial(invoke, name='bingo') + ... def func(name): print('called with', name) + called with bingo + """ + f(*args, **kwargs) + return f + + +class Throttler: + """Rate-limit a function (or other callable).""" + + def __init__(self, func, max_rate=float('Inf')): + if isinstance(func, Throttler): + func = func.func + self.func = func + self.max_rate = max_rate + self.reset() + + def reset(self): + self.last_called = 0 + + def __call__(self, *args, **kwargs): + self._wait() + return self.func(*args, **kwargs) + + def _wait(self): + """Ensure at least 1/max_rate seconds from last call.""" + elapsed = time.time() - self.last_called + must_wait = 1 / self.max_rate - elapsed + time.sleep(max(0, must_wait)) + self.last_called = time.time() + + def __get__(self, obj, owner=None): + return first_invoke(self._wait, functools.partial(self.func, obj)) + + +def first_invoke(func1, func2): + """ + Return a function that when invoked will invoke func1 without + any parameters (for its side effect) and then invoke func2 + with whatever parameters were passed, returning its result. + """ + + def wrapper(*args, **kwargs): + func1() + return func2(*args, **kwargs) + + return wrapper + + +method_caller = first_invoke( + lambda: warnings.warn( + '`jaraco.functools.method_caller` is deprecated, ' + 'use `operator.methodcaller` instead', + DeprecationWarning, + stacklevel=3, + ), + operator.methodcaller, +) + + +def retry_call(func, cleanup=lambda: None, retries=0, trap=()): + """ + Given a callable func, trap the indicated exceptions + for up to 'retries' times, invoking cleanup on the + exception. On the final attempt, allow any exceptions + to propagate. + """ + attempts = itertools.count() if retries == float('inf') else range(retries) + for _ in attempts: + try: + return func() + except trap: + cleanup() + + return func() + + +def retry(*r_args, **r_kwargs): + """ + Decorator wrapper for retry_call. Accepts arguments to retry_call + except func and then returns a decorator for the decorated function. + + Ex: + + >>> @retry(retries=3) + ... def my_func(a, b): + ... "this is my funk" + ... print(a, b) + >>> my_func.__doc__ + 'this is my funk' + """ + + def decorate(func): + @functools.wraps(func) + def wrapper(*f_args, **f_kwargs): + bound = functools.partial(func, *f_args, **f_kwargs) + return retry_call(bound, *r_args, **r_kwargs) + + return wrapper + + return decorate + + +def print_yielded(func): + """ + Convert a generator into a function that prints all yielded elements. + + >>> @print_yielded + ... def x(): + ... yield 3; yield None + >>> x() + 3 + None + """ + print_all = functools.partial(map, print) + print_results = compose(more_itertools.consume, print_all, func) + return functools.wraps(func)(print_results) + + +def pass_none(func): + """ + Wrap func so it's not called if its first param is None. + + >>> print_text = pass_none(print) + >>> print_text('text') + text + >>> print_text(None) + """ + + @functools.wraps(func) + def wrapper(param, /, *args, **kwargs): + if param is not None: + return func(param, *args, **kwargs) + return None + + return wrapper + + +def assign_params(func, namespace): + """ + Assign parameters from namespace where func solicits. + + >>> def func(x, y=3): + ... print(x, y) + >>> assigned = assign_params(func, dict(x=2, z=4)) + >>> assigned() + 2 3 + + The usual errors are raised if a function doesn't receive + its required parameters: + + >>> assigned = assign_params(func, dict(y=3, z=4)) + >>> assigned() + Traceback (most recent call last): + TypeError: func() ...argument... + + It even works on methods: + + >>> class Handler: + ... def meth(self, arg): + ... print(arg) + >>> assign_params(Handler().meth, dict(arg='crystal', foo='clear'))() + crystal + """ + sig = inspect.signature(func) + params = sig.parameters.keys() + call_ns = {k: namespace[k] for k in params if k in namespace} + return functools.partial(func, **call_ns) + + +def save_method_args(method): + """ + Wrap a method such that when it is called, the args and kwargs are + saved on the method. + + >>> class MyClass: + ... @save_method_args + ... def method(self, a, b): + ... print(a, b) + >>> my_ob = MyClass() + >>> my_ob.method(1, 2) + 1 2 + >>> my_ob._saved_method.args + (1, 2) + >>> my_ob._saved_method.kwargs + {} + >>> my_ob.method(a=3, b='foo') + 3 foo + >>> my_ob._saved_method.args + () + >>> my_ob._saved_method.kwargs == dict(a=3, b='foo') + True + + The arguments are stored on the instance, allowing for + different instance to save different args. + + >>> your_ob = MyClass() + >>> your_ob.method({str('x'): 3}, b=[4]) + {'x': 3} [4] + >>> your_ob._saved_method.args + ({'x': 3},) + >>> my_ob._saved_method.args + () + """ + args_and_kwargs = collections.namedtuple('args_and_kwargs', 'args kwargs') + + @functools.wraps(method) + def wrapper(self, /, *args, **kwargs): + attr_name = '_saved_' + method.__name__ + attr = args_and_kwargs(args, kwargs) + setattr(self, attr_name, attr) + return method(self, *args, **kwargs) + + return wrapper + + +def except_(*exceptions, replace=None, use=None): + """ + Replace the indicated exceptions, if raised, with the indicated + literal replacement or evaluated expression (if present). + + >>> safe_int = except_(ValueError)(int) + >>> safe_int('five') + >>> safe_int('5') + 5 + + Specify a literal replacement with ``replace``. + + >>> safe_int_r = except_(ValueError, replace=0)(int) + >>> safe_int_r('five') + 0 + + Provide an expression to ``use`` to pass through particular parameters. + + >>> safe_int_pt = except_(ValueError, use='args[0]')(int) + >>> safe_int_pt('five') + 'five' + + """ + + def decorate(func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + try: + return func(*args, **kwargs) + except exceptions: + try: + return eval(use) + except TypeError: + return replace + + return wrapper + + return decorate + + +def identity(x): + """ + Return the argument. + + >>> o = object() + >>> identity(o) is o + True + """ + return x + + +def bypass_when(check, *, _op=identity): + """ + Decorate a function to return its parameter when ``check``. + + >>> bypassed = [] # False + + >>> @bypass_when(bypassed) + ... def double(x): + ... return x * 2 + >>> double(2) + 4 + >>> bypassed[:] = [object()] # True + >>> double(2) + 2 + """ + + def decorate(func): + @functools.wraps(func) + def wrapper(param, /): + return param if _op(check) else func(param) + + return wrapper + + return decorate + + +def bypass_unless(check): + """ + Decorate a function to return its parameter unless ``check``. + + >>> enabled = [object()] # True + + >>> @bypass_unless(enabled) + ... def double(x): + ... return x * 2 + >>> double(2) + 4 + >>> del enabled[:] # False + >>> double(2) + 2 + """ + return bypass_when(check, _op=operator.not_) + + +@functools.singledispatch +def _splat_inner(args, func): + """Splat args to func.""" + return func(*args) + + +@_splat_inner.register +def _(args: collections.abc.Mapping, func): + """Splat kargs to func as kwargs.""" + return func(**args) + + +def splat(func): + """ + Wrap func to expect its parameters to be passed positionally in a tuple. + + Has a similar effect to that of ``itertools.starmap`` over + simple ``map``. + + >>> pairs = [(-1, 1), (0, 2)] + >>> more_itertools.consume(itertools.starmap(print, pairs)) + -1 1 + 0 2 + >>> more_itertools.consume(map(splat(print), pairs)) + -1 1 + 0 2 + + The approach generalizes to other iterators that don't have a "star" + equivalent, such as a "starfilter". + + >>> list(filter(splat(operator.add), pairs)) + [(0, 2)] + + Splat also accepts a mapping argument. + + >>> def is_nice(msg, code): + ... return "smile" in msg or code == 0 + >>> msgs = [ + ... dict(msg='smile!', code=20), + ... dict(msg='error :(', code=1), + ... dict(msg='unknown', code=0), + ... ] + >>> for msg in filter(splat(is_nice), msgs): + ... print(msg) + {'msg': 'smile!', 'code': 20} + {'msg': 'unknown', 'code': 0} + """ + return functools.wraps(func)(functools.partial(_splat_inner, func=func)) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/functools/__init__.pyi b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/functools/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..19191bf93eea22a55c8d47a57ec24de370caca27 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/functools/__init__.pyi @@ -0,0 +1,125 @@ +from collections.abc import Callable, Hashable, Iterator +from functools import partial +from operator import methodcaller +import sys +from typing import ( + Any, + Generic, + Protocol, + TypeVar, + overload, +) + +if sys.version_info >= (3, 10): + from typing import Concatenate, ParamSpec +else: + from typing_extensions import Concatenate, ParamSpec + +_P = ParamSpec('_P') +_R = TypeVar('_R') +_T = TypeVar('_T') +_R1 = TypeVar('_R1') +_R2 = TypeVar('_R2') +_V = TypeVar('_V') +_S = TypeVar('_S') +_R_co = TypeVar('_R_co', covariant=True) + +class _OnceCallable(Protocol[_P, _R]): + saved_result: _R + reset: Callable[[], None] + def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _R: ... + +class _ProxyMethodCacheWrapper(Protocol[_R_co]): + cache_clear: Callable[[], None] + def __call__(self, *args: Hashable, **kwargs: Hashable) -> _R_co: ... + +class _MethodCacheWrapper(Protocol[_R_co]): + def cache_clear(self) -> None: ... + def __call__(self, *args: Hashable, **kwargs: Hashable) -> _R_co: ... + +# `compose()` overloads below will cover most use cases. + +@overload +def compose( + __func1: Callable[[_R], _T], + __func2: Callable[_P, _R], + /, +) -> Callable[_P, _T]: ... +@overload +def compose( + __func1: Callable[[_R], _T], + __func2: Callable[[_R1], _R], + __func3: Callable[_P, _R1], + /, +) -> Callable[_P, _T]: ... +@overload +def compose( + __func1: Callable[[_R], _T], + __func2: Callable[[_R2], _R], + __func3: Callable[[_R1], _R2], + __func4: Callable[_P, _R1], + /, +) -> Callable[_P, _T]: ... +def once(func: Callable[_P, _R]) -> _OnceCallable[_P, _R]: ... +def method_cache( + method: Callable[..., _R], + cache_wrapper: Callable[[Callable[..., _R]], _MethodCacheWrapper[_R]] = ..., +) -> _MethodCacheWrapper[_R] | _ProxyMethodCacheWrapper[_R]: ... +def apply( + transform: Callable[[_R], _T] +) -> Callable[[Callable[_P, _R]], Callable[_P, _T]]: ... +def result_invoke( + action: Callable[[_R], Any] +) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: ... +def invoke( + f: Callable[_P, _R], /, *args: _P.args, **kwargs: _P.kwargs +) -> Callable[_P, _R]: ... + +class Throttler(Generic[_R]): + last_called: float + func: Callable[..., _R] + max_rate: float + def __init__( + self, func: Callable[..., _R] | Throttler[_R], max_rate: float = ... + ) -> None: ... + def reset(self) -> None: ... + def __call__(self, *args: Any, **kwargs: Any) -> _R: ... + def __get__(self, obj: Any, owner: type[Any] | None = ...) -> Callable[..., _R]: ... + +def first_invoke( + func1: Callable[..., Any], func2: Callable[_P, _R] +) -> Callable[_P, _R]: ... + +method_caller: Callable[..., methodcaller] + +def retry_call( + func: Callable[..., _R], + cleanup: Callable[..., None] = ..., + retries: int | float = ..., + trap: type[BaseException] | tuple[type[BaseException], ...] = ..., +) -> _R: ... +def retry( + cleanup: Callable[..., None] = ..., + retries: int | float = ..., + trap: type[BaseException] | tuple[type[BaseException], ...] = ..., +) -> Callable[[Callable[..., _R]], Callable[..., _R]]: ... +def print_yielded(func: Callable[_P, Iterator[Any]]) -> Callable[_P, None]: ... +def pass_none( + func: Callable[Concatenate[_T, _P], _R] +) -> Callable[Concatenate[_T, _P], _R]: ... +def assign_params( + func: Callable[..., _R], namespace: dict[str, Any] +) -> partial[_R]: ... +def save_method_args( + method: Callable[Concatenate[_S, _P], _R] +) -> Callable[Concatenate[_S, _P], _R]: ... +def except_( + *exceptions: type[BaseException], replace: Any = ..., use: Any = ... +) -> Callable[[Callable[_P, Any]], Callable[_P, Any]]: ... +def identity(x: _T) -> _T: ... +def bypass_when( + check: _V, *, _op: Callable[[_V], Any] = ... +) -> Callable[[Callable[[_T], _R]], Callable[[_T], _T | _R]]: ... +def bypass_unless( + check: Any, +) -> Callable[[Callable[[_T], _R]], Callable[[_T], _T | _R]]: ... diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/functools/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/functools/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40ca007ed44a94e302beec6a3ca68572f381b82e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/functools/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/functools/py.typed b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/functools/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/Lorem ipsum.txt b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/Lorem ipsum.txt new file mode 100644 index 0000000000000000000000000000000000000000..986f944b60b9900c22464a0c027d713854cc204e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/Lorem ipsum.txt @@ -0,0 +1,2 @@ +Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. +Curabitur pretium tincidunt lacus. Nulla gravida orci a odio. Nullam varius, turpis et commodo pharetra, est eros bibendum elit, nec luctus magna felis sollicitudin mauris. Integer in mauris eu nibh euismod gravida. Duis ac tellus et risus vulputate vehicula. Donec lobortis risus a elit. Etiam tempor. Ut ullamcorper, ligula eu tempor congue, eros est euismod turpis, id tincidunt sapien risus a quam. Maecenas fermentum consequat mi. Donec fermentum. Pellentesque malesuada nulla a mi. Duis sapien sem, aliquet nec, commodo eget, consequat quis, neque. Aliquam faucibus, elit ut dictum aliquet, felis nisl adipiscing sapien, sed malesuada diam lacus eget erat. Cras mollis scelerisque nunc. Nullam arcu. Aliquam consequat. Curabitur augue lorem, dapibus quis, laoreet et, pretium ac, nisi. Aenean magna nisl, mollis quis, molestie eu, feugiat in, orci. In hac habitasse platea dictumst. diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/__init__.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0fabd0c3f036d47f2cd9b2a66828ba33a00ab7b3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/__init__.py @@ -0,0 +1,624 @@ +import re +import itertools +import textwrap +import functools + +try: + from importlib.resources import files # type: ignore +except ImportError: # pragma: nocover + from importlib_resources import files # type: ignore + +from jaraco.functools import compose, method_cache +from jaraco.context import ExceptionTrap + + +def substitution(old, new): + """ + Return a function that will perform a substitution on a string + """ + return lambda s: s.replace(old, new) + + +def multi_substitution(*substitutions): + """ + Take a sequence of pairs specifying substitutions, and create + a function that performs those substitutions. + + >>> multi_substitution(('foo', 'bar'), ('bar', 'baz'))('foo') + 'baz' + """ + substitutions = itertools.starmap(substitution, substitutions) + # compose function applies last function first, so reverse the + # substitutions to get the expected order. + substitutions = reversed(tuple(substitutions)) + return compose(*substitutions) + + +class FoldedCase(str): + """ + A case insensitive string class; behaves just like str + except compares equal when the only variation is case. + + >>> s = FoldedCase('hello world') + + >>> s == 'Hello World' + True + + >>> 'Hello World' == s + True + + >>> s != 'Hello World' + False + + >>> s.index('O') + 4 + + >>> s.split('O') + ['hell', ' w', 'rld'] + + >>> sorted(map(FoldedCase, ['GAMMA', 'alpha', 'Beta'])) + ['alpha', 'Beta', 'GAMMA'] + + Sequence membership is straightforward. + + >>> "Hello World" in [s] + True + >>> s in ["Hello World"] + True + + Allows testing for set inclusion, but candidate and elements + must both be folded. + + >>> FoldedCase("Hello World") in {s} + True + >>> s in {FoldedCase("Hello World")} + True + + String inclusion works as long as the FoldedCase object + is on the right. + + >>> "hello" in FoldedCase("Hello World") + True + + But not if the FoldedCase object is on the left: + + >>> FoldedCase('hello') in 'Hello World' + False + + In that case, use ``in_``: + + >>> FoldedCase('hello').in_('Hello World') + True + + >>> FoldedCase('hello') > FoldedCase('Hello') + False + + >>> FoldedCase('ß') == FoldedCase('ss') + True + """ + + def __lt__(self, other): + return self.casefold() < other.casefold() + + def __gt__(self, other): + return self.casefold() > other.casefold() + + def __eq__(self, other): + return self.casefold() == other.casefold() + + def __ne__(self, other): + return self.casefold() != other.casefold() + + def __hash__(self): + return hash(self.casefold()) + + def __contains__(self, other): + return super().casefold().__contains__(other.casefold()) + + def in_(self, other): + "Does self appear in other?" + return self in FoldedCase(other) + + # cache casefold since it's likely to be called frequently. + @method_cache + def casefold(self): + return super().casefold() + + def index(self, sub): + return self.casefold().index(sub.casefold()) + + def split(self, splitter=' ', maxsplit=0): + pattern = re.compile(re.escape(splitter), re.I) + return pattern.split(self, maxsplit) + + +# Python 3.8 compatibility +_unicode_trap = ExceptionTrap(UnicodeDecodeError) + + +@_unicode_trap.passes +def is_decodable(value): + r""" + Return True if the supplied value is decodable (using the default + encoding). + + >>> is_decodable(b'\xff') + False + >>> is_decodable(b'\x32') + True + """ + value.decode() + + +def is_binary(value): + r""" + Return True if the value appears to be binary (that is, it's a byte + string and isn't decodable). + + >>> is_binary(b'\xff') + True + >>> is_binary('\xff') + False + """ + return isinstance(value, bytes) and not is_decodable(value) + + +def trim(s): + r""" + Trim something like a docstring to remove the whitespace that + is common due to indentation and formatting. + + >>> trim("\n\tfoo = bar\n\t\tbar = baz\n") + 'foo = bar\n\tbar = baz' + """ + return textwrap.dedent(s).strip() + + +def wrap(s): + """ + Wrap lines of text, retaining existing newlines as + paragraph markers. + + >>> print(wrap(lorem_ipsum)) + Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do + eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad + minim veniam, quis nostrud exercitation ullamco laboris nisi ut + aliquip ex ea commodo consequat. Duis aute irure dolor in + reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla + pariatur. Excepteur sint occaecat cupidatat non proident, sunt in + culpa qui officia deserunt mollit anim id est laborum. + + Curabitur pretium tincidunt lacus. Nulla gravida orci a odio. Nullam + varius, turpis et commodo pharetra, est eros bibendum elit, nec luctus + magna felis sollicitudin mauris. Integer in mauris eu nibh euismod + gravida. Duis ac tellus et risus vulputate vehicula. Donec lobortis + risus a elit. Etiam tempor. Ut ullamcorper, ligula eu tempor congue, + eros est euismod turpis, id tincidunt sapien risus a quam. Maecenas + fermentum consequat mi. Donec fermentum. Pellentesque malesuada nulla + a mi. Duis sapien sem, aliquet nec, commodo eget, consequat quis, + neque. Aliquam faucibus, elit ut dictum aliquet, felis nisl adipiscing + sapien, sed malesuada diam lacus eget erat. Cras mollis scelerisque + nunc. Nullam arcu. Aliquam consequat. Curabitur augue lorem, dapibus + quis, laoreet et, pretium ac, nisi. Aenean magna nisl, mollis quis, + molestie eu, feugiat in, orci. In hac habitasse platea dictumst. + """ + paragraphs = s.splitlines() + wrapped = ('\n'.join(textwrap.wrap(para)) for para in paragraphs) + return '\n\n'.join(wrapped) + + +def unwrap(s): + r""" + Given a multi-line string, return an unwrapped version. + + >>> wrapped = wrap(lorem_ipsum) + >>> wrapped.count('\n') + 20 + >>> unwrapped = unwrap(wrapped) + >>> unwrapped.count('\n') + 1 + >>> print(unwrapped) + Lorem ipsum dolor sit amet, consectetur adipiscing ... + Curabitur pretium tincidunt lacus. Nulla gravida orci ... + + """ + paragraphs = re.split(r'\n\n+', s) + cleaned = (para.replace('\n', ' ') for para in paragraphs) + return '\n'.join(cleaned) + + +lorem_ipsum: str = ( + files(__name__).joinpath('Lorem ipsum.txt').read_text(encoding='utf-8') +) + + +class Splitter: + """object that will split a string with the given arguments for each call + + >>> s = Splitter(',') + >>> s('hello, world, this is your, master calling') + ['hello', ' world', ' this is your', ' master calling'] + """ + + def __init__(self, *args): + self.args = args + + def __call__(self, s): + return s.split(*self.args) + + +def indent(string, prefix=' ' * 4): + """ + >>> indent('foo') + ' foo' + """ + return prefix + string + + +class WordSet(tuple): + """ + Given an identifier, return the words that identifier represents, + whether in camel case, underscore-separated, etc. + + >>> WordSet.parse("camelCase") + ('camel', 'Case') + + >>> WordSet.parse("under_sep") + ('under', 'sep') + + Acronyms should be retained + + >>> WordSet.parse("firstSNL") + ('first', 'SNL') + + >>> WordSet.parse("you_and_I") + ('you', 'and', 'I') + + >>> WordSet.parse("A simple test") + ('A', 'simple', 'test') + + Multiple caps should not interfere with the first cap of another word. + + >>> WordSet.parse("myABCClass") + ('my', 'ABC', 'Class') + + The result is a WordSet, providing access to other forms. + + >>> WordSet.parse("myABCClass").underscore_separated() + 'my_ABC_Class' + + >>> WordSet.parse('a-command').camel_case() + 'ACommand' + + >>> WordSet.parse('someIdentifier').lowered().space_separated() + 'some identifier' + + Slices of the result should return another WordSet. + + >>> WordSet.parse('taken-out-of-context')[1:].underscore_separated() + 'out_of_context' + + >>> WordSet.from_class_name(WordSet()).lowered().space_separated() + 'word set' + + >>> example = WordSet.parse('figured it out') + >>> example.headless_camel_case() + 'figuredItOut' + >>> example.dash_separated() + 'figured-it-out' + + """ + + _pattern = re.compile('([A-Z]?[a-z]+)|([A-Z]+(?![a-z]))') + + def capitalized(self): + return WordSet(word.capitalize() for word in self) + + def lowered(self): + return WordSet(word.lower() for word in self) + + def camel_case(self): + return ''.join(self.capitalized()) + + def headless_camel_case(self): + words = iter(self) + first = next(words).lower() + new_words = itertools.chain((first,), WordSet(words).camel_case()) + return ''.join(new_words) + + def underscore_separated(self): + return '_'.join(self) + + def dash_separated(self): + return '-'.join(self) + + def space_separated(self): + return ' '.join(self) + + def trim_right(self, item): + """ + Remove the item from the end of the set. + + >>> WordSet.parse('foo bar').trim_right('foo') + ('foo', 'bar') + >>> WordSet.parse('foo bar').trim_right('bar') + ('foo',) + >>> WordSet.parse('').trim_right('bar') + () + """ + return self[:-1] if self and self[-1] == item else self + + def trim_left(self, item): + """ + Remove the item from the beginning of the set. + + >>> WordSet.parse('foo bar').trim_left('foo') + ('bar',) + >>> WordSet.parse('foo bar').trim_left('bar') + ('foo', 'bar') + >>> WordSet.parse('').trim_left('bar') + () + """ + return self[1:] if self and self[0] == item else self + + def trim(self, item): + """ + >>> WordSet.parse('foo bar').trim('foo') + ('bar',) + """ + return self.trim_left(item).trim_right(item) + + def __getitem__(self, item): + result = super().__getitem__(item) + if isinstance(item, slice): + result = WordSet(result) + return result + + @classmethod + def parse(cls, identifier): + matches = cls._pattern.finditer(identifier) + return WordSet(match.group(0) for match in matches) + + @classmethod + def from_class_name(cls, subject): + return cls.parse(subject.__class__.__name__) + + +# for backward compatibility +words = WordSet.parse + + +def simple_html_strip(s): + r""" + Remove HTML from the string `s`. + + >>> str(simple_html_strip('')) + '' + + >>> print(simple_html_strip('A stormy day in paradise')) + A stormy day in paradise + + >>> print(simple_html_strip('Somebody tell the truth.')) + Somebody tell the truth. + + >>> print(simple_html_strip('What about
\nmultiple lines?')) + What about + multiple lines? + """ + html_stripper = re.compile('()|(<[^>]*>)|([^<]+)', re.DOTALL) + texts = (match.group(3) or '' for match in html_stripper.finditer(s)) + return ''.join(texts) + + +class SeparatedValues(str): + """ + A string separated by a separator. Overrides __iter__ for getting + the values. + + >>> list(SeparatedValues('a,b,c')) + ['a', 'b', 'c'] + + Whitespace is stripped and empty values are discarded. + + >>> list(SeparatedValues(' a, b , c, ')) + ['a', 'b', 'c'] + """ + + separator = ',' + + def __iter__(self): + parts = self.split(self.separator) + return filter(None, (part.strip() for part in parts)) + + +class Stripper: + r""" + Given a series of lines, find the common prefix and strip it from them. + + >>> lines = [ + ... 'abcdefg\n', + ... 'abc\n', + ... 'abcde\n', + ... ] + >>> res = Stripper.strip_prefix(lines) + >>> res.prefix + 'abc' + >>> list(res.lines) + ['defg\n', '\n', 'de\n'] + + If no prefix is common, nothing should be stripped. + + >>> lines = [ + ... 'abcd\n', + ... '1234\n', + ... ] + >>> res = Stripper.strip_prefix(lines) + >>> res.prefix = '' + >>> list(res.lines) + ['abcd\n', '1234\n'] + """ + + def __init__(self, prefix, lines): + self.prefix = prefix + self.lines = map(self, lines) + + @classmethod + def strip_prefix(cls, lines): + prefix_lines, lines = itertools.tee(lines) + prefix = functools.reduce(cls.common_prefix, prefix_lines) + return cls(prefix, lines) + + def __call__(self, line): + if not self.prefix: + return line + null, prefix, rest = line.partition(self.prefix) + return rest + + @staticmethod + def common_prefix(s1, s2): + """ + Return the common prefix of two lines. + """ + index = min(len(s1), len(s2)) + while s1[:index] != s2[:index]: + index -= 1 + return s1[:index] + + +def remove_prefix(text, prefix): + """ + Remove the prefix from the text if it exists. + + >>> remove_prefix('underwhelming performance', 'underwhelming ') + 'performance' + + >>> remove_prefix('something special', 'sample') + 'something special' + """ + null, prefix, rest = text.rpartition(prefix) + return rest + + +def remove_suffix(text, suffix): + """ + Remove the suffix from the text if it exists. + + >>> remove_suffix('name.git', '.git') + 'name' + + >>> remove_suffix('something special', 'sample') + 'something special' + """ + rest, suffix, null = text.partition(suffix) + return rest + + +def normalize_newlines(text): + r""" + Replace alternate newlines with the canonical newline. + + >>> normalize_newlines('Lorem Ipsum\u2029') + 'Lorem Ipsum\n' + >>> normalize_newlines('Lorem Ipsum\r\n') + 'Lorem Ipsum\n' + >>> normalize_newlines('Lorem Ipsum\x85') + 'Lorem Ipsum\n' + """ + newlines = ['\r\n', '\r', '\n', '\u0085', '\u2028', '\u2029'] + pattern = '|'.join(newlines) + return re.sub(pattern, '\n', text) + + +def _nonblank(str): + return str and not str.startswith('#') + + +@functools.singledispatch +def yield_lines(iterable): + r""" + Yield valid lines of a string or iterable. + + >>> list(yield_lines('')) + [] + >>> list(yield_lines(['foo', 'bar'])) + ['foo', 'bar'] + >>> list(yield_lines('foo\nbar')) + ['foo', 'bar'] + >>> list(yield_lines('\nfoo\n#bar\nbaz #comment')) + ['foo', 'baz #comment'] + >>> list(yield_lines(['foo\nbar', 'baz', 'bing\n\n\n'])) + ['foo', 'bar', 'baz', 'bing'] + """ + return itertools.chain.from_iterable(map(yield_lines, iterable)) + + +@yield_lines.register(str) +def _(text): + return filter(_nonblank, map(str.strip, text.splitlines())) + + +def drop_comment(line): + """ + Drop comments. + + >>> drop_comment('foo # bar') + 'foo' + + A hash without a space may be in a URL. + + >>> drop_comment('http://example.com/foo#bar') + 'http://example.com/foo#bar' + """ + return line.partition(' #')[0] + + +def join_continuation(lines): + r""" + Join lines continued by a trailing backslash. + + >>> list(join_continuation(['foo \\', 'bar', 'baz'])) + ['foobar', 'baz'] + >>> list(join_continuation(['foo \\', 'bar', 'baz'])) + ['foobar', 'baz'] + >>> list(join_continuation(['foo \\', 'bar \\', 'baz'])) + ['foobarbaz'] + + Not sure why, but... + The character preceding the backslash is also elided. + + >>> list(join_continuation(['goo\\', 'dly'])) + ['godly'] + + A terrible idea, but... + If no line is available to continue, suppress the lines. + + >>> list(join_continuation(['foo', 'bar\\', 'baz\\'])) + ['foo'] + """ + lines = iter(lines) + for item in lines: + while item.endswith('\\'): + try: + item = item[:-2].strip() + next(lines) + except StopIteration: + return + yield item + + +def read_newlines(filename, limit=1024): + r""" + >>> tmp_path = getfixture('tmp_path') + >>> filename = tmp_path / 'out.txt' + >>> _ = filename.write_text('foo\n', newline='', encoding='utf-8') + >>> read_newlines(filename) + '\n' + >>> _ = filename.write_text('foo\r\n', newline='', encoding='utf-8') + >>> read_newlines(filename) + '\r\n' + >>> _ = filename.write_text('foo\r\nbar\nbing\r', newline='', encoding='utf-8') + >>> read_newlines(filename) + ('\r', '\n', '\r\n') + """ + with open(filename, encoding='utf-8') as fp: + fp.read(limit) + return fp.newlines diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..162e7de4afbac3062517e53afd6568a2587e5120 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/__pycache__/layouts.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/__pycache__/layouts.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..497ff5f95fe2419d5b4a597ea6c2c55e0388e1ea Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/__pycache__/layouts.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/__pycache__/show-newlines.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/__pycache__/show-newlines.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a8bc49a976cde259e5b4d68b003d0c9ca410a96 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/__pycache__/show-newlines.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/__pycache__/strip-prefix.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/__pycache__/strip-prefix.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..effe10a65dff45bebe1d567938fb811d16f6feeb Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/__pycache__/strip-prefix.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/__pycache__/to-dvorak.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/__pycache__/to-dvorak.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57aff1cc3d1d285d4652cfce4275a611fc6b5696 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/__pycache__/to-dvorak.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/__pycache__/to-qwerty.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/__pycache__/to-qwerty.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d136f60b8ccc095e7309456199ba368b7560ee5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/__pycache__/to-qwerty.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/layouts.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/layouts.py new file mode 100644 index 0000000000000000000000000000000000000000..9636f0f7b53cb4d1ea5842e1eb62c998ddb91070 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/layouts.py @@ -0,0 +1,25 @@ +qwerty = "-=qwertyuiop[]asdfghjkl;'zxcvbnm,./_+QWERTYUIOP{}ASDFGHJKL:\"ZXCVBNM<>?" +dvorak = "[]',.pyfgcrl/=aoeuidhtns-;qjkxbmwvz{}\"<>PYFGCRL?+AOEUIDHTNS_:QJKXBMWVZ" + + +to_dvorak = str.maketrans(qwerty, dvorak) +to_qwerty = str.maketrans(dvorak, qwerty) + + +def translate(input, translation): + """ + >>> translate('dvorak', to_dvorak) + 'ekrpat' + >>> translate('qwerty', to_qwerty) + 'x,dokt' + """ + return input.translate(translation) + + +def _translate_stream(stream, translation): + """ + >>> import io + >>> _translate_stream(io.StringIO('foo'), to_dvorak) + urr + """ + print(translate(stream.read(), translation)) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/show-newlines.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/show-newlines.py new file mode 100644 index 0000000000000000000000000000000000000000..e11d1ba4280e9a882ca788c27f56034e90987004 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/show-newlines.py @@ -0,0 +1,33 @@ +import autocommand +import inflect + +from more_itertools import always_iterable + +import jaraco.text + + +def report_newlines(filename): + r""" + Report the newlines in the indicated file. + + >>> tmp_path = getfixture('tmp_path') + >>> filename = tmp_path / 'out.txt' + >>> _ = filename.write_text('foo\nbar\n', newline='', encoding='utf-8') + >>> report_newlines(filename) + newline is '\n' + >>> filename = tmp_path / 'out.txt' + >>> _ = filename.write_text('foo\nbar\r\n', newline='', encoding='utf-8') + >>> report_newlines(filename) + newlines are ('\n', '\r\n') + """ + newlines = jaraco.text.read_newlines(filename) + count = len(tuple(always_iterable(newlines))) + engine = inflect.engine() + print( + engine.plural_noun("newline", count), + engine.plural_verb("is", count), + repr(newlines), + ) + + +autocommand.autocommand(__name__)(report_newlines) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/strip-prefix.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/strip-prefix.py new file mode 100644 index 0000000000000000000000000000000000000000..761717a9b9e1f837eeacf0e888822f6fad881361 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/strip-prefix.py @@ -0,0 +1,21 @@ +import sys + +import autocommand + +from jaraco.text import Stripper + + +def strip_prefix(): + r""" + Strip any common prefix from stdin. + + >>> import io, pytest + >>> getfixture('monkeypatch').setattr('sys.stdin', io.StringIO('abcdef\nabc123')) + >>> strip_prefix() + def + 123 + """ + sys.stdout.writelines(Stripper.strip_prefix(sys.stdin).lines) + + +autocommand.autocommand(__name__)(strip_prefix) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/to-dvorak.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/to-dvorak.py new file mode 100644 index 0000000000000000000000000000000000000000..a6d5da80b3b565b956b523a5e0aaea7b6274cfcb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/to-dvorak.py @@ -0,0 +1,6 @@ +import sys + +from . import layouts + + +__name__ == '__main__' and layouts._translate_stream(sys.stdin, layouts.to_dvorak) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/to-qwerty.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/to-qwerty.py new file mode 100644 index 0000000000000000000000000000000000000000..abe27286629cd3c1d95a984ad4a172957927af9b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/jaraco/text/to-qwerty.py @@ -0,0 +1,6 @@ +import sys + +from . import layouts + + +__name__ == '__main__' and layouts._translate_stream(sys.stdin, layouts.to_qwerty) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools-10.3.0.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools-10.3.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools-10.3.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools-10.3.0.dist-info/LICENSE b/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools-10.3.0.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0a523bece3e50519653c4d7a38399baa487fefa1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools-10.3.0.dist-info/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2012 Erik Rose + +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.12/site-packages/setuptools/_vendor/more_itertools-10.3.0.dist-info/METADATA b/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools-10.3.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..fb41b0cfe69bd01a045de31597a3f6d176604d25 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools-10.3.0.dist-info/METADATA @@ -0,0 +1,266 @@ +Metadata-Version: 2.1 +Name: more-itertools +Version: 10.3.0 +Summary: More routines for operating on iterables, beyond itertools +Keywords: itertools,iterator,iteration,filter,peek,peekable,chunk,chunked +Author-email: Erik Rose +Requires-Python: >=3.8 +Description-Content-Type: text/x-rst +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Natural Language :: English +Classifier: License :: OSI Approved :: MIT License +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 :: Only +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Software Development :: Libraries +Project-URL: Homepage, https://github.com/more-itertools/more-itertools + +============== +More Itertools +============== + +.. image:: https://readthedocs.org/projects/more-itertools/badge/?version=latest + :target: https://more-itertools.readthedocs.io/en/stable/ + +Python's ``itertools`` library is a gem - you can compose elegant solutions +for a variety of problems with the functions it provides. In ``more-itertools`` +we collect additional building blocks, recipes, and routines for working with +Python iterables. + ++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Grouping | `chunked `_, | +| | `ichunked `_, | +| | `chunked_even `_, | +| | `sliced `_, | +| | `constrained_batches `_, | +| | `distribute `_, | +| | `divide `_, | +| | `split_at `_, | +| | `split_before `_, | +| | `split_after `_, | +| | `split_into `_, | +| | `split_when `_, | +| | `bucket `_, | +| | `unzip `_, | +| | `batched `_, | +| | `grouper `_, | +| | `partition `_, | +| | `transpose `_ | ++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Lookahead and lookback | `spy `_, | +| | `peekable `_, | +| | `seekable `_ | ++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Windowing | `windowed `_, | +| | `substrings `_, | +| | `substrings_indexes `_, | +| | `stagger `_, | +| | `windowed_complete `_, | +| | `pairwise `_, | +| | `triplewise `_, | +| | `sliding_window `_, | +| | `subslices `_ | ++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Augmenting | `count_cycle `_, | +| | `intersperse `_, | +| | `padded `_, | +| | `repeat_each `_, | +| | `mark_ends `_, | +| | `repeat_last `_, | +| | `adjacent `_, | +| | `groupby_transform `_, | +| | `pad_none `_, | +| | `ncycles `_ | ++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Combining | `collapse `_, | +| | `sort_together `_, | +| | `interleave `_, | +| | `interleave_longest `_, | +| | `interleave_evenly `_, | +| | `zip_offset `_, | +| | `zip_equal `_, | +| | `zip_broadcast `_, | +| | `flatten `_, | +| | `roundrobin `_, | +| | `prepend `_, | +| | `value_chain `_, | +| | `partial_product `_ | ++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Summarizing | `ilen `_, | +| | `unique_to_each `_, | +| | `sample `_, | +| | `consecutive_groups `_, | +| | `run_length `_, | +| | `map_reduce `_, | +| | `join_mappings `_, | +| | `exactly_n `_, | +| | `is_sorted `_, | +| | `all_equal `_, | +| | `all_unique `_, | +| | `minmax `_, | +| | `first_true `_, | +| | `quantify `_, | +| | `iequals `_ | ++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Selecting | `islice_extended `_, | +| | `first `_, | +| | `last `_, | +| | `one `_, | +| | `only `_, | +| | `strictly_n `_, | +| | `strip `_, | +| | `lstrip `_, | +| | `rstrip `_, | +| | `filter_except `_, | +| | `map_except `_, | +| | `filter_map `_, | +| | `iter_suppress `_, | +| | `nth_or_last `_, | +| | `unique_in_window `_, | +| | `before_and_after `_, | +| | `nth `_, | +| | `take `_, | +| | `tail `_, | +| | `unique_everseen `_, | +| | `unique_justseen `_, | +| | `unique `_, | +| | `duplicates_everseen `_, | +| | `duplicates_justseen `_, | +| | `classify_unique `_, | +| | `longest_common_prefix `_, | +| | `takewhile_inclusive `_ | ++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Math | `dft `_, | +| | `idft `_, | +| | `convolve `_, | +| | `dotproduct `_, | +| | `factor `_, | +| | `matmul `_, | +| | `polynomial_from_roots `_, | +| | `polynomial_derivative `_, | +| | `polynomial_eval `_, | +| | `sieve `_, | +| | `sum_of_squares `_, | +| | `totient `_ | ++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Combinatorics | `distinct_permutations `_, | +| | `distinct_combinations `_, | +| | `circular_shifts `_, | +| | `partitions `_, | +| | `set_partitions `_, | +| | `product_index `_, | +| | `combination_index `_, | +| | `permutation_index `_, | +| | `combination_with_replacement_index `_, | +| | `gray_product `_, | +| | `outer_product `_, | +| | `powerset `_, | +| | `powerset_of_sets `_, | +| | `random_product `_, | +| | `random_permutation `_, | +| | `random_combination `_, | +| | `random_combination_with_replacement `_, | +| | `nth_product `_, | +| | `nth_permutation `_, | +| | `nth_combination `_, | +| | `nth_combination_with_replacement `_ | ++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Wrapping | `always_iterable `_, | +| | `always_reversible `_, | +| | `countable `_, | +| | `consumer `_, | +| | `with_iter `_, | +| | `iter_except `_ | ++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Others | `locate `_, | +| | `rlocate `_, | +| | `replace `_, | +| | `numeric_range `_, | +| | `side_effect `_, | +| | `iterate `_, | +| | `difference `_, | +| | `make_decorator `_, | +| | `SequenceView `_, | +| | `time_limited `_, | +| | `map_if `_, | +| | `iter_index `_, | +| | `consume `_, | +| | `tabulate `_, | +| | `repeatfunc `_, | +| | `reshape `_ | +| | `doublestarmap `_ | ++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ + + +Getting started +=============== + +To get started, install the library with `pip `_: + +.. code-block:: shell + + pip install more-itertools + +The recipes from the `itertools docs `_ +are included in the top-level package: + +.. code-block:: python + + >>> from more_itertools import flatten + >>> iterable = [(0, 1), (2, 3)] + >>> list(flatten(iterable)) + [0, 1, 2, 3] + +Several new recipes are available as well: + +.. code-block:: python + + >>> from more_itertools import chunked + >>> iterable = [0, 1, 2, 3, 4, 5, 6, 7, 8] + >>> list(chunked(iterable, 3)) + [[0, 1, 2], [3, 4, 5], [6, 7, 8]] + + >>> from more_itertools import spy + >>> iterable = (x * x for x in range(1, 6)) + >>> head, iterable = spy(iterable, n=3) + >>> list(head) + [1, 4, 9] + >>> list(iterable) + [1, 4, 9, 16, 25] + + + +For the full listing of functions, see the `API documentation `_. + + +Links elsewhere +=============== + +Blog posts about ``more-itertools``: + +* `Yo, I heard you like decorators `__ +* `Tour of Python Itertools `__ (`Alternate `__) +* `Real-World Python More Itertools `_ + + +Development +=========== + +``more-itertools`` is maintained by `@erikrose `_ +and `@bbayles `_, with help from `many others `_. +If you have a problem or suggestion, please file a bug or pull request in this +repository. Thanks for contributing! + + +Version History +=============== + +The version history can be found in `documentation `_. + diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools-10.3.0.dist-info/RECORD b/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools-10.3.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..f15f3fcdc5c751048d3c9eac077a3d11c861df36 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools-10.3.0.dist-info/RECORD @@ -0,0 +1,16 @@ +more_itertools-10.3.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +more_itertools-10.3.0.dist-info/LICENSE,sha256=CfHIyelBrz5YTVlkHqm4fYPAyw_QB-te85Gn4mQ8GkY,1053 +more_itertools-10.3.0.dist-info/METADATA,sha256=BFO90O-fLNiVQMpj7oIS5ztzgJUUQZ3TA32P5HH3N-A,36293 +more_itertools-10.3.0.dist-info/RECORD,, +more_itertools-10.3.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +more_itertools-10.3.0.dist-info/WHEEL,sha256=rSgq_JpHF9fHR1lx53qwg_1-2LypZE_qmcuXbVUq948,81 +more_itertools/__init__.py,sha256=dtAbGjTDmn_ghiU5YXfhyDy0phAlXVdt5klZA5fUa-Q,149 +more_itertools/__init__.pyi,sha256=5B3eTzON1BBuOLob1vCflyEb2lSd6usXQQ-Cv-hXkeA,43 +more_itertools/__pycache__/__init__.cpython-312.pyc,, +more_itertools/__pycache__/more.cpython-312.pyc,, +more_itertools/__pycache__/recipes.cpython-312.pyc,, +more_itertools/more.py,sha256=1E5kzFncRKTDw0cYv1yRXMgDdunstLQd1QStcnL6U90,148370 +more_itertools/more.pyi,sha256=iXXeqt48Nxe8VGmIWpkVXuKpR2FYNuu2DU8nQLWCCu0,21484 +more_itertools/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +more_itertools/recipes.py,sha256=WedhhfhGVgr6zii8fIbGJVmRTw0ZKRiLKnYBDGJv4nY,28591 +more_itertools/recipes.pyi,sha256=T_mdGpcFdfrP3JSWbwzYP9JyNV-Go-7RPfpxfftAWlA,4617 diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools-10.3.0.dist-info/REQUESTED b/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools-10.3.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools-10.3.0.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools-10.3.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..db4a255f3a271083b66f205eeaa81f74c97bb8ac --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools-10.3.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 3.8.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools/__init__.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9c4662fc31a75cd576f6f110a345f5e2f3cb2958 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools/__init__.py @@ -0,0 +1,6 @@ +"""More routines for operating on iterables, beyond itertools""" + +from .more import * # noqa +from .recipes import * # noqa + +__version__ = '10.3.0' diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools/__init__.pyi b/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..96f6e36c7f4ac9ea0aebdcd9e11b8d1ff092d2ef --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools/__init__.pyi @@ -0,0 +1,2 @@ +from .more import * +from .recipes import * diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7018fc5d790d94cafd858a6e7a19cdaa1dd6e34d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools/__pycache__/more.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools/__pycache__/more.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83e8846e16fbbf29daa5745e2f5d1863ef5229dc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools/__pycache__/more.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7e58539f19196ca8842554b8b8c0be3d9dd849ed6ca8bf54619a2901587b8024 +size 174210 diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools/__pycache__/recipes.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools/__pycache__/recipes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f985dd997ac5a6bd64e22627f8fd63dffee79e4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools/__pycache__/recipes.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools/more.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools/more.py new file mode 100644 index 0000000000000000000000000000000000000000..7b481907daee16c08b1e6fac8cec3b87ea4c8bd8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools/more.py @@ -0,0 +1,4806 @@ +import math +import warnings + +from collections import Counter, defaultdict, deque, abc +from collections.abc import Sequence +from functools import cached_property, partial, reduce, wraps +from heapq import heapify, heapreplace, heappop +from itertools import ( + chain, + combinations, + compress, + count, + cycle, + dropwhile, + groupby, + islice, + repeat, + starmap, + takewhile, + tee, + zip_longest, + product, +) +from math import comb, e, exp, factorial, floor, fsum, log, perm, tau +from queue import Empty, Queue +from random import random, randrange, uniform +from operator import itemgetter, mul, sub, gt, lt, ge, le +from sys import hexversion, maxsize +from time import monotonic + +from .recipes import ( + _marker, + _zip_equal, + UnequalIterablesError, + consume, + flatten, + pairwise, + powerset, + take, + unique_everseen, + all_equal, + batched, +) + +__all__ = [ + 'AbortThread', + 'SequenceView', + 'UnequalIterablesError', + 'adjacent', + 'all_unique', + 'always_iterable', + 'always_reversible', + 'bucket', + 'callback_iter', + 'chunked', + 'chunked_even', + 'circular_shifts', + 'collapse', + 'combination_index', + 'combination_with_replacement_index', + 'consecutive_groups', + 'constrained_batches', + 'consumer', + 'count_cycle', + 'countable', + 'dft', + 'difference', + 'distinct_combinations', + 'distinct_permutations', + 'distribute', + 'divide', + 'doublestarmap', + 'duplicates_everseen', + 'duplicates_justseen', + 'classify_unique', + 'exactly_n', + 'filter_except', + 'filter_map', + 'first', + 'gray_product', + 'groupby_transform', + 'ichunked', + 'iequals', + 'idft', + 'ilen', + 'interleave', + 'interleave_evenly', + 'interleave_longest', + 'intersperse', + 'is_sorted', + 'islice_extended', + 'iterate', + 'iter_suppress', + 'join_mappings', + 'last', + 'locate', + 'longest_common_prefix', + 'lstrip', + 'make_decorator', + 'map_except', + 'map_if', + 'map_reduce', + 'mark_ends', + 'minmax', + 'nth_or_last', + 'nth_permutation', + 'nth_product', + 'nth_combination_with_replacement', + 'numeric_range', + 'one', + 'only', + 'outer_product', + 'padded', + 'partial_product', + 'partitions', + 'peekable', + 'permutation_index', + 'powerset_of_sets', + 'product_index', + 'raise_', + 'repeat_each', + 'repeat_last', + 'replace', + 'rlocate', + 'rstrip', + 'run_length', + 'sample', + 'seekable', + 'set_partitions', + 'side_effect', + 'sliced', + 'sort_together', + 'split_after', + 'split_at', + 'split_before', + 'split_into', + 'split_when', + 'spy', + 'stagger', + 'strip', + 'strictly_n', + 'substrings', + 'substrings_indexes', + 'takewhile_inclusive', + 'time_limited', + 'unique_in_window', + 'unique_to_each', + 'unzip', + 'value_chain', + 'windowed', + 'windowed_complete', + 'with_iter', + 'zip_broadcast', + 'zip_equal', + 'zip_offset', +] + +# math.sumprod is available for Python 3.12+ +_fsumprod = getattr(math, 'sumprod', lambda x, y: fsum(map(mul, x, y))) + + +def chunked(iterable, n, strict=False): + """Break *iterable* into lists of length *n*: + + >>> list(chunked([1, 2, 3, 4, 5, 6], 3)) + [[1, 2, 3], [4, 5, 6]] + + By the default, the last yielded list will have fewer than *n* elements + if the length of *iterable* is not divisible by *n*: + + >>> list(chunked([1, 2, 3, 4, 5, 6, 7, 8], 3)) + [[1, 2, 3], [4, 5, 6], [7, 8]] + + To use a fill-in value instead, see the :func:`grouper` recipe. + + If the length of *iterable* is not divisible by *n* and *strict* is + ``True``, then ``ValueError`` will be raised before the last + list is yielded. + + """ + iterator = iter(partial(take, n, iter(iterable)), []) + if strict: + if n is None: + raise ValueError('n must not be None when using strict mode.') + + def ret(): + for chunk in iterator: + if len(chunk) != n: + raise ValueError('iterable is not divisible by n.') + yield chunk + + return iter(ret()) + else: + return iterator + + +def first(iterable, default=_marker): + """Return the first item of *iterable*, or *default* if *iterable* is + empty. + + >>> first([0, 1, 2, 3]) + 0 + >>> first([], 'some default') + 'some default' + + If *default* is not provided and there are no items in the iterable, + raise ``ValueError``. + + :func:`first` is useful when you have a generator of expensive-to-retrieve + values and want any arbitrary one. It is marginally shorter than + ``next(iter(iterable), default)``. + + """ + for item in iterable: + return item + if default is _marker: + raise ValueError( + 'first() was called on an empty iterable, and no ' + 'default value was provided.' + ) + return default + + +def last(iterable, default=_marker): + """Return the last item of *iterable*, or *default* if *iterable* is + empty. + + >>> last([0, 1, 2, 3]) + 3 + >>> last([], 'some default') + 'some default' + + If *default* is not provided and there are no items in the iterable, + raise ``ValueError``. + """ + try: + if isinstance(iterable, Sequence): + return iterable[-1] + # Work around https://bugs.python.org/issue38525 + elif hasattr(iterable, '__reversed__') and (hexversion != 0x030800F0): + return next(reversed(iterable)) + else: + return deque(iterable, maxlen=1)[-1] + except (IndexError, TypeError, StopIteration): + if default is _marker: + raise ValueError( + 'last() was called on an empty iterable, and no default was ' + 'provided.' + ) + return default + + +def nth_or_last(iterable, n, default=_marker): + """Return the nth or the last item of *iterable*, + or *default* if *iterable* is empty. + + >>> nth_or_last([0, 1, 2, 3], 2) + 2 + >>> nth_or_last([0, 1], 2) + 1 + >>> nth_or_last([], 0, 'some default') + 'some default' + + If *default* is not provided and there are no items in the iterable, + raise ``ValueError``. + """ + return last(islice(iterable, n + 1), default=default) + + +class peekable: + """Wrap an iterator to allow lookahead and prepending elements. + + Call :meth:`peek` on the result to get the value that will be returned + by :func:`next`. This won't advance the iterator: + + >>> p = peekable(['a', 'b']) + >>> p.peek() + 'a' + >>> next(p) + 'a' + + Pass :meth:`peek` a default value to return that instead of raising + ``StopIteration`` when the iterator is exhausted. + + >>> p = peekable([]) + >>> p.peek('hi') + 'hi' + + peekables also offer a :meth:`prepend` method, which "inserts" items + at the head of the iterable: + + >>> p = peekable([1, 2, 3]) + >>> p.prepend(10, 11, 12) + >>> next(p) + 10 + >>> p.peek() + 11 + >>> list(p) + [11, 12, 1, 2, 3] + + peekables can be indexed. Index 0 is the item that will be returned by + :func:`next`, index 1 is the item after that, and so on: + The values up to the given index will be cached. + + >>> p = peekable(['a', 'b', 'c', 'd']) + >>> p[0] + 'a' + >>> p[1] + 'b' + >>> next(p) + 'a' + + Negative indexes are supported, but be aware that they will cache the + remaining items in the source iterator, which may require significant + storage. + + To check whether a peekable is exhausted, check its truth value: + + >>> p = peekable(['a', 'b']) + >>> if p: # peekable has items + ... list(p) + ['a', 'b'] + >>> if not p: # peekable is exhausted + ... list(p) + [] + + """ + + def __init__(self, iterable): + self._it = iter(iterable) + self._cache = deque() + + def __iter__(self): + return self + + def __bool__(self): + try: + self.peek() + except StopIteration: + return False + return True + + def peek(self, default=_marker): + """Return the item that will be next returned from ``next()``. + + Return ``default`` if there are no items left. If ``default`` is not + provided, raise ``StopIteration``. + + """ + if not self._cache: + try: + self._cache.append(next(self._it)) + except StopIteration: + if default is _marker: + raise + return default + return self._cache[0] + + def prepend(self, *items): + """Stack up items to be the next ones returned from ``next()`` or + ``self.peek()``. The items will be returned in + first in, first out order:: + + >>> p = peekable([1, 2, 3]) + >>> p.prepend(10, 11, 12) + >>> next(p) + 10 + >>> list(p) + [11, 12, 1, 2, 3] + + It is possible, by prepending items, to "resurrect" a peekable that + previously raised ``StopIteration``. + + >>> p = peekable([]) + >>> next(p) + Traceback (most recent call last): + ... + StopIteration + >>> p.prepend(1) + >>> next(p) + 1 + >>> next(p) + Traceback (most recent call last): + ... + StopIteration + + """ + self._cache.extendleft(reversed(items)) + + def __next__(self): + if self._cache: + return self._cache.popleft() + + return next(self._it) + + def _get_slice(self, index): + # Normalize the slice's arguments + step = 1 if (index.step is None) else index.step + if step > 0: + start = 0 if (index.start is None) else index.start + stop = maxsize if (index.stop is None) else index.stop + elif step < 0: + start = -1 if (index.start is None) else index.start + stop = (-maxsize - 1) if (index.stop is None) else index.stop + else: + raise ValueError('slice step cannot be zero') + + # If either the start or stop index is negative, we'll need to cache + # the rest of the iterable in order to slice from the right side. + if (start < 0) or (stop < 0): + self._cache.extend(self._it) + # Otherwise we'll need to find the rightmost index and cache to that + # point. + else: + n = min(max(start, stop) + 1, maxsize) + cache_len = len(self._cache) + if n >= cache_len: + self._cache.extend(islice(self._it, n - cache_len)) + + return list(self._cache)[index] + + def __getitem__(self, index): + if isinstance(index, slice): + return self._get_slice(index) + + cache_len = len(self._cache) + if index < 0: + self._cache.extend(self._it) + elif index >= cache_len: + self._cache.extend(islice(self._it, index + 1 - cache_len)) + + return self._cache[index] + + +def consumer(func): + """Decorator that automatically advances a PEP-342-style "reverse iterator" + to its first yield point so you don't have to call ``next()`` on it + manually. + + >>> @consumer + ... def tally(): + ... i = 0 + ... while True: + ... print('Thing number %s is %s.' % (i, (yield))) + ... i += 1 + ... + >>> t = tally() + >>> t.send('red') + Thing number 0 is red. + >>> t.send('fish') + Thing number 1 is fish. + + Without the decorator, you would have to call ``next(t)`` before + ``t.send()`` could be used. + + """ + + @wraps(func) + def wrapper(*args, **kwargs): + gen = func(*args, **kwargs) + next(gen) + return gen + + return wrapper + + +def ilen(iterable): + """Return the number of items in *iterable*. + + >>> ilen(x for x in range(1000000) if x % 3 == 0) + 333334 + + This consumes the iterable, so handle with care. + + """ + # This approach was selected because benchmarks showed it's likely the + # fastest of the known implementations at the time of writing. + # See GitHub tracker: #236, #230. + counter = count() + deque(zip(iterable, counter), maxlen=0) + return next(counter) + + +def iterate(func, start): + """Return ``start``, ``func(start)``, ``func(func(start))``, ... + + >>> from itertools import islice + >>> list(islice(iterate(lambda x: 2*x, 1), 10)) + [1, 2, 4, 8, 16, 32, 64, 128, 256, 512] + + """ + while True: + yield start + try: + start = func(start) + except StopIteration: + break + + +def with_iter(context_manager): + """Wrap an iterable in a ``with`` statement, so it closes once exhausted. + + For example, this will close the file when the iterator is exhausted:: + + upper_lines = (line.upper() for line in with_iter(open('foo'))) + + Any context manager which returns an iterable is a candidate for + ``with_iter``. + + """ + with context_manager as iterable: + yield from iterable + + +def one(iterable, too_short=None, too_long=None): + """Return the first item from *iterable*, which is expected to contain only + that item. Raise an exception if *iterable* is empty or has more than one + item. + + :func:`one` is useful for ensuring that an iterable contains only one item. + For example, it can be used to retrieve the result of a database query + that is expected to return a single row. + + If *iterable* is empty, ``ValueError`` will be raised. You may specify a + different exception with the *too_short* keyword: + + >>> it = [] + >>> one(it) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + ValueError: too many items in iterable (expected 1)' + >>> too_short = IndexError('too few items') + >>> one(it, too_short=too_short) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + IndexError: too few items + + Similarly, if *iterable* contains more than one item, ``ValueError`` will + be raised. You may specify a different exception with the *too_long* + keyword: + + >>> it = ['too', 'many'] + >>> one(it) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + ValueError: Expected exactly one item in iterable, but got 'too', + 'many', and perhaps more. + >>> too_long = RuntimeError + >>> one(it, too_long=too_long) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + RuntimeError + + Note that :func:`one` attempts to advance *iterable* twice to ensure there + is only one item. See :func:`spy` or :func:`peekable` to check iterable + contents less destructively. + + """ + it = iter(iterable) + + try: + first_value = next(it) + except StopIteration as exc: + raise ( + too_short or ValueError('too few items in iterable (expected 1)') + ) from exc + + try: + second_value = next(it) + except StopIteration: + pass + else: + msg = ( + 'Expected exactly one item in iterable, but got {!r}, {!r}, ' + 'and perhaps more.'.format(first_value, second_value) + ) + raise too_long or ValueError(msg) + + return first_value + + +def raise_(exception, *args): + raise exception(*args) + + +def strictly_n(iterable, n, too_short=None, too_long=None): + """Validate that *iterable* has exactly *n* items and return them if + it does. If it has fewer than *n* items, call function *too_short* + with those items. If it has more than *n* items, call function + *too_long* with the first ``n + 1`` items. + + >>> iterable = ['a', 'b', 'c', 'd'] + >>> n = 4 + >>> list(strictly_n(iterable, n)) + ['a', 'b', 'c', 'd'] + + Note that the returned iterable must be consumed in order for the check to + be made. + + By default, *too_short* and *too_long* are functions that raise + ``ValueError``. + + >>> list(strictly_n('ab', 3)) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + ValueError: too few items in iterable (got 2) + + >>> list(strictly_n('abc', 2)) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + ValueError: too many items in iterable (got at least 3) + + You can instead supply functions that do something else. + *too_short* will be called with the number of items in *iterable*. + *too_long* will be called with `n + 1`. + + >>> def too_short(item_count): + ... raise RuntimeError + >>> it = strictly_n('abcd', 6, too_short=too_short) + >>> list(it) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + RuntimeError + + >>> def too_long(item_count): + ... print('The boss is going to hear about this') + >>> it = strictly_n('abcdef', 4, too_long=too_long) + >>> list(it) + The boss is going to hear about this + ['a', 'b', 'c', 'd'] + + """ + if too_short is None: + too_short = lambda item_count: raise_( + ValueError, + 'Too few items in iterable (got {})'.format(item_count), + ) + + if too_long is None: + too_long = lambda item_count: raise_( + ValueError, + 'Too many items in iterable (got at least {})'.format(item_count), + ) + + it = iter(iterable) + for i in range(n): + try: + item = next(it) + except StopIteration: + too_short(i) + return + else: + yield item + + try: + next(it) + except StopIteration: + pass + else: + too_long(n + 1) + + +def distinct_permutations(iterable, r=None): + """Yield successive distinct permutations of the elements in *iterable*. + + >>> sorted(distinct_permutations([1, 0, 1])) + [(0, 1, 1), (1, 0, 1), (1, 1, 0)] + + Equivalent to ``set(permutations(iterable))``, except duplicates are not + generated and thrown away. For larger input sequences this is much more + efficient. + + Duplicate permutations arise when there are duplicated elements in the + input iterable. The number of items returned is + `n! / (x_1! * x_2! * ... * x_n!)`, where `n` is the total number of + items input, and each `x_i` is the count of a distinct item in the input + sequence. + + If *r* is given, only the *r*-length permutations are yielded. + + >>> sorted(distinct_permutations([1, 0, 1], r=2)) + [(0, 1), (1, 0), (1, 1)] + >>> sorted(distinct_permutations(range(3), r=2)) + [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)] + + """ + + # Algorithm: https://w.wiki/Qai + def _full(A): + while True: + # Yield the permutation we have + yield tuple(A) + + # Find the largest index i such that A[i] < A[i + 1] + for i in range(size - 2, -1, -1): + if A[i] < A[i + 1]: + break + # If no such index exists, this permutation is the last one + else: + return + + # Find the largest index j greater than j such that A[i] < A[j] + for j in range(size - 1, i, -1): + if A[i] < A[j]: + break + + # Swap the value of A[i] with that of A[j], then reverse the + # sequence from A[i + 1] to form the new permutation + A[i], A[j] = A[j], A[i] + A[i + 1 :] = A[: i - size : -1] # A[i + 1:][::-1] + + # Algorithm: modified from the above + def _partial(A, r): + # Split A into the first r items and the last r items + head, tail = A[:r], A[r:] + right_head_indexes = range(r - 1, -1, -1) + left_tail_indexes = range(len(tail)) + + while True: + # Yield the permutation we have + yield tuple(head) + + # Starting from the right, find the first index of the head with + # value smaller than the maximum value of the tail - call it i. + pivot = tail[-1] + for i in right_head_indexes: + if head[i] < pivot: + break + pivot = head[i] + else: + return + + # Starting from the left, find the first value of the tail + # with a value greater than head[i] and swap. + for j in left_tail_indexes: + if tail[j] > head[i]: + head[i], tail[j] = tail[j], head[i] + break + # If we didn't find one, start from the right and find the first + # index of the head with a value greater than head[i] and swap. + else: + for j in right_head_indexes: + if head[j] > head[i]: + head[i], head[j] = head[j], head[i] + break + + # Reverse head[i + 1:] and swap it with tail[:r - (i + 1)] + tail += head[: i - r : -1] # head[i + 1:][::-1] + i += 1 + head[i:], tail[:] = tail[: r - i], tail[r - i :] + + items = sorted(iterable) + + size = len(items) + if r is None: + r = size + + if 0 < r <= size: + return _full(items) if (r == size) else _partial(items, r) + + return iter(() if r else ((),)) + + +def intersperse(e, iterable, n=1): + """Intersperse filler element *e* among the items in *iterable*, leaving + *n* items between each filler element. + + >>> list(intersperse('!', [1, 2, 3, 4, 5])) + [1, '!', 2, '!', 3, '!', 4, '!', 5] + + >>> list(intersperse(None, [1, 2, 3, 4, 5], n=2)) + [1, 2, None, 3, 4, None, 5] + + """ + if n == 0: + raise ValueError('n must be > 0') + elif n == 1: + # interleave(repeat(e), iterable) -> e, x_0, e, x_1, e, x_2... + # islice(..., 1, None) -> x_0, e, x_1, e, x_2... + return islice(interleave(repeat(e), iterable), 1, None) + else: + # interleave(filler, chunks) -> [e], [x_0, x_1], [e], [x_2, x_3]... + # islice(..., 1, None) -> [x_0, x_1], [e], [x_2, x_3]... + # flatten(...) -> x_0, x_1, e, x_2, x_3... + filler = repeat([e]) + chunks = chunked(iterable, n) + return flatten(islice(interleave(filler, chunks), 1, None)) + + +def unique_to_each(*iterables): + """Return the elements from each of the input iterables that aren't in the + other input iterables. + + For example, suppose you have a set of packages, each with a set of + dependencies:: + + {'pkg_1': {'A', 'B'}, 'pkg_2': {'B', 'C'}, 'pkg_3': {'B', 'D'}} + + If you remove one package, which dependencies can also be removed? + + If ``pkg_1`` is removed, then ``A`` is no longer necessary - it is not + associated with ``pkg_2`` or ``pkg_3``. Similarly, ``C`` is only needed for + ``pkg_2``, and ``D`` is only needed for ``pkg_3``:: + + >>> unique_to_each({'A', 'B'}, {'B', 'C'}, {'B', 'D'}) + [['A'], ['C'], ['D']] + + If there are duplicates in one input iterable that aren't in the others + they will be duplicated in the output. Input order is preserved:: + + >>> unique_to_each("mississippi", "missouri") + [['p', 'p'], ['o', 'u', 'r']] + + It is assumed that the elements of each iterable are hashable. + + """ + pool = [list(it) for it in iterables] + counts = Counter(chain.from_iterable(map(set, pool))) + uniques = {element for element in counts if counts[element] == 1} + return [list(filter(uniques.__contains__, it)) for it in pool] + + +def windowed(seq, n, fillvalue=None, step=1): + """Return a sliding window of width *n* over the given iterable. + + >>> all_windows = windowed([1, 2, 3, 4, 5], 3) + >>> list(all_windows) + [(1, 2, 3), (2, 3, 4), (3, 4, 5)] + + When the window is larger than the iterable, *fillvalue* is used in place + of missing values: + + >>> list(windowed([1, 2, 3], 4)) + [(1, 2, 3, None)] + + Each window will advance in increments of *step*: + + >>> list(windowed([1, 2, 3, 4, 5, 6], 3, fillvalue='!', step=2)) + [(1, 2, 3), (3, 4, 5), (5, 6, '!')] + + To slide into the iterable's items, use :func:`chain` to add filler items + to the left: + + >>> iterable = [1, 2, 3, 4] + >>> n = 3 + >>> padding = [None] * (n - 1) + >>> list(windowed(chain(padding, iterable), 3)) + [(None, None, 1), (None, 1, 2), (1, 2, 3), (2, 3, 4)] + """ + if n < 0: + raise ValueError('n must be >= 0') + if n == 0: + yield () + return + if step < 1: + raise ValueError('step must be >= 1') + + iterable = iter(seq) + + # Generate first window + window = deque(islice(iterable, n), maxlen=n) + + # Deal with the first window not being full + if not window: + return + if len(window) < n: + yield tuple(window) + ((fillvalue,) * (n - len(window))) + return + yield tuple(window) + + # Create the filler for the next windows. The padding ensures + # we have just enough elements to fill the last window. + padding = (fillvalue,) * (n - 1 if step >= n else step - 1) + filler = map(window.append, chain(iterable, padding)) + + # Generate the rest of the windows + for _ in islice(filler, step - 1, None, step): + yield tuple(window) + + +def substrings(iterable): + """Yield all of the substrings of *iterable*. + + >>> [''.join(s) for s in substrings('more')] + ['m', 'o', 'r', 'e', 'mo', 'or', 're', 'mor', 'ore', 'more'] + + Note that non-string iterables can also be subdivided. + + >>> list(substrings([0, 1, 2])) + [(0,), (1,), (2,), (0, 1), (1, 2), (0, 1, 2)] + + """ + # The length-1 substrings + seq = [] + for item in iter(iterable): + seq.append(item) + yield (item,) + seq = tuple(seq) + item_count = len(seq) + + # And the rest + for n in range(2, item_count + 1): + for i in range(item_count - n + 1): + yield seq[i : i + n] + + +def substrings_indexes(seq, reverse=False): + """Yield all substrings and their positions in *seq* + + The items yielded will be a tuple of the form ``(substr, i, j)``, where + ``substr == seq[i:j]``. + + This function only works for iterables that support slicing, such as + ``str`` objects. + + >>> for item in substrings_indexes('more'): + ... print(item) + ('m', 0, 1) + ('o', 1, 2) + ('r', 2, 3) + ('e', 3, 4) + ('mo', 0, 2) + ('or', 1, 3) + ('re', 2, 4) + ('mor', 0, 3) + ('ore', 1, 4) + ('more', 0, 4) + + Set *reverse* to ``True`` to yield the same items in the opposite order. + + + """ + r = range(1, len(seq) + 1) + if reverse: + r = reversed(r) + return ( + (seq[i : i + L], i, i + L) for L in r for i in range(len(seq) - L + 1) + ) + + +class bucket: + """Wrap *iterable* and return an object that buckets the iterable into + child iterables based on a *key* function. + + >>> iterable = ['a1', 'b1', 'c1', 'a2', 'b2', 'c2', 'b3'] + >>> s = bucket(iterable, key=lambda x: x[0]) # Bucket by 1st character + >>> sorted(list(s)) # Get the keys + ['a', 'b', 'c'] + >>> a_iterable = s['a'] + >>> next(a_iterable) + 'a1' + >>> next(a_iterable) + 'a2' + >>> list(s['b']) + ['b1', 'b2', 'b3'] + + The original iterable will be advanced and its items will be cached until + they are used by the child iterables. This may require significant storage. + + By default, attempting to select a bucket to which no items belong will + exhaust the iterable and cache all values. + If you specify a *validator* function, selected buckets will instead be + checked against it. + + >>> from itertools import count + >>> it = count(1, 2) # Infinite sequence of odd numbers + >>> key = lambda x: x % 10 # Bucket by last digit + >>> validator = lambda x: x in {1, 3, 5, 7, 9} # Odd digits only + >>> s = bucket(it, key=key, validator=validator) + >>> 2 in s + False + >>> list(s[2]) + [] + + """ + + def __init__(self, iterable, key, validator=None): + self._it = iter(iterable) + self._key = key + self._cache = defaultdict(deque) + self._validator = validator or (lambda x: True) + + def __contains__(self, value): + if not self._validator(value): + return False + + try: + item = next(self[value]) + except StopIteration: + return False + else: + self._cache[value].appendleft(item) + + return True + + def _get_values(self, value): + """ + Helper to yield items from the parent iterator that match *value*. + Items that don't match are stored in the local cache as they + are encountered. + """ + while True: + # If we've cached some items that match the target value, emit + # the first one and evict it from the cache. + if self._cache[value]: + yield self._cache[value].popleft() + # Otherwise we need to advance the parent iterator to search for + # a matching item, caching the rest. + else: + while True: + try: + item = next(self._it) + except StopIteration: + return + item_value = self._key(item) + if item_value == value: + yield item + break + elif self._validator(item_value): + self._cache[item_value].append(item) + + def __iter__(self): + for item in self._it: + item_value = self._key(item) + if self._validator(item_value): + self._cache[item_value].append(item) + + yield from self._cache.keys() + + def __getitem__(self, value): + if not self._validator(value): + return iter(()) + + return self._get_values(value) + + +def spy(iterable, n=1): + """Return a 2-tuple with a list containing the first *n* elements of + *iterable*, and an iterator with the same items as *iterable*. + This allows you to "look ahead" at the items in the iterable without + advancing it. + + There is one item in the list by default: + + >>> iterable = 'abcdefg' + >>> head, iterable = spy(iterable) + >>> head + ['a'] + >>> list(iterable) + ['a', 'b', 'c', 'd', 'e', 'f', 'g'] + + You may use unpacking to retrieve items instead of lists: + + >>> (head,), iterable = spy('abcdefg') + >>> head + 'a' + >>> (first, second), iterable = spy('abcdefg', 2) + >>> first + 'a' + >>> second + 'b' + + The number of items requested can be larger than the number of items in + the iterable: + + >>> iterable = [1, 2, 3, 4, 5] + >>> head, iterable = spy(iterable, 10) + >>> head + [1, 2, 3, 4, 5] + >>> list(iterable) + [1, 2, 3, 4, 5] + + """ + it = iter(iterable) + head = take(n, it) + + return head.copy(), chain(head, it) + + +def interleave(*iterables): + """Return a new iterable yielding from each iterable in turn, + until the shortest is exhausted. + + >>> list(interleave([1, 2, 3], [4, 5], [6, 7, 8])) + [1, 4, 6, 2, 5, 7] + + For a version that doesn't terminate after the shortest iterable is + exhausted, see :func:`interleave_longest`. + + """ + return chain.from_iterable(zip(*iterables)) + + +def interleave_longest(*iterables): + """Return a new iterable yielding from each iterable in turn, + skipping any that are exhausted. + + >>> list(interleave_longest([1, 2, 3], [4, 5], [6, 7, 8])) + [1, 4, 6, 2, 5, 7, 3, 8] + + This function produces the same output as :func:`roundrobin`, but may + perform better for some inputs (in particular when the number of iterables + is large). + + """ + i = chain.from_iterable(zip_longest(*iterables, fillvalue=_marker)) + return (x for x in i if x is not _marker) + + +def interleave_evenly(iterables, lengths=None): + """ + Interleave multiple iterables so that their elements are evenly distributed + throughout the output sequence. + + >>> iterables = [1, 2, 3, 4, 5], ['a', 'b'] + >>> list(interleave_evenly(iterables)) + [1, 2, 'a', 3, 4, 'b', 5] + + >>> iterables = [[1, 2, 3], [4, 5], [6, 7, 8]] + >>> list(interleave_evenly(iterables)) + [1, 6, 4, 2, 7, 3, 8, 5] + + This function requires iterables of known length. Iterables without + ``__len__()`` can be used by manually specifying lengths with *lengths*: + + >>> from itertools import combinations, repeat + >>> iterables = [combinations(range(4), 2), ['a', 'b', 'c']] + >>> lengths = [4 * (4 - 1) // 2, 3] + >>> list(interleave_evenly(iterables, lengths=lengths)) + [(0, 1), (0, 2), 'a', (0, 3), (1, 2), 'b', (1, 3), (2, 3), 'c'] + + Based on Bresenham's algorithm. + """ + if lengths is None: + try: + lengths = [len(it) for it in iterables] + except TypeError: + raise ValueError( + 'Iterable lengths could not be determined automatically. ' + 'Specify them with the lengths keyword.' + ) + elif len(iterables) != len(lengths): + raise ValueError('Mismatching number of iterables and lengths.') + + dims = len(lengths) + + # sort iterables by length, descending + lengths_permute = sorted( + range(dims), key=lambda i: lengths[i], reverse=True + ) + lengths_desc = [lengths[i] for i in lengths_permute] + iters_desc = [iter(iterables[i]) for i in lengths_permute] + + # the longest iterable is the primary one (Bresenham: the longest + # distance along an axis) + delta_primary, deltas_secondary = lengths_desc[0], lengths_desc[1:] + iter_primary, iters_secondary = iters_desc[0], iters_desc[1:] + errors = [delta_primary // dims] * len(deltas_secondary) + + to_yield = sum(lengths) + while to_yield: + yield next(iter_primary) + to_yield -= 1 + # update errors for each secondary iterable + errors = [e - delta for e, delta in zip(errors, deltas_secondary)] + + # those iterables for which the error is negative are yielded + # ("diagonal step" in Bresenham) + for i, e_ in enumerate(errors): + if e_ < 0: + yield next(iters_secondary[i]) + to_yield -= 1 + errors[i] += delta_primary + + +def collapse(iterable, base_type=None, levels=None): + """Flatten an iterable with multiple levels of nesting (e.g., a list of + lists of tuples) into non-iterable types. + + >>> iterable = [(1, 2), ([3, 4], [[5], [6]])] + >>> list(collapse(iterable)) + [1, 2, 3, 4, 5, 6] + + Binary and text strings are not considered iterable and + will not be collapsed. + + To avoid collapsing other types, specify *base_type*: + + >>> iterable = ['ab', ('cd', 'ef'), ['gh', 'ij']] + >>> list(collapse(iterable, base_type=tuple)) + ['ab', ('cd', 'ef'), 'gh', 'ij'] + + Specify *levels* to stop flattening after a certain level: + + >>> iterable = [('a', ['b']), ('c', ['d'])] + >>> list(collapse(iterable)) # Fully flattened + ['a', 'b', 'c', 'd'] + >>> list(collapse(iterable, levels=1)) # Only one level flattened + ['a', ['b'], 'c', ['d']] + + """ + stack = deque() + # Add our first node group, treat the iterable as a single node + stack.appendleft((0, repeat(iterable, 1))) + + while stack: + node_group = stack.popleft() + level, nodes = node_group + + # Check if beyond max level + if levels is not None and level > levels: + yield from nodes + continue + + for node in nodes: + # Check if done iterating + if isinstance(node, (str, bytes)) or ( + (base_type is not None) and isinstance(node, base_type) + ): + yield node + # Otherwise try to create child nodes + else: + try: + tree = iter(node) + except TypeError: + yield node + else: + # Save our current location + stack.appendleft(node_group) + # Append the new child node + stack.appendleft((level + 1, tree)) + # Break to process child node + break + + +def side_effect(func, iterable, chunk_size=None, before=None, after=None): + """Invoke *func* on each item in *iterable* (or on each *chunk_size* group + of items) before yielding the item. + + `func` must be a function that takes a single argument. Its return value + will be discarded. + + *before* and *after* are optional functions that take no arguments. They + will be executed before iteration starts and after it ends, respectively. + + `side_effect` can be used for logging, updating progress bars, or anything + that is not functionally "pure." + + Emitting a status message: + + >>> from more_itertools import consume + >>> func = lambda item: print('Received {}'.format(item)) + >>> consume(side_effect(func, range(2))) + Received 0 + Received 1 + + Operating on chunks of items: + + >>> pair_sums = [] + >>> func = lambda chunk: pair_sums.append(sum(chunk)) + >>> list(side_effect(func, [0, 1, 2, 3, 4, 5], 2)) + [0, 1, 2, 3, 4, 5] + >>> list(pair_sums) + [1, 5, 9] + + Writing to a file-like object: + + >>> from io import StringIO + >>> from more_itertools import consume + >>> f = StringIO() + >>> func = lambda x: print(x, file=f) + >>> before = lambda: print(u'HEADER', file=f) + >>> after = f.close + >>> it = [u'a', u'b', u'c'] + >>> consume(side_effect(func, it, before=before, after=after)) + >>> f.closed + True + + """ + try: + if before is not None: + before() + + if chunk_size is None: + for item in iterable: + func(item) + yield item + else: + for chunk in chunked(iterable, chunk_size): + func(chunk) + yield from chunk + finally: + if after is not None: + after() + + +def sliced(seq, n, strict=False): + """Yield slices of length *n* from the sequence *seq*. + + >>> list(sliced((1, 2, 3, 4, 5, 6), 3)) + [(1, 2, 3), (4, 5, 6)] + + By the default, the last yielded slice will have fewer than *n* elements + if the length of *seq* is not divisible by *n*: + + >>> list(sliced((1, 2, 3, 4, 5, 6, 7, 8), 3)) + [(1, 2, 3), (4, 5, 6), (7, 8)] + + If the length of *seq* is not divisible by *n* and *strict* is + ``True``, then ``ValueError`` will be raised before the last + slice is yielded. + + This function will only work for iterables that support slicing. + For non-sliceable iterables, see :func:`chunked`. + + """ + iterator = takewhile(len, (seq[i : i + n] for i in count(0, n))) + if strict: + + def ret(): + for _slice in iterator: + if len(_slice) != n: + raise ValueError("seq is not divisible by n.") + yield _slice + + return iter(ret()) + else: + return iterator + + +def split_at(iterable, pred, maxsplit=-1, keep_separator=False): + """Yield lists of items from *iterable*, where each list is delimited by + an item where callable *pred* returns ``True``. + + >>> list(split_at('abcdcba', lambda x: x == 'b')) + [['a'], ['c', 'd', 'c'], ['a']] + + >>> list(split_at(range(10), lambda n: n % 2 == 1)) + [[0], [2], [4], [6], [8], []] + + At most *maxsplit* splits are done. If *maxsplit* is not specified or -1, + then there is no limit on the number of splits: + + >>> list(split_at(range(10), lambda n: n % 2 == 1, maxsplit=2)) + [[0], [2], [4, 5, 6, 7, 8, 9]] + + By default, the delimiting items are not included in the output. + To include them, set *keep_separator* to ``True``. + + >>> list(split_at('abcdcba', lambda x: x == 'b', keep_separator=True)) + [['a'], ['b'], ['c', 'd', 'c'], ['b'], ['a']] + + """ + if maxsplit == 0: + yield list(iterable) + return + + buf = [] + it = iter(iterable) + for item in it: + if pred(item): + yield buf + if keep_separator: + yield [item] + if maxsplit == 1: + yield list(it) + return + buf = [] + maxsplit -= 1 + else: + buf.append(item) + yield buf + + +def split_before(iterable, pred, maxsplit=-1): + """Yield lists of items from *iterable*, where each list ends just before + an item for which callable *pred* returns ``True``: + + >>> list(split_before('OneTwo', lambda s: s.isupper())) + [['O', 'n', 'e'], ['T', 'w', 'o']] + + >>> list(split_before(range(10), lambda n: n % 3 == 0)) + [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]] + + At most *maxsplit* splits are done. If *maxsplit* is not specified or -1, + then there is no limit on the number of splits: + + >>> list(split_before(range(10), lambda n: n % 3 == 0, maxsplit=2)) + [[0, 1, 2], [3, 4, 5], [6, 7, 8, 9]] + """ + if maxsplit == 0: + yield list(iterable) + return + + buf = [] + it = iter(iterable) + for item in it: + if pred(item) and buf: + yield buf + if maxsplit == 1: + yield [item] + list(it) + return + buf = [] + maxsplit -= 1 + buf.append(item) + if buf: + yield buf + + +def split_after(iterable, pred, maxsplit=-1): + """Yield lists of items from *iterable*, where each list ends with an + item where callable *pred* returns ``True``: + + >>> list(split_after('one1two2', lambda s: s.isdigit())) + [['o', 'n', 'e', '1'], ['t', 'w', 'o', '2']] + + >>> list(split_after(range(10), lambda n: n % 3 == 0)) + [[0], [1, 2, 3], [4, 5, 6], [7, 8, 9]] + + At most *maxsplit* splits are done. If *maxsplit* is not specified or -1, + then there is no limit on the number of splits: + + >>> list(split_after(range(10), lambda n: n % 3 == 0, maxsplit=2)) + [[0], [1, 2, 3], [4, 5, 6, 7, 8, 9]] + + """ + if maxsplit == 0: + yield list(iterable) + return + + buf = [] + it = iter(iterable) + for item in it: + buf.append(item) + if pred(item) and buf: + yield buf + if maxsplit == 1: + buf = list(it) + if buf: + yield buf + return + buf = [] + maxsplit -= 1 + if buf: + yield buf + + +def split_when(iterable, pred, maxsplit=-1): + """Split *iterable* into pieces based on the output of *pred*. + *pred* should be a function that takes successive pairs of items and + returns ``True`` if the iterable should be split in between them. + + For example, to find runs of increasing numbers, split the iterable when + element ``i`` is larger than element ``i + 1``: + + >>> list(split_when([1, 2, 3, 3, 2, 5, 2, 4, 2], lambda x, y: x > y)) + [[1, 2, 3, 3], [2, 5], [2, 4], [2]] + + At most *maxsplit* splits are done. If *maxsplit* is not specified or -1, + then there is no limit on the number of splits: + + >>> list(split_when([1, 2, 3, 3, 2, 5, 2, 4, 2], + ... lambda x, y: x > y, maxsplit=2)) + [[1, 2, 3, 3], [2, 5], [2, 4, 2]] + + """ + if maxsplit == 0: + yield list(iterable) + return + + it = iter(iterable) + try: + cur_item = next(it) + except StopIteration: + return + + buf = [cur_item] + for next_item in it: + if pred(cur_item, next_item): + yield buf + if maxsplit == 1: + yield [next_item] + list(it) + return + buf = [] + maxsplit -= 1 + + buf.append(next_item) + cur_item = next_item + + yield buf + + +def split_into(iterable, sizes): + """Yield a list of sequential items from *iterable* of length 'n' for each + integer 'n' in *sizes*. + + >>> list(split_into([1,2,3,4,5,6], [1,2,3])) + [[1], [2, 3], [4, 5, 6]] + + If the sum of *sizes* is smaller than the length of *iterable*, then the + remaining items of *iterable* will not be returned. + + >>> list(split_into([1,2,3,4,5,6], [2,3])) + [[1, 2], [3, 4, 5]] + + If the sum of *sizes* is larger than the length of *iterable*, fewer items + will be returned in the iteration that overruns *iterable* and further + lists will be empty: + + >>> list(split_into([1,2,3,4], [1,2,3,4])) + [[1], [2, 3], [4], []] + + When a ``None`` object is encountered in *sizes*, the returned list will + contain items up to the end of *iterable* the same way that itertools.slice + does: + + >>> list(split_into([1,2,3,4,5,6,7,8,9,0], [2,3,None])) + [[1, 2], [3, 4, 5], [6, 7, 8, 9, 0]] + + :func:`split_into` can be useful for grouping a series of items where the + sizes of the groups are not uniform. An example would be where in a row + from a table, multiple columns represent elements of the same feature + (e.g. a point represented by x,y,z) but, the format is not the same for + all columns. + """ + # convert the iterable argument into an iterator so its contents can + # be consumed by islice in case it is a generator + it = iter(iterable) + + for size in sizes: + if size is None: + yield list(it) + return + else: + yield list(islice(it, size)) + + +def padded(iterable, fillvalue=None, n=None, next_multiple=False): + """Yield the elements from *iterable*, followed by *fillvalue*, such that + at least *n* items are emitted. + + >>> list(padded([1, 2, 3], '?', 5)) + [1, 2, 3, '?', '?'] + + If *next_multiple* is ``True``, *fillvalue* will be emitted until the + number of items emitted is a multiple of *n*: + + >>> list(padded([1, 2, 3, 4], n=3, next_multiple=True)) + [1, 2, 3, 4, None, None] + + If *n* is ``None``, *fillvalue* will be emitted indefinitely. + + To create an *iterable* of exactly size *n*, you can truncate with + :func:`islice`. + + >>> list(islice(padded([1, 2, 3], '?'), 5)) + [1, 2, 3, '?', '?'] + >>> list(islice(padded([1, 2, 3, 4, 5, 6, 7, 8], '?'), 5)) + [1, 2, 3, 4, 5] + + """ + iterable = iter(iterable) + iterable_with_repeat = chain(iterable, repeat(fillvalue)) + + if n is None: + return iterable_with_repeat + elif n < 1: + raise ValueError('n must be at least 1') + elif next_multiple: + + def slice_generator(): + for first in iterable: + yield (first,) + yield islice(iterable_with_repeat, n - 1) + + # While elements exist produce slices of size n + return chain.from_iterable(slice_generator()) + else: + # Ensure the first batch is at least size n then iterate + return chain(islice(iterable_with_repeat, n), iterable) + + +def repeat_each(iterable, n=2): + """Repeat each element in *iterable* *n* times. + + >>> list(repeat_each('ABC', 3)) + ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'] + """ + return chain.from_iterable(map(repeat, iterable, repeat(n))) + + +def repeat_last(iterable, default=None): + """After the *iterable* is exhausted, keep yielding its last element. + + >>> list(islice(repeat_last(range(3)), 5)) + [0, 1, 2, 2, 2] + + If the iterable is empty, yield *default* forever:: + + >>> list(islice(repeat_last(range(0), 42), 5)) + [42, 42, 42, 42, 42] + + """ + item = _marker + for item in iterable: + yield item + final = default if item is _marker else item + yield from repeat(final) + + +def distribute(n, iterable): + """Distribute the items from *iterable* among *n* smaller iterables. + + >>> group_1, group_2 = distribute(2, [1, 2, 3, 4, 5, 6]) + >>> list(group_1) + [1, 3, 5] + >>> list(group_2) + [2, 4, 6] + + If the length of *iterable* is not evenly divisible by *n*, then the + length of the returned iterables will not be identical: + + >>> children = distribute(3, [1, 2, 3, 4, 5, 6, 7]) + >>> [list(c) for c in children] + [[1, 4, 7], [2, 5], [3, 6]] + + If the length of *iterable* is smaller than *n*, then the last returned + iterables will be empty: + + >>> children = distribute(5, [1, 2, 3]) + >>> [list(c) for c in children] + [[1], [2], [3], [], []] + + This function uses :func:`itertools.tee` and may require significant + storage. + + If you need the order items in the smaller iterables to match the + original iterable, see :func:`divide`. + + """ + if n < 1: + raise ValueError('n must be at least 1') + + children = tee(iterable, n) + return [islice(it, index, None, n) for index, it in enumerate(children)] + + +def stagger(iterable, offsets=(-1, 0, 1), longest=False, fillvalue=None): + """Yield tuples whose elements are offset from *iterable*. + The amount by which the `i`-th item in each tuple is offset is given by + the `i`-th item in *offsets*. + + >>> list(stagger([0, 1, 2, 3])) + [(None, 0, 1), (0, 1, 2), (1, 2, 3)] + >>> list(stagger(range(8), offsets=(0, 2, 4))) + [(0, 2, 4), (1, 3, 5), (2, 4, 6), (3, 5, 7)] + + By default, the sequence will end when the final element of a tuple is the + last item in the iterable. To continue until the first element of a tuple + is the last item in the iterable, set *longest* to ``True``:: + + >>> list(stagger([0, 1, 2, 3], longest=True)) + [(None, 0, 1), (0, 1, 2), (1, 2, 3), (2, 3, None), (3, None, None)] + + By default, ``None`` will be used to replace offsets beyond the end of the + sequence. Specify *fillvalue* to use some other value. + + """ + children = tee(iterable, len(offsets)) + + return zip_offset( + *children, offsets=offsets, longest=longest, fillvalue=fillvalue + ) + + +def zip_equal(*iterables): + """``zip`` the input *iterables* together, but raise + ``UnequalIterablesError`` if they aren't all the same length. + + >>> it_1 = range(3) + >>> it_2 = iter('abc') + >>> list(zip_equal(it_1, it_2)) + [(0, 'a'), (1, 'b'), (2, 'c')] + + >>> it_1 = range(3) + >>> it_2 = iter('abcd') + >>> list(zip_equal(it_1, it_2)) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + more_itertools.more.UnequalIterablesError: Iterables have different + lengths + + """ + if hexversion >= 0x30A00A6: + warnings.warn( + ( + 'zip_equal will be removed in a future version of ' + 'more-itertools. Use the builtin zip function with ' + 'strict=True instead.' + ), + DeprecationWarning, + ) + + return _zip_equal(*iterables) + + +def zip_offset(*iterables, offsets, longest=False, fillvalue=None): + """``zip`` the input *iterables* together, but offset the `i`-th iterable + by the `i`-th item in *offsets*. + + >>> list(zip_offset('0123', 'abcdef', offsets=(0, 1))) + [('0', 'b'), ('1', 'c'), ('2', 'd'), ('3', 'e')] + + This can be used as a lightweight alternative to SciPy or pandas to analyze + data sets in which some series have a lead or lag relationship. + + By default, the sequence will end when the shortest iterable is exhausted. + To continue until the longest iterable is exhausted, set *longest* to + ``True``. + + >>> list(zip_offset('0123', 'abcdef', offsets=(0, 1), longest=True)) + [('0', 'b'), ('1', 'c'), ('2', 'd'), ('3', 'e'), (None, 'f')] + + By default, ``None`` will be used to replace offsets beyond the end of the + sequence. Specify *fillvalue* to use some other value. + + """ + if len(iterables) != len(offsets): + raise ValueError("Number of iterables and offsets didn't match") + + staggered = [] + for it, n in zip(iterables, offsets): + if n < 0: + staggered.append(chain(repeat(fillvalue, -n), it)) + elif n > 0: + staggered.append(islice(it, n, None)) + else: + staggered.append(it) + + if longest: + return zip_longest(*staggered, fillvalue=fillvalue) + + return zip(*staggered) + + +def sort_together(iterables, key_list=(0,), key=None, reverse=False): + """Return the input iterables sorted together, with *key_list* as the + priority for sorting. All iterables are trimmed to the length of the + shortest one. + + This can be used like the sorting function in a spreadsheet. If each + iterable represents a column of data, the key list determines which + columns are used for sorting. + + By default, all iterables are sorted using the ``0``-th iterable:: + + >>> iterables = [(4, 3, 2, 1), ('a', 'b', 'c', 'd')] + >>> sort_together(iterables) + [(1, 2, 3, 4), ('d', 'c', 'b', 'a')] + + Set a different key list to sort according to another iterable. + Specifying multiple keys dictates how ties are broken:: + + >>> iterables = [(3, 1, 2), (0, 1, 0), ('c', 'b', 'a')] + >>> sort_together(iterables, key_list=(1, 2)) + [(2, 3, 1), (0, 0, 1), ('a', 'c', 'b')] + + To sort by a function of the elements of the iterable, pass a *key* + function. Its arguments are the elements of the iterables corresponding to + the key list:: + + >>> names = ('a', 'b', 'c') + >>> lengths = (1, 2, 3) + >>> widths = (5, 2, 1) + >>> def area(length, width): + ... return length * width + >>> sort_together([names, lengths, widths], key_list=(1, 2), key=area) + [('c', 'b', 'a'), (3, 2, 1), (1, 2, 5)] + + Set *reverse* to ``True`` to sort in descending order. + + >>> sort_together([(1, 2, 3), ('c', 'b', 'a')], reverse=True) + [(3, 2, 1), ('a', 'b', 'c')] + + """ + if key is None: + # if there is no key function, the key argument to sorted is an + # itemgetter + key_argument = itemgetter(*key_list) + else: + # if there is a key function, call it with the items at the offsets + # specified by the key function as arguments + key_list = list(key_list) + if len(key_list) == 1: + # if key_list contains a single item, pass the item at that offset + # as the only argument to the key function + key_offset = key_list[0] + key_argument = lambda zipped_items: key(zipped_items[key_offset]) + else: + # if key_list contains multiple items, use itemgetter to return a + # tuple of items, which we pass as *args to the key function + get_key_items = itemgetter(*key_list) + key_argument = lambda zipped_items: key( + *get_key_items(zipped_items) + ) + + return list( + zip(*sorted(zip(*iterables), key=key_argument, reverse=reverse)) + ) + + +def unzip(iterable): + """The inverse of :func:`zip`, this function disaggregates the elements + of the zipped *iterable*. + + The ``i``-th iterable contains the ``i``-th element from each element + of the zipped iterable. The first element is used to determine the + length of the remaining elements. + + >>> iterable = [('a', 1), ('b', 2), ('c', 3), ('d', 4)] + >>> letters, numbers = unzip(iterable) + >>> list(letters) + ['a', 'b', 'c', 'd'] + >>> list(numbers) + [1, 2, 3, 4] + + This is similar to using ``zip(*iterable)``, but it avoids reading + *iterable* into memory. Note, however, that this function uses + :func:`itertools.tee` and thus may require significant storage. + + """ + head, iterable = spy(iter(iterable)) + if not head: + # empty iterable, e.g. zip([], [], []) + return () + # spy returns a one-length iterable as head + head = head[0] + iterables = tee(iterable, len(head)) + + def itemgetter(i): + def getter(obj): + try: + return obj[i] + except IndexError: + # basically if we have an iterable like + # iter([(1, 2, 3), (4, 5), (6,)]) + # the second unzipped iterable would fail at the third tuple + # since it would try to access tup[1] + # same with the third unzipped iterable and the second tuple + # to support these "improperly zipped" iterables, + # we create a custom itemgetter + # which just stops the unzipped iterables + # at first length mismatch + raise StopIteration + + return getter + + return tuple(map(itemgetter(i), it) for i, it in enumerate(iterables)) + + +def divide(n, iterable): + """Divide the elements from *iterable* into *n* parts, maintaining + order. + + >>> group_1, group_2 = divide(2, [1, 2, 3, 4, 5, 6]) + >>> list(group_1) + [1, 2, 3] + >>> list(group_2) + [4, 5, 6] + + If the length of *iterable* is not evenly divisible by *n*, then the + length of the returned iterables will not be identical: + + >>> children = divide(3, [1, 2, 3, 4, 5, 6, 7]) + >>> [list(c) for c in children] + [[1, 2, 3], [4, 5], [6, 7]] + + If the length of the iterable is smaller than n, then the last returned + iterables will be empty: + + >>> children = divide(5, [1, 2, 3]) + >>> [list(c) for c in children] + [[1], [2], [3], [], []] + + This function will exhaust the iterable before returning. + If order is not important, see :func:`distribute`, which does not first + pull the iterable into memory. + + """ + if n < 1: + raise ValueError('n must be at least 1') + + try: + iterable[:0] + except TypeError: + seq = tuple(iterable) + else: + seq = iterable + + q, r = divmod(len(seq), n) + + ret = [] + stop = 0 + for i in range(1, n + 1): + start = stop + stop += q + 1 if i <= r else q + ret.append(iter(seq[start:stop])) + + return ret + + +def always_iterable(obj, base_type=(str, bytes)): + """If *obj* is iterable, return an iterator over its items:: + + >>> obj = (1, 2, 3) + >>> list(always_iterable(obj)) + [1, 2, 3] + + If *obj* is not iterable, return a one-item iterable containing *obj*:: + + >>> obj = 1 + >>> list(always_iterable(obj)) + [1] + + If *obj* is ``None``, return an empty iterable: + + >>> obj = None + >>> list(always_iterable(None)) + [] + + By default, binary and text strings are not considered iterable:: + + >>> obj = 'foo' + >>> list(always_iterable(obj)) + ['foo'] + + If *base_type* is set, objects for which ``isinstance(obj, base_type)`` + returns ``True`` won't be considered iterable. + + >>> obj = {'a': 1} + >>> list(always_iterable(obj)) # Iterate over the dict's keys + ['a'] + >>> list(always_iterable(obj, base_type=dict)) # Treat dicts as a unit + [{'a': 1}] + + Set *base_type* to ``None`` to avoid any special handling and treat objects + Python considers iterable as iterable: + + >>> obj = 'foo' + >>> list(always_iterable(obj, base_type=None)) + ['f', 'o', 'o'] + """ + if obj is None: + return iter(()) + + if (base_type is not None) and isinstance(obj, base_type): + return iter((obj,)) + + try: + return iter(obj) + except TypeError: + return iter((obj,)) + + +def adjacent(predicate, iterable, distance=1): + """Return an iterable over `(bool, item)` tuples where the `item` is + drawn from *iterable* and the `bool` indicates whether + that item satisfies the *predicate* or is adjacent to an item that does. + + For example, to find whether items are adjacent to a ``3``:: + + >>> list(adjacent(lambda x: x == 3, range(6))) + [(False, 0), (False, 1), (True, 2), (True, 3), (True, 4), (False, 5)] + + Set *distance* to change what counts as adjacent. For example, to find + whether items are two places away from a ``3``: + + >>> list(adjacent(lambda x: x == 3, range(6), distance=2)) + [(False, 0), (True, 1), (True, 2), (True, 3), (True, 4), (True, 5)] + + This is useful for contextualizing the results of a search function. + For example, a code comparison tool might want to identify lines that + have changed, but also surrounding lines to give the viewer of the diff + context. + + The predicate function will only be called once for each item in the + iterable. + + See also :func:`groupby_transform`, which can be used with this function + to group ranges of items with the same `bool` value. + + """ + # Allow distance=0 mainly for testing that it reproduces results with map() + if distance < 0: + raise ValueError('distance must be at least 0') + + i1, i2 = tee(iterable) + padding = [False] * distance + selected = chain(padding, map(predicate, i1), padding) + adjacent_to_selected = map(any, windowed(selected, 2 * distance + 1)) + return zip(adjacent_to_selected, i2) + + +def groupby_transform(iterable, keyfunc=None, valuefunc=None, reducefunc=None): + """An extension of :func:`itertools.groupby` that can apply transformations + to the grouped data. + + * *keyfunc* is a function computing a key value for each item in *iterable* + * *valuefunc* is a function that transforms the individual items from + *iterable* after grouping + * *reducefunc* is a function that transforms each group of items + + >>> iterable = 'aAAbBBcCC' + >>> keyfunc = lambda k: k.upper() + >>> valuefunc = lambda v: v.lower() + >>> reducefunc = lambda g: ''.join(g) + >>> list(groupby_transform(iterable, keyfunc, valuefunc, reducefunc)) + [('A', 'aaa'), ('B', 'bbb'), ('C', 'ccc')] + + Each optional argument defaults to an identity function if not specified. + + :func:`groupby_transform` is useful when grouping elements of an iterable + using a separate iterable as the key. To do this, :func:`zip` the iterables + and pass a *keyfunc* that extracts the first element and a *valuefunc* + that extracts the second element:: + + >>> from operator import itemgetter + >>> keys = [0, 0, 1, 1, 1, 2, 2, 2, 3] + >>> values = 'abcdefghi' + >>> iterable = zip(keys, values) + >>> grouper = groupby_transform(iterable, itemgetter(0), itemgetter(1)) + >>> [(k, ''.join(g)) for k, g in grouper] + [(0, 'ab'), (1, 'cde'), (2, 'fgh'), (3, 'i')] + + Note that the order of items in the iterable is significant. + Only adjacent items are grouped together, so if you don't want any + duplicate groups, you should sort the iterable by the key function. + + """ + ret = groupby(iterable, keyfunc) + if valuefunc: + ret = ((k, map(valuefunc, g)) for k, g in ret) + if reducefunc: + ret = ((k, reducefunc(g)) for k, g in ret) + + return ret + + +class numeric_range(abc.Sequence, abc.Hashable): + """An extension of the built-in ``range()`` function whose arguments can + be any orderable numeric type. + + With only *stop* specified, *start* defaults to ``0`` and *step* + defaults to ``1``. The output items will match the type of *stop*: + + >>> list(numeric_range(3.5)) + [0.0, 1.0, 2.0, 3.0] + + With only *start* and *stop* specified, *step* defaults to ``1``. The + output items will match the type of *start*: + + >>> from decimal import Decimal + >>> start = Decimal('2.1') + >>> stop = Decimal('5.1') + >>> list(numeric_range(start, stop)) + [Decimal('2.1'), Decimal('3.1'), Decimal('4.1')] + + With *start*, *stop*, and *step* specified the output items will match + the type of ``start + step``: + + >>> from fractions import Fraction + >>> start = Fraction(1, 2) # Start at 1/2 + >>> stop = Fraction(5, 2) # End at 5/2 + >>> step = Fraction(1, 2) # Count by 1/2 + >>> list(numeric_range(start, stop, step)) + [Fraction(1, 2), Fraction(1, 1), Fraction(3, 2), Fraction(2, 1)] + + If *step* is zero, ``ValueError`` is raised. Negative steps are supported: + + >>> list(numeric_range(3, -1, -1.0)) + [3.0, 2.0, 1.0, 0.0] + + Be aware of the limitations of floating point numbers; the representation + of the yielded numbers may be surprising. + + ``datetime.datetime`` objects can be used for *start* and *stop*, if *step* + is a ``datetime.timedelta`` object: + + >>> import datetime + >>> start = datetime.datetime(2019, 1, 1) + >>> stop = datetime.datetime(2019, 1, 3) + >>> step = datetime.timedelta(days=1) + >>> items = iter(numeric_range(start, stop, step)) + >>> next(items) + datetime.datetime(2019, 1, 1, 0, 0) + >>> next(items) + datetime.datetime(2019, 1, 2, 0, 0) + + """ + + _EMPTY_HASH = hash(range(0, 0)) + + def __init__(self, *args): + argc = len(args) + if argc == 1: + (self._stop,) = args + self._start = type(self._stop)(0) + self._step = type(self._stop - self._start)(1) + elif argc == 2: + self._start, self._stop = args + self._step = type(self._stop - self._start)(1) + elif argc == 3: + self._start, self._stop, self._step = args + elif argc == 0: + raise TypeError( + 'numeric_range expected at least ' + '1 argument, got {}'.format(argc) + ) + else: + raise TypeError( + 'numeric_range expected at most ' + '3 arguments, got {}'.format(argc) + ) + + self._zero = type(self._step)(0) + if self._step == self._zero: + raise ValueError('numeric_range() arg 3 must not be zero') + self._growing = self._step > self._zero + + def __bool__(self): + if self._growing: + return self._start < self._stop + else: + return self._start > self._stop + + def __contains__(self, elem): + if self._growing: + if self._start <= elem < self._stop: + return (elem - self._start) % self._step == self._zero + else: + if self._start >= elem > self._stop: + return (self._start - elem) % (-self._step) == self._zero + + return False + + def __eq__(self, other): + if isinstance(other, numeric_range): + empty_self = not bool(self) + empty_other = not bool(other) + if empty_self or empty_other: + return empty_self and empty_other # True if both empty + else: + return ( + self._start == other._start + and self._step == other._step + and self._get_by_index(-1) == other._get_by_index(-1) + ) + else: + return False + + def __getitem__(self, key): + if isinstance(key, int): + return self._get_by_index(key) + elif isinstance(key, slice): + step = self._step if key.step is None else key.step * self._step + + if key.start is None or key.start <= -self._len: + start = self._start + elif key.start >= self._len: + start = self._stop + else: # -self._len < key.start < self._len + start = self._get_by_index(key.start) + + if key.stop is None or key.stop >= self._len: + stop = self._stop + elif key.stop <= -self._len: + stop = self._start + else: # -self._len < key.stop < self._len + stop = self._get_by_index(key.stop) + + return numeric_range(start, stop, step) + else: + raise TypeError( + 'numeric range indices must be ' + 'integers or slices, not {}'.format(type(key).__name__) + ) + + def __hash__(self): + if self: + return hash((self._start, self._get_by_index(-1), self._step)) + else: + return self._EMPTY_HASH + + def __iter__(self): + values = (self._start + (n * self._step) for n in count()) + if self._growing: + return takewhile(partial(gt, self._stop), values) + else: + return takewhile(partial(lt, self._stop), values) + + def __len__(self): + return self._len + + @cached_property + def _len(self): + if self._growing: + start = self._start + stop = self._stop + step = self._step + else: + start = self._stop + stop = self._start + step = -self._step + distance = stop - start + if distance <= self._zero: + return 0 + else: # distance > 0 and step > 0: regular euclidean division + q, r = divmod(distance, step) + return int(q) + int(r != self._zero) + + def __reduce__(self): + return numeric_range, (self._start, self._stop, self._step) + + def __repr__(self): + if self._step == 1: + return "numeric_range({}, {})".format( + repr(self._start), repr(self._stop) + ) + else: + return "numeric_range({}, {}, {})".format( + repr(self._start), repr(self._stop), repr(self._step) + ) + + def __reversed__(self): + return iter( + numeric_range( + self._get_by_index(-1), self._start - self._step, -self._step + ) + ) + + def count(self, value): + return int(value in self) + + def index(self, value): + if self._growing: + if self._start <= value < self._stop: + q, r = divmod(value - self._start, self._step) + if r == self._zero: + return int(q) + else: + if self._start >= value > self._stop: + q, r = divmod(self._start - value, -self._step) + if r == self._zero: + return int(q) + + raise ValueError("{} is not in numeric range".format(value)) + + def _get_by_index(self, i): + if i < 0: + i += self._len + if i < 0 or i >= self._len: + raise IndexError("numeric range object index out of range") + return self._start + i * self._step + + +def count_cycle(iterable, n=None): + """Cycle through the items from *iterable* up to *n* times, yielding + the number of completed cycles along with each item. If *n* is omitted the + process repeats indefinitely. + + >>> list(count_cycle('AB', 3)) + [(0, 'A'), (0, 'B'), (1, 'A'), (1, 'B'), (2, 'A'), (2, 'B')] + + """ + iterable = tuple(iterable) + if not iterable: + return iter(()) + counter = count() if n is None else range(n) + return ((i, item) for i in counter for item in iterable) + + +def mark_ends(iterable): + """Yield 3-tuples of the form ``(is_first, is_last, item)``. + + >>> list(mark_ends('ABC')) + [(True, False, 'A'), (False, False, 'B'), (False, True, 'C')] + + Use this when looping over an iterable to take special action on its first + and/or last items: + + >>> iterable = ['Header', 100, 200, 'Footer'] + >>> total = 0 + >>> for is_first, is_last, item in mark_ends(iterable): + ... if is_first: + ... continue # Skip the header + ... if is_last: + ... continue # Skip the footer + ... total += item + >>> print(total) + 300 + """ + it = iter(iterable) + + try: + b = next(it) + except StopIteration: + return + + try: + for i in count(): + a = b + b = next(it) + yield i == 0, False, a + + except StopIteration: + yield i == 0, True, a + + +def locate(iterable, pred=bool, window_size=None): + """Yield the index of each item in *iterable* for which *pred* returns + ``True``. + + *pred* defaults to :func:`bool`, which will select truthy items: + + >>> list(locate([0, 1, 1, 0, 1, 0, 0])) + [1, 2, 4] + + Set *pred* to a custom function to, e.g., find the indexes for a particular + item. + + >>> list(locate(['a', 'b', 'c', 'b'], lambda x: x == 'b')) + [1, 3] + + If *window_size* is given, then the *pred* function will be called with + that many items. This enables searching for sub-sequences: + + >>> iterable = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3] + >>> pred = lambda *args: args == (1, 2, 3) + >>> list(locate(iterable, pred=pred, window_size=3)) + [1, 5, 9] + + Use with :func:`seekable` to find indexes and then retrieve the associated + items: + + >>> from itertools import count + >>> from more_itertools import seekable + >>> source = (3 * n + 1 if (n % 2) else n // 2 for n in count()) + >>> it = seekable(source) + >>> pred = lambda x: x > 100 + >>> indexes = locate(it, pred=pred) + >>> i = next(indexes) + >>> it.seek(i) + >>> next(it) + 106 + + """ + if window_size is None: + return compress(count(), map(pred, iterable)) + + if window_size < 1: + raise ValueError('window size must be at least 1') + + it = windowed(iterable, window_size, fillvalue=_marker) + return compress(count(), starmap(pred, it)) + + +def longest_common_prefix(iterables): + """Yield elements of the longest common prefix amongst given *iterables*. + + >>> ''.join(longest_common_prefix(['abcd', 'abc', 'abf'])) + 'ab' + + """ + return (c[0] for c in takewhile(all_equal, zip(*iterables))) + + +def lstrip(iterable, pred): + """Yield the items from *iterable*, but strip any from the beginning + for which *pred* returns ``True``. + + For example, to remove a set of items from the start of an iterable: + + >>> iterable = (None, False, None, 1, 2, None, 3, False, None) + >>> pred = lambda x: x in {None, False, ''} + >>> list(lstrip(iterable, pred)) + [1, 2, None, 3, False, None] + + This function is analogous to to :func:`str.lstrip`, and is essentially + an wrapper for :func:`itertools.dropwhile`. + + """ + return dropwhile(pred, iterable) + + +def rstrip(iterable, pred): + """Yield the items from *iterable*, but strip any from the end + for which *pred* returns ``True``. + + For example, to remove a set of items from the end of an iterable: + + >>> iterable = (None, False, None, 1, 2, None, 3, False, None) + >>> pred = lambda x: x in {None, False, ''} + >>> list(rstrip(iterable, pred)) + [None, False, None, 1, 2, None, 3] + + This function is analogous to :func:`str.rstrip`. + + """ + cache = [] + cache_append = cache.append + cache_clear = cache.clear + for x in iterable: + if pred(x): + cache_append(x) + else: + yield from cache + cache_clear() + yield x + + +def strip(iterable, pred): + """Yield the items from *iterable*, but strip any from the + beginning and end for which *pred* returns ``True``. + + For example, to remove a set of items from both ends of an iterable: + + >>> iterable = (None, False, None, 1, 2, None, 3, False, None) + >>> pred = lambda x: x in {None, False, ''} + >>> list(strip(iterable, pred)) + [1, 2, None, 3] + + This function is analogous to :func:`str.strip`. + + """ + return rstrip(lstrip(iterable, pred), pred) + + +class islice_extended: + """An extension of :func:`itertools.islice` that supports negative values + for *stop*, *start*, and *step*. + + >>> iterable = iter('abcdefgh') + >>> list(islice_extended(iterable, -4, -1)) + ['e', 'f', 'g'] + + Slices with negative values require some caching of *iterable*, but this + function takes care to minimize the amount of memory required. + + For example, you can use a negative step with an infinite iterator: + + >>> from itertools import count + >>> list(islice_extended(count(), 110, 99, -2)) + [110, 108, 106, 104, 102, 100] + + You can also use slice notation directly: + + >>> iterable = map(str, count()) + >>> it = islice_extended(iterable)[10:20:2] + >>> list(it) + ['10', '12', '14', '16', '18'] + + """ + + def __init__(self, iterable, *args): + it = iter(iterable) + if args: + self._iterable = _islice_helper(it, slice(*args)) + else: + self._iterable = it + + def __iter__(self): + return self + + def __next__(self): + return next(self._iterable) + + def __getitem__(self, key): + if isinstance(key, slice): + return islice_extended(_islice_helper(self._iterable, key)) + + raise TypeError('islice_extended.__getitem__ argument must be a slice') + + +def _islice_helper(it, s): + start = s.start + stop = s.stop + if s.step == 0: + raise ValueError('step argument must be a non-zero integer or None.') + step = s.step or 1 + + if step > 0: + start = 0 if (start is None) else start + + if start < 0: + # Consume all but the last -start items + cache = deque(enumerate(it, 1), maxlen=-start) + len_iter = cache[-1][0] if cache else 0 + + # Adjust start to be positive + i = max(len_iter + start, 0) + + # Adjust stop to be positive + if stop is None: + j = len_iter + elif stop >= 0: + j = min(stop, len_iter) + else: + j = max(len_iter + stop, 0) + + # Slice the cache + n = j - i + if n <= 0: + return + + for index, item in islice(cache, 0, n, step): + yield item + elif (stop is not None) and (stop < 0): + # Advance to the start position + next(islice(it, start, start), None) + + # When stop is negative, we have to carry -stop items while + # iterating + cache = deque(islice(it, -stop), maxlen=-stop) + + for index, item in enumerate(it): + cached_item = cache.popleft() + if index % step == 0: + yield cached_item + cache.append(item) + else: + # When both start and stop are positive we have the normal case + yield from islice(it, start, stop, step) + else: + start = -1 if (start is None) else start + + if (stop is not None) and (stop < 0): + # Consume all but the last items + n = -stop - 1 + cache = deque(enumerate(it, 1), maxlen=n) + len_iter = cache[-1][0] if cache else 0 + + # If start and stop are both negative they are comparable and + # we can just slice. Otherwise we can adjust start to be negative + # and then slice. + if start < 0: + i, j = start, stop + else: + i, j = min(start - len_iter, -1), None + + for index, item in list(cache)[i:j:step]: + yield item + else: + # Advance to the stop position + if stop is not None: + m = stop + 1 + next(islice(it, m, m), None) + + # stop is positive, so if start is negative they are not comparable + # and we need the rest of the items. + if start < 0: + i = start + n = None + # stop is None and start is positive, so we just need items up to + # the start index. + elif stop is None: + i = None + n = start + 1 + # Both stop and start are positive, so they are comparable. + else: + i = None + n = start - stop + if n <= 0: + return + + cache = list(islice(it, n)) + + yield from cache[i::step] + + +def always_reversible(iterable): + """An extension of :func:`reversed` that supports all iterables, not + just those which implement the ``Reversible`` or ``Sequence`` protocols. + + >>> print(*always_reversible(x for x in range(3))) + 2 1 0 + + If the iterable is already reversible, this function returns the + result of :func:`reversed()`. If the iterable is not reversible, + this function will cache the remaining items in the iterable and + yield them in reverse order, which may require significant storage. + """ + try: + return reversed(iterable) + except TypeError: + return reversed(list(iterable)) + + +def consecutive_groups(iterable, ordering=lambda x: x): + """Yield groups of consecutive items using :func:`itertools.groupby`. + The *ordering* function determines whether two items are adjacent by + returning their position. + + By default, the ordering function is the identity function. This is + suitable for finding runs of numbers: + + >>> iterable = [1, 10, 11, 12, 20, 30, 31, 32, 33, 40] + >>> for group in consecutive_groups(iterable): + ... print(list(group)) + [1] + [10, 11, 12] + [20] + [30, 31, 32, 33] + [40] + + For finding runs of adjacent letters, try using the :meth:`index` method + of a string of letters: + + >>> from string import ascii_lowercase + >>> iterable = 'abcdfgilmnop' + >>> ordering = ascii_lowercase.index + >>> for group in consecutive_groups(iterable, ordering): + ... print(list(group)) + ['a', 'b', 'c', 'd'] + ['f', 'g'] + ['i'] + ['l', 'm', 'n', 'o', 'p'] + + Each group of consecutive items is an iterator that shares it source with + *iterable*. When an an output group is advanced, the previous group is + no longer available unless its elements are copied (e.g., into a ``list``). + + >>> iterable = [1, 2, 11, 12, 21, 22] + >>> saved_groups = [] + >>> for group in consecutive_groups(iterable): + ... saved_groups.append(list(group)) # Copy group elements + >>> saved_groups + [[1, 2], [11, 12], [21, 22]] + + """ + for k, g in groupby( + enumerate(iterable), key=lambda x: x[0] - ordering(x[1]) + ): + yield map(itemgetter(1), g) + + +def difference(iterable, func=sub, *, initial=None): + """This function is the inverse of :func:`itertools.accumulate`. By default + it will compute the first difference of *iterable* using + :func:`operator.sub`: + + >>> from itertools import accumulate + >>> iterable = accumulate([0, 1, 2, 3, 4]) # produces 0, 1, 3, 6, 10 + >>> list(difference(iterable)) + [0, 1, 2, 3, 4] + + *func* defaults to :func:`operator.sub`, but other functions can be + specified. They will be applied as follows:: + + A, B, C, D, ... --> A, func(B, A), func(C, B), func(D, C), ... + + For example, to do progressive division: + + >>> iterable = [1, 2, 6, 24, 120] + >>> func = lambda x, y: x // y + >>> list(difference(iterable, func)) + [1, 2, 3, 4, 5] + + If the *initial* keyword is set, the first element will be skipped when + computing successive differences. + + >>> it = [10, 11, 13, 16] # from accumulate([1, 2, 3], initial=10) + >>> list(difference(it, initial=10)) + [1, 2, 3] + + """ + a, b = tee(iterable) + try: + first = [next(b)] + except StopIteration: + return iter([]) + + if initial is not None: + first = [] + + return chain(first, map(func, b, a)) + + +class SequenceView(Sequence): + """Return a read-only view of the sequence object *target*. + + :class:`SequenceView` objects are analogous to Python's built-in + "dictionary view" types. They provide a dynamic view of a sequence's items, + meaning that when the sequence updates, so does the view. + + >>> seq = ['0', '1', '2'] + >>> view = SequenceView(seq) + >>> view + SequenceView(['0', '1', '2']) + >>> seq.append('3') + >>> view + SequenceView(['0', '1', '2', '3']) + + Sequence views support indexing, slicing, and length queries. They act + like the underlying sequence, except they don't allow assignment: + + >>> view[1] + '1' + >>> view[1:-1] + ['1', '2'] + >>> len(view) + 4 + + Sequence views are useful as an alternative to copying, as they don't + require (much) extra storage. + + """ + + def __init__(self, target): + if not isinstance(target, Sequence): + raise TypeError + self._target = target + + def __getitem__(self, index): + return self._target[index] + + def __len__(self): + return len(self._target) + + def __repr__(self): + return '{}({})'.format(self.__class__.__name__, repr(self._target)) + + +class seekable: + """Wrap an iterator to allow for seeking backward and forward. This + progressively caches the items in the source iterable so they can be + re-visited. + + Call :meth:`seek` with an index to seek to that position in the source + iterable. + + To "reset" an iterator, seek to ``0``: + + >>> from itertools import count + >>> it = seekable((str(n) for n in count())) + >>> next(it), next(it), next(it) + ('0', '1', '2') + >>> it.seek(0) + >>> next(it), next(it), next(it) + ('0', '1', '2') + >>> next(it) + '3' + + You can also seek forward: + + >>> it = seekable((str(n) for n in range(20))) + >>> it.seek(10) + >>> next(it) + '10' + >>> it.relative_seek(-2) # Seeking relative to the current position + >>> next(it) + '9' + >>> it.seek(20) # Seeking past the end of the source isn't a problem + >>> list(it) + [] + >>> it.seek(0) # Resetting works even after hitting the end + >>> next(it), next(it), next(it) + ('0', '1', '2') + + Call :meth:`peek` to look ahead one item without advancing the iterator: + + >>> it = seekable('1234') + >>> it.peek() + '1' + >>> list(it) + ['1', '2', '3', '4'] + >>> it.peek(default='empty') + 'empty' + + Before the iterator is at its end, calling :func:`bool` on it will return + ``True``. After it will return ``False``: + + >>> it = seekable('5678') + >>> bool(it) + True + >>> list(it) + ['5', '6', '7', '8'] + >>> bool(it) + False + + You may view the contents of the cache with the :meth:`elements` method. + That returns a :class:`SequenceView`, a view that updates automatically: + + >>> it = seekable((str(n) for n in range(10))) + >>> next(it), next(it), next(it) + ('0', '1', '2') + >>> elements = it.elements() + >>> elements + SequenceView(['0', '1', '2']) + >>> next(it) + '3' + >>> elements + SequenceView(['0', '1', '2', '3']) + + By default, the cache grows as the source iterable progresses, so beware of + wrapping very large or infinite iterables. Supply *maxlen* to limit the + size of the cache (this of course limits how far back you can seek). + + >>> from itertools import count + >>> it = seekable((str(n) for n in count()), maxlen=2) + >>> next(it), next(it), next(it), next(it) + ('0', '1', '2', '3') + >>> list(it.elements()) + ['2', '3'] + >>> it.seek(0) + >>> next(it), next(it), next(it), next(it) + ('2', '3', '4', '5') + >>> next(it) + '6' + + """ + + def __init__(self, iterable, maxlen=None): + self._source = iter(iterable) + if maxlen is None: + self._cache = [] + else: + self._cache = deque([], maxlen) + self._index = None + + def __iter__(self): + return self + + def __next__(self): + if self._index is not None: + try: + item = self._cache[self._index] + except IndexError: + self._index = None + else: + self._index += 1 + return item + + item = next(self._source) + self._cache.append(item) + return item + + def __bool__(self): + try: + self.peek() + except StopIteration: + return False + return True + + def peek(self, default=_marker): + try: + peeked = next(self) + except StopIteration: + if default is _marker: + raise + return default + if self._index is None: + self._index = len(self._cache) + self._index -= 1 + return peeked + + def elements(self): + return SequenceView(self._cache) + + def seek(self, index): + self._index = index + remainder = index - len(self._cache) + if remainder > 0: + consume(self, remainder) + + def relative_seek(self, count): + index = len(self._cache) + self.seek(max(index + count, 0)) + + +class run_length: + """ + :func:`run_length.encode` compresses an iterable with run-length encoding. + It yields groups of repeated items with the count of how many times they + were repeated: + + >>> uncompressed = 'abbcccdddd' + >>> list(run_length.encode(uncompressed)) + [('a', 1), ('b', 2), ('c', 3), ('d', 4)] + + :func:`run_length.decode` decompresses an iterable that was previously + compressed with run-length encoding. It yields the items of the + decompressed iterable: + + >>> compressed = [('a', 1), ('b', 2), ('c', 3), ('d', 4)] + >>> list(run_length.decode(compressed)) + ['a', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd', 'd'] + + """ + + @staticmethod + def encode(iterable): + return ((k, ilen(g)) for k, g in groupby(iterable)) + + @staticmethod + def decode(iterable): + return chain.from_iterable(repeat(k, n) for k, n in iterable) + + +def exactly_n(iterable, n, predicate=bool): + """Return ``True`` if exactly ``n`` items in the iterable are ``True`` + according to the *predicate* function. + + >>> exactly_n([True, True, False], 2) + True + >>> exactly_n([True, True, False], 1) + False + >>> exactly_n([0, 1, 2, 3, 4, 5], 3, lambda x: x < 3) + True + + The iterable will be advanced until ``n + 1`` truthy items are encountered, + so avoid calling it on infinite iterables. + + """ + return len(take(n + 1, filter(predicate, iterable))) == n + + +def circular_shifts(iterable): + """Return a list of circular shifts of *iterable*. + + >>> circular_shifts(range(4)) + [(0, 1, 2, 3), (1, 2, 3, 0), (2, 3, 0, 1), (3, 0, 1, 2)] + """ + lst = list(iterable) + return take(len(lst), windowed(cycle(lst), len(lst))) + + +def make_decorator(wrapping_func, result_index=0): + """Return a decorator version of *wrapping_func*, which is a function that + modifies an iterable. *result_index* is the position in that function's + signature where the iterable goes. + + This lets you use itertools on the "production end," i.e. at function + definition. This can augment what the function returns without changing the + function's code. + + For example, to produce a decorator version of :func:`chunked`: + + >>> from more_itertools import chunked + >>> chunker = make_decorator(chunked, result_index=0) + >>> @chunker(3) + ... def iter_range(n): + ... return iter(range(n)) + ... + >>> list(iter_range(9)) + [[0, 1, 2], [3, 4, 5], [6, 7, 8]] + + To only allow truthy items to be returned: + + >>> truth_serum = make_decorator(filter, result_index=1) + >>> @truth_serum(bool) + ... def boolean_test(): + ... return [0, 1, '', ' ', False, True] + ... + >>> list(boolean_test()) + [1, ' ', True] + + The :func:`peekable` and :func:`seekable` wrappers make for practical + decorators: + + >>> from more_itertools import peekable + >>> peekable_function = make_decorator(peekable) + >>> @peekable_function() + ... def str_range(*args): + ... return (str(x) for x in range(*args)) + ... + >>> it = str_range(1, 20, 2) + >>> next(it), next(it), next(it) + ('1', '3', '5') + >>> it.peek() + '7' + >>> next(it) + '7' + + """ + + # See https://sites.google.com/site/bbayles/index/decorator_factory for + # notes on how this works. + def decorator(*wrapping_args, **wrapping_kwargs): + def outer_wrapper(f): + def inner_wrapper(*args, **kwargs): + result = f(*args, **kwargs) + wrapping_args_ = list(wrapping_args) + wrapping_args_.insert(result_index, result) + return wrapping_func(*wrapping_args_, **wrapping_kwargs) + + return inner_wrapper + + return outer_wrapper + + return decorator + + +def map_reduce(iterable, keyfunc, valuefunc=None, reducefunc=None): + """Return a dictionary that maps the items in *iterable* to categories + defined by *keyfunc*, transforms them with *valuefunc*, and + then summarizes them by category with *reducefunc*. + + *valuefunc* defaults to the identity function if it is unspecified. + If *reducefunc* is unspecified, no summarization takes place: + + >>> keyfunc = lambda x: x.upper() + >>> result = map_reduce('abbccc', keyfunc) + >>> sorted(result.items()) + [('A', ['a']), ('B', ['b', 'b']), ('C', ['c', 'c', 'c'])] + + Specifying *valuefunc* transforms the categorized items: + + >>> keyfunc = lambda x: x.upper() + >>> valuefunc = lambda x: 1 + >>> result = map_reduce('abbccc', keyfunc, valuefunc) + >>> sorted(result.items()) + [('A', [1]), ('B', [1, 1]), ('C', [1, 1, 1])] + + Specifying *reducefunc* summarizes the categorized items: + + >>> keyfunc = lambda x: x.upper() + >>> valuefunc = lambda x: 1 + >>> reducefunc = sum + >>> result = map_reduce('abbccc', keyfunc, valuefunc, reducefunc) + >>> sorted(result.items()) + [('A', 1), ('B', 2), ('C', 3)] + + You may want to filter the input iterable before applying the map/reduce + procedure: + + >>> all_items = range(30) + >>> items = [x for x in all_items if 10 <= x <= 20] # Filter + >>> keyfunc = lambda x: x % 2 # Evens map to 0; odds to 1 + >>> categories = map_reduce(items, keyfunc=keyfunc) + >>> sorted(categories.items()) + [(0, [10, 12, 14, 16, 18, 20]), (1, [11, 13, 15, 17, 19])] + >>> summaries = map_reduce(items, keyfunc=keyfunc, reducefunc=sum) + >>> sorted(summaries.items()) + [(0, 90), (1, 75)] + + Note that all items in the iterable are gathered into a list before the + summarization step, which may require significant storage. + + The returned object is a :obj:`collections.defaultdict` with the + ``default_factory`` set to ``None``, such that it behaves like a normal + dictionary. + + """ + valuefunc = (lambda x: x) if (valuefunc is None) else valuefunc + + ret = defaultdict(list) + for item in iterable: + key = keyfunc(item) + value = valuefunc(item) + ret[key].append(value) + + if reducefunc is not None: + for key, value_list in ret.items(): + ret[key] = reducefunc(value_list) + + ret.default_factory = None + return ret + + +def rlocate(iterable, pred=bool, window_size=None): + """Yield the index of each item in *iterable* for which *pred* returns + ``True``, starting from the right and moving left. + + *pred* defaults to :func:`bool`, which will select truthy items: + + >>> list(rlocate([0, 1, 1, 0, 1, 0, 0])) # Truthy at 1, 2, and 4 + [4, 2, 1] + + Set *pred* to a custom function to, e.g., find the indexes for a particular + item: + + >>> iterable = iter('abcb') + >>> pred = lambda x: x == 'b' + >>> list(rlocate(iterable, pred)) + [3, 1] + + If *window_size* is given, then the *pred* function will be called with + that many items. This enables searching for sub-sequences: + + >>> iterable = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3] + >>> pred = lambda *args: args == (1, 2, 3) + >>> list(rlocate(iterable, pred=pred, window_size=3)) + [9, 5, 1] + + Beware, this function won't return anything for infinite iterables. + If *iterable* is reversible, ``rlocate`` will reverse it and search from + the right. Otherwise, it will search from the left and return the results + in reverse order. + + See :func:`locate` to for other example applications. + + """ + if window_size is None: + try: + len_iter = len(iterable) + return (len_iter - i - 1 for i in locate(reversed(iterable), pred)) + except TypeError: + pass + + return reversed(list(locate(iterable, pred, window_size))) + + +def replace(iterable, pred, substitutes, count=None, window_size=1): + """Yield the items from *iterable*, replacing the items for which *pred* + returns ``True`` with the items from the iterable *substitutes*. + + >>> iterable = [1, 1, 0, 1, 1, 0, 1, 1] + >>> pred = lambda x: x == 0 + >>> substitutes = (2, 3) + >>> list(replace(iterable, pred, substitutes)) + [1, 1, 2, 3, 1, 1, 2, 3, 1, 1] + + If *count* is given, the number of replacements will be limited: + + >>> iterable = [1, 1, 0, 1, 1, 0, 1, 1, 0] + >>> pred = lambda x: x == 0 + >>> substitutes = [None] + >>> list(replace(iterable, pred, substitutes, count=2)) + [1, 1, None, 1, 1, None, 1, 1, 0] + + Use *window_size* to control the number of items passed as arguments to + *pred*. This allows for locating and replacing subsequences. + + >>> iterable = [0, 1, 2, 5, 0, 1, 2, 5] + >>> window_size = 3 + >>> pred = lambda *args: args == (0, 1, 2) # 3 items passed to pred + >>> substitutes = [3, 4] # Splice in these items + >>> list(replace(iterable, pred, substitutes, window_size=window_size)) + [3, 4, 5, 3, 4, 5] + + """ + if window_size < 1: + raise ValueError('window_size must be at least 1') + + # Save the substitutes iterable, since it's used more than once + substitutes = tuple(substitutes) + + # Add padding such that the number of windows matches the length of the + # iterable + it = chain(iterable, [_marker] * (window_size - 1)) + windows = windowed(it, window_size) + + n = 0 + for w in windows: + # If the current window matches our predicate (and we haven't hit + # our maximum number of replacements), splice in the substitutes + # and then consume the following windows that overlap with this one. + # For example, if the iterable is (0, 1, 2, 3, 4...) + # and the window size is 2, we have (0, 1), (1, 2), (2, 3)... + # If the predicate matches on (0, 1), we need to zap (0, 1) and (1, 2) + if pred(*w): + if (count is None) or (n < count): + n += 1 + yield from substitutes + consume(windows, window_size - 1) + continue + + # If there was no match (or we've reached the replacement limit), + # yield the first item from the window. + if w and (w[0] is not _marker): + yield w[0] + + +def partitions(iterable): + """Yield all possible order-preserving partitions of *iterable*. + + >>> iterable = 'abc' + >>> for part in partitions(iterable): + ... print([''.join(p) for p in part]) + ['abc'] + ['a', 'bc'] + ['ab', 'c'] + ['a', 'b', 'c'] + + This is unrelated to :func:`partition`. + + """ + sequence = list(iterable) + n = len(sequence) + for i in powerset(range(1, n)): + yield [sequence[i:j] for i, j in zip((0,) + i, i + (n,))] + + +def set_partitions(iterable, k=None): + """ + Yield the set partitions of *iterable* into *k* parts. Set partitions are + not order-preserving. + + >>> iterable = 'abc' + >>> for part in set_partitions(iterable, 2): + ... print([''.join(p) for p in part]) + ['a', 'bc'] + ['ab', 'c'] + ['b', 'ac'] + + + If *k* is not given, every set partition is generated. + + >>> iterable = 'abc' + >>> for part in set_partitions(iterable): + ... print([''.join(p) for p in part]) + ['abc'] + ['a', 'bc'] + ['ab', 'c'] + ['b', 'ac'] + ['a', 'b', 'c'] + + """ + L = list(iterable) + n = len(L) + if k is not None: + if k < 1: + raise ValueError( + "Can't partition in a negative or zero number of groups" + ) + elif k > n: + return + + def set_partitions_helper(L, k): + n = len(L) + if k == 1: + yield [L] + elif n == k: + yield [[s] for s in L] + else: + e, *M = L + for p in set_partitions_helper(M, k - 1): + yield [[e], *p] + for p in set_partitions_helper(M, k): + for i in range(len(p)): + yield p[:i] + [[e] + p[i]] + p[i + 1 :] + + if k is None: + for k in range(1, n + 1): + yield from set_partitions_helper(L, k) + else: + yield from set_partitions_helper(L, k) + + +class time_limited: + """ + Yield items from *iterable* until *limit_seconds* have passed. + If the time limit expires before all items have been yielded, the + ``timed_out`` parameter will be set to ``True``. + + >>> from time import sleep + >>> def generator(): + ... yield 1 + ... yield 2 + ... sleep(0.2) + ... yield 3 + >>> iterable = time_limited(0.1, generator()) + >>> list(iterable) + [1, 2] + >>> iterable.timed_out + True + + Note that the time is checked before each item is yielded, and iteration + stops if the time elapsed is greater than *limit_seconds*. If your time + limit is 1 second, but it takes 2 seconds to generate the first item from + the iterable, the function will run for 2 seconds and not yield anything. + As a special case, when *limit_seconds* is zero, the iterator never + returns anything. + + """ + + def __init__(self, limit_seconds, iterable): + if limit_seconds < 0: + raise ValueError('limit_seconds must be positive') + self.limit_seconds = limit_seconds + self._iterable = iter(iterable) + self._start_time = monotonic() + self.timed_out = False + + def __iter__(self): + return self + + def __next__(self): + if self.limit_seconds == 0: + self.timed_out = True + raise StopIteration + item = next(self._iterable) + if monotonic() - self._start_time > self.limit_seconds: + self.timed_out = True + raise StopIteration + + return item + + +def only(iterable, default=None, too_long=None): + """If *iterable* has only one item, return it. + If it has zero items, return *default*. + If it has more than one item, raise the exception given by *too_long*, + which is ``ValueError`` by default. + + >>> only([], default='missing') + 'missing' + >>> only([1]) + 1 + >>> only([1, 2]) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + ValueError: Expected exactly one item in iterable, but got 1, 2, + and perhaps more.' + >>> only([1, 2], too_long=TypeError) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + TypeError + + Note that :func:`only` attempts to advance *iterable* twice to ensure there + is only one item. See :func:`spy` or :func:`peekable` to check + iterable contents less destructively. + """ + it = iter(iterable) + first_value = next(it, default) + + try: + second_value = next(it) + except StopIteration: + pass + else: + msg = ( + 'Expected exactly one item in iterable, but got {!r}, {!r}, ' + 'and perhaps more.'.format(first_value, second_value) + ) + raise too_long or ValueError(msg) + + return first_value + + +def _ichunk(iterable, n): + cache = deque() + chunk = islice(iterable, n) + + def generator(): + while True: + if cache: + yield cache.popleft() + else: + try: + item = next(chunk) + except StopIteration: + return + else: + yield item + + def materialize_next(n=1): + # if n not specified materialize everything + if n is None: + cache.extend(chunk) + return len(cache) + + to_cache = n - len(cache) + + # materialize up to n + if to_cache > 0: + cache.extend(islice(chunk, to_cache)) + + # return number materialized up to n + return min(n, len(cache)) + + return (generator(), materialize_next) + + +def ichunked(iterable, n): + """Break *iterable* into sub-iterables with *n* elements each. + :func:`ichunked` is like :func:`chunked`, but it yields iterables + instead of lists. + + If the sub-iterables are read in order, the elements of *iterable* + won't be stored in memory. + If they are read out of order, :func:`itertools.tee` is used to cache + elements as necessary. + + >>> from itertools import count + >>> all_chunks = ichunked(count(), 4) + >>> c_1, c_2, c_3 = next(all_chunks), next(all_chunks), next(all_chunks) + >>> list(c_2) # c_1's elements have been cached; c_3's haven't been + [4, 5, 6, 7] + >>> list(c_1) + [0, 1, 2, 3] + >>> list(c_3) + [8, 9, 10, 11] + + """ + iterable = iter(iterable) + while True: + # Create new chunk + chunk, materialize_next = _ichunk(iterable, n) + + # Check to see whether we're at the end of the source iterable + if not materialize_next(): + return + + yield chunk + + # Fill previous chunk's cache + materialize_next(None) + + +def iequals(*iterables): + """Return ``True`` if all given *iterables* are equal to each other, + which means that they contain the same elements in the same order. + + The function is useful for comparing iterables of different data types + or iterables that do not support equality checks. + + >>> iequals("abc", ['a', 'b', 'c'], ('a', 'b', 'c'), iter("abc")) + True + + >>> iequals("abc", "acb") + False + + Not to be confused with :func:`all_equal`, which checks whether all + elements of iterable are equal to each other. + + """ + return all(map(all_equal, zip_longest(*iterables, fillvalue=object()))) + + +def distinct_combinations(iterable, r): + """Yield the distinct combinations of *r* items taken from *iterable*. + + >>> list(distinct_combinations([0, 0, 1], 2)) + [(0, 0), (0, 1)] + + Equivalent to ``set(combinations(iterable))``, except duplicates are not + generated and thrown away. For larger input sequences this is much more + efficient. + + """ + if r < 0: + raise ValueError('r must be non-negative') + elif r == 0: + yield () + return + pool = tuple(iterable) + generators = [unique_everseen(enumerate(pool), key=itemgetter(1))] + current_combo = [None] * r + level = 0 + while generators: + try: + cur_idx, p = next(generators[-1]) + except StopIteration: + generators.pop() + level -= 1 + continue + current_combo[level] = p + if level + 1 == r: + yield tuple(current_combo) + else: + generators.append( + unique_everseen( + enumerate(pool[cur_idx + 1 :], cur_idx + 1), + key=itemgetter(1), + ) + ) + level += 1 + + +def filter_except(validator, iterable, *exceptions): + """Yield the items from *iterable* for which the *validator* function does + not raise one of the specified *exceptions*. + + *validator* is called for each item in *iterable*. + It should be a function that accepts one argument and raises an exception + if that item is not valid. + + >>> iterable = ['1', '2', 'three', '4', None] + >>> list(filter_except(int, iterable, ValueError, TypeError)) + ['1', '2', '4'] + + If an exception other than one given by *exceptions* is raised by + *validator*, it is raised like normal. + """ + for item in iterable: + try: + validator(item) + except exceptions: + pass + else: + yield item + + +def map_except(function, iterable, *exceptions): + """Transform each item from *iterable* with *function* and yield the + result, unless *function* raises one of the specified *exceptions*. + + *function* is called to transform each item in *iterable*. + It should accept one argument. + + >>> iterable = ['1', '2', 'three', '4', None] + >>> list(map_except(int, iterable, ValueError, TypeError)) + [1, 2, 4] + + If an exception other than one given by *exceptions* is raised by + *function*, it is raised like normal. + """ + for item in iterable: + try: + yield function(item) + except exceptions: + pass + + +def map_if(iterable, pred, func, func_else=lambda x: x): + """Evaluate each item from *iterable* using *pred*. If the result is + equivalent to ``True``, transform the item with *func* and yield it. + Otherwise, transform the item with *func_else* and yield it. + + *pred*, *func*, and *func_else* should each be functions that accept + one argument. By default, *func_else* is the identity function. + + >>> from math import sqrt + >>> iterable = list(range(-5, 5)) + >>> iterable + [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4] + >>> list(map_if(iterable, lambda x: x > 3, lambda x: 'toobig')) + [-5, -4, -3, -2, -1, 0, 1, 2, 3, 'toobig'] + >>> list(map_if(iterable, lambda x: x >= 0, + ... lambda x: f'{sqrt(x):.2f}', lambda x: None)) + [None, None, None, None, None, '0.00', '1.00', '1.41', '1.73', '2.00'] + """ + for item in iterable: + yield func(item) if pred(item) else func_else(item) + + +def _sample_unweighted(iterable, k): + # Implementation of "Algorithm L" from the 1994 paper by Kim-Hung Li: + # "Reservoir-Sampling Algorithms of Time Complexity O(n(1+log(N/n)))". + + # Fill up the reservoir (collection of samples) with the first `k` samples + reservoir = take(k, iterable) + + # Generate random number that's the largest in a sample of k U(0,1) numbers + # Largest order statistic: https://en.wikipedia.org/wiki/Order_statistic + W = exp(log(random()) / k) + + # The number of elements to skip before changing the reservoir is a random + # number with a geometric distribution. Sample it using random() and logs. + next_index = k + floor(log(random()) / log(1 - W)) + + for index, element in enumerate(iterable, k): + if index == next_index: + reservoir[randrange(k)] = element + # The new W is the largest in a sample of k U(0, `old_W`) numbers + W *= exp(log(random()) / k) + next_index += floor(log(random()) / log(1 - W)) + 1 + + return reservoir + + +def _sample_weighted(iterable, k, weights): + # Implementation of "A-ExpJ" from the 2006 paper by Efraimidis et al. : + # "Weighted random sampling with a reservoir". + + # Log-transform for numerical stability for weights that are small/large + weight_keys = (log(random()) / weight for weight in weights) + + # Fill up the reservoir (collection of samples) with the first `k` + # weight-keys and elements, then heapify the list. + reservoir = take(k, zip(weight_keys, iterable)) + heapify(reservoir) + + # The number of jumps before changing the reservoir is a random variable + # with an exponential distribution. Sample it using random() and logs. + smallest_weight_key, _ = reservoir[0] + weights_to_skip = log(random()) / smallest_weight_key + + for weight, element in zip(weights, iterable): + if weight >= weights_to_skip: + # The notation here is consistent with the paper, but we store + # the weight-keys in log-space for better numerical stability. + smallest_weight_key, _ = reservoir[0] + t_w = exp(weight * smallest_weight_key) + r_2 = uniform(t_w, 1) # generate U(t_w, 1) + weight_key = log(r_2) / weight + heapreplace(reservoir, (weight_key, element)) + smallest_weight_key, _ = reservoir[0] + weights_to_skip = log(random()) / smallest_weight_key + else: + weights_to_skip -= weight + + # Equivalent to [element for weight_key, element in sorted(reservoir)] + return [heappop(reservoir)[1] for _ in range(k)] + + +def sample(iterable, k, weights=None): + """Return a *k*-length list of elements chosen (without replacement) + from the *iterable*. Like :func:`random.sample`, but works on iterables + of unknown length. + + >>> iterable = range(100) + >>> sample(iterable, 5) # doctest: +SKIP + [81, 60, 96, 16, 4] + + An iterable with *weights* may also be given: + + >>> iterable = range(100) + >>> weights = (i * i + 1 for i in range(100)) + >>> sampled = sample(iterable, 5, weights=weights) # doctest: +SKIP + [79, 67, 74, 66, 78] + + The algorithm can also be used to generate weighted random permutations. + The relative weight of each item determines the probability that it + appears late in the permutation. + + >>> data = "abcdefgh" + >>> weights = range(1, len(data) + 1) + >>> sample(data, k=len(data), weights=weights) # doctest: +SKIP + ['c', 'a', 'b', 'e', 'g', 'd', 'h', 'f'] + """ + if k == 0: + return [] + + iterable = iter(iterable) + if weights is None: + return _sample_unweighted(iterable, k) + else: + weights = iter(weights) + return _sample_weighted(iterable, k, weights) + + +def is_sorted(iterable, key=None, reverse=False, strict=False): + """Returns ``True`` if the items of iterable are in sorted order, and + ``False`` otherwise. *key* and *reverse* have the same meaning that they do + in the built-in :func:`sorted` function. + + >>> is_sorted(['1', '2', '3', '4', '5'], key=int) + True + >>> is_sorted([5, 4, 3, 1, 2], reverse=True) + False + + If *strict*, tests for strict sorting, that is, returns ``False`` if equal + elements are found: + + >>> is_sorted([1, 2, 2]) + True + >>> is_sorted([1, 2, 2], strict=True) + False + + The function returns ``False`` after encountering the first out-of-order + item. If there are no out-of-order items, the iterable is exhausted. + """ + + compare = (le if reverse else ge) if strict else (lt if reverse else gt) + it = iterable if key is None else map(key, iterable) + return not any(starmap(compare, pairwise(it))) + + +class AbortThread(BaseException): + pass + + +class callback_iter: + """Convert a function that uses callbacks to an iterator. + + Let *func* be a function that takes a `callback` keyword argument. + For example: + + >>> def func(callback=None): + ... for i, c in [(1, 'a'), (2, 'b'), (3, 'c')]: + ... if callback: + ... callback(i, c) + ... return 4 + + + Use ``with callback_iter(func)`` to get an iterator over the parameters + that are delivered to the callback. + + >>> with callback_iter(func) as it: + ... for args, kwargs in it: + ... print(args) + (1, 'a') + (2, 'b') + (3, 'c') + + The function will be called in a background thread. The ``done`` property + indicates whether it has completed execution. + + >>> it.done + True + + If it completes successfully, its return value will be available + in the ``result`` property. + + >>> it.result + 4 + + Notes: + + * If the function uses some keyword argument besides ``callback``, supply + *callback_kwd*. + * If it finished executing, but raised an exception, accessing the + ``result`` property will raise the same exception. + * If it hasn't finished executing, accessing the ``result`` + property from within the ``with`` block will raise ``RuntimeError``. + * If it hasn't finished executing, accessing the ``result`` property from + outside the ``with`` block will raise a + ``more_itertools.AbortThread`` exception. + * Provide *wait_seconds* to adjust how frequently the it is polled for + output. + + """ + + def __init__(self, func, callback_kwd='callback', wait_seconds=0.1): + self._func = func + self._callback_kwd = callback_kwd + self._aborted = False + self._future = None + self._wait_seconds = wait_seconds + # Lazily import concurrent.future + self._executor = __import__( + 'concurrent.futures' + ).futures.ThreadPoolExecutor(max_workers=1) + self._iterator = self._reader() + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + self._aborted = True + self._executor.shutdown() + + def __iter__(self): + return self + + def __next__(self): + return next(self._iterator) + + @property + def done(self): + if self._future is None: + return False + return self._future.done() + + @property + def result(self): + if not self.done: + raise RuntimeError('Function has not yet completed') + + return self._future.result() + + def _reader(self): + q = Queue() + + def callback(*args, **kwargs): + if self._aborted: + raise AbortThread('canceled by user') + + q.put((args, kwargs)) + + self._future = self._executor.submit( + self._func, **{self._callback_kwd: callback} + ) + + while True: + try: + item = q.get(timeout=self._wait_seconds) + except Empty: + pass + else: + q.task_done() + yield item + + if self._future.done(): + break + + remaining = [] + while True: + try: + item = q.get_nowait() + except Empty: + break + else: + q.task_done() + remaining.append(item) + q.join() + yield from remaining + + +def windowed_complete(iterable, n): + """ + Yield ``(beginning, middle, end)`` tuples, where: + + * Each ``middle`` has *n* items from *iterable* + * Each ``beginning`` has the items before the ones in ``middle`` + * Each ``end`` has the items after the ones in ``middle`` + + >>> iterable = range(7) + >>> n = 3 + >>> for beginning, middle, end in windowed_complete(iterable, n): + ... print(beginning, middle, end) + () (0, 1, 2) (3, 4, 5, 6) + (0,) (1, 2, 3) (4, 5, 6) + (0, 1) (2, 3, 4) (5, 6) + (0, 1, 2) (3, 4, 5) (6,) + (0, 1, 2, 3) (4, 5, 6) () + + Note that *n* must be at least 0 and most equal to the length of + *iterable*. + + This function will exhaust the iterable and may require significant + storage. + """ + if n < 0: + raise ValueError('n must be >= 0') + + seq = tuple(iterable) + size = len(seq) + + if n > size: + raise ValueError('n must be <= len(seq)') + + for i in range(size - n + 1): + beginning = seq[:i] + middle = seq[i : i + n] + end = seq[i + n :] + yield beginning, middle, end + + +def all_unique(iterable, key=None): + """ + Returns ``True`` if all the elements of *iterable* are unique (no two + elements are equal). + + >>> all_unique('ABCB') + False + + If a *key* function is specified, it will be used to make comparisons. + + >>> all_unique('ABCb') + True + >>> all_unique('ABCb', str.lower) + False + + The function returns as soon as the first non-unique element is + encountered. Iterables with a mix of hashable and unhashable items can + be used, but the function will be slower for unhashable items. + """ + seenset = set() + seenset_add = seenset.add + seenlist = [] + seenlist_add = seenlist.append + for element in map(key, iterable) if key else iterable: + try: + if element in seenset: + return False + seenset_add(element) + except TypeError: + if element in seenlist: + return False + seenlist_add(element) + return True + + +def nth_product(index, *args): + """Equivalent to ``list(product(*args))[index]``. + + The products of *args* can be ordered lexicographically. + :func:`nth_product` computes the product at sort position *index* without + computing the previous products. + + >>> nth_product(8, range(2), range(2), range(2), range(2)) + (1, 0, 0, 0) + + ``IndexError`` will be raised if the given *index* is invalid. + """ + pools = list(map(tuple, reversed(args))) + ns = list(map(len, pools)) + + c = reduce(mul, ns) + + if index < 0: + index += c + + if not 0 <= index < c: + raise IndexError + + result = [] + for pool, n in zip(pools, ns): + result.append(pool[index % n]) + index //= n + + return tuple(reversed(result)) + + +def nth_permutation(iterable, r, index): + """Equivalent to ``list(permutations(iterable, r))[index]``` + + The subsequences of *iterable* that are of length *r* where order is + important can be ordered lexicographically. :func:`nth_permutation` + computes the subsequence at sort position *index* directly, without + computing the previous subsequences. + + >>> nth_permutation('ghijk', 2, 5) + ('h', 'i') + + ``ValueError`` will be raised If *r* is negative or greater than the length + of *iterable*. + ``IndexError`` will be raised if the given *index* is invalid. + """ + pool = list(iterable) + n = len(pool) + + if r is None or r == n: + r, c = n, factorial(n) + elif not 0 <= r < n: + raise ValueError + else: + c = perm(n, r) + assert c > 0 # factortial(n)>0, and r>> nth_combination_with_replacement(range(5), 3, 5) + (0, 1, 1) + + ``ValueError`` will be raised If *r* is negative or greater than the length + of *iterable*. + ``IndexError`` will be raised if the given *index* is invalid. + """ + pool = tuple(iterable) + n = len(pool) + if (r < 0) or (r > n): + raise ValueError + + c = comb(n + r - 1, r) + + if index < 0: + index += c + + if (index < 0) or (index >= c): + raise IndexError + + result = [] + i = 0 + while r: + r -= 1 + while n >= 0: + num_combs = comb(n + r - 1, r) + if index < num_combs: + break + n -= 1 + i += 1 + index -= num_combs + result.append(pool[i]) + + return tuple(result) + + +def value_chain(*args): + """Yield all arguments passed to the function in the same order in which + they were passed. If an argument itself is iterable then iterate over its + values. + + >>> list(value_chain(1, 2, 3, [4, 5, 6])) + [1, 2, 3, 4, 5, 6] + + Binary and text strings are not considered iterable and are emitted + as-is: + + >>> list(value_chain('12', '34', ['56', '78'])) + ['12', '34', '56', '78'] + + Pre- or postpend a single element to an iterable: + + >>> list(value_chain(1, [2, 3, 4, 5, 6])) + [1, 2, 3, 4, 5, 6] + >>> list(value_chain([1, 2, 3, 4, 5], 6)) + [1, 2, 3, 4, 5, 6] + + Multiple levels of nesting are not flattened. + + """ + for value in args: + if isinstance(value, (str, bytes)): + yield value + continue + try: + yield from value + except TypeError: + yield value + + +def product_index(element, *args): + """Equivalent to ``list(product(*args)).index(element)`` + + The products of *args* can be ordered lexicographically. + :func:`product_index` computes the first index of *element* without + computing the previous products. + + >>> product_index([8, 2], range(10), range(5)) + 42 + + ``ValueError`` will be raised if the given *element* isn't in the product + of *args*. + """ + index = 0 + + for x, pool in zip_longest(element, args, fillvalue=_marker): + if x is _marker or pool is _marker: + raise ValueError('element is not a product of args') + + pool = tuple(pool) + index = index * len(pool) + pool.index(x) + + return index + + +def combination_index(element, iterable): + """Equivalent to ``list(combinations(iterable, r)).index(element)`` + + The subsequences of *iterable* that are of length *r* can be ordered + lexicographically. :func:`combination_index` computes the index of the + first *element*, without computing the previous combinations. + + >>> combination_index('adf', 'abcdefg') + 10 + + ``ValueError`` will be raised if the given *element* isn't one of the + combinations of *iterable*. + """ + element = enumerate(element) + k, y = next(element, (None, None)) + if k is None: + return 0 + + indexes = [] + pool = enumerate(iterable) + for n, x in pool: + if x == y: + indexes.append(n) + tmp, y = next(element, (None, None)) + if tmp is None: + break + else: + k = tmp + else: + raise ValueError('element is not a combination of iterable') + + n, _ = last(pool, default=(n, None)) + + # Python versions below 3.8 don't have math.comb + index = 1 + for i, j in enumerate(reversed(indexes), start=1): + j = n - j + if i <= j: + index += comb(j, i) + + return comb(n + 1, k + 1) - index + + +def combination_with_replacement_index(element, iterable): + """Equivalent to + ``list(combinations_with_replacement(iterable, r)).index(element)`` + + The subsequences with repetition of *iterable* that are of length *r* can + be ordered lexicographically. :func:`combination_with_replacement_index` + computes the index of the first *element*, without computing the previous + combinations with replacement. + + >>> combination_with_replacement_index('adf', 'abcdefg') + 20 + + ``ValueError`` will be raised if the given *element* isn't one of the + combinations with replacement of *iterable*. + """ + element = tuple(element) + l = len(element) + element = enumerate(element) + + k, y = next(element, (None, None)) + if k is None: + return 0 + + indexes = [] + pool = tuple(iterable) + for n, x in enumerate(pool): + while x == y: + indexes.append(n) + tmp, y = next(element, (None, None)) + if tmp is None: + break + else: + k = tmp + if y is None: + break + else: + raise ValueError( + 'element is not a combination with replacement of iterable' + ) + + n = len(pool) + occupations = [0] * n + for p in indexes: + occupations[p] += 1 + + index = 0 + cumulative_sum = 0 + for k in range(1, n): + cumulative_sum += occupations[k - 1] + j = l + n - 1 - k - cumulative_sum + i = n - k + if i <= j: + index += comb(j, i) + + return index + + +def permutation_index(element, iterable): + """Equivalent to ``list(permutations(iterable, r)).index(element)``` + + The subsequences of *iterable* that are of length *r* where order is + important can be ordered lexicographically. :func:`permutation_index` + computes the index of the first *element* directly, without computing + the previous permutations. + + >>> permutation_index([1, 3, 2], range(5)) + 19 + + ``ValueError`` will be raised if the given *element* isn't one of the + permutations of *iterable*. + """ + index = 0 + pool = list(iterable) + for i, x in zip(range(len(pool), -1, -1), element): + r = pool.index(x) + index = index * i + r + del pool[r] + + return index + + +class countable: + """Wrap *iterable* and keep a count of how many items have been consumed. + + The ``items_seen`` attribute starts at ``0`` and increments as the iterable + is consumed: + + >>> iterable = map(str, range(10)) + >>> it = countable(iterable) + >>> it.items_seen + 0 + >>> next(it), next(it) + ('0', '1') + >>> list(it) + ['2', '3', '4', '5', '6', '7', '8', '9'] + >>> it.items_seen + 10 + """ + + def __init__(self, iterable): + self._it = iter(iterable) + self.items_seen = 0 + + def __iter__(self): + return self + + def __next__(self): + item = next(self._it) + self.items_seen += 1 + + return item + + +def chunked_even(iterable, n): + """Break *iterable* into lists of approximately length *n*. + Items are distributed such the lengths of the lists differ by at most + 1 item. + + >>> iterable = [1, 2, 3, 4, 5, 6, 7] + >>> n = 3 + >>> list(chunked_even(iterable, n)) # List lengths: 3, 2, 2 + [[1, 2, 3], [4, 5], [6, 7]] + >>> list(chunked(iterable, n)) # List lengths: 3, 3, 1 + [[1, 2, 3], [4, 5, 6], [7]] + + """ + iterable = iter(iterable) + + # Initialize a buffer to process the chunks while keeping + # some back to fill any underfilled chunks + min_buffer = (n - 1) * (n - 2) + buffer = list(islice(iterable, min_buffer)) + + # Append items until we have a completed chunk + for _ in islice(map(buffer.append, iterable), n, None, n): + yield buffer[:n] + del buffer[:n] + + # Check if any chunks need addition processing + if not buffer: + return + length = len(buffer) + + # Chunks are either size `full_size <= n` or `partial_size = full_size - 1` + q, r = divmod(length, n) + num_lists = q + (1 if r > 0 else 0) + q, r = divmod(length, num_lists) + full_size = q + (1 if r > 0 else 0) + partial_size = full_size - 1 + num_full = length - partial_size * num_lists + + # Yield chunks of full size + partial_start_idx = num_full * full_size + if full_size > 0: + for i in range(0, partial_start_idx, full_size): + yield buffer[i : i + full_size] + + # Yield chunks of partial size + if partial_size > 0: + for i in range(partial_start_idx, length, partial_size): + yield buffer[i : i + partial_size] + + +def zip_broadcast(*objects, scalar_types=(str, bytes), strict=False): + """A version of :func:`zip` that "broadcasts" any scalar + (i.e., non-iterable) items into output tuples. + + >>> iterable_1 = [1, 2, 3] + >>> iterable_2 = ['a', 'b', 'c'] + >>> scalar = '_' + >>> list(zip_broadcast(iterable_1, iterable_2, scalar)) + [(1, 'a', '_'), (2, 'b', '_'), (3, 'c', '_')] + + The *scalar_types* keyword argument determines what types are considered + scalar. It is set to ``(str, bytes)`` by default. Set it to ``None`` to + treat strings and byte strings as iterable: + + >>> list(zip_broadcast('abc', 0, 'xyz', scalar_types=None)) + [('a', 0, 'x'), ('b', 0, 'y'), ('c', 0, 'z')] + + If the *strict* keyword argument is ``True``, then + ``UnequalIterablesError`` will be raised if any of the iterables have + different lengths. + """ + + def is_scalar(obj): + if scalar_types and isinstance(obj, scalar_types): + return True + try: + iter(obj) + except TypeError: + return True + else: + return False + + size = len(objects) + if not size: + return + + new_item = [None] * size + iterables, iterable_positions = [], [] + for i, obj in enumerate(objects): + if is_scalar(obj): + new_item[i] = obj + else: + iterables.append(iter(obj)) + iterable_positions.append(i) + + if not iterables: + yield tuple(objects) + return + + zipper = _zip_equal if strict else zip + for item in zipper(*iterables): + for i, new_item[i] in zip(iterable_positions, item): + pass + yield tuple(new_item) + + +def unique_in_window(iterable, n, key=None): + """Yield the items from *iterable* that haven't been seen recently. + *n* is the size of the lookback window. + + >>> iterable = [0, 1, 0, 2, 3, 0] + >>> n = 3 + >>> list(unique_in_window(iterable, n)) + [0, 1, 2, 3, 0] + + The *key* function, if provided, will be used to determine uniqueness: + + >>> list(unique_in_window('abAcda', 3, key=lambda x: x.lower())) + ['a', 'b', 'c', 'd', 'a'] + + The items in *iterable* must be hashable. + + """ + if n <= 0: + raise ValueError('n must be greater than 0') + + window = deque(maxlen=n) + counts = defaultdict(int) + use_key = key is not None + + for item in iterable: + if len(window) == n: + to_discard = window[0] + if counts[to_discard] == 1: + del counts[to_discard] + else: + counts[to_discard] -= 1 + + k = key(item) if use_key else item + if k not in counts: + yield item + counts[k] += 1 + window.append(k) + + +def duplicates_everseen(iterable, key=None): + """Yield duplicate elements after their first appearance. + + >>> list(duplicates_everseen('mississippi')) + ['s', 'i', 's', 's', 'i', 'p', 'i'] + >>> list(duplicates_everseen('AaaBbbCccAaa', str.lower)) + ['a', 'a', 'b', 'b', 'c', 'c', 'A', 'a', 'a'] + + This function is analogous to :func:`unique_everseen` and is subject to + the same performance considerations. + + """ + seen_set = set() + seen_list = [] + use_key = key is not None + + for element in iterable: + k = key(element) if use_key else element + try: + if k not in seen_set: + seen_set.add(k) + else: + yield element + except TypeError: + if k not in seen_list: + seen_list.append(k) + else: + yield element + + +def duplicates_justseen(iterable, key=None): + """Yields serially-duplicate elements after their first appearance. + + >>> list(duplicates_justseen('mississippi')) + ['s', 's', 'p'] + >>> list(duplicates_justseen('AaaBbbCccAaa', str.lower)) + ['a', 'a', 'b', 'b', 'c', 'c', 'a', 'a'] + + This function is analogous to :func:`unique_justseen`. + + """ + return flatten(g for _, g in groupby(iterable, key) for _ in g) + + +def classify_unique(iterable, key=None): + """Classify each element in terms of its uniqueness. + + For each element in the input iterable, return a 3-tuple consisting of: + + 1. The element itself + 2. ``False`` if the element is equal to the one preceding it in the input, + ``True`` otherwise (i.e. the equivalent of :func:`unique_justseen`) + 3. ``False`` if this element has been seen anywhere in the input before, + ``True`` otherwise (i.e. the equivalent of :func:`unique_everseen`) + + >>> list(classify_unique('otto')) # doctest: +NORMALIZE_WHITESPACE + [('o', True, True), + ('t', True, True), + ('t', False, False), + ('o', True, False)] + + This function is analogous to :func:`unique_everseen` and is subject to + the same performance considerations. + + """ + seen_set = set() + seen_list = [] + use_key = key is not None + previous = None + + for i, element in enumerate(iterable): + k = key(element) if use_key else element + is_unique_justseen = not i or previous != k + previous = k + is_unique_everseen = False + try: + if k not in seen_set: + seen_set.add(k) + is_unique_everseen = True + except TypeError: + if k not in seen_list: + seen_list.append(k) + is_unique_everseen = True + yield element, is_unique_justseen, is_unique_everseen + + +def minmax(iterable_or_value, *others, key=None, default=_marker): + """Returns both the smallest and largest items in an iterable + or the largest of two or more arguments. + + >>> minmax([3, 1, 5]) + (1, 5) + + >>> minmax(4, 2, 6) + (2, 6) + + If a *key* function is provided, it will be used to transform the input + items for comparison. + + >>> minmax([5, 30], key=str) # '30' sorts before '5' + (30, 5) + + If a *default* value is provided, it will be returned if there are no + input items. + + >>> minmax([], default=(0, 0)) + (0, 0) + + Otherwise ``ValueError`` is raised. + + This function is based on the + `recipe `__ by + Raymond Hettinger and takes care to minimize the number of comparisons + performed. + """ + iterable = (iterable_or_value, *others) if others else iterable_or_value + + it = iter(iterable) + + try: + lo = hi = next(it) + except StopIteration as exc: + if default is _marker: + raise ValueError( + '`minmax()` argument is an empty iterable. ' + 'Provide a `default` value to suppress this error.' + ) from exc + return default + + # Different branches depending on the presence of key. This saves a lot + # of unimportant copies which would slow the "key=None" branch + # significantly down. + if key is None: + for x, y in zip_longest(it, it, fillvalue=lo): + if y < x: + x, y = y, x + if x < lo: + lo = x + if hi < y: + hi = y + + else: + lo_key = hi_key = key(lo) + + for x, y in zip_longest(it, it, fillvalue=lo): + x_key, y_key = key(x), key(y) + + if y_key < x_key: + x, y, x_key, y_key = y, x, y_key, x_key + if x_key < lo_key: + lo, lo_key = x, x_key + if hi_key < y_key: + hi, hi_key = y, y_key + + return lo, hi + + +def constrained_batches( + iterable, max_size, max_count=None, get_len=len, strict=True +): + """Yield batches of items from *iterable* with a combined size limited by + *max_size*. + + >>> iterable = [b'12345', b'123', b'12345678', b'1', b'1', b'12', b'1'] + >>> list(constrained_batches(iterable, 10)) + [(b'12345', b'123'), (b'12345678', b'1', b'1'), (b'12', b'1')] + + If a *max_count* is supplied, the number of items per batch is also + limited: + + >>> iterable = [b'12345', b'123', b'12345678', b'1', b'1', b'12', b'1'] + >>> list(constrained_batches(iterable, 10, max_count = 2)) + [(b'12345', b'123'), (b'12345678', b'1'), (b'1', b'12'), (b'1',)] + + If a *get_len* function is supplied, use that instead of :func:`len` to + determine item size. + + If *strict* is ``True``, raise ``ValueError`` if any single item is bigger + than *max_size*. Otherwise, allow single items to exceed *max_size*. + """ + if max_size <= 0: + raise ValueError('maximum size must be greater than zero') + + batch = [] + batch_size = 0 + batch_count = 0 + for item in iterable: + item_len = get_len(item) + if strict and item_len > max_size: + raise ValueError('item size exceeds maximum size') + + reached_count = batch_count == max_count + reached_size = item_len + batch_size > max_size + if batch_count and (reached_size or reached_count): + yield tuple(batch) + batch.clear() + batch_size = 0 + batch_count = 0 + + batch.append(item) + batch_size += item_len + batch_count += 1 + + if batch: + yield tuple(batch) + + +def gray_product(*iterables): + """Like :func:`itertools.product`, but return tuples in an order such + that only one element in the generated tuple changes from one iteration + to the next. + + >>> list(gray_product('AB','CD')) + [('A', 'C'), ('B', 'C'), ('B', 'D'), ('A', 'D')] + + This function consumes all of the input iterables before producing output. + If any of the input iterables have fewer than two items, ``ValueError`` + is raised. + + For information on the algorithm, see + `this section `__ + of Donald Knuth's *The Art of Computer Programming*. + """ + all_iterables = tuple(tuple(x) for x in iterables) + iterable_count = len(all_iterables) + for iterable in all_iterables: + if len(iterable) < 2: + raise ValueError("each iterable must have two or more items") + + # This is based on "Algorithm H" from section 7.2.1.1, page 20. + # a holds the indexes of the source iterables for the n-tuple to be yielded + # f is the array of "focus pointers" + # o is the array of "directions" + a = [0] * iterable_count + f = list(range(iterable_count + 1)) + o = [1] * iterable_count + while True: + yield tuple(all_iterables[i][a[i]] for i in range(iterable_count)) + j = f[0] + f[0] = 0 + if j == iterable_count: + break + a[j] = a[j] + o[j] + if a[j] == 0 or a[j] == len(all_iterables[j]) - 1: + o[j] = -o[j] + f[j] = f[j + 1] + f[j + 1] = j + 1 + + +def partial_product(*iterables): + """Yields tuples containing one item from each iterator, with subsequent + tuples changing a single item at a time by advancing each iterator until it + is exhausted. This sequence guarantees every value in each iterable is + output at least once without generating all possible combinations. + + This may be useful, for example, when testing an expensive function. + + >>> list(partial_product('AB', 'C', 'DEF')) + [('A', 'C', 'D'), ('B', 'C', 'D'), ('B', 'C', 'E'), ('B', 'C', 'F')] + """ + + iterators = list(map(iter, iterables)) + + try: + prod = [next(it) for it in iterators] + except StopIteration: + return + yield tuple(prod) + + for i, it in enumerate(iterators): + for prod[i] in it: + yield tuple(prod) + + +def takewhile_inclusive(predicate, iterable): + """A variant of :func:`takewhile` that yields one additional element. + + >>> list(takewhile_inclusive(lambda x: x < 5, [1, 4, 6, 4, 1])) + [1, 4, 6] + + :func:`takewhile` would return ``[1, 4]``. + """ + for x in iterable: + yield x + if not predicate(x): + break + + +def outer_product(func, xs, ys, *args, **kwargs): + """A generalized outer product that applies a binary function to all + pairs of items. Returns a 2D matrix with ``len(xs)`` rows and ``len(ys)`` + columns. + Also accepts ``*args`` and ``**kwargs`` that are passed to ``func``. + + Multiplication table: + + >>> list(outer_product(mul, range(1, 4), range(1, 6))) + [(1, 2, 3, 4, 5), (2, 4, 6, 8, 10), (3, 6, 9, 12, 15)] + + Cross tabulation: + + >>> xs = ['A', 'B', 'A', 'A', 'B', 'B', 'A', 'A', 'B', 'B'] + >>> ys = ['X', 'X', 'X', 'Y', 'Z', 'Z', 'Y', 'Y', 'Z', 'Z'] + >>> rows = list(zip(xs, ys)) + >>> count_rows = lambda x, y: rows.count((x, y)) + >>> list(outer_product(count_rows, sorted(set(xs)), sorted(set(ys)))) + [(2, 3, 0), (1, 0, 4)] + + Usage with ``*args`` and ``**kwargs``: + + >>> animals = ['cat', 'wolf', 'mouse'] + >>> list(outer_product(min, animals, animals, key=len)) + [('cat', 'cat', 'cat'), ('cat', 'wolf', 'wolf'), ('cat', 'wolf', 'mouse')] + """ + ys = tuple(ys) + return batched( + starmap(lambda x, y: func(x, y, *args, **kwargs), product(xs, ys)), + n=len(ys), + ) + + +def iter_suppress(iterable, *exceptions): + """Yield each of the items from *iterable*. If the iteration raises one of + the specified *exceptions*, that exception will be suppressed and iteration + will stop. + + >>> from itertools import chain + >>> def breaks_at_five(x): + ... while True: + ... if x >= 5: + ... raise RuntimeError + ... yield x + ... x += 1 + >>> it_1 = iter_suppress(breaks_at_five(1), RuntimeError) + >>> it_2 = iter_suppress(breaks_at_five(2), RuntimeError) + >>> list(chain(it_1, it_2)) + [1, 2, 3, 4, 2, 3, 4] + """ + try: + yield from iterable + except exceptions: + return + + +def filter_map(func, iterable): + """Apply *func* to every element of *iterable*, yielding only those which + are not ``None``. + + >>> elems = ['1', 'a', '2', 'b', '3'] + >>> list(filter_map(lambda s: int(s) if s.isnumeric() else None, elems)) + [1, 2, 3] + """ + for x in iterable: + y = func(x) + if y is not None: + yield y + + +def powerset_of_sets(iterable): + """Yields all possible subsets of the iterable. + + >>> list(powerset_of_sets([1, 2, 3])) # doctest: +SKIP + [set(), {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}] + >>> list(powerset_of_sets([1, 1, 0])) # doctest: +SKIP + [set(), {1}, {0}, {0, 1}] + + :func:`powerset_of_sets` takes care to minimize the number + of hash operations performed. + """ + sets = tuple(map(set, dict.fromkeys(map(frozenset, zip(iterable))))) + for r in range(len(sets) + 1): + yield from starmap(set().union, combinations(sets, r)) + + +def join_mappings(**field_to_map): + """ + Joins multiple mappings together using their common keys. + + >>> user_scores = {'elliot': 50, 'claris': 60} + >>> user_times = {'elliot': 30, 'claris': 40} + >>> join_mappings(score=user_scores, time=user_times) + {'elliot': {'score': 50, 'time': 30}, 'claris': {'score': 60, 'time': 40}} + """ + ret = defaultdict(dict) + + for field_name, mapping in field_to_map.items(): + for key, value in mapping.items(): + ret[key][field_name] = value + + return dict(ret) + + +def _complex_sumprod(v1, v2): + """High precision sumprod() for complex numbers. + Used by :func:`dft` and :func:`idft`. + """ + + r1 = chain((p.real for p in v1), (-p.imag for p in v1)) + r2 = chain((q.real for q in v2), (q.imag for q in v2)) + i1 = chain((p.real for p in v1), (p.imag for p in v1)) + i2 = chain((q.imag for q in v2), (q.real for q in v2)) + return complex(_fsumprod(r1, r2), _fsumprod(i1, i2)) + + +def dft(xarr): + """Discrete Fourier Tranform. *xarr* is a sequence of complex numbers. + Yields the components of the corresponding transformed output vector. + + >>> import cmath + >>> xarr = [1, 2-1j, -1j, -1+2j] + >>> Xarr = [2, -2-2j, -2j, 4+4j] + >>> all(map(cmath.isclose, dft(xarr), Xarr)) + True + + See :func:`idft` for the inverse Discrete Fourier Transform. + """ + N = len(xarr) + roots_of_unity = [e ** (n / N * tau * -1j) for n in range(N)] + for k in range(N): + coeffs = [roots_of_unity[k * n % N] for n in range(N)] + yield _complex_sumprod(xarr, coeffs) + + +def idft(Xarr): + """Inverse Discrete Fourier Tranform. *Xarr* is a sequence of + complex numbers. Yields the components of the corresponding + inverse-transformed output vector. + + >>> import cmath + >>> xarr = [1, 2-1j, -1j, -1+2j] + >>> Xarr = [2, -2-2j, -2j, 4+4j] + >>> all(map(cmath.isclose, idft(Xarr), xarr)) + True + + See :func:`dft` for the Discrete Fourier Transform. + """ + N = len(Xarr) + roots_of_unity = [e ** (n / N * tau * 1j) for n in range(N)] + for k in range(N): + coeffs = [roots_of_unity[k * n % N] for n in range(N)] + yield _complex_sumprod(Xarr, coeffs) / N + + +def doublestarmap(func, iterable): + """Apply *func* to every item of *iterable* by dictionary unpacking + the item into *func*. + + The difference between :func:`itertools.starmap` and :func:`doublestarmap` + parallels the distinction between ``func(*a)`` and ``func(**a)``. + + >>> iterable = [{'a': 1, 'b': 2}, {'a': 40, 'b': 60}] + >>> list(doublestarmap(lambda a, b: a + b, iterable)) + [3, 100] + + ``TypeError`` will be raised if *func*'s signature doesn't match the + mapping contained in *iterable* or if *iterable* does not contain mappings. + """ + for item in iterable: + yield func(**item) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools/more.pyi b/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools/more.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e94602325935c27066f916356b8b8a3e180e8b6f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools/more.pyi @@ -0,0 +1,709 @@ +"""Stubs for more_itertools.more""" + +from __future__ import annotations + +from types import TracebackType +from typing import ( + Any, + Callable, + Container, + ContextManager, + Generic, + Hashable, + Mapping, + Iterable, + Iterator, + Mapping, + overload, + Reversible, + Sequence, + Sized, + Type, + TypeVar, + type_check_only, +) +from typing_extensions import Protocol + +# Type and type variable definitions +_T = TypeVar('_T') +_T1 = TypeVar('_T1') +_T2 = TypeVar('_T2') +_U = TypeVar('_U') +_V = TypeVar('_V') +_W = TypeVar('_W') +_T_co = TypeVar('_T_co', covariant=True) +_GenFn = TypeVar('_GenFn', bound=Callable[..., Iterator[Any]]) +_Raisable = BaseException | Type[BaseException] + +@type_check_only +class _SizedIterable(Protocol[_T_co], Sized, Iterable[_T_co]): ... + +@type_check_only +class _SizedReversible(Protocol[_T_co], Sized, Reversible[_T_co]): ... + +@type_check_only +class _SupportsSlicing(Protocol[_T_co]): + def __getitem__(self, __k: slice) -> _T_co: ... + +def chunked( + iterable: Iterable[_T], n: int | None, strict: bool = ... +) -> Iterator[list[_T]]: ... +@overload +def first(iterable: Iterable[_T]) -> _T: ... +@overload +def first(iterable: Iterable[_T], default: _U) -> _T | _U: ... +@overload +def last(iterable: Iterable[_T]) -> _T: ... +@overload +def last(iterable: Iterable[_T], default: _U) -> _T | _U: ... +@overload +def nth_or_last(iterable: Iterable[_T], n: int) -> _T: ... +@overload +def nth_or_last(iterable: Iterable[_T], n: int, default: _U) -> _T | _U: ... + +class peekable(Generic[_T], Iterator[_T]): + def __init__(self, iterable: Iterable[_T]) -> None: ... + def __iter__(self) -> peekable[_T]: ... + def __bool__(self) -> bool: ... + @overload + def peek(self) -> _T: ... + @overload + def peek(self, default: _U) -> _T | _U: ... + def prepend(self, *items: _T) -> None: ... + def __next__(self) -> _T: ... + @overload + def __getitem__(self, index: int) -> _T: ... + @overload + def __getitem__(self, index: slice) -> list[_T]: ... + +def consumer(func: _GenFn) -> _GenFn: ... +def ilen(iterable: Iterable[_T]) -> int: ... +def iterate(func: Callable[[_T], _T], start: _T) -> Iterator[_T]: ... +def with_iter( + context_manager: ContextManager[Iterable[_T]], +) -> Iterator[_T]: ... +def one( + iterable: Iterable[_T], + too_short: _Raisable | None = ..., + too_long: _Raisable | None = ..., +) -> _T: ... +def raise_(exception: _Raisable, *args: Any) -> None: ... +def strictly_n( + iterable: Iterable[_T], + n: int, + too_short: _GenFn | None = ..., + too_long: _GenFn | None = ..., +) -> list[_T]: ... +def distinct_permutations( + iterable: Iterable[_T], r: int | None = ... +) -> Iterator[tuple[_T, ...]]: ... +def intersperse( + e: _U, iterable: Iterable[_T], n: int = ... +) -> Iterator[_T | _U]: ... +def unique_to_each(*iterables: Iterable[_T]) -> list[list[_T]]: ... +@overload +def windowed( + seq: Iterable[_T], n: int, *, step: int = ... +) -> Iterator[tuple[_T | None, ...]]: ... +@overload +def windowed( + seq: Iterable[_T], n: int, fillvalue: _U, step: int = ... +) -> Iterator[tuple[_T | _U, ...]]: ... +def substrings(iterable: Iterable[_T]) -> Iterator[tuple[_T, ...]]: ... +def substrings_indexes( + seq: Sequence[_T], reverse: bool = ... +) -> Iterator[tuple[Sequence[_T], int, int]]: ... + +class bucket(Generic[_T, _U], Container[_U]): + def __init__( + self, + iterable: Iterable[_T], + key: Callable[[_T], _U], + validator: Callable[[_U], object] | None = ..., + ) -> None: ... + def __contains__(self, value: object) -> bool: ... + def __iter__(self) -> Iterator[_U]: ... + def __getitem__(self, value: object) -> Iterator[_T]: ... + +def spy( + iterable: Iterable[_T], n: int = ... +) -> tuple[list[_T], Iterator[_T]]: ... +def interleave(*iterables: Iterable[_T]) -> Iterator[_T]: ... +def interleave_longest(*iterables: Iterable[_T]) -> Iterator[_T]: ... +def interleave_evenly( + iterables: list[Iterable[_T]], lengths: list[int] | None = ... +) -> Iterator[_T]: ... +def collapse( + iterable: Iterable[Any], + base_type: type | None = ..., + levels: int | None = ..., +) -> Iterator[Any]: ... +@overload +def side_effect( + func: Callable[[_T], object], + iterable: Iterable[_T], + chunk_size: None = ..., + before: Callable[[], object] | None = ..., + after: Callable[[], object] | None = ..., +) -> Iterator[_T]: ... +@overload +def side_effect( + func: Callable[[list[_T]], object], + iterable: Iterable[_T], + chunk_size: int, + before: Callable[[], object] | None = ..., + after: Callable[[], object] | None = ..., +) -> Iterator[_T]: ... +def sliced( + seq: _SupportsSlicing[_T], n: int, strict: bool = ... +) -> Iterator[_T]: ... +def split_at( + iterable: Iterable[_T], + pred: Callable[[_T], object], + maxsplit: int = ..., + keep_separator: bool = ..., +) -> Iterator[list[_T]]: ... +def split_before( + iterable: Iterable[_T], pred: Callable[[_T], object], maxsplit: int = ... +) -> Iterator[list[_T]]: ... +def split_after( + iterable: Iterable[_T], pred: Callable[[_T], object], maxsplit: int = ... +) -> Iterator[list[_T]]: ... +def split_when( + iterable: Iterable[_T], + pred: Callable[[_T, _T], object], + maxsplit: int = ..., +) -> Iterator[list[_T]]: ... +def split_into( + iterable: Iterable[_T], sizes: Iterable[int | None] +) -> Iterator[list[_T]]: ... +@overload +def padded( + iterable: Iterable[_T], + *, + n: int | None = ..., + next_multiple: bool = ..., +) -> Iterator[_T | None]: ... +@overload +def padded( + iterable: Iterable[_T], + fillvalue: _U, + n: int | None = ..., + next_multiple: bool = ..., +) -> Iterator[_T | _U]: ... +@overload +def repeat_last(iterable: Iterable[_T]) -> Iterator[_T]: ... +@overload +def repeat_last(iterable: Iterable[_T], default: _U) -> Iterator[_T | _U]: ... +def distribute(n: int, iterable: Iterable[_T]) -> list[Iterator[_T]]: ... +@overload +def stagger( + iterable: Iterable[_T], + offsets: _SizedIterable[int] = ..., + longest: bool = ..., +) -> Iterator[tuple[_T | None, ...]]: ... +@overload +def stagger( + iterable: Iterable[_T], + offsets: _SizedIterable[int] = ..., + longest: bool = ..., + fillvalue: _U = ..., +) -> Iterator[tuple[_T | _U, ...]]: ... + +class UnequalIterablesError(ValueError): + def __init__(self, details: tuple[int, int, int] | None = ...) -> None: ... + +@overload +def zip_equal(__iter1: Iterable[_T1]) -> Iterator[tuple[_T1]]: ... +@overload +def zip_equal( + __iter1: Iterable[_T1], __iter2: Iterable[_T2] +) -> Iterator[tuple[_T1, _T2]]: ... +@overload +def zip_equal( + __iter1: Iterable[_T], + __iter2: Iterable[_T], + __iter3: Iterable[_T], + *iterables: Iterable[_T], +) -> Iterator[tuple[_T, ...]]: ... +@overload +def zip_offset( + __iter1: Iterable[_T1], + *, + offsets: _SizedIterable[int], + longest: bool = ..., + fillvalue: None = None, +) -> Iterator[tuple[_T1 | None]]: ... +@overload +def zip_offset( + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + *, + offsets: _SizedIterable[int], + longest: bool = ..., + fillvalue: None = None, +) -> Iterator[tuple[_T1 | None, _T2 | None]]: ... +@overload +def zip_offset( + __iter1: Iterable[_T], + __iter2: Iterable[_T], + __iter3: Iterable[_T], + *iterables: Iterable[_T], + offsets: _SizedIterable[int], + longest: bool = ..., + fillvalue: None = None, +) -> Iterator[tuple[_T | None, ...]]: ... +@overload +def zip_offset( + __iter1: Iterable[_T1], + *, + offsets: _SizedIterable[int], + longest: bool = ..., + fillvalue: _U, +) -> Iterator[tuple[_T1 | _U]]: ... +@overload +def zip_offset( + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + *, + offsets: _SizedIterable[int], + longest: bool = ..., + fillvalue: _U, +) -> Iterator[tuple[_T1 | _U, _T2 | _U]]: ... +@overload +def zip_offset( + __iter1: Iterable[_T], + __iter2: Iterable[_T], + __iter3: Iterable[_T], + *iterables: Iterable[_T], + offsets: _SizedIterable[int], + longest: bool = ..., + fillvalue: _U, +) -> Iterator[tuple[_T | _U, ...]]: ... +def sort_together( + iterables: Iterable[Iterable[_T]], + key_list: Iterable[int] = ..., + key: Callable[..., Any] | None = ..., + reverse: bool = ..., +) -> list[tuple[_T, ...]]: ... +def unzip(iterable: Iterable[Sequence[_T]]) -> tuple[Iterator[_T], ...]: ... +def divide(n: int, iterable: Iterable[_T]) -> list[Iterator[_T]]: ... +def always_iterable( + obj: object, + base_type: type | tuple[type | tuple[Any, ...], ...] | None = ..., +) -> Iterator[Any]: ... +def adjacent( + predicate: Callable[[_T], bool], + iterable: Iterable[_T], + distance: int = ..., +) -> Iterator[tuple[bool, _T]]: ... +@overload +def groupby_transform( + iterable: Iterable[_T], + keyfunc: None = None, + valuefunc: None = None, + reducefunc: None = None, +) -> Iterator[tuple[_T, Iterator[_T]]]: ... +@overload +def groupby_transform( + iterable: Iterable[_T], + keyfunc: Callable[[_T], _U], + valuefunc: None, + reducefunc: None, +) -> Iterator[tuple[_U, Iterator[_T]]]: ... +@overload +def groupby_transform( + iterable: Iterable[_T], + keyfunc: None, + valuefunc: Callable[[_T], _V], + reducefunc: None, +) -> Iterable[tuple[_T, Iterable[_V]]]: ... +@overload +def groupby_transform( + iterable: Iterable[_T], + keyfunc: Callable[[_T], _U], + valuefunc: Callable[[_T], _V], + reducefunc: None, +) -> Iterable[tuple[_U, Iterator[_V]]]: ... +@overload +def groupby_transform( + iterable: Iterable[_T], + keyfunc: None, + valuefunc: None, + reducefunc: Callable[[Iterator[_T]], _W], +) -> Iterable[tuple[_T, _W]]: ... +@overload +def groupby_transform( + iterable: Iterable[_T], + keyfunc: Callable[[_T], _U], + valuefunc: None, + reducefunc: Callable[[Iterator[_T]], _W], +) -> Iterable[tuple[_U, _W]]: ... +@overload +def groupby_transform( + iterable: Iterable[_T], + keyfunc: None, + valuefunc: Callable[[_T], _V], + reducefunc: Callable[[Iterable[_V]], _W], +) -> Iterable[tuple[_T, _W]]: ... +@overload +def groupby_transform( + iterable: Iterable[_T], + keyfunc: Callable[[_T], _U], + valuefunc: Callable[[_T], _V], + reducefunc: Callable[[Iterable[_V]], _W], +) -> Iterable[tuple[_U, _W]]: ... + +class numeric_range(Generic[_T, _U], Sequence[_T], Hashable, Reversible[_T]): + @overload + def __init__(self, __stop: _T) -> None: ... + @overload + def __init__(self, __start: _T, __stop: _T) -> None: ... + @overload + def __init__(self, __start: _T, __stop: _T, __step: _U) -> None: ... + def __bool__(self) -> bool: ... + def __contains__(self, elem: object) -> bool: ... + def __eq__(self, other: object) -> bool: ... + @overload + def __getitem__(self, key: int) -> _T: ... + @overload + def __getitem__(self, key: slice) -> numeric_range[_T, _U]: ... + def __hash__(self) -> int: ... + def __iter__(self) -> Iterator[_T]: ... + def __len__(self) -> int: ... + def __reduce__( + self, + ) -> tuple[Type[numeric_range[_T, _U]], tuple[_T, _T, _U]]: ... + def __repr__(self) -> str: ... + def __reversed__(self) -> Iterator[_T]: ... + def count(self, value: _T) -> int: ... + def index(self, value: _T) -> int: ... # type: ignore + +def count_cycle( + iterable: Iterable[_T], n: int | None = ... +) -> Iterable[tuple[int, _T]]: ... +def mark_ends( + iterable: Iterable[_T], +) -> Iterable[tuple[bool, bool, _T]]: ... +def locate( + iterable: Iterable[_T], + pred: Callable[..., Any] = ..., + window_size: int | None = ..., +) -> Iterator[int]: ... +def lstrip( + iterable: Iterable[_T], pred: Callable[[_T], object] +) -> Iterator[_T]: ... +def rstrip( + iterable: Iterable[_T], pred: Callable[[_T], object] +) -> Iterator[_T]: ... +def strip( + iterable: Iterable[_T], pred: Callable[[_T], object] +) -> Iterator[_T]: ... + +class islice_extended(Generic[_T], Iterator[_T]): + def __init__(self, iterable: Iterable[_T], *args: int | None) -> None: ... + def __iter__(self) -> islice_extended[_T]: ... + def __next__(self) -> _T: ... + def __getitem__(self, index: slice) -> islice_extended[_T]: ... + +def always_reversible(iterable: Iterable[_T]) -> Iterator[_T]: ... +def consecutive_groups( + iterable: Iterable[_T], ordering: Callable[[_T], int] = ... +) -> Iterator[Iterator[_T]]: ... +@overload +def difference( + iterable: Iterable[_T], + func: Callable[[_T, _T], _U] = ..., + *, + initial: None = ..., +) -> Iterator[_T | _U]: ... +@overload +def difference( + iterable: Iterable[_T], func: Callable[[_T, _T], _U] = ..., *, initial: _U +) -> Iterator[_U]: ... + +class SequenceView(Generic[_T], Sequence[_T]): + def __init__(self, target: Sequence[_T]) -> None: ... + @overload + def __getitem__(self, index: int) -> _T: ... + @overload + def __getitem__(self, index: slice) -> Sequence[_T]: ... + def __len__(self) -> int: ... + +class seekable(Generic[_T], Iterator[_T]): + def __init__( + self, iterable: Iterable[_T], maxlen: int | None = ... + ) -> None: ... + def __iter__(self) -> seekable[_T]: ... + def __next__(self) -> _T: ... + def __bool__(self) -> bool: ... + @overload + def peek(self) -> _T: ... + @overload + def peek(self, default: _U) -> _T | _U: ... + def elements(self) -> SequenceView[_T]: ... + def seek(self, index: int) -> None: ... + def relative_seek(self, count: int) -> None: ... + +class run_length: + @staticmethod + def encode(iterable: Iterable[_T]) -> Iterator[tuple[_T, int]]: ... + @staticmethod + def decode(iterable: Iterable[tuple[_T, int]]) -> Iterator[_T]: ... + +def exactly_n( + iterable: Iterable[_T], n: int, predicate: Callable[[_T], object] = ... +) -> bool: ... +def circular_shifts(iterable: Iterable[_T]) -> list[tuple[_T, ...]]: ... +def make_decorator( + wrapping_func: Callable[..., _U], result_index: int = ... +) -> Callable[..., Callable[[Callable[..., Any]], Callable[..., _U]]]: ... +@overload +def map_reduce( + iterable: Iterable[_T], + keyfunc: Callable[[_T], _U], + valuefunc: None = ..., + reducefunc: None = ..., +) -> dict[_U, list[_T]]: ... +@overload +def map_reduce( + iterable: Iterable[_T], + keyfunc: Callable[[_T], _U], + valuefunc: Callable[[_T], _V], + reducefunc: None = ..., +) -> dict[_U, list[_V]]: ... +@overload +def map_reduce( + iterable: Iterable[_T], + keyfunc: Callable[[_T], _U], + valuefunc: None = ..., + reducefunc: Callable[[list[_T]], _W] = ..., +) -> dict[_U, _W]: ... +@overload +def map_reduce( + iterable: Iterable[_T], + keyfunc: Callable[[_T], _U], + valuefunc: Callable[[_T], _V], + reducefunc: Callable[[list[_V]], _W], +) -> dict[_U, _W]: ... +def rlocate( + iterable: Iterable[_T], + pred: Callable[..., object] = ..., + window_size: int | None = ..., +) -> Iterator[int]: ... +def replace( + iterable: Iterable[_T], + pred: Callable[..., object], + substitutes: Iterable[_U], + count: int | None = ..., + window_size: int = ..., +) -> Iterator[_T | _U]: ... +def partitions(iterable: Iterable[_T]) -> Iterator[list[list[_T]]]: ... +def set_partitions( + iterable: Iterable[_T], k: int | None = ... +) -> Iterator[list[list[_T]]]: ... + +class time_limited(Generic[_T], Iterator[_T]): + def __init__( + self, limit_seconds: float, iterable: Iterable[_T] + ) -> None: ... + def __iter__(self) -> islice_extended[_T]: ... + def __next__(self) -> _T: ... + +@overload +def only( + iterable: Iterable[_T], *, too_long: _Raisable | None = ... +) -> _T | None: ... +@overload +def only( + iterable: Iterable[_T], default: _U, too_long: _Raisable | None = ... +) -> _T | _U: ... +def ichunked(iterable: Iterable[_T], n: int) -> Iterator[Iterator[_T]]: ... +def distinct_combinations( + iterable: Iterable[_T], r: int +) -> Iterator[tuple[_T, ...]]: ... +def filter_except( + validator: Callable[[Any], object], + iterable: Iterable[_T], + *exceptions: Type[BaseException], +) -> Iterator[_T]: ... +def map_except( + function: Callable[[Any], _U], + iterable: Iterable[_T], + *exceptions: Type[BaseException], +) -> Iterator[_U]: ... +def map_if( + iterable: Iterable[Any], + pred: Callable[[Any], bool], + func: Callable[[Any], Any], + func_else: Callable[[Any], Any] | None = ..., +) -> Iterator[Any]: ... +def sample( + iterable: Iterable[_T], + k: int, + weights: Iterable[float] | None = ..., +) -> list[_T]: ... +def is_sorted( + iterable: Iterable[_T], + key: Callable[[_T], _U] | None = ..., + reverse: bool = False, + strict: bool = False, +) -> bool: ... + +class AbortThread(BaseException): + pass + +class callback_iter(Generic[_T], Iterator[_T]): + def __init__( + self, + func: Callable[..., Any], + callback_kwd: str = ..., + wait_seconds: float = ..., + ) -> None: ... + def __enter__(self) -> callback_iter[_T]: ... + def __exit__( + self, + exc_type: Type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> bool | None: ... + def __iter__(self) -> callback_iter[_T]: ... + def __next__(self) -> _T: ... + def _reader(self) -> Iterator[_T]: ... + @property + def done(self) -> bool: ... + @property + def result(self) -> Any: ... + +def windowed_complete( + iterable: Iterable[_T], n: int +) -> Iterator[tuple[_T, ...]]: ... +def all_unique( + iterable: Iterable[_T], key: Callable[[_T], _U] | None = ... +) -> bool: ... +def nth_product(index: int, *args: Iterable[_T]) -> tuple[_T, ...]: ... +def nth_combination_with_replacement( + iterable: Iterable[_T], r: int, index: int +) -> tuple[_T, ...]: ... +def nth_permutation( + iterable: Iterable[_T], r: int, index: int +) -> tuple[_T, ...]: ... +def value_chain(*args: _T | Iterable[_T]) -> Iterable[_T]: ... +def product_index(element: Iterable[_T], *args: Iterable[_T]) -> int: ... +def combination_index( + element: Iterable[_T], iterable: Iterable[_T] +) -> int: ... +def combination_with_replacement_index( + element: Iterable[_T], iterable: Iterable[_T] +) -> int: ... +def permutation_index( + element: Iterable[_T], iterable: Iterable[_T] +) -> int: ... +def repeat_each(iterable: Iterable[_T], n: int = ...) -> Iterator[_T]: ... + +class countable(Generic[_T], Iterator[_T]): + def __init__(self, iterable: Iterable[_T]) -> None: ... + def __iter__(self) -> countable[_T]: ... + def __next__(self) -> _T: ... + items_seen: int + +def chunked_even(iterable: Iterable[_T], n: int) -> Iterator[list[_T]]: ... +def zip_broadcast( + *objects: _T | Iterable[_T], + scalar_types: type | tuple[type | tuple[Any, ...], ...] | None = ..., + strict: bool = ..., +) -> Iterable[tuple[_T, ...]]: ... +def unique_in_window( + iterable: Iterable[_T], n: int, key: Callable[[_T], _U] | None = ... +) -> Iterator[_T]: ... +def duplicates_everseen( + iterable: Iterable[_T], key: Callable[[_T], _U] | None = ... +) -> Iterator[_T]: ... +def duplicates_justseen( + iterable: Iterable[_T], key: Callable[[_T], _U] | None = ... +) -> Iterator[_T]: ... +def classify_unique( + iterable: Iterable[_T], key: Callable[[_T], _U] | None = ... +) -> Iterator[tuple[_T, bool, bool]]: ... + +class _SupportsLessThan(Protocol): + def __lt__(self, __other: Any) -> bool: ... + +_SupportsLessThanT = TypeVar("_SupportsLessThanT", bound=_SupportsLessThan) + +@overload +def minmax( + iterable_or_value: Iterable[_SupportsLessThanT], *, key: None = None +) -> tuple[_SupportsLessThanT, _SupportsLessThanT]: ... +@overload +def minmax( + iterable_or_value: Iterable[_T], *, key: Callable[[_T], _SupportsLessThan] +) -> tuple[_T, _T]: ... +@overload +def minmax( + iterable_or_value: Iterable[_SupportsLessThanT], + *, + key: None = None, + default: _U, +) -> _U | tuple[_SupportsLessThanT, _SupportsLessThanT]: ... +@overload +def minmax( + iterable_or_value: Iterable[_T], + *, + key: Callable[[_T], _SupportsLessThan], + default: _U, +) -> _U | tuple[_T, _T]: ... +@overload +def minmax( + iterable_or_value: _SupportsLessThanT, + __other: _SupportsLessThanT, + *others: _SupportsLessThanT, +) -> tuple[_SupportsLessThanT, _SupportsLessThanT]: ... +@overload +def minmax( + iterable_or_value: _T, + __other: _T, + *others: _T, + key: Callable[[_T], _SupportsLessThan], +) -> tuple[_T, _T]: ... +def longest_common_prefix( + iterables: Iterable[Iterable[_T]], +) -> Iterator[_T]: ... +def iequals(*iterables: Iterable[Any]) -> bool: ... +def constrained_batches( + iterable: Iterable[_T], + max_size: int, + max_count: int | None = ..., + get_len: Callable[[_T], object] = ..., + strict: bool = ..., +) -> Iterator[tuple[_T]]: ... +def gray_product(*iterables: Iterable[_T]) -> Iterator[tuple[_T, ...]]: ... +def partial_product(*iterables: Iterable[_T]) -> Iterator[tuple[_T, ...]]: ... +def takewhile_inclusive( + predicate: Callable[[_T], bool], iterable: Iterable[_T] +) -> Iterator[_T]: ... +def outer_product( + func: Callable[[_T, _U], _V], + xs: Iterable[_T], + ys: Iterable[_U], + *args: Any, + **kwargs: Any, +) -> Iterator[tuple[_V, ...]]: ... +def iter_suppress( + iterable: Iterable[_T], + *exceptions: Type[BaseException], +) -> Iterator[_T]: ... +def filter_map( + func: Callable[[_T], _V | None], + iterable: Iterable[_T], +) -> Iterator[_V]: ... +def powerset_of_sets(iterable: Iterable[_T]) -> Iterator[set[_T]]: ... +def join_mappings( + **field_to_map: Mapping[_T, _V] +) -> dict[_T, dict[str, _V]]: ... +def doublestarmap( + func: Callable[..., _T], + iterable: Iterable[Mapping[str, Any]], +) -> Iterator[_T]: ... +def dft(xarr: Sequence[complex]) -> Iterator[complex]: ... +def idft(Xarr: Sequence[complex]) -> Iterator[complex]: ... diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools/py.typed b/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools/recipes.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools/recipes.py new file mode 100644 index 0000000000000000000000000000000000000000..b32fa955339a07c2a789a15fd2287e70fc94d867 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools/recipes.py @@ -0,0 +1,1046 @@ +"""Imported from the recipes section of the itertools documentation. + +All functions taken from the recipes section of the itertools library docs +[1]_. +Some backward-compatible usability improvements have been made. + +.. [1] http://docs.python.org/library/itertools.html#recipes + +""" + +import math +import operator + +from collections import deque +from collections.abc import Sized +from functools import partial, reduce +from itertools import ( + chain, + combinations, + compress, + count, + cycle, + groupby, + islice, + product, + repeat, + starmap, + tee, + zip_longest, +) +from random import randrange, sample, choice +from sys import hexversion + +__all__ = [ + 'all_equal', + 'batched', + 'before_and_after', + 'consume', + 'convolve', + 'dotproduct', + 'first_true', + 'factor', + 'flatten', + 'grouper', + 'iter_except', + 'iter_index', + 'matmul', + 'ncycles', + 'nth', + 'nth_combination', + 'padnone', + 'pad_none', + 'pairwise', + 'partition', + 'polynomial_eval', + 'polynomial_from_roots', + 'polynomial_derivative', + 'powerset', + 'prepend', + 'quantify', + 'reshape', + 'random_combination_with_replacement', + 'random_combination', + 'random_permutation', + 'random_product', + 'repeatfunc', + 'roundrobin', + 'sieve', + 'sliding_window', + 'subslices', + 'sum_of_squares', + 'tabulate', + 'tail', + 'take', + 'totient', + 'transpose', + 'triplewise', + 'unique', + 'unique_everseen', + 'unique_justseen', +] + +_marker = object() + + +# zip with strict is available for Python 3.10+ +try: + zip(strict=True) +except TypeError: + _zip_strict = zip +else: + _zip_strict = partial(zip, strict=True) + +# math.sumprod is available for Python 3.12+ +_sumprod = getattr(math, 'sumprod', lambda x, y: dotproduct(x, y)) + + +def take(n, iterable): + """Return first *n* items of the iterable as a list. + + >>> take(3, range(10)) + [0, 1, 2] + + If there are fewer than *n* items in the iterable, all of them are + returned. + + >>> take(10, range(3)) + [0, 1, 2] + + """ + return list(islice(iterable, n)) + + +def tabulate(function, start=0): + """Return an iterator over the results of ``func(start)``, + ``func(start + 1)``, ``func(start + 2)``... + + *func* should be a function that accepts one integer argument. + + If *start* is not specified it defaults to 0. It will be incremented each + time the iterator is advanced. + + >>> square = lambda x: x ** 2 + >>> iterator = tabulate(square, -3) + >>> take(4, iterator) + [9, 4, 1, 0] + + """ + return map(function, count(start)) + + +def tail(n, iterable): + """Return an iterator over the last *n* items of *iterable*. + + >>> t = tail(3, 'ABCDEFG') + >>> list(t) + ['E', 'F', 'G'] + + """ + # If the given iterable has a length, then we can use islice to get its + # final elements. Note that if the iterable is not actually Iterable, + # either islice or deque will throw a TypeError. This is why we don't + # check if it is Iterable. + if isinstance(iterable, Sized): + yield from islice(iterable, max(0, len(iterable) - n), None) + else: + yield from iter(deque(iterable, maxlen=n)) + + +def consume(iterator, n=None): + """Advance *iterable* by *n* steps. If *n* is ``None``, consume it + entirely. + + Efficiently exhausts an iterator without returning values. Defaults to + consuming the whole iterator, but an optional second argument may be + provided to limit consumption. + + >>> i = (x for x in range(10)) + >>> next(i) + 0 + >>> consume(i, 3) + >>> next(i) + 4 + >>> consume(i) + >>> next(i) + Traceback (most recent call last): + File "", line 1, in + StopIteration + + If the iterator has fewer items remaining than the provided limit, the + whole iterator will be consumed. + + >>> i = (x for x in range(3)) + >>> consume(i, 5) + >>> next(i) + Traceback (most recent call last): + File "", line 1, in + StopIteration + + """ + # Use functions that consume iterators at C speed. + if n is None: + # feed the entire iterator into a zero-length deque + deque(iterator, maxlen=0) + else: + # advance to the empty slice starting at position n + next(islice(iterator, n, n), None) + + +def nth(iterable, n, default=None): + """Returns the nth item or a default value. + + >>> l = range(10) + >>> nth(l, 3) + 3 + >>> nth(l, 20, "zebra") + 'zebra' + + """ + return next(islice(iterable, n, None), default) + + +def all_equal(iterable, key=None): + """ + Returns ``True`` if all the elements are equal to each other. + + >>> all_equal('aaaa') + True + >>> all_equal('aaab') + False + + A function that accepts a single argument and returns a transformed version + of each input item can be specified with *key*: + + >>> all_equal('AaaA', key=str.casefold) + True + >>> all_equal([1, 2, 3], key=lambda x: x < 10) + True + + """ + return len(list(islice(groupby(iterable, key), 2))) <= 1 + + +def quantify(iterable, pred=bool): + """Return the how many times the predicate is true. + + >>> quantify([True, False, True]) + 2 + + """ + return sum(map(pred, iterable)) + + +def pad_none(iterable): + """Returns the sequence of elements and then returns ``None`` indefinitely. + + >>> take(5, pad_none(range(3))) + [0, 1, 2, None, None] + + Useful for emulating the behavior of the built-in :func:`map` function. + + See also :func:`padded`. + + """ + return chain(iterable, repeat(None)) + + +padnone = pad_none + + +def ncycles(iterable, n): + """Returns the sequence elements *n* times + + >>> list(ncycles(["a", "b"], 3)) + ['a', 'b', 'a', 'b', 'a', 'b'] + + """ + return chain.from_iterable(repeat(tuple(iterable), n)) + + +def dotproduct(vec1, vec2): + """Returns the dot product of the two iterables. + + >>> dotproduct([10, 10], [20, 20]) + 400 + + """ + return sum(map(operator.mul, vec1, vec2)) + + +def flatten(listOfLists): + """Return an iterator flattening one level of nesting in a list of lists. + + >>> list(flatten([[0, 1], [2, 3]])) + [0, 1, 2, 3] + + See also :func:`collapse`, which can flatten multiple levels of nesting. + + """ + return chain.from_iterable(listOfLists) + + +def repeatfunc(func, times=None, *args): + """Call *func* with *args* repeatedly, returning an iterable over the + results. + + If *times* is specified, the iterable will terminate after that many + repetitions: + + >>> from operator import add + >>> times = 4 + >>> args = 3, 5 + >>> list(repeatfunc(add, times, *args)) + [8, 8, 8, 8] + + If *times* is ``None`` the iterable will not terminate: + + >>> from random import randrange + >>> times = None + >>> args = 1, 11 + >>> take(6, repeatfunc(randrange, times, *args)) # doctest:+SKIP + [2, 4, 8, 1, 8, 4] + + """ + if times is None: + return starmap(func, repeat(args)) + return starmap(func, repeat(args, times)) + + +def _pairwise(iterable): + """Returns an iterator of paired items, overlapping, from the original + + >>> take(4, pairwise(count())) + [(0, 1), (1, 2), (2, 3), (3, 4)] + + On Python 3.10 and above, this is an alias for :func:`itertools.pairwise`. + + """ + a, b = tee(iterable) + next(b, None) + return zip(a, b) + + +try: + from itertools import pairwise as itertools_pairwise +except ImportError: + pairwise = _pairwise +else: + + def pairwise(iterable): + return itertools_pairwise(iterable) + + pairwise.__doc__ = _pairwise.__doc__ + + +class UnequalIterablesError(ValueError): + def __init__(self, details=None): + msg = 'Iterables have different lengths' + if details is not None: + msg += (': index 0 has length {}; index {} has length {}').format( + *details + ) + + super().__init__(msg) + + +def _zip_equal_generator(iterables): + for combo in zip_longest(*iterables, fillvalue=_marker): + for val in combo: + if val is _marker: + raise UnequalIterablesError() + yield combo + + +def _zip_equal(*iterables): + # Check whether the iterables are all the same size. + try: + first_size = len(iterables[0]) + for i, it in enumerate(iterables[1:], 1): + size = len(it) + if size != first_size: + raise UnequalIterablesError(details=(first_size, i, size)) + # All sizes are equal, we can use the built-in zip. + return zip(*iterables) + # If any one of the iterables didn't have a length, start reading + # them until one runs out. + except TypeError: + return _zip_equal_generator(iterables) + + +def grouper(iterable, n, incomplete='fill', fillvalue=None): + """Group elements from *iterable* into fixed-length groups of length *n*. + + >>> list(grouper('ABCDEF', 3)) + [('A', 'B', 'C'), ('D', 'E', 'F')] + + The keyword arguments *incomplete* and *fillvalue* control what happens for + iterables whose length is not a multiple of *n*. + + When *incomplete* is `'fill'`, the last group will contain instances of + *fillvalue*. + + >>> list(grouper('ABCDEFG', 3, incomplete='fill', fillvalue='x')) + [('A', 'B', 'C'), ('D', 'E', 'F'), ('G', 'x', 'x')] + + When *incomplete* is `'ignore'`, the last group will not be emitted. + + >>> list(grouper('ABCDEFG', 3, incomplete='ignore', fillvalue='x')) + [('A', 'B', 'C'), ('D', 'E', 'F')] + + When *incomplete* is `'strict'`, a subclass of `ValueError` will be raised. + + >>> it = grouper('ABCDEFG', 3, incomplete='strict') + >>> list(it) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + UnequalIterablesError + + """ + args = [iter(iterable)] * n + if incomplete == 'fill': + return zip_longest(*args, fillvalue=fillvalue) + if incomplete == 'strict': + return _zip_equal(*args) + if incomplete == 'ignore': + return zip(*args) + else: + raise ValueError('Expected fill, strict, or ignore') + + +def roundrobin(*iterables): + """Yields an item from each iterable, alternating between them. + + >>> list(roundrobin('ABC', 'D', 'EF')) + ['A', 'D', 'E', 'B', 'F', 'C'] + + This function produces the same output as :func:`interleave_longest`, but + may perform better for some inputs (in particular when the number of + iterables is small). + + """ + # Algorithm credited to George Sakkis + iterators = map(iter, iterables) + for num_active in range(len(iterables), 0, -1): + iterators = cycle(islice(iterators, num_active)) + yield from map(next, iterators) + + +def partition(pred, iterable): + """ + Returns a 2-tuple of iterables derived from the input iterable. + The first yields the items that have ``pred(item) == False``. + The second yields the items that have ``pred(item) == True``. + + >>> is_odd = lambda x: x % 2 != 0 + >>> iterable = range(10) + >>> even_items, odd_items = partition(is_odd, iterable) + >>> list(even_items), list(odd_items) + ([0, 2, 4, 6, 8], [1, 3, 5, 7, 9]) + + If *pred* is None, :func:`bool` is used. + + >>> iterable = [0, 1, False, True, '', ' '] + >>> false_items, true_items = partition(None, iterable) + >>> list(false_items), list(true_items) + ([0, False, ''], [1, True, ' ']) + + """ + if pred is None: + pred = bool + + t1, t2, p = tee(iterable, 3) + p1, p2 = tee(map(pred, p)) + return (compress(t1, map(operator.not_, p1)), compress(t2, p2)) + + +def powerset(iterable): + """Yields all possible subsets of the iterable. + + >>> list(powerset([1, 2, 3])) + [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)] + + :func:`powerset` will operate on iterables that aren't :class:`set` + instances, so repeated elements in the input will produce repeated elements + in the output. + + >>> seq = [1, 1, 0] + >>> list(powerset(seq)) + [(), (1,), (1,), (0,), (1, 1), (1, 0), (1, 0), (1, 1, 0)] + + For a variant that efficiently yields actual :class:`set` instances, see + :func:`powerset_of_sets`. + """ + s = list(iterable) + return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1)) + + +def unique_everseen(iterable, key=None): + """ + Yield unique elements, preserving order. + + >>> list(unique_everseen('AAAABBBCCDAABBB')) + ['A', 'B', 'C', 'D'] + >>> list(unique_everseen('ABBCcAD', str.lower)) + ['A', 'B', 'C', 'D'] + + Sequences with a mix of hashable and unhashable items can be used. + The function will be slower (i.e., `O(n^2)`) for unhashable items. + + Remember that ``list`` objects are unhashable - you can use the *key* + parameter to transform the list to a tuple (which is hashable) to + avoid a slowdown. + + >>> iterable = ([1, 2], [2, 3], [1, 2]) + >>> list(unique_everseen(iterable)) # Slow + [[1, 2], [2, 3]] + >>> list(unique_everseen(iterable, key=tuple)) # Faster + [[1, 2], [2, 3]] + + Similarly, you may want to convert unhashable ``set`` objects with + ``key=frozenset``. For ``dict`` objects, + ``key=lambda x: frozenset(x.items())`` can be used. + + """ + seenset = set() + seenset_add = seenset.add + seenlist = [] + seenlist_add = seenlist.append + use_key = key is not None + + for element in iterable: + k = key(element) if use_key else element + try: + if k not in seenset: + seenset_add(k) + yield element + except TypeError: + if k not in seenlist: + seenlist_add(k) + yield element + + +def unique_justseen(iterable, key=None): + """Yields elements in order, ignoring serial duplicates + + >>> list(unique_justseen('AAAABBBCCDAABBB')) + ['A', 'B', 'C', 'D', 'A', 'B'] + >>> list(unique_justseen('ABBCcAD', str.lower)) + ['A', 'B', 'C', 'A', 'D'] + + """ + if key is None: + return map(operator.itemgetter(0), groupby(iterable)) + + return map(next, map(operator.itemgetter(1), groupby(iterable, key))) + + +def unique(iterable, key=None, reverse=False): + """Yields unique elements in sorted order. + + >>> list(unique([[1, 2], [3, 4], [1, 2]])) + [[1, 2], [3, 4]] + + *key* and *reverse* are passed to :func:`sorted`. + + >>> list(unique('ABBcCAD', str.casefold)) + ['A', 'B', 'c', 'D'] + >>> list(unique('ABBcCAD', str.casefold, reverse=True)) + ['D', 'c', 'B', 'A'] + + The elements in *iterable* need not be hashable, but they must be + comparable for sorting to work. + """ + return unique_justseen(sorted(iterable, key=key, reverse=reverse), key=key) + + +def iter_except(func, exception, first=None): + """Yields results from a function repeatedly until an exception is raised. + + Converts a call-until-exception interface to an iterator interface. + Like ``iter(func, sentinel)``, but uses an exception instead of a sentinel + to end the loop. + + >>> l = [0, 1, 2] + >>> list(iter_except(l.pop, IndexError)) + [2, 1, 0] + + Multiple exceptions can be specified as a stopping condition: + + >>> l = [1, 2, 3, '...', 4, 5, 6] + >>> list(iter_except(lambda: 1 + l.pop(), (IndexError, TypeError))) + [7, 6, 5] + >>> list(iter_except(lambda: 1 + l.pop(), (IndexError, TypeError))) + [4, 3, 2] + >>> list(iter_except(lambda: 1 + l.pop(), (IndexError, TypeError))) + [] + + """ + try: + if first is not None: + yield first() + while 1: + yield func() + except exception: + pass + + +def first_true(iterable, default=None, pred=None): + """ + Returns the first true value in the iterable. + + If no true value is found, returns *default* + + If *pred* is not None, returns the first item for which + ``pred(item) == True`` . + + >>> first_true(range(10)) + 1 + >>> first_true(range(10), pred=lambda x: x > 5) + 6 + >>> first_true(range(10), default='missing', pred=lambda x: x > 9) + 'missing' + + """ + return next(filter(pred, iterable), default) + + +def random_product(*args, repeat=1): + """Draw an item at random from each of the input iterables. + + >>> random_product('abc', range(4), 'XYZ') # doctest:+SKIP + ('c', 3, 'Z') + + If *repeat* is provided as a keyword argument, that many items will be + drawn from each iterable. + + >>> random_product('abcd', range(4), repeat=2) # doctest:+SKIP + ('a', 2, 'd', 3) + + This equivalent to taking a random selection from + ``itertools.product(*args, **kwarg)``. + + """ + pools = [tuple(pool) for pool in args] * repeat + return tuple(choice(pool) for pool in pools) + + +def random_permutation(iterable, r=None): + """Return a random *r* length permutation of the elements in *iterable*. + + If *r* is not specified or is ``None``, then *r* defaults to the length of + *iterable*. + + >>> random_permutation(range(5)) # doctest:+SKIP + (3, 4, 0, 1, 2) + + This equivalent to taking a random selection from + ``itertools.permutations(iterable, r)``. + + """ + pool = tuple(iterable) + r = len(pool) if r is None else r + return tuple(sample(pool, r)) + + +def random_combination(iterable, r): + """Return a random *r* length subsequence of the elements in *iterable*. + + >>> random_combination(range(5), 3) # doctest:+SKIP + (2, 3, 4) + + This equivalent to taking a random selection from + ``itertools.combinations(iterable, r)``. + + """ + pool = tuple(iterable) + n = len(pool) + indices = sorted(sample(range(n), r)) + return tuple(pool[i] for i in indices) + + +def random_combination_with_replacement(iterable, r): + """Return a random *r* length subsequence of elements in *iterable*, + allowing individual elements to be repeated. + + >>> random_combination_with_replacement(range(3), 5) # doctest:+SKIP + (0, 0, 1, 2, 2) + + This equivalent to taking a random selection from + ``itertools.combinations_with_replacement(iterable, r)``. + + """ + pool = tuple(iterable) + n = len(pool) + indices = sorted(randrange(n) for i in range(r)) + return tuple(pool[i] for i in indices) + + +def nth_combination(iterable, r, index): + """Equivalent to ``list(combinations(iterable, r))[index]``. + + The subsequences of *iterable* that are of length *r* can be ordered + lexicographically. :func:`nth_combination` computes the subsequence at + sort position *index* directly, without computing the previous + subsequences. + + >>> nth_combination(range(5), 3, 5) + (0, 3, 4) + + ``ValueError`` will be raised If *r* is negative or greater than the length + of *iterable*. + ``IndexError`` will be raised if the given *index* is invalid. + """ + pool = tuple(iterable) + n = len(pool) + if (r < 0) or (r > n): + raise ValueError + + c = 1 + k = min(r, n - r) + for i in range(1, k + 1): + c = c * (n - k + i) // i + + if index < 0: + index += c + + if (index < 0) or (index >= c): + raise IndexError + + result = [] + while r: + c, n, r = c * r // n, n - 1, r - 1 + while index >= c: + index -= c + c, n = c * (n - r) // n, n - 1 + result.append(pool[-1 - n]) + + return tuple(result) + + +def prepend(value, iterator): + """Yield *value*, followed by the elements in *iterator*. + + >>> value = '0' + >>> iterator = ['1', '2', '3'] + >>> list(prepend(value, iterator)) + ['0', '1', '2', '3'] + + To prepend multiple values, see :func:`itertools.chain` + or :func:`value_chain`. + + """ + return chain([value], iterator) + + +def convolve(signal, kernel): + """Convolve the iterable *signal* with the iterable *kernel*. + + >>> signal = (1, 2, 3, 4, 5) + >>> kernel = [3, 2, 1] + >>> list(convolve(signal, kernel)) + [3, 8, 14, 20, 26, 14, 5] + + Note: the input arguments are not interchangeable, as the *kernel* + is immediately consumed and stored. + + """ + # This implementation intentionally doesn't match the one in the itertools + # documentation. + kernel = tuple(kernel)[::-1] + n = len(kernel) + window = deque([0], maxlen=n) * n + for x in chain(signal, repeat(0, n - 1)): + window.append(x) + yield _sumprod(kernel, window) + + +def before_and_after(predicate, it): + """A variant of :func:`takewhile` that allows complete access to the + remainder of the iterator. + + >>> it = iter('ABCdEfGhI') + >>> all_upper, remainder = before_and_after(str.isupper, it) + >>> ''.join(all_upper) + 'ABC' + >>> ''.join(remainder) # takewhile() would lose the 'd' + 'dEfGhI' + + Note that the first iterator must be fully consumed before the second + iterator can generate valid results. + """ + it = iter(it) + transition = [] + + def true_iterator(): + for elem in it: + if predicate(elem): + yield elem + else: + transition.append(elem) + return + + # Note: this is different from itertools recipes to allow nesting + # before_and_after remainders into before_and_after again. See tests + # for an example. + remainder_iterator = chain(transition, it) + + return true_iterator(), remainder_iterator + + +def triplewise(iterable): + """Return overlapping triplets from *iterable*. + + >>> list(triplewise('ABCDE')) + [('A', 'B', 'C'), ('B', 'C', 'D'), ('C', 'D', 'E')] + + """ + for (a, _), (b, c) in pairwise(pairwise(iterable)): + yield a, b, c + + +def sliding_window(iterable, n): + """Return a sliding window of width *n* over *iterable*. + + >>> list(sliding_window(range(6), 4)) + [(0, 1, 2, 3), (1, 2, 3, 4), (2, 3, 4, 5)] + + If *iterable* has fewer than *n* items, then nothing is yielded: + + >>> list(sliding_window(range(3), 4)) + [] + + For a variant with more features, see :func:`windowed`. + """ + it = iter(iterable) + window = deque(islice(it, n - 1), maxlen=n) + for x in it: + window.append(x) + yield tuple(window) + + +def subslices(iterable): + """Return all contiguous non-empty subslices of *iterable*. + + >>> list(subslices('ABC')) + [['A'], ['A', 'B'], ['A', 'B', 'C'], ['B'], ['B', 'C'], ['C']] + + This is similar to :func:`substrings`, but emits items in a different + order. + """ + seq = list(iterable) + slices = starmap(slice, combinations(range(len(seq) + 1), 2)) + return map(operator.getitem, repeat(seq), slices) + + +def polynomial_from_roots(roots): + """Compute a polynomial's coefficients from its roots. + + >>> roots = [5, -4, 3] # (x - 5) * (x + 4) * (x - 3) + >>> polynomial_from_roots(roots) # x^3 - 4 * x^2 - 17 * x + 60 + [1, -4, -17, 60] + """ + factors = zip(repeat(1), map(operator.neg, roots)) + return list(reduce(convolve, factors, [1])) + + +def iter_index(iterable, value, start=0, stop=None): + """Yield the index of each place in *iterable* that *value* occurs, + beginning with index *start* and ending before index *stop*. + + + >>> list(iter_index('AABCADEAF', 'A')) + [0, 1, 4, 7] + >>> list(iter_index('AABCADEAF', 'A', 1)) # start index is inclusive + [1, 4, 7] + >>> list(iter_index('AABCADEAF', 'A', 1, 7)) # stop index is not inclusive + [1, 4] + + The behavior for non-scalar *values* matches the built-in Python types. + + >>> list(iter_index('ABCDABCD', 'AB')) + [0, 4] + >>> list(iter_index([0, 1, 2, 3, 0, 1, 2, 3], [0, 1])) + [] + >>> list(iter_index([[0, 1], [2, 3], [0, 1], [2, 3]], [0, 1])) + [0, 2] + + See :func:`locate` for a more general means of finding the indexes + associated with particular values. + + """ + seq_index = getattr(iterable, 'index', None) + if seq_index is None: + # Slow path for general iterables + it = islice(iterable, start, stop) + for i, element in enumerate(it, start): + if element is value or element == value: + yield i + else: + # Fast path for sequences + stop = len(iterable) if stop is None else stop + i = start - 1 + try: + while True: + yield (i := seq_index(value, i + 1, stop)) + except ValueError: + pass + + +def sieve(n): + """Yield the primes less than n. + + >>> list(sieve(30)) + [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] + """ + if n > 2: + yield 2 + start = 3 + data = bytearray((0, 1)) * (n // 2) + limit = math.isqrt(n) + 1 + for p in iter_index(data, 1, start, limit): + yield from iter_index(data, 1, start, p * p) + data[p * p : n : p + p] = bytes(len(range(p * p, n, p + p))) + start = p * p + yield from iter_index(data, 1, start) + + +def _batched(iterable, n, *, strict=False): + """Batch data into tuples of length *n*. If the number of items in + *iterable* is not divisible by *n*: + * The last batch will be shorter if *strict* is ``False``. + * :exc:`ValueError` will be raised if *strict* is ``True``. + + >>> list(batched('ABCDEFG', 3)) + [('A', 'B', 'C'), ('D', 'E', 'F'), ('G',)] + + On Python 3.13 and above, this is an alias for :func:`itertools.batched`. + """ + if n < 1: + raise ValueError('n must be at least one') + it = iter(iterable) + while batch := tuple(islice(it, n)): + if strict and len(batch) != n: + raise ValueError('batched(): incomplete batch') + yield batch + + +if hexversion >= 0x30D00A2: + from itertools import batched as itertools_batched + + def batched(iterable, n, *, strict=False): + return itertools_batched(iterable, n, strict=strict) + +else: + batched = _batched + + batched.__doc__ = _batched.__doc__ + + +def transpose(it): + """Swap the rows and columns of the input matrix. + + >>> list(transpose([(1, 2, 3), (11, 22, 33)])) + [(1, 11), (2, 22), (3, 33)] + + The caller should ensure that the dimensions of the input are compatible. + If the input is empty, no output will be produced. + """ + return _zip_strict(*it) + + +def reshape(matrix, cols): + """Reshape the 2-D input *matrix* to have a column count given by *cols*. + + >>> matrix = [(0, 1), (2, 3), (4, 5)] + >>> cols = 3 + >>> list(reshape(matrix, cols)) + [(0, 1, 2), (3, 4, 5)] + """ + return batched(chain.from_iterable(matrix), cols) + + +def matmul(m1, m2): + """Multiply two matrices. + + >>> list(matmul([(7, 5), (3, 5)], [(2, 5), (7, 9)])) + [(49, 80), (41, 60)] + + The caller should ensure that the dimensions of the input matrices are + compatible with each other. + """ + n = len(m2[0]) + return batched(starmap(_sumprod, product(m1, transpose(m2))), n) + + +def factor(n): + """Yield the prime factors of n. + + >>> list(factor(360)) + [2, 2, 2, 3, 3, 5] + """ + for prime in sieve(math.isqrt(n) + 1): + while not n % prime: + yield prime + n //= prime + if n == 1: + return + if n > 1: + yield n + + +def polynomial_eval(coefficients, x): + """Evaluate a polynomial at a specific value. + + Example: evaluating x^3 - 4 * x^2 - 17 * x + 60 at x = 2.5: + + >>> coefficients = [1, -4, -17, 60] + >>> x = 2.5 + >>> polynomial_eval(coefficients, x) + 8.125 + """ + n = len(coefficients) + if n == 0: + return x * 0 # coerce zero to the type of x + powers = map(pow, repeat(x), reversed(range(n))) + return _sumprod(coefficients, powers) + + +def sum_of_squares(it): + """Return the sum of the squares of the input values. + + >>> sum_of_squares([10, 20, 30]) + 1400 + """ + return _sumprod(*tee(it)) + + +def polynomial_derivative(coefficients): + """Compute the first derivative of a polynomial. + + Example: evaluating the derivative of x^3 - 4 * x^2 - 17 * x + 60 + + >>> coefficients = [1, -4, -17, 60] + >>> derivative_coefficients = polynomial_derivative(coefficients) + >>> derivative_coefficients + [3, -8, -17] + """ + n = len(coefficients) + powers = reversed(range(1, n)) + return list(map(operator.mul, coefficients, powers)) + + +def totient(n): + """Return the count of natural numbers up to *n* that are coprime with *n*. + + >>> totient(9) + 6 + >>> totient(12) + 4 + """ + # The itertools docs use unique_justseen instead of set; see + # https://github.com/more-itertools/more-itertools/issues/823 + for p in set(factor(n)): + n = n // p * (p - 1) + + return n diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools/recipes.pyi b/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools/recipes.pyi new file mode 100644 index 0000000000000000000000000000000000000000..739acec05fb3fdd5778aa27db82face3442c3c3f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/more_itertools/recipes.pyi @@ -0,0 +1,136 @@ +"""Stubs for more_itertools.recipes""" + +from __future__ import annotations + +from typing import ( + Any, + Callable, + Iterable, + Iterator, + overload, + Sequence, + Type, + TypeVar, +) + +# Type and type variable definitions +_T = TypeVar('_T') +_T1 = TypeVar('_T1') +_T2 = TypeVar('_T2') +_U = TypeVar('_U') + +def take(n: int, iterable: Iterable[_T]) -> list[_T]: ... +def tabulate( + function: Callable[[int], _T], start: int = ... +) -> Iterator[_T]: ... +def tail(n: int, iterable: Iterable[_T]) -> Iterator[_T]: ... +def consume(iterator: Iterable[_T], n: int | None = ...) -> None: ... +@overload +def nth(iterable: Iterable[_T], n: int) -> _T | None: ... +@overload +def nth(iterable: Iterable[_T], n: int, default: _U) -> _T | _U: ... +def all_equal( + iterable: Iterable[_T], key: Callable[[_T], _U] | None = ... +) -> bool: ... +def quantify( + iterable: Iterable[_T], pred: Callable[[_T], bool] = ... +) -> int: ... +def pad_none(iterable: Iterable[_T]) -> Iterator[_T | None]: ... +def padnone(iterable: Iterable[_T]) -> Iterator[_T | None]: ... +def ncycles(iterable: Iterable[_T], n: int) -> Iterator[_T]: ... +def dotproduct(vec1: Iterable[_T1], vec2: Iterable[_T2]) -> Any: ... +def flatten(listOfLists: Iterable[Iterable[_T]]) -> Iterator[_T]: ... +def repeatfunc( + func: Callable[..., _U], times: int | None = ..., *args: Any +) -> Iterator[_U]: ... +def pairwise(iterable: Iterable[_T]) -> Iterator[tuple[_T, _T]]: ... +def grouper( + iterable: Iterable[_T], + n: int, + incomplete: str = ..., + fillvalue: _U = ..., +) -> Iterator[tuple[_T | _U, ...]]: ... +def roundrobin(*iterables: Iterable[_T]) -> Iterator[_T]: ... +def partition( + pred: Callable[[_T], object] | None, iterable: Iterable[_T] +) -> tuple[Iterator[_T], Iterator[_T]]: ... +def powerset(iterable: Iterable[_T]) -> Iterator[tuple[_T, ...]]: ... +def unique_everseen( + iterable: Iterable[_T], key: Callable[[_T], _U] | None = ... +) -> Iterator[_T]: ... +def unique_justseen( + iterable: Iterable[_T], key: Callable[[_T], object] | None = ... +) -> Iterator[_T]: ... +def unique( + iterable: Iterable[_T], + key: Callable[[_T], object] | None = ..., + reverse: bool = False, +) -> Iterator[_T]: ... +@overload +def iter_except( + func: Callable[[], _T], + exception: Type[BaseException] | tuple[Type[BaseException], ...], + first: None = ..., +) -> Iterator[_T]: ... +@overload +def iter_except( + func: Callable[[], _T], + exception: Type[BaseException] | tuple[Type[BaseException], ...], + first: Callable[[], _U], +) -> Iterator[_T | _U]: ... +@overload +def first_true( + iterable: Iterable[_T], *, pred: Callable[[_T], object] | None = ... +) -> _T | None: ... +@overload +def first_true( + iterable: Iterable[_T], + default: _U, + pred: Callable[[_T], object] | None = ..., +) -> _T | _U: ... +def random_product( + *args: Iterable[_T], repeat: int = ... +) -> tuple[_T, ...]: ... +def random_permutation( + iterable: Iterable[_T], r: int | None = ... +) -> tuple[_T, ...]: ... +def random_combination(iterable: Iterable[_T], r: int) -> tuple[_T, ...]: ... +def random_combination_with_replacement( + iterable: Iterable[_T], r: int +) -> tuple[_T, ...]: ... +def nth_combination( + iterable: Iterable[_T], r: int, index: int +) -> tuple[_T, ...]: ... +def prepend(value: _T, iterator: Iterable[_U]) -> Iterator[_T | _U]: ... +def convolve(signal: Iterable[_T], kernel: Iterable[_T]) -> Iterator[_T]: ... +def before_and_after( + predicate: Callable[[_T], bool], it: Iterable[_T] +) -> tuple[Iterator[_T], Iterator[_T]]: ... +def triplewise(iterable: Iterable[_T]) -> Iterator[tuple[_T, _T, _T]]: ... +def sliding_window( + iterable: Iterable[_T], n: int +) -> Iterator[tuple[_T, ...]]: ... +def subslices(iterable: Iterable[_T]) -> Iterator[list[_T]]: ... +def polynomial_from_roots(roots: Sequence[_T]) -> list[_T]: ... +def iter_index( + iterable: Iterable[_T], + value: Any, + start: int | None = ..., + stop: int | None = ..., +) -> Iterator[int]: ... +def sieve(n: int) -> Iterator[int]: ... +def batched( + iterable: Iterable[_T], n: int, *, strict: bool = False +) -> Iterator[tuple[_T]]: ... +def transpose( + it: Iterable[Iterable[_T]], +) -> Iterator[tuple[_T, ...]]: ... +def reshape( + matrix: Iterable[Iterable[_T]], cols: int +) -> Iterator[tuple[_T, ...]]: ... +def matmul(m1: Sequence[_T], m2: Sequence[_T]) -> Iterator[tuple[_T]]: ... +def factor(n: int) -> Iterator[int]: ... +def polynomial_eval(coefficients: Sequence[_T], x: _U) -> _U: ... +def sum_of_squares(it: Iterable[_T]) -> _T: ... +def polynomial_derivative(coefficients: Sequence[_T]) -> list[_T]: ... +def totient(n: int) -> int: ... diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging-24.2.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging-24.2.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..5c69047b2eb8235994febeeae1da4a82365a240a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging-24.2.dist-info/INSTALLER @@ -0,0 +1 @@ +uv \ No newline at end of file diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging-24.2.dist-info/LICENSE b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging-24.2.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..6f62d44e4ef733c0e713afcd2371fed7f2b3de67 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging-24.2.dist-info/LICENSE @@ -0,0 +1,3 @@ +This software is made available under the terms of *either* of the licenses +found in LICENSE.APACHE or LICENSE.BSD. Contributions to this software is made +under the terms of *both* these licenses. diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging-24.2.dist-info/LICENSE.APACHE b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging-24.2.dist-info/LICENSE.APACHE new file mode 100644 index 0000000000000000000000000000000000000000..f433b1a53f5b830a205fd2df78e2b34974656c7b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging-24.2.dist-info/LICENSE.APACHE @@ -0,0 +1,177 @@ + + 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 diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging-24.2.dist-info/LICENSE.BSD b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging-24.2.dist-info/LICENSE.BSD new file mode 100644 index 0000000000000000000000000000000000000000..42ce7b75c92fb01a3f6ed17eea363f756b7da582 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging-24.2.dist-info/LICENSE.BSD @@ -0,0 +1,23 @@ +Copyright (c) Donald Stufft and individual contributors. +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. + +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.12/site-packages/setuptools/_vendor/packaging-24.2.dist-info/METADATA b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging-24.2.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..1479c8694bfbd583a896dbe9bd33cdb6d7e7371e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging-24.2.dist-info/METADATA @@ -0,0 +1,102 @@ +Metadata-Version: 2.3 +Name: packaging +Version: 24.2 +Summary: Core utilities for Python packages +Author-email: Donald Stufft +Requires-Python: >=3.8 +Description-Content-Type: text/x-rst +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: License :: OSI Approved :: BSD License +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +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: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Typing :: Typed +Project-URL: Documentation, https://packaging.pypa.io/ +Project-URL: Source, https://github.com/pypa/packaging + +packaging +========= + +.. start-intro + +Reusable core utilities for various Python Packaging +`interoperability specifications `_. + +This library provides utilities that implement the interoperability +specifications which have clearly one correct behaviour (eg: :pep:`440`) +or benefit greatly from having a single shared implementation (eg: :pep:`425`). + +.. end-intro + +The ``packaging`` project includes the following: version handling, specifiers, +markers, requirements, tags, utilities. + +Documentation +------------- + +The `documentation`_ provides information and the API for the following: + +- Version Handling +- Specifiers +- Markers +- Requirements +- Tags +- Utilities + +Installation +------------ + +Use ``pip`` to install these utilities:: + + pip install packaging + +The ``packaging`` library uses calendar-based versioning (``YY.N``). + +Discussion +---------- + +If you run into bugs, you can file them in our `issue tracker`_. + +You can also join ``#pypa`` on Freenode to ask questions or get involved. + + +.. _`documentation`: https://packaging.pypa.io/ +.. _`issue tracker`: https://github.com/pypa/packaging/issues + + +Code of Conduct +--------------- + +Everyone interacting in the packaging project's codebases, issue trackers, chat +rooms, and mailing lists is expected to follow the `PSF Code of Conduct`_. + +.. _PSF Code of Conduct: https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md + +Contributing +------------ + +The ``CONTRIBUTING.rst`` file outlines how to contribute to this project as +well as how to report a potential security issue. The documentation for this +project also covers information about `project development`_ and `security`_. + +.. _`project development`: https://packaging.pypa.io/en/latest/development/ +.. _`security`: https://packaging.pypa.io/en/latest/security/ + +Project History +--------------- + +Please review the ``CHANGELOG.rst`` file or the `Changelog documentation`_ for +recent changes and project history. + +.. _`Changelog documentation`: https://packaging.pypa.io/en/latest/changelog/ + diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging-24.2.dist-info/RECORD b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging-24.2.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..678aa5a501dfda29cfdd8a585e038754f008d380 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging-24.2.dist-info/RECORD @@ -0,0 +1,25 @@ +packaging-24.2.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +packaging-24.2.dist-info/LICENSE,sha256=ytHvW9NA1z4HS6YU0m996spceUDD2MNIUuZcSQlobEg,197 +packaging-24.2.dist-info/LICENSE.APACHE,sha256=DVQuDIgE45qn836wDaWnYhSdxoLXgpRRKH4RuTjpRZQ,10174 +packaging-24.2.dist-info/LICENSE.BSD,sha256=tw5-m3QvHMb5SLNMFqo5_-zpQZY2S8iP8NIYDwAo-sU,1344 +packaging-24.2.dist-info/METADATA,sha256=ohH86s6k5mIfQxY2TS0LcSfADeOFa4BiCC-bxZV-pNs,3204 +packaging-24.2.dist-info/RECORD,, +packaging-24.2.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +packaging-24.2.dist-info/WHEEL,sha256=CpUCUxeHQbRN5UGRQHYRJorO5Af-Qy_fHMctcQ8DSGI,82 +packaging/__init__.py,sha256=dk4Ta_vmdVJxYHDcfyhvQNw8V3PgSBomKNXqg-D2JDY,494 +packaging/_elffile.py,sha256=cflAQAkE25tzhYmq_aCi72QfbT_tn891tPzfpbeHOwE,3306 +packaging/_manylinux.py,sha256=vl5OCoz4kx80H5rwXKeXWjl9WNISGmr4ZgTpTP9lU9c,9612 +packaging/_musllinux.py,sha256=p9ZqNYiOItGee8KcZFeHF_YcdhVwGHdK6r-8lgixvGQ,2694 +packaging/_parser.py,sha256=s_TvTvDNK0NrM2QB3VKThdWFM4Nc0P6JnkObkl3MjpM,10236 +packaging/_structures.py,sha256=q3eVNmbWJGG_S0Dit_S3Ao8qQqz_5PYTXFAKBZe5yr4,1431 +packaging/_tokenizer.py,sha256=J6v5H7Jzvb-g81xp_2QACKwO7LxHQA6ikryMU7zXwN8,5273 +packaging/licenses/__init__.py,sha256=1x5M1nEYjcgwEbLt0dXwz2ukjr18DiCzC0sraQqJ-Ww,5715 +packaging/licenses/_spdx.py,sha256=oAm1ztPFwlsmCKe7lAAsv_OIOfS1cWDu9bNBkeu-2ns,48398 +packaging/markers.py,sha256=c89TNzB7ZdGYhkovm6PYmqGyHxXlYVaLW591PHUNKD8,10561 +packaging/metadata.py,sha256=YJibM7GYe4re8-0a3OlXmGS-XDgTEoO4tlBt2q25Bng,34762 +packaging/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +packaging/requirements.py,sha256=gYyRSAdbrIyKDY66ugIDUQjRMvxkH2ALioTmX3tnL6o,2947 +packaging/specifiers.py,sha256=GG1wPNMcL0fMJO68vF53wKMdwnfehDcaI-r9NpTfilA,40074 +packaging/tags.py,sha256=CFqrJzAzc2XNGexerH__T-Y5Iwq7WbsYXsiLERLWxY0,21014 +packaging/utils.py,sha256=0F3Hh9OFuRgrhTgGZUl5K22Fv1YP2tZl1z_2gO6kJiA,5050 +packaging/version.py,sha256=olfyuk_DPbflNkJ4wBWetXQ17c74x3DB501degUv7DY,16676 diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging-24.2.dist-info/REQUESTED b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging-24.2.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging-24.2.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging-24.2.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..e3c6feefa22927866e3fd5575379ea972b432aaf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging-24.2.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 3.10.1 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__init__.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d79f73c574ffc759ef5d2145b1ec742d85c2500b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__init__.py @@ -0,0 +1,15 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +__title__ = "packaging" +__summary__ = "Core utilities for Python packages" +__uri__ = "https://github.com/pypa/packaging" + +__version__ = "24.2" + +__author__ = "Donald Stufft and individual contributors" +__email__ = "donald@stufft.io" + +__license__ = "BSD-2-Clause or Apache-2.0" +__copyright__ = f"2014 {__author__}" diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dbf8d06ab31afe69c751d985355b996ea22086e0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/_elffile.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/_elffile.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3314ecc5b35296e3c082314ab3ddf9054774e254 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/_elffile.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/_manylinux.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/_manylinux.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0dfad25e082e17e3aa8c7a5dc9f166899c39a209 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/_manylinux.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/_musllinux.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/_musllinux.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3462758c891251c8f04a6c1efa7c6ffc7e6556ce Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/_musllinux.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/_parser.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/_parser.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db5910f315ff69dc916ea0d3dbfb5a3c1e0ba8c9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/_parser.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/_structures.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/_structures.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b509bc4f5b3ca0326e5ff4ee77689ca6eda384d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/_structures.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/_tokenizer.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/_tokenizer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7d14a5167b93e71027bbf4f74272582130bc8e8f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/_tokenizer.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/markers.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/markers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30aaf49f40e55092d6e1d56831add96a7cbec7d3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/markers.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/metadata.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/metadata.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5fd889a50421164f8e80f464aadbf4af874dd792 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/metadata.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/requirements.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/requirements.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55c05996fda73f8a6a62f6b839f66963a18e0504 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/requirements.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/specifiers.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/specifiers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc2b6e47f0eb12053df82a5457bbaa458252cbb4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/specifiers.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/tags.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/tags.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3bfbdcb15b91766175a7f20dfe987c5134f20140 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/tags.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..675d3db763b0b0f853802e4e22066bcccbc49787 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/version.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/version.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b37109cb251d6e2841ab451abc1a9bc8e1bf69e5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/__pycache__/version.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/_elffile.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/_elffile.py new file mode 100644 index 0000000000000000000000000000000000000000..25f4282cc29cb03d7be881f03dee841d7dbc215a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/_elffile.py @@ -0,0 +1,110 @@ +""" +ELF file parser. + +This provides a class ``ELFFile`` that parses an ELF executable in a similar +interface to ``ZipFile``. Only the read interface is implemented. + +Based on: https://gist.github.com/lyssdod/f51579ae8d93c8657a5564aefc2ffbca +ELF header: https://refspecs.linuxfoundation.org/elf/gabi4+/ch4.eheader.html +""" + +from __future__ import annotations + +import enum +import os +import struct +from typing import IO + + +class ELFInvalid(ValueError): + pass + + +class EIClass(enum.IntEnum): + C32 = 1 + C64 = 2 + + +class EIData(enum.IntEnum): + Lsb = 1 + Msb = 2 + + +class EMachine(enum.IntEnum): + I386 = 3 + S390 = 22 + Arm = 40 + X8664 = 62 + AArc64 = 183 + + +class ELFFile: + """ + Representation of an ELF executable. + """ + + def __init__(self, f: IO[bytes]) -> None: + self._f = f + + try: + ident = self._read("16B") + except struct.error as e: + raise ELFInvalid("unable to parse identification") from e + magic = bytes(ident[:4]) + if magic != b"\x7fELF": + raise ELFInvalid(f"invalid magic: {magic!r}") + + self.capacity = ident[4] # Format for program header (bitness). + self.encoding = ident[5] # Data structure encoding (endianness). + + try: + # e_fmt: Format for program header. + # p_fmt: Format for section header. + # p_idx: Indexes to find p_type, p_offset, and p_filesz. + e_fmt, self._p_fmt, self._p_idx = { + (1, 1): ("HHIIIIIHHH", ">IIIIIIII", (0, 1, 4)), # 32-bit MSB. + (2, 1): ("HHIQQQIHHH", ">IIQQQQQQ", (0, 2, 5)), # 64-bit MSB. + }[(self.capacity, self.encoding)] + except KeyError as e: + raise ELFInvalid( + f"unrecognized capacity ({self.capacity}) or " + f"encoding ({self.encoding})" + ) from e + + try: + ( + _, + self.machine, # Architecture type. + _, + _, + self._e_phoff, # Offset of program header. + _, + self.flags, # Processor-specific flags. + _, + self._e_phentsize, # Size of section. + self._e_phnum, # Number of sections. + ) = self._read(e_fmt) + except struct.error as e: + raise ELFInvalid("unable to parse machine and section information") from e + + def _read(self, fmt: str) -> tuple[int, ...]: + return struct.unpack(fmt, self._f.read(struct.calcsize(fmt))) + + @property + def interpreter(self) -> str | None: + """ + The path recorded in the ``PT_INTERP`` section header. + """ + for index in range(self._e_phnum): + self._f.seek(self._e_phoff + self._e_phentsize * index) + try: + data = self._read(self._p_fmt) + except struct.error: + continue + if data[self._p_idx[0]] != 3: # Not PT_INTERP. + continue + self._f.seek(data[self._p_idx[1]]) + return os.fsdecode(self._f.read(data[self._p_idx[2]])).strip("\0") + return None diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/_manylinux.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/_manylinux.py new file mode 100644 index 0000000000000000000000000000000000000000..61339a6fcc1b82803136f3bf980e0c8f574b2220 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/_manylinux.py @@ -0,0 +1,263 @@ +from __future__ import annotations + +import collections +import contextlib +import functools +import os +import re +import sys +import warnings +from typing import Generator, Iterator, NamedTuple, Sequence + +from ._elffile import EIClass, EIData, ELFFile, EMachine + +EF_ARM_ABIMASK = 0xFF000000 +EF_ARM_ABI_VER5 = 0x05000000 +EF_ARM_ABI_FLOAT_HARD = 0x00000400 + + +# `os.PathLike` not a generic type until Python 3.9, so sticking with `str` +# as the type for `path` until then. +@contextlib.contextmanager +def _parse_elf(path: str) -> Generator[ELFFile | None, None, None]: + try: + with open(path, "rb") as f: + yield ELFFile(f) + except (OSError, TypeError, ValueError): + yield None + + +def _is_linux_armhf(executable: str) -> bool: + # hard-float ABI can be detected from the ELF header of the running + # process + # https://static.docs.arm.com/ihi0044/g/aaelf32.pdf + with _parse_elf(executable) as f: + return ( + f is not None + and f.capacity == EIClass.C32 + and f.encoding == EIData.Lsb + and f.machine == EMachine.Arm + and f.flags & EF_ARM_ABIMASK == EF_ARM_ABI_VER5 + and f.flags & EF_ARM_ABI_FLOAT_HARD == EF_ARM_ABI_FLOAT_HARD + ) + + +def _is_linux_i686(executable: str) -> bool: + with _parse_elf(executable) as f: + return ( + f is not None + and f.capacity == EIClass.C32 + and f.encoding == EIData.Lsb + and f.machine == EMachine.I386 + ) + + +def _have_compatible_abi(executable: str, archs: Sequence[str]) -> bool: + if "armv7l" in archs: + return _is_linux_armhf(executable) + if "i686" in archs: + return _is_linux_i686(executable) + allowed_archs = { + "x86_64", + "aarch64", + "ppc64", + "ppc64le", + "s390x", + "loongarch64", + "riscv64", + } + return any(arch in allowed_archs for arch in archs) + + +# If glibc ever changes its major version, we need to know what the last +# minor version was, so we can build the complete list of all versions. +# For now, guess what the highest minor version might be, assume it will +# be 50 for testing. Once this actually happens, update the dictionary +# with the actual value. +_LAST_GLIBC_MINOR: dict[int, int] = collections.defaultdict(lambda: 50) + + +class _GLibCVersion(NamedTuple): + major: int + minor: int + + +def _glibc_version_string_confstr() -> str | None: + """ + Primary implementation of glibc_version_string using os.confstr. + """ + # os.confstr is quite a bit faster than ctypes.DLL. It's also less likely + # to be broken or missing. This strategy is used in the standard library + # platform module. + # https://github.com/python/cpython/blob/fcf1d003bf4f0100c/Lib/platform.py#L175-L183 + try: + # Should be a string like "glibc 2.17". + version_string: str | None = os.confstr("CS_GNU_LIBC_VERSION") + assert version_string is not None + _, version = version_string.rsplit() + except (AssertionError, AttributeError, OSError, ValueError): + # os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)... + return None + return version + + +def _glibc_version_string_ctypes() -> str | None: + """ + Fallback implementation of glibc_version_string using ctypes. + """ + try: + import ctypes + except ImportError: + return None + + # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen + # manpage says, "If filename is NULL, then the returned handle is for the + # main program". This way we can let the linker do the work to figure out + # which libc our process is actually using. + # + # We must also handle the special case where the executable is not a + # dynamically linked executable. This can occur when using musl libc, + # for example. In this situation, dlopen() will error, leading to an + # OSError. Interestingly, at least in the case of musl, there is no + # errno set on the OSError. The single string argument used to construct + # OSError comes from libc itself and is therefore not portable to + # hard code here. In any case, failure to call dlopen() means we + # can proceed, so we bail on our attempt. + try: + process_namespace = ctypes.CDLL(None) + except OSError: + return None + + try: + gnu_get_libc_version = process_namespace.gnu_get_libc_version + except AttributeError: + # Symbol doesn't exist -> therefore, we are not linked to + # glibc. + return None + + # Call gnu_get_libc_version, which returns a string like "2.5" + gnu_get_libc_version.restype = ctypes.c_char_p + version_str: str = gnu_get_libc_version() + # py2 / py3 compatibility: + if not isinstance(version_str, str): + version_str = version_str.decode("ascii") + + return version_str + + +def _glibc_version_string() -> str | None: + """Returns glibc version string, or None if not using glibc.""" + return _glibc_version_string_confstr() or _glibc_version_string_ctypes() + + +def _parse_glibc_version(version_str: str) -> tuple[int, int]: + """Parse glibc version. + + We use a regexp instead of str.split because we want to discard any + random junk that might come after the minor version -- this might happen + in patched/forked versions of glibc (e.g. Linaro's version of glibc + uses version strings like "2.20-2014.11"). See gh-3588. + """ + m = re.match(r"(?P[0-9]+)\.(?P[0-9]+)", version_str) + if not m: + warnings.warn( + f"Expected glibc version with 2 components major.minor," + f" got: {version_str}", + RuntimeWarning, + stacklevel=2, + ) + return -1, -1 + return int(m.group("major")), int(m.group("minor")) + + +@functools.lru_cache +def _get_glibc_version() -> tuple[int, int]: + version_str = _glibc_version_string() + if version_str is None: + return (-1, -1) + return _parse_glibc_version(version_str) + + +# From PEP 513, PEP 600 +def _is_compatible(arch: str, version: _GLibCVersion) -> bool: + sys_glibc = _get_glibc_version() + if sys_glibc < version: + return False + # Check for presence of _manylinux module. + try: + import _manylinux + except ImportError: + return True + if hasattr(_manylinux, "manylinux_compatible"): + result = _manylinux.manylinux_compatible(version[0], version[1], arch) + if result is not None: + return bool(result) + return True + if version == _GLibCVersion(2, 5): + if hasattr(_manylinux, "manylinux1_compatible"): + return bool(_manylinux.manylinux1_compatible) + if version == _GLibCVersion(2, 12): + if hasattr(_manylinux, "manylinux2010_compatible"): + return bool(_manylinux.manylinux2010_compatible) + if version == _GLibCVersion(2, 17): + if hasattr(_manylinux, "manylinux2014_compatible"): + return bool(_manylinux.manylinux2014_compatible) + return True + + +_LEGACY_MANYLINUX_MAP = { + # CentOS 7 w/ glibc 2.17 (PEP 599) + (2, 17): "manylinux2014", + # CentOS 6 w/ glibc 2.12 (PEP 571) + (2, 12): "manylinux2010", + # CentOS 5 w/ glibc 2.5 (PEP 513) + (2, 5): "manylinux1", +} + + +def platform_tags(archs: Sequence[str]) -> Iterator[str]: + """Generate manylinux tags compatible to the current platform. + + :param archs: Sequence of compatible architectures. + The first one shall be the closest to the actual architecture and be the part of + platform tag after the ``linux_`` prefix, e.g. ``x86_64``. + The ``linux_`` prefix is assumed as a prerequisite for the current platform to + be manylinux-compatible. + + :returns: An iterator of compatible manylinux tags. + """ + if not _have_compatible_abi(sys.executable, archs): + return + # Oldest glibc to be supported regardless of architecture is (2, 17). + too_old_glibc2 = _GLibCVersion(2, 16) + if set(archs) & {"x86_64", "i686"}: + # On x86/i686 also oldest glibc to be supported is (2, 5). + too_old_glibc2 = _GLibCVersion(2, 4) + current_glibc = _GLibCVersion(*_get_glibc_version()) + glibc_max_list = [current_glibc] + # We can assume compatibility across glibc major versions. + # https://sourceware.org/bugzilla/show_bug.cgi?id=24636 + # + # Build a list of maximum glibc versions so that we can + # output the canonical list of all glibc from current_glibc + # down to too_old_glibc2, including all intermediary versions. + for glibc_major in range(current_glibc.major - 1, 1, -1): + glibc_minor = _LAST_GLIBC_MINOR[glibc_major] + glibc_max_list.append(_GLibCVersion(glibc_major, glibc_minor)) + for arch in archs: + for glibc_max in glibc_max_list: + if glibc_max.major == too_old_glibc2.major: + min_minor = too_old_glibc2.minor + else: + # For other glibc major versions oldest supported is (x, 0). + min_minor = -1 + for glibc_minor in range(glibc_max.minor, min_minor, -1): + glibc_version = _GLibCVersion(glibc_max.major, glibc_minor) + tag = "manylinux_{}_{}".format(*glibc_version) + if _is_compatible(arch, glibc_version): + yield f"{tag}_{arch}" + # Handle the legacy manylinux1, manylinux2010, manylinux2014 tags. + if glibc_version in _LEGACY_MANYLINUX_MAP: + legacy_tag = _LEGACY_MANYLINUX_MAP[glibc_version] + if _is_compatible(arch, glibc_version): + yield f"{legacy_tag}_{arch}" diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/_musllinux.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/_musllinux.py new file mode 100644 index 0000000000000000000000000000000000000000..d2bf30b56319ba862c5c9a1a39a87c6d1cb68718 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/_musllinux.py @@ -0,0 +1,85 @@ +"""PEP 656 support. + +This module implements logic to detect if the currently running Python is +linked against musl, and what musl version is used. +""" + +from __future__ import annotations + +import functools +import re +import subprocess +import sys +from typing import Iterator, NamedTuple, Sequence + +from ._elffile import ELFFile + + +class _MuslVersion(NamedTuple): + major: int + minor: int + + +def _parse_musl_version(output: str) -> _MuslVersion | None: + lines = [n for n in (n.strip() for n in output.splitlines()) if n] + if len(lines) < 2 or lines[0][:4] != "musl": + return None + m = re.match(r"Version (\d+)\.(\d+)", lines[1]) + if not m: + return None + return _MuslVersion(major=int(m.group(1)), minor=int(m.group(2))) + + +@functools.lru_cache +def _get_musl_version(executable: str) -> _MuslVersion | None: + """Detect currently-running musl runtime version. + + This is done by checking the specified executable's dynamic linking + information, and invoking the loader to parse its output for a version + string. If the loader is musl, the output would be something like:: + + musl libc (x86_64) + Version 1.2.2 + Dynamic Program Loader + """ + try: + with open(executable, "rb") as f: + ld = ELFFile(f).interpreter + except (OSError, TypeError, ValueError): + return None + if ld is None or "musl" not in ld: + return None + proc = subprocess.run([ld], stderr=subprocess.PIPE, text=True) + return _parse_musl_version(proc.stderr) + + +def platform_tags(archs: Sequence[str]) -> Iterator[str]: + """Generate musllinux tags compatible to the current platform. + + :param archs: Sequence of compatible architectures. + The first one shall be the closest to the actual architecture and be the part of + platform tag after the ``linux_`` prefix, e.g. ``x86_64``. + The ``linux_`` prefix is assumed as a prerequisite for the current platform to + be musllinux-compatible. + + :returns: An iterator of compatible musllinux tags. + """ + sys_musl = _get_musl_version(sys.executable) + if sys_musl is None: # Python not dynamically linked against musl. + return + for arch in archs: + for minor in range(sys_musl.minor, -1, -1): + yield f"musllinux_{sys_musl.major}_{minor}_{arch}" + + +if __name__ == "__main__": # pragma: no cover + import sysconfig + + plat = sysconfig.get_platform() + assert plat.startswith("linux-"), "not linux" + + print("plat:", plat) + print("musl:", _get_musl_version(sys.executable)) + print("tags:", end=" ") + for t in platform_tags(re.sub(r"[.-]", "_", plat.split("-", 1)[-1])): + print(t, end="\n ") diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/_parser.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..c1238c06eab95f8c90c393383a703aa3b8c366a5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/_parser.py @@ -0,0 +1,354 @@ +"""Handwritten parser of dependency specifiers. + +The docstring for each __parse_* function contains EBNF-inspired grammar representing +the implementation. +""" + +from __future__ import annotations + +import ast +from typing import NamedTuple, Sequence, Tuple, Union + +from ._tokenizer import DEFAULT_RULES, Tokenizer + + +class Node: + def __init__(self, value: str) -> None: + self.value = value + + def __str__(self) -> str: + return self.value + + def __repr__(self) -> str: + return f"<{self.__class__.__name__}('{self}')>" + + def serialize(self) -> str: + raise NotImplementedError + + +class Variable(Node): + def serialize(self) -> str: + return str(self) + + +class Value(Node): + def serialize(self) -> str: + return f'"{self}"' + + +class Op(Node): + def serialize(self) -> str: + return str(self) + + +MarkerVar = Union[Variable, Value] +MarkerItem = Tuple[MarkerVar, Op, MarkerVar] +MarkerAtom = Union[MarkerItem, Sequence["MarkerAtom"]] +MarkerList = Sequence[Union["MarkerList", MarkerAtom, str]] + + +class ParsedRequirement(NamedTuple): + name: str + url: str + extras: list[str] + specifier: str + marker: MarkerList | None + + +# -------------------------------------------------------------------------------------- +# Recursive descent parser for dependency specifier +# -------------------------------------------------------------------------------------- +def parse_requirement(source: str) -> ParsedRequirement: + return _parse_requirement(Tokenizer(source, rules=DEFAULT_RULES)) + + +def _parse_requirement(tokenizer: Tokenizer) -> ParsedRequirement: + """ + requirement = WS? IDENTIFIER WS? extras WS? requirement_details + """ + tokenizer.consume("WS") + + name_token = tokenizer.expect( + "IDENTIFIER", expected="package name at the start of dependency specifier" + ) + name = name_token.text + tokenizer.consume("WS") + + extras = _parse_extras(tokenizer) + tokenizer.consume("WS") + + url, specifier, marker = _parse_requirement_details(tokenizer) + tokenizer.expect("END", expected="end of dependency specifier") + + return ParsedRequirement(name, url, extras, specifier, marker) + + +def _parse_requirement_details( + tokenizer: Tokenizer, +) -> tuple[str, str, MarkerList | None]: + """ + requirement_details = AT URL (WS requirement_marker?)? + | specifier WS? (requirement_marker)? + """ + + specifier = "" + url = "" + marker = None + + if tokenizer.check("AT"): + tokenizer.read() + tokenizer.consume("WS") + + url_start = tokenizer.position + url = tokenizer.expect("URL", expected="URL after @").text + if tokenizer.check("END", peek=True): + return (url, specifier, marker) + + tokenizer.expect("WS", expected="whitespace after URL") + + # The input might end after whitespace. + if tokenizer.check("END", peek=True): + return (url, specifier, marker) + + marker = _parse_requirement_marker( + tokenizer, span_start=url_start, after="URL and whitespace" + ) + else: + specifier_start = tokenizer.position + specifier = _parse_specifier(tokenizer) + tokenizer.consume("WS") + + if tokenizer.check("END", peek=True): + return (url, specifier, marker) + + marker = _parse_requirement_marker( + tokenizer, + span_start=specifier_start, + after=( + "version specifier" + if specifier + else "name and no valid version specifier" + ), + ) + + return (url, specifier, marker) + + +def _parse_requirement_marker( + tokenizer: Tokenizer, *, span_start: int, after: str +) -> MarkerList: + """ + requirement_marker = SEMICOLON marker WS? + """ + + if not tokenizer.check("SEMICOLON"): + tokenizer.raise_syntax_error( + f"Expected end or semicolon (after {after})", + span_start=span_start, + ) + tokenizer.read() + + marker = _parse_marker(tokenizer) + tokenizer.consume("WS") + + return marker + + +def _parse_extras(tokenizer: Tokenizer) -> list[str]: + """ + extras = (LEFT_BRACKET wsp* extras_list? wsp* RIGHT_BRACKET)? + """ + if not tokenizer.check("LEFT_BRACKET", peek=True): + return [] + + with tokenizer.enclosing_tokens( + "LEFT_BRACKET", + "RIGHT_BRACKET", + around="extras", + ): + tokenizer.consume("WS") + extras = _parse_extras_list(tokenizer) + tokenizer.consume("WS") + + return extras + + +def _parse_extras_list(tokenizer: Tokenizer) -> list[str]: + """ + extras_list = identifier (wsp* ',' wsp* identifier)* + """ + extras: list[str] = [] + + if not tokenizer.check("IDENTIFIER"): + return extras + + extras.append(tokenizer.read().text) + + while True: + tokenizer.consume("WS") + if tokenizer.check("IDENTIFIER", peek=True): + tokenizer.raise_syntax_error("Expected comma between extra names") + elif not tokenizer.check("COMMA"): + break + + tokenizer.read() + tokenizer.consume("WS") + + extra_token = tokenizer.expect("IDENTIFIER", expected="extra name after comma") + extras.append(extra_token.text) + + return extras + + +def _parse_specifier(tokenizer: Tokenizer) -> str: + """ + specifier = LEFT_PARENTHESIS WS? version_many WS? RIGHT_PARENTHESIS + | WS? version_many WS? + """ + with tokenizer.enclosing_tokens( + "LEFT_PARENTHESIS", + "RIGHT_PARENTHESIS", + around="version specifier", + ): + tokenizer.consume("WS") + parsed_specifiers = _parse_version_many(tokenizer) + tokenizer.consume("WS") + + return parsed_specifiers + + +def _parse_version_many(tokenizer: Tokenizer) -> str: + """ + version_many = (SPECIFIER (WS? COMMA WS? SPECIFIER)*)? + """ + parsed_specifiers = "" + while tokenizer.check("SPECIFIER"): + span_start = tokenizer.position + parsed_specifiers += tokenizer.read().text + if tokenizer.check("VERSION_PREFIX_TRAIL", peek=True): + tokenizer.raise_syntax_error( + ".* suffix can only be used with `==` or `!=` operators", + span_start=span_start, + span_end=tokenizer.position + 1, + ) + if tokenizer.check("VERSION_LOCAL_LABEL_TRAIL", peek=True): + tokenizer.raise_syntax_error( + "Local version label can only be used with `==` or `!=` operators", + span_start=span_start, + span_end=tokenizer.position, + ) + tokenizer.consume("WS") + if not tokenizer.check("COMMA"): + break + parsed_specifiers += tokenizer.read().text + tokenizer.consume("WS") + + return parsed_specifiers + + +# -------------------------------------------------------------------------------------- +# Recursive descent parser for marker expression +# -------------------------------------------------------------------------------------- +def parse_marker(source: str) -> MarkerList: + return _parse_full_marker(Tokenizer(source, rules=DEFAULT_RULES)) + + +def _parse_full_marker(tokenizer: Tokenizer) -> MarkerList: + retval = _parse_marker(tokenizer) + tokenizer.expect("END", expected="end of marker expression") + return retval + + +def _parse_marker(tokenizer: Tokenizer) -> MarkerList: + """ + marker = marker_atom (BOOLOP marker_atom)+ + """ + expression = [_parse_marker_atom(tokenizer)] + while tokenizer.check("BOOLOP"): + token = tokenizer.read() + expr_right = _parse_marker_atom(tokenizer) + expression.extend((token.text, expr_right)) + return expression + + +def _parse_marker_atom(tokenizer: Tokenizer) -> MarkerAtom: + """ + marker_atom = WS? LEFT_PARENTHESIS WS? marker WS? RIGHT_PARENTHESIS WS? + | WS? marker_item WS? + """ + + tokenizer.consume("WS") + if tokenizer.check("LEFT_PARENTHESIS", peek=True): + with tokenizer.enclosing_tokens( + "LEFT_PARENTHESIS", + "RIGHT_PARENTHESIS", + around="marker expression", + ): + tokenizer.consume("WS") + marker: MarkerAtom = _parse_marker(tokenizer) + tokenizer.consume("WS") + else: + marker = _parse_marker_item(tokenizer) + tokenizer.consume("WS") + return marker + + +def _parse_marker_item(tokenizer: Tokenizer) -> MarkerItem: + """ + marker_item = WS? marker_var WS? marker_op WS? marker_var WS? + """ + tokenizer.consume("WS") + marker_var_left = _parse_marker_var(tokenizer) + tokenizer.consume("WS") + marker_op = _parse_marker_op(tokenizer) + tokenizer.consume("WS") + marker_var_right = _parse_marker_var(tokenizer) + tokenizer.consume("WS") + return (marker_var_left, marker_op, marker_var_right) + + +def _parse_marker_var(tokenizer: Tokenizer) -> MarkerVar: + """ + marker_var = VARIABLE | QUOTED_STRING + """ + if tokenizer.check("VARIABLE"): + return process_env_var(tokenizer.read().text.replace(".", "_")) + elif tokenizer.check("QUOTED_STRING"): + return process_python_str(tokenizer.read().text) + else: + tokenizer.raise_syntax_error( + message="Expected a marker variable or quoted string" + ) + + +def process_env_var(env_var: str) -> Variable: + if env_var in ("platform_python_implementation", "python_implementation"): + return Variable("platform_python_implementation") + else: + return Variable(env_var) + + +def process_python_str(python_str: str) -> Value: + value = ast.literal_eval(python_str) + return Value(str(value)) + + +def _parse_marker_op(tokenizer: Tokenizer) -> Op: + """ + marker_op = IN | NOT IN | OP + """ + if tokenizer.check("IN"): + tokenizer.read() + return Op("in") + elif tokenizer.check("NOT"): + tokenizer.read() + tokenizer.expect("WS", expected="whitespace after 'not'") + tokenizer.expect("IN", expected="'in' after 'not'") + return Op("not in") + elif tokenizer.check("OP"): + return Op(tokenizer.read().text) + else: + return tokenizer.raise_syntax_error( + "Expected marker operator, one of " + "<=, <, !=, ==, >=, >, ~=, ===, in, not in" + ) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/_structures.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/_structures.py new file mode 100644 index 0000000000000000000000000000000000000000..90a6465f9682c886363eea5327dac64bf623a6ff --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/_structures.py @@ -0,0 +1,61 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + + +class InfinityType: + def __repr__(self) -> str: + return "Infinity" + + def __hash__(self) -> int: + return hash(repr(self)) + + def __lt__(self, other: object) -> bool: + return False + + def __le__(self, other: object) -> bool: + return False + + def __eq__(self, other: object) -> bool: + return isinstance(other, self.__class__) + + def __gt__(self, other: object) -> bool: + return True + + def __ge__(self, other: object) -> bool: + return True + + def __neg__(self: object) -> "NegativeInfinityType": + return NegativeInfinity + + +Infinity = InfinityType() + + +class NegativeInfinityType: + def __repr__(self) -> str: + return "-Infinity" + + def __hash__(self) -> int: + return hash(repr(self)) + + def __lt__(self, other: object) -> bool: + return True + + def __le__(self, other: object) -> bool: + return True + + def __eq__(self, other: object) -> bool: + return isinstance(other, self.__class__) + + def __gt__(self, other: object) -> bool: + return False + + def __ge__(self, other: object) -> bool: + return False + + def __neg__(self: object) -> InfinityType: + return Infinity + + +NegativeInfinity = NegativeInfinityType() diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/_tokenizer.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/_tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..89d041605c006e326a67f399a58a1fec8eb24acf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/_tokenizer.py @@ -0,0 +1,194 @@ +from __future__ import annotations + +import contextlib +import re +from dataclasses import dataclass +from typing import Iterator, NoReturn + +from .specifiers import Specifier + + +@dataclass +class Token: + name: str + text: str + position: int + + +class ParserSyntaxError(Exception): + """The provided source text could not be parsed correctly.""" + + def __init__( + self, + message: str, + *, + source: str, + span: tuple[int, int], + ) -> None: + self.span = span + self.message = message + self.source = source + + super().__init__() + + def __str__(self) -> str: + marker = " " * self.span[0] + "~" * (self.span[1] - self.span[0]) + "^" + return "\n ".join([self.message, self.source, marker]) + + +DEFAULT_RULES: dict[str, str | re.Pattern[str]] = { + "LEFT_PARENTHESIS": r"\(", + "RIGHT_PARENTHESIS": r"\)", + "LEFT_BRACKET": r"\[", + "RIGHT_BRACKET": r"\]", + "SEMICOLON": r";", + "COMMA": r",", + "QUOTED_STRING": re.compile( + r""" + ( + ('[^']*') + | + ("[^"]*") + ) + """, + re.VERBOSE, + ), + "OP": r"(===|==|~=|!=|<=|>=|<|>)", + "BOOLOP": r"\b(or|and)\b", + "IN": r"\bin\b", + "NOT": r"\bnot\b", + "VARIABLE": re.compile( + r""" + \b( + python_version + |python_full_version + |os[._]name + |sys[._]platform + |platform_(release|system) + |platform[._](version|machine|python_implementation) + |python_implementation + |implementation_(name|version) + |extra + )\b + """, + re.VERBOSE, + ), + "SPECIFIER": re.compile( + Specifier._operator_regex_str + Specifier._version_regex_str, + re.VERBOSE | re.IGNORECASE, + ), + "AT": r"\@", + "URL": r"[^ \t]+", + "IDENTIFIER": r"\b[a-zA-Z0-9][a-zA-Z0-9._-]*\b", + "VERSION_PREFIX_TRAIL": r"\.\*", + "VERSION_LOCAL_LABEL_TRAIL": r"\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*", + "WS": r"[ \t]+", + "END": r"$", +} + + +class Tokenizer: + """Context-sensitive token parsing. + + Provides methods to examine the input stream to check whether the next token + matches. + """ + + def __init__( + self, + source: str, + *, + rules: dict[str, str | re.Pattern[str]], + ) -> None: + self.source = source + self.rules: dict[str, re.Pattern[str]] = { + name: re.compile(pattern) for name, pattern in rules.items() + } + self.next_token: Token | None = None + self.position = 0 + + def consume(self, name: str) -> None: + """Move beyond provided token name, if at current position.""" + if self.check(name): + self.read() + + def check(self, name: str, *, peek: bool = False) -> bool: + """Check whether the next token has the provided name. + + By default, if the check succeeds, the token *must* be read before + another check. If `peek` is set to `True`, the token is not loaded and + would need to be checked again. + """ + assert ( + self.next_token is None + ), f"Cannot check for {name!r}, already have {self.next_token!r}" + assert name in self.rules, f"Unknown token name: {name!r}" + + expression = self.rules[name] + + match = expression.match(self.source, self.position) + if match is None: + return False + if not peek: + self.next_token = Token(name, match[0], self.position) + return True + + def expect(self, name: str, *, expected: str) -> Token: + """Expect a certain token name next, failing with a syntax error otherwise. + + The token is *not* read. + """ + if not self.check(name): + raise self.raise_syntax_error(f"Expected {expected}") + return self.read() + + def read(self) -> Token: + """Consume the next token and return it.""" + token = self.next_token + assert token is not None + + self.position += len(token.text) + self.next_token = None + + return token + + def raise_syntax_error( + self, + message: str, + *, + span_start: int | None = None, + span_end: int | None = None, + ) -> NoReturn: + """Raise ParserSyntaxError at the given position.""" + span = ( + self.position if span_start is None else span_start, + self.position if span_end is None else span_end, + ) + raise ParserSyntaxError( + message, + source=self.source, + span=span, + ) + + @contextlib.contextmanager + def enclosing_tokens( + self, open_token: str, close_token: str, *, around: str + ) -> Iterator[None]: + if self.check(open_token): + open_position = self.position + self.read() + else: + open_position = None + + yield + + if open_position is None: + return + + if not self.check(close_token): + self.raise_syntax_error( + f"Expected matching {close_token} for {open_token}, after {around}", + span_start=open_position, + ) + + self.read() diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/licenses/__init__.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/licenses/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..569156d6ca47719f49b753a4781a86a924de173b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/licenses/__init__.py @@ -0,0 +1,145 @@ +####################################################################################### +# +# Adapted from: +# https://github.com/pypa/hatch/blob/5352e44/backend/src/hatchling/licenses/parse.py +# +# MIT License +# +# Copyright (c) 2017-present Ofek Lev +# +# 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. +# +# +# With additional allowance of arbitrary `LicenseRef-` identifiers, not just +# `LicenseRef-Public-Domain` and `LicenseRef-Proprietary`. +# +####################################################################################### +from __future__ import annotations + +import re +from typing import NewType, cast + +from packaging.licenses._spdx import EXCEPTIONS, LICENSES + +__all__ = [ + "NormalizedLicenseExpression", + "InvalidLicenseExpression", + "canonicalize_license_expression", +] + +license_ref_allowed = re.compile("^[A-Za-z0-9.-]*$") + +NormalizedLicenseExpression = NewType("NormalizedLicenseExpression", str) + + +class InvalidLicenseExpression(ValueError): + """Raised when a license-expression string is invalid + + >>> canonicalize_license_expression("invalid") + Traceback (most recent call last): + ... + packaging.licenses.InvalidLicenseExpression: Invalid license expression: 'invalid' + """ + + +def canonicalize_license_expression( + raw_license_expression: str, +) -> NormalizedLicenseExpression: + if not raw_license_expression: + message = f"Invalid license expression: {raw_license_expression!r}" + raise InvalidLicenseExpression(message) + + # Pad any parentheses so tokenization can be achieved by merely splitting on + # whitespace. + license_expression = raw_license_expression.replace("(", " ( ").replace(")", " ) ") + licenseref_prefix = "LicenseRef-" + license_refs = { + ref.lower(): "LicenseRef-" + ref[len(licenseref_prefix) :] + for ref in license_expression.split() + if ref.lower().startswith(licenseref_prefix.lower()) + } + + # Normalize to lower case so we can look up licenses/exceptions + # and so boolean operators are Python-compatible. + license_expression = license_expression.lower() + + tokens = license_expression.split() + + # Rather than implementing boolean logic, we create an expression that Python can + # parse. Everything that is not involved with the grammar itself is treated as + # `False` and the expression should evaluate as such. + python_tokens = [] + for token in tokens: + if token not in {"or", "and", "with", "(", ")"}: + python_tokens.append("False") + elif token == "with": + python_tokens.append("or") + elif token == "(" and python_tokens and python_tokens[-1] not in {"or", "and"}: + message = f"Invalid license expression: {raw_license_expression!r}" + raise InvalidLicenseExpression(message) + else: + python_tokens.append(token) + + python_expression = " ".join(python_tokens) + try: + invalid = eval(python_expression, globals(), locals()) + except Exception: + invalid = True + + if invalid is not False: + message = f"Invalid license expression: {raw_license_expression!r}" + raise InvalidLicenseExpression(message) from None + + # Take a final pass to check for unknown licenses/exceptions. + normalized_tokens = [] + for token in tokens: + if token in {"or", "and", "with", "(", ")"}: + normalized_tokens.append(token.upper()) + continue + + if normalized_tokens and normalized_tokens[-1] == "WITH": + if token not in EXCEPTIONS: + message = f"Unknown license exception: {token!r}" + raise InvalidLicenseExpression(message) + + normalized_tokens.append(EXCEPTIONS[token]["id"]) + else: + if token.endswith("+"): + final_token = token[:-1] + suffix = "+" + else: + final_token = token + suffix = "" + + if final_token.startswith("licenseref-"): + if not license_ref_allowed.match(final_token): + message = f"Invalid licenseref: {final_token!r}" + raise InvalidLicenseExpression(message) + normalized_tokens.append(license_refs[final_token] + suffix) + else: + if final_token not in LICENSES: + message = f"Unknown license: {final_token!r}" + raise InvalidLicenseExpression(message) + normalized_tokens.append(LICENSES[final_token]["id"] + suffix) + + normalized_expression = " ".join(normalized_tokens) + + return cast( + NormalizedLicenseExpression, + normalized_expression.replace("( ", "(").replace(" )", ")"), + ) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/licenses/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/licenses/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cdcd1c5639991328862713b04756b8cf07dda1dc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/licenses/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/licenses/__pycache__/_spdx.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/licenses/__pycache__/_spdx.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..62f7f3f35a2b7a0b9791ee3a41ec4548f1a93a6d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/licenses/__pycache__/_spdx.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/licenses/_spdx.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/licenses/_spdx.py new file mode 100644 index 0000000000000000000000000000000000000000..eac22276a34ccd73fc9d70c67ca318a49eb11e77 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/licenses/_spdx.py @@ -0,0 +1,759 @@ + +from __future__ import annotations + +from typing import TypedDict + +class SPDXLicense(TypedDict): + id: str + deprecated: bool + +class SPDXException(TypedDict): + id: str + deprecated: bool + + +VERSION = '3.25.0' + +LICENSES: dict[str, SPDXLicense] = { + '0bsd': {'id': '0BSD', 'deprecated': False}, + '3d-slicer-1.0': {'id': '3D-Slicer-1.0', 'deprecated': False}, + 'aal': {'id': 'AAL', 'deprecated': False}, + 'abstyles': {'id': 'Abstyles', 'deprecated': False}, + 'adacore-doc': {'id': 'AdaCore-doc', 'deprecated': False}, + 'adobe-2006': {'id': 'Adobe-2006', 'deprecated': False}, + 'adobe-display-postscript': {'id': 'Adobe-Display-PostScript', 'deprecated': False}, + 'adobe-glyph': {'id': 'Adobe-Glyph', 'deprecated': False}, + 'adobe-utopia': {'id': 'Adobe-Utopia', 'deprecated': False}, + 'adsl': {'id': 'ADSL', 'deprecated': False}, + 'afl-1.1': {'id': 'AFL-1.1', 'deprecated': False}, + 'afl-1.2': {'id': 'AFL-1.2', 'deprecated': False}, + 'afl-2.0': {'id': 'AFL-2.0', 'deprecated': False}, + 'afl-2.1': {'id': 'AFL-2.1', 'deprecated': False}, + 'afl-3.0': {'id': 'AFL-3.0', 'deprecated': False}, + 'afmparse': {'id': 'Afmparse', 'deprecated': False}, + 'agpl-1.0': {'id': 'AGPL-1.0', 'deprecated': True}, + 'agpl-1.0-only': {'id': 'AGPL-1.0-only', 'deprecated': False}, + 'agpl-1.0-or-later': {'id': 'AGPL-1.0-or-later', 'deprecated': False}, + 'agpl-3.0': {'id': 'AGPL-3.0', 'deprecated': True}, + 'agpl-3.0-only': {'id': 'AGPL-3.0-only', 'deprecated': False}, + 'agpl-3.0-or-later': {'id': 'AGPL-3.0-or-later', 'deprecated': False}, + 'aladdin': {'id': 'Aladdin', 'deprecated': False}, + 'amd-newlib': {'id': 'AMD-newlib', 'deprecated': False}, + 'amdplpa': {'id': 'AMDPLPA', 'deprecated': False}, + 'aml': {'id': 'AML', 'deprecated': False}, + 'aml-glslang': {'id': 'AML-glslang', 'deprecated': False}, + 'ampas': {'id': 'AMPAS', 'deprecated': False}, + 'antlr-pd': {'id': 'ANTLR-PD', 'deprecated': False}, + 'antlr-pd-fallback': {'id': 'ANTLR-PD-fallback', 'deprecated': False}, + 'any-osi': {'id': 'any-OSI', 'deprecated': False}, + 'apache-1.0': {'id': 'Apache-1.0', 'deprecated': False}, + 'apache-1.1': {'id': 'Apache-1.1', 'deprecated': False}, + 'apache-2.0': {'id': 'Apache-2.0', 'deprecated': False}, + 'apafml': {'id': 'APAFML', 'deprecated': False}, + 'apl-1.0': {'id': 'APL-1.0', 'deprecated': False}, + 'app-s2p': {'id': 'App-s2p', 'deprecated': False}, + 'apsl-1.0': {'id': 'APSL-1.0', 'deprecated': False}, + 'apsl-1.1': {'id': 'APSL-1.1', 'deprecated': False}, + 'apsl-1.2': {'id': 'APSL-1.2', 'deprecated': False}, + 'apsl-2.0': {'id': 'APSL-2.0', 'deprecated': False}, + 'arphic-1999': {'id': 'Arphic-1999', 'deprecated': False}, + 'artistic-1.0': {'id': 'Artistic-1.0', 'deprecated': False}, + 'artistic-1.0-cl8': {'id': 'Artistic-1.0-cl8', 'deprecated': False}, + 'artistic-1.0-perl': {'id': 'Artistic-1.0-Perl', 'deprecated': False}, + 'artistic-2.0': {'id': 'Artistic-2.0', 'deprecated': False}, + 'aswf-digital-assets-1.0': {'id': 'ASWF-Digital-Assets-1.0', 'deprecated': False}, + 'aswf-digital-assets-1.1': {'id': 'ASWF-Digital-Assets-1.1', 'deprecated': False}, + 'baekmuk': {'id': 'Baekmuk', 'deprecated': False}, + 'bahyph': {'id': 'Bahyph', 'deprecated': False}, + 'barr': {'id': 'Barr', 'deprecated': False}, + 'bcrypt-solar-designer': {'id': 'bcrypt-Solar-Designer', 'deprecated': False}, + 'beerware': {'id': 'Beerware', 'deprecated': False}, + 'bitstream-charter': {'id': 'Bitstream-Charter', 'deprecated': False}, + 'bitstream-vera': {'id': 'Bitstream-Vera', 'deprecated': False}, + 'bittorrent-1.0': {'id': 'BitTorrent-1.0', 'deprecated': False}, + 'bittorrent-1.1': {'id': 'BitTorrent-1.1', 'deprecated': False}, + 'blessing': {'id': 'blessing', 'deprecated': False}, + 'blueoak-1.0.0': {'id': 'BlueOak-1.0.0', 'deprecated': False}, + 'boehm-gc': {'id': 'Boehm-GC', 'deprecated': False}, + 'borceux': {'id': 'Borceux', 'deprecated': False}, + 'brian-gladman-2-clause': {'id': 'Brian-Gladman-2-Clause', 'deprecated': False}, + 'brian-gladman-3-clause': {'id': 'Brian-Gladman-3-Clause', 'deprecated': False}, + 'bsd-1-clause': {'id': 'BSD-1-Clause', 'deprecated': False}, + 'bsd-2-clause': {'id': 'BSD-2-Clause', 'deprecated': False}, + 'bsd-2-clause-darwin': {'id': 'BSD-2-Clause-Darwin', 'deprecated': False}, + 'bsd-2-clause-first-lines': {'id': 'BSD-2-Clause-first-lines', 'deprecated': False}, + 'bsd-2-clause-freebsd': {'id': 'BSD-2-Clause-FreeBSD', 'deprecated': True}, + 'bsd-2-clause-netbsd': {'id': 'BSD-2-Clause-NetBSD', 'deprecated': True}, + 'bsd-2-clause-patent': {'id': 'BSD-2-Clause-Patent', 'deprecated': False}, + 'bsd-2-clause-views': {'id': 'BSD-2-Clause-Views', 'deprecated': False}, + 'bsd-3-clause': {'id': 'BSD-3-Clause', 'deprecated': False}, + 'bsd-3-clause-acpica': {'id': 'BSD-3-Clause-acpica', 'deprecated': False}, + 'bsd-3-clause-attribution': {'id': 'BSD-3-Clause-Attribution', 'deprecated': False}, + 'bsd-3-clause-clear': {'id': 'BSD-3-Clause-Clear', 'deprecated': False}, + 'bsd-3-clause-flex': {'id': 'BSD-3-Clause-flex', 'deprecated': False}, + 'bsd-3-clause-hp': {'id': 'BSD-3-Clause-HP', 'deprecated': False}, + 'bsd-3-clause-lbnl': {'id': 'BSD-3-Clause-LBNL', 'deprecated': False}, + 'bsd-3-clause-modification': {'id': 'BSD-3-Clause-Modification', 'deprecated': False}, + 'bsd-3-clause-no-military-license': {'id': 'BSD-3-Clause-No-Military-License', 'deprecated': False}, + 'bsd-3-clause-no-nuclear-license': {'id': 'BSD-3-Clause-No-Nuclear-License', 'deprecated': False}, + 'bsd-3-clause-no-nuclear-license-2014': {'id': 'BSD-3-Clause-No-Nuclear-License-2014', 'deprecated': False}, + 'bsd-3-clause-no-nuclear-warranty': {'id': 'BSD-3-Clause-No-Nuclear-Warranty', 'deprecated': False}, + 'bsd-3-clause-open-mpi': {'id': 'BSD-3-Clause-Open-MPI', 'deprecated': False}, + 'bsd-3-clause-sun': {'id': 'BSD-3-Clause-Sun', 'deprecated': False}, + 'bsd-4-clause': {'id': 'BSD-4-Clause', 'deprecated': False}, + 'bsd-4-clause-shortened': {'id': 'BSD-4-Clause-Shortened', 'deprecated': False}, + 'bsd-4-clause-uc': {'id': 'BSD-4-Clause-UC', 'deprecated': False}, + 'bsd-4.3reno': {'id': 'BSD-4.3RENO', 'deprecated': False}, + 'bsd-4.3tahoe': {'id': 'BSD-4.3TAHOE', 'deprecated': False}, + 'bsd-advertising-acknowledgement': {'id': 'BSD-Advertising-Acknowledgement', 'deprecated': False}, + 'bsd-attribution-hpnd-disclaimer': {'id': 'BSD-Attribution-HPND-disclaimer', 'deprecated': False}, + 'bsd-inferno-nettverk': {'id': 'BSD-Inferno-Nettverk', 'deprecated': False}, + 'bsd-protection': {'id': 'BSD-Protection', 'deprecated': False}, + 'bsd-source-beginning-file': {'id': 'BSD-Source-beginning-file', 'deprecated': False}, + 'bsd-source-code': {'id': 'BSD-Source-Code', 'deprecated': False}, + 'bsd-systemics': {'id': 'BSD-Systemics', 'deprecated': False}, + 'bsd-systemics-w3works': {'id': 'BSD-Systemics-W3Works', 'deprecated': False}, + 'bsl-1.0': {'id': 'BSL-1.0', 'deprecated': False}, + 'busl-1.1': {'id': 'BUSL-1.1', 'deprecated': False}, + 'bzip2-1.0.5': {'id': 'bzip2-1.0.5', 'deprecated': True}, + 'bzip2-1.0.6': {'id': 'bzip2-1.0.6', 'deprecated': False}, + 'c-uda-1.0': {'id': 'C-UDA-1.0', 'deprecated': False}, + 'cal-1.0': {'id': 'CAL-1.0', 'deprecated': False}, + 'cal-1.0-combined-work-exception': {'id': 'CAL-1.0-Combined-Work-Exception', 'deprecated': False}, + 'caldera': {'id': 'Caldera', 'deprecated': False}, + 'caldera-no-preamble': {'id': 'Caldera-no-preamble', 'deprecated': False}, + 'catharon': {'id': 'Catharon', 'deprecated': False}, + 'catosl-1.1': {'id': 'CATOSL-1.1', 'deprecated': False}, + 'cc-by-1.0': {'id': 'CC-BY-1.0', 'deprecated': False}, + 'cc-by-2.0': {'id': 'CC-BY-2.0', 'deprecated': False}, + 'cc-by-2.5': {'id': 'CC-BY-2.5', 'deprecated': False}, + 'cc-by-2.5-au': {'id': 'CC-BY-2.5-AU', 'deprecated': False}, + 'cc-by-3.0': {'id': 'CC-BY-3.0', 'deprecated': False}, + 'cc-by-3.0-at': {'id': 'CC-BY-3.0-AT', 'deprecated': False}, + 'cc-by-3.0-au': {'id': 'CC-BY-3.0-AU', 'deprecated': False}, + 'cc-by-3.0-de': {'id': 'CC-BY-3.0-DE', 'deprecated': False}, + 'cc-by-3.0-igo': {'id': 'CC-BY-3.0-IGO', 'deprecated': False}, + 'cc-by-3.0-nl': {'id': 'CC-BY-3.0-NL', 'deprecated': False}, + 'cc-by-3.0-us': {'id': 'CC-BY-3.0-US', 'deprecated': False}, + 'cc-by-4.0': {'id': 'CC-BY-4.0', 'deprecated': False}, + 'cc-by-nc-1.0': {'id': 'CC-BY-NC-1.0', 'deprecated': False}, + 'cc-by-nc-2.0': {'id': 'CC-BY-NC-2.0', 'deprecated': False}, + 'cc-by-nc-2.5': {'id': 'CC-BY-NC-2.5', 'deprecated': False}, + 'cc-by-nc-3.0': {'id': 'CC-BY-NC-3.0', 'deprecated': False}, + 'cc-by-nc-3.0-de': {'id': 'CC-BY-NC-3.0-DE', 'deprecated': False}, + 'cc-by-nc-4.0': {'id': 'CC-BY-NC-4.0', 'deprecated': False}, + 'cc-by-nc-nd-1.0': {'id': 'CC-BY-NC-ND-1.0', 'deprecated': False}, + 'cc-by-nc-nd-2.0': {'id': 'CC-BY-NC-ND-2.0', 'deprecated': False}, + 'cc-by-nc-nd-2.5': {'id': 'CC-BY-NC-ND-2.5', 'deprecated': False}, + 'cc-by-nc-nd-3.0': {'id': 'CC-BY-NC-ND-3.0', 'deprecated': False}, + 'cc-by-nc-nd-3.0-de': {'id': 'CC-BY-NC-ND-3.0-DE', 'deprecated': False}, + 'cc-by-nc-nd-3.0-igo': {'id': 'CC-BY-NC-ND-3.0-IGO', 'deprecated': False}, + 'cc-by-nc-nd-4.0': {'id': 'CC-BY-NC-ND-4.0', 'deprecated': False}, + 'cc-by-nc-sa-1.0': {'id': 'CC-BY-NC-SA-1.0', 'deprecated': False}, + 'cc-by-nc-sa-2.0': {'id': 'CC-BY-NC-SA-2.0', 'deprecated': False}, + 'cc-by-nc-sa-2.0-de': {'id': 'CC-BY-NC-SA-2.0-DE', 'deprecated': False}, + 'cc-by-nc-sa-2.0-fr': {'id': 'CC-BY-NC-SA-2.0-FR', 'deprecated': False}, + 'cc-by-nc-sa-2.0-uk': {'id': 'CC-BY-NC-SA-2.0-UK', 'deprecated': False}, + 'cc-by-nc-sa-2.5': {'id': 'CC-BY-NC-SA-2.5', 'deprecated': False}, + 'cc-by-nc-sa-3.0': {'id': 'CC-BY-NC-SA-3.0', 'deprecated': False}, + 'cc-by-nc-sa-3.0-de': {'id': 'CC-BY-NC-SA-3.0-DE', 'deprecated': False}, + 'cc-by-nc-sa-3.0-igo': {'id': 'CC-BY-NC-SA-3.0-IGO', 'deprecated': False}, + 'cc-by-nc-sa-4.0': {'id': 'CC-BY-NC-SA-4.0', 'deprecated': False}, + 'cc-by-nd-1.0': {'id': 'CC-BY-ND-1.0', 'deprecated': False}, + 'cc-by-nd-2.0': {'id': 'CC-BY-ND-2.0', 'deprecated': False}, + 'cc-by-nd-2.5': {'id': 'CC-BY-ND-2.5', 'deprecated': False}, + 'cc-by-nd-3.0': {'id': 'CC-BY-ND-3.0', 'deprecated': False}, + 'cc-by-nd-3.0-de': {'id': 'CC-BY-ND-3.0-DE', 'deprecated': False}, + 'cc-by-nd-4.0': {'id': 'CC-BY-ND-4.0', 'deprecated': False}, + 'cc-by-sa-1.0': {'id': 'CC-BY-SA-1.0', 'deprecated': False}, + 'cc-by-sa-2.0': {'id': 'CC-BY-SA-2.0', 'deprecated': False}, + 'cc-by-sa-2.0-uk': {'id': 'CC-BY-SA-2.0-UK', 'deprecated': False}, + 'cc-by-sa-2.1-jp': {'id': 'CC-BY-SA-2.1-JP', 'deprecated': False}, + 'cc-by-sa-2.5': {'id': 'CC-BY-SA-2.5', 'deprecated': False}, + 'cc-by-sa-3.0': {'id': 'CC-BY-SA-3.0', 'deprecated': False}, + 'cc-by-sa-3.0-at': {'id': 'CC-BY-SA-3.0-AT', 'deprecated': False}, + 'cc-by-sa-3.0-de': {'id': 'CC-BY-SA-3.0-DE', 'deprecated': False}, + 'cc-by-sa-3.0-igo': {'id': 'CC-BY-SA-3.0-IGO', 'deprecated': False}, + 'cc-by-sa-4.0': {'id': 'CC-BY-SA-4.0', 'deprecated': False}, + 'cc-pddc': {'id': 'CC-PDDC', 'deprecated': False}, + 'cc0-1.0': {'id': 'CC0-1.0', 'deprecated': False}, + 'cddl-1.0': {'id': 'CDDL-1.0', 'deprecated': False}, + 'cddl-1.1': {'id': 'CDDL-1.1', 'deprecated': False}, + 'cdl-1.0': {'id': 'CDL-1.0', 'deprecated': False}, + 'cdla-permissive-1.0': {'id': 'CDLA-Permissive-1.0', 'deprecated': False}, + 'cdla-permissive-2.0': {'id': 'CDLA-Permissive-2.0', 'deprecated': False}, + 'cdla-sharing-1.0': {'id': 'CDLA-Sharing-1.0', 'deprecated': False}, + 'cecill-1.0': {'id': 'CECILL-1.0', 'deprecated': False}, + 'cecill-1.1': {'id': 'CECILL-1.1', 'deprecated': False}, + 'cecill-2.0': {'id': 'CECILL-2.0', 'deprecated': False}, + 'cecill-2.1': {'id': 'CECILL-2.1', 'deprecated': False}, + 'cecill-b': {'id': 'CECILL-B', 'deprecated': False}, + 'cecill-c': {'id': 'CECILL-C', 'deprecated': False}, + 'cern-ohl-1.1': {'id': 'CERN-OHL-1.1', 'deprecated': False}, + 'cern-ohl-1.2': {'id': 'CERN-OHL-1.2', 'deprecated': False}, + 'cern-ohl-p-2.0': {'id': 'CERN-OHL-P-2.0', 'deprecated': False}, + 'cern-ohl-s-2.0': {'id': 'CERN-OHL-S-2.0', 'deprecated': False}, + 'cern-ohl-w-2.0': {'id': 'CERN-OHL-W-2.0', 'deprecated': False}, + 'cfitsio': {'id': 'CFITSIO', 'deprecated': False}, + 'check-cvs': {'id': 'check-cvs', 'deprecated': False}, + 'checkmk': {'id': 'checkmk', 'deprecated': False}, + 'clartistic': {'id': 'ClArtistic', 'deprecated': False}, + 'clips': {'id': 'Clips', 'deprecated': False}, + 'cmu-mach': {'id': 'CMU-Mach', 'deprecated': False}, + 'cmu-mach-nodoc': {'id': 'CMU-Mach-nodoc', 'deprecated': False}, + 'cnri-jython': {'id': 'CNRI-Jython', 'deprecated': False}, + 'cnri-python': {'id': 'CNRI-Python', 'deprecated': False}, + 'cnri-python-gpl-compatible': {'id': 'CNRI-Python-GPL-Compatible', 'deprecated': False}, + 'coil-1.0': {'id': 'COIL-1.0', 'deprecated': False}, + 'community-spec-1.0': {'id': 'Community-Spec-1.0', 'deprecated': False}, + 'condor-1.1': {'id': 'Condor-1.1', 'deprecated': False}, + 'copyleft-next-0.3.0': {'id': 'copyleft-next-0.3.0', 'deprecated': False}, + 'copyleft-next-0.3.1': {'id': 'copyleft-next-0.3.1', 'deprecated': False}, + 'cornell-lossless-jpeg': {'id': 'Cornell-Lossless-JPEG', 'deprecated': False}, + 'cpal-1.0': {'id': 'CPAL-1.0', 'deprecated': False}, + 'cpl-1.0': {'id': 'CPL-1.0', 'deprecated': False}, + 'cpol-1.02': {'id': 'CPOL-1.02', 'deprecated': False}, + 'cronyx': {'id': 'Cronyx', 'deprecated': False}, + 'crossword': {'id': 'Crossword', 'deprecated': False}, + 'crystalstacker': {'id': 'CrystalStacker', 'deprecated': False}, + 'cua-opl-1.0': {'id': 'CUA-OPL-1.0', 'deprecated': False}, + 'cube': {'id': 'Cube', 'deprecated': False}, + 'curl': {'id': 'curl', 'deprecated': False}, + 'cve-tou': {'id': 'cve-tou', 'deprecated': False}, + 'd-fsl-1.0': {'id': 'D-FSL-1.0', 'deprecated': False}, + 'dec-3-clause': {'id': 'DEC-3-Clause', 'deprecated': False}, + 'diffmark': {'id': 'diffmark', 'deprecated': False}, + 'dl-de-by-2.0': {'id': 'DL-DE-BY-2.0', 'deprecated': False}, + 'dl-de-zero-2.0': {'id': 'DL-DE-ZERO-2.0', 'deprecated': False}, + 'doc': {'id': 'DOC', 'deprecated': False}, + 'docbook-schema': {'id': 'DocBook-Schema', 'deprecated': False}, + 'docbook-xml': {'id': 'DocBook-XML', 'deprecated': False}, + 'dotseqn': {'id': 'Dotseqn', 'deprecated': False}, + 'drl-1.0': {'id': 'DRL-1.0', 'deprecated': False}, + 'drl-1.1': {'id': 'DRL-1.1', 'deprecated': False}, + 'dsdp': {'id': 'DSDP', 'deprecated': False}, + 'dtoa': {'id': 'dtoa', 'deprecated': False}, + 'dvipdfm': {'id': 'dvipdfm', 'deprecated': False}, + 'ecl-1.0': {'id': 'ECL-1.0', 'deprecated': False}, + 'ecl-2.0': {'id': 'ECL-2.0', 'deprecated': False}, + 'ecos-2.0': {'id': 'eCos-2.0', 'deprecated': True}, + 'efl-1.0': {'id': 'EFL-1.0', 'deprecated': False}, + 'efl-2.0': {'id': 'EFL-2.0', 'deprecated': False}, + 'egenix': {'id': 'eGenix', 'deprecated': False}, + 'elastic-2.0': {'id': 'Elastic-2.0', 'deprecated': False}, + 'entessa': {'id': 'Entessa', 'deprecated': False}, + 'epics': {'id': 'EPICS', 'deprecated': False}, + 'epl-1.0': {'id': 'EPL-1.0', 'deprecated': False}, + 'epl-2.0': {'id': 'EPL-2.0', 'deprecated': False}, + 'erlpl-1.1': {'id': 'ErlPL-1.1', 'deprecated': False}, + 'etalab-2.0': {'id': 'etalab-2.0', 'deprecated': False}, + 'eudatagrid': {'id': 'EUDatagrid', 'deprecated': False}, + 'eupl-1.0': {'id': 'EUPL-1.0', 'deprecated': False}, + 'eupl-1.1': {'id': 'EUPL-1.1', 'deprecated': False}, + 'eupl-1.2': {'id': 'EUPL-1.2', 'deprecated': False}, + 'eurosym': {'id': 'Eurosym', 'deprecated': False}, + 'fair': {'id': 'Fair', 'deprecated': False}, + 'fbm': {'id': 'FBM', 'deprecated': False}, + 'fdk-aac': {'id': 'FDK-AAC', 'deprecated': False}, + 'ferguson-twofish': {'id': 'Ferguson-Twofish', 'deprecated': False}, + 'frameworx-1.0': {'id': 'Frameworx-1.0', 'deprecated': False}, + 'freebsd-doc': {'id': 'FreeBSD-DOC', 'deprecated': False}, + 'freeimage': {'id': 'FreeImage', 'deprecated': False}, + 'fsfap': {'id': 'FSFAP', 'deprecated': False}, + 'fsfap-no-warranty-disclaimer': {'id': 'FSFAP-no-warranty-disclaimer', 'deprecated': False}, + 'fsful': {'id': 'FSFUL', 'deprecated': False}, + 'fsfullr': {'id': 'FSFULLR', 'deprecated': False}, + 'fsfullrwd': {'id': 'FSFULLRWD', 'deprecated': False}, + 'ftl': {'id': 'FTL', 'deprecated': False}, + 'furuseth': {'id': 'Furuseth', 'deprecated': False}, + 'fwlw': {'id': 'fwlw', 'deprecated': False}, + 'gcr-docs': {'id': 'GCR-docs', 'deprecated': False}, + 'gd': {'id': 'GD', 'deprecated': False}, + 'gfdl-1.1': {'id': 'GFDL-1.1', 'deprecated': True}, + 'gfdl-1.1-invariants-only': {'id': 'GFDL-1.1-invariants-only', 'deprecated': False}, + 'gfdl-1.1-invariants-or-later': {'id': 'GFDL-1.1-invariants-or-later', 'deprecated': False}, + 'gfdl-1.1-no-invariants-only': {'id': 'GFDL-1.1-no-invariants-only', 'deprecated': False}, + 'gfdl-1.1-no-invariants-or-later': {'id': 'GFDL-1.1-no-invariants-or-later', 'deprecated': False}, + 'gfdl-1.1-only': {'id': 'GFDL-1.1-only', 'deprecated': False}, + 'gfdl-1.1-or-later': {'id': 'GFDL-1.1-or-later', 'deprecated': False}, + 'gfdl-1.2': {'id': 'GFDL-1.2', 'deprecated': True}, + 'gfdl-1.2-invariants-only': {'id': 'GFDL-1.2-invariants-only', 'deprecated': False}, + 'gfdl-1.2-invariants-or-later': {'id': 'GFDL-1.2-invariants-or-later', 'deprecated': False}, + 'gfdl-1.2-no-invariants-only': {'id': 'GFDL-1.2-no-invariants-only', 'deprecated': False}, + 'gfdl-1.2-no-invariants-or-later': {'id': 'GFDL-1.2-no-invariants-or-later', 'deprecated': False}, + 'gfdl-1.2-only': {'id': 'GFDL-1.2-only', 'deprecated': False}, + 'gfdl-1.2-or-later': {'id': 'GFDL-1.2-or-later', 'deprecated': False}, + 'gfdl-1.3': {'id': 'GFDL-1.3', 'deprecated': True}, + 'gfdl-1.3-invariants-only': {'id': 'GFDL-1.3-invariants-only', 'deprecated': False}, + 'gfdl-1.3-invariants-or-later': {'id': 'GFDL-1.3-invariants-or-later', 'deprecated': False}, + 'gfdl-1.3-no-invariants-only': {'id': 'GFDL-1.3-no-invariants-only', 'deprecated': False}, + 'gfdl-1.3-no-invariants-or-later': {'id': 'GFDL-1.3-no-invariants-or-later', 'deprecated': False}, + 'gfdl-1.3-only': {'id': 'GFDL-1.3-only', 'deprecated': False}, + 'gfdl-1.3-or-later': {'id': 'GFDL-1.3-or-later', 'deprecated': False}, + 'giftware': {'id': 'Giftware', 'deprecated': False}, + 'gl2ps': {'id': 'GL2PS', 'deprecated': False}, + 'glide': {'id': 'Glide', 'deprecated': False}, + 'glulxe': {'id': 'Glulxe', 'deprecated': False}, + 'glwtpl': {'id': 'GLWTPL', 'deprecated': False}, + 'gnuplot': {'id': 'gnuplot', 'deprecated': False}, + 'gpl-1.0': {'id': 'GPL-1.0', 'deprecated': True}, + 'gpl-1.0+': {'id': 'GPL-1.0+', 'deprecated': True}, + 'gpl-1.0-only': {'id': 'GPL-1.0-only', 'deprecated': False}, + 'gpl-1.0-or-later': {'id': 'GPL-1.0-or-later', 'deprecated': False}, + 'gpl-2.0': {'id': 'GPL-2.0', 'deprecated': True}, + 'gpl-2.0+': {'id': 'GPL-2.0+', 'deprecated': True}, + 'gpl-2.0-only': {'id': 'GPL-2.0-only', 'deprecated': False}, + 'gpl-2.0-or-later': {'id': 'GPL-2.0-or-later', 'deprecated': False}, + 'gpl-2.0-with-autoconf-exception': {'id': 'GPL-2.0-with-autoconf-exception', 'deprecated': True}, + 'gpl-2.0-with-bison-exception': {'id': 'GPL-2.0-with-bison-exception', 'deprecated': True}, + 'gpl-2.0-with-classpath-exception': {'id': 'GPL-2.0-with-classpath-exception', 'deprecated': True}, + 'gpl-2.0-with-font-exception': {'id': 'GPL-2.0-with-font-exception', 'deprecated': True}, + 'gpl-2.0-with-gcc-exception': {'id': 'GPL-2.0-with-GCC-exception', 'deprecated': True}, + 'gpl-3.0': {'id': 'GPL-3.0', 'deprecated': True}, + 'gpl-3.0+': {'id': 'GPL-3.0+', 'deprecated': True}, + 'gpl-3.0-only': {'id': 'GPL-3.0-only', 'deprecated': False}, + 'gpl-3.0-or-later': {'id': 'GPL-3.0-or-later', 'deprecated': False}, + 'gpl-3.0-with-autoconf-exception': {'id': 'GPL-3.0-with-autoconf-exception', 'deprecated': True}, + 'gpl-3.0-with-gcc-exception': {'id': 'GPL-3.0-with-GCC-exception', 'deprecated': True}, + 'graphics-gems': {'id': 'Graphics-Gems', 'deprecated': False}, + 'gsoap-1.3b': {'id': 'gSOAP-1.3b', 'deprecated': False}, + 'gtkbook': {'id': 'gtkbook', 'deprecated': False}, + 'gutmann': {'id': 'Gutmann', 'deprecated': False}, + 'haskellreport': {'id': 'HaskellReport', 'deprecated': False}, + 'hdparm': {'id': 'hdparm', 'deprecated': False}, + 'hidapi': {'id': 'HIDAPI', 'deprecated': False}, + 'hippocratic-2.1': {'id': 'Hippocratic-2.1', 'deprecated': False}, + 'hp-1986': {'id': 'HP-1986', 'deprecated': False}, + 'hp-1989': {'id': 'HP-1989', 'deprecated': False}, + 'hpnd': {'id': 'HPND', 'deprecated': False}, + 'hpnd-dec': {'id': 'HPND-DEC', 'deprecated': False}, + 'hpnd-doc': {'id': 'HPND-doc', 'deprecated': False}, + 'hpnd-doc-sell': {'id': 'HPND-doc-sell', 'deprecated': False}, + 'hpnd-export-us': {'id': 'HPND-export-US', 'deprecated': False}, + 'hpnd-export-us-acknowledgement': {'id': 'HPND-export-US-acknowledgement', 'deprecated': False}, + 'hpnd-export-us-modify': {'id': 'HPND-export-US-modify', 'deprecated': False}, + 'hpnd-export2-us': {'id': 'HPND-export2-US', 'deprecated': False}, + 'hpnd-fenneberg-livingston': {'id': 'HPND-Fenneberg-Livingston', 'deprecated': False}, + 'hpnd-inria-imag': {'id': 'HPND-INRIA-IMAG', 'deprecated': False}, + 'hpnd-intel': {'id': 'HPND-Intel', 'deprecated': False}, + 'hpnd-kevlin-henney': {'id': 'HPND-Kevlin-Henney', 'deprecated': False}, + 'hpnd-markus-kuhn': {'id': 'HPND-Markus-Kuhn', 'deprecated': False}, + 'hpnd-merchantability-variant': {'id': 'HPND-merchantability-variant', 'deprecated': False}, + 'hpnd-mit-disclaimer': {'id': 'HPND-MIT-disclaimer', 'deprecated': False}, + 'hpnd-netrek': {'id': 'HPND-Netrek', 'deprecated': False}, + 'hpnd-pbmplus': {'id': 'HPND-Pbmplus', 'deprecated': False}, + 'hpnd-sell-mit-disclaimer-xserver': {'id': 'HPND-sell-MIT-disclaimer-xserver', 'deprecated': False}, + 'hpnd-sell-regexpr': {'id': 'HPND-sell-regexpr', 'deprecated': False}, + 'hpnd-sell-variant': {'id': 'HPND-sell-variant', 'deprecated': False}, + 'hpnd-sell-variant-mit-disclaimer': {'id': 'HPND-sell-variant-MIT-disclaimer', 'deprecated': False}, + 'hpnd-sell-variant-mit-disclaimer-rev': {'id': 'HPND-sell-variant-MIT-disclaimer-rev', 'deprecated': False}, + 'hpnd-uc': {'id': 'HPND-UC', 'deprecated': False}, + 'hpnd-uc-export-us': {'id': 'HPND-UC-export-US', 'deprecated': False}, + 'htmltidy': {'id': 'HTMLTIDY', 'deprecated': False}, + 'ibm-pibs': {'id': 'IBM-pibs', 'deprecated': False}, + 'icu': {'id': 'ICU', 'deprecated': False}, + 'iec-code-components-eula': {'id': 'IEC-Code-Components-EULA', 'deprecated': False}, + 'ijg': {'id': 'IJG', 'deprecated': False}, + 'ijg-short': {'id': 'IJG-short', 'deprecated': False}, + 'imagemagick': {'id': 'ImageMagick', 'deprecated': False}, + 'imatix': {'id': 'iMatix', 'deprecated': False}, + 'imlib2': {'id': 'Imlib2', 'deprecated': False}, + 'info-zip': {'id': 'Info-ZIP', 'deprecated': False}, + 'inner-net-2.0': {'id': 'Inner-Net-2.0', 'deprecated': False}, + 'intel': {'id': 'Intel', 'deprecated': False}, + 'intel-acpi': {'id': 'Intel-ACPI', 'deprecated': False}, + 'interbase-1.0': {'id': 'Interbase-1.0', 'deprecated': False}, + 'ipa': {'id': 'IPA', 'deprecated': False}, + 'ipl-1.0': {'id': 'IPL-1.0', 'deprecated': False}, + 'isc': {'id': 'ISC', 'deprecated': False}, + 'isc-veillard': {'id': 'ISC-Veillard', 'deprecated': False}, + 'jam': {'id': 'Jam', 'deprecated': False}, + 'jasper-2.0': {'id': 'JasPer-2.0', 'deprecated': False}, + 'jpl-image': {'id': 'JPL-image', 'deprecated': False}, + 'jpnic': {'id': 'JPNIC', 'deprecated': False}, + 'json': {'id': 'JSON', 'deprecated': False}, + 'kastrup': {'id': 'Kastrup', 'deprecated': False}, + 'kazlib': {'id': 'Kazlib', 'deprecated': False}, + 'knuth-ctan': {'id': 'Knuth-CTAN', 'deprecated': False}, + 'lal-1.2': {'id': 'LAL-1.2', 'deprecated': False}, + 'lal-1.3': {'id': 'LAL-1.3', 'deprecated': False}, + 'latex2e': {'id': 'Latex2e', 'deprecated': False}, + 'latex2e-translated-notice': {'id': 'Latex2e-translated-notice', 'deprecated': False}, + 'leptonica': {'id': 'Leptonica', 'deprecated': False}, + 'lgpl-2.0': {'id': 'LGPL-2.0', 'deprecated': True}, + 'lgpl-2.0+': {'id': 'LGPL-2.0+', 'deprecated': True}, + 'lgpl-2.0-only': {'id': 'LGPL-2.0-only', 'deprecated': False}, + 'lgpl-2.0-or-later': {'id': 'LGPL-2.0-or-later', 'deprecated': False}, + 'lgpl-2.1': {'id': 'LGPL-2.1', 'deprecated': True}, + 'lgpl-2.1+': {'id': 'LGPL-2.1+', 'deprecated': True}, + 'lgpl-2.1-only': {'id': 'LGPL-2.1-only', 'deprecated': False}, + 'lgpl-2.1-or-later': {'id': 'LGPL-2.1-or-later', 'deprecated': False}, + 'lgpl-3.0': {'id': 'LGPL-3.0', 'deprecated': True}, + 'lgpl-3.0+': {'id': 'LGPL-3.0+', 'deprecated': True}, + 'lgpl-3.0-only': {'id': 'LGPL-3.0-only', 'deprecated': False}, + 'lgpl-3.0-or-later': {'id': 'LGPL-3.0-or-later', 'deprecated': False}, + 'lgpllr': {'id': 'LGPLLR', 'deprecated': False}, + 'libpng': {'id': 'Libpng', 'deprecated': False}, + 'libpng-2.0': {'id': 'libpng-2.0', 'deprecated': False}, + 'libselinux-1.0': {'id': 'libselinux-1.0', 'deprecated': False}, + 'libtiff': {'id': 'libtiff', 'deprecated': False}, + 'libutil-david-nugent': {'id': 'libutil-David-Nugent', 'deprecated': False}, + 'liliq-p-1.1': {'id': 'LiLiQ-P-1.1', 'deprecated': False}, + 'liliq-r-1.1': {'id': 'LiLiQ-R-1.1', 'deprecated': False}, + 'liliq-rplus-1.1': {'id': 'LiLiQ-Rplus-1.1', 'deprecated': False}, + 'linux-man-pages-1-para': {'id': 'Linux-man-pages-1-para', 'deprecated': False}, + 'linux-man-pages-copyleft': {'id': 'Linux-man-pages-copyleft', 'deprecated': False}, + 'linux-man-pages-copyleft-2-para': {'id': 'Linux-man-pages-copyleft-2-para', 'deprecated': False}, + 'linux-man-pages-copyleft-var': {'id': 'Linux-man-pages-copyleft-var', 'deprecated': False}, + 'linux-openib': {'id': 'Linux-OpenIB', 'deprecated': False}, + 'loop': {'id': 'LOOP', 'deprecated': False}, + 'lpd-document': {'id': 'LPD-document', 'deprecated': False}, + 'lpl-1.0': {'id': 'LPL-1.0', 'deprecated': False}, + 'lpl-1.02': {'id': 'LPL-1.02', 'deprecated': False}, + 'lppl-1.0': {'id': 'LPPL-1.0', 'deprecated': False}, + 'lppl-1.1': {'id': 'LPPL-1.1', 'deprecated': False}, + 'lppl-1.2': {'id': 'LPPL-1.2', 'deprecated': False}, + 'lppl-1.3a': {'id': 'LPPL-1.3a', 'deprecated': False}, + 'lppl-1.3c': {'id': 'LPPL-1.3c', 'deprecated': False}, + 'lsof': {'id': 'lsof', 'deprecated': False}, + 'lucida-bitmap-fonts': {'id': 'Lucida-Bitmap-Fonts', 'deprecated': False}, + 'lzma-sdk-9.11-to-9.20': {'id': 'LZMA-SDK-9.11-to-9.20', 'deprecated': False}, + 'lzma-sdk-9.22': {'id': 'LZMA-SDK-9.22', 'deprecated': False}, + 'mackerras-3-clause': {'id': 'Mackerras-3-Clause', 'deprecated': False}, + 'mackerras-3-clause-acknowledgment': {'id': 'Mackerras-3-Clause-acknowledgment', 'deprecated': False}, + 'magaz': {'id': 'magaz', 'deprecated': False}, + 'mailprio': {'id': 'mailprio', 'deprecated': False}, + 'makeindex': {'id': 'MakeIndex', 'deprecated': False}, + 'martin-birgmeier': {'id': 'Martin-Birgmeier', 'deprecated': False}, + 'mcphee-slideshow': {'id': 'McPhee-slideshow', 'deprecated': False}, + 'metamail': {'id': 'metamail', 'deprecated': False}, + 'minpack': {'id': 'Minpack', 'deprecated': False}, + 'miros': {'id': 'MirOS', 'deprecated': False}, + 'mit': {'id': 'MIT', 'deprecated': False}, + 'mit-0': {'id': 'MIT-0', 'deprecated': False}, + 'mit-advertising': {'id': 'MIT-advertising', 'deprecated': False}, + 'mit-cmu': {'id': 'MIT-CMU', 'deprecated': False}, + 'mit-enna': {'id': 'MIT-enna', 'deprecated': False}, + 'mit-feh': {'id': 'MIT-feh', 'deprecated': False}, + 'mit-festival': {'id': 'MIT-Festival', 'deprecated': False}, + 'mit-khronos-old': {'id': 'MIT-Khronos-old', 'deprecated': False}, + 'mit-modern-variant': {'id': 'MIT-Modern-Variant', 'deprecated': False}, + 'mit-open-group': {'id': 'MIT-open-group', 'deprecated': False}, + 'mit-testregex': {'id': 'MIT-testregex', 'deprecated': False}, + 'mit-wu': {'id': 'MIT-Wu', 'deprecated': False}, + 'mitnfa': {'id': 'MITNFA', 'deprecated': False}, + 'mmixware': {'id': 'MMIXware', 'deprecated': False}, + 'motosoto': {'id': 'Motosoto', 'deprecated': False}, + 'mpeg-ssg': {'id': 'MPEG-SSG', 'deprecated': False}, + 'mpi-permissive': {'id': 'mpi-permissive', 'deprecated': False}, + 'mpich2': {'id': 'mpich2', 'deprecated': False}, + 'mpl-1.0': {'id': 'MPL-1.0', 'deprecated': False}, + 'mpl-1.1': {'id': 'MPL-1.1', 'deprecated': False}, + 'mpl-2.0': {'id': 'MPL-2.0', 'deprecated': False}, + 'mpl-2.0-no-copyleft-exception': {'id': 'MPL-2.0-no-copyleft-exception', 'deprecated': False}, + 'mplus': {'id': 'mplus', 'deprecated': False}, + 'ms-lpl': {'id': 'MS-LPL', 'deprecated': False}, + 'ms-pl': {'id': 'MS-PL', 'deprecated': False}, + 'ms-rl': {'id': 'MS-RL', 'deprecated': False}, + 'mtll': {'id': 'MTLL', 'deprecated': False}, + 'mulanpsl-1.0': {'id': 'MulanPSL-1.0', 'deprecated': False}, + 'mulanpsl-2.0': {'id': 'MulanPSL-2.0', 'deprecated': False}, + 'multics': {'id': 'Multics', 'deprecated': False}, + 'mup': {'id': 'Mup', 'deprecated': False}, + 'naist-2003': {'id': 'NAIST-2003', 'deprecated': False}, + 'nasa-1.3': {'id': 'NASA-1.3', 'deprecated': False}, + 'naumen': {'id': 'Naumen', 'deprecated': False}, + 'nbpl-1.0': {'id': 'NBPL-1.0', 'deprecated': False}, + 'ncbi-pd': {'id': 'NCBI-PD', 'deprecated': False}, + 'ncgl-uk-2.0': {'id': 'NCGL-UK-2.0', 'deprecated': False}, + 'ncl': {'id': 'NCL', 'deprecated': False}, + 'ncsa': {'id': 'NCSA', 'deprecated': False}, + 'net-snmp': {'id': 'Net-SNMP', 'deprecated': True}, + 'netcdf': {'id': 'NetCDF', 'deprecated': False}, + 'newsletr': {'id': 'Newsletr', 'deprecated': False}, + 'ngpl': {'id': 'NGPL', 'deprecated': False}, + 'nicta-1.0': {'id': 'NICTA-1.0', 'deprecated': False}, + 'nist-pd': {'id': 'NIST-PD', 'deprecated': False}, + 'nist-pd-fallback': {'id': 'NIST-PD-fallback', 'deprecated': False}, + 'nist-software': {'id': 'NIST-Software', 'deprecated': False}, + 'nlod-1.0': {'id': 'NLOD-1.0', 'deprecated': False}, + 'nlod-2.0': {'id': 'NLOD-2.0', 'deprecated': False}, + 'nlpl': {'id': 'NLPL', 'deprecated': False}, + 'nokia': {'id': 'Nokia', 'deprecated': False}, + 'nosl': {'id': 'NOSL', 'deprecated': False}, + 'noweb': {'id': 'Noweb', 'deprecated': False}, + 'npl-1.0': {'id': 'NPL-1.0', 'deprecated': False}, + 'npl-1.1': {'id': 'NPL-1.1', 'deprecated': False}, + 'nposl-3.0': {'id': 'NPOSL-3.0', 'deprecated': False}, + 'nrl': {'id': 'NRL', 'deprecated': False}, + 'ntp': {'id': 'NTP', 'deprecated': False}, + 'ntp-0': {'id': 'NTP-0', 'deprecated': False}, + 'nunit': {'id': 'Nunit', 'deprecated': True}, + 'o-uda-1.0': {'id': 'O-UDA-1.0', 'deprecated': False}, + 'oar': {'id': 'OAR', 'deprecated': False}, + 'occt-pl': {'id': 'OCCT-PL', 'deprecated': False}, + 'oclc-2.0': {'id': 'OCLC-2.0', 'deprecated': False}, + 'odbl-1.0': {'id': 'ODbL-1.0', 'deprecated': False}, + 'odc-by-1.0': {'id': 'ODC-By-1.0', 'deprecated': False}, + 'offis': {'id': 'OFFIS', 'deprecated': False}, + 'ofl-1.0': {'id': 'OFL-1.0', 'deprecated': False}, + 'ofl-1.0-no-rfn': {'id': 'OFL-1.0-no-RFN', 'deprecated': False}, + 'ofl-1.0-rfn': {'id': 'OFL-1.0-RFN', 'deprecated': False}, + 'ofl-1.1': {'id': 'OFL-1.1', 'deprecated': False}, + 'ofl-1.1-no-rfn': {'id': 'OFL-1.1-no-RFN', 'deprecated': False}, + 'ofl-1.1-rfn': {'id': 'OFL-1.1-RFN', 'deprecated': False}, + 'ogc-1.0': {'id': 'OGC-1.0', 'deprecated': False}, + 'ogdl-taiwan-1.0': {'id': 'OGDL-Taiwan-1.0', 'deprecated': False}, + 'ogl-canada-2.0': {'id': 'OGL-Canada-2.0', 'deprecated': False}, + 'ogl-uk-1.0': {'id': 'OGL-UK-1.0', 'deprecated': False}, + 'ogl-uk-2.0': {'id': 'OGL-UK-2.0', 'deprecated': False}, + 'ogl-uk-3.0': {'id': 'OGL-UK-3.0', 'deprecated': False}, + 'ogtsl': {'id': 'OGTSL', 'deprecated': False}, + 'oldap-1.1': {'id': 'OLDAP-1.1', 'deprecated': False}, + 'oldap-1.2': {'id': 'OLDAP-1.2', 'deprecated': False}, + 'oldap-1.3': {'id': 'OLDAP-1.3', 'deprecated': False}, + 'oldap-1.4': {'id': 'OLDAP-1.4', 'deprecated': False}, + 'oldap-2.0': {'id': 'OLDAP-2.0', 'deprecated': False}, + 'oldap-2.0.1': {'id': 'OLDAP-2.0.1', 'deprecated': False}, + 'oldap-2.1': {'id': 'OLDAP-2.1', 'deprecated': False}, + 'oldap-2.2': {'id': 'OLDAP-2.2', 'deprecated': False}, + 'oldap-2.2.1': {'id': 'OLDAP-2.2.1', 'deprecated': False}, + 'oldap-2.2.2': {'id': 'OLDAP-2.2.2', 'deprecated': False}, + 'oldap-2.3': {'id': 'OLDAP-2.3', 'deprecated': False}, + 'oldap-2.4': {'id': 'OLDAP-2.4', 'deprecated': False}, + 'oldap-2.5': {'id': 'OLDAP-2.5', 'deprecated': False}, + 'oldap-2.6': {'id': 'OLDAP-2.6', 'deprecated': False}, + 'oldap-2.7': {'id': 'OLDAP-2.7', 'deprecated': False}, + 'oldap-2.8': {'id': 'OLDAP-2.8', 'deprecated': False}, + 'olfl-1.3': {'id': 'OLFL-1.3', 'deprecated': False}, + 'oml': {'id': 'OML', 'deprecated': False}, + 'openpbs-2.3': {'id': 'OpenPBS-2.3', 'deprecated': False}, + 'openssl': {'id': 'OpenSSL', 'deprecated': False}, + 'openssl-standalone': {'id': 'OpenSSL-standalone', 'deprecated': False}, + 'openvision': {'id': 'OpenVision', 'deprecated': False}, + 'opl-1.0': {'id': 'OPL-1.0', 'deprecated': False}, + 'opl-uk-3.0': {'id': 'OPL-UK-3.0', 'deprecated': False}, + 'opubl-1.0': {'id': 'OPUBL-1.0', 'deprecated': False}, + 'oset-pl-2.1': {'id': 'OSET-PL-2.1', 'deprecated': False}, + 'osl-1.0': {'id': 'OSL-1.0', 'deprecated': False}, + 'osl-1.1': {'id': 'OSL-1.1', 'deprecated': False}, + 'osl-2.0': {'id': 'OSL-2.0', 'deprecated': False}, + 'osl-2.1': {'id': 'OSL-2.1', 'deprecated': False}, + 'osl-3.0': {'id': 'OSL-3.0', 'deprecated': False}, + 'padl': {'id': 'PADL', 'deprecated': False}, + 'parity-6.0.0': {'id': 'Parity-6.0.0', 'deprecated': False}, + 'parity-7.0.0': {'id': 'Parity-7.0.0', 'deprecated': False}, + 'pddl-1.0': {'id': 'PDDL-1.0', 'deprecated': False}, + 'php-3.0': {'id': 'PHP-3.0', 'deprecated': False}, + 'php-3.01': {'id': 'PHP-3.01', 'deprecated': False}, + 'pixar': {'id': 'Pixar', 'deprecated': False}, + 'pkgconf': {'id': 'pkgconf', 'deprecated': False}, + 'plexus': {'id': 'Plexus', 'deprecated': False}, + 'pnmstitch': {'id': 'pnmstitch', 'deprecated': False}, + 'polyform-noncommercial-1.0.0': {'id': 'PolyForm-Noncommercial-1.0.0', 'deprecated': False}, + 'polyform-small-business-1.0.0': {'id': 'PolyForm-Small-Business-1.0.0', 'deprecated': False}, + 'postgresql': {'id': 'PostgreSQL', 'deprecated': False}, + 'ppl': {'id': 'PPL', 'deprecated': False}, + 'psf-2.0': {'id': 'PSF-2.0', 'deprecated': False}, + 'psfrag': {'id': 'psfrag', 'deprecated': False}, + 'psutils': {'id': 'psutils', 'deprecated': False}, + 'python-2.0': {'id': 'Python-2.0', 'deprecated': False}, + 'python-2.0.1': {'id': 'Python-2.0.1', 'deprecated': False}, + 'python-ldap': {'id': 'python-ldap', 'deprecated': False}, + 'qhull': {'id': 'Qhull', 'deprecated': False}, + 'qpl-1.0': {'id': 'QPL-1.0', 'deprecated': False}, + 'qpl-1.0-inria-2004': {'id': 'QPL-1.0-INRIA-2004', 'deprecated': False}, + 'radvd': {'id': 'radvd', 'deprecated': False}, + 'rdisc': {'id': 'Rdisc', 'deprecated': False}, + 'rhecos-1.1': {'id': 'RHeCos-1.1', 'deprecated': False}, + 'rpl-1.1': {'id': 'RPL-1.1', 'deprecated': False}, + 'rpl-1.5': {'id': 'RPL-1.5', 'deprecated': False}, + 'rpsl-1.0': {'id': 'RPSL-1.0', 'deprecated': False}, + 'rsa-md': {'id': 'RSA-MD', 'deprecated': False}, + 'rscpl': {'id': 'RSCPL', 'deprecated': False}, + 'ruby': {'id': 'Ruby', 'deprecated': False}, + 'ruby-pty': {'id': 'Ruby-pty', 'deprecated': False}, + 'sax-pd': {'id': 'SAX-PD', 'deprecated': False}, + 'sax-pd-2.0': {'id': 'SAX-PD-2.0', 'deprecated': False}, + 'saxpath': {'id': 'Saxpath', 'deprecated': False}, + 'scea': {'id': 'SCEA', 'deprecated': False}, + 'schemereport': {'id': 'SchemeReport', 'deprecated': False}, + 'sendmail': {'id': 'Sendmail', 'deprecated': False}, + 'sendmail-8.23': {'id': 'Sendmail-8.23', 'deprecated': False}, + 'sgi-b-1.0': {'id': 'SGI-B-1.0', 'deprecated': False}, + 'sgi-b-1.1': {'id': 'SGI-B-1.1', 'deprecated': False}, + 'sgi-b-2.0': {'id': 'SGI-B-2.0', 'deprecated': False}, + 'sgi-opengl': {'id': 'SGI-OpenGL', 'deprecated': False}, + 'sgp4': {'id': 'SGP4', 'deprecated': False}, + 'shl-0.5': {'id': 'SHL-0.5', 'deprecated': False}, + 'shl-0.51': {'id': 'SHL-0.51', 'deprecated': False}, + 'simpl-2.0': {'id': 'SimPL-2.0', 'deprecated': False}, + 'sissl': {'id': 'SISSL', 'deprecated': False}, + 'sissl-1.2': {'id': 'SISSL-1.2', 'deprecated': False}, + 'sl': {'id': 'SL', 'deprecated': False}, + 'sleepycat': {'id': 'Sleepycat', 'deprecated': False}, + 'smlnj': {'id': 'SMLNJ', 'deprecated': False}, + 'smppl': {'id': 'SMPPL', 'deprecated': False}, + 'snia': {'id': 'SNIA', 'deprecated': False}, + 'snprintf': {'id': 'snprintf', 'deprecated': False}, + 'softsurfer': {'id': 'softSurfer', 'deprecated': False}, + 'soundex': {'id': 'Soundex', 'deprecated': False}, + 'spencer-86': {'id': 'Spencer-86', 'deprecated': False}, + 'spencer-94': {'id': 'Spencer-94', 'deprecated': False}, + 'spencer-99': {'id': 'Spencer-99', 'deprecated': False}, + 'spl-1.0': {'id': 'SPL-1.0', 'deprecated': False}, + 'ssh-keyscan': {'id': 'ssh-keyscan', 'deprecated': False}, + 'ssh-openssh': {'id': 'SSH-OpenSSH', 'deprecated': False}, + 'ssh-short': {'id': 'SSH-short', 'deprecated': False}, + 'ssleay-standalone': {'id': 'SSLeay-standalone', 'deprecated': False}, + 'sspl-1.0': {'id': 'SSPL-1.0', 'deprecated': False}, + 'standardml-nj': {'id': 'StandardML-NJ', 'deprecated': True}, + 'sugarcrm-1.1.3': {'id': 'SugarCRM-1.1.3', 'deprecated': False}, + 'sun-ppp': {'id': 'Sun-PPP', 'deprecated': False}, + 'sun-ppp-2000': {'id': 'Sun-PPP-2000', 'deprecated': False}, + 'sunpro': {'id': 'SunPro', 'deprecated': False}, + 'swl': {'id': 'SWL', 'deprecated': False}, + 'swrule': {'id': 'swrule', 'deprecated': False}, + 'symlinks': {'id': 'Symlinks', 'deprecated': False}, + 'tapr-ohl-1.0': {'id': 'TAPR-OHL-1.0', 'deprecated': False}, + 'tcl': {'id': 'TCL', 'deprecated': False}, + 'tcp-wrappers': {'id': 'TCP-wrappers', 'deprecated': False}, + 'termreadkey': {'id': 'TermReadKey', 'deprecated': False}, + 'tgppl-1.0': {'id': 'TGPPL-1.0', 'deprecated': False}, + 'threeparttable': {'id': 'threeparttable', 'deprecated': False}, + 'tmate': {'id': 'TMate', 'deprecated': False}, + 'torque-1.1': {'id': 'TORQUE-1.1', 'deprecated': False}, + 'tosl': {'id': 'TOSL', 'deprecated': False}, + 'tpdl': {'id': 'TPDL', 'deprecated': False}, + 'tpl-1.0': {'id': 'TPL-1.0', 'deprecated': False}, + 'ttwl': {'id': 'TTWL', 'deprecated': False}, + 'ttyp0': {'id': 'TTYP0', 'deprecated': False}, + 'tu-berlin-1.0': {'id': 'TU-Berlin-1.0', 'deprecated': False}, + 'tu-berlin-2.0': {'id': 'TU-Berlin-2.0', 'deprecated': False}, + 'ubuntu-font-1.0': {'id': 'Ubuntu-font-1.0', 'deprecated': False}, + 'ucar': {'id': 'UCAR', 'deprecated': False}, + 'ucl-1.0': {'id': 'UCL-1.0', 'deprecated': False}, + 'ulem': {'id': 'ulem', 'deprecated': False}, + 'umich-merit': {'id': 'UMich-Merit', 'deprecated': False}, + 'unicode-3.0': {'id': 'Unicode-3.0', 'deprecated': False}, + 'unicode-dfs-2015': {'id': 'Unicode-DFS-2015', 'deprecated': False}, + 'unicode-dfs-2016': {'id': 'Unicode-DFS-2016', 'deprecated': False}, + 'unicode-tou': {'id': 'Unicode-TOU', 'deprecated': False}, + 'unixcrypt': {'id': 'UnixCrypt', 'deprecated': False}, + 'unlicense': {'id': 'Unlicense', 'deprecated': False}, + 'upl-1.0': {'id': 'UPL-1.0', 'deprecated': False}, + 'urt-rle': {'id': 'URT-RLE', 'deprecated': False}, + 'vim': {'id': 'Vim', 'deprecated': False}, + 'vostrom': {'id': 'VOSTROM', 'deprecated': False}, + 'vsl-1.0': {'id': 'VSL-1.0', 'deprecated': False}, + 'w3c': {'id': 'W3C', 'deprecated': False}, + 'w3c-19980720': {'id': 'W3C-19980720', 'deprecated': False}, + 'w3c-20150513': {'id': 'W3C-20150513', 'deprecated': False}, + 'w3m': {'id': 'w3m', 'deprecated': False}, + 'watcom-1.0': {'id': 'Watcom-1.0', 'deprecated': False}, + 'widget-workshop': {'id': 'Widget-Workshop', 'deprecated': False}, + 'wsuipa': {'id': 'Wsuipa', 'deprecated': False}, + 'wtfpl': {'id': 'WTFPL', 'deprecated': False}, + 'wxwindows': {'id': 'wxWindows', 'deprecated': True}, + 'x11': {'id': 'X11', 'deprecated': False}, + 'x11-distribute-modifications-variant': {'id': 'X11-distribute-modifications-variant', 'deprecated': False}, + 'x11-swapped': {'id': 'X11-swapped', 'deprecated': False}, + 'xdebug-1.03': {'id': 'Xdebug-1.03', 'deprecated': False}, + 'xerox': {'id': 'Xerox', 'deprecated': False}, + 'xfig': {'id': 'Xfig', 'deprecated': False}, + 'xfree86-1.1': {'id': 'XFree86-1.1', 'deprecated': False}, + 'xinetd': {'id': 'xinetd', 'deprecated': False}, + 'xkeyboard-config-zinoviev': {'id': 'xkeyboard-config-Zinoviev', 'deprecated': False}, + 'xlock': {'id': 'xlock', 'deprecated': False}, + 'xnet': {'id': 'Xnet', 'deprecated': False}, + 'xpp': {'id': 'xpp', 'deprecated': False}, + 'xskat': {'id': 'XSkat', 'deprecated': False}, + 'xzoom': {'id': 'xzoom', 'deprecated': False}, + 'ypl-1.0': {'id': 'YPL-1.0', 'deprecated': False}, + 'ypl-1.1': {'id': 'YPL-1.1', 'deprecated': False}, + 'zed': {'id': 'Zed', 'deprecated': False}, + 'zeeff': {'id': 'Zeeff', 'deprecated': False}, + 'zend-2.0': {'id': 'Zend-2.0', 'deprecated': False}, + 'zimbra-1.3': {'id': 'Zimbra-1.3', 'deprecated': False}, + 'zimbra-1.4': {'id': 'Zimbra-1.4', 'deprecated': False}, + 'zlib': {'id': 'Zlib', 'deprecated': False}, + 'zlib-acknowledgement': {'id': 'zlib-acknowledgement', 'deprecated': False}, + 'zpl-1.1': {'id': 'ZPL-1.1', 'deprecated': False}, + 'zpl-2.0': {'id': 'ZPL-2.0', 'deprecated': False}, + 'zpl-2.1': {'id': 'ZPL-2.1', 'deprecated': False}, +} + +EXCEPTIONS: dict[str, SPDXException] = { + '389-exception': {'id': '389-exception', 'deprecated': False}, + 'asterisk-exception': {'id': 'Asterisk-exception', 'deprecated': False}, + 'asterisk-linking-protocols-exception': {'id': 'Asterisk-linking-protocols-exception', 'deprecated': False}, + 'autoconf-exception-2.0': {'id': 'Autoconf-exception-2.0', 'deprecated': False}, + 'autoconf-exception-3.0': {'id': 'Autoconf-exception-3.0', 'deprecated': False}, + 'autoconf-exception-generic': {'id': 'Autoconf-exception-generic', 'deprecated': False}, + 'autoconf-exception-generic-3.0': {'id': 'Autoconf-exception-generic-3.0', 'deprecated': False}, + 'autoconf-exception-macro': {'id': 'Autoconf-exception-macro', 'deprecated': False}, + 'bison-exception-1.24': {'id': 'Bison-exception-1.24', 'deprecated': False}, + 'bison-exception-2.2': {'id': 'Bison-exception-2.2', 'deprecated': False}, + 'bootloader-exception': {'id': 'Bootloader-exception', 'deprecated': False}, + 'classpath-exception-2.0': {'id': 'Classpath-exception-2.0', 'deprecated': False}, + 'clisp-exception-2.0': {'id': 'CLISP-exception-2.0', 'deprecated': False}, + 'cryptsetup-openssl-exception': {'id': 'cryptsetup-OpenSSL-exception', 'deprecated': False}, + 'digirule-foss-exception': {'id': 'DigiRule-FOSS-exception', 'deprecated': False}, + 'ecos-exception-2.0': {'id': 'eCos-exception-2.0', 'deprecated': False}, + 'erlang-otp-linking-exception': {'id': 'erlang-otp-linking-exception', 'deprecated': False}, + 'fawkes-runtime-exception': {'id': 'Fawkes-Runtime-exception', 'deprecated': False}, + 'fltk-exception': {'id': 'FLTK-exception', 'deprecated': False}, + 'fmt-exception': {'id': 'fmt-exception', 'deprecated': False}, + 'font-exception-2.0': {'id': 'Font-exception-2.0', 'deprecated': False}, + 'freertos-exception-2.0': {'id': 'freertos-exception-2.0', 'deprecated': False}, + 'gcc-exception-2.0': {'id': 'GCC-exception-2.0', 'deprecated': False}, + 'gcc-exception-2.0-note': {'id': 'GCC-exception-2.0-note', 'deprecated': False}, + 'gcc-exception-3.1': {'id': 'GCC-exception-3.1', 'deprecated': False}, + 'gmsh-exception': {'id': 'Gmsh-exception', 'deprecated': False}, + 'gnat-exception': {'id': 'GNAT-exception', 'deprecated': False}, + 'gnome-examples-exception': {'id': 'GNOME-examples-exception', 'deprecated': False}, + 'gnu-compiler-exception': {'id': 'GNU-compiler-exception', 'deprecated': False}, + 'gnu-javamail-exception': {'id': 'gnu-javamail-exception', 'deprecated': False}, + 'gpl-3.0-interface-exception': {'id': 'GPL-3.0-interface-exception', 'deprecated': False}, + 'gpl-3.0-linking-exception': {'id': 'GPL-3.0-linking-exception', 'deprecated': False}, + 'gpl-3.0-linking-source-exception': {'id': 'GPL-3.0-linking-source-exception', 'deprecated': False}, + 'gpl-cc-1.0': {'id': 'GPL-CC-1.0', 'deprecated': False}, + 'gstreamer-exception-2005': {'id': 'GStreamer-exception-2005', 'deprecated': False}, + 'gstreamer-exception-2008': {'id': 'GStreamer-exception-2008', 'deprecated': False}, + 'i2p-gpl-java-exception': {'id': 'i2p-gpl-java-exception', 'deprecated': False}, + 'kicad-libraries-exception': {'id': 'KiCad-libraries-exception', 'deprecated': False}, + 'lgpl-3.0-linking-exception': {'id': 'LGPL-3.0-linking-exception', 'deprecated': False}, + 'libpri-openh323-exception': {'id': 'libpri-OpenH323-exception', 'deprecated': False}, + 'libtool-exception': {'id': 'Libtool-exception', 'deprecated': False}, + 'linux-syscall-note': {'id': 'Linux-syscall-note', 'deprecated': False}, + 'llgpl': {'id': 'LLGPL', 'deprecated': False}, + 'llvm-exception': {'id': 'LLVM-exception', 'deprecated': False}, + 'lzma-exception': {'id': 'LZMA-exception', 'deprecated': False}, + 'mif-exception': {'id': 'mif-exception', 'deprecated': False}, + 'nokia-qt-exception-1.1': {'id': 'Nokia-Qt-exception-1.1', 'deprecated': True}, + 'ocaml-lgpl-linking-exception': {'id': 'OCaml-LGPL-linking-exception', 'deprecated': False}, + 'occt-exception-1.0': {'id': 'OCCT-exception-1.0', 'deprecated': False}, + 'openjdk-assembly-exception-1.0': {'id': 'OpenJDK-assembly-exception-1.0', 'deprecated': False}, + 'openvpn-openssl-exception': {'id': 'openvpn-openssl-exception', 'deprecated': False}, + 'pcre2-exception': {'id': 'PCRE2-exception', 'deprecated': False}, + 'ps-or-pdf-font-exception-20170817': {'id': 'PS-or-PDF-font-exception-20170817', 'deprecated': False}, + 'qpl-1.0-inria-2004-exception': {'id': 'QPL-1.0-INRIA-2004-exception', 'deprecated': False}, + 'qt-gpl-exception-1.0': {'id': 'Qt-GPL-exception-1.0', 'deprecated': False}, + 'qt-lgpl-exception-1.1': {'id': 'Qt-LGPL-exception-1.1', 'deprecated': False}, + 'qwt-exception-1.0': {'id': 'Qwt-exception-1.0', 'deprecated': False}, + 'romic-exception': {'id': 'romic-exception', 'deprecated': False}, + 'rrdtool-floss-exception-2.0': {'id': 'RRDtool-FLOSS-exception-2.0', 'deprecated': False}, + 'sane-exception': {'id': 'SANE-exception', 'deprecated': False}, + 'shl-2.0': {'id': 'SHL-2.0', 'deprecated': False}, + 'shl-2.1': {'id': 'SHL-2.1', 'deprecated': False}, + 'stunnel-exception': {'id': 'stunnel-exception', 'deprecated': False}, + 'swi-exception': {'id': 'SWI-exception', 'deprecated': False}, + 'swift-exception': {'id': 'Swift-exception', 'deprecated': False}, + 'texinfo-exception': {'id': 'Texinfo-exception', 'deprecated': False}, + 'u-boot-exception-2.0': {'id': 'u-boot-exception-2.0', 'deprecated': False}, + 'ubdl-exception': {'id': 'UBDL-exception', 'deprecated': False}, + 'universal-foss-exception-1.0': {'id': 'Universal-FOSS-exception-1.0', 'deprecated': False}, + 'vsftpd-openssl-exception': {'id': 'vsftpd-openssl-exception', 'deprecated': False}, + 'wxwindows-exception-3.1': {'id': 'WxWindows-exception-3.1', 'deprecated': False}, + 'x11vnc-openssl-exception': {'id': 'x11vnc-openssl-exception', 'deprecated': False}, +} diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/markers.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/markers.py new file mode 100644 index 0000000000000000000000000000000000000000..fb7f49cf8cd43ffae71e3e8d15174d7536f9da02 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/markers.py @@ -0,0 +1,331 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import operator +import os +import platform +import sys +from typing import Any, Callable, TypedDict, cast + +from ._parser import MarkerAtom, MarkerList, Op, Value, Variable +from ._parser import parse_marker as _parse_marker +from ._tokenizer import ParserSyntaxError +from .specifiers import InvalidSpecifier, Specifier +from .utils import canonicalize_name + +__all__ = [ + "InvalidMarker", + "Marker", + "UndefinedComparison", + "UndefinedEnvironmentName", + "default_environment", +] + +Operator = Callable[[str, str], bool] + + +class InvalidMarker(ValueError): + """ + An invalid marker was found, users should refer to PEP 508. + """ + + +class UndefinedComparison(ValueError): + """ + An invalid operation was attempted on a value that doesn't support it. + """ + + +class UndefinedEnvironmentName(ValueError): + """ + A name was attempted to be used that does not exist inside of the + environment. + """ + + +class Environment(TypedDict): + implementation_name: str + """The implementation's identifier, e.g. ``'cpython'``.""" + + implementation_version: str + """ + The implementation's version, e.g. ``'3.13.0a2'`` for CPython 3.13.0a2, or + ``'7.3.13'`` for PyPy3.10 v7.3.13. + """ + + os_name: str + """ + The value of :py:data:`os.name`. The name of the operating system dependent module + imported, e.g. ``'posix'``. + """ + + platform_machine: str + """ + Returns the machine type, e.g. ``'i386'``. + + An empty string if the value cannot be determined. + """ + + platform_release: str + """ + The system's release, e.g. ``'2.2.0'`` or ``'NT'``. + + An empty string if the value cannot be determined. + """ + + platform_system: str + """ + The system/OS name, e.g. ``'Linux'``, ``'Windows'`` or ``'Java'``. + + An empty string if the value cannot be determined. + """ + + platform_version: str + """ + The system's release version, e.g. ``'#3 on degas'``. + + An empty string if the value cannot be determined. + """ + + python_full_version: str + """ + The Python version as string ``'major.minor.patchlevel'``. + + Note that unlike the Python :py:data:`sys.version`, this value will always include + the patchlevel (it defaults to 0). + """ + + platform_python_implementation: str + """ + A string identifying the Python implementation, e.g. ``'CPython'``. + """ + + python_version: str + """The Python version as string ``'major.minor'``.""" + + sys_platform: str + """ + This string contains a platform identifier that can be used to append + platform-specific components to :py:data:`sys.path`, for instance. + + For Unix systems, except on Linux and AIX, this is the lowercased OS name as + returned by ``uname -s`` with the first part of the version as returned by + ``uname -r`` appended, e.g. ``'sunos5'`` or ``'freebsd8'``, at the time when Python + was built. + """ + + +def _normalize_extra_values(results: Any) -> Any: + """ + Normalize extra values. + """ + if isinstance(results[0], tuple): + lhs, op, rhs = results[0] + if isinstance(lhs, Variable) and lhs.value == "extra": + normalized_extra = canonicalize_name(rhs.value) + rhs = Value(normalized_extra) + elif isinstance(rhs, Variable) and rhs.value == "extra": + normalized_extra = canonicalize_name(lhs.value) + lhs = Value(normalized_extra) + results[0] = lhs, op, rhs + return results + + +def _format_marker( + marker: list[str] | MarkerAtom | str, first: bool | None = True +) -> str: + assert isinstance(marker, (list, tuple, str)) + + # Sometimes we have a structure like [[...]] which is a single item list + # where the single item is itself it's own list. In that case we want skip + # the rest of this function so that we don't get extraneous () on the + # outside. + if ( + isinstance(marker, list) + and len(marker) == 1 + and isinstance(marker[0], (list, tuple)) + ): + return _format_marker(marker[0]) + + if isinstance(marker, list): + inner = (_format_marker(m, first=False) for m in marker) + if first: + return " ".join(inner) + else: + return "(" + " ".join(inner) + ")" + elif isinstance(marker, tuple): + return " ".join([m.serialize() for m in marker]) + else: + return marker + + +_operators: dict[str, Operator] = { + "in": lambda lhs, rhs: lhs in rhs, + "not in": lambda lhs, rhs: lhs not in rhs, + "<": operator.lt, + "<=": operator.le, + "==": operator.eq, + "!=": operator.ne, + ">=": operator.ge, + ">": operator.gt, +} + + +def _eval_op(lhs: str, op: Op, rhs: str) -> bool: + try: + spec = Specifier("".join([op.serialize(), rhs])) + except InvalidSpecifier: + pass + else: + return spec.contains(lhs, prereleases=True) + + oper: Operator | None = _operators.get(op.serialize()) + if oper is None: + raise UndefinedComparison(f"Undefined {op!r} on {lhs!r} and {rhs!r}.") + + return oper(lhs, rhs) + + +def _normalize(*values: str, key: str) -> tuple[str, ...]: + # PEP 685 – Comparison of extra names for optional distribution dependencies + # https://peps.python.org/pep-0685/ + # > When comparing extra names, tools MUST normalize the names being + # > compared using the semantics outlined in PEP 503 for names + if key == "extra": + return tuple(canonicalize_name(v) for v in values) + + # other environment markers don't have such standards + return values + + +def _evaluate_markers(markers: MarkerList, environment: dict[str, str]) -> bool: + groups: list[list[bool]] = [[]] + + for marker in markers: + assert isinstance(marker, (list, tuple, str)) + + if isinstance(marker, list): + groups[-1].append(_evaluate_markers(marker, environment)) + elif isinstance(marker, tuple): + lhs, op, rhs = marker + + if isinstance(lhs, Variable): + environment_key = lhs.value + lhs_value = environment[environment_key] + rhs_value = rhs.value + else: + lhs_value = lhs.value + environment_key = rhs.value + rhs_value = environment[environment_key] + + lhs_value, rhs_value = _normalize(lhs_value, rhs_value, key=environment_key) + groups[-1].append(_eval_op(lhs_value, op, rhs_value)) + else: + assert marker in ["and", "or"] + if marker == "or": + groups.append([]) + + return any(all(item) for item in groups) + + +def format_full_version(info: sys._version_info) -> str: + version = f"{info.major}.{info.minor}.{info.micro}" + kind = info.releaselevel + if kind != "final": + version += kind[0] + str(info.serial) + return version + + +def default_environment() -> Environment: + iver = format_full_version(sys.implementation.version) + implementation_name = sys.implementation.name + return { + "implementation_name": implementation_name, + "implementation_version": iver, + "os_name": os.name, + "platform_machine": platform.machine(), + "platform_release": platform.release(), + "platform_system": platform.system(), + "platform_version": platform.version(), + "python_full_version": platform.python_version(), + "platform_python_implementation": platform.python_implementation(), + "python_version": ".".join(platform.python_version_tuple()[:2]), + "sys_platform": sys.platform, + } + + +class Marker: + def __init__(self, marker: str) -> None: + # Note: We create a Marker object without calling this constructor in + # packaging.requirements.Requirement. If any additional logic is + # added here, make sure to mirror/adapt Requirement. + try: + self._markers = _normalize_extra_values(_parse_marker(marker)) + # The attribute `_markers` can be described in terms of a recursive type: + # MarkerList = List[Union[Tuple[Node, ...], str, MarkerList]] + # + # For example, the following expression: + # python_version > "3.6" or (python_version == "3.6" and os_name == "unix") + # + # is parsed into: + # [ + # (, ')>, ), + # 'and', + # [ + # (, , ), + # 'or', + # (, , ) + # ] + # ] + except ParserSyntaxError as e: + raise InvalidMarker(str(e)) from e + + def __str__(self) -> str: + return _format_marker(self._markers) + + def __repr__(self) -> str: + return f"" + + def __hash__(self) -> int: + return hash((self.__class__.__name__, str(self))) + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, Marker): + return NotImplemented + + return str(self) == str(other) + + def evaluate(self, environment: dict[str, str] | None = None) -> bool: + """Evaluate a marker. + + Return the boolean from evaluating the given marker against the + environment. environment is an optional argument to override all or + part of the determined environment. + + The environment is determined from the current Python process. + """ + current_environment = cast("dict[str, str]", default_environment()) + current_environment["extra"] = "" + if environment is not None: + current_environment.update(environment) + # The API used to allow setting extra to None. We need to handle this + # case for backwards compatibility. + if current_environment["extra"] is None: + current_environment["extra"] = "" + + return _evaluate_markers( + self._markers, _repair_python_full_version(current_environment) + ) + + +def _repair_python_full_version(env: dict[str, str]) -> dict[str, str]: + """ + Work around platform.python_version() returning something that is not PEP 440 + compliant for non-tagged Python builds. + """ + if env["python_full_version"].endswith("+"): + env["python_full_version"] += "local" + return env diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/metadata.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..721f411cfc44f6d24c13112e4246b5ad776a5e0b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/metadata.py @@ -0,0 +1,863 @@ +from __future__ import annotations + +import email.feedparser +import email.header +import email.message +import email.parser +import email.policy +import pathlib +import sys +import typing +from typing import ( + Any, + Callable, + Generic, + Literal, + TypedDict, + cast, +) + +from . import licenses, requirements, specifiers, utils +from . import version as version_module +from .licenses import NormalizedLicenseExpression + +T = typing.TypeVar("T") + + +if sys.version_info >= (3, 11): # pragma: no cover + ExceptionGroup = ExceptionGroup +else: # pragma: no cover + + class ExceptionGroup(Exception): + """A minimal implementation of :external:exc:`ExceptionGroup` from Python 3.11. + + If :external:exc:`ExceptionGroup` is already defined by Python itself, + that version is used instead. + """ + + message: str + exceptions: list[Exception] + + def __init__(self, message: str, exceptions: list[Exception]) -> None: + self.message = message + self.exceptions = exceptions + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.message!r}, {self.exceptions!r})" + + +class InvalidMetadata(ValueError): + """A metadata field contains invalid data.""" + + field: str + """The name of the field that contains invalid data.""" + + def __init__(self, field: str, message: str) -> None: + self.field = field + super().__init__(message) + + +# The RawMetadata class attempts to make as few assumptions about the underlying +# serialization formats as possible. The idea is that as long as a serialization +# formats offer some very basic primitives in *some* way then we can support +# serializing to and from that format. +class RawMetadata(TypedDict, total=False): + """A dictionary of raw core metadata. + + Each field in core metadata maps to a key of this dictionary (when data is + provided). The key is lower-case and underscores are used instead of dashes + compared to the equivalent core metadata field. Any core metadata field that + can be specified multiple times or can hold multiple values in a single + field have a key with a plural name. See :class:`Metadata` whose attributes + match the keys of this dictionary. + + Core metadata fields that can be specified multiple times are stored as a + list or dict depending on which is appropriate for the field. Any fields + which hold multiple values in a single field are stored as a list. + + """ + + # Metadata 1.0 - PEP 241 + metadata_version: str + name: str + version: str + platforms: list[str] + summary: str + description: str + keywords: list[str] + home_page: str + author: str + author_email: str + license: str + + # Metadata 1.1 - PEP 314 + supported_platforms: list[str] + download_url: str + classifiers: list[str] + requires: list[str] + provides: list[str] + obsoletes: list[str] + + # Metadata 1.2 - PEP 345 + maintainer: str + maintainer_email: str + requires_dist: list[str] + provides_dist: list[str] + obsoletes_dist: list[str] + requires_python: str + requires_external: list[str] + project_urls: dict[str, str] + + # Metadata 2.0 + # PEP 426 attempted to completely revamp the metadata format + # but got stuck without ever being able to build consensus on + # it and ultimately ended up withdrawn. + # + # However, a number of tools had started emitting METADATA with + # `2.0` Metadata-Version, so for historical reasons, this version + # was skipped. + + # Metadata 2.1 - PEP 566 + description_content_type: str + provides_extra: list[str] + + # Metadata 2.2 - PEP 643 + dynamic: list[str] + + # Metadata 2.3 - PEP 685 + # No new fields were added in PEP 685, just some edge case were + # tightened up to provide better interoptability. + + # Metadata 2.4 - PEP 639 + license_expression: str + license_files: list[str] + + +_STRING_FIELDS = { + "author", + "author_email", + "description", + "description_content_type", + "download_url", + "home_page", + "license", + "license_expression", + "maintainer", + "maintainer_email", + "metadata_version", + "name", + "requires_python", + "summary", + "version", +} + +_LIST_FIELDS = { + "classifiers", + "dynamic", + "license_files", + "obsoletes", + "obsoletes_dist", + "platforms", + "provides", + "provides_dist", + "provides_extra", + "requires", + "requires_dist", + "requires_external", + "supported_platforms", +} + +_DICT_FIELDS = { + "project_urls", +} + + +def _parse_keywords(data: str) -> list[str]: + """Split a string of comma-separated keywords into a list of keywords.""" + return [k.strip() for k in data.split(",")] + + +def _parse_project_urls(data: list[str]) -> dict[str, str]: + """Parse a list of label/URL string pairings separated by a comma.""" + urls = {} + for pair in data: + # Our logic is slightly tricky here as we want to try and do + # *something* reasonable with malformed data. + # + # The main thing that we have to worry about, is data that does + # not have a ',' at all to split the label from the Value. There + # isn't a singular right answer here, and we will fail validation + # later on (if the caller is validating) so it doesn't *really* + # matter, but since the missing value has to be an empty str + # and our return value is dict[str, str], if we let the key + # be the missing value, then they'd have multiple '' values that + # overwrite each other in a accumulating dict. + # + # The other potentional issue is that it's possible to have the + # same label multiple times in the metadata, with no solid "right" + # answer with what to do in that case. As such, we'll do the only + # thing we can, which is treat the field as unparseable and add it + # to our list of unparsed fields. + parts = [p.strip() for p in pair.split(",", 1)] + parts.extend([""] * (max(0, 2 - len(parts)))) # Ensure 2 items + + # TODO: The spec doesn't say anything about if the keys should be + # considered case sensitive or not... logically they should + # be case-preserving and case-insensitive, but doing that + # would open up more cases where we might have duplicate + # entries. + label, url = parts + if label in urls: + # The label already exists in our set of urls, so this field + # is unparseable, and we can just add the whole thing to our + # unparseable data and stop processing it. + raise KeyError("duplicate labels in project urls") + urls[label] = url + + return urls + + +def _get_payload(msg: email.message.Message, source: bytes | str) -> str: + """Get the body of the message.""" + # If our source is a str, then our caller has managed encodings for us, + # and we don't need to deal with it. + if isinstance(source, str): + payload = msg.get_payload() + assert isinstance(payload, str) + return payload + # If our source is a bytes, then we're managing the encoding and we need + # to deal with it. + else: + bpayload = msg.get_payload(decode=True) + assert isinstance(bpayload, bytes) + try: + return bpayload.decode("utf8", "strict") + except UnicodeDecodeError as exc: + raise ValueError("payload in an invalid encoding") from exc + + +# The various parse_FORMAT functions here are intended to be as lenient as +# possible in their parsing, while still returning a correctly typed +# RawMetadata. +# +# To aid in this, we also generally want to do as little touching of the +# data as possible, except where there are possibly some historic holdovers +# that make valid data awkward to work with. +# +# While this is a lower level, intermediate format than our ``Metadata`` +# class, some light touch ups can make a massive difference in usability. + +# Map METADATA fields to RawMetadata. +_EMAIL_TO_RAW_MAPPING = { + "author": "author", + "author-email": "author_email", + "classifier": "classifiers", + "description": "description", + "description-content-type": "description_content_type", + "download-url": "download_url", + "dynamic": "dynamic", + "home-page": "home_page", + "keywords": "keywords", + "license": "license", + "license-expression": "license_expression", + "license-file": "license_files", + "maintainer": "maintainer", + "maintainer-email": "maintainer_email", + "metadata-version": "metadata_version", + "name": "name", + "obsoletes": "obsoletes", + "obsoletes-dist": "obsoletes_dist", + "platform": "platforms", + "project-url": "project_urls", + "provides": "provides", + "provides-dist": "provides_dist", + "provides-extra": "provides_extra", + "requires": "requires", + "requires-dist": "requires_dist", + "requires-external": "requires_external", + "requires-python": "requires_python", + "summary": "summary", + "supported-platform": "supported_platforms", + "version": "version", +} +_RAW_TO_EMAIL_MAPPING = {raw: email for email, raw in _EMAIL_TO_RAW_MAPPING.items()} + + +def parse_email(data: bytes | str) -> tuple[RawMetadata, dict[str, list[str]]]: + """Parse a distribution's metadata stored as email headers (e.g. from ``METADATA``). + + This function returns a two-item tuple of dicts. The first dict is of + recognized fields from the core metadata specification. Fields that can be + parsed and translated into Python's built-in types are converted + appropriately. All other fields are left as-is. Fields that are allowed to + appear multiple times are stored as lists. + + The second dict contains all other fields from the metadata. This includes + any unrecognized fields. It also includes any fields which are expected to + be parsed into a built-in type but were not formatted appropriately. Finally, + any fields that are expected to appear only once but are repeated are + included in this dict. + + """ + raw: dict[str, str | list[str] | dict[str, str]] = {} + unparsed: dict[str, list[str]] = {} + + if isinstance(data, str): + parsed = email.parser.Parser(policy=email.policy.compat32).parsestr(data) + else: + parsed = email.parser.BytesParser(policy=email.policy.compat32).parsebytes(data) + + # We have to wrap parsed.keys() in a set, because in the case of multiple + # values for a key (a list), the key will appear multiple times in the + # list of keys, but we're avoiding that by using get_all(). + for name in frozenset(parsed.keys()): + # Header names in RFC are case insensitive, so we'll normalize to all + # lower case to make comparisons easier. + name = name.lower() + + # We use get_all() here, even for fields that aren't multiple use, + # because otherwise someone could have e.g. two Name fields, and we + # would just silently ignore it rather than doing something about it. + headers = parsed.get_all(name) or [] + + # The way the email module works when parsing bytes is that it + # unconditionally decodes the bytes as ascii using the surrogateescape + # handler. When you pull that data back out (such as with get_all() ), + # it looks to see if the str has any surrogate escapes, and if it does + # it wraps it in a Header object instead of returning the string. + # + # As such, we'll look for those Header objects, and fix up the encoding. + value = [] + # Flag if we have run into any issues processing the headers, thus + # signalling that the data belongs in 'unparsed'. + valid_encoding = True + for h in headers: + # It's unclear if this can return more types than just a Header or + # a str, so we'll just assert here to make sure. + assert isinstance(h, (email.header.Header, str)) + + # If it's a header object, we need to do our little dance to get + # the real data out of it. In cases where there is invalid data + # we're going to end up with mojibake, but there's no obvious, good + # way around that without reimplementing parts of the Header object + # ourselves. + # + # That should be fine since, if mojibacked happens, this key is + # going into the unparsed dict anyways. + if isinstance(h, email.header.Header): + # The Header object stores it's data as chunks, and each chunk + # can be independently encoded, so we'll need to check each + # of them. + chunks: list[tuple[bytes, str | None]] = [] + for bin, encoding in email.header.decode_header(h): + try: + bin.decode("utf8", "strict") + except UnicodeDecodeError: + # Enable mojibake. + encoding = "latin1" + valid_encoding = False + else: + encoding = "utf8" + chunks.append((bin, encoding)) + + # Turn our chunks back into a Header object, then let that + # Header object do the right thing to turn them into a + # string for us. + value.append(str(email.header.make_header(chunks))) + # This is already a string, so just add it. + else: + value.append(h) + + # We've processed all of our values to get them into a list of str, + # but we may have mojibake data, in which case this is an unparsed + # field. + if not valid_encoding: + unparsed[name] = value + continue + + raw_name = _EMAIL_TO_RAW_MAPPING.get(name) + if raw_name is None: + # This is a bit of a weird situation, we've encountered a key that + # we don't know what it means, so we don't know whether it's meant + # to be a list or not. + # + # Since we can't really tell one way or another, we'll just leave it + # as a list, even though it may be a single item list, because that's + # what makes the most sense for email headers. + unparsed[name] = value + continue + + # If this is one of our string fields, then we'll check to see if our + # value is a list of a single item. If it is then we'll assume that + # it was emitted as a single string, and unwrap the str from inside + # the list. + # + # If it's any other kind of data, then we haven't the faintest clue + # what we should parse it as, and we have to just add it to our list + # of unparsed stuff. + if raw_name in _STRING_FIELDS and len(value) == 1: + raw[raw_name] = value[0] + # If this is one of our list of string fields, then we can just assign + # the value, since email *only* has strings, and our get_all() call + # above ensures that this is a list. + elif raw_name in _LIST_FIELDS: + raw[raw_name] = value + # Special Case: Keywords + # The keywords field is implemented in the metadata spec as a str, + # but it conceptually is a list of strings, and is serialized using + # ", ".join(keywords), so we'll do some light data massaging to turn + # this into what it logically is. + elif raw_name == "keywords" and len(value) == 1: + raw[raw_name] = _parse_keywords(value[0]) + # Special Case: Project-URL + # The project urls is implemented in the metadata spec as a list of + # specially-formatted strings that represent a key and a value, which + # is fundamentally a mapping, however the email format doesn't support + # mappings in a sane way, so it was crammed into a list of strings + # instead. + # + # We will do a little light data massaging to turn this into a map as + # it logically should be. + elif raw_name == "project_urls": + try: + raw[raw_name] = _parse_project_urls(value) + except KeyError: + unparsed[name] = value + # Nothing that we've done has managed to parse this, so it'll just + # throw it in our unparseable data and move on. + else: + unparsed[name] = value + + # We need to support getting the Description from the message payload in + # addition to getting it from the the headers. This does mean, though, there + # is the possibility of it being set both ways, in which case we put both + # in 'unparsed' since we don't know which is right. + try: + payload = _get_payload(parsed, data) + except ValueError: + unparsed.setdefault("description", []).append( + parsed.get_payload(decode=isinstance(data, bytes)) # type: ignore[call-overload] + ) + else: + if payload: + # Check to see if we've already got a description, if so then both + # it, and this body move to unparseable. + if "description" in raw: + description_header = cast(str, raw.pop("description")) + unparsed.setdefault("description", []).extend( + [description_header, payload] + ) + elif "description" in unparsed: + unparsed["description"].append(payload) + else: + raw["description"] = payload + + # We need to cast our `raw` to a metadata, because a TypedDict only support + # literal key names, but we're computing our key names on purpose, but the + # way this function is implemented, our `TypedDict` can only have valid key + # names. + return cast(RawMetadata, raw), unparsed + + +_NOT_FOUND = object() + + +# Keep the two values in sync. +_VALID_METADATA_VERSIONS = ["1.0", "1.1", "1.2", "2.1", "2.2", "2.3", "2.4"] +_MetadataVersion = Literal["1.0", "1.1", "1.2", "2.1", "2.2", "2.3", "2.4"] + +_REQUIRED_ATTRS = frozenset(["metadata_version", "name", "version"]) + + +class _Validator(Generic[T]): + """Validate a metadata field. + + All _process_*() methods correspond to a core metadata field. The method is + called with the field's raw value. If the raw value is valid it is returned + in its "enriched" form (e.g. ``version.Version`` for the ``Version`` field). + If the raw value is invalid, :exc:`InvalidMetadata` is raised (with a cause + as appropriate). + """ + + name: str + raw_name: str + added: _MetadataVersion + + def __init__( + self, + *, + added: _MetadataVersion = "1.0", + ) -> None: + self.added = added + + def __set_name__(self, _owner: Metadata, name: str) -> None: + self.name = name + self.raw_name = _RAW_TO_EMAIL_MAPPING[name] + + def __get__(self, instance: Metadata, _owner: type[Metadata]) -> T: + # With Python 3.8, the caching can be replaced with functools.cached_property(). + # No need to check the cache as attribute lookup will resolve into the + # instance's __dict__ before __get__ is called. + cache = instance.__dict__ + value = instance._raw.get(self.name) + + # To make the _process_* methods easier, we'll check if the value is None + # and if this field is NOT a required attribute, and if both of those + # things are true, we'll skip the the converter. This will mean that the + # converters never have to deal with the None union. + if self.name in _REQUIRED_ATTRS or value is not None: + try: + converter: Callable[[Any], T] = getattr(self, f"_process_{self.name}") + except AttributeError: + pass + else: + value = converter(value) + + cache[self.name] = value + try: + del instance._raw[self.name] # type: ignore[misc] + except KeyError: + pass + + return cast(T, value) + + def _invalid_metadata( + self, msg: str, cause: Exception | None = None + ) -> InvalidMetadata: + exc = InvalidMetadata( + self.raw_name, msg.format_map({"field": repr(self.raw_name)}) + ) + exc.__cause__ = cause + return exc + + def _process_metadata_version(self, value: str) -> _MetadataVersion: + # Implicitly makes Metadata-Version required. + if value not in _VALID_METADATA_VERSIONS: + raise self._invalid_metadata(f"{value!r} is not a valid metadata version") + return cast(_MetadataVersion, value) + + def _process_name(self, value: str) -> str: + if not value: + raise self._invalid_metadata("{field} is a required field") + # Validate the name as a side-effect. + try: + utils.canonicalize_name(value, validate=True) + except utils.InvalidName as exc: + raise self._invalid_metadata( + f"{value!r} is invalid for {{field}}", cause=exc + ) from exc + else: + return value + + def _process_version(self, value: str) -> version_module.Version: + if not value: + raise self._invalid_metadata("{field} is a required field") + try: + return version_module.parse(value) + except version_module.InvalidVersion as exc: + raise self._invalid_metadata( + f"{value!r} is invalid for {{field}}", cause=exc + ) from exc + + def _process_summary(self, value: str) -> str: + """Check the field contains no newlines.""" + if "\n" in value: + raise self._invalid_metadata("{field} must be a single line") + return value + + def _process_description_content_type(self, value: str) -> str: + content_types = {"text/plain", "text/x-rst", "text/markdown"} + message = email.message.EmailMessage() + message["content-type"] = value + + content_type, parameters = ( + # Defaults to `text/plain` if parsing failed. + message.get_content_type().lower(), + message["content-type"].params, + ) + # Check if content-type is valid or defaulted to `text/plain` and thus was + # not parseable. + if content_type not in content_types or content_type not in value.lower(): + raise self._invalid_metadata( + f"{{field}} must be one of {list(content_types)}, not {value!r}" + ) + + charset = parameters.get("charset", "UTF-8") + if charset != "UTF-8": + raise self._invalid_metadata( + f"{{field}} can only specify the UTF-8 charset, not {list(charset)}" + ) + + markdown_variants = {"GFM", "CommonMark"} + variant = parameters.get("variant", "GFM") # Use an acceptable default. + if content_type == "text/markdown" and variant not in markdown_variants: + raise self._invalid_metadata( + f"valid Markdown variants for {{field}} are {list(markdown_variants)}, " + f"not {variant!r}", + ) + return value + + def _process_dynamic(self, value: list[str]) -> list[str]: + for dynamic_field in map(str.lower, value): + if dynamic_field in {"name", "version", "metadata-version"}: + raise self._invalid_metadata( + f"{dynamic_field!r} is not allowed as a dynamic field" + ) + elif dynamic_field not in _EMAIL_TO_RAW_MAPPING: + raise self._invalid_metadata( + f"{dynamic_field!r} is not a valid dynamic field" + ) + return list(map(str.lower, value)) + + def _process_provides_extra( + self, + value: list[str], + ) -> list[utils.NormalizedName]: + normalized_names = [] + try: + for name in value: + normalized_names.append(utils.canonicalize_name(name, validate=True)) + except utils.InvalidName as exc: + raise self._invalid_metadata( + f"{name!r} is invalid for {{field}}", cause=exc + ) from exc + else: + return normalized_names + + def _process_requires_python(self, value: str) -> specifiers.SpecifierSet: + try: + return specifiers.SpecifierSet(value) + except specifiers.InvalidSpecifier as exc: + raise self._invalid_metadata( + f"{value!r} is invalid for {{field}}", cause=exc + ) from exc + + def _process_requires_dist( + self, + value: list[str], + ) -> list[requirements.Requirement]: + reqs = [] + try: + for req in value: + reqs.append(requirements.Requirement(req)) + except requirements.InvalidRequirement as exc: + raise self._invalid_metadata( + f"{req!r} is invalid for {{field}}", cause=exc + ) from exc + else: + return reqs + + def _process_license_expression( + self, value: str + ) -> NormalizedLicenseExpression | None: + try: + return licenses.canonicalize_license_expression(value) + except ValueError as exc: + raise self._invalid_metadata( + f"{value!r} is invalid for {{field}}", cause=exc + ) from exc + + def _process_license_files(self, value: list[str]) -> list[str]: + paths = [] + for path in value: + if ".." in path: + raise self._invalid_metadata( + f"{path!r} is invalid for {{field}}, " + "parent directory indicators are not allowed" + ) + if "*" in path: + raise self._invalid_metadata( + f"{path!r} is invalid for {{field}}, paths must be resolved" + ) + if ( + pathlib.PurePosixPath(path).is_absolute() + or pathlib.PureWindowsPath(path).is_absolute() + ): + raise self._invalid_metadata( + f"{path!r} is invalid for {{field}}, paths must be relative" + ) + if pathlib.PureWindowsPath(path).as_posix() != path: + raise self._invalid_metadata( + f"{path!r} is invalid for {{field}}, " + "paths must use '/' delimiter" + ) + paths.append(path) + return paths + + +class Metadata: + """Representation of distribution metadata. + + Compared to :class:`RawMetadata`, this class provides objects representing + metadata fields instead of only using built-in types. Any invalid metadata + will cause :exc:`InvalidMetadata` to be raised (with a + :py:attr:`~BaseException.__cause__` attribute as appropriate). + """ + + _raw: RawMetadata + + @classmethod + def from_raw(cls, data: RawMetadata, *, validate: bool = True) -> Metadata: + """Create an instance from :class:`RawMetadata`. + + If *validate* is true, all metadata will be validated. All exceptions + related to validation will be gathered and raised as an :class:`ExceptionGroup`. + """ + ins = cls() + ins._raw = data.copy() # Mutations occur due to caching enriched values. + + if validate: + exceptions: list[Exception] = [] + try: + metadata_version = ins.metadata_version + metadata_age = _VALID_METADATA_VERSIONS.index(metadata_version) + except InvalidMetadata as metadata_version_exc: + exceptions.append(metadata_version_exc) + metadata_version = None + + # Make sure to check for the fields that are present, the required + # fields (so their absence can be reported). + fields_to_check = frozenset(ins._raw) | _REQUIRED_ATTRS + # Remove fields that have already been checked. + fields_to_check -= {"metadata_version"} + + for key in fields_to_check: + try: + if metadata_version: + # Can't use getattr() as that triggers descriptor protocol which + # will fail due to no value for the instance argument. + try: + field_metadata_version = cls.__dict__[key].added + except KeyError: + exc = InvalidMetadata(key, f"unrecognized field: {key!r}") + exceptions.append(exc) + continue + field_age = _VALID_METADATA_VERSIONS.index( + field_metadata_version + ) + if field_age > metadata_age: + field = _RAW_TO_EMAIL_MAPPING[key] + exc = InvalidMetadata( + field, + f"{field} introduced in metadata version " + f"{field_metadata_version}, not {metadata_version}", + ) + exceptions.append(exc) + continue + getattr(ins, key) + except InvalidMetadata as exc: + exceptions.append(exc) + + if exceptions: + raise ExceptionGroup("invalid metadata", exceptions) + + return ins + + @classmethod + def from_email(cls, data: bytes | str, *, validate: bool = True) -> Metadata: + """Parse metadata from email headers. + + If *validate* is true, the metadata will be validated. All exceptions + related to validation will be gathered and raised as an :class:`ExceptionGroup`. + """ + raw, unparsed = parse_email(data) + + if validate: + exceptions: list[Exception] = [] + for unparsed_key in unparsed: + if unparsed_key in _EMAIL_TO_RAW_MAPPING: + message = f"{unparsed_key!r} has invalid data" + else: + message = f"unrecognized field: {unparsed_key!r}" + exceptions.append(InvalidMetadata(unparsed_key, message)) + + if exceptions: + raise ExceptionGroup("unparsed", exceptions) + + try: + return cls.from_raw(raw, validate=validate) + except ExceptionGroup as exc_group: + raise ExceptionGroup( + "invalid or unparsed metadata", exc_group.exceptions + ) from None + + metadata_version: _Validator[_MetadataVersion] = _Validator() + """:external:ref:`core-metadata-metadata-version` + (required; validated to be a valid metadata version)""" + # `name` is not normalized/typed to NormalizedName so as to provide access to + # the original/raw name. + name: _Validator[str] = _Validator() + """:external:ref:`core-metadata-name` + (required; validated using :func:`~packaging.utils.canonicalize_name` and its + *validate* parameter)""" + version: _Validator[version_module.Version] = _Validator() + """:external:ref:`core-metadata-version` (required)""" + dynamic: _Validator[list[str] | None] = _Validator( + added="2.2", + ) + """:external:ref:`core-metadata-dynamic` + (validated against core metadata field names and lowercased)""" + platforms: _Validator[list[str] | None] = _Validator() + """:external:ref:`core-metadata-platform`""" + supported_platforms: _Validator[list[str] | None] = _Validator(added="1.1") + """:external:ref:`core-metadata-supported-platform`""" + summary: _Validator[str | None] = _Validator() + """:external:ref:`core-metadata-summary` (validated to contain no newlines)""" + description: _Validator[str | None] = _Validator() # TODO 2.1: can be in body + """:external:ref:`core-metadata-description`""" + description_content_type: _Validator[str | None] = _Validator(added="2.1") + """:external:ref:`core-metadata-description-content-type` (validated)""" + keywords: _Validator[list[str] | None] = _Validator() + """:external:ref:`core-metadata-keywords`""" + home_page: _Validator[str | None] = _Validator() + """:external:ref:`core-metadata-home-page`""" + download_url: _Validator[str | None] = _Validator(added="1.1") + """:external:ref:`core-metadata-download-url`""" + author: _Validator[str | None] = _Validator() + """:external:ref:`core-metadata-author`""" + author_email: _Validator[str | None] = _Validator() + """:external:ref:`core-metadata-author-email`""" + maintainer: _Validator[str | None] = _Validator(added="1.2") + """:external:ref:`core-metadata-maintainer`""" + maintainer_email: _Validator[str | None] = _Validator(added="1.2") + """:external:ref:`core-metadata-maintainer-email`""" + license: _Validator[str | None] = _Validator() + """:external:ref:`core-metadata-license`""" + license_expression: _Validator[NormalizedLicenseExpression | None] = _Validator( + added="2.4" + ) + """:external:ref:`core-metadata-license-expression`""" + license_files: _Validator[list[str] | None] = _Validator(added="2.4") + """:external:ref:`core-metadata-license-file`""" + classifiers: _Validator[list[str] | None] = _Validator(added="1.1") + """:external:ref:`core-metadata-classifier`""" + requires_dist: _Validator[list[requirements.Requirement] | None] = _Validator( + added="1.2" + ) + """:external:ref:`core-metadata-requires-dist`""" + requires_python: _Validator[specifiers.SpecifierSet | None] = _Validator( + added="1.2" + ) + """:external:ref:`core-metadata-requires-python`""" + # Because `Requires-External` allows for non-PEP 440 version specifiers, we + # don't do any processing on the values. + requires_external: _Validator[list[str] | None] = _Validator(added="1.2") + """:external:ref:`core-metadata-requires-external`""" + project_urls: _Validator[dict[str, str] | None] = _Validator(added="1.2") + """:external:ref:`core-metadata-project-url`""" + # PEP 685 lets us raise an error if an extra doesn't pass `Name` validation + # regardless of metadata version. + provides_extra: _Validator[list[utils.NormalizedName] | None] = _Validator( + added="2.1", + ) + """:external:ref:`core-metadata-provides-extra`""" + provides_dist: _Validator[list[str] | None] = _Validator(added="1.2") + """:external:ref:`core-metadata-provides-dist`""" + obsoletes_dist: _Validator[list[str] | None] = _Validator(added="1.2") + """:external:ref:`core-metadata-obsoletes-dist`""" + requires: _Validator[list[str] | None] = _Validator(added="1.1") + """``Requires`` (deprecated)""" + provides: _Validator[list[str] | None] = _Validator(added="1.1") + """``Provides`` (deprecated)""" + obsoletes: _Validator[list[str] | None] = _Validator(added="1.1") + """``Obsoletes`` (deprecated)""" diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/py.typed b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/requirements.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/requirements.py new file mode 100644 index 0000000000000000000000000000000000000000..4e068c9567def3564f238a76fe7ab46b569f33e5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/requirements.py @@ -0,0 +1,91 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. +from __future__ import annotations + +from typing import Any, Iterator + +from ._parser import parse_requirement as _parse_requirement +from ._tokenizer import ParserSyntaxError +from .markers import Marker, _normalize_extra_values +from .specifiers import SpecifierSet +from .utils import canonicalize_name + + +class InvalidRequirement(ValueError): + """ + An invalid requirement was found, users should refer to PEP 508. + """ + + +class Requirement: + """Parse a requirement. + + Parse a given requirement string into its parts, such as name, specifier, + URL, and extras. Raises InvalidRequirement on a badly-formed requirement + string. + """ + + # TODO: Can we test whether something is contained within a requirement? + # If so how do we do that? Do we need to test against the _name_ of + # the thing as well as the version? What about the markers? + # TODO: Can we normalize the name and extra name? + + def __init__(self, requirement_string: str) -> None: + try: + parsed = _parse_requirement(requirement_string) + except ParserSyntaxError as e: + raise InvalidRequirement(str(e)) from e + + self.name: str = parsed.name + self.url: str | None = parsed.url or None + self.extras: set[str] = set(parsed.extras or []) + self.specifier: SpecifierSet = SpecifierSet(parsed.specifier) + self.marker: Marker | None = None + if parsed.marker is not None: + self.marker = Marker.__new__(Marker) + self.marker._markers = _normalize_extra_values(parsed.marker) + + def _iter_parts(self, name: str) -> Iterator[str]: + yield name + + if self.extras: + formatted_extras = ",".join(sorted(self.extras)) + yield f"[{formatted_extras}]" + + if self.specifier: + yield str(self.specifier) + + if self.url: + yield f"@ {self.url}" + if self.marker: + yield " " + + if self.marker: + yield f"; {self.marker}" + + def __str__(self) -> str: + return "".join(self._iter_parts(self.name)) + + def __repr__(self) -> str: + return f"" + + def __hash__(self) -> int: + return hash( + ( + self.__class__.__name__, + *self._iter_parts(canonicalize_name(self.name)), + ) + ) + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, Requirement): + return NotImplemented + + return ( + canonicalize_name(self.name) == canonicalize_name(other.name) + and self.extras == other.extras + and self.specifier == other.specifier + and self.url == other.url + and self.marker == other.marker + ) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/specifiers.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/specifiers.py new file mode 100644 index 0000000000000000000000000000000000000000..b30926af8bf4f47efe98eea44d5ded4cb6f7e07d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/specifiers.py @@ -0,0 +1,1020 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. +""" +.. testsetup:: + + from packaging.specifiers import Specifier, SpecifierSet, InvalidSpecifier + from packaging.version import Version +""" + +from __future__ import annotations + +import abc +import itertools +import re +from typing import Callable, Iterable, Iterator, TypeVar, Union + +from .utils import canonicalize_version +from .version import Version + +UnparsedVersion = Union[Version, str] +UnparsedVersionVar = TypeVar("UnparsedVersionVar", bound=UnparsedVersion) +CallableOperator = Callable[[Version, str], bool] + + +def _coerce_version(version: UnparsedVersion) -> Version: + if not isinstance(version, Version): + version = Version(version) + return version + + +class InvalidSpecifier(ValueError): + """ + Raised when attempting to create a :class:`Specifier` with a specifier + string that is invalid. + + >>> Specifier("lolwat") + Traceback (most recent call last): + ... + packaging.specifiers.InvalidSpecifier: Invalid specifier: 'lolwat' + """ + + +class BaseSpecifier(metaclass=abc.ABCMeta): + @abc.abstractmethod + def __str__(self) -> str: + """ + Returns the str representation of this Specifier-like object. This + should be representative of the Specifier itself. + """ + + @abc.abstractmethod + def __hash__(self) -> int: + """ + Returns a hash value for this Specifier-like object. + """ + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Returns a boolean representing whether or not the two Specifier-like + objects are equal. + + :param other: The other object to check against. + """ + + @property + @abc.abstractmethod + def prereleases(self) -> bool | None: + """Whether or not pre-releases as a whole are allowed. + + This can be set to either ``True`` or ``False`` to explicitly enable or disable + prereleases or it can be set to ``None`` (the default) to use default semantics. + """ + + @prereleases.setter + def prereleases(self, value: bool) -> None: + """Setter for :attr:`prereleases`. + + :param value: The value to set. + """ + + @abc.abstractmethod + def contains(self, item: str, prereleases: bool | None = None) -> bool: + """ + Determines if the given item is contained within this specifier. + """ + + @abc.abstractmethod + def filter( + self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None + ) -> Iterator[UnparsedVersionVar]: + """ + Takes an iterable of items and filters them so that only items which + are contained within this specifier are allowed in it. + """ + + +class Specifier(BaseSpecifier): + """This class abstracts handling of version specifiers. + + .. tip:: + + It is generally not required to instantiate this manually. You should instead + prefer to work with :class:`SpecifierSet` instead, which can parse + comma-separated version specifiers (which is what package metadata contains). + """ + + _operator_regex_str = r""" + (?P(~=|==|!=|<=|>=|<|>|===)) + """ + _version_regex_str = r""" + (?P + (?: + # The identity operators allow for an escape hatch that will + # do an exact string match of the version you wish to install. + # This will not be parsed by PEP 440 and we cannot determine + # any semantic meaning from it. This operator is discouraged + # but included entirely as an escape hatch. + (?<====) # Only match for the identity operator + \s* + [^\s;)]* # The arbitrary version can be just about anything, + # we match everything except for whitespace, a + # semi-colon for marker support, and a closing paren + # since versions can be enclosed in them. + ) + | + (?: + # The (non)equality operators allow for wild card and local + # versions to be specified so we have to define these two + # operators separately to enable that. + (?<===|!=) # Only match for equals and not equals + + \s* + v? + (?:[0-9]+!)? # epoch + [0-9]+(?:\.[0-9]+)* # release + + # You cannot use a wild card and a pre-release, post-release, a dev or + # local version together so group them with a | and make them optional. + (?: + \.\* # Wild card syntax of .* + | + (?: # pre release + [-_\.]? + (alpha|beta|preview|pre|a|b|c|rc) + [-_\.]? + [0-9]* + )? + (?: # post release + (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) + )? + (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release + (?:\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*)? # local + )? + ) + | + (?: + # The compatible operator requires at least two digits in the + # release segment. + (?<=~=) # Only match for the compatible operator + + \s* + v? + (?:[0-9]+!)? # epoch + [0-9]+(?:\.[0-9]+)+ # release (We have a + instead of a *) + (?: # pre release + [-_\.]? + (alpha|beta|preview|pre|a|b|c|rc) + [-_\.]? + [0-9]* + )? + (?: # post release + (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) + )? + (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release + ) + | + (?: + # All other operators only allow a sub set of what the + # (non)equality operators do. Specifically they do not allow + # local versions to be specified nor do they allow the prefix + # matching wild cards. + (?=": "greater_than_equal", + "<": "less_than", + ">": "greater_than", + "===": "arbitrary", + } + + def __init__(self, spec: str = "", prereleases: bool | None = None) -> None: + """Initialize a Specifier instance. + + :param spec: + The string representation of a specifier which will be parsed and + normalized before use. + :param prereleases: + This tells the specifier if it should accept prerelease versions if + applicable or not. The default of ``None`` will autodetect it from the + given specifiers. + :raises InvalidSpecifier: + If the given specifier is invalid (i.e. bad syntax). + """ + match = self._regex.search(spec) + if not match: + raise InvalidSpecifier(f"Invalid specifier: {spec!r}") + + self._spec: tuple[str, str] = ( + match.group("operator").strip(), + match.group("version").strip(), + ) + + # Store whether or not this Specifier should accept prereleases + self._prereleases = prereleases + + # https://github.com/python/mypy/pull/13475#pullrequestreview-1079784515 + @property # type: ignore[override] + def prereleases(self) -> bool: + # If there is an explicit prereleases set for this, then we'll just + # blindly use that. + if self._prereleases is not None: + return self._prereleases + + # Look at all of our specifiers and determine if they are inclusive + # operators, and if they are if they are including an explicit + # prerelease. + operator, version = self._spec + if operator in ["==", ">=", "<=", "~=", "===", ">", "<"]: + # The == specifier can include a trailing .*, if it does we + # want to remove before parsing. + if operator == "==" and version.endswith(".*"): + version = version[:-2] + + # Parse the version, and if it is a pre-release than this + # specifier allows pre-releases. + if Version(version).is_prerelease: + return True + + return False + + @prereleases.setter + def prereleases(self, value: bool) -> None: + self._prereleases = value + + @property + def operator(self) -> str: + """The operator of this specifier. + + >>> Specifier("==1.2.3").operator + '==' + """ + return self._spec[0] + + @property + def version(self) -> str: + """The version of this specifier. + + >>> Specifier("==1.2.3").version + '1.2.3' + """ + return self._spec[1] + + def __repr__(self) -> str: + """A representation of the Specifier that shows all internal state. + + >>> Specifier('>=1.0.0') + =1.0.0')> + >>> Specifier('>=1.0.0', prereleases=False) + =1.0.0', prereleases=False)> + >>> Specifier('>=1.0.0', prereleases=True) + =1.0.0', prereleases=True)> + """ + pre = ( + f", prereleases={self.prereleases!r}" + if self._prereleases is not None + else "" + ) + + return f"<{self.__class__.__name__}({str(self)!r}{pre})>" + + def __str__(self) -> str: + """A string representation of the Specifier that can be round-tripped. + + >>> str(Specifier('>=1.0.0')) + '>=1.0.0' + >>> str(Specifier('>=1.0.0', prereleases=False)) + '>=1.0.0' + """ + return "{}{}".format(*self._spec) + + @property + def _canonical_spec(self) -> tuple[str, str]: + canonical_version = canonicalize_version( + self._spec[1], + strip_trailing_zero=(self._spec[0] != "~="), + ) + return self._spec[0], canonical_version + + def __hash__(self) -> int: + return hash(self._canonical_spec) + + def __eq__(self, other: object) -> bool: + """Whether or not the two Specifier-like objects are equal. + + :param other: The other object to check against. + + The value of :attr:`prereleases` is ignored. + + >>> Specifier("==1.2.3") == Specifier("== 1.2.3.0") + True + >>> (Specifier("==1.2.3", prereleases=False) == + ... Specifier("==1.2.3", prereleases=True)) + True + >>> Specifier("==1.2.3") == "==1.2.3" + True + >>> Specifier("==1.2.3") == Specifier("==1.2.4") + False + >>> Specifier("==1.2.3") == Specifier("~=1.2.3") + False + """ + if isinstance(other, str): + try: + other = self.__class__(str(other)) + except InvalidSpecifier: + return NotImplemented + elif not isinstance(other, self.__class__): + return NotImplemented + + return self._canonical_spec == other._canonical_spec + + def _get_operator(self, op: str) -> CallableOperator: + operator_callable: CallableOperator = getattr( + self, f"_compare_{self._operators[op]}" + ) + return operator_callable + + def _compare_compatible(self, prospective: Version, spec: str) -> bool: + # Compatible releases have an equivalent combination of >= and ==. That + # is that ~=2.2 is equivalent to >=2.2,==2.*. This allows us to + # implement this in terms of the other specifiers instead of + # implementing it ourselves. The only thing we need to do is construct + # the other specifiers. + + # We want everything but the last item in the version, but we want to + # ignore suffix segments. + prefix = _version_join( + list(itertools.takewhile(_is_not_suffix, _version_split(spec)))[:-1] + ) + + # Add the prefix notation to the end of our string + prefix += ".*" + + return self._get_operator(">=")(prospective, spec) and self._get_operator("==")( + prospective, prefix + ) + + def _compare_equal(self, prospective: Version, spec: str) -> bool: + # We need special logic to handle prefix matching + if spec.endswith(".*"): + # In the case of prefix matching we want to ignore local segment. + normalized_prospective = canonicalize_version( + prospective.public, strip_trailing_zero=False + ) + # Get the normalized version string ignoring the trailing .* + normalized_spec = canonicalize_version(spec[:-2], strip_trailing_zero=False) + # Split the spec out by bangs and dots, and pretend that there is + # an implicit dot in between a release segment and a pre-release segment. + split_spec = _version_split(normalized_spec) + + # Split the prospective version out by bangs and dots, and pretend + # that there is an implicit dot in between a release segment and + # a pre-release segment. + split_prospective = _version_split(normalized_prospective) + + # 0-pad the prospective version before shortening it to get the correct + # shortened version. + padded_prospective, _ = _pad_version(split_prospective, split_spec) + + # Shorten the prospective version to be the same length as the spec + # so that we can determine if the specifier is a prefix of the + # prospective version or not. + shortened_prospective = padded_prospective[: len(split_spec)] + + return shortened_prospective == split_spec + else: + # Convert our spec string into a Version + spec_version = Version(spec) + + # If the specifier does not have a local segment, then we want to + # act as if the prospective version also does not have a local + # segment. + if not spec_version.local: + prospective = Version(prospective.public) + + return prospective == spec_version + + def _compare_not_equal(self, prospective: Version, spec: str) -> bool: + return not self._compare_equal(prospective, spec) + + def _compare_less_than_equal(self, prospective: Version, spec: str) -> bool: + # NB: Local version identifiers are NOT permitted in the version + # specifier, so local version labels can be universally removed from + # the prospective version. + return Version(prospective.public) <= Version(spec) + + def _compare_greater_than_equal(self, prospective: Version, spec: str) -> bool: + # NB: Local version identifiers are NOT permitted in the version + # specifier, so local version labels can be universally removed from + # the prospective version. + return Version(prospective.public) >= Version(spec) + + def _compare_less_than(self, prospective: Version, spec_str: str) -> bool: + # Convert our spec to a Version instance, since we'll want to work with + # it as a version. + spec = Version(spec_str) + + # Check to see if the prospective version is less than the spec + # version. If it's not we can short circuit and just return False now + # instead of doing extra unneeded work. + if not prospective < spec: + return False + + # This special case is here so that, unless the specifier itself + # includes is a pre-release version, that we do not accept pre-release + # versions for the version mentioned in the specifier (e.g. <3.1 should + # not match 3.1.dev0, but should match 3.0.dev0). + if not spec.is_prerelease and prospective.is_prerelease: + if Version(prospective.base_version) == Version(spec.base_version): + return False + + # If we've gotten to here, it means that prospective version is both + # less than the spec version *and* it's not a pre-release of the same + # version in the spec. + return True + + def _compare_greater_than(self, prospective: Version, spec_str: str) -> bool: + # Convert our spec to a Version instance, since we'll want to work with + # it as a version. + spec = Version(spec_str) + + # Check to see if the prospective version is greater than the spec + # version. If it's not we can short circuit and just return False now + # instead of doing extra unneeded work. + if not prospective > spec: + return False + + # This special case is here so that, unless the specifier itself + # includes is a post-release version, that we do not accept + # post-release versions for the version mentioned in the specifier + # (e.g. >3.1 should not match 3.0.post0, but should match 3.2.post0). + if not spec.is_postrelease and prospective.is_postrelease: + if Version(prospective.base_version) == Version(spec.base_version): + return False + + # Ensure that we do not allow a local version of the version mentioned + # in the specifier, which is technically greater than, to match. + if prospective.local is not None: + if Version(prospective.base_version) == Version(spec.base_version): + return False + + # If we've gotten to here, it means that prospective version is both + # greater than the spec version *and* it's not a pre-release of the + # same version in the spec. + return True + + def _compare_arbitrary(self, prospective: Version, spec: str) -> bool: + return str(prospective).lower() == str(spec).lower() + + def __contains__(self, item: str | Version) -> bool: + """Return whether or not the item is contained in this specifier. + + :param item: The item to check for. + + This is used for the ``in`` operator and behaves the same as + :meth:`contains` with no ``prereleases`` argument passed. + + >>> "1.2.3" in Specifier(">=1.2.3") + True + >>> Version("1.2.3") in Specifier(">=1.2.3") + True + >>> "1.0.0" in Specifier(">=1.2.3") + False + >>> "1.3.0a1" in Specifier(">=1.2.3") + False + >>> "1.3.0a1" in Specifier(">=1.2.3", prereleases=True) + True + """ + return self.contains(item) + + def contains(self, item: UnparsedVersion, prereleases: bool | None = None) -> bool: + """Return whether or not the item is contained in this specifier. + + :param item: + The item to check for, which can be a version string or a + :class:`Version` instance. + :param prereleases: + Whether or not to match prereleases with this Specifier. If set to + ``None`` (the default), it uses :attr:`prereleases` to determine + whether or not prereleases are allowed. + + >>> Specifier(">=1.2.3").contains("1.2.3") + True + >>> Specifier(">=1.2.3").contains(Version("1.2.3")) + True + >>> Specifier(">=1.2.3").contains("1.0.0") + False + >>> Specifier(">=1.2.3").contains("1.3.0a1") + False + >>> Specifier(">=1.2.3", prereleases=True).contains("1.3.0a1") + True + >>> Specifier(">=1.2.3").contains("1.3.0a1", prereleases=True) + True + """ + + # Determine if prereleases are to be allowed or not. + if prereleases is None: + prereleases = self.prereleases + + # Normalize item to a Version, this allows us to have a shortcut for + # "2.0" in Specifier(">=2") + normalized_item = _coerce_version(item) + + # Determine if we should be supporting prereleases in this specifier + # or not, if we do not support prereleases than we can short circuit + # logic if this version is a prereleases. + if normalized_item.is_prerelease and not prereleases: + return False + + # Actually do the comparison to determine if this item is contained + # within this Specifier or not. + operator_callable: CallableOperator = self._get_operator(self.operator) + return operator_callable(normalized_item, self.version) + + def filter( + self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None + ) -> Iterator[UnparsedVersionVar]: + """Filter items in the given iterable, that match the specifier. + + :param iterable: + An iterable that can contain version strings and :class:`Version` instances. + The items in the iterable will be filtered according to the specifier. + :param prereleases: + Whether or not to allow prereleases in the returned iterator. If set to + ``None`` (the default), it will be intelligently decide whether to allow + prereleases or not (based on the :attr:`prereleases` attribute, and + whether the only versions matching are prereleases). + + This method is smarter than just ``filter(Specifier().contains, [...])`` + because it implements the rule from :pep:`440` that a prerelease item + SHOULD be accepted if no other versions match the given specifier. + + >>> list(Specifier(">=1.2.3").filter(["1.2", "1.3", "1.5a1"])) + ['1.3'] + >>> list(Specifier(">=1.2.3").filter(["1.2", "1.2.3", "1.3", Version("1.4")])) + ['1.2.3', '1.3', ] + >>> list(Specifier(">=1.2.3").filter(["1.2", "1.5a1"])) + ['1.5a1'] + >>> list(Specifier(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True)) + ['1.3', '1.5a1'] + >>> list(Specifier(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"])) + ['1.3', '1.5a1'] + """ + + yielded = False + found_prereleases = [] + + kw = {"prereleases": prereleases if prereleases is not None else True} + + # Attempt to iterate over all the values in the iterable and if any of + # them match, yield them. + for version in iterable: + parsed_version = _coerce_version(version) + + if self.contains(parsed_version, **kw): + # If our version is a prerelease, and we were not set to allow + # prereleases, then we'll store it for later in case nothing + # else matches this specifier. + if parsed_version.is_prerelease and not ( + prereleases or self.prereleases + ): + found_prereleases.append(version) + # Either this is not a prerelease, or we should have been + # accepting prereleases from the beginning. + else: + yielded = True + yield version + + # Now that we've iterated over everything, determine if we've yielded + # any values, and if we have not and we have any prereleases stored up + # then we will go ahead and yield the prereleases. + if not yielded and found_prereleases: + for version in found_prereleases: + yield version + + +_prefix_regex = re.compile(r"^([0-9]+)((?:a|b|c|rc)[0-9]+)$") + + +def _version_split(version: str) -> list[str]: + """Split version into components. + + The split components are intended for version comparison. The logic does + not attempt to retain the original version string, so joining the + components back with :func:`_version_join` may not produce the original + version string. + """ + result: list[str] = [] + + epoch, _, rest = version.rpartition("!") + result.append(epoch or "0") + + for item in rest.split("."): + match = _prefix_regex.search(item) + if match: + result.extend(match.groups()) + else: + result.append(item) + return result + + +def _version_join(components: list[str]) -> str: + """Join split version components into a version string. + + This function assumes the input came from :func:`_version_split`, where the + first component must be the epoch (either empty or numeric), and all other + components numeric. + """ + epoch, *rest = components + return f"{epoch}!{'.'.join(rest)}" + + +def _is_not_suffix(segment: str) -> bool: + return not any( + segment.startswith(prefix) for prefix in ("dev", "a", "b", "rc", "post") + ) + + +def _pad_version(left: list[str], right: list[str]) -> tuple[list[str], list[str]]: + left_split, right_split = [], [] + + # Get the release segment of our versions + left_split.append(list(itertools.takewhile(lambda x: x.isdigit(), left))) + right_split.append(list(itertools.takewhile(lambda x: x.isdigit(), right))) + + # Get the rest of our versions + left_split.append(left[len(left_split[0]) :]) + right_split.append(right[len(right_split[0]) :]) + + # Insert our padding + left_split.insert(1, ["0"] * max(0, len(right_split[0]) - len(left_split[0]))) + right_split.insert(1, ["0"] * max(0, len(left_split[0]) - len(right_split[0]))) + + return ( + list(itertools.chain.from_iterable(left_split)), + list(itertools.chain.from_iterable(right_split)), + ) + + +class SpecifierSet(BaseSpecifier): + """This class abstracts handling of a set of version specifiers. + + It can be passed a single specifier (``>=3.0``), a comma-separated list of + specifiers (``>=3.0,!=3.1``), or no specifier at all. + """ + + def __init__( + self, + specifiers: str | Iterable[Specifier] = "", + prereleases: bool | None = None, + ) -> None: + """Initialize a SpecifierSet instance. + + :param specifiers: + The string representation of a specifier or a comma-separated list of + specifiers which will be parsed and normalized before use. + May also be an iterable of ``Specifier`` instances, which will be used + as is. + :param prereleases: + This tells the SpecifierSet if it should accept prerelease versions if + applicable or not. The default of ``None`` will autodetect it from the + given specifiers. + + :raises InvalidSpecifier: + If the given ``specifiers`` are not parseable than this exception will be + raised. + """ + + if isinstance(specifiers, str): + # Split on `,` to break each individual specifier into its own item, and + # strip each item to remove leading/trailing whitespace. + split_specifiers = [s.strip() for s in specifiers.split(",") if s.strip()] + + # Make each individual specifier a Specifier and save in a frozen set + # for later. + self._specs = frozenset(map(Specifier, split_specifiers)) + else: + # Save the supplied specifiers in a frozen set. + self._specs = frozenset(specifiers) + + # Store our prereleases value so we can use it later to determine if + # we accept prereleases or not. + self._prereleases = prereleases + + @property + def prereleases(self) -> bool | None: + # If we have been given an explicit prerelease modifier, then we'll + # pass that through here. + if self._prereleases is not None: + return self._prereleases + + # If we don't have any specifiers, and we don't have a forced value, + # then we'll just return None since we don't know if this should have + # pre-releases or not. + if not self._specs: + return None + + # Otherwise we'll see if any of the given specifiers accept + # prereleases, if any of them do we'll return True, otherwise False. + return any(s.prereleases for s in self._specs) + + @prereleases.setter + def prereleases(self, value: bool) -> None: + self._prereleases = value + + def __repr__(self) -> str: + """A representation of the specifier set that shows all internal state. + + Note that the ordering of the individual specifiers within the set may not + match the input string. + + >>> SpecifierSet('>=1.0.0,!=2.0.0') + =1.0.0')> + >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=False) + =1.0.0', prereleases=False)> + >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=True) + =1.0.0', prereleases=True)> + """ + pre = ( + f", prereleases={self.prereleases!r}" + if self._prereleases is not None + else "" + ) + + return f"" + + def __str__(self) -> str: + """A string representation of the specifier set that can be round-tripped. + + Note that the ordering of the individual specifiers within the set may not + match the input string. + + >>> str(SpecifierSet(">=1.0.0,!=1.0.1")) + '!=1.0.1,>=1.0.0' + >>> str(SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False)) + '!=1.0.1,>=1.0.0' + """ + return ",".join(sorted(str(s) for s in self._specs)) + + def __hash__(self) -> int: + return hash(self._specs) + + def __and__(self, other: SpecifierSet | str) -> SpecifierSet: + """Return a SpecifierSet which is a combination of the two sets. + + :param other: The other object to combine with. + + >>> SpecifierSet(">=1.0.0,!=1.0.1") & '<=2.0.0,!=2.0.1' + =1.0.0')> + >>> SpecifierSet(">=1.0.0,!=1.0.1") & SpecifierSet('<=2.0.0,!=2.0.1') + =1.0.0')> + """ + if isinstance(other, str): + other = SpecifierSet(other) + elif not isinstance(other, SpecifierSet): + return NotImplemented + + specifier = SpecifierSet() + specifier._specs = frozenset(self._specs | other._specs) + + if self._prereleases is None and other._prereleases is not None: + specifier._prereleases = other._prereleases + elif self._prereleases is not None and other._prereleases is None: + specifier._prereleases = self._prereleases + elif self._prereleases == other._prereleases: + specifier._prereleases = self._prereleases + else: + raise ValueError( + "Cannot combine SpecifierSets with True and False prerelease " + "overrides." + ) + + return specifier + + def __eq__(self, other: object) -> bool: + """Whether or not the two SpecifierSet-like objects are equal. + + :param other: The other object to check against. + + The value of :attr:`prereleases` is ignored. + + >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.1") + True + >>> (SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False) == + ... SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True)) + True + >>> SpecifierSet(">=1.0.0,!=1.0.1") == ">=1.0.0,!=1.0.1" + True + >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0") + False + >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.2") + False + """ + if isinstance(other, (str, Specifier)): + other = SpecifierSet(str(other)) + elif not isinstance(other, SpecifierSet): + return NotImplemented + + return self._specs == other._specs + + def __len__(self) -> int: + """Returns the number of specifiers in this specifier set.""" + return len(self._specs) + + def __iter__(self) -> Iterator[Specifier]: + """ + Returns an iterator over all the underlying :class:`Specifier` instances + in this specifier set. + + >>> sorted(SpecifierSet(">=1.0.0,!=1.0.1"), key=str) + [, =1.0.0')>] + """ + return iter(self._specs) + + def __contains__(self, item: UnparsedVersion) -> bool: + """Return whether or not the item is contained in this specifier. + + :param item: The item to check for. + + This is used for the ``in`` operator and behaves the same as + :meth:`contains` with no ``prereleases`` argument passed. + + >>> "1.2.3" in SpecifierSet(">=1.0.0,!=1.0.1") + True + >>> Version("1.2.3") in SpecifierSet(">=1.0.0,!=1.0.1") + True + >>> "1.0.1" in SpecifierSet(">=1.0.0,!=1.0.1") + False + >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1") + False + >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True) + True + """ + return self.contains(item) + + def contains( + self, + item: UnparsedVersion, + prereleases: bool | None = None, + installed: bool | None = None, + ) -> bool: + """Return whether or not the item is contained in this SpecifierSet. + + :param item: + The item to check for, which can be a version string or a + :class:`Version` instance. + :param prereleases: + Whether or not to match prereleases with this SpecifierSet. If set to + ``None`` (the default), it uses :attr:`prereleases` to determine + whether or not prereleases are allowed. + + >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.2.3") + True + >>> SpecifierSet(">=1.0.0,!=1.0.1").contains(Version("1.2.3")) + True + >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.0.1") + False + >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1") + False + >>> SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True).contains("1.3.0a1") + True + >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1", prereleases=True) + True + """ + # Ensure that our item is a Version instance. + if not isinstance(item, Version): + item = Version(item) + + # Determine if we're forcing a prerelease or not, if we're not forcing + # one for this particular filter call, then we'll use whatever the + # SpecifierSet thinks for whether or not we should support prereleases. + if prereleases is None: + prereleases = self.prereleases + + # We can determine if we're going to allow pre-releases by looking to + # see if any of the underlying items supports them. If none of them do + # and this item is a pre-release then we do not allow it and we can + # short circuit that here. + # Note: This means that 1.0.dev1 would not be contained in something + # like >=1.0.devabc however it would be in >=1.0.debabc,>0.0.dev0 + if not prereleases and item.is_prerelease: + return False + + if installed and item.is_prerelease: + item = Version(item.base_version) + + # We simply dispatch to the underlying specs here to make sure that the + # given version is contained within all of them. + # Note: This use of all() here means that an empty set of specifiers + # will always return True, this is an explicit design decision. + return all(s.contains(item, prereleases=prereleases) for s in self._specs) + + def filter( + self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None + ) -> Iterator[UnparsedVersionVar]: + """Filter items in the given iterable, that match the specifiers in this set. + + :param iterable: + An iterable that can contain version strings and :class:`Version` instances. + The items in the iterable will be filtered according to the specifier. + :param prereleases: + Whether or not to allow prereleases in the returned iterator. If set to + ``None`` (the default), it will be intelligently decide whether to allow + prereleases or not (based on the :attr:`prereleases` attribute, and + whether the only versions matching are prereleases). + + This method is smarter than just ``filter(SpecifierSet(...).contains, [...])`` + because it implements the rule from :pep:`440` that a prerelease item + SHOULD be accepted if no other versions match the given specifier. + + >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", "1.5a1"])) + ['1.3'] + >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", Version("1.4")])) + ['1.3', ] + >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.5a1"])) + [] + >>> list(SpecifierSet(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True)) + ['1.3', '1.5a1'] + >>> list(SpecifierSet(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"])) + ['1.3', '1.5a1'] + + An "empty" SpecifierSet will filter items based on the presence of prerelease + versions in the set. + + >>> list(SpecifierSet("").filter(["1.3", "1.5a1"])) + ['1.3'] + >>> list(SpecifierSet("").filter(["1.5a1"])) + ['1.5a1'] + >>> list(SpecifierSet("", prereleases=True).filter(["1.3", "1.5a1"])) + ['1.3', '1.5a1'] + >>> list(SpecifierSet("").filter(["1.3", "1.5a1"], prereleases=True)) + ['1.3', '1.5a1'] + """ + # Determine if we're forcing a prerelease or not, if we're not forcing + # one for this particular filter call, then we'll use whatever the + # SpecifierSet thinks for whether or not we should support prereleases. + if prereleases is None: + prereleases = self.prereleases + + # If we have any specifiers, then we want to wrap our iterable in the + # filter method for each one, this will act as a logical AND amongst + # each specifier. + if self._specs: + for spec in self._specs: + iterable = spec.filter(iterable, prereleases=bool(prereleases)) + return iter(iterable) + # If we do not have any specifiers, then we need to have a rough filter + # which will filter out any pre-releases, unless there are no final + # releases. + else: + filtered: list[UnparsedVersionVar] = [] + found_prereleases: list[UnparsedVersionVar] = [] + + for item in iterable: + parsed_version = _coerce_version(item) + + # Store any item which is a pre-release for later unless we've + # already found a final version or we are accepting prereleases + if parsed_version.is_prerelease and not prereleases: + if not filtered: + found_prereleases.append(item) + else: + filtered.append(item) + + # If we've found no items except for pre-releases, then we'll go + # ahead and use the pre-releases + if not filtered and found_prereleases and prereleases is None: + return iter(found_prereleases) + + return iter(filtered) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/tags.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/tags.py new file mode 100644 index 0000000000000000000000000000000000000000..f5903402abb5a0aed37bb23914f678ef7e34a554 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/tags.py @@ -0,0 +1,617 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import logging +import platform +import re +import struct +import subprocess +import sys +import sysconfig +from importlib.machinery import EXTENSION_SUFFIXES +from typing import ( + Iterable, + Iterator, + Sequence, + Tuple, + cast, +) + +from . import _manylinux, _musllinux + +logger = logging.getLogger(__name__) + +PythonVersion = Sequence[int] +AppleVersion = Tuple[int, int] + +INTERPRETER_SHORT_NAMES: dict[str, str] = { + "python": "py", # Generic. + "cpython": "cp", + "pypy": "pp", + "ironpython": "ip", + "jython": "jy", +} + + +_32_BIT_INTERPRETER = struct.calcsize("P") == 4 + + +class Tag: + """ + A representation of the tag triple for a wheel. + + Instances are considered immutable and thus are hashable. Equality checking + is also supported. + """ + + __slots__ = ["_abi", "_hash", "_interpreter", "_platform"] + + def __init__(self, interpreter: str, abi: str, platform: str) -> None: + self._interpreter = interpreter.lower() + self._abi = abi.lower() + self._platform = platform.lower() + # The __hash__ of every single element in a Set[Tag] will be evaluated each time + # that a set calls its `.disjoint()` method, which may be called hundreds of + # times when scanning a page of links for packages with tags matching that + # Set[Tag]. Pre-computing the value here produces significant speedups for + # downstream consumers. + self._hash = hash((self._interpreter, self._abi, self._platform)) + + @property + def interpreter(self) -> str: + return self._interpreter + + @property + def abi(self) -> str: + return self._abi + + @property + def platform(self) -> str: + return self._platform + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Tag): + return NotImplemented + + return ( + (self._hash == other._hash) # Short-circuit ASAP for perf reasons. + and (self._platform == other._platform) + and (self._abi == other._abi) + and (self._interpreter == other._interpreter) + ) + + def __hash__(self) -> int: + return self._hash + + def __str__(self) -> str: + return f"{self._interpreter}-{self._abi}-{self._platform}" + + def __repr__(self) -> str: + return f"<{self} @ {id(self)}>" + + +def parse_tag(tag: str) -> frozenset[Tag]: + """ + Parses the provided tag (e.g. `py3-none-any`) into a frozenset of Tag instances. + + Returning a set is required due to the possibility that the tag is a + compressed tag set. + """ + tags = set() + interpreters, abis, platforms = tag.split("-") + for interpreter in interpreters.split("."): + for abi in abis.split("."): + for platform_ in platforms.split("."): + tags.add(Tag(interpreter, abi, platform_)) + return frozenset(tags) + + +def _get_config_var(name: str, warn: bool = False) -> int | str | None: + value: int | str | None = sysconfig.get_config_var(name) + if value is None and warn: + logger.debug( + "Config variable '%s' is unset, Python ABI tag may be incorrect", name + ) + return value + + +def _normalize_string(string: str) -> str: + return string.replace(".", "_").replace("-", "_").replace(" ", "_") + + +def _is_threaded_cpython(abis: list[str]) -> bool: + """ + Determine if the ABI corresponds to a threaded (`--disable-gil`) build. + + The threaded builds are indicated by a "t" in the abiflags. + """ + if len(abis) == 0: + return False + # expect e.g., cp313 + m = re.match(r"cp\d+(.*)", abis[0]) + if not m: + return False + abiflags = m.group(1) + return "t" in abiflags + + +def _abi3_applies(python_version: PythonVersion, threading: bool) -> bool: + """ + Determine if the Python version supports abi3. + + PEP 384 was first implemented in Python 3.2. The threaded (`--disable-gil`) + builds do not support abi3. + """ + return len(python_version) > 1 and tuple(python_version) >= (3, 2) and not threading + + +def _cpython_abis(py_version: PythonVersion, warn: bool = False) -> list[str]: + py_version = tuple(py_version) # To allow for version comparison. + abis = [] + version = _version_nodot(py_version[:2]) + threading = debug = pymalloc = ucs4 = "" + with_debug = _get_config_var("Py_DEBUG", warn) + has_refcount = hasattr(sys, "gettotalrefcount") + # Windows doesn't set Py_DEBUG, so checking for support of debug-compiled + # extension modules is the best option. + # https://github.com/pypa/pip/issues/3383#issuecomment-173267692 + has_ext = "_d.pyd" in EXTENSION_SUFFIXES + if with_debug or (with_debug is None and (has_refcount or has_ext)): + debug = "d" + if py_version >= (3, 13) and _get_config_var("Py_GIL_DISABLED", warn): + threading = "t" + if py_version < (3, 8): + with_pymalloc = _get_config_var("WITH_PYMALLOC", warn) + if with_pymalloc or with_pymalloc is None: + pymalloc = "m" + if py_version < (3, 3): + unicode_size = _get_config_var("Py_UNICODE_SIZE", warn) + if unicode_size == 4 or ( + unicode_size is None and sys.maxunicode == 0x10FFFF + ): + ucs4 = "u" + elif debug: + # Debug builds can also load "normal" extension modules. + # We can also assume no UCS-4 or pymalloc requirement. + abis.append(f"cp{version}{threading}") + abis.insert(0, f"cp{version}{threading}{debug}{pymalloc}{ucs4}") + return abis + + +def cpython_tags( + python_version: PythonVersion | None = None, + abis: Iterable[str] | None = None, + platforms: Iterable[str] | None = None, + *, + warn: bool = False, +) -> Iterator[Tag]: + """ + Yields the tags for a CPython interpreter. + + The tags consist of: + - cp-- + - cp-abi3- + - cp-none- + - cp-abi3- # Older Python versions down to 3.2. + + If python_version only specifies a major version then user-provided ABIs and + the 'none' ABItag will be used. + + If 'abi3' or 'none' are specified in 'abis' then they will be yielded at + their normal position and not at the beginning. + """ + if not python_version: + python_version = sys.version_info[:2] + + interpreter = f"cp{_version_nodot(python_version[:2])}" + + if abis is None: + if len(python_version) > 1: + abis = _cpython_abis(python_version, warn) + else: + abis = [] + abis = list(abis) + # 'abi3' and 'none' are explicitly handled later. + for explicit_abi in ("abi3", "none"): + try: + abis.remove(explicit_abi) + except ValueError: + pass + + platforms = list(platforms or platform_tags()) + for abi in abis: + for platform_ in platforms: + yield Tag(interpreter, abi, platform_) + + threading = _is_threaded_cpython(abis) + use_abi3 = _abi3_applies(python_version, threading) + if use_abi3: + yield from (Tag(interpreter, "abi3", platform_) for platform_ in platforms) + yield from (Tag(interpreter, "none", platform_) for platform_ in platforms) + + if use_abi3: + for minor_version in range(python_version[1] - 1, 1, -1): + for platform_ in platforms: + version = _version_nodot((python_version[0], minor_version)) + interpreter = f"cp{version}" + yield Tag(interpreter, "abi3", platform_) + + +def _generic_abi() -> list[str]: + """ + Return the ABI tag based on EXT_SUFFIX. + """ + # The following are examples of `EXT_SUFFIX`. + # We want to keep the parts which are related to the ABI and remove the + # parts which are related to the platform: + # - linux: '.cpython-310-x86_64-linux-gnu.so' => cp310 + # - mac: '.cpython-310-darwin.so' => cp310 + # - win: '.cp310-win_amd64.pyd' => cp310 + # - win: '.pyd' => cp37 (uses _cpython_abis()) + # - pypy: '.pypy38-pp73-x86_64-linux-gnu.so' => pypy38_pp73 + # - graalpy: '.graalpy-38-native-x86_64-darwin.dylib' + # => graalpy_38_native + + ext_suffix = _get_config_var("EXT_SUFFIX", warn=True) + if not isinstance(ext_suffix, str) or ext_suffix[0] != ".": + raise SystemError("invalid sysconfig.get_config_var('EXT_SUFFIX')") + parts = ext_suffix.split(".") + if len(parts) < 3: + # CPython3.7 and earlier uses ".pyd" on Windows. + return _cpython_abis(sys.version_info[:2]) + soabi = parts[1] + if soabi.startswith("cpython"): + # non-windows + abi = "cp" + soabi.split("-")[1] + elif soabi.startswith("cp"): + # windows + abi = soabi.split("-")[0] + elif soabi.startswith("pypy"): + abi = "-".join(soabi.split("-")[:2]) + elif soabi.startswith("graalpy"): + abi = "-".join(soabi.split("-")[:3]) + elif soabi: + # pyston, ironpython, others? + abi = soabi + else: + return [] + return [_normalize_string(abi)] + + +def generic_tags( + interpreter: str | None = None, + abis: Iterable[str] | None = None, + platforms: Iterable[str] | None = None, + *, + warn: bool = False, +) -> Iterator[Tag]: + """ + Yields the tags for a generic interpreter. + + The tags consist of: + - -- + + The "none" ABI will be added if it was not explicitly provided. + """ + if not interpreter: + interp_name = interpreter_name() + interp_version = interpreter_version(warn=warn) + interpreter = "".join([interp_name, interp_version]) + if abis is None: + abis = _generic_abi() + else: + abis = list(abis) + platforms = list(platforms or platform_tags()) + if "none" not in abis: + abis.append("none") + for abi in abis: + for platform_ in platforms: + yield Tag(interpreter, abi, platform_) + + +def _py_interpreter_range(py_version: PythonVersion) -> Iterator[str]: + """ + Yields Python versions in descending order. + + After the latest version, the major-only version will be yielded, and then + all previous versions of that major version. + """ + if len(py_version) > 1: + yield f"py{_version_nodot(py_version[:2])}" + yield f"py{py_version[0]}" + if len(py_version) > 1: + for minor in range(py_version[1] - 1, -1, -1): + yield f"py{_version_nodot((py_version[0], minor))}" + + +def compatible_tags( + python_version: PythonVersion | None = None, + interpreter: str | None = None, + platforms: Iterable[str] | None = None, +) -> Iterator[Tag]: + """ + Yields the sequence of tags that are compatible with a specific version of Python. + + The tags consist of: + - py*-none- + - -none-any # ... if `interpreter` is provided. + - py*-none-any + """ + if not python_version: + python_version = sys.version_info[:2] + platforms = list(platforms or platform_tags()) + for version in _py_interpreter_range(python_version): + for platform_ in platforms: + yield Tag(version, "none", platform_) + if interpreter: + yield Tag(interpreter, "none", "any") + for version in _py_interpreter_range(python_version): + yield Tag(version, "none", "any") + + +def _mac_arch(arch: str, is_32bit: bool = _32_BIT_INTERPRETER) -> str: + if not is_32bit: + return arch + + if arch.startswith("ppc"): + return "ppc" + + return "i386" + + +def _mac_binary_formats(version: AppleVersion, cpu_arch: str) -> list[str]: + formats = [cpu_arch] + if cpu_arch == "x86_64": + if version < (10, 4): + return [] + formats.extend(["intel", "fat64", "fat32"]) + + elif cpu_arch == "i386": + if version < (10, 4): + return [] + formats.extend(["intel", "fat32", "fat"]) + + elif cpu_arch == "ppc64": + # TODO: Need to care about 32-bit PPC for ppc64 through 10.2? + if version > (10, 5) or version < (10, 4): + return [] + formats.append("fat64") + + elif cpu_arch == "ppc": + if version > (10, 6): + return [] + formats.extend(["fat32", "fat"]) + + if cpu_arch in {"arm64", "x86_64"}: + formats.append("universal2") + + if cpu_arch in {"x86_64", "i386", "ppc64", "ppc", "intel"}: + formats.append("universal") + + return formats + + +def mac_platforms( + version: AppleVersion | None = None, arch: str | None = None +) -> Iterator[str]: + """ + Yields the platform tags for a macOS system. + + The `version` parameter is a two-item tuple specifying the macOS version to + generate platform tags for. The `arch` parameter is the CPU architecture to + generate platform tags for. Both parameters default to the appropriate value + for the current system. + """ + version_str, _, cpu_arch = platform.mac_ver() + if version is None: + version = cast("AppleVersion", tuple(map(int, version_str.split(".")[:2]))) + if version == (10, 16): + # When built against an older macOS SDK, Python will report macOS 10.16 + # instead of the real version. + version_str = subprocess.run( + [ + sys.executable, + "-sS", + "-c", + "import platform; print(platform.mac_ver()[0])", + ], + check=True, + env={"SYSTEM_VERSION_COMPAT": "0"}, + stdout=subprocess.PIPE, + text=True, + ).stdout + version = cast("AppleVersion", tuple(map(int, version_str.split(".")[:2]))) + else: + version = version + if arch is None: + arch = _mac_arch(cpu_arch) + else: + arch = arch + + if (10, 0) <= version and version < (11, 0): + # Prior to Mac OS 11, each yearly release of Mac OS bumped the + # "minor" version number. The major version was always 10. + major_version = 10 + for minor_version in range(version[1], -1, -1): + compat_version = major_version, minor_version + binary_formats = _mac_binary_formats(compat_version, arch) + for binary_format in binary_formats: + yield f"macosx_{major_version}_{minor_version}_{binary_format}" + + if version >= (11, 0): + # Starting with Mac OS 11, each yearly release bumps the major version + # number. The minor versions are now the midyear updates. + minor_version = 0 + for major_version in range(version[0], 10, -1): + compat_version = major_version, minor_version + binary_formats = _mac_binary_formats(compat_version, arch) + for binary_format in binary_formats: + yield f"macosx_{major_version}_{minor_version}_{binary_format}" + + if version >= (11, 0): + # Mac OS 11 on x86_64 is compatible with binaries from previous releases. + # Arm64 support was introduced in 11.0, so no Arm binaries from previous + # releases exist. + # + # However, the "universal2" binary format can have a + # macOS version earlier than 11.0 when the x86_64 part of the binary supports + # that version of macOS. + major_version = 10 + if arch == "x86_64": + for minor_version in range(16, 3, -1): + compat_version = major_version, minor_version + binary_formats = _mac_binary_formats(compat_version, arch) + for binary_format in binary_formats: + yield f"macosx_{major_version}_{minor_version}_{binary_format}" + else: + for minor_version in range(16, 3, -1): + compat_version = major_version, minor_version + binary_format = "universal2" + yield f"macosx_{major_version}_{minor_version}_{binary_format}" + + +def ios_platforms( + version: AppleVersion | None = None, multiarch: str | None = None +) -> Iterator[str]: + """ + Yields the platform tags for an iOS system. + + :param version: A two-item tuple specifying the iOS version to generate + platform tags for. Defaults to the current iOS version. + :param multiarch: The CPU architecture+ABI to generate platform tags for - + (the value used by `sys.implementation._multiarch` e.g., + `arm64_iphoneos` or `x84_64_iphonesimulator`). Defaults to the current + multiarch value. + """ + if version is None: + # if iOS is the current platform, ios_ver *must* be defined. However, + # it won't exist for CPython versions before 3.13, which causes a mypy + # error. + _, release, _, _ = platform.ios_ver() # type: ignore[attr-defined, unused-ignore] + version = cast("AppleVersion", tuple(map(int, release.split(".")[:2]))) + + if multiarch is None: + multiarch = sys.implementation._multiarch + multiarch = multiarch.replace("-", "_") + + ios_platform_template = "ios_{major}_{minor}_{multiarch}" + + # Consider any iOS major.minor version from the version requested, down to + # 12.0. 12.0 is the first iOS version that is known to have enough features + # to support CPython. Consider every possible minor release up to X.9. There + # highest the minor has ever gone is 8 (14.8 and 15.8) but having some extra + # candidates that won't ever match doesn't really hurt, and it saves us from + # having to keep an explicit list of known iOS versions in the code. Return + # the results descending order of version number. + + # If the requested major version is less than 12, there won't be any matches. + if version[0] < 12: + return + + # Consider the actual X.Y version that was requested. + yield ios_platform_template.format( + major=version[0], minor=version[1], multiarch=multiarch + ) + + # Consider every minor version from X.0 to the minor version prior to the + # version requested by the platform. + for minor in range(version[1] - 1, -1, -1): + yield ios_platform_template.format( + major=version[0], minor=minor, multiarch=multiarch + ) + + for major in range(version[0] - 1, 11, -1): + for minor in range(9, -1, -1): + yield ios_platform_template.format( + major=major, minor=minor, multiarch=multiarch + ) + + +def _linux_platforms(is_32bit: bool = _32_BIT_INTERPRETER) -> Iterator[str]: + linux = _normalize_string(sysconfig.get_platform()) + if not linux.startswith("linux_"): + # we should never be here, just yield the sysconfig one and return + yield linux + return + if is_32bit: + if linux == "linux_x86_64": + linux = "linux_i686" + elif linux == "linux_aarch64": + linux = "linux_armv8l" + _, arch = linux.split("_", 1) + archs = {"armv8l": ["armv8l", "armv7l"]}.get(arch, [arch]) + yield from _manylinux.platform_tags(archs) + yield from _musllinux.platform_tags(archs) + for arch in archs: + yield f"linux_{arch}" + + +def _generic_platforms() -> Iterator[str]: + yield _normalize_string(sysconfig.get_platform()) + + +def platform_tags() -> Iterator[str]: + """ + Provides the platform tags for this installation. + """ + if platform.system() == "Darwin": + return mac_platforms() + elif platform.system() == "iOS": + return ios_platforms() + elif platform.system() == "Linux": + return _linux_platforms() + else: + return _generic_platforms() + + +def interpreter_name() -> str: + """ + Returns the name of the running interpreter. + + Some implementations have a reserved, two-letter abbreviation which will + be returned when appropriate. + """ + name = sys.implementation.name + return INTERPRETER_SHORT_NAMES.get(name) or name + + +def interpreter_version(*, warn: bool = False) -> str: + """ + Returns the version of the running interpreter. + """ + version = _get_config_var("py_version_nodot", warn=warn) + if version: + version = str(version) + else: + version = _version_nodot(sys.version_info[:2]) + return version + + +def _version_nodot(version: PythonVersion) -> str: + return "".join(map(str, version)) + + +def sys_tags(*, warn: bool = False) -> Iterator[Tag]: + """ + Returns the sequence of tag triples for the running interpreter. + + The order of the sequence corresponds to priority order for the + interpreter, from most to least important. + """ + + interp_name = interpreter_name() + if interp_name == "cp": + yield from cpython_tags(warn=warn) + else: + yield from generic_tags() + + if interp_name == "pp": + interp = "pp3" + elif interp_name == "cp": + interp = "cp" + interpreter_version(warn=warn) + else: + interp = None + yield from compatible_tags(interpreter=interp) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/utils.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..23450953df74eccd9c13cd2a955ce09d1f968565 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/utils.py @@ -0,0 +1,163 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import functools +import re +from typing import NewType, Tuple, Union, cast + +from .tags import Tag, parse_tag +from .version import InvalidVersion, Version, _TrimmedRelease + +BuildTag = Union[Tuple[()], Tuple[int, str]] +NormalizedName = NewType("NormalizedName", str) + + +class InvalidName(ValueError): + """ + An invalid distribution name; users should refer to the packaging user guide. + """ + + +class InvalidWheelFilename(ValueError): + """ + An invalid wheel filename was found, users should refer to PEP 427. + """ + + +class InvalidSdistFilename(ValueError): + """ + An invalid sdist filename was found, users should refer to the packaging user guide. + """ + + +# Core metadata spec for `Name` +_validate_regex = re.compile( + r"^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$", re.IGNORECASE +) +_canonicalize_regex = re.compile(r"[-_.]+") +_normalized_regex = re.compile(r"^([a-z0-9]|[a-z0-9]([a-z0-9-](?!--))*[a-z0-9])$") +# PEP 427: The build number must start with a digit. +_build_tag_regex = re.compile(r"(\d+)(.*)") + + +def canonicalize_name(name: str, *, validate: bool = False) -> NormalizedName: + if validate and not _validate_regex.match(name): + raise InvalidName(f"name is invalid: {name!r}") + # This is taken from PEP 503. + value = _canonicalize_regex.sub("-", name).lower() + return cast(NormalizedName, value) + + +def is_normalized_name(name: str) -> bool: + return _normalized_regex.match(name) is not None + + +@functools.singledispatch +def canonicalize_version( + version: Version | str, *, strip_trailing_zero: bool = True +) -> str: + """ + Return a canonical form of a version as a string. + + >>> canonicalize_version('1.0.1') + '1.0.1' + + Per PEP 625, versions may have multiple canonical forms, differing + only by trailing zeros. + + >>> canonicalize_version('1.0.0') + '1' + >>> canonicalize_version('1.0.0', strip_trailing_zero=False) + '1.0.0' + + Invalid versions are returned unaltered. + + >>> canonicalize_version('foo bar baz') + 'foo bar baz' + """ + return str(_TrimmedRelease(str(version)) if strip_trailing_zero else version) + + +@canonicalize_version.register +def _(version: str, *, strip_trailing_zero: bool = True) -> str: + try: + parsed = Version(version) + except InvalidVersion: + # Legacy versions cannot be normalized + return version + return canonicalize_version(parsed, strip_trailing_zero=strip_trailing_zero) + + +def parse_wheel_filename( + filename: str, +) -> tuple[NormalizedName, Version, BuildTag, frozenset[Tag]]: + if not filename.endswith(".whl"): + raise InvalidWheelFilename( + f"Invalid wheel filename (extension must be '.whl'): {filename!r}" + ) + + filename = filename[:-4] + dashes = filename.count("-") + if dashes not in (4, 5): + raise InvalidWheelFilename( + f"Invalid wheel filename (wrong number of parts): {filename!r}" + ) + + parts = filename.split("-", dashes - 2) + name_part = parts[0] + # See PEP 427 for the rules on escaping the project name. + if "__" in name_part or re.match(r"^[\w\d._]*$", name_part, re.UNICODE) is None: + raise InvalidWheelFilename(f"Invalid project name: {filename!r}") + name = canonicalize_name(name_part) + + try: + version = Version(parts[1]) + except InvalidVersion as e: + raise InvalidWheelFilename( + f"Invalid wheel filename (invalid version): {filename!r}" + ) from e + + if dashes == 5: + build_part = parts[2] + build_match = _build_tag_regex.match(build_part) + if build_match is None: + raise InvalidWheelFilename( + f"Invalid build number: {build_part} in {filename!r}" + ) + build = cast(BuildTag, (int(build_match.group(1)), build_match.group(2))) + else: + build = () + tags = parse_tag(parts[-1]) + return (name, version, build, tags) + + +def parse_sdist_filename(filename: str) -> tuple[NormalizedName, Version]: + if filename.endswith(".tar.gz"): + file_stem = filename[: -len(".tar.gz")] + elif filename.endswith(".zip"): + file_stem = filename[: -len(".zip")] + else: + raise InvalidSdistFilename( + f"Invalid sdist filename (extension must be '.tar.gz' or '.zip'):" + f" {filename!r}" + ) + + # We are requiring a PEP 440 version, which cannot contain dashes, + # so we split on the last dash. + name_part, sep, version_part = file_stem.rpartition("-") + if not sep: + raise InvalidSdistFilename(f"Invalid sdist filename: {filename!r}") + + name = canonicalize_name(name_part) + + try: + version = Version(version_part) + except InvalidVersion as e: + raise InvalidSdistFilename( + f"Invalid sdist filename (invalid version): {filename!r}" + ) from e + + return (name, version) diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/version.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/version.py new file mode 100644 index 0000000000000000000000000000000000000000..c9bbda20e463b8d9389ecd65f74af33810a02bdd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/packaging/version.py @@ -0,0 +1,582 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. +""" +.. testsetup:: + + from packaging.version import parse, Version +""" + +from __future__ import annotations + +import itertools +import re +from typing import Any, Callable, NamedTuple, SupportsInt, Tuple, Union + +from ._structures import Infinity, InfinityType, NegativeInfinity, NegativeInfinityType + +__all__ = ["VERSION_PATTERN", "InvalidVersion", "Version", "parse"] + +LocalType = Tuple[Union[int, str], ...] + +CmpPrePostDevType = Union[InfinityType, NegativeInfinityType, Tuple[str, int]] +CmpLocalType = Union[ + NegativeInfinityType, + Tuple[Union[Tuple[int, str], Tuple[NegativeInfinityType, Union[int, str]]], ...], +] +CmpKey = Tuple[ + int, + Tuple[int, ...], + CmpPrePostDevType, + CmpPrePostDevType, + CmpPrePostDevType, + CmpLocalType, +] +VersionComparisonMethod = Callable[[CmpKey, CmpKey], bool] + + +class _Version(NamedTuple): + epoch: int + release: tuple[int, ...] + dev: tuple[str, int] | None + pre: tuple[str, int] | None + post: tuple[str, int] | None + local: LocalType | None + + +def parse(version: str) -> Version: + """Parse the given version string. + + >>> parse('1.0.dev1') + + + :param version: The version string to parse. + :raises InvalidVersion: When the version string is not a valid version. + """ + return Version(version) + + +class InvalidVersion(ValueError): + """Raised when a version string is not a valid version. + + >>> Version("invalid") + Traceback (most recent call last): + ... + packaging.version.InvalidVersion: Invalid version: 'invalid' + """ + + +class _BaseVersion: + _key: tuple[Any, ...] + + def __hash__(self) -> int: + return hash(self._key) + + # Please keep the duplicated `isinstance` check + # in the six comparisons hereunder + # unless you find a way to avoid adding overhead function calls. + def __lt__(self, other: _BaseVersion) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key < other._key + + def __le__(self, other: _BaseVersion) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key <= other._key + + def __eq__(self, other: object) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key == other._key + + def __ge__(self, other: _BaseVersion) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key >= other._key + + def __gt__(self, other: _BaseVersion) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key > other._key + + def __ne__(self, other: object) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key != other._key + + +# Deliberately not anchored to the start and end of the string, to make it +# easier for 3rd party code to reuse +_VERSION_PATTERN = r""" + v? + (?: + (?:(?P[0-9]+)!)? # epoch + (?P[0-9]+(?:\.[0-9]+)*) # release segment + (?P
                                          # pre-release
+            [-_\.]?
+            (?Palpha|a|beta|b|preview|pre|c|rc)
+            [-_\.]?
+            (?P[0-9]+)?
+        )?
+        (?P                                         # post release
+            (?:-(?P[0-9]+))
+            |
+            (?:
+                [-_\.]?
+                (?Ppost|rev|r)
+                [-_\.]?
+                (?P[0-9]+)?
+            )
+        )?
+        (?P                                          # dev release
+            [-_\.]?
+            (?Pdev)
+            [-_\.]?
+            (?P[0-9]+)?
+        )?
+    )
+    (?:\+(?P[a-z0-9]+(?:[-_\.][a-z0-9]+)*))?       # local version
+"""
+
+VERSION_PATTERN = _VERSION_PATTERN
+"""
+A string containing the regular expression used to match a valid version.
+
+The pattern is not anchored at either end, and is intended for embedding in larger
+expressions (for example, matching a version number as part of a file name). The
+regular expression should be compiled with the ``re.VERBOSE`` and ``re.IGNORECASE``
+flags set.
+
+:meta hide-value:
+"""
+
+
+class Version(_BaseVersion):
+    """This class abstracts handling of a project's versions.
+
+    A :class:`Version` instance is comparison aware and can be compared and
+    sorted using the standard Python interfaces.
+
+    >>> v1 = Version("1.0a5")
+    >>> v2 = Version("1.0")
+    >>> v1
+    
+    >>> v2
+    
+    >>> v1 < v2
+    True
+    >>> v1 == v2
+    False
+    >>> v1 > v2
+    False
+    >>> v1 >= v2
+    False
+    >>> v1 <= v2
+    True
+    """
+
+    _regex = re.compile(r"^\s*" + VERSION_PATTERN + r"\s*$", re.VERBOSE | re.IGNORECASE)
+    _key: CmpKey
+
+    def __init__(self, version: str) -> None:
+        """Initialize a Version object.
+
+        :param version:
+            The string representation of a version which will be parsed and normalized
+            before use.
+        :raises InvalidVersion:
+            If the ``version`` does not conform to PEP 440 in any way then this
+            exception will be raised.
+        """
+
+        # Validate the version and parse it into pieces
+        match = self._regex.search(version)
+        if not match:
+            raise InvalidVersion(f"Invalid version: {version!r}")
+
+        # Store the parsed out pieces of the version
+        self._version = _Version(
+            epoch=int(match.group("epoch")) if match.group("epoch") else 0,
+            release=tuple(int(i) for i in match.group("release").split(".")),
+            pre=_parse_letter_version(match.group("pre_l"), match.group("pre_n")),
+            post=_parse_letter_version(
+                match.group("post_l"), match.group("post_n1") or match.group("post_n2")
+            ),
+            dev=_parse_letter_version(match.group("dev_l"), match.group("dev_n")),
+            local=_parse_local_version(match.group("local")),
+        )
+
+        # Generate a key which will be used for sorting
+        self._key = _cmpkey(
+            self._version.epoch,
+            self._version.release,
+            self._version.pre,
+            self._version.post,
+            self._version.dev,
+            self._version.local,
+        )
+
+    def __repr__(self) -> str:
+        """A representation of the Version that shows all internal state.
+
+        >>> Version('1.0.0')
+        
+        """
+        return f""
+
+    def __str__(self) -> str:
+        """A string representation of the version that can be round-tripped.
+
+        >>> str(Version("1.0a5"))
+        '1.0a5'
+        """
+        parts = []
+
+        # Epoch
+        if self.epoch != 0:
+            parts.append(f"{self.epoch}!")
+
+        # Release segment
+        parts.append(".".join(str(x) for x in self.release))
+
+        # Pre-release
+        if self.pre is not None:
+            parts.append("".join(str(x) for x in self.pre))
+
+        # Post-release
+        if self.post is not None:
+            parts.append(f".post{self.post}")
+
+        # Development release
+        if self.dev is not None:
+            parts.append(f".dev{self.dev}")
+
+        # Local version segment
+        if self.local is not None:
+            parts.append(f"+{self.local}")
+
+        return "".join(parts)
+
+    @property
+    def epoch(self) -> int:
+        """The epoch of the version.
+
+        >>> Version("2.0.0").epoch
+        0
+        >>> Version("1!2.0.0").epoch
+        1
+        """
+        return self._version.epoch
+
+    @property
+    def release(self) -> tuple[int, ...]:
+        """The components of the "release" segment of the version.
+
+        >>> Version("1.2.3").release
+        (1, 2, 3)
+        >>> Version("2.0.0").release
+        (2, 0, 0)
+        >>> Version("1!2.0.0.post0").release
+        (2, 0, 0)
+
+        Includes trailing zeroes but not the epoch or any pre-release / development /
+        post-release suffixes.
+        """
+        return self._version.release
+
+    @property
+    def pre(self) -> tuple[str, int] | None:
+        """The pre-release segment of the version.
+
+        >>> print(Version("1.2.3").pre)
+        None
+        >>> Version("1.2.3a1").pre
+        ('a', 1)
+        >>> Version("1.2.3b1").pre
+        ('b', 1)
+        >>> Version("1.2.3rc1").pre
+        ('rc', 1)
+        """
+        return self._version.pre
+
+    @property
+    def post(self) -> int | None:
+        """The post-release number of the version.
+
+        >>> print(Version("1.2.3").post)
+        None
+        >>> Version("1.2.3.post1").post
+        1
+        """
+        return self._version.post[1] if self._version.post else None
+
+    @property
+    def dev(self) -> int | None:
+        """The development number of the version.
+
+        >>> print(Version("1.2.3").dev)
+        None
+        >>> Version("1.2.3.dev1").dev
+        1
+        """
+        return self._version.dev[1] if self._version.dev else None
+
+    @property
+    def local(self) -> str | None:
+        """The local version segment of the version.
+
+        >>> print(Version("1.2.3").local)
+        None
+        >>> Version("1.2.3+abc").local
+        'abc'
+        """
+        if self._version.local:
+            return ".".join(str(x) for x in self._version.local)
+        else:
+            return None
+
+    @property
+    def public(self) -> str:
+        """The public portion of the version.
+
+        >>> Version("1.2.3").public
+        '1.2.3'
+        >>> Version("1.2.3+abc").public
+        '1.2.3'
+        >>> Version("1!1.2.3dev1+abc").public
+        '1!1.2.3.dev1'
+        """
+        return str(self).split("+", 1)[0]
+
+    @property
+    def base_version(self) -> str:
+        """The "base version" of the version.
+
+        >>> Version("1.2.3").base_version
+        '1.2.3'
+        >>> Version("1.2.3+abc").base_version
+        '1.2.3'
+        >>> Version("1!1.2.3dev1+abc").base_version
+        '1!1.2.3'
+
+        The "base version" is the public version of the project without any pre or post
+        release markers.
+        """
+        parts = []
+
+        # Epoch
+        if self.epoch != 0:
+            parts.append(f"{self.epoch}!")
+
+        # Release segment
+        parts.append(".".join(str(x) for x in self.release))
+
+        return "".join(parts)
+
+    @property
+    def is_prerelease(self) -> bool:
+        """Whether this version is a pre-release.
+
+        >>> Version("1.2.3").is_prerelease
+        False
+        >>> Version("1.2.3a1").is_prerelease
+        True
+        >>> Version("1.2.3b1").is_prerelease
+        True
+        >>> Version("1.2.3rc1").is_prerelease
+        True
+        >>> Version("1.2.3dev1").is_prerelease
+        True
+        """
+        return self.dev is not None or self.pre is not None
+
+    @property
+    def is_postrelease(self) -> bool:
+        """Whether this version is a post-release.
+
+        >>> Version("1.2.3").is_postrelease
+        False
+        >>> Version("1.2.3.post1").is_postrelease
+        True
+        """
+        return self.post is not None
+
+    @property
+    def is_devrelease(self) -> bool:
+        """Whether this version is a development release.
+
+        >>> Version("1.2.3").is_devrelease
+        False
+        >>> Version("1.2.3.dev1").is_devrelease
+        True
+        """
+        return self.dev is not None
+
+    @property
+    def major(self) -> int:
+        """The first item of :attr:`release` or ``0`` if unavailable.
+
+        >>> Version("1.2.3").major
+        1
+        """
+        return self.release[0] if len(self.release) >= 1 else 0
+
+    @property
+    def minor(self) -> int:
+        """The second item of :attr:`release` or ``0`` if unavailable.
+
+        >>> Version("1.2.3").minor
+        2
+        >>> Version("1").minor
+        0
+        """
+        return self.release[1] if len(self.release) >= 2 else 0
+
+    @property
+    def micro(self) -> int:
+        """The third item of :attr:`release` or ``0`` if unavailable.
+
+        >>> Version("1.2.3").micro
+        3
+        >>> Version("1").micro
+        0
+        """
+        return self.release[2] if len(self.release) >= 3 else 0
+
+
+class _TrimmedRelease(Version):
+    @property
+    def release(self) -> tuple[int, ...]:
+        """
+        Release segment without any trailing zeros.
+
+        >>> _TrimmedRelease('1.0.0').release
+        (1,)
+        >>> _TrimmedRelease('0.0').release
+        (0,)
+        """
+        rel = super().release
+        nonzeros = (index for index, val in enumerate(rel) if val)
+        last_nonzero = max(nonzeros, default=0)
+        return rel[: last_nonzero + 1]
+
+
+def _parse_letter_version(
+    letter: str | None, number: str | bytes | SupportsInt | None
+) -> tuple[str, int] | None:
+    if letter:
+        # We consider there to be an implicit 0 in a pre-release if there is
+        # not a numeral associated with it.
+        if number is None:
+            number = 0
+
+        # We normalize any letters to their lower case form
+        letter = letter.lower()
+
+        # We consider some words to be alternate spellings of other words and
+        # in those cases we want to normalize the spellings to our preferred
+        # spelling.
+        if letter == "alpha":
+            letter = "a"
+        elif letter == "beta":
+            letter = "b"
+        elif letter in ["c", "pre", "preview"]:
+            letter = "rc"
+        elif letter in ["rev", "r"]:
+            letter = "post"
+
+        return letter, int(number)
+
+    assert not letter
+    if number:
+        # We assume if we are given a number, but we are not given a letter
+        # then this is using the implicit post release syntax (e.g. 1.0-1)
+        letter = "post"
+
+        return letter, int(number)
+
+    return None
+
+
+_local_version_separators = re.compile(r"[\._-]")
+
+
+def _parse_local_version(local: str | None) -> LocalType | None:
+    """
+    Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
+    """
+    if local is not None:
+        return tuple(
+            part.lower() if not part.isdigit() else int(part)
+            for part in _local_version_separators.split(local)
+        )
+    return None
+
+
+def _cmpkey(
+    epoch: int,
+    release: tuple[int, ...],
+    pre: tuple[str, int] | None,
+    post: tuple[str, int] | None,
+    dev: tuple[str, int] | None,
+    local: LocalType | None,
+) -> CmpKey:
+    # When we compare a release version, we want to compare it with all of the
+    # trailing zeros removed. So we'll use a reverse the list, drop all the now
+    # leading zeros until we come to something non zero, then take the rest
+    # re-reverse it back into the correct order and make it a tuple and use
+    # that for our sorting key.
+    _release = tuple(
+        reversed(list(itertools.dropwhile(lambda x: x == 0, reversed(release))))
+    )
+
+    # We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
+    # We'll do this by abusing the pre segment, but we _only_ want to do this
+    # if there is not a pre or a post segment. If we have one of those then
+    # the normal sorting rules will handle this case correctly.
+    if pre is None and post is None and dev is not None:
+        _pre: CmpPrePostDevType = NegativeInfinity
+    # Versions without a pre-release (except as noted above) should sort after
+    # those with one.
+    elif pre is None:
+        _pre = Infinity
+    else:
+        _pre = pre
+
+    # Versions without a post segment should sort before those with one.
+    if post is None:
+        _post: CmpPrePostDevType = NegativeInfinity
+
+    else:
+        _post = post
+
+    # Versions without a development segment should sort after those with one.
+    if dev is None:
+        _dev: CmpPrePostDevType = Infinity
+
+    else:
+        _dev = dev
+
+    if local is None:
+        # Versions without a local segment should sort before those with one.
+        _local: CmpLocalType = NegativeInfinity
+    else:
+        # Versions with a local segment need that segment parsed to implement
+        # the sorting rules in PEP440.
+        # - Alpha numeric segments sort before numeric segments
+        # - Alpha numeric segments sort lexicographically
+        # - Numeric segments sort numerically
+        # - Shorter versions sort before longer versions when the prefixes
+        #   match exactly
+        _local = tuple(
+            (i, "") if isinstance(i, int) else (NegativeInfinity, i) for i in local
+        )
+
+    return epoch, _release, _pre, _post, _dev, _local
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs-4.2.2.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs-4.2.2.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs-4.2.2.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs-4.2.2.dist-info/METADATA b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs-4.2.2.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..ab51ef36add104ccb48652a207a3667ba9b582c7
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs-4.2.2.dist-info/METADATA
@@ -0,0 +1,319 @@
+Metadata-Version: 2.3
+Name: platformdirs
+Version: 4.2.2
+Summary: A small Python package for determining appropriate platform-specific dirs, e.g. a `user data dir`.
+Project-URL: Documentation, https://platformdirs.readthedocs.io
+Project-URL: Homepage, https://github.com/platformdirs/platformdirs
+Project-URL: Source, https://github.com/platformdirs/platformdirs
+Project-URL: Tracker, https://github.com/platformdirs/platformdirs/issues
+Maintainer-email: Bernát Gábor , Julian Berman , Ofek Lev , Ronny Pfannschmidt 
+License-Expression: MIT
+License-File: LICENSE
+Keywords: appdirs,application,cache,directory,log,user
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 3 :: Only
+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 :: Implementation :: CPython
+Classifier: Programming Language :: Python :: Implementation :: PyPy
+Classifier: Topic :: Software Development :: Libraries :: Python Modules
+Requires-Python: >=3.8
+Provides-Extra: docs
+Requires-Dist: furo>=2023.9.10; extra == 'docs'
+Requires-Dist: proselint>=0.13; extra == 'docs'
+Requires-Dist: sphinx-autodoc-typehints>=1.25.2; extra == 'docs'
+Requires-Dist: sphinx>=7.2.6; extra == 'docs'
+Provides-Extra: test
+Requires-Dist: appdirs==1.4.4; extra == 'test'
+Requires-Dist: covdefaults>=2.3; extra == 'test'
+Requires-Dist: pytest-cov>=4.1; extra == 'test'
+Requires-Dist: pytest-mock>=3.12; extra == 'test'
+Requires-Dist: pytest>=7.4.3; extra == 'test'
+Provides-Extra: type
+Requires-Dist: mypy>=1.8; extra == 'type'
+Description-Content-Type: text/x-rst
+
+The problem
+===========
+
+.. image:: https://github.com/platformdirs/platformdirs/actions/workflows/check.yml/badge.svg
+   :target: https://github.com/platformdirs/platformdirs/actions
+
+When writing desktop application, finding the right location to store user data
+and configuration varies per platform. Even for single-platform apps, there
+may by plenty of nuances in figuring out the right location.
+
+For example, if running on macOS, you should use::
+
+    ~/Library/Application Support/
+
+If on Windows (at least English Win) that should be::
+
+    C:\Documents and Settings\\Application Data\Local Settings\\
+
+or possibly::
+
+    C:\Documents and Settings\\Application Data\\
+
+for `roaming profiles `_ but that is another story.
+
+On Linux (and other Unices), according to the `XDG Basedir Spec`_, it should be::
+
+    ~/.local/share/
+
+.. _XDG Basedir Spec: https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
+
+``platformdirs`` to the rescue
+==============================
+
+This kind of thing is what the ``platformdirs`` package is for.
+``platformdirs`` will help you choose an appropriate:
+
+- user data dir (``user_data_dir``)
+- user config dir (``user_config_dir``)
+- user cache dir (``user_cache_dir``)
+- site data dir (``site_data_dir``)
+- site config dir (``site_config_dir``)
+- user log dir (``user_log_dir``)
+- user documents dir (``user_documents_dir``)
+- user downloads dir (``user_downloads_dir``)
+- user pictures dir (``user_pictures_dir``)
+- user videos dir (``user_videos_dir``)
+- user music dir (``user_music_dir``)
+- user desktop dir (``user_desktop_dir``)
+- user runtime dir (``user_runtime_dir``)
+
+And also:
+
+- Is slightly opinionated on the directory names used. Look for "OPINION" in
+  documentation and code for when an opinion is being applied.
+
+Example output
+==============
+
+On macOS:
+
+.. code-block:: pycon
+
+    >>> from platformdirs import *
+    >>> appname = "SuperApp"
+    >>> appauthor = "Acme"
+    >>> user_data_dir(appname, appauthor)
+    '/Users/trentm/Library/Application Support/SuperApp'
+    >>> site_data_dir(appname, appauthor)
+    '/Library/Application Support/SuperApp'
+    >>> user_cache_dir(appname, appauthor)
+    '/Users/trentm/Library/Caches/SuperApp'
+    >>> user_log_dir(appname, appauthor)
+    '/Users/trentm/Library/Logs/SuperApp'
+    >>> user_documents_dir()
+    '/Users/trentm/Documents'
+    >>> user_downloads_dir()
+    '/Users/trentm/Downloads'
+    >>> user_pictures_dir()
+    '/Users/trentm/Pictures'
+    >>> user_videos_dir()
+    '/Users/trentm/Movies'
+    >>> user_music_dir()
+    '/Users/trentm/Music'
+    >>> user_desktop_dir()
+    '/Users/trentm/Desktop'
+    >>> user_runtime_dir(appname, appauthor)
+    '/Users/trentm/Library/Caches/TemporaryItems/SuperApp'
+
+On Windows:
+
+.. code-block:: pycon
+
+    >>> from platformdirs import *
+    >>> appname = "SuperApp"
+    >>> appauthor = "Acme"
+    >>> user_data_dir(appname, appauthor)
+    'C:\\Users\\trentm\\AppData\\Local\\Acme\\SuperApp'
+    >>> user_data_dir(appname, appauthor, roaming=True)
+    'C:\\Users\\trentm\\AppData\\Roaming\\Acme\\SuperApp'
+    >>> user_cache_dir(appname, appauthor)
+    'C:\\Users\\trentm\\AppData\\Local\\Acme\\SuperApp\\Cache'
+    >>> user_log_dir(appname, appauthor)
+    'C:\\Users\\trentm\\AppData\\Local\\Acme\\SuperApp\\Logs'
+    >>> user_documents_dir()
+    'C:\\Users\\trentm\\Documents'
+    >>> user_downloads_dir()
+    'C:\\Users\\trentm\\Downloads'
+    >>> user_pictures_dir()
+    'C:\\Users\\trentm\\Pictures'
+    >>> user_videos_dir()
+    'C:\\Users\\trentm\\Videos'
+    >>> user_music_dir()
+    'C:\\Users\\trentm\\Music'
+    >>> user_desktop_dir()
+    'C:\\Users\\trentm\\Desktop'
+    >>> user_runtime_dir(appname, appauthor)
+    'C:\\Users\\trentm\\AppData\\Local\\Temp\\Acme\\SuperApp'
+
+On Linux:
+
+.. code-block:: pycon
+
+    >>> from platformdirs import *
+    >>> appname = "SuperApp"
+    >>> appauthor = "Acme"
+    >>> user_data_dir(appname, appauthor)
+    '/home/trentm/.local/share/SuperApp'
+    >>> site_data_dir(appname, appauthor)
+    '/usr/local/share/SuperApp'
+    >>> site_data_dir(appname, appauthor, multipath=True)
+    '/usr/local/share/SuperApp:/usr/share/SuperApp'
+    >>> user_cache_dir(appname, appauthor)
+    '/home/trentm/.cache/SuperApp'
+    >>> user_log_dir(appname, appauthor)
+    '/home/trentm/.local/state/SuperApp/log'
+    >>> user_config_dir(appname)
+    '/home/trentm/.config/SuperApp'
+    >>> user_documents_dir()
+    '/home/trentm/Documents'
+    >>> user_downloads_dir()
+    '/home/trentm/Downloads'
+    >>> user_pictures_dir()
+    '/home/trentm/Pictures'
+    >>> user_videos_dir()
+    '/home/trentm/Videos'
+    >>> user_music_dir()
+    '/home/trentm/Music'
+    >>> user_desktop_dir()
+    '/home/trentm/Desktop'
+    >>> user_runtime_dir(appname, appauthor)
+    '/run/user/{os.getuid()}/SuperApp'
+    >>> site_config_dir(appname)
+    '/etc/xdg/SuperApp'
+    >>> os.environ["XDG_CONFIG_DIRS"] = "/etc:/usr/local/etc"
+    >>> site_config_dir(appname, multipath=True)
+    '/etc/SuperApp:/usr/local/etc/SuperApp'
+
+On Android::
+
+    >>> from platformdirs import *
+    >>> appname = "SuperApp"
+    >>> appauthor = "Acme"
+    >>> user_data_dir(appname, appauthor)
+    '/data/data/com.myApp/files/SuperApp'
+    >>> user_cache_dir(appname, appauthor)
+    '/data/data/com.myApp/cache/SuperApp'
+    >>> user_log_dir(appname, appauthor)
+    '/data/data/com.myApp/cache/SuperApp/log'
+    >>> user_config_dir(appname)
+    '/data/data/com.myApp/shared_prefs/SuperApp'
+    >>> user_documents_dir()
+    '/storage/emulated/0/Documents'
+    >>> user_downloads_dir()
+    '/storage/emulated/0/Downloads'
+    >>> user_pictures_dir()
+    '/storage/emulated/0/Pictures'
+    >>> user_videos_dir()
+    '/storage/emulated/0/DCIM/Camera'
+    >>> user_music_dir()
+    '/storage/emulated/0/Music'
+    >>> user_desktop_dir()
+    '/storage/emulated/0/Desktop'
+    >>> user_runtime_dir(appname, appauthor)
+    '/data/data/com.myApp/cache/SuperApp/tmp'
+
+Note: Some android apps like Termux and Pydroid are used as shells. These
+apps are used by the end user to emulate Linux environment. Presence of
+``SHELL`` environment variable is used by Platformdirs to differentiate
+between general android apps and android apps used as shells. Shell android
+apps also support ``XDG_*`` environment variables.
+
+
+``PlatformDirs`` for convenience
+================================
+
+.. code-block:: pycon
+
+    >>> from platformdirs import PlatformDirs
+    >>> dirs = PlatformDirs("SuperApp", "Acme")
+    >>> dirs.user_data_dir
+    '/Users/trentm/Library/Application Support/SuperApp'
+    >>> dirs.site_data_dir
+    '/Library/Application Support/SuperApp'
+    >>> dirs.user_cache_dir
+    '/Users/trentm/Library/Caches/SuperApp'
+    >>> dirs.user_log_dir
+    '/Users/trentm/Library/Logs/SuperApp'
+    >>> dirs.user_documents_dir
+    '/Users/trentm/Documents'
+    >>> dirs.user_downloads_dir
+    '/Users/trentm/Downloads'
+    >>> dirs.user_pictures_dir
+    '/Users/trentm/Pictures'
+    >>> dirs.user_videos_dir
+    '/Users/trentm/Movies'
+    >>> dirs.user_music_dir
+    '/Users/trentm/Music'
+    >>> dirs.user_desktop_dir
+    '/Users/trentm/Desktop'
+    >>> dirs.user_runtime_dir
+    '/Users/trentm/Library/Caches/TemporaryItems/SuperApp'
+
+Per-version isolation
+=====================
+
+If you have multiple versions of your app in use that you want to be
+able to run side-by-side, then you may want version-isolation for these
+dirs::
+
+    >>> from platformdirs import PlatformDirs
+    >>> dirs = PlatformDirs("SuperApp", "Acme", version="1.0")
+    >>> dirs.user_data_dir
+    '/Users/trentm/Library/Application Support/SuperApp/1.0'
+    >>> dirs.site_data_dir
+    '/Library/Application Support/SuperApp/1.0'
+    >>> dirs.user_cache_dir
+    '/Users/trentm/Library/Caches/SuperApp/1.0'
+    >>> dirs.user_log_dir
+    '/Users/trentm/Library/Logs/SuperApp/1.0'
+    >>> dirs.user_documents_dir
+    '/Users/trentm/Documents'
+    >>> dirs.user_downloads_dir
+    '/Users/trentm/Downloads'
+    >>> dirs.user_pictures_dir
+    '/Users/trentm/Pictures'
+    >>> dirs.user_videos_dir
+    '/Users/trentm/Movies'
+    >>> dirs.user_music_dir
+    '/Users/trentm/Music'
+    >>> dirs.user_desktop_dir
+    '/Users/trentm/Desktop'
+    >>> dirs.user_runtime_dir
+    '/Users/trentm/Library/Caches/TemporaryItems/SuperApp/1.0'
+
+Be wary of using this for configuration files though; you'll need to handle
+migrating configuration files manually.
+
+Why this Fork?
+==============
+
+This repository is a friendly fork of the wonderful work started by
+`ActiveState `_ who created
+``appdirs``, this package's ancestor.
+
+Maintaining an open source project is no easy task, particularly
+from within an organization, and the Python community is indebted
+to ``appdirs`` (and to Trent Mick and Jeff Rouse in particular) for
+creating an incredibly useful simple module, as evidenced by the wide
+number of users it has attracted over the years.
+
+Nonetheless, given the number of long-standing open issues
+and pull requests, and no clear path towards `ensuring
+that maintenance of the package would continue or grow
+`_, this fork was
+created.
+
+Contributions are most welcome.
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs-4.2.2.dist-info/RECORD b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs-4.2.2.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..64c0c8ea2eeca2768ee87d653fa3539517b0d6bb
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs-4.2.2.dist-info/RECORD
@@ -0,0 +1,23 @@
+platformdirs-4.2.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+platformdirs-4.2.2.dist-info/METADATA,sha256=zmsie01G1MtXR0wgIv5XpVeTO7idr0WWvfmxKsKWuGk,11429
+platformdirs-4.2.2.dist-info/RECORD,,
+platformdirs-4.2.2.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+platformdirs-4.2.2.dist-info/WHEEL,sha256=zEMcRr9Kr03x1ozGwg5v9NQBKn3kndp6LSoSlVg-jhU,87
+platformdirs-4.2.2.dist-info/licenses/LICENSE,sha256=KeD9YukphQ6G6yjD_czwzv30-pSHkBHP-z0NS-1tTbY,1089
+platformdirs/__init__.py,sha256=EMGE8qeHRR9CzDFr8kL3tA8hdZZniYjXBVZd0UGTWK0,22225
+platformdirs/__main__.py,sha256=HnsUQHpiBaiTxwcmwVw-nFaPdVNZtQIdi1eWDtI-MzI,1493
+platformdirs/__pycache__/__init__.cpython-312.pyc,,
+platformdirs/__pycache__/__main__.cpython-312.pyc,,
+platformdirs/__pycache__/android.cpython-312.pyc,,
+platformdirs/__pycache__/api.cpython-312.pyc,,
+platformdirs/__pycache__/macos.cpython-312.pyc,,
+platformdirs/__pycache__/unix.cpython-312.pyc,,
+platformdirs/__pycache__/version.cpython-312.pyc,,
+platformdirs/__pycache__/windows.cpython-312.pyc,,
+platformdirs/android.py,sha256=xZXY9Jd46WOsxT2U6-5HsNtDZ-IQqxcEUrBLl3hYk4o,9016
+platformdirs/api.py,sha256=QBYdUac2eC521ek_y53uD1Dcq-lJX8IgSRVd4InC6uc,8996
+platformdirs/macos.py,sha256=wftsbsvq6nZ0WORXSiCrZNkRHz_WKuktl0a6mC7MFkI,5580
+platformdirs/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+platformdirs/unix.py,sha256=Cci9Wqt35dAMsg6HT9nRGHSBW5obb0pR3AE1JJnsCXg,10643
+platformdirs/version.py,sha256=r7F76tZRjgQKzrpx_I0_ZMQOMU-PS7eGnHD7zEK3KB0,411
+platformdirs/windows.py,sha256=IFpiohUBwxPtCzlyKwNtxyW4Jk8haa6W8o59mfrDXVo,10125
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs-4.2.2.dist-info/REQUESTED b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs-4.2.2.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs-4.2.2.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs-4.2.2.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..516596c76787b10928cbab24f22c0ea00433b15d
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs-4.2.2.dist-info/WHEEL
@@ -0,0 +1,4 @@
+Wheel-Version: 1.0
+Generator: hatchling 1.24.2
+Root-Is-Purelib: true
+Tag: py3-none-any
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs-4.2.2.dist-info/licenses/LICENSE b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs-4.2.2.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..f35fed9191b1142ddaada8a96de4a9461c5d796c
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs-4.2.2.dist-info/licenses/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2010-202x The platformdirs developers
+
+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.12/site-packages/setuptools/_vendor/platformdirs/__init__.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3f7d9490d12b7224fc5d5348823619f262a0aae5
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/__init__.py
@@ -0,0 +1,627 @@
+"""
+Utilities for determining application-specific dirs.
+
+See  for details and usage.
+
+"""
+
+from __future__ import annotations
+
+import os
+import sys
+from typing import TYPE_CHECKING
+
+from .api import PlatformDirsABC
+from .version import __version__
+from .version import __version_tuple__ as __version_info__
+
+if TYPE_CHECKING:
+    from pathlib import Path
+    from typing import Literal
+
+
+def _set_platform_dir_class() -> type[PlatformDirsABC]:
+    if sys.platform == "win32":
+        from platformdirs.windows import Windows as Result  # noqa: PLC0415
+    elif sys.platform == "darwin":
+        from platformdirs.macos import MacOS as Result  # noqa: PLC0415
+    else:
+        from platformdirs.unix import Unix as Result  # noqa: PLC0415
+
+    if os.getenv("ANDROID_DATA") == "/data" and os.getenv("ANDROID_ROOT") == "/system":
+        if os.getenv("SHELL") or os.getenv("PREFIX"):
+            return Result
+
+        from platformdirs.android import _android_folder  # noqa: PLC0415
+
+        if _android_folder() is not None:
+            from platformdirs.android import Android  # noqa: PLC0415
+
+            return Android  # return to avoid redefinition of a result
+
+    return Result
+
+
+PlatformDirs = _set_platform_dir_class()  #: Currently active platform
+AppDirs = PlatformDirs  #: Backwards compatibility with appdirs
+
+
+def user_data_dir(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    roaming: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param roaming: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: data directory tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        roaming=roaming,
+        ensure_exists=ensure_exists,
+    ).user_data_dir
+
+
+def site_data_dir(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    multipath: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param multipath: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: data directory shared by users
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        multipath=multipath,
+        ensure_exists=ensure_exists,
+    ).site_data_dir
+
+
+def user_config_dir(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    roaming: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param roaming: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: config directory tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        roaming=roaming,
+        ensure_exists=ensure_exists,
+    ).user_config_dir
+
+
+def site_config_dir(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    multipath: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param multipath: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: config directory shared by the users
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        multipath=multipath,
+        ensure_exists=ensure_exists,
+    ).site_config_dir
+
+
+def user_cache_dir(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: cache directory tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+    ).user_cache_dir
+
+
+def site_cache_dir(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `opinion `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: cache directory tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+    ).site_cache_dir
+
+
+def user_state_dir(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    roaming: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param roaming: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: state directory tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        roaming=roaming,
+        ensure_exists=ensure_exists,
+    ).user_state_dir
+
+
+def user_log_dir(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: log directory tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+    ).user_log_dir
+
+
+def user_documents_dir() -> str:
+    """:returns: documents directory tied to the user"""
+    return PlatformDirs().user_documents_dir
+
+
+def user_downloads_dir() -> str:
+    """:returns: downloads directory tied to the user"""
+    return PlatformDirs().user_downloads_dir
+
+
+def user_pictures_dir() -> str:
+    """:returns: pictures directory tied to the user"""
+    return PlatformDirs().user_pictures_dir
+
+
+def user_videos_dir() -> str:
+    """:returns: videos directory tied to the user"""
+    return PlatformDirs().user_videos_dir
+
+
+def user_music_dir() -> str:
+    """:returns: music directory tied to the user"""
+    return PlatformDirs().user_music_dir
+
+
+def user_desktop_dir() -> str:
+    """:returns: desktop directory tied to the user"""
+    return PlatformDirs().user_desktop_dir
+
+
+def user_runtime_dir(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `opinion `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: runtime directory tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+    ).user_runtime_dir
+
+
+def site_runtime_dir(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `opinion `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: runtime directory shared by users
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+    ).site_runtime_dir
+
+
+def user_data_path(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    roaming: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param roaming: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: data path tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        roaming=roaming,
+        ensure_exists=ensure_exists,
+    ).user_data_path
+
+
+def site_data_path(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    multipath: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param multipath: See `multipath `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: data path shared by users
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        multipath=multipath,
+        ensure_exists=ensure_exists,
+    ).site_data_path
+
+
+def user_config_path(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    roaming: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param roaming: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: config path tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        roaming=roaming,
+        ensure_exists=ensure_exists,
+    ).user_config_path
+
+
+def site_config_path(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    multipath: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param multipath: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: config path shared by the users
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        multipath=multipath,
+        ensure_exists=ensure_exists,
+    ).site_config_path
+
+
+def site_cache_path(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `opinion `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: cache directory tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+    ).site_cache_path
+
+
+def user_cache_path(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: cache path tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+    ).user_cache_path
+
+
+def user_state_path(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    roaming: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param roaming: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: state path tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        roaming=roaming,
+        ensure_exists=ensure_exists,
+    ).user_state_path
+
+
+def user_log_path(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: log path tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+    ).user_log_path
+
+
+def user_documents_path() -> Path:
+    """:returns: documents a path tied to the user"""
+    return PlatformDirs().user_documents_path
+
+
+def user_downloads_path() -> Path:
+    """:returns: downloads path tied to the user"""
+    return PlatformDirs().user_downloads_path
+
+
+def user_pictures_path() -> Path:
+    """:returns: pictures path tied to the user"""
+    return PlatformDirs().user_pictures_path
+
+
+def user_videos_path() -> Path:
+    """:returns: videos path tied to the user"""
+    return PlatformDirs().user_videos_path
+
+
+def user_music_path() -> Path:
+    """:returns: music path tied to the user"""
+    return PlatformDirs().user_music_path
+
+
+def user_desktop_path() -> Path:
+    """:returns: desktop path tied to the user"""
+    return PlatformDirs().user_desktop_path
+
+
+def user_runtime_path(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `opinion `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: runtime path tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+    ).user_runtime_path
+
+
+def site_runtime_path(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `opinion `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: runtime path shared by users
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+    ).site_runtime_path
+
+
+__all__ = [
+    "AppDirs",
+    "PlatformDirs",
+    "PlatformDirsABC",
+    "__version__",
+    "__version_info__",
+    "site_cache_dir",
+    "site_cache_path",
+    "site_config_dir",
+    "site_config_path",
+    "site_data_dir",
+    "site_data_path",
+    "site_runtime_dir",
+    "site_runtime_path",
+    "user_cache_dir",
+    "user_cache_path",
+    "user_config_dir",
+    "user_config_path",
+    "user_data_dir",
+    "user_data_path",
+    "user_desktop_dir",
+    "user_desktop_path",
+    "user_documents_dir",
+    "user_documents_path",
+    "user_downloads_dir",
+    "user_downloads_path",
+    "user_log_dir",
+    "user_log_path",
+    "user_music_dir",
+    "user_music_path",
+    "user_pictures_dir",
+    "user_pictures_path",
+    "user_runtime_dir",
+    "user_runtime_path",
+    "user_state_dir",
+    "user_state_path",
+    "user_videos_dir",
+    "user_videos_path",
+]
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/__main__.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/__main__.py
new file mode 100644
index 0000000000000000000000000000000000000000..922c521358e349470ec48d6372b8f8ee8641128a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/__main__.py
@@ -0,0 +1,55 @@
+"""Main entry point."""
+
+from __future__ import annotations
+
+from platformdirs import PlatformDirs, __version__
+
+PROPS = (
+    "user_data_dir",
+    "user_config_dir",
+    "user_cache_dir",
+    "user_state_dir",
+    "user_log_dir",
+    "user_documents_dir",
+    "user_downloads_dir",
+    "user_pictures_dir",
+    "user_videos_dir",
+    "user_music_dir",
+    "user_runtime_dir",
+    "site_data_dir",
+    "site_config_dir",
+    "site_cache_dir",
+    "site_runtime_dir",
+)
+
+
+def main() -> None:
+    """Run the main entry point."""
+    app_name = "MyApp"
+    app_author = "MyCompany"
+
+    print(f"-- platformdirs {__version__} --")  # noqa: T201
+
+    print("-- app dirs (with optional 'version')")  # noqa: T201
+    dirs = PlatformDirs(app_name, app_author, version="1.0")
+    for prop in PROPS:
+        print(f"{prop}: {getattr(dirs, prop)}")  # noqa: T201
+
+    print("\n-- app dirs (without optional 'version')")  # noqa: T201
+    dirs = PlatformDirs(app_name, app_author)
+    for prop in PROPS:
+        print(f"{prop}: {getattr(dirs, prop)}")  # noqa: T201
+
+    print("\n-- app dirs (without optional 'appauthor')")  # noqa: T201
+    dirs = PlatformDirs(app_name)
+    for prop in PROPS:
+        print(f"{prop}: {getattr(dirs, prop)}")  # noqa: T201
+
+    print("\n-- app dirs (with disabled 'appauthor')")  # noqa: T201
+    dirs = PlatformDirs(app_name, appauthor=False)
+    for prop in PROPS:
+        print(f"{prop}: {getattr(dirs, prop)}")  # noqa: T201
+
+
+if __name__ == "__main__":
+    main()
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4d9b2ef492f21960b2f70a157a9824b37cc7813b
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/__pycache__/__main__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/__pycache__/__main__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..22cdaf123e882f1f410bea259943321f6b8f59ea
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/__pycache__/__main__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/__pycache__/android.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/__pycache__/android.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c7f73790693f19ddb8b7300533c6d28ed74bf276
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/__pycache__/android.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/__pycache__/api.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/__pycache__/api.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b5dfbc80ed443678c4d5c9d87666d9da78c214a6
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/__pycache__/api.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/__pycache__/macos.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/__pycache__/macos.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8c85c80d539356efeb23ac013e8177f5764759e1
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/__pycache__/macos.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/__pycache__/unix.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/__pycache__/unix.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3c05b09dceec3f27eed6c2c49f94b33b1864f268
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/__pycache__/unix.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/__pycache__/version.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/__pycache__/version.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a65d8de021bedaba66a583fafe633c90c30407e6
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/__pycache__/version.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/__pycache__/windows.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/__pycache__/windows.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c4962987e73a459a160198fe0f3a1efd7e4058cd
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/__pycache__/windows.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/android.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/android.py
new file mode 100644
index 0000000000000000000000000000000000000000..afd3141c725873847bdecf88222c73ff7d5afc39
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/android.py
@@ -0,0 +1,249 @@
+"""Android."""
+
+from __future__ import annotations
+
+import os
+import re
+import sys
+from functools import lru_cache
+from typing import TYPE_CHECKING, cast
+
+from .api import PlatformDirsABC
+
+
+class Android(PlatformDirsABC):
+    """
+    Follows the guidance `from here `_.
+
+    Makes use of the `appname `, `version
+    `, `ensure_exists `.
+
+    """
+
+    @property
+    def user_data_dir(self) -> str:
+        """:return: data directory tied to the user, e.g. ``/data/user///files/``"""
+        return self._append_app_name_and_version(cast(str, _android_folder()), "files")
+
+    @property
+    def site_data_dir(self) -> str:
+        """:return: data directory shared by users, same as `user_data_dir`"""
+        return self.user_data_dir
+
+    @property
+    def user_config_dir(self) -> str:
+        """
+        :return: config directory tied to the user, e.g. \
+        ``/data/user///shared_prefs/``
+        """
+        return self._append_app_name_and_version(cast(str, _android_folder()), "shared_prefs")
+
+    @property
+    def site_config_dir(self) -> str:
+        """:return: config directory shared by the users, same as `user_config_dir`"""
+        return self.user_config_dir
+
+    @property
+    def user_cache_dir(self) -> str:
+        """:return: cache directory tied to the user, e.g.,``/data/user///cache/``"""
+        return self._append_app_name_and_version(cast(str, _android_folder()), "cache")
+
+    @property
+    def site_cache_dir(self) -> str:
+        """:return: cache directory shared by users, same as `user_cache_dir`"""
+        return self.user_cache_dir
+
+    @property
+    def user_state_dir(self) -> str:
+        """:return: state directory tied to the user, same as `user_data_dir`"""
+        return self.user_data_dir
+
+    @property
+    def user_log_dir(self) -> str:
+        """
+        :return: log directory tied to the user, same as `user_cache_dir` if not opinionated else ``log`` in it,
+          e.g. ``/data/user///cache//log``
+        """
+        path = self.user_cache_dir
+        if self.opinion:
+            path = os.path.join(path, "log")  # noqa: PTH118
+        return path
+
+    @property
+    def user_documents_dir(self) -> str:
+        """:return: documents directory tied to the user e.g. ``/storage/emulated/0/Documents``"""
+        return _android_documents_folder()
+
+    @property
+    def user_downloads_dir(self) -> str:
+        """:return: downloads directory tied to the user e.g. ``/storage/emulated/0/Downloads``"""
+        return _android_downloads_folder()
+
+    @property
+    def user_pictures_dir(self) -> str:
+        """:return: pictures directory tied to the user e.g. ``/storage/emulated/0/Pictures``"""
+        return _android_pictures_folder()
+
+    @property
+    def user_videos_dir(self) -> str:
+        """:return: videos directory tied to the user e.g. ``/storage/emulated/0/DCIM/Camera``"""
+        return _android_videos_folder()
+
+    @property
+    def user_music_dir(self) -> str:
+        """:return: music directory tied to the user e.g. ``/storage/emulated/0/Music``"""
+        return _android_music_folder()
+
+    @property
+    def user_desktop_dir(self) -> str:
+        """:return: desktop directory tied to the user e.g. ``/storage/emulated/0/Desktop``"""
+        return "/storage/emulated/0/Desktop"
+
+    @property
+    def user_runtime_dir(self) -> str:
+        """
+        :return: runtime directory tied to the user, same as `user_cache_dir` if not opinionated else ``tmp`` in it,
+          e.g. ``/data/user///cache//tmp``
+        """
+        path = self.user_cache_dir
+        if self.opinion:
+            path = os.path.join(path, "tmp")  # noqa: PTH118
+        return path
+
+    @property
+    def site_runtime_dir(self) -> str:
+        """:return: runtime directory shared by users, same as `user_runtime_dir`"""
+        return self.user_runtime_dir
+
+
+@lru_cache(maxsize=1)
+def _android_folder() -> str | None:  # noqa: C901, PLR0912
+    """:return: base folder for the Android OS or None if it cannot be found"""
+    result: str | None = None
+    # type checker isn't happy with our "import android", just don't do this when type checking see
+    # https://stackoverflow.com/a/61394121
+    if not TYPE_CHECKING:
+        try:
+            # First try to get a path to android app using python4android (if available)...
+            from android import mActivity  # noqa: PLC0415
+
+            context = cast("android.content.Context", mActivity.getApplicationContext())  # noqa: F821
+            result = context.getFilesDir().getParentFile().getAbsolutePath()
+        except Exception:  # noqa: BLE001
+            result = None
+    if result is None:
+        try:
+            # ...and fall back to using plain pyjnius, if python4android isn't available or doesn't deliver any useful
+            # result...
+            from jnius import autoclass  # noqa: PLC0415
+
+            context = autoclass("android.content.Context")
+            result = context.getFilesDir().getParentFile().getAbsolutePath()
+        except Exception:  # noqa: BLE001
+            result = None
+    if result is None:
+        # and if that fails, too, find an android folder looking at path on the sys.path
+        # warning: only works for apps installed under /data, not adopted storage etc.
+        pattern = re.compile(r"/data/(data|user/\d+)/(.+)/files")
+        for path in sys.path:
+            if pattern.match(path):
+                result = path.split("/files")[0]
+                break
+        else:
+            result = None
+    if result is None:
+        # one last try: find an android folder looking at path on the sys.path taking adopted storage paths into
+        # account
+        pattern = re.compile(r"/mnt/expand/[a-fA-F0-9-]{36}/(data|user/\d+)/(.+)/files")
+        for path in sys.path:
+            if pattern.match(path):
+                result = path.split("/files")[0]
+                break
+        else:
+            result = None
+    return result
+
+
+@lru_cache(maxsize=1)
+def _android_documents_folder() -> str:
+    """:return: documents folder for the Android OS"""
+    # Get directories with pyjnius
+    try:
+        from jnius import autoclass  # noqa: PLC0415
+
+        context = autoclass("android.content.Context")
+        environment = autoclass("android.os.Environment")
+        documents_dir: str = context.getExternalFilesDir(environment.DIRECTORY_DOCUMENTS).getAbsolutePath()
+    except Exception:  # noqa: BLE001
+        documents_dir = "/storage/emulated/0/Documents"
+
+    return documents_dir
+
+
+@lru_cache(maxsize=1)
+def _android_downloads_folder() -> str:
+    """:return: downloads folder for the Android OS"""
+    # Get directories with pyjnius
+    try:
+        from jnius import autoclass  # noqa: PLC0415
+
+        context = autoclass("android.content.Context")
+        environment = autoclass("android.os.Environment")
+        downloads_dir: str = context.getExternalFilesDir(environment.DIRECTORY_DOWNLOADS).getAbsolutePath()
+    except Exception:  # noqa: BLE001
+        downloads_dir = "/storage/emulated/0/Downloads"
+
+    return downloads_dir
+
+
+@lru_cache(maxsize=1)
+def _android_pictures_folder() -> str:
+    """:return: pictures folder for the Android OS"""
+    # Get directories with pyjnius
+    try:
+        from jnius import autoclass  # noqa: PLC0415
+
+        context = autoclass("android.content.Context")
+        environment = autoclass("android.os.Environment")
+        pictures_dir: str = context.getExternalFilesDir(environment.DIRECTORY_PICTURES).getAbsolutePath()
+    except Exception:  # noqa: BLE001
+        pictures_dir = "/storage/emulated/0/Pictures"
+
+    return pictures_dir
+
+
+@lru_cache(maxsize=1)
+def _android_videos_folder() -> str:
+    """:return: videos folder for the Android OS"""
+    # Get directories with pyjnius
+    try:
+        from jnius import autoclass  # noqa: PLC0415
+
+        context = autoclass("android.content.Context")
+        environment = autoclass("android.os.Environment")
+        videos_dir: str = context.getExternalFilesDir(environment.DIRECTORY_DCIM).getAbsolutePath()
+    except Exception:  # noqa: BLE001
+        videos_dir = "/storage/emulated/0/DCIM/Camera"
+
+    return videos_dir
+
+
+@lru_cache(maxsize=1)
+def _android_music_folder() -> str:
+    """:return: music folder for the Android OS"""
+    # Get directories with pyjnius
+    try:
+        from jnius import autoclass  # noqa: PLC0415
+
+        context = autoclass("android.content.Context")
+        environment = autoclass("android.os.Environment")
+        music_dir: str = context.getExternalFilesDir(environment.DIRECTORY_MUSIC).getAbsolutePath()
+    except Exception:  # noqa: BLE001
+        music_dir = "/storage/emulated/0/Music"
+
+    return music_dir
+
+
+__all__ = [
+    "Android",
+]
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/api.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..c50caa648a6d18f5b515404ac5a4d0e41a072739
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/api.py
@@ -0,0 +1,292 @@
+"""Base API."""
+
+from __future__ import annotations
+
+import os
+from abc import ABC, abstractmethod
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Iterator, Literal
+
+
+class PlatformDirsABC(ABC):  # noqa: PLR0904
+    """Abstract base class for platform directories."""
+
+    def __init__(  # noqa: PLR0913, PLR0917
+        self,
+        appname: str | None = None,
+        appauthor: str | None | Literal[False] = None,
+        version: str | None = None,
+        roaming: bool = False,  # noqa: FBT001, FBT002
+        multipath: bool = False,  # noqa: FBT001, FBT002
+        opinion: bool = True,  # noqa: FBT001, FBT002
+        ensure_exists: bool = False,  # noqa: FBT001, FBT002
+    ) -> None:
+        """
+        Create a new platform directory.
+
+        :param appname: See `appname`.
+        :param appauthor: See `appauthor`.
+        :param version: See `version`.
+        :param roaming: See `roaming`.
+        :param multipath: See `multipath`.
+        :param opinion: See `opinion`.
+        :param ensure_exists: See `ensure_exists`.
+
+        """
+        self.appname = appname  #: The name of application.
+        self.appauthor = appauthor
+        """
+        The name of the app author or distributing body for this application.
+
+        Typically, it is the owning company name. Defaults to `appname`. You may pass ``False`` to disable it.
+
+        """
+        self.version = version
+        """
+        An optional version path element to append to the path.
+
+        You might want to use this if you want multiple versions of your app to be able to run independently. If used,
+        this would typically be ``.``.
+
+        """
+        self.roaming = roaming
+        """
+        Whether to use the roaming appdata directory on Windows.
+
+        That means that for users on a Windows network setup for roaming profiles, this user data will be synced on
+        login (see
+        `here `_).
+
+        """
+        self.multipath = multipath
+        """
+        An optional parameter which indicates that the entire list of data dirs should be returned.
+
+        By default, the first item would only be returned.
+
+        """
+        self.opinion = opinion  #: A flag to indicating to use opinionated values.
+        self.ensure_exists = ensure_exists
+        """
+        Optionally create the directory (and any missing parents) upon access if it does not exist.
+
+        By default, no directories are created.
+
+        """
+
+    def _append_app_name_and_version(self, *base: str) -> str:
+        params = list(base[1:])
+        if self.appname:
+            params.append(self.appname)
+            if self.version:
+                params.append(self.version)
+        path = os.path.join(base[0], *params)  # noqa: PTH118
+        self._optionally_create_directory(path)
+        return path
+
+    def _optionally_create_directory(self, path: str) -> None:
+        if self.ensure_exists:
+            Path(path).mkdir(parents=True, exist_ok=True)
+
+    @property
+    @abstractmethod
+    def user_data_dir(self) -> str:
+        """:return: data directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def site_data_dir(self) -> str:
+        """:return: data directory shared by users"""
+
+    @property
+    @abstractmethod
+    def user_config_dir(self) -> str:
+        """:return: config directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def site_config_dir(self) -> str:
+        """:return: config directory shared by the users"""
+
+    @property
+    @abstractmethod
+    def user_cache_dir(self) -> str:
+        """:return: cache directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def site_cache_dir(self) -> str:
+        """:return: cache directory shared by users"""
+
+    @property
+    @abstractmethod
+    def user_state_dir(self) -> str:
+        """:return: state directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def user_log_dir(self) -> str:
+        """:return: log directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def user_documents_dir(self) -> str:
+        """:return: documents directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def user_downloads_dir(self) -> str:
+        """:return: downloads directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def user_pictures_dir(self) -> str:
+        """:return: pictures directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def user_videos_dir(self) -> str:
+        """:return: videos directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def user_music_dir(self) -> str:
+        """:return: music directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def user_desktop_dir(self) -> str:
+        """:return: desktop directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def user_runtime_dir(self) -> str:
+        """:return: runtime directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def site_runtime_dir(self) -> str:
+        """:return: runtime directory shared by users"""
+
+    @property
+    def user_data_path(self) -> Path:
+        """:return: data path tied to the user"""
+        return Path(self.user_data_dir)
+
+    @property
+    def site_data_path(self) -> Path:
+        """:return: data path shared by users"""
+        return Path(self.site_data_dir)
+
+    @property
+    def user_config_path(self) -> Path:
+        """:return: config path tied to the user"""
+        return Path(self.user_config_dir)
+
+    @property
+    def site_config_path(self) -> Path:
+        """:return: config path shared by the users"""
+        return Path(self.site_config_dir)
+
+    @property
+    def user_cache_path(self) -> Path:
+        """:return: cache path tied to the user"""
+        return Path(self.user_cache_dir)
+
+    @property
+    def site_cache_path(self) -> Path:
+        """:return: cache path shared by users"""
+        return Path(self.site_cache_dir)
+
+    @property
+    def user_state_path(self) -> Path:
+        """:return: state path tied to the user"""
+        return Path(self.user_state_dir)
+
+    @property
+    def user_log_path(self) -> Path:
+        """:return: log path tied to the user"""
+        return Path(self.user_log_dir)
+
+    @property
+    def user_documents_path(self) -> Path:
+        """:return: documents a path tied to the user"""
+        return Path(self.user_documents_dir)
+
+    @property
+    def user_downloads_path(self) -> Path:
+        """:return: downloads path tied to the user"""
+        return Path(self.user_downloads_dir)
+
+    @property
+    def user_pictures_path(self) -> Path:
+        """:return: pictures path tied to the user"""
+        return Path(self.user_pictures_dir)
+
+    @property
+    def user_videos_path(self) -> Path:
+        """:return: videos path tied to the user"""
+        return Path(self.user_videos_dir)
+
+    @property
+    def user_music_path(self) -> Path:
+        """:return: music path tied to the user"""
+        return Path(self.user_music_dir)
+
+    @property
+    def user_desktop_path(self) -> Path:
+        """:return: desktop path tied to the user"""
+        return Path(self.user_desktop_dir)
+
+    @property
+    def user_runtime_path(self) -> Path:
+        """:return: runtime path tied to the user"""
+        return Path(self.user_runtime_dir)
+
+    @property
+    def site_runtime_path(self) -> Path:
+        """:return: runtime path shared by users"""
+        return Path(self.site_runtime_dir)
+
+    def iter_config_dirs(self) -> Iterator[str]:
+        """:yield: all user and site configuration directories."""
+        yield self.user_config_dir
+        yield self.site_config_dir
+
+    def iter_data_dirs(self) -> Iterator[str]:
+        """:yield: all user and site data directories."""
+        yield self.user_data_dir
+        yield self.site_data_dir
+
+    def iter_cache_dirs(self) -> Iterator[str]:
+        """:yield: all user and site cache directories."""
+        yield self.user_cache_dir
+        yield self.site_cache_dir
+
+    def iter_runtime_dirs(self) -> Iterator[str]:
+        """:yield: all user and site runtime directories."""
+        yield self.user_runtime_dir
+        yield self.site_runtime_dir
+
+    def iter_config_paths(self) -> Iterator[Path]:
+        """:yield: all user and site configuration paths."""
+        for path in self.iter_config_dirs():
+            yield Path(path)
+
+    def iter_data_paths(self) -> Iterator[Path]:
+        """:yield: all user and site data paths."""
+        for path in self.iter_data_dirs():
+            yield Path(path)
+
+    def iter_cache_paths(self) -> Iterator[Path]:
+        """:yield: all user and site cache paths."""
+        for path in self.iter_cache_dirs():
+            yield Path(path)
+
+    def iter_runtime_paths(self) -> Iterator[Path]:
+        """:yield: all user and site runtime paths."""
+        for path in self.iter_runtime_dirs():
+            yield Path(path)
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/macos.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/macos.py
new file mode 100644
index 0000000000000000000000000000000000000000..eb1ba5df1dacfb4cbedc66e0ddd81a4057d4ebbe
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/macos.py
@@ -0,0 +1,130 @@
+"""macOS."""
+
+from __future__ import annotations
+
+import os.path
+import sys
+
+from .api import PlatformDirsABC
+
+
+class MacOS(PlatformDirsABC):
+    """
+    Platform directories for the macOS operating system.
+
+    Follows the guidance from
+    `Apple documentation `_.
+    Makes use of the `appname `,
+    `version `,
+    `ensure_exists `.
+
+    """
+
+    @property
+    def user_data_dir(self) -> str:
+        """:return: data directory tied to the user, e.g. ``~/Library/Application Support/$appname/$version``"""
+        return self._append_app_name_and_version(os.path.expanduser("~/Library/Application Support"))  # noqa: PTH111
+
+    @property
+    def site_data_dir(self) -> str:
+        """
+        :return: data directory shared by users, e.g. ``/Library/Application Support/$appname/$version``.
+          If we're using a Python binary managed by `Homebrew `_, the directory
+          will be under the Homebrew prefix, e.g. ``/opt/homebrew/share/$appname/$version``.
+          If `multipath ` is enabled, and we're in Homebrew,
+          the response is a multi-path string separated by ":", e.g.
+          ``/opt/homebrew/share/$appname/$version:/Library/Application Support/$appname/$version``
+        """
+        is_homebrew = sys.prefix.startswith("/opt/homebrew")
+        path_list = [self._append_app_name_and_version("/opt/homebrew/share")] if is_homebrew else []
+        path_list.append(self._append_app_name_and_version("/Library/Application Support"))
+        if self.multipath:
+            return os.pathsep.join(path_list)
+        return path_list[0]
+
+    @property
+    def user_config_dir(self) -> str:
+        """:return: config directory tied to the user, same as `user_data_dir`"""
+        return self.user_data_dir
+
+    @property
+    def site_config_dir(self) -> str:
+        """:return: config directory shared by the users, same as `site_data_dir`"""
+        return self.site_data_dir
+
+    @property
+    def user_cache_dir(self) -> str:
+        """:return: cache directory tied to the user, e.g. ``~/Library/Caches/$appname/$version``"""
+        return self._append_app_name_and_version(os.path.expanduser("~/Library/Caches"))  # noqa: PTH111
+
+    @property
+    def site_cache_dir(self) -> str:
+        """
+        :return: cache directory shared by users, e.g. ``/Library/Caches/$appname/$version``.
+          If we're using a Python binary managed by `Homebrew `_, the directory
+          will be under the Homebrew prefix, e.g. ``/opt/homebrew/var/cache/$appname/$version``.
+          If `multipath ` is enabled, and we're in Homebrew,
+          the response is a multi-path string separated by ":", e.g.
+          ``/opt/homebrew/var/cache/$appname/$version:/Library/Caches/$appname/$version``
+        """
+        is_homebrew = sys.prefix.startswith("/opt/homebrew")
+        path_list = [self._append_app_name_and_version("/opt/homebrew/var/cache")] if is_homebrew else []
+        path_list.append(self._append_app_name_and_version("/Library/Caches"))
+        if self.multipath:
+            return os.pathsep.join(path_list)
+        return path_list[0]
+
+    @property
+    def user_state_dir(self) -> str:
+        """:return: state directory tied to the user, same as `user_data_dir`"""
+        return self.user_data_dir
+
+    @property
+    def user_log_dir(self) -> str:
+        """:return: log directory tied to the user, e.g. ``~/Library/Logs/$appname/$version``"""
+        return self._append_app_name_and_version(os.path.expanduser("~/Library/Logs"))  # noqa: PTH111
+
+    @property
+    def user_documents_dir(self) -> str:
+        """:return: documents directory tied to the user, e.g. ``~/Documents``"""
+        return os.path.expanduser("~/Documents")  # noqa: PTH111
+
+    @property
+    def user_downloads_dir(self) -> str:
+        """:return: downloads directory tied to the user, e.g. ``~/Downloads``"""
+        return os.path.expanduser("~/Downloads")  # noqa: PTH111
+
+    @property
+    def user_pictures_dir(self) -> str:
+        """:return: pictures directory tied to the user, e.g. ``~/Pictures``"""
+        return os.path.expanduser("~/Pictures")  # noqa: PTH111
+
+    @property
+    def user_videos_dir(self) -> str:
+        """:return: videos directory tied to the user, e.g. ``~/Movies``"""
+        return os.path.expanduser("~/Movies")  # noqa: PTH111
+
+    @property
+    def user_music_dir(self) -> str:
+        """:return: music directory tied to the user, e.g. ``~/Music``"""
+        return os.path.expanduser("~/Music")  # noqa: PTH111
+
+    @property
+    def user_desktop_dir(self) -> str:
+        """:return: desktop directory tied to the user, e.g. ``~/Desktop``"""
+        return os.path.expanduser("~/Desktop")  # noqa: PTH111
+
+    @property
+    def user_runtime_dir(self) -> str:
+        """:return: runtime directory tied to the user, e.g. ``~/Library/Caches/TemporaryItems/$appname/$version``"""
+        return self._append_app_name_and_version(os.path.expanduser("~/Library/Caches/TemporaryItems"))  # noqa: PTH111
+
+    @property
+    def site_runtime_dir(self) -> str:
+        """:return: runtime directory shared by users, same as `user_runtime_dir`"""
+        return self.user_runtime_dir
+
+
+__all__ = [
+    "MacOS",
+]
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/py.typed b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/unix.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/unix.py
new file mode 100644
index 0000000000000000000000000000000000000000..9500ade614ce4e698ce02e23c8d7b52988a2b1a8
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/unix.py
@@ -0,0 +1,275 @@
+"""Unix."""
+
+from __future__ import annotations
+
+import os
+import sys
+from configparser import ConfigParser
+from pathlib import Path
+from typing import Iterator, NoReturn
+
+from .api import PlatformDirsABC
+
+if sys.platform == "win32":
+
+    def getuid() -> NoReturn:
+        msg = "should only be used on Unix"
+        raise RuntimeError(msg)
+
+else:
+    from os import getuid
+
+
+class Unix(PlatformDirsABC):  # noqa: PLR0904
+    """
+    On Unix/Linux, we follow the `XDG Basedir Spec `_.
+
+    The spec allows overriding directories with environment variables. The examples shown are the default values,
+    alongside the name of the environment variable that overrides them. Makes use of the `appname
+    `, `version `, `multipath
+    `, `opinion `, `ensure_exists
+    `.
+
+    """
+
+    @property
+    def user_data_dir(self) -> str:
+        """
+        :return: data directory tied to the user, e.g. ``~/.local/share/$appname/$version`` or
+         ``$XDG_DATA_HOME/$appname/$version``
+        """
+        path = os.environ.get("XDG_DATA_HOME", "")
+        if not path.strip():
+            path = os.path.expanduser("~/.local/share")  # noqa: PTH111
+        return self._append_app_name_and_version(path)
+
+    @property
+    def _site_data_dirs(self) -> list[str]:
+        path = os.environ.get("XDG_DATA_DIRS", "")
+        if not path.strip():
+            path = f"/usr/local/share{os.pathsep}/usr/share"
+        return [self._append_app_name_and_version(p) for p in path.split(os.pathsep)]
+
+    @property
+    def site_data_dir(self) -> str:
+        """
+        :return: data directories shared by users (if `multipath ` is
+         enabled and ``XDG_DATA_DIRS`` is set and a multi path the response is also a multi path separated by the
+         OS path separator), e.g. ``/usr/local/share/$appname/$version`` or ``/usr/share/$appname/$version``
+        """
+        # XDG default for $XDG_DATA_DIRS; only first, if multipath is False
+        dirs = self._site_data_dirs
+        if not self.multipath:
+            return dirs[0]
+        return os.pathsep.join(dirs)
+
+    @property
+    def user_config_dir(self) -> str:
+        """
+        :return: config directory tied to the user, e.g. ``~/.config/$appname/$version`` or
+         ``$XDG_CONFIG_HOME/$appname/$version``
+        """
+        path = os.environ.get("XDG_CONFIG_HOME", "")
+        if not path.strip():
+            path = os.path.expanduser("~/.config")  # noqa: PTH111
+        return self._append_app_name_and_version(path)
+
+    @property
+    def _site_config_dirs(self) -> list[str]:
+        path = os.environ.get("XDG_CONFIG_DIRS", "")
+        if not path.strip():
+            path = "/etc/xdg"
+        return [self._append_app_name_and_version(p) for p in path.split(os.pathsep)]
+
+    @property
+    def site_config_dir(self) -> str:
+        """
+        :return: config directories shared by users (if `multipath `
+         is enabled and ``XDG_CONFIG_DIRS`` is set and a multi path the response is also a multi path separated by
+         the OS path separator), e.g. ``/etc/xdg/$appname/$version``
+        """
+        # XDG default for $XDG_CONFIG_DIRS only first, if multipath is False
+        dirs = self._site_config_dirs
+        if not self.multipath:
+            return dirs[0]
+        return os.pathsep.join(dirs)
+
+    @property
+    def user_cache_dir(self) -> str:
+        """
+        :return: cache directory tied to the user, e.g. ``~/.cache/$appname/$version`` or
+         ``~/$XDG_CACHE_HOME/$appname/$version``
+        """
+        path = os.environ.get("XDG_CACHE_HOME", "")
+        if not path.strip():
+            path = os.path.expanduser("~/.cache")  # noqa: PTH111
+        return self._append_app_name_and_version(path)
+
+    @property
+    def site_cache_dir(self) -> str:
+        """:return: cache directory shared by users, e.g. ``/var/cache/$appname/$version``"""
+        return self._append_app_name_and_version("/var/cache")
+
+    @property
+    def user_state_dir(self) -> str:
+        """
+        :return: state directory tied to the user, e.g. ``~/.local/state/$appname/$version`` or
+         ``$XDG_STATE_HOME/$appname/$version``
+        """
+        path = os.environ.get("XDG_STATE_HOME", "")
+        if not path.strip():
+            path = os.path.expanduser("~/.local/state")  # noqa: PTH111
+        return self._append_app_name_and_version(path)
+
+    @property
+    def user_log_dir(self) -> str:
+        """:return: log directory tied to the user, same as `user_state_dir` if not opinionated else ``log`` in it"""
+        path = self.user_state_dir
+        if self.opinion:
+            path = os.path.join(path, "log")  # noqa: PTH118
+            self._optionally_create_directory(path)
+        return path
+
+    @property
+    def user_documents_dir(self) -> str:
+        """:return: documents directory tied to the user, e.g. ``~/Documents``"""
+        return _get_user_media_dir("XDG_DOCUMENTS_DIR", "~/Documents")
+
+    @property
+    def user_downloads_dir(self) -> str:
+        """:return: downloads directory tied to the user, e.g. ``~/Downloads``"""
+        return _get_user_media_dir("XDG_DOWNLOAD_DIR", "~/Downloads")
+
+    @property
+    def user_pictures_dir(self) -> str:
+        """:return: pictures directory tied to the user, e.g. ``~/Pictures``"""
+        return _get_user_media_dir("XDG_PICTURES_DIR", "~/Pictures")
+
+    @property
+    def user_videos_dir(self) -> str:
+        """:return: videos directory tied to the user, e.g. ``~/Videos``"""
+        return _get_user_media_dir("XDG_VIDEOS_DIR", "~/Videos")
+
+    @property
+    def user_music_dir(self) -> str:
+        """:return: music directory tied to the user, e.g. ``~/Music``"""
+        return _get_user_media_dir("XDG_MUSIC_DIR", "~/Music")
+
+    @property
+    def user_desktop_dir(self) -> str:
+        """:return: desktop directory tied to the user, e.g. ``~/Desktop``"""
+        return _get_user_media_dir("XDG_DESKTOP_DIR", "~/Desktop")
+
+    @property
+    def user_runtime_dir(self) -> str:
+        """
+        :return: runtime directory tied to the user, e.g. ``/run/user/$(id -u)/$appname/$version`` or
+         ``$XDG_RUNTIME_DIR/$appname/$version``.
+
+         For FreeBSD/OpenBSD/NetBSD, it would return ``/var/run/user/$(id -u)/$appname/$version`` if
+         exists, otherwise ``/tmp/runtime-$(id -u)/$appname/$version``, if``$XDG_RUNTIME_DIR``
+         is not set.
+        """
+        path = os.environ.get("XDG_RUNTIME_DIR", "")
+        if not path.strip():
+            if sys.platform.startswith(("freebsd", "openbsd", "netbsd")):
+                path = f"/var/run/user/{getuid()}"
+                if not Path(path).exists():
+                    path = f"/tmp/runtime-{getuid()}"  # noqa: S108
+            else:
+                path = f"/run/user/{getuid()}"
+        return self._append_app_name_and_version(path)
+
+    @property
+    def site_runtime_dir(self) -> str:
+        """
+        :return: runtime directory shared by users, e.g. ``/run/$appname/$version`` or \
+        ``$XDG_RUNTIME_DIR/$appname/$version``.
+
+        Note that this behaves almost exactly like `user_runtime_dir` if ``$XDG_RUNTIME_DIR`` is set, but will
+        fall back to paths associated to the root user instead of a regular logged-in user if it's not set.
+
+        If you wish to ensure that a logged-in root user path is returned e.g. ``/run/user/0``, use `user_runtime_dir`
+        instead.
+
+        For FreeBSD/OpenBSD/NetBSD, it would return ``/var/run/$appname/$version`` if ``$XDG_RUNTIME_DIR`` is not set.
+        """
+        path = os.environ.get("XDG_RUNTIME_DIR", "")
+        if not path.strip():
+            if sys.platform.startswith(("freebsd", "openbsd", "netbsd")):
+                path = "/var/run"
+            else:
+                path = "/run"
+        return self._append_app_name_and_version(path)
+
+    @property
+    def site_data_path(self) -> Path:
+        """:return: data path shared by users. Only return the first item, even if ``multipath`` is set to ``True``"""
+        return self._first_item_as_path_if_multipath(self.site_data_dir)
+
+    @property
+    def site_config_path(self) -> Path:
+        """:return: config path shared by the users, returns the first item, even if ``multipath`` is set to ``True``"""
+        return self._first_item_as_path_if_multipath(self.site_config_dir)
+
+    @property
+    def site_cache_path(self) -> Path:
+        """:return: cache path shared by users. Only return the first item, even if ``multipath`` is set to ``True``"""
+        return self._first_item_as_path_if_multipath(self.site_cache_dir)
+
+    def _first_item_as_path_if_multipath(self, directory: str) -> Path:
+        if self.multipath:
+            # If multipath is True, the first path is returned.
+            directory = directory.split(os.pathsep)[0]
+        return Path(directory)
+
+    def iter_config_dirs(self) -> Iterator[str]:
+        """:yield: all user and site configuration directories."""
+        yield self.user_config_dir
+        yield from self._site_config_dirs
+
+    def iter_data_dirs(self) -> Iterator[str]:
+        """:yield: all user and site data directories."""
+        yield self.user_data_dir
+        yield from self._site_data_dirs
+
+
+def _get_user_media_dir(env_var: str, fallback_tilde_path: str) -> str:
+    media_dir = _get_user_dirs_folder(env_var)
+    if media_dir is None:
+        media_dir = os.environ.get(env_var, "").strip()
+        if not media_dir:
+            media_dir = os.path.expanduser(fallback_tilde_path)  # noqa: PTH111
+
+    return media_dir
+
+
+def _get_user_dirs_folder(key: str) -> str | None:
+    """
+    Return directory from user-dirs.dirs config file.
+
+    See https://freedesktop.org/wiki/Software/xdg-user-dirs/.
+
+    """
+    user_dirs_config_path = Path(Unix().user_config_dir) / "user-dirs.dirs"
+    if user_dirs_config_path.exists():
+        parser = ConfigParser()
+
+        with user_dirs_config_path.open() as stream:
+            # Add fake section header, so ConfigParser doesn't complain
+            parser.read_string(f"[top]\n{stream.read()}")
+
+        if key not in parser["top"]:
+            return None
+
+        path = parser["top"][key].strip('"')
+        # Handle relative home paths
+        return path.replace("$HOME", os.path.expanduser("~"))  # noqa: PTH111
+
+    return None
+
+
+__all__ = [
+    "Unix",
+]
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/version.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/version.py
new file mode 100644
index 0000000000000000000000000000000000000000..6483ddce0bcfbaa01a5b3dc3f8b864de20ef0683
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/version.py
@@ -0,0 +1,16 @@
+# file generated by setuptools_scm
+# don't change, don't track in version control
+TYPE_CHECKING = False
+if TYPE_CHECKING:
+    from typing import Tuple, Union
+    VERSION_TUPLE = Tuple[Union[int, str], ...]
+else:
+    VERSION_TUPLE = object
+
+version: str
+__version__: str
+__version_tuple__: VERSION_TUPLE
+version_tuple: VERSION_TUPLE
+
+__version__ = version = '4.2.2'
+__version_tuple__ = version_tuple = (4, 2, 2)
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/windows.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/windows.py
new file mode 100644
index 0000000000000000000000000000000000000000..d7bc96091a2b1cd078a0847519cb5dd50a5d8898
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/platformdirs/windows.py
@@ -0,0 +1,272 @@
+"""Windows."""
+
+from __future__ import annotations
+
+import os
+import sys
+from functools import lru_cache
+from typing import TYPE_CHECKING
+
+from .api import PlatformDirsABC
+
+if TYPE_CHECKING:
+    from collections.abc import Callable
+
+
+class Windows(PlatformDirsABC):
+    """
+    `MSDN on where to store app data files `_.
+
+    Makes use of the `appname `, `appauthor
+    `, `version `, `roaming
+    `, `opinion `, `ensure_exists
+    `.
+
+    """
+
+    @property
+    def user_data_dir(self) -> str:
+        """
+        :return: data directory tied to the user, e.g.
+         ``%USERPROFILE%\\AppData\\Local\\$appauthor\\$appname`` (not roaming) or
+         ``%USERPROFILE%\\AppData\\Roaming\\$appauthor\\$appname`` (roaming)
+        """
+        const = "CSIDL_APPDATA" if self.roaming else "CSIDL_LOCAL_APPDATA"
+        path = os.path.normpath(get_win_folder(const))
+        return self._append_parts(path)
+
+    def _append_parts(self, path: str, *, opinion_value: str | None = None) -> str:
+        params = []
+        if self.appname:
+            if self.appauthor is not False:
+                author = self.appauthor or self.appname
+                params.append(author)
+            params.append(self.appname)
+            if opinion_value is not None and self.opinion:
+                params.append(opinion_value)
+            if self.version:
+                params.append(self.version)
+        path = os.path.join(path, *params)  # noqa: PTH118
+        self._optionally_create_directory(path)
+        return path
+
+    @property
+    def site_data_dir(self) -> str:
+        """:return: data directory shared by users, e.g. ``C:\\ProgramData\\$appauthor\\$appname``"""
+        path = os.path.normpath(get_win_folder("CSIDL_COMMON_APPDATA"))
+        return self._append_parts(path)
+
+    @property
+    def user_config_dir(self) -> str:
+        """:return: config directory tied to the user, same as `user_data_dir`"""
+        return self.user_data_dir
+
+    @property
+    def site_config_dir(self) -> str:
+        """:return: config directory shared by the users, same as `site_data_dir`"""
+        return self.site_data_dir
+
+    @property
+    def user_cache_dir(self) -> str:
+        """
+        :return: cache directory tied to the user (if opinionated with ``Cache`` folder within ``$appname``) e.g.
+         ``%USERPROFILE%\\AppData\\Local\\$appauthor\\$appname\\Cache\\$version``
+        """
+        path = os.path.normpath(get_win_folder("CSIDL_LOCAL_APPDATA"))
+        return self._append_parts(path, opinion_value="Cache")
+
+    @property
+    def site_cache_dir(self) -> str:
+        """:return: cache directory shared by users, e.g. ``C:\\ProgramData\\$appauthor\\$appname\\Cache\\$version``"""
+        path = os.path.normpath(get_win_folder("CSIDL_COMMON_APPDATA"))
+        return self._append_parts(path, opinion_value="Cache")
+
+    @property
+    def user_state_dir(self) -> str:
+        """:return: state directory tied to the user, same as `user_data_dir`"""
+        return self.user_data_dir
+
+    @property
+    def user_log_dir(self) -> str:
+        """:return: log directory tied to the user, same as `user_data_dir` if not opinionated else ``Logs`` in it"""
+        path = self.user_data_dir
+        if self.opinion:
+            path = os.path.join(path, "Logs")  # noqa: PTH118
+            self._optionally_create_directory(path)
+        return path
+
+    @property
+    def user_documents_dir(self) -> str:
+        """:return: documents directory tied to the user e.g. ``%USERPROFILE%\\Documents``"""
+        return os.path.normpath(get_win_folder("CSIDL_PERSONAL"))
+
+    @property
+    def user_downloads_dir(self) -> str:
+        """:return: downloads directory tied to the user e.g. ``%USERPROFILE%\\Downloads``"""
+        return os.path.normpath(get_win_folder("CSIDL_DOWNLOADS"))
+
+    @property
+    def user_pictures_dir(self) -> str:
+        """:return: pictures directory tied to the user e.g. ``%USERPROFILE%\\Pictures``"""
+        return os.path.normpath(get_win_folder("CSIDL_MYPICTURES"))
+
+    @property
+    def user_videos_dir(self) -> str:
+        """:return: videos directory tied to the user e.g. ``%USERPROFILE%\\Videos``"""
+        return os.path.normpath(get_win_folder("CSIDL_MYVIDEO"))
+
+    @property
+    def user_music_dir(self) -> str:
+        """:return: music directory tied to the user e.g. ``%USERPROFILE%\\Music``"""
+        return os.path.normpath(get_win_folder("CSIDL_MYMUSIC"))
+
+    @property
+    def user_desktop_dir(self) -> str:
+        """:return: desktop directory tied to the user, e.g. ``%USERPROFILE%\\Desktop``"""
+        return os.path.normpath(get_win_folder("CSIDL_DESKTOPDIRECTORY"))
+
+    @property
+    def user_runtime_dir(self) -> str:
+        """
+        :return: runtime directory tied to the user, e.g.
+         ``%USERPROFILE%\\AppData\\Local\\Temp\\$appauthor\\$appname``
+        """
+        path = os.path.normpath(os.path.join(get_win_folder("CSIDL_LOCAL_APPDATA"), "Temp"))  # noqa: PTH118
+        return self._append_parts(path)
+
+    @property
+    def site_runtime_dir(self) -> str:
+        """:return: runtime directory shared by users, same as `user_runtime_dir`"""
+        return self.user_runtime_dir
+
+
+def get_win_folder_from_env_vars(csidl_name: str) -> str:
+    """Get folder from environment variables."""
+    result = get_win_folder_if_csidl_name_not_env_var(csidl_name)
+    if result is not None:
+        return result
+
+    env_var_name = {
+        "CSIDL_APPDATA": "APPDATA",
+        "CSIDL_COMMON_APPDATA": "ALLUSERSPROFILE",
+        "CSIDL_LOCAL_APPDATA": "LOCALAPPDATA",
+    }.get(csidl_name)
+    if env_var_name is None:
+        msg = f"Unknown CSIDL name: {csidl_name}"
+        raise ValueError(msg)
+    result = os.environ.get(env_var_name)
+    if result is None:
+        msg = f"Unset environment variable: {env_var_name}"
+        raise ValueError(msg)
+    return result
+
+
+def get_win_folder_if_csidl_name_not_env_var(csidl_name: str) -> str | None:
+    """Get a folder for a CSIDL name that does not exist as an environment variable."""
+    if csidl_name == "CSIDL_PERSONAL":
+        return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Documents")  # noqa: PTH118
+
+    if csidl_name == "CSIDL_DOWNLOADS":
+        return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Downloads")  # noqa: PTH118
+
+    if csidl_name == "CSIDL_MYPICTURES":
+        return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Pictures")  # noqa: PTH118
+
+    if csidl_name == "CSIDL_MYVIDEO":
+        return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Videos")  # noqa: PTH118
+
+    if csidl_name == "CSIDL_MYMUSIC":
+        return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Music")  # noqa: PTH118
+    return None
+
+
+def get_win_folder_from_registry(csidl_name: str) -> str:
+    """
+    Get folder from the registry.
+
+    This is a fallback technique at best. I'm not sure if using the registry for these guarantees us the correct answer
+    for all CSIDL_* names.
+
+    """
+    shell_folder_name = {
+        "CSIDL_APPDATA": "AppData",
+        "CSIDL_COMMON_APPDATA": "Common AppData",
+        "CSIDL_LOCAL_APPDATA": "Local AppData",
+        "CSIDL_PERSONAL": "Personal",
+        "CSIDL_DOWNLOADS": "{374DE290-123F-4565-9164-39C4925E467B}",
+        "CSIDL_MYPICTURES": "My Pictures",
+        "CSIDL_MYVIDEO": "My Video",
+        "CSIDL_MYMUSIC": "My Music",
+    }.get(csidl_name)
+    if shell_folder_name is None:
+        msg = f"Unknown CSIDL name: {csidl_name}"
+        raise ValueError(msg)
+    if sys.platform != "win32":  # only needed for mypy type checker to know that this code runs only on Windows
+        raise NotImplementedError
+    import winreg  # noqa: PLC0415
+
+    key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
+    directory, _ = winreg.QueryValueEx(key, shell_folder_name)
+    return str(directory)
+
+
+def get_win_folder_via_ctypes(csidl_name: str) -> str:
+    """Get folder with ctypes."""
+    # There is no 'CSIDL_DOWNLOADS'.
+    # Use 'CSIDL_PROFILE' (40) and append the default folder 'Downloads' instead.
+    # https://learn.microsoft.com/en-us/windows/win32/shell/knownfolderid
+
+    import ctypes  # noqa: PLC0415
+
+    csidl_const = {
+        "CSIDL_APPDATA": 26,
+        "CSIDL_COMMON_APPDATA": 35,
+        "CSIDL_LOCAL_APPDATA": 28,
+        "CSIDL_PERSONAL": 5,
+        "CSIDL_MYPICTURES": 39,
+        "CSIDL_MYVIDEO": 14,
+        "CSIDL_MYMUSIC": 13,
+        "CSIDL_DOWNLOADS": 40,
+        "CSIDL_DESKTOPDIRECTORY": 16,
+    }.get(csidl_name)
+    if csidl_const is None:
+        msg = f"Unknown CSIDL name: {csidl_name}"
+        raise ValueError(msg)
+
+    buf = ctypes.create_unicode_buffer(1024)
+    windll = getattr(ctypes, "windll")  # noqa: B009 # using getattr to avoid false positive with mypy type checker
+    windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf)
+
+    # Downgrade to short path name if it has high-bit chars.
+    if any(ord(c) > 255 for c in buf):  # noqa: PLR2004
+        buf2 = ctypes.create_unicode_buffer(1024)
+        if windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024):
+            buf = buf2
+
+    if csidl_name == "CSIDL_DOWNLOADS":
+        return os.path.join(buf.value, "Downloads")  # noqa: PTH118
+
+    return buf.value
+
+
+def _pick_get_win_folder() -> Callable[[str], str]:
+    try:
+        import ctypes  # noqa: PLC0415
+    except ImportError:
+        pass
+    else:
+        if hasattr(ctypes, "windll"):
+            return get_win_folder_via_ctypes
+    try:
+        import winreg  # noqa: PLC0415, F401
+    except ImportError:
+        return get_win_folder_from_env_vars
+    else:
+        return get_win_folder_from_registry
+
+
+get_win_folder = lru_cache(maxsize=None)(_pick_get_win_folder())
+
+__all__ = [
+    "Windows",
+]
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli-2.0.1.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli-2.0.1.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli-2.0.1.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli-2.0.1.dist-info/LICENSE b/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli-2.0.1.dist-info/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..e859590f886cd78344206af1a8ccb3080d4385e0
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli-2.0.1.dist-info/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2021 Taneli Hukkinen
+
+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.12/site-packages/setuptools/_vendor/tomli-2.0.1.dist-info/METADATA b/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli-2.0.1.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..efd87ecc1659a43c0a6e37bdc77954f352172acc
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli-2.0.1.dist-info/METADATA
@@ -0,0 +1,206 @@
+Metadata-Version: 2.1
+Name: tomli
+Version: 2.0.1
+Summary: A lil' TOML parser
+Keywords: toml
+Author-email: Taneli Hukkinen 
+Requires-Python: >=3.7
+Description-Content-Type: text/markdown
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Operating System :: MacOS
+Classifier: Operating System :: Microsoft :: Windows
+Classifier: Operating System :: POSIX :: Linux
+Classifier: Programming Language :: Python :: 3 :: Only
+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 :: Implementation :: CPython
+Classifier: Programming Language :: Python :: Implementation :: PyPy
+Classifier: Topic :: Software Development :: Libraries :: Python Modules
+Classifier: Typing :: Typed
+Project-URL: Changelog, https://github.com/hukkin/tomli/blob/master/CHANGELOG.md
+Project-URL: Homepage, https://github.com/hukkin/tomli
+
+[![Build Status](https://github.com/hukkin/tomli/workflows/Tests/badge.svg?branch=master)](https://github.com/hukkin/tomli/actions?query=workflow%3ATests+branch%3Amaster+event%3Apush)
+[![codecov.io](https://codecov.io/gh/hukkin/tomli/branch/master/graph/badge.svg)](https://codecov.io/gh/hukkin/tomli)
+[![PyPI version](https://img.shields.io/pypi/v/tomli)](https://pypi.org/project/tomli)
+
+# Tomli
+
+> A lil' TOML parser
+
+**Table of Contents**  *generated with [mdformat-toc](https://github.com/hukkin/mdformat-toc)*
+
+
+
+- [Intro](#intro)
+- [Installation](#installation)
+- [Usage](#usage)
+  - [Parse a TOML string](#parse-a-toml-string)
+  - [Parse a TOML file](#parse-a-toml-file)
+  - [Handle invalid TOML](#handle-invalid-toml)
+  - [Construct `decimal.Decimal`s from TOML floats](#construct-decimaldecimals-from-toml-floats)
+- [FAQ](#faq)
+  - [Why this parser?](#why-this-parser)
+  - [Is comment preserving round-trip parsing supported?](#is-comment-preserving-round-trip-parsing-supported)
+  - [Is there a `dumps`, `write` or `encode` function?](#is-there-a-dumps-write-or-encode-function)
+  - [How do TOML types map into Python types?](#how-do-toml-types-map-into-python-types)
+- [Performance](#performance)
+
+
+
+## Intro
+
+Tomli is a Python library for parsing [TOML](https://toml.io).
+Tomli is fully compatible with [TOML v1.0.0](https://toml.io/en/v1.0.0).
+
+## Installation
+
+```bash
+pip install tomli
+```
+
+## Usage
+
+### Parse a TOML string
+
+```python
+import tomli
+
+toml_str = """
+           gretzky = 99
+
+           [kurri]
+           jari = 17
+           """
+
+toml_dict = tomli.loads(toml_str)
+assert toml_dict == {"gretzky": 99, "kurri": {"jari": 17}}
+```
+
+### Parse a TOML file
+
+```python
+import tomli
+
+with open("path_to_file/conf.toml", "rb") as f:
+    toml_dict = tomli.load(f)
+```
+
+The file must be opened in binary mode (with the `"rb"` flag).
+Binary mode will enforce decoding the file as UTF-8 with universal newlines disabled,
+both of which are required to correctly parse TOML.
+
+### Handle invalid TOML
+
+```python
+import tomli
+
+try:
+    toml_dict = tomli.loads("]] this is invalid TOML [[")
+except tomli.TOMLDecodeError:
+    print("Yep, definitely not valid.")
+```
+
+Note that error messages are considered informational only.
+They should not be assumed to stay constant across Tomli versions.
+
+### Construct `decimal.Decimal`s from TOML floats
+
+```python
+from decimal import Decimal
+import tomli
+
+toml_dict = tomli.loads("precision-matters = 0.982492", parse_float=Decimal)
+assert toml_dict["precision-matters"] == Decimal("0.982492")
+```
+
+Note that `decimal.Decimal` can be replaced with another callable that converts a TOML float from string to a Python type.
+The `decimal.Decimal` is, however, a practical choice for use cases where float inaccuracies can not be tolerated.
+
+Illegal types are `dict` and `list`, and their subtypes.
+A `ValueError` will be raised if `parse_float` produces illegal types.
+
+## FAQ
+
+### Why this parser?
+
+- it's lil'
+- pure Python with zero dependencies
+- the fastest pure Python parser [\*](#performance):
+  15x as fast as [tomlkit](https://pypi.org/project/tomlkit/),
+  2.4x as fast as [toml](https://pypi.org/project/toml/)
+- outputs [basic data types](#how-do-toml-types-map-into-python-types) only
+- 100% spec compliant: passes all tests in
+  [a test set](https://github.com/toml-lang/compliance/pull/8)
+  soon to be merged to the official
+  [compliance tests for TOML](https://github.com/toml-lang/compliance)
+  repository
+- thoroughly tested: 100% branch coverage
+
+### Is comment preserving round-trip parsing supported?
+
+No.
+
+The `tomli.loads` function returns a plain `dict` that is populated with builtin types and types from the standard library only.
+Preserving comments requires a custom type to be returned so will not be supported,
+at least not by the `tomli.loads` and `tomli.load` functions.
+
+Look into [TOML Kit](https://github.com/sdispater/tomlkit) if preservation of style is what you need.
+
+### Is there a `dumps`, `write` or `encode` function?
+
+[Tomli-W](https://github.com/hukkin/tomli-w) is the write-only counterpart of Tomli, providing `dump` and `dumps` functions.
+
+The core library does not include write capability, as most TOML use cases are read-only, and Tomli intends to be minimal.
+
+### How do TOML types map into Python types?
+
+| TOML type        | Python type         | Details                                                      |
+| ---------------- | ------------------- | ------------------------------------------------------------ |
+| Document Root    | `dict`              |                                                              |
+| Key              | `str`               |                                                              |
+| String           | `str`               |                                                              |
+| Integer          | `int`               |                                                              |
+| Float            | `float`             |                                                              |
+| Boolean          | `bool`              |                                                              |
+| Offset Date-Time | `datetime.datetime` | `tzinfo` attribute set to an instance of `datetime.timezone` |
+| Local Date-Time  | `datetime.datetime` | `tzinfo` attribute set to `None`                             |
+| Local Date       | `datetime.date`     |                                                              |
+| Local Time       | `datetime.time`     |                                                              |
+| Array            | `list`              |                                                              |
+| Table            | `dict`              |                                                              |
+| Inline Table     | `dict`              |                                                              |
+
+## Performance
+
+The `benchmark/` folder in this repository contains a performance benchmark for comparing the various Python TOML parsers.
+The benchmark can be run with `tox -e benchmark-pypi`.
+Running the benchmark on my personal computer output the following:
+
+```console
+foo@bar:~/dev/tomli$ tox -e benchmark-pypi
+benchmark-pypi installed: attrs==19.3.0,click==7.1.2,pytomlpp==1.0.2,qtoml==0.3.0,rtoml==0.7.0,toml==0.10.2,tomli==1.1.0,tomlkit==0.7.2
+benchmark-pypi run-test-pre: PYTHONHASHSEED='2658546909'
+benchmark-pypi run-test: commands[0] | python -c 'import datetime; print(datetime.date.today())'
+2021-07-23
+benchmark-pypi run-test: commands[1] | python --version
+Python 3.8.10
+benchmark-pypi run-test: commands[2] | python benchmark/run.py
+Parsing data.toml 5000 times:
+------------------------------------------------------
+    parser |  exec time | performance (more is better)
+-----------+------------+-----------------------------
+     rtoml |    0.901 s | baseline (100%)
+  pytomlpp |     1.08 s | 83.15%
+     tomli |     3.89 s | 23.15%
+      toml |     9.36 s | 9.63%
+     qtoml |     11.5 s | 7.82%
+   tomlkit |     56.8 s | 1.59%
+```
+
+The parsers are ordered from fastest to slowest, using the fastest parser as baseline.
+Tomli performed the best out of all pure Python TOML parsers,
+losing only to pytomlpp (wraps C++) and rtoml (wraps Rust).
+
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli-2.0.1.dist-info/RECORD b/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli-2.0.1.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..1db8063ec5c3ba925e681030347e8d396eb934be
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli-2.0.1.dist-info/RECORD
@@ -0,0 +1,15 @@
+tomli-2.0.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+tomli-2.0.1.dist-info/LICENSE,sha256=uAgWsNUwuKzLTCIReDeQmEpuO2GSLCte6S8zcqsnQv4,1072
+tomli-2.0.1.dist-info/METADATA,sha256=zPDceKmPwJGLWtZykrHixL7WVXWmJGzZ1jyRT5lCoPI,8875
+tomli-2.0.1.dist-info/RECORD,,
+tomli-2.0.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+tomli-2.0.1.dist-info/WHEEL,sha256=jPMR_Dzkc4X4icQtmz81lnNY_kAsfog7ry7qoRvYLXw,81
+tomli/__init__.py,sha256=JhUwV66DB1g4Hvt1UQCVMdfCu-IgAV8FXmvDU9onxd4,396
+tomli/__pycache__/__init__.cpython-312.pyc,,
+tomli/__pycache__/_parser.cpython-312.pyc,,
+tomli/__pycache__/_re.cpython-312.pyc,,
+tomli/__pycache__/_types.cpython-312.pyc,,
+tomli/_parser.py,sha256=g9-ENaALS-B8dokYpCuzUFalWlog7T-SIYMjLZSWrtM,22633
+tomli/_re.py,sha256=dbjg5ChZT23Ka9z9DHOXfdtSpPwUfdgMXnj8NOoly-w,2943
+tomli/_types.py,sha256=-GTG2VUqkpxwMqzmVO4F7ybKddIbAnuAHXfmWQcTi3Q,254
+tomli/py.typed,sha256=8PjyZ1aVoQpRVvt71muvuq5qE-jTFZkK-GLHkhdebmc,26
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli-2.0.1.dist-info/REQUESTED b/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli-2.0.1.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli-2.0.1.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli-2.0.1.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..c727d148239a36b0e8de2b97fdb23fb96da78869
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli-2.0.1.dist-info/WHEEL
@@ -0,0 +1,4 @@
+Wheel-Version: 1.0
+Generator: flit 3.6.0
+Root-Is-Purelib: true
+Tag: py3-none-any
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli/__init__.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4c6ec97ec6961bcf184b6e0b2437b9924db0b9de
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli/__init__.py
@@ -0,0 +1,11 @@
+# SPDX-License-Identifier: MIT
+# SPDX-FileCopyrightText: 2021 Taneli Hukkinen
+# Licensed to PSF under a Contributor Agreement.
+
+__all__ = ("loads", "load", "TOMLDecodeError")
+__version__ = "2.0.1"  # DO NOT EDIT THIS LINE MANUALLY. LET bump2version UTILITY DO IT
+
+from ._parser import TOMLDecodeError, load, loads
+
+# Pretend this exception was created here.
+TOMLDecodeError.__module__ = __name__
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e41de273cc93419b65d7b442320d7f0215a2e987
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli/__pycache__/_parser.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli/__pycache__/_parser.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..378467fcbdcbeb39871528afa1e34a3ae0d2a085
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli/__pycache__/_parser.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli/__pycache__/_re.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli/__pycache__/_re.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..25dec0adf5c134c57b2ea90914835e6f336ade15
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli/__pycache__/_re.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli/__pycache__/_types.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli/__pycache__/_types.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..59009a77cae4b8996e70e2c49fc833554a0c5d17
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli/__pycache__/_types.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli/_parser.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli/_parser.py
new file mode 100644
index 0000000000000000000000000000000000000000..f1bb0aa19a556725aa2ae2b8cea95489c99a9078
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli/_parser.py
@@ -0,0 +1,691 @@
+# SPDX-License-Identifier: MIT
+# SPDX-FileCopyrightText: 2021 Taneli Hukkinen
+# Licensed to PSF under a Contributor Agreement.
+
+from __future__ import annotations
+
+from collections.abc import Iterable
+import string
+from types import MappingProxyType
+from typing import Any, BinaryIO, NamedTuple
+
+from ._re import (
+    RE_DATETIME,
+    RE_LOCALTIME,
+    RE_NUMBER,
+    match_to_datetime,
+    match_to_localtime,
+    match_to_number,
+)
+from ._types import Key, ParseFloat, Pos
+
+ASCII_CTRL = frozenset(chr(i) for i in range(32)) | frozenset(chr(127))
+
+# Neither of these sets include quotation mark or backslash. They are
+# currently handled as separate cases in the parser functions.
+ILLEGAL_BASIC_STR_CHARS = ASCII_CTRL - frozenset("\t")
+ILLEGAL_MULTILINE_BASIC_STR_CHARS = ASCII_CTRL - frozenset("\t\n")
+
+ILLEGAL_LITERAL_STR_CHARS = ILLEGAL_BASIC_STR_CHARS
+ILLEGAL_MULTILINE_LITERAL_STR_CHARS = ILLEGAL_MULTILINE_BASIC_STR_CHARS
+
+ILLEGAL_COMMENT_CHARS = ILLEGAL_BASIC_STR_CHARS
+
+TOML_WS = frozenset(" \t")
+TOML_WS_AND_NEWLINE = TOML_WS | frozenset("\n")
+BARE_KEY_CHARS = frozenset(string.ascii_letters + string.digits + "-_")
+KEY_INITIAL_CHARS = BARE_KEY_CHARS | frozenset("\"'")
+HEXDIGIT_CHARS = frozenset(string.hexdigits)
+
+BASIC_STR_ESCAPE_REPLACEMENTS = MappingProxyType(
+    {
+        "\\b": "\u0008",  # backspace
+        "\\t": "\u0009",  # tab
+        "\\n": "\u000A",  # linefeed
+        "\\f": "\u000C",  # form feed
+        "\\r": "\u000D",  # carriage return
+        '\\"': "\u0022",  # quote
+        "\\\\": "\u005C",  # backslash
+    }
+)
+
+
+class TOMLDecodeError(ValueError):
+    """An error raised if a document is not valid TOML."""
+
+
+def load(__fp: BinaryIO, *, parse_float: ParseFloat = float) -> dict[str, Any]:
+    """Parse TOML from a binary file object."""
+    b = __fp.read()
+    try:
+        s = b.decode()
+    except AttributeError:
+        raise TypeError(
+            "File must be opened in binary mode, e.g. use `open('foo.toml', 'rb')`"
+        ) from None
+    return loads(s, parse_float=parse_float)
+
+
+def loads(__s: str, *, parse_float: ParseFloat = float) -> dict[str, Any]:  # noqa: C901
+    """Parse TOML from a string."""
+
+    # The spec allows converting "\r\n" to "\n", even in string
+    # literals. Let's do so to simplify parsing.
+    src = __s.replace("\r\n", "\n")
+    pos = 0
+    out = Output(NestedDict(), Flags())
+    header: Key = ()
+    parse_float = make_safe_parse_float(parse_float)
+
+    # Parse one statement at a time
+    # (typically means one line in TOML source)
+    while True:
+        # 1. Skip line leading whitespace
+        pos = skip_chars(src, pos, TOML_WS)
+
+        # 2. Parse rules. Expect one of the following:
+        #    - end of file
+        #    - end of line
+        #    - comment
+        #    - key/value pair
+        #    - append dict to list (and move to its namespace)
+        #    - create dict (and move to its namespace)
+        # Skip trailing whitespace when applicable.
+        try:
+            char = src[pos]
+        except IndexError:
+            break
+        if char == "\n":
+            pos += 1
+            continue
+        if char in KEY_INITIAL_CHARS:
+            pos = key_value_rule(src, pos, out, header, parse_float)
+            pos = skip_chars(src, pos, TOML_WS)
+        elif char == "[":
+            try:
+                second_char: str | None = src[pos + 1]
+            except IndexError:
+                second_char = None
+            out.flags.finalize_pending()
+            if second_char == "[":
+                pos, header = create_list_rule(src, pos, out)
+            else:
+                pos, header = create_dict_rule(src, pos, out)
+            pos = skip_chars(src, pos, TOML_WS)
+        elif char != "#":
+            raise suffixed_err(src, pos, "Invalid statement")
+
+        # 3. Skip comment
+        pos = skip_comment(src, pos)
+
+        # 4. Expect end of line or end of file
+        try:
+            char = src[pos]
+        except IndexError:
+            break
+        if char != "\n":
+            raise suffixed_err(
+                src, pos, "Expected newline or end of document after a statement"
+            )
+        pos += 1
+
+    return out.data.dict
+
+
+class Flags:
+    """Flags that map to parsed keys/namespaces."""
+
+    # Marks an immutable namespace (inline array or inline table).
+    FROZEN = 0
+    # Marks a nest that has been explicitly created and can no longer
+    # be opened using the "[table]" syntax.
+    EXPLICIT_NEST = 1
+
+    def __init__(self) -> None:
+        self._flags: dict[str, dict] = {}
+        self._pending_flags: set[tuple[Key, int]] = set()
+
+    def add_pending(self, key: Key, flag: int) -> None:
+        self._pending_flags.add((key, flag))
+
+    def finalize_pending(self) -> None:
+        for key, flag in self._pending_flags:
+            self.set(key, flag, recursive=False)
+        self._pending_flags.clear()
+
+    def unset_all(self, key: Key) -> None:
+        cont = self._flags
+        for k in key[:-1]:
+            if k not in cont:
+                return
+            cont = cont[k]["nested"]
+        cont.pop(key[-1], None)
+
+    def set(self, key: Key, flag: int, *, recursive: bool) -> None:  # noqa: A003
+        cont = self._flags
+        key_parent, key_stem = key[:-1], key[-1]
+        for k in key_parent:
+            if k not in cont:
+                cont[k] = {"flags": set(), "recursive_flags": set(), "nested": {}}
+            cont = cont[k]["nested"]
+        if key_stem not in cont:
+            cont[key_stem] = {"flags": set(), "recursive_flags": set(), "nested": {}}
+        cont[key_stem]["recursive_flags" if recursive else "flags"].add(flag)
+
+    def is_(self, key: Key, flag: int) -> bool:
+        if not key:
+            return False  # document root has no flags
+        cont = self._flags
+        for k in key[:-1]:
+            if k not in cont:
+                return False
+            inner_cont = cont[k]
+            if flag in inner_cont["recursive_flags"]:
+                return True
+            cont = inner_cont["nested"]
+        key_stem = key[-1]
+        if key_stem in cont:
+            cont = cont[key_stem]
+            return flag in cont["flags"] or flag in cont["recursive_flags"]
+        return False
+
+
+class NestedDict:
+    def __init__(self) -> None:
+        # The parsed content of the TOML document
+        self.dict: dict[str, Any] = {}
+
+    def get_or_create_nest(
+        self,
+        key: Key,
+        *,
+        access_lists: bool = True,
+    ) -> dict:
+        cont: Any = self.dict
+        for k in key:
+            if k not in cont:
+                cont[k] = {}
+            cont = cont[k]
+            if access_lists and isinstance(cont, list):
+                cont = cont[-1]
+            if not isinstance(cont, dict):
+                raise KeyError("There is no nest behind this key")
+        return cont
+
+    def append_nest_to_list(self, key: Key) -> None:
+        cont = self.get_or_create_nest(key[:-1])
+        last_key = key[-1]
+        if last_key in cont:
+            list_ = cont[last_key]
+            if not isinstance(list_, list):
+                raise KeyError("An object other than list found behind this key")
+            list_.append({})
+        else:
+            cont[last_key] = [{}]
+
+
+class Output(NamedTuple):
+    data: NestedDict
+    flags: Flags
+
+
+def skip_chars(src: str, pos: Pos, chars: Iterable[str]) -> Pos:
+    try:
+        while src[pos] in chars:
+            pos += 1
+    except IndexError:
+        pass
+    return pos
+
+
+def skip_until(
+    src: str,
+    pos: Pos,
+    expect: str,
+    *,
+    error_on: frozenset[str],
+    error_on_eof: bool,
+) -> Pos:
+    try:
+        new_pos = src.index(expect, pos)
+    except ValueError:
+        new_pos = len(src)
+        if error_on_eof:
+            raise suffixed_err(src, new_pos, f"Expected {expect!r}") from None
+
+    if not error_on.isdisjoint(src[pos:new_pos]):
+        while src[pos] not in error_on:
+            pos += 1
+        raise suffixed_err(src, pos, f"Found invalid character {src[pos]!r}")
+    return new_pos
+
+
+def skip_comment(src: str, pos: Pos) -> Pos:
+    try:
+        char: str | None = src[pos]
+    except IndexError:
+        char = None
+    if char == "#":
+        return skip_until(
+            src, pos + 1, "\n", error_on=ILLEGAL_COMMENT_CHARS, error_on_eof=False
+        )
+    return pos
+
+
+def skip_comments_and_array_ws(src: str, pos: Pos) -> Pos:
+    while True:
+        pos_before_skip = pos
+        pos = skip_chars(src, pos, TOML_WS_AND_NEWLINE)
+        pos = skip_comment(src, pos)
+        if pos == pos_before_skip:
+            return pos
+
+
+def create_dict_rule(src: str, pos: Pos, out: Output) -> tuple[Pos, Key]:
+    pos += 1  # Skip "["
+    pos = skip_chars(src, pos, TOML_WS)
+    pos, key = parse_key(src, pos)
+
+    if out.flags.is_(key, Flags.EXPLICIT_NEST) or out.flags.is_(key, Flags.FROZEN):
+        raise suffixed_err(src, pos, f"Cannot declare {key} twice")
+    out.flags.set(key, Flags.EXPLICIT_NEST, recursive=False)
+    try:
+        out.data.get_or_create_nest(key)
+    except KeyError:
+        raise suffixed_err(src, pos, "Cannot overwrite a value") from None
+
+    if not src.startswith("]", pos):
+        raise suffixed_err(src, pos, "Expected ']' at the end of a table declaration")
+    return pos + 1, key
+
+
+def create_list_rule(src: str, pos: Pos, out: Output) -> tuple[Pos, Key]:
+    pos += 2  # Skip "[["
+    pos = skip_chars(src, pos, TOML_WS)
+    pos, key = parse_key(src, pos)
+
+    if out.flags.is_(key, Flags.FROZEN):
+        raise suffixed_err(src, pos, f"Cannot mutate immutable namespace {key}")
+    # Free the namespace now that it points to another empty list item...
+    out.flags.unset_all(key)
+    # ...but this key precisely is still prohibited from table declaration
+    out.flags.set(key, Flags.EXPLICIT_NEST, recursive=False)
+    try:
+        out.data.append_nest_to_list(key)
+    except KeyError:
+        raise suffixed_err(src, pos, "Cannot overwrite a value") from None
+
+    if not src.startswith("]]", pos):
+        raise suffixed_err(src, pos, "Expected ']]' at the end of an array declaration")
+    return pos + 2, key
+
+
+def key_value_rule(
+    src: str, pos: Pos, out: Output, header: Key, parse_float: ParseFloat
+) -> Pos:
+    pos, key, value = parse_key_value_pair(src, pos, parse_float)
+    key_parent, key_stem = key[:-1], key[-1]
+    abs_key_parent = header + key_parent
+
+    relative_path_cont_keys = (header + key[:i] for i in range(1, len(key)))
+    for cont_key in relative_path_cont_keys:
+        # Check that dotted key syntax does not redefine an existing table
+        if out.flags.is_(cont_key, Flags.EXPLICIT_NEST):
+            raise suffixed_err(src, pos, f"Cannot redefine namespace {cont_key}")
+        # Containers in the relative path can't be opened with the table syntax or
+        # dotted key/value syntax in following table sections.
+        out.flags.add_pending(cont_key, Flags.EXPLICIT_NEST)
+
+    if out.flags.is_(abs_key_parent, Flags.FROZEN):
+        raise suffixed_err(
+            src, pos, f"Cannot mutate immutable namespace {abs_key_parent}"
+        )
+
+    try:
+        nest = out.data.get_or_create_nest(abs_key_parent)
+    except KeyError:
+        raise suffixed_err(src, pos, "Cannot overwrite a value") from None
+    if key_stem in nest:
+        raise suffixed_err(src, pos, "Cannot overwrite a value")
+    # Mark inline table and array namespaces recursively immutable
+    if isinstance(value, (dict, list)):
+        out.flags.set(header + key, Flags.FROZEN, recursive=True)
+    nest[key_stem] = value
+    return pos
+
+
+def parse_key_value_pair(
+    src: str, pos: Pos, parse_float: ParseFloat
+) -> tuple[Pos, Key, Any]:
+    pos, key = parse_key(src, pos)
+    try:
+        char: str | None = src[pos]
+    except IndexError:
+        char = None
+    if char != "=":
+        raise suffixed_err(src, pos, "Expected '=' after a key in a key/value pair")
+    pos += 1
+    pos = skip_chars(src, pos, TOML_WS)
+    pos, value = parse_value(src, pos, parse_float)
+    return pos, key, value
+
+
+def parse_key(src: str, pos: Pos) -> tuple[Pos, Key]:
+    pos, key_part = parse_key_part(src, pos)
+    key: Key = (key_part,)
+    pos = skip_chars(src, pos, TOML_WS)
+    while True:
+        try:
+            char: str | None = src[pos]
+        except IndexError:
+            char = None
+        if char != ".":
+            return pos, key
+        pos += 1
+        pos = skip_chars(src, pos, TOML_WS)
+        pos, key_part = parse_key_part(src, pos)
+        key += (key_part,)
+        pos = skip_chars(src, pos, TOML_WS)
+
+
+def parse_key_part(src: str, pos: Pos) -> tuple[Pos, str]:
+    try:
+        char: str | None = src[pos]
+    except IndexError:
+        char = None
+    if char in BARE_KEY_CHARS:
+        start_pos = pos
+        pos = skip_chars(src, pos, BARE_KEY_CHARS)
+        return pos, src[start_pos:pos]
+    if char == "'":
+        return parse_literal_str(src, pos)
+    if char == '"':
+        return parse_one_line_basic_str(src, pos)
+    raise suffixed_err(src, pos, "Invalid initial character for a key part")
+
+
+def parse_one_line_basic_str(src: str, pos: Pos) -> tuple[Pos, str]:
+    pos += 1
+    return parse_basic_str(src, pos, multiline=False)
+
+
+def parse_array(src: str, pos: Pos, parse_float: ParseFloat) -> tuple[Pos, list]:
+    pos += 1
+    array: list = []
+
+    pos = skip_comments_and_array_ws(src, pos)
+    if src.startswith("]", pos):
+        return pos + 1, array
+    while True:
+        pos, val = parse_value(src, pos, parse_float)
+        array.append(val)
+        pos = skip_comments_and_array_ws(src, pos)
+
+        c = src[pos : pos + 1]
+        if c == "]":
+            return pos + 1, array
+        if c != ",":
+            raise suffixed_err(src, pos, "Unclosed array")
+        pos += 1
+
+        pos = skip_comments_and_array_ws(src, pos)
+        if src.startswith("]", pos):
+            return pos + 1, array
+
+
+def parse_inline_table(src: str, pos: Pos, parse_float: ParseFloat) -> tuple[Pos, dict]:
+    pos += 1
+    nested_dict = NestedDict()
+    flags = Flags()
+
+    pos = skip_chars(src, pos, TOML_WS)
+    if src.startswith("}", pos):
+        return pos + 1, nested_dict.dict
+    while True:
+        pos, key, value = parse_key_value_pair(src, pos, parse_float)
+        key_parent, key_stem = key[:-1], key[-1]
+        if flags.is_(key, Flags.FROZEN):
+            raise suffixed_err(src, pos, f"Cannot mutate immutable namespace {key}")
+        try:
+            nest = nested_dict.get_or_create_nest(key_parent, access_lists=False)
+        except KeyError:
+            raise suffixed_err(src, pos, "Cannot overwrite a value") from None
+        if key_stem in nest:
+            raise suffixed_err(src, pos, f"Duplicate inline table key {key_stem!r}")
+        nest[key_stem] = value
+        pos = skip_chars(src, pos, TOML_WS)
+        c = src[pos : pos + 1]
+        if c == "}":
+            return pos + 1, nested_dict.dict
+        if c != ",":
+            raise suffixed_err(src, pos, "Unclosed inline table")
+        if isinstance(value, (dict, list)):
+            flags.set(key, Flags.FROZEN, recursive=True)
+        pos += 1
+        pos = skip_chars(src, pos, TOML_WS)
+
+
+def parse_basic_str_escape(
+    src: str, pos: Pos, *, multiline: bool = False
+) -> tuple[Pos, str]:
+    escape_id = src[pos : pos + 2]
+    pos += 2
+    if multiline and escape_id in {"\\ ", "\\\t", "\\\n"}:
+        # Skip whitespace until next non-whitespace character or end of
+        # the doc. Error if non-whitespace is found before newline.
+        if escape_id != "\\\n":
+            pos = skip_chars(src, pos, TOML_WS)
+            try:
+                char = src[pos]
+            except IndexError:
+                return pos, ""
+            if char != "\n":
+                raise suffixed_err(src, pos, "Unescaped '\\' in a string")
+            pos += 1
+        pos = skip_chars(src, pos, TOML_WS_AND_NEWLINE)
+        return pos, ""
+    if escape_id == "\\u":
+        return parse_hex_char(src, pos, 4)
+    if escape_id == "\\U":
+        return parse_hex_char(src, pos, 8)
+    try:
+        return pos, BASIC_STR_ESCAPE_REPLACEMENTS[escape_id]
+    except KeyError:
+        raise suffixed_err(src, pos, "Unescaped '\\' in a string") from None
+
+
+def parse_basic_str_escape_multiline(src: str, pos: Pos) -> tuple[Pos, str]:
+    return parse_basic_str_escape(src, pos, multiline=True)
+
+
+def parse_hex_char(src: str, pos: Pos, hex_len: int) -> tuple[Pos, str]:
+    hex_str = src[pos : pos + hex_len]
+    if len(hex_str) != hex_len or not HEXDIGIT_CHARS.issuperset(hex_str):
+        raise suffixed_err(src, pos, "Invalid hex value")
+    pos += hex_len
+    hex_int = int(hex_str, 16)
+    if not is_unicode_scalar_value(hex_int):
+        raise suffixed_err(src, pos, "Escaped character is not a Unicode scalar value")
+    return pos, chr(hex_int)
+
+
+def parse_literal_str(src: str, pos: Pos) -> tuple[Pos, str]:
+    pos += 1  # Skip starting apostrophe
+    start_pos = pos
+    pos = skip_until(
+        src, pos, "'", error_on=ILLEGAL_LITERAL_STR_CHARS, error_on_eof=True
+    )
+    return pos + 1, src[start_pos:pos]  # Skip ending apostrophe
+
+
+def parse_multiline_str(src: str, pos: Pos, *, literal: bool) -> tuple[Pos, str]:
+    pos += 3
+    if src.startswith("\n", pos):
+        pos += 1
+
+    if literal:
+        delim = "'"
+        end_pos = skip_until(
+            src,
+            pos,
+            "'''",
+            error_on=ILLEGAL_MULTILINE_LITERAL_STR_CHARS,
+            error_on_eof=True,
+        )
+        result = src[pos:end_pos]
+        pos = end_pos + 3
+    else:
+        delim = '"'
+        pos, result = parse_basic_str(src, pos, multiline=True)
+
+    # Add at maximum two extra apostrophes/quotes if the end sequence
+    # is 4 or 5 chars long instead of just 3.
+    if not src.startswith(delim, pos):
+        return pos, result
+    pos += 1
+    if not src.startswith(delim, pos):
+        return pos, result + delim
+    pos += 1
+    return pos, result + (delim * 2)
+
+
+def parse_basic_str(src: str, pos: Pos, *, multiline: bool) -> tuple[Pos, str]:
+    if multiline:
+        error_on = ILLEGAL_MULTILINE_BASIC_STR_CHARS
+        parse_escapes = parse_basic_str_escape_multiline
+    else:
+        error_on = ILLEGAL_BASIC_STR_CHARS
+        parse_escapes = parse_basic_str_escape
+    result = ""
+    start_pos = pos
+    while True:
+        try:
+            char = src[pos]
+        except IndexError:
+            raise suffixed_err(src, pos, "Unterminated string") from None
+        if char == '"':
+            if not multiline:
+                return pos + 1, result + src[start_pos:pos]
+            if src.startswith('"""', pos):
+                return pos + 3, result + src[start_pos:pos]
+            pos += 1
+            continue
+        if char == "\\":
+            result += src[start_pos:pos]
+            pos, parsed_escape = parse_escapes(src, pos)
+            result += parsed_escape
+            start_pos = pos
+            continue
+        if char in error_on:
+            raise suffixed_err(src, pos, f"Illegal character {char!r}")
+        pos += 1
+
+
+def parse_value(  # noqa: C901
+    src: str, pos: Pos, parse_float: ParseFloat
+) -> tuple[Pos, Any]:
+    try:
+        char: str | None = src[pos]
+    except IndexError:
+        char = None
+
+    # IMPORTANT: order conditions based on speed of checking and likelihood
+
+    # Basic strings
+    if char == '"':
+        if src.startswith('"""', pos):
+            return parse_multiline_str(src, pos, literal=False)
+        return parse_one_line_basic_str(src, pos)
+
+    # Literal strings
+    if char == "'":
+        if src.startswith("'''", pos):
+            return parse_multiline_str(src, pos, literal=True)
+        return parse_literal_str(src, pos)
+
+    # Booleans
+    if char == "t":
+        if src.startswith("true", pos):
+            return pos + 4, True
+    if char == "f":
+        if src.startswith("false", pos):
+            return pos + 5, False
+
+    # Arrays
+    if char == "[":
+        return parse_array(src, pos, parse_float)
+
+    # Inline tables
+    if char == "{":
+        return parse_inline_table(src, pos, parse_float)
+
+    # Dates and times
+    datetime_match = RE_DATETIME.match(src, pos)
+    if datetime_match:
+        try:
+            datetime_obj = match_to_datetime(datetime_match)
+        except ValueError as e:
+            raise suffixed_err(src, pos, "Invalid date or datetime") from e
+        return datetime_match.end(), datetime_obj
+    localtime_match = RE_LOCALTIME.match(src, pos)
+    if localtime_match:
+        return localtime_match.end(), match_to_localtime(localtime_match)
+
+    # Integers and "normal" floats.
+    # The regex will greedily match any type starting with a decimal
+    # char, so needs to be located after handling of dates and times.
+    number_match = RE_NUMBER.match(src, pos)
+    if number_match:
+        return number_match.end(), match_to_number(number_match, parse_float)
+
+    # Special floats
+    first_three = src[pos : pos + 3]
+    if first_three in {"inf", "nan"}:
+        return pos + 3, parse_float(first_three)
+    first_four = src[pos : pos + 4]
+    if first_four in {"-inf", "+inf", "-nan", "+nan"}:
+        return pos + 4, parse_float(first_four)
+
+    raise suffixed_err(src, pos, "Invalid value")
+
+
+def suffixed_err(src: str, pos: Pos, msg: str) -> TOMLDecodeError:
+    """Return a `TOMLDecodeError` where error message is suffixed with
+    coordinates in source."""
+
+    def coord_repr(src: str, pos: Pos) -> str:
+        if pos >= len(src):
+            return "end of document"
+        line = src.count("\n", 0, pos) + 1
+        if line == 1:
+            column = pos + 1
+        else:
+            column = pos - src.rindex("\n", 0, pos)
+        return f"line {line}, column {column}"
+
+    return TOMLDecodeError(f"{msg} (at {coord_repr(src, pos)})")
+
+
+def is_unicode_scalar_value(codepoint: int) -> bool:
+    return (0 <= codepoint <= 55295) or (57344 <= codepoint <= 1114111)
+
+
+def make_safe_parse_float(parse_float: ParseFloat) -> ParseFloat:
+    """A decorator to make `parse_float` safe.
+
+    `parse_float` must not return dicts or lists, because these types
+    would be mixed with parsed TOML tables and arrays, thus confusing
+    the parser. The returned decorated callable raises `ValueError`
+    instead of returning illegal types.
+    """
+    # The default `float` callable never returns illegal types. Optimize it.
+    if parse_float is float:  # type: ignore[comparison-overlap]
+        return float
+
+    def safe_parse_float(float_str: str) -> Any:
+        float_value = parse_float(float_str)
+        if isinstance(float_value, (dict, list)):
+            raise ValueError("parse_float must not return dicts or lists")
+        return float_value
+
+    return safe_parse_float
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli/_re.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli/_re.py
new file mode 100644
index 0000000000000000000000000000000000000000..994bb7493fd92865e6ab87c277ba5741b44c31a9
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli/_re.py
@@ -0,0 +1,107 @@
+# SPDX-License-Identifier: MIT
+# SPDX-FileCopyrightText: 2021 Taneli Hukkinen
+# Licensed to PSF under a Contributor Agreement.
+
+from __future__ import annotations
+
+from datetime import date, datetime, time, timedelta, timezone, tzinfo
+from functools import lru_cache
+import re
+from typing import Any
+
+from ._types import ParseFloat
+
+# E.g.
+# - 00:32:00.999999
+# - 00:32:00
+_TIME_RE_STR = r"([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])(?:\.([0-9]{1,6})[0-9]*)?"
+
+RE_NUMBER = re.compile(
+    r"""
+0
+(?:
+    x[0-9A-Fa-f](?:_?[0-9A-Fa-f])*   # hex
+    |
+    b[01](?:_?[01])*                 # bin
+    |
+    o[0-7](?:_?[0-7])*               # oct
+)
+|
+[+-]?(?:0|[1-9](?:_?[0-9])*)         # dec, integer part
+(?P
+    (?:\.[0-9](?:_?[0-9])*)?         # optional fractional part
+    (?:[eE][+-]?[0-9](?:_?[0-9])*)?  # optional exponent part
+)
+""",
+    flags=re.VERBOSE,
+)
+RE_LOCALTIME = re.compile(_TIME_RE_STR)
+RE_DATETIME = re.compile(
+    rf"""
+([0-9]{{4}})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])  # date, e.g. 1988-10-27
+(?:
+    [Tt ]
+    {_TIME_RE_STR}
+    (?:([Zz])|([+-])([01][0-9]|2[0-3]):([0-5][0-9]))?  # optional time offset
+)?
+""",
+    flags=re.VERBOSE,
+)
+
+
+def match_to_datetime(match: re.Match) -> datetime | date:
+    """Convert a `RE_DATETIME` match to `datetime.datetime` or `datetime.date`.
+
+    Raises ValueError if the match does not correspond to a valid date
+    or datetime.
+    """
+    (
+        year_str,
+        month_str,
+        day_str,
+        hour_str,
+        minute_str,
+        sec_str,
+        micros_str,
+        zulu_time,
+        offset_sign_str,
+        offset_hour_str,
+        offset_minute_str,
+    ) = match.groups()
+    year, month, day = int(year_str), int(month_str), int(day_str)
+    if hour_str is None:
+        return date(year, month, day)
+    hour, minute, sec = int(hour_str), int(minute_str), int(sec_str)
+    micros = int(micros_str.ljust(6, "0")) if micros_str else 0
+    if offset_sign_str:
+        tz: tzinfo | None = cached_tz(
+            offset_hour_str, offset_minute_str, offset_sign_str
+        )
+    elif zulu_time:
+        tz = timezone.utc
+    else:  # local date-time
+        tz = None
+    return datetime(year, month, day, hour, minute, sec, micros, tzinfo=tz)
+
+
+@lru_cache(maxsize=None)
+def cached_tz(hour_str: str, minute_str: str, sign_str: str) -> timezone:
+    sign = 1 if sign_str == "+" else -1
+    return timezone(
+        timedelta(
+            hours=sign * int(hour_str),
+            minutes=sign * int(minute_str),
+        )
+    )
+
+
+def match_to_localtime(match: re.Match) -> time:
+    hour_str, minute_str, sec_str, micros_str = match.groups()
+    micros = int(micros_str.ljust(6, "0")) if micros_str else 0
+    return time(int(hour_str), int(minute_str), int(sec_str), micros)
+
+
+def match_to_number(match: re.Match, parse_float: ParseFloat) -> Any:
+    if match.group("floatpart"):
+        return parse_float(match.group())
+    return int(match.group(), 0)
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli/_types.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli/_types.py
new file mode 100644
index 0000000000000000000000000000000000000000..d949412e03b29d70592c7721fe747e5085c2e280
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli/_types.py
@@ -0,0 +1,10 @@
+# SPDX-License-Identifier: MIT
+# SPDX-FileCopyrightText: 2021 Taneli Hukkinen
+# Licensed to PSF under a Contributor Agreement.
+
+from typing import Any, Callable, Tuple
+
+# Type annotations
+ParseFloat = Callable[[str], Any]
+Key = Tuple[str, ...]
+Pos = int
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli/py.typed b/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..7632ecf77545c5e5501cb3fc5719df0761104ca2
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/tomli/py.typed
@@ -0,0 +1 @@
+# Marker file for PEP 561
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/LICENSE b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..07806f8af9dd3253ebdb5710b67e73124aea4941
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/LICENSE
@@ -0,0 +1,19 @@
+This is the MIT license: http://www.opensource.org/licenses/mit-license.php
+
+Copyright (c) Alex Grönholm
+
+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.12/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/METADATA b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..6e5750b485fd5cbdb25a9ac9b03bc494357546c7
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/METADATA
@@ -0,0 +1,81 @@
+Metadata-Version: 2.1
+Name: typeguard
+Version: 4.3.0
+Summary: Run-time type checker for Python
+Author-email: Alex Grönholm 
+License: MIT
+Project-URL: Documentation, https://typeguard.readthedocs.io/en/latest/
+Project-URL: Change log, https://typeguard.readthedocs.io/en/latest/versionhistory.html
+Project-URL: Source code, https://github.com/agronholm/typeguard
+Project-URL: Issue tracker, https://github.com/agronholm/typeguard/issues
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: MIT License
+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
+Requires-Python: >=3.8
+Description-Content-Type: text/x-rst
+License-File: LICENSE
+Requires-Dist: typing-extensions >=4.10.0
+Requires-Dist: importlib-metadata >=3.6 ; python_version < "3.10"
+Provides-Extra: doc
+Requires-Dist: packaging ; extra == 'doc'
+Requires-Dist: Sphinx >=7 ; extra == 'doc'
+Requires-Dist: sphinx-autodoc-typehints >=1.2.0 ; extra == 'doc'
+Requires-Dist: sphinx-rtd-theme >=1.3.0 ; extra == 'doc'
+Provides-Extra: test
+Requires-Dist: coverage[toml] >=7 ; extra == 'test'
+Requires-Dist: pytest >=7 ; extra == 'test'
+Requires-Dist: mypy >=1.2.0 ; (platform_python_implementation != "PyPy") and extra == 'test'
+
+.. image:: https://github.com/agronholm/typeguard/actions/workflows/test.yml/badge.svg
+  :target: https://github.com/agronholm/typeguard/actions/workflows/test.yml
+  :alt: Build Status
+.. image:: https://coveralls.io/repos/agronholm/typeguard/badge.svg?branch=master&service=github
+  :target: https://coveralls.io/github/agronholm/typeguard?branch=master
+  :alt: Code Coverage
+.. image:: https://readthedocs.org/projects/typeguard/badge/?version=latest
+  :target: https://typeguard.readthedocs.io/en/latest/?badge=latest
+  :alt: Documentation
+
+This library provides run-time type checking for functions defined with
+`PEP 484 `_ argument (and return) type
+annotations, and any arbitrary objects. It can be used together with static type
+checkers as an additional layer of type safety, to catch type violations that could only
+be detected at run time.
+
+Two principal ways to do type checking are provided:
+
+#. The ``check_type`` function:
+
+   * like ``isinstance()``, but supports arbitrary type annotations (within limits)
+   * can be used as a ``cast()`` replacement, but with actual checking of the value
+#. Code instrumentation:
+
+   * entire modules, or individual functions (via ``@typechecked``) are recompiled, with
+     type checking code injected into them
+   * automatically checks function arguments, return values and assignments to annotated
+     local variables
+   * for generator functions (regular and async), checks yield and send values
+   * requires the original source code of the instrumented module(s) to be accessible
+
+Two options are provided for code instrumentation:
+
+#. the ``@typechecked`` function:
+
+   * can be applied to functions individually
+#. the import hook (``typeguard.install_import_hook()``):
+
+   * automatically instruments targeted modules on import
+   * no manual code changes required in the target modules
+   * requires the import hook to be installed before the targeted modules are imported
+   * may clash with other import hooks
+
+See the documentation_ for further information.
+
+.. _documentation: https://typeguard.readthedocs.io/en/latest/
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/RECORD b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..801e73347c4dfdd6c275f53295de748d0aa7049d
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/RECORD
@@ -0,0 +1,34 @@
+typeguard-4.3.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+typeguard-4.3.0.dist-info/LICENSE,sha256=YWP3mH37ONa8MgzitwsvArhivEESZRbVUu8c1DJH51g,1130
+typeguard-4.3.0.dist-info/METADATA,sha256=z2dcHAp0TwhYCFU5Deh8x31nazElgujUz9tbuP0pjSE,3717
+typeguard-4.3.0.dist-info/RECORD,,
+typeguard-4.3.0.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
+typeguard-4.3.0.dist-info/entry_points.txt,sha256=qp7NQ1aLtiSgMQqo6gWlfGpy0IIXzoMJmeQTLpzqFZQ,48
+typeguard-4.3.0.dist-info/top_level.txt,sha256=4z28AhuDodwRS_c1J_l8H51t5QuwfTseskYzlxp6grs,10
+typeguard/__init__.py,sha256=Onh4w38elPCjtlcU3JY9k3h70NjsxXIkAflmQn-Z0FY,2071
+typeguard/__pycache__/__init__.cpython-312.pyc,,
+typeguard/__pycache__/_checkers.cpython-312.pyc,,
+typeguard/__pycache__/_config.cpython-312.pyc,,
+typeguard/__pycache__/_decorators.cpython-312.pyc,,
+typeguard/__pycache__/_exceptions.cpython-312.pyc,,
+typeguard/__pycache__/_functions.cpython-312.pyc,,
+typeguard/__pycache__/_importhook.cpython-312.pyc,,
+typeguard/__pycache__/_memo.cpython-312.pyc,,
+typeguard/__pycache__/_pytest_plugin.cpython-312.pyc,,
+typeguard/__pycache__/_suppression.cpython-312.pyc,,
+typeguard/__pycache__/_transformer.cpython-312.pyc,,
+typeguard/__pycache__/_union_transformer.cpython-312.pyc,,
+typeguard/__pycache__/_utils.cpython-312.pyc,,
+typeguard/_checkers.py,sha256=JRrgKicdOEfIBoNEtegYCEIlhpad-a1u1Em7GCj0WCI,31360
+typeguard/_config.py,sha256=nIz8QwDa-oFO3L9O8_6srzlmd99pSby2wOM4Wb7F_B0,2846
+typeguard/_decorators.py,sha256=v6dsIeWvPhExGLP_wXF-RmDUyjZf_Ak28g7gBJ_v0-0,9033
+typeguard/_exceptions.py,sha256=ZIPeiV-FBd5Emw2EaWd2Fvlsrwi4ocwT2fVGBIAtHcQ,1121
+typeguard/_functions.py,sha256=ibgSAKa5ptIm1eR9ARG0BSozAFJPFNASZqhPVyQeqig,10393
+typeguard/_importhook.py,sha256=ugjCDvFcdWMU7UugqlJG91IpVNpEIxtRr-99s0h1k7M,6389
+typeguard/_memo.py,sha256=1juQV_vxnD2JYKbSrebiQuj4oKHz6n67v9pYA-CCISg,1303
+typeguard/_pytest_plugin.py,sha256=-fcSqkv54rIfIF8pDavY5YQPkj4OX8GMt_lL7CQSD4I,4416
+typeguard/_suppression.py,sha256=VQfzxcwIbu3if0f7VBkKM7hkYOA7tNFw9a7jMBsmMg4,2266
+typeguard/_transformer.py,sha256=9Ha7_QhdwoUni_6hvdY-hZbuEergowHrNL2vzHIakFY,44937
+typeguard/_union_transformer.py,sha256=v_42r7-6HuRX2SoFwnyJ-E5PlxXpVeUJPJR1-HU9qSo,1354
+typeguard/_utils.py,sha256=5HhO1rPn5f1M6ymkVAEv7Xmlz1cX-j0OnTMlyHqqrR8,5270
+typeguard/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..bab98d675883cc7567a79df485cd7b4f015e376f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: bdist_wheel (0.43.0)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/entry_points.txt b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/entry_points.txt
new file mode 100644
index 0000000000000000000000000000000000000000..47c9d0bd913e50da44b12013bde2a1df636ef684
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/entry_points.txt
@@ -0,0 +1,2 @@
+[pytest11]
+typeguard = typeguard._pytest_plugin
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/top_level.txt b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..be5ec23ea2016f69345eaf80c7714777d04988f0
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/top_level.txt
@@ -0,0 +1 @@
+typeguard
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__init__.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..6781cad094b29db0959df4fb0c29c0fa9d480c0c
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__init__.py
@@ -0,0 +1,48 @@
+import os
+from typing import Any
+
+from ._checkers import TypeCheckerCallable as TypeCheckerCallable
+from ._checkers import TypeCheckLookupCallback as TypeCheckLookupCallback
+from ._checkers import check_type_internal as check_type_internal
+from ._checkers import checker_lookup_functions as checker_lookup_functions
+from ._checkers import load_plugins as load_plugins
+from ._config import CollectionCheckStrategy as CollectionCheckStrategy
+from ._config import ForwardRefPolicy as ForwardRefPolicy
+from ._config import TypeCheckConfiguration as TypeCheckConfiguration
+from ._decorators import typechecked as typechecked
+from ._decorators import typeguard_ignore as typeguard_ignore
+from ._exceptions import InstrumentationWarning as InstrumentationWarning
+from ._exceptions import TypeCheckError as TypeCheckError
+from ._exceptions import TypeCheckWarning as TypeCheckWarning
+from ._exceptions import TypeHintWarning as TypeHintWarning
+from ._functions import TypeCheckFailCallback as TypeCheckFailCallback
+from ._functions import check_type as check_type
+from ._functions import warn_on_error as warn_on_error
+from ._importhook import ImportHookManager as ImportHookManager
+from ._importhook import TypeguardFinder as TypeguardFinder
+from ._importhook import install_import_hook as install_import_hook
+from ._memo import TypeCheckMemo as TypeCheckMemo
+from ._suppression import suppress_type_checks as suppress_type_checks
+from ._utils import Unset as Unset
+
+# Re-export imports so they look like they live directly in this package
+for value in list(locals().values()):
+    if getattr(value, "__module__", "").startswith(f"{__name__}."):
+        value.__module__ = __name__
+
+
+config: TypeCheckConfiguration
+
+
+def __getattr__(name: str) -> Any:
+    if name == "config":
+        from ._config import global_config
+
+        return global_config
+
+    raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
+
+
+# Automatically load checker lookup functions unless explicitly disabled
+if "TYPEGUARD_DISABLE_PLUGIN_AUTOLOAD" not in os.environ:
+    load_plugins()
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3a6726ccd9fa8f89e97563ccad5e02d20769baae
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/_checkers.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/_checkers.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a884f4f48f43f54770b5ef1568e0c55c3484c054
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/_checkers.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/_config.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/_config.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5b176c3df1bc6321ecd5110e2f2fda1ae9256263
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/_config.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/_decorators.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/_decorators.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..843cb9e50547304e0c2adebba1034615a5d757af
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/_decorators.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/_exceptions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/_exceptions.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eaf321cca941b2cb1370bf30a1d3b31eac0ca50f
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/_exceptions.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/_functions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/_functions.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c6c99a4eb4131be55ca5c26fa55071b6c0772bf1
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/_functions.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/_importhook.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/_importhook.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..730aa534e0b50a934e885c0c0c33aeab46377154
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/_importhook.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/_memo.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/_memo.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b21e5fa3cfaf773c7e729394664372deee4e625e
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/_memo.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/_pytest_plugin.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/_pytest_plugin.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4a619c08600a29a263aba5e1e756a5b902f91ad8
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/_pytest_plugin.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/_suppression.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/_suppression.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8c2f7df71d3321b92d20731f806495eaaca232e2
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/_suppression.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/_transformer.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/_transformer.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3fbb3f0e6044fb0e9c26dea0234147475c33a31e
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/_transformer.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/_union_transformer.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/_union_transformer.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d83bd4acde41130637f13c66229e65596f2e3954
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/_union_transformer.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..adb29cb6aff406e9bedd32cbecbbe9255ce97569
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/__pycache__/_utils.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/_checkers.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/_checkers.py
new file mode 100644
index 0000000000000000000000000000000000000000..67dd5ad4dcbda70353b06fc08db962d1a41ba266
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/_checkers.py
@@ -0,0 +1,993 @@
+from __future__ import annotations
+
+import collections.abc
+import inspect
+import sys
+import types
+import typing
+import warnings
+from enum import Enum
+from inspect import Parameter, isclass, isfunction
+from io import BufferedIOBase, IOBase, RawIOBase, TextIOBase
+from textwrap import indent
+from typing import (
+    IO,
+    AbstractSet,
+    Any,
+    BinaryIO,
+    Callable,
+    Dict,
+    ForwardRef,
+    List,
+    Mapping,
+    MutableMapping,
+    NewType,
+    Optional,
+    Sequence,
+    Set,
+    TextIO,
+    Tuple,
+    Type,
+    TypeVar,
+    Union,
+)
+from unittest.mock import Mock
+from weakref import WeakKeyDictionary
+
+try:
+    import typing_extensions
+except ImportError:
+    typing_extensions = None  # type: ignore[assignment]
+
+# Must use this because typing.is_typeddict does not recognize
+# TypedDict from typing_extensions, and as of version 4.12.0
+# typing_extensions.TypedDict is different from typing.TypedDict
+# on all versions.
+from typing_extensions import is_typeddict
+
+from ._config import ForwardRefPolicy
+from ._exceptions import TypeCheckError, TypeHintWarning
+from ._memo import TypeCheckMemo
+from ._utils import evaluate_forwardref, get_stacklevel, get_type_name, qualified_name
+
+if sys.version_info >= (3, 11):
+    from typing import (
+        Annotated,
+        NotRequired,
+        TypeAlias,
+        get_args,
+        get_origin,
+    )
+
+    SubclassableAny = Any
+else:
+    from typing_extensions import (
+        Annotated,
+        NotRequired,
+        TypeAlias,
+        get_args,
+        get_origin,
+    )
+    from typing_extensions import Any as SubclassableAny
+
+if sys.version_info >= (3, 10):
+    from importlib.metadata import entry_points
+    from typing import ParamSpec
+else:
+    from importlib_metadata import entry_points
+    from typing_extensions import ParamSpec
+
+TypeCheckerCallable: TypeAlias = Callable[
+    [Any, Any, Tuple[Any, ...], TypeCheckMemo], Any
+]
+TypeCheckLookupCallback: TypeAlias = Callable[
+    [Any, Tuple[Any, ...], Tuple[Any, ...]], Optional[TypeCheckerCallable]
+]
+
+checker_lookup_functions: list[TypeCheckLookupCallback] = []
+generic_alias_types: tuple[type, ...] = (type(List), type(List[Any]))
+if sys.version_info >= (3, 9):
+    generic_alias_types += (types.GenericAlias,)
+
+protocol_check_cache: WeakKeyDictionary[
+    type[Any], dict[type[Any], TypeCheckError | None]
+] = WeakKeyDictionary()
+
+# Sentinel
+_missing = object()
+
+# Lifted from mypy.sharedparse
+BINARY_MAGIC_METHODS = {
+    "__add__",
+    "__and__",
+    "__cmp__",
+    "__divmod__",
+    "__div__",
+    "__eq__",
+    "__floordiv__",
+    "__ge__",
+    "__gt__",
+    "__iadd__",
+    "__iand__",
+    "__idiv__",
+    "__ifloordiv__",
+    "__ilshift__",
+    "__imatmul__",
+    "__imod__",
+    "__imul__",
+    "__ior__",
+    "__ipow__",
+    "__irshift__",
+    "__isub__",
+    "__itruediv__",
+    "__ixor__",
+    "__le__",
+    "__lshift__",
+    "__lt__",
+    "__matmul__",
+    "__mod__",
+    "__mul__",
+    "__ne__",
+    "__or__",
+    "__pow__",
+    "__radd__",
+    "__rand__",
+    "__rdiv__",
+    "__rfloordiv__",
+    "__rlshift__",
+    "__rmatmul__",
+    "__rmod__",
+    "__rmul__",
+    "__ror__",
+    "__rpow__",
+    "__rrshift__",
+    "__rshift__",
+    "__rsub__",
+    "__rtruediv__",
+    "__rxor__",
+    "__sub__",
+    "__truediv__",
+    "__xor__",
+}
+
+
+def check_callable(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    if not callable(value):
+        raise TypeCheckError("is not callable")
+
+    if args:
+        try:
+            signature = inspect.signature(value)
+        except (TypeError, ValueError):
+            return
+
+        argument_types = args[0]
+        if isinstance(argument_types, list) and not any(
+            type(item) is ParamSpec for item in argument_types
+        ):
+            # The callable must not have keyword-only arguments without defaults
+            unfulfilled_kwonlyargs = [
+                param.name
+                for param in signature.parameters.values()
+                if param.kind == Parameter.KEYWORD_ONLY
+                and param.default == Parameter.empty
+            ]
+            if unfulfilled_kwonlyargs:
+                raise TypeCheckError(
+                    f"has mandatory keyword-only arguments in its declaration: "
+                    f'{", ".join(unfulfilled_kwonlyargs)}'
+                )
+
+            num_positional_args = num_mandatory_pos_args = 0
+            has_varargs = False
+            for param in signature.parameters.values():
+                if param.kind in (
+                    Parameter.POSITIONAL_ONLY,
+                    Parameter.POSITIONAL_OR_KEYWORD,
+                ):
+                    num_positional_args += 1
+                    if param.default is Parameter.empty:
+                        num_mandatory_pos_args += 1
+                elif param.kind == Parameter.VAR_POSITIONAL:
+                    has_varargs = True
+
+            if num_mandatory_pos_args > len(argument_types):
+                raise TypeCheckError(
+                    f"has too many mandatory positional arguments in its declaration; "
+                    f"expected {len(argument_types)} but {num_mandatory_pos_args} "
+                    f"mandatory positional argument(s) declared"
+                )
+            elif not has_varargs and num_positional_args < len(argument_types):
+                raise TypeCheckError(
+                    f"has too few arguments in its declaration; expected "
+                    f"{len(argument_types)} but {num_positional_args} argument(s) "
+                    f"declared"
+                )
+
+
+def check_mapping(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    if origin_type is Dict or origin_type is dict:
+        if not isinstance(value, dict):
+            raise TypeCheckError("is not a dict")
+    if origin_type is MutableMapping or origin_type is collections.abc.MutableMapping:
+        if not isinstance(value, collections.abc.MutableMapping):
+            raise TypeCheckError("is not a mutable mapping")
+    elif not isinstance(value, collections.abc.Mapping):
+        raise TypeCheckError("is not a mapping")
+
+    if args:
+        key_type, value_type = args
+        if key_type is not Any or value_type is not Any:
+            samples = memo.config.collection_check_strategy.iterate_samples(
+                value.items()
+            )
+            for k, v in samples:
+                try:
+                    check_type_internal(k, key_type, memo)
+                except TypeCheckError as exc:
+                    exc.append_path_element(f"key {k!r}")
+                    raise
+
+                try:
+                    check_type_internal(v, value_type, memo)
+                except TypeCheckError as exc:
+                    exc.append_path_element(f"value of key {k!r}")
+                    raise
+
+
+def check_typed_dict(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    if not isinstance(value, dict):
+        raise TypeCheckError("is not a dict")
+
+    declared_keys = frozenset(origin_type.__annotations__)
+    if hasattr(origin_type, "__required_keys__"):
+        required_keys = set(origin_type.__required_keys__)
+    else:  # py3.8 and lower
+        required_keys = set(declared_keys) if origin_type.__total__ else set()
+
+    existing_keys = set(value)
+    extra_keys = existing_keys - declared_keys
+    if extra_keys:
+        keys_formatted = ", ".join(f'"{key}"' for key in sorted(extra_keys, key=repr))
+        raise TypeCheckError(f"has unexpected extra key(s): {keys_formatted}")
+
+    # Detect NotRequired fields which are hidden by get_type_hints()
+    type_hints: dict[str, type] = {}
+    for key, annotation in origin_type.__annotations__.items():
+        if isinstance(annotation, ForwardRef):
+            annotation = evaluate_forwardref(annotation, memo)
+            if get_origin(annotation) is NotRequired:
+                required_keys.discard(key)
+                annotation = get_args(annotation)[0]
+
+        type_hints[key] = annotation
+
+    missing_keys = required_keys - existing_keys
+    if missing_keys:
+        keys_formatted = ", ".join(f'"{key}"' for key in sorted(missing_keys, key=repr))
+        raise TypeCheckError(f"is missing required key(s): {keys_formatted}")
+
+    for key, argtype in type_hints.items():
+        argvalue = value.get(key, _missing)
+        if argvalue is not _missing:
+            try:
+                check_type_internal(argvalue, argtype, memo)
+            except TypeCheckError as exc:
+                exc.append_path_element(f"value of key {key!r}")
+                raise
+
+
+def check_list(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    if not isinstance(value, list):
+        raise TypeCheckError("is not a list")
+
+    if args and args != (Any,):
+        samples = memo.config.collection_check_strategy.iterate_samples(value)
+        for i, v in enumerate(samples):
+            try:
+                check_type_internal(v, args[0], memo)
+            except TypeCheckError as exc:
+                exc.append_path_element(f"item {i}")
+                raise
+
+
+def check_sequence(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    if not isinstance(value, collections.abc.Sequence):
+        raise TypeCheckError("is not a sequence")
+
+    if args and args != (Any,):
+        samples = memo.config.collection_check_strategy.iterate_samples(value)
+        for i, v in enumerate(samples):
+            try:
+                check_type_internal(v, args[0], memo)
+            except TypeCheckError as exc:
+                exc.append_path_element(f"item {i}")
+                raise
+
+
+def check_set(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    if origin_type is frozenset:
+        if not isinstance(value, frozenset):
+            raise TypeCheckError("is not a frozenset")
+    elif not isinstance(value, AbstractSet):
+        raise TypeCheckError("is not a set")
+
+    if args and args != (Any,):
+        samples = memo.config.collection_check_strategy.iterate_samples(value)
+        for v in samples:
+            try:
+                check_type_internal(v, args[0], memo)
+            except TypeCheckError as exc:
+                exc.append_path_element(f"[{v}]")
+                raise
+
+
+def check_tuple(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    # Specialized check for NamedTuples
+    if field_types := getattr(origin_type, "__annotations__", None):
+        if not isinstance(value, origin_type):
+            raise TypeCheckError(
+                f"is not a named tuple of type {qualified_name(origin_type)}"
+            )
+
+        for name, field_type in field_types.items():
+            try:
+                check_type_internal(getattr(value, name), field_type, memo)
+            except TypeCheckError as exc:
+                exc.append_path_element(f"attribute {name!r}")
+                raise
+
+        return
+    elif not isinstance(value, tuple):
+        raise TypeCheckError("is not a tuple")
+
+    if args:
+        use_ellipsis = args[-1] is Ellipsis
+        tuple_params = args[: -1 if use_ellipsis else None]
+    else:
+        # Unparametrized Tuple or plain tuple
+        return
+
+    if use_ellipsis:
+        element_type = tuple_params[0]
+        samples = memo.config.collection_check_strategy.iterate_samples(value)
+        for i, element in enumerate(samples):
+            try:
+                check_type_internal(element, element_type, memo)
+            except TypeCheckError as exc:
+                exc.append_path_element(f"item {i}")
+                raise
+    elif tuple_params == ((),):
+        if value != ():
+            raise TypeCheckError("is not an empty tuple")
+    else:
+        if len(value) != len(tuple_params):
+            raise TypeCheckError(
+                f"has wrong number of elements (expected {len(tuple_params)}, got "
+                f"{len(value)} instead)"
+            )
+
+        for i, (element, element_type) in enumerate(zip(value, tuple_params)):
+            try:
+                check_type_internal(element, element_type, memo)
+            except TypeCheckError as exc:
+                exc.append_path_element(f"item {i}")
+                raise
+
+
+def check_union(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    errors: dict[str, TypeCheckError] = {}
+    try:
+        for type_ in args:
+            try:
+                check_type_internal(value, type_, memo)
+                return
+            except TypeCheckError as exc:
+                errors[get_type_name(type_)] = exc
+
+        formatted_errors = indent(
+            "\n".join(f"{key}: {error}" for key, error in errors.items()), "  "
+        )
+    finally:
+        del errors  # avoid creating ref cycle
+    raise TypeCheckError(f"did not match any element in the union:\n{formatted_errors}")
+
+
+def check_uniontype(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    errors: dict[str, TypeCheckError] = {}
+    for type_ in args:
+        try:
+            check_type_internal(value, type_, memo)
+            return
+        except TypeCheckError as exc:
+            errors[get_type_name(type_)] = exc
+
+    formatted_errors = indent(
+        "\n".join(f"{key}: {error}" for key, error in errors.items()), "  "
+    )
+    raise TypeCheckError(f"did not match any element in the union:\n{formatted_errors}")
+
+
+def check_class(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    if not isclass(value) and not isinstance(value, generic_alias_types):
+        raise TypeCheckError("is not a class")
+
+    if not args:
+        return
+
+    if isinstance(args[0], ForwardRef):
+        expected_class = evaluate_forwardref(args[0], memo)
+    else:
+        expected_class = args[0]
+
+    if expected_class is Any:
+        return
+    elif getattr(expected_class, "_is_protocol", False):
+        check_protocol(value, expected_class, (), memo)
+    elif isinstance(expected_class, TypeVar):
+        check_typevar(value, expected_class, (), memo, subclass_check=True)
+    elif get_origin(expected_class) is Union:
+        errors: dict[str, TypeCheckError] = {}
+        for arg in get_args(expected_class):
+            if arg is Any:
+                return
+
+            try:
+                check_class(value, type, (arg,), memo)
+                return
+            except TypeCheckError as exc:
+                errors[get_type_name(arg)] = exc
+        else:
+            formatted_errors = indent(
+                "\n".join(f"{key}: {error}" for key, error in errors.items()), "  "
+            )
+            raise TypeCheckError(
+                f"did not match any element in the union:\n{formatted_errors}"
+            )
+    elif not issubclass(value, expected_class):  # type: ignore[arg-type]
+        raise TypeCheckError(f"is not a subclass of {qualified_name(expected_class)}")
+
+
+def check_newtype(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    check_type_internal(value, origin_type.__supertype__, memo)
+
+
+def check_instance(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    if not isinstance(value, origin_type):
+        raise TypeCheckError(f"is not an instance of {qualified_name(origin_type)}")
+
+
+def check_typevar(
+    value: Any,
+    origin_type: TypeVar,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+    *,
+    subclass_check: bool = False,
+) -> None:
+    if origin_type.__bound__ is not None:
+        annotation = (
+            Type[origin_type.__bound__] if subclass_check else origin_type.__bound__
+        )
+        check_type_internal(value, annotation, memo)
+    elif origin_type.__constraints__:
+        for constraint in origin_type.__constraints__:
+            annotation = Type[constraint] if subclass_check else constraint
+            try:
+                check_type_internal(value, annotation, memo)
+            except TypeCheckError:
+                pass
+            else:
+                break
+        else:
+            formatted_constraints = ", ".join(
+                get_type_name(constraint) for constraint in origin_type.__constraints__
+            )
+            raise TypeCheckError(
+                f"does not match any of the constraints " f"({formatted_constraints})"
+            )
+
+
+if typing_extensions is None:
+
+    def _is_literal_type(typ: object) -> bool:
+        return typ is typing.Literal
+
+else:
+
+    def _is_literal_type(typ: object) -> bool:
+        return typ is typing.Literal or typ is typing_extensions.Literal
+
+
+def check_literal(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    def get_literal_args(literal_args: tuple[Any, ...]) -> tuple[Any, ...]:
+        retval: list[Any] = []
+        for arg in literal_args:
+            if _is_literal_type(get_origin(arg)):
+                retval.extend(get_literal_args(arg.__args__))
+            elif arg is None or isinstance(arg, (int, str, bytes, bool, Enum)):
+                retval.append(arg)
+            else:
+                raise TypeError(
+                    f"Illegal literal value: {arg}"
+                )  # TypeError here is deliberate
+
+        return tuple(retval)
+
+    final_args = tuple(get_literal_args(args))
+    try:
+        index = final_args.index(value)
+    except ValueError:
+        pass
+    else:
+        if type(final_args[index]) is type(value):
+            return
+
+    formatted_args = ", ".join(repr(arg) for arg in final_args)
+    raise TypeCheckError(f"is not any of ({formatted_args})") from None
+
+
+def check_literal_string(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    check_type_internal(value, str, memo)
+
+
+def check_typeguard(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    check_type_internal(value, bool, memo)
+
+
+def check_none(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    if value is not None:
+        raise TypeCheckError("is not None")
+
+
+def check_number(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    if origin_type is complex and not isinstance(value, (complex, float, int)):
+        raise TypeCheckError("is neither complex, float or int")
+    elif origin_type is float and not isinstance(value, (float, int)):
+        raise TypeCheckError("is neither float or int")
+
+
+def check_io(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    if origin_type is TextIO or (origin_type is IO and args == (str,)):
+        if not isinstance(value, TextIOBase):
+            raise TypeCheckError("is not a text based I/O object")
+    elif origin_type is BinaryIO or (origin_type is IO and args == (bytes,)):
+        if not isinstance(value, (RawIOBase, BufferedIOBase)):
+            raise TypeCheckError("is not a binary I/O object")
+    elif not isinstance(value, IOBase):
+        raise TypeCheckError("is not an I/O object")
+
+
+def check_protocol(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    subject: type[Any] = value if isclass(value) else type(value)
+
+    if subject in protocol_check_cache:
+        result_map = protocol_check_cache[subject]
+        if origin_type in result_map:
+            if exc := result_map[origin_type]:
+                raise exc
+            else:
+                return
+
+    # Collect a set of methods and non-method attributes present in the protocol
+    ignored_attrs = set(dir(typing.Protocol)) | {
+        "__annotations__",
+        "__non_callable_proto_members__",
+    }
+    expected_methods: dict[str, tuple[Any, Any]] = {}
+    expected_noncallable_members: dict[str, Any] = {}
+    for attrname in dir(origin_type):
+        # Skip attributes present in typing.Protocol
+        if attrname in ignored_attrs:
+            continue
+
+        member = getattr(origin_type, attrname)
+        if callable(member):
+            signature = inspect.signature(member)
+            argtypes = [
+                (p.annotation if p.annotation is not Parameter.empty else Any)
+                for p in signature.parameters.values()
+                if p.kind is not Parameter.KEYWORD_ONLY
+            ] or Ellipsis
+            return_annotation = (
+                signature.return_annotation
+                if signature.return_annotation is not Parameter.empty
+                else Any
+            )
+            expected_methods[attrname] = argtypes, return_annotation
+        else:
+            expected_noncallable_members[attrname] = member
+
+    for attrname, annotation in typing.get_type_hints(origin_type).items():
+        expected_noncallable_members[attrname] = annotation
+
+    subject_annotations = typing.get_type_hints(subject)
+
+    # Check that all required methods are present and their signatures are compatible
+    result_map = protocol_check_cache.setdefault(subject, {})
+    try:
+        for attrname, callable_args in expected_methods.items():
+            try:
+                method = getattr(subject, attrname)
+            except AttributeError:
+                if attrname in subject_annotations:
+                    raise TypeCheckError(
+                        f"is not compatible with the {origin_type.__qualname__} protocol "
+                        f"because its {attrname!r} attribute is not a method"
+                    ) from None
+                else:
+                    raise TypeCheckError(
+                        f"is not compatible with the {origin_type.__qualname__} protocol "
+                        f"because it has no method named {attrname!r}"
+                    ) from None
+
+            if not callable(method):
+                raise TypeCheckError(
+                    f"is not compatible with the {origin_type.__qualname__} protocol "
+                    f"because its {attrname!r} attribute is not a callable"
+                )
+
+            # TODO: raise exception on added keyword-only arguments without defaults
+            try:
+                check_callable(method, Callable, callable_args, memo)
+            except TypeCheckError as exc:
+                raise TypeCheckError(
+                    f"is not compatible with the {origin_type.__qualname__} protocol "
+                    f"because its {attrname!r} method {exc}"
+                ) from None
+
+        # Check that all required non-callable members are present
+        for attrname in expected_noncallable_members:
+            # TODO: implement assignability checks for non-callable members
+            if attrname not in subject_annotations and not hasattr(subject, attrname):
+                raise TypeCheckError(
+                    f"is not compatible with the {origin_type.__qualname__} protocol "
+                    f"because it has no attribute named {attrname!r}"
+                )
+    except TypeCheckError as exc:
+        result_map[origin_type] = exc
+        raise
+    else:
+        result_map[origin_type] = None
+
+
+def check_byteslike(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    if not isinstance(value, (bytearray, bytes, memoryview)):
+        raise TypeCheckError("is not bytes-like")
+
+
+def check_self(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    if memo.self_type is None:
+        raise TypeCheckError("cannot be checked against Self outside of a method call")
+
+    if isclass(value):
+        if not issubclass(value, memo.self_type):
+            raise TypeCheckError(
+                f"is not an instance of the self type "
+                f"({qualified_name(memo.self_type)})"
+            )
+    elif not isinstance(value, memo.self_type):
+        raise TypeCheckError(
+            f"is not an instance of the self type ({qualified_name(memo.self_type)})"
+        )
+
+
+def check_paramspec(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    pass  # No-op for now
+
+
+def check_instanceof(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    if not isinstance(value, origin_type):
+        raise TypeCheckError(f"is not an instance of {qualified_name(origin_type)}")
+
+
+def check_type_internal(
+    value: Any,
+    annotation: Any,
+    memo: TypeCheckMemo,
+) -> None:
+    """
+    Check that the given object is compatible with the given type annotation.
+
+    This function should only be used by type checker callables. Applications should use
+    :func:`~.check_type` instead.
+
+    :param value: the value to check
+    :param annotation: the type annotation to check against
+    :param memo: a memo object containing configuration and information necessary for
+        looking up forward references
+    """
+
+    if isinstance(annotation, ForwardRef):
+        try:
+            annotation = evaluate_forwardref(annotation, memo)
+        except NameError:
+            if memo.config.forward_ref_policy is ForwardRefPolicy.ERROR:
+                raise
+            elif memo.config.forward_ref_policy is ForwardRefPolicy.WARN:
+                warnings.warn(
+                    f"Cannot resolve forward reference {annotation.__forward_arg__!r}",
+                    TypeHintWarning,
+                    stacklevel=get_stacklevel(),
+                )
+
+            return
+
+    if annotation is Any or annotation is SubclassableAny or isinstance(value, Mock):
+        return
+
+    # Skip type checks if value is an instance of a class that inherits from Any
+    if not isclass(value) and SubclassableAny in type(value).__bases__:
+        return
+
+    extras: tuple[Any, ...]
+    origin_type = get_origin(annotation)
+    if origin_type is Annotated:
+        annotation, *extras_ = get_args(annotation)
+        extras = tuple(extras_)
+        origin_type = get_origin(annotation)
+    else:
+        extras = ()
+
+    if origin_type is not None:
+        args = get_args(annotation)
+
+        # Compatibility hack to distinguish between unparametrized and empty tuple
+        # (tuple[()]), necessary due to https://github.com/python/cpython/issues/91137
+        if origin_type in (tuple, Tuple) and annotation is not Tuple and not args:
+            args = ((),)
+    else:
+        origin_type = annotation
+        args = ()
+
+    for lookup_func in checker_lookup_functions:
+        checker = lookup_func(origin_type, args, extras)
+        if checker:
+            checker(value, origin_type, args, memo)
+            return
+
+    if isclass(origin_type):
+        if not isinstance(value, origin_type):
+            raise TypeCheckError(f"is not an instance of {qualified_name(origin_type)}")
+    elif type(origin_type) is str:  # noqa: E721
+        warnings.warn(
+            f"Skipping type check against {origin_type!r}; this looks like a "
+            f"string-form forward reference imported from another module",
+            TypeHintWarning,
+            stacklevel=get_stacklevel(),
+        )
+
+
+# Equality checks are applied to these
+origin_type_checkers = {
+    bytes: check_byteslike,
+    AbstractSet: check_set,
+    BinaryIO: check_io,
+    Callable: check_callable,
+    collections.abc.Callable: check_callable,
+    complex: check_number,
+    dict: check_mapping,
+    Dict: check_mapping,
+    float: check_number,
+    frozenset: check_set,
+    IO: check_io,
+    list: check_list,
+    List: check_list,
+    typing.Literal: check_literal,
+    Mapping: check_mapping,
+    MutableMapping: check_mapping,
+    None: check_none,
+    collections.abc.Mapping: check_mapping,
+    collections.abc.MutableMapping: check_mapping,
+    Sequence: check_sequence,
+    collections.abc.Sequence: check_sequence,
+    collections.abc.Set: check_set,
+    set: check_set,
+    Set: check_set,
+    TextIO: check_io,
+    tuple: check_tuple,
+    Tuple: check_tuple,
+    type: check_class,
+    Type: check_class,
+    Union: check_union,
+}
+if sys.version_info >= (3, 10):
+    origin_type_checkers[types.UnionType] = check_uniontype
+    origin_type_checkers[typing.TypeGuard] = check_typeguard
+if sys.version_info >= (3, 11):
+    origin_type_checkers.update(
+        {typing.LiteralString: check_literal_string, typing.Self: check_self}
+    )
+if typing_extensions is not None:
+    # On some Python versions, these may simply be re-exports from typing,
+    # but exactly which Python versions is subject to change,
+    # so it's best to err on the safe side
+    # and update the dictionary on all Python versions
+    # if typing_extensions is installed
+    origin_type_checkers[typing_extensions.Literal] = check_literal
+    origin_type_checkers[typing_extensions.LiteralString] = check_literal_string
+    origin_type_checkers[typing_extensions.Self] = check_self
+    origin_type_checkers[typing_extensions.TypeGuard] = check_typeguard
+
+
+def builtin_checker_lookup(
+    origin_type: Any, args: tuple[Any, ...], extras: tuple[Any, ...]
+) -> TypeCheckerCallable | None:
+    checker = origin_type_checkers.get(origin_type)
+    if checker is not None:
+        return checker
+    elif is_typeddict(origin_type):
+        return check_typed_dict
+    elif isclass(origin_type) and issubclass(
+        origin_type,
+        Tuple,  # type: ignore[arg-type]
+    ):
+        # NamedTuple
+        return check_tuple
+    elif getattr(origin_type, "_is_protocol", False):
+        return check_protocol
+    elif isinstance(origin_type, ParamSpec):
+        return check_paramspec
+    elif isinstance(origin_type, TypeVar):
+        return check_typevar
+    elif origin_type.__class__ is NewType:
+        # typing.NewType on Python 3.10+
+        return check_newtype
+    elif (
+        isfunction(origin_type)
+        and getattr(origin_type, "__module__", None) == "typing"
+        and getattr(origin_type, "__qualname__", "").startswith("NewType.")
+        and hasattr(origin_type, "__supertype__")
+    ):
+        # typing.NewType on Python 3.9 and below
+        return check_newtype
+
+    return None
+
+
+checker_lookup_functions.append(builtin_checker_lookup)
+
+
+def load_plugins() -> None:
+    """
+    Load all type checker lookup functions from entry points.
+
+    All entry points from the ``typeguard.checker_lookup`` group are loaded, and the
+    returned lookup functions are added to :data:`typeguard.checker_lookup_functions`.
+
+    .. note:: This function is called implicitly on import, unless the
+        ``TYPEGUARD_DISABLE_PLUGIN_AUTOLOAD`` environment variable is present.
+    """
+
+    for ep in entry_points(group="typeguard.checker_lookup"):
+        try:
+            plugin = ep.load()
+        except Exception as exc:
+            warnings.warn(
+                f"Failed to load plugin {ep.name!r}: " f"{qualified_name(exc)}: {exc}",
+                stacklevel=2,
+            )
+            continue
+
+        if not callable(plugin):
+            warnings.warn(
+                f"Plugin {ep} returned a non-callable object: {plugin!r}", stacklevel=2
+            )
+            continue
+
+        checker_lookup_functions.insert(0, plugin)
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/_config.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..36efad53965488e7e003c265262db8d5d902a930
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/_config.py
@@ -0,0 +1,108 @@
+from __future__ import annotations
+
+from collections.abc import Iterable
+from dataclasses import dataclass
+from enum import Enum, auto
+from typing import TYPE_CHECKING, TypeVar
+
+if TYPE_CHECKING:
+    from ._functions import TypeCheckFailCallback
+
+T = TypeVar("T")
+
+
+class ForwardRefPolicy(Enum):
+    """
+    Defines how unresolved forward references are handled.
+
+    Members:
+
+    * ``ERROR``: propagate the :exc:`NameError` when the forward reference lookup fails
+    * ``WARN``: emit a :class:`~.TypeHintWarning` if the forward reference lookup fails
+    * ``IGNORE``: silently skip checks for unresolveable forward references
+    """
+
+    ERROR = auto()
+    WARN = auto()
+    IGNORE = auto()
+
+
+class CollectionCheckStrategy(Enum):
+    """
+    Specifies how thoroughly the contents of collections are type checked.
+
+    This has an effect on the following built-in checkers:
+
+    * ``AbstractSet``
+    * ``Dict``
+    * ``List``
+    * ``Mapping``
+    * ``Set``
+    * ``Tuple[, ...]`` (arbitrarily sized tuples)
+
+    Members:
+
+    * ``FIRST_ITEM``: check only the first item
+    * ``ALL_ITEMS``: check all items
+    """
+
+    FIRST_ITEM = auto()
+    ALL_ITEMS = auto()
+
+    def iterate_samples(self, collection: Iterable[T]) -> Iterable[T]:
+        if self is CollectionCheckStrategy.FIRST_ITEM:
+            try:
+                return [next(iter(collection))]
+            except StopIteration:
+                return ()
+        else:
+            return collection
+
+
+@dataclass
+class TypeCheckConfiguration:
+    """
+     You can change Typeguard's behavior with these settings.
+
+    .. attribute:: typecheck_fail_callback
+       :type: Callable[[TypeCheckError, TypeCheckMemo], Any]
+
+         Callable that is called when type checking fails.
+
+         Default: ``None`` (the :exc:`~.TypeCheckError` is raised directly)
+
+    .. attribute:: forward_ref_policy
+       :type: ForwardRefPolicy
+
+         Specifies what to do when a forward reference fails to resolve.
+
+         Default: ``WARN``
+
+    .. attribute:: collection_check_strategy
+       :type: CollectionCheckStrategy
+
+         Specifies how thoroughly the contents of collections (list, dict, etc.) are
+         type checked.
+
+         Default: ``FIRST_ITEM``
+
+    .. attribute:: debug_instrumentation
+       :type: bool
+
+         If set to ``True``, the code of modules or functions instrumented by typeguard
+         is printed to ``sys.stderr`` after the instrumentation is done
+
+         Requires Python 3.9 or newer.
+
+         Default: ``False``
+    """
+
+    forward_ref_policy: ForwardRefPolicy = ForwardRefPolicy.WARN
+    typecheck_fail_callback: TypeCheckFailCallback | None = None
+    collection_check_strategy: CollectionCheckStrategy = (
+        CollectionCheckStrategy.FIRST_ITEM
+    )
+    debug_instrumentation: bool = False
+
+
+global_config = TypeCheckConfiguration()
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/_decorators.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/_decorators.py
new file mode 100644
index 0000000000000000000000000000000000000000..cf3253351fe3b07af0b79f7c1ffac7b2d6127a19
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/_decorators.py
@@ -0,0 +1,235 @@
+from __future__ import annotations
+
+import ast
+import inspect
+import sys
+from collections.abc import Sequence
+from functools import partial
+from inspect import isclass, isfunction
+from types import CodeType, FrameType, FunctionType
+from typing import TYPE_CHECKING, Any, Callable, ForwardRef, TypeVar, cast, overload
+from warnings import warn
+
+from ._config import CollectionCheckStrategy, ForwardRefPolicy, global_config
+from ._exceptions import InstrumentationWarning
+from ._functions import TypeCheckFailCallback
+from ._transformer import TypeguardTransformer
+from ._utils import Unset, function_name, get_stacklevel, is_method_of, unset
+
+if TYPE_CHECKING:
+    from typeshed.stdlib.types import _Cell
+
+    _F = TypeVar("_F")
+
+    def typeguard_ignore(f: _F) -> _F:
+        """This decorator is a noop during static type-checking."""
+        return f
+
+else:
+    from typing import no_type_check as typeguard_ignore  # noqa: F401
+
+T_CallableOrType = TypeVar("T_CallableOrType", bound=Callable[..., Any])
+
+
+def make_cell(value: object) -> _Cell:
+    return (lambda: value).__closure__[0]  # type: ignore[index]
+
+
+def find_target_function(
+    new_code: CodeType, target_path: Sequence[str], firstlineno: int
+) -> CodeType | None:
+    target_name = target_path[0]
+    for const in new_code.co_consts:
+        if isinstance(const, CodeType):
+            if const.co_name == target_name:
+                if const.co_firstlineno == firstlineno:
+                    return const
+                elif len(target_path) > 1:
+                    target_code = find_target_function(
+                        const, target_path[1:], firstlineno
+                    )
+                    if target_code:
+                        return target_code
+
+    return None
+
+
+def instrument(f: T_CallableOrType) -> FunctionType | str:
+    if not getattr(f, "__code__", None):
+        return "no code associated"
+    elif not getattr(f, "__module__", None):
+        return "__module__ attribute is not set"
+    elif f.__code__.co_filename == "":
+        return "cannot instrument functions defined in a REPL"
+    elif hasattr(f, "__wrapped__"):
+        return (
+            "@typechecked only supports instrumenting functions wrapped with "
+            "@classmethod, @staticmethod or @property"
+        )
+
+    target_path = [item for item in f.__qualname__.split(".") if item != ""]
+    module_source = inspect.getsource(sys.modules[f.__module__])
+    module_ast = ast.parse(module_source)
+    instrumentor = TypeguardTransformer(target_path, f.__code__.co_firstlineno)
+    instrumentor.visit(module_ast)
+
+    if not instrumentor.target_node or instrumentor.target_lineno is None:
+        return "instrumentor did not find the target function"
+
+    module_code = compile(module_ast, f.__code__.co_filename, "exec", dont_inherit=True)
+    new_code = find_target_function(
+        module_code, target_path, instrumentor.target_lineno
+    )
+    if not new_code:
+        return "cannot find the target function in the AST"
+
+    if global_config.debug_instrumentation and sys.version_info >= (3, 9):
+        # Find the matching AST node, then unparse it to source and print to stdout
+        print(
+            f"Source code of {f.__qualname__}() after instrumentation:"
+            "\n----------------------------------------------",
+            file=sys.stderr,
+        )
+        print(ast.unparse(instrumentor.target_node), file=sys.stderr)
+        print(
+            "----------------------------------------------",
+            file=sys.stderr,
+        )
+
+    closure = f.__closure__
+    if new_code.co_freevars != f.__code__.co_freevars:
+        # Create a new closure and find values for the new free variables
+        frame = cast(FrameType, inspect.currentframe())
+        frame = cast(FrameType, frame.f_back)
+        frame_locals = cast(FrameType, frame.f_back).f_locals
+        cells: list[_Cell] = []
+        for key in new_code.co_freevars:
+            if key in instrumentor.names_used_in_annotations:
+                # Find the value and make a new cell from it
+                value = frame_locals.get(key) or ForwardRef(key)
+                cells.append(make_cell(value))
+            else:
+                # Reuse the cell from the existing closure
+                assert f.__closure__
+                cells.append(f.__closure__[f.__code__.co_freevars.index(key)])
+
+        closure = tuple(cells)
+
+    new_function = FunctionType(new_code, f.__globals__, f.__name__, closure=closure)
+    new_function.__module__ = f.__module__
+    new_function.__name__ = f.__name__
+    new_function.__qualname__ = f.__qualname__
+    new_function.__annotations__ = f.__annotations__
+    new_function.__doc__ = f.__doc__
+    new_function.__defaults__ = f.__defaults__
+    new_function.__kwdefaults__ = f.__kwdefaults__
+    return new_function
+
+
+@overload
+def typechecked(
+    *,
+    forward_ref_policy: ForwardRefPolicy | Unset = unset,
+    typecheck_fail_callback: TypeCheckFailCallback | Unset = unset,
+    collection_check_strategy: CollectionCheckStrategy | Unset = unset,
+    debug_instrumentation: bool | Unset = unset,
+) -> Callable[[T_CallableOrType], T_CallableOrType]: ...
+
+
+@overload
+def typechecked(target: T_CallableOrType) -> T_CallableOrType: ...
+
+
+def typechecked(
+    target: T_CallableOrType | None = None,
+    *,
+    forward_ref_policy: ForwardRefPolicy | Unset = unset,
+    typecheck_fail_callback: TypeCheckFailCallback | Unset = unset,
+    collection_check_strategy: CollectionCheckStrategy | Unset = unset,
+    debug_instrumentation: bool | Unset = unset,
+) -> Any:
+    """
+    Instrument the target function to perform run-time type checking.
+
+    This decorator recompiles the target function, injecting code to type check
+    arguments, return values, yield values (excluding ``yield from``) and assignments to
+    annotated local variables.
+
+    This can also be used as a class decorator. This will instrument all type annotated
+    methods, including :func:`@classmethod `,
+    :func:`@staticmethod `,  and :class:`@property ` decorated
+    methods in the class.
+
+    .. note:: When Python is run in optimized mode (``-O`` or ``-OO``, this decorator
+        is a no-op). This is a feature meant for selectively introducing type checking
+        into a code base where the checks aren't meant to be run in production.
+
+    :param target: the function or class to enable type checking for
+    :param forward_ref_policy: override for
+        :attr:`.TypeCheckConfiguration.forward_ref_policy`
+    :param typecheck_fail_callback: override for
+        :attr:`.TypeCheckConfiguration.typecheck_fail_callback`
+    :param collection_check_strategy: override for
+        :attr:`.TypeCheckConfiguration.collection_check_strategy`
+    :param debug_instrumentation: override for
+        :attr:`.TypeCheckConfiguration.debug_instrumentation`
+
+    """
+    if target is None:
+        return partial(
+            typechecked,
+            forward_ref_policy=forward_ref_policy,
+            typecheck_fail_callback=typecheck_fail_callback,
+            collection_check_strategy=collection_check_strategy,
+            debug_instrumentation=debug_instrumentation,
+        )
+
+    if not __debug__:
+        return target
+
+    if isclass(target):
+        for key, attr in target.__dict__.items():
+            if is_method_of(attr, target):
+                retval = instrument(attr)
+                if isfunction(retval):
+                    setattr(target, key, retval)
+            elif isinstance(attr, (classmethod, staticmethod)):
+                if is_method_of(attr.__func__, target):
+                    retval = instrument(attr.__func__)
+                    if isfunction(retval):
+                        wrapper = attr.__class__(retval)
+                        setattr(target, key, wrapper)
+            elif isinstance(attr, property):
+                kwargs: dict[str, Any] = dict(doc=attr.__doc__)
+                for name in ("fset", "fget", "fdel"):
+                    property_func = kwargs[name] = getattr(attr, name)
+                    if is_method_of(property_func, target):
+                        retval = instrument(property_func)
+                        if isfunction(retval):
+                            kwargs[name] = retval
+
+                setattr(target, key, attr.__class__(**kwargs))
+
+        return target
+
+    # Find either the first Python wrapper or the actual function
+    wrapper_class: (
+        type[classmethod[Any, Any, Any]] | type[staticmethod[Any, Any]] | None
+    ) = None
+    if isinstance(target, (classmethod, staticmethod)):
+        wrapper_class = target.__class__
+        target = target.__func__
+
+    retval = instrument(target)
+    if isinstance(retval, str):
+        warn(
+            f"{retval} -- not typechecking {function_name(target)}",
+            InstrumentationWarning,
+            stacklevel=get_stacklevel(),
+        )
+        return target
+
+    if wrapper_class is None:
+        return retval
+    else:
+        return wrapper_class(retval)
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/_exceptions.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/_exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..625437a64990b5fae898c9c98fe9a7bd6be90cfb
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/_exceptions.py
@@ -0,0 +1,42 @@
+from collections import deque
+from typing import Deque
+
+
+class TypeHintWarning(UserWarning):
+    """
+    A warning that is emitted when a type hint in string form could not be resolved to
+    an actual type.
+    """
+
+
+class TypeCheckWarning(UserWarning):
+    """Emitted by typeguard's type checkers when a type mismatch is detected."""
+
+    def __init__(self, message: str):
+        super().__init__(message)
+
+
+class InstrumentationWarning(UserWarning):
+    """Emitted when there's a problem with instrumenting a function for type checks."""
+
+    def __init__(self, message: str):
+        super().__init__(message)
+
+
+class TypeCheckError(Exception):
+    """
+    Raised by typeguard's type checkers when a type mismatch is detected.
+    """
+
+    def __init__(self, message: str):
+        super().__init__(message)
+        self._path: Deque[str] = deque()
+
+    def append_path_element(self, element: str) -> None:
+        self._path.append(element)
+
+    def __str__(self) -> str:
+        if self._path:
+            return " of ".join(self._path) + " " + str(self.args[0])
+        else:
+            return str(self.args[0])
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/_functions.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/_functions.py
new file mode 100644
index 0000000000000000000000000000000000000000..28497856a325e1b00dbe4aadfd2ed1c6082cd23a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/_functions.py
@@ -0,0 +1,308 @@
+from __future__ import annotations
+
+import sys
+import warnings
+from typing import Any, Callable, NoReturn, TypeVar, Union, overload
+
+from . import _suppression
+from ._checkers import BINARY_MAGIC_METHODS, check_type_internal
+from ._config import (
+    CollectionCheckStrategy,
+    ForwardRefPolicy,
+    TypeCheckConfiguration,
+)
+from ._exceptions import TypeCheckError, TypeCheckWarning
+from ._memo import TypeCheckMemo
+from ._utils import get_stacklevel, qualified_name
+
+if sys.version_info >= (3, 11):
+    from typing import Literal, Never, TypeAlias
+else:
+    from typing_extensions import Literal, Never, TypeAlias
+
+T = TypeVar("T")
+TypeCheckFailCallback: TypeAlias = Callable[[TypeCheckError, TypeCheckMemo], Any]
+
+
+@overload
+def check_type(
+    value: object,
+    expected_type: type[T],
+    *,
+    forward_ref_policy: ForwardRefPolicy = ...,
+    typecheck_fail_callback: TypeCheckFailCallback | None = ...,
+    collection_check_strategy: CollectionCheckStrategy = ...,
+) -> T: ...
+
+
+@overload
+def check_type(
+    value: object,
+    expected_type: Any,
+    *,
+    forward_ref_policy: ForwardRefPolicy = ...,
+    typecheck_fail_callback: TypeCheckFailCallback | None = ...,
+    collection_check_strategy: CollectionCheckStrategy = ...,
+) -> Any: ...
+
+
+def check_type(
+    value: object,
+    expected_type: Any,
+    *,
+    forward_ref_policy: ForwardRefPolicy = TypeCheckConfiguration().forward_ref_policy,
+    typecheck_fail_callback: TypeCheckFailCallback | None = (
+        TypeCheckConfiguration().typecheck_fail_callback
+    ),
+    collection_check_strategy: CollectionCheckStrategy = (
+        TypeCheckConfiguration().collection_check_strategy
+    ),
+) -> Any:
+    """
+    Ensure that ``value`` matches ``expected_type``.
+
+    The types from the :mod:`typing` module do not support :func:`isinstance` or
+    :func:`issubclass` so a number of type specific checks are required. This function
+    knows which checker to call for which type.
+
+    This function wraps :func:`~.check_type_internal` in the following ways:
+
+    * Respects type checking suppression (:func:`~.suppress_type_checks`)
+    * Forms a :class:`~.TypeCheckMemo` from the current stack frame
+    * Calls the configured type check fail callback if the check fails
+
+    Note that this function is independent of the globally shared configuration in
+    :data:`typeguard.config`. This means that usage within libraries is safe from being
+    affected configuration changes made by other libraries or by the integrating
+    application. Instead, configuration options have the same default values as their
+    corresponding fields in :class:`TypeCheckConfiguration`.
+
+    :param value: value to be checked against ``expected_type``
+    :param expected_type: a class or generic type instance, or a tuple of such things
+    :param forward_ref_policy: see :attr:`TypeCheckConfiguration.forward_ref_policy`
+    :param typecheck_fail_callback:
+        see :attr`TypeCheckConfiguration.typecheck_fail_callback`
+    :param collection_check_strategy:
+        see :attr:`TypeCheckConfiguration.collection_check_strategy`
+    :return: ``value``, unmodified
+    :raises TypeCheckError: if there is a type mismatch
+
+    """
+    if type(expected_type) is tuple:
+        expected_type = Union[expected_type]
+
+    config = TypeCheckConfiguration(
+        forward_ref_policy=forward_ref_policy,
+        typecheck_fail_callback=typecheck_fail_callback,
+        collection_check_strategy=collection_check_strategy,
+    )
+
+    if _suppression.type_checks_suppressed or expected_type is Any:
+        return value
+
+    frame = sys._getframe(1)
+    memo = TypeCheckMemo(frame.f_globals, frame.f_locals, config=config)
+    try:
+        check_type_internal(value, expected_type, memo)
+    except TypeCheckError as exc:
+        exc.append_path_element(qualified_name(value, add_class_prefix=True))
+        if config.typecheck_fail_callback:
+            config.typecheck_fail_callback(exc, memo)
+        else:
+            raise
+
+    return value
+
+
+def check_argument_types(
+    func_name: str,
+    arguments: dict[str, tuple[Any, Any]],
+    memo: TypeCheckMemo,
+) -> Literal[True]:
+    if _suppression.type_checks_suppressed:
+        return True
+
+    for argname, (value, annotation) in arguments.items():
+        if annotation is NoReturn or annotation is Never:
+            exc = TypeCheckError(
+                f"{func_name}() was declared never to be called but it was"
+            )
+            if memo.config.typecheck_fail_callback:
+                memo.config.typecheck_fail_callback(exc, memo)
+            else:
+                raise exc
+
+        try:
+            check_type_internal(value, annotation, memo)
+        except TypeCheckError as exc:
+            qualname = qualified_name(value, add_class_prefix=True)
+            exc.append_path_element(f'argument "{argname}" ({qualname})')
+            if memo.config.typecheck_fail_callback:
+                memo.config.typecheck_fail_callback(exc, memo)
+            else:
+                raise
+
+    return True
+
+
+def check_return_type(
+    func_name: str,
+    retval: T,
+    annotation: Any,
+    memo: TypeCheckMemo,
+) -> T:
+    if _suppression.type_checks_suppressed:
+        return retval
+
+    if annotation is NoReturn or annotation is Never:
+        exc = TypeCheckError(f"{func_name}() was declared never to return but it did")
+        if memo.config.typecheck_fail_callback:
+            memo.config.typecheck_fail_callback(exc, memo)
+        else:
+            raise exc
+
+    try:
+        check_type_internal(retval, annotation, memo)
+    except TypeCheckError as exc:
+        # Allow NotImplemented if this is a binary magic method (__eq__() et al)
+        if retval is NotImplemented and annotation is bool:
+            # This does (and cannot) not check if it's actually a method
+            func_name = func_name.rsplit(".", 1)[-1]
+            if func_name in BINARY_MAGIC_METHODS:
+                return retval
+
+        qualname = qualified_name(retval, add_class_prefix=True)
+        exc.append_path_element(f"the return value ({qualname})")
+        if memo.config.typecheck_fail_callback:
+            memo.config.typecheck_fail_callback(exc, memo)
+        else:
+            raise
+
+    return retval
+
+
+def check_send_type(
+    func_name: str,
+    sendval: T,
+    annotation: Any,
+    memo: TypeCheckMemo,
+) -> T:
+    if _suppression.type_checks_suppressed:
+        return sendval
+
+    if annotation is NoReturn or annotation is Never:
+        exc = TypeCheckError(
+            f"{func_name}() was declared never to be sent a value to but it was"
+        )
+        if memo.config.typecheck_fail_callback:
+            memo.config.typecheck_fail_callback(exc, memo)
+        else:
+            raise exc
+
+    try:
+        check_type_internal(sendval, annotation, memo)
+    except TypeCheckError as exc:
+        qualname = qualified_name(sendval, add_class_prefix=True)
+        exc.append_path_element(f"the value sent to generator ({qualname})")
+        if memo.config.typecheck_fail_callback:
+            memo.config.typecheck_fail_callback(exc, memo)
+        else:
+            raise
+
+    return sendval
+
+
+def check_yield_type(
+    func_name: str,
+    yieldval: T,
+    annotation: Any,
+    memo: TypeCheckMemo,
+) -> T:
+    if _suppression.type_checks_suppressed:
+        return yieldval
+
+    if annotation is NoReturn or annotation is Never:
+        exc = TypeCheckError(f"{func_name}() was declared never to yield but it did")
+        if memo.config.typecheck_fail_callback:
+            memo.config.typecheck_fail_callback(exc, memo)
+        else:
+            raise exc
+
+    try:
+        check_type_internal(yieldval, annotation, memo)
+    except TypeCheckError as exc:
+        qualname = qualified_name(yieldval, add_class_prefix=True)
+        exc.append_path_element(f"the yielded value ({qualname})")
+        if memo.config.typecheck_fail_callback:
+            memo.config.typecheck_fail_callback(exc, memo)
+        else:
+            raise
+
+    return yieldval
+
+
+def check_variable_assignment(
+    value: object, varname: str, annotation: Any, memo: TypeCheckMemo
+) -> Any:
+    if _suppression.type_checks_suppressed:
+        return value
+
+    try:
+        check_type_internal(value, annotation, memo)
+    except TypeCheckError as exc:
+        qualname = qualified_name(value, add_class_prefix=True)
+        exc.append_path_element(f"value assigned to {varname} ({qualname})")
+        if memo.config.typecheck_fail_callback:
+            memo.config.typecheck_fail_callback(exc, memo)
+        else:
+            raise
+
+    return value
+
+
+def check_multi_variable_assignment(
+    value: Any, targets: list[dict[str, Any]], memo: TypeCheckMemo
+) -> Any:
+    if max(len(target) for target in targets) == 1:
+        iterated_values = [value]
+    else:
+        iterated_values = list(value)
+
+    if not _suppression.type_checks_suppressed:
+        for expected_types in targets:
+            value_index = 0
+            for ann_index, (varname, expected_type) in enumerate(
+                expected_types.items()
+            ):
+                if varname.startswith("*"):
+                    varname = varname[1:]
+                    keys_left = len(expected_types) - 1 - ann_index
+                    next_value_index = len(iterated_values) - keys_left
+                    obj: object = iterated_values[value_index:next_value_index]
+                    value_index = next_value_index
+                else:
+                    obj = iterated_values[value_index]
+                    value_index += 1
+
+                try:
+                    check_type_internal(obj, expected_type, memo)
+                except TypeCheckError as exc:
+                    qualname = qualified_name(obj, add_class_prefix=True)
+                    exc.append_path_element(f"value assigned to {varname} ({qualname})")
+                    if memo.config.typecheck_fail_callback:
+                        memo.config.typecheck_fail_callback(exc, memo)
+                    else:
+                        raise
+
+    return iterated_values[0] if len(iterated_values) == 1 else iterated_values
+
+
+def warn_on_error(exc: TypeCheckError, memo: TypeCheckMemo) -> None:
+    """
+    Emit a warning on a type mismatch.
+
+    This is intended to be used as an error handler in
+    :attr:`TypeCheckConfiguration.typecheck_fail_callback`.
+
+    """
+    warnings.warn(TypeCheckWarning(str(exc)), stacklevel=get_stacklevel())
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/_importhook.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/_importhook.py
new file mode 100644
index 0000000000000000000000000000000000000000..8590540a5a2ace23bbfc8272aca8e066740474a6
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/_importhook.py
@@ -0,0 +1,213 @@
+from __future__ import annotations
+
+import ast
+import sys
+import types
+from collections.abc import Callable, Iterable
+from importlib.abc import MetaPathFinder
+from importlib.machinery import ModuleSpec, SourceFileLoader
+from importlib.util import cache_from_source, decode_source
+from inspect import isclass
+from os import PathLike
+from types import CodeType, ModuleType, TracebackType
+from typing import Sequence, TypeVar
+from unittest.mock import patch
+
+from ._config import global_config
+from ._transformer import TypeguardTransformer
+
+if sys.version_info >= (3, 12):
+    from collections.abc import Buffer
+else:
+    from typing_extensions import Buffer
+
+if sys.version_info >= (3, 11):
+    from typing import ParamSpec
+else:
+    from typing_extensions import ParamSpec
+
+if sys.version_info >= (3, 10):
+    from importlib.metadata import PackageNotFoundError, version
+else:
+    from importlib_metadata import PackageNotFoundError, version
+
+try:
+    OPTIMIZATION = "typeguard" + "".join(version("typeguard").split(".")[:3])
+except PackageNotFoundError:
+    OPTIMIZATION = "typeguard"
+
+P = ParamSpec("P")
+T = TypeVar("T")
+
+
+# The name of this function is magical
+def _call_with_frames_removed(
+    f: Callable[P, T], *args: P.args, **kwargs: P.kwargs
+) -> T:
+    return f(*args, **kwargs)
+
+
+def optimized_cache_from_source(path: str, debug_override: bool | None = None) -> str:
+    return cache_from_source(path, debug_override, optimization=OPTIMIZATION)
+
+
+class TypeguardLoader(SourceFileLoader):
+    @staticmethod
+    def source_to_code(
+        data: Buffer | str | ast.Module | ast.Expression | ast.Interactive,
+        path: Buffer | str | PathLike[str] = "",
+    ) -> CodeType:
+        if isinstance(data, (ast.Module, ast.Expression, ast.Interactive)):
+            tree = data
+        else:
+            if isinstance(data, str):
+                source = data
+            else:
+                source = decode_source(data)
+
+            tree = _call_with_frames_removed(
+                ast.parse,
+                source,
+                path,
+                "exec",
+            )
+
+        tree = TypeguardTransformer().visit(tree)
+        ast.fix_missing_locations(tree)
+
+        if global_config.debug_instrumentation and sys.version_info >= (3, 9):
+            print(
+                f"Source code of {path!r} after instrumentation:\n"
+                "----------------------------------------------",
+                file=sys.stderr,
+            )
+            print(ast.unparse(tree), file=sys.stderr)
+            print("----------------------------------------------", file=sys.stderr)
+
+        return _call_with_frames_removed(
+            compile, tree, path, "exec", 0, dont_inherit=True
+        )
+
+    def exec_module(self, module: ModuleType) -> None:
+        # Use a custom optimization marker – the import lock should make this monkey
+        # patch safe
+        with patch(
+            "importlib._bootstrap_external.cache_from_source",
+            optimized_cache_from_source,
+        ):
+            super().exec_module(module)
+
+
+class TypeguardFinder(MetaPathFinder):
+    """
+    Wraps another path finder and instruments the module with
+    :func:`@typechecked ` if :meth:`should_instrument` returns
+    ``True``.
+
+    Should not be used directly, but rather via :func:`~.install_import_hook`.
+
+    .. versionadded:: 2.6
+    """
+
+    def __init__(self, packages: list[str] | None, original_pathfinder: MetaPathFinder):
+        self.packages = packages
+        self._original_pathfinder = original_pathfinder
+
+    def find_spec(
+        self,
+        fullname: str,
+        path: Sequence[str] | None,
+        target: types.ModuleType | None = None,
+    ) -> ModuleSpec | None:
+        if self.should_instrument(fullname):
+            spec = self._original_pathfinder.find_spec(fullname, path, target)
+            if spec is not None and isinstance(spec.loader, SourceFileLoader):
+                spec.loader = TypeguardLoader(spec.loader.name, spec.loader.path)
+                return spec
+
+        return None
+
+    def should_instrument(self, module_name: str) -> bool:
+        """
+        Determine whether the module with the given name should be instrumented.
+
+        :param module_name: full name of the module that is about to be imported (e.g.
+            ``xyz.abc``)
+
+        """
+        if self.packages is None:
+            return True
+
+        for package in self.packages:
+            if module_name == package or module_name.startswith(package + "."):
+                return True
+
+        return False
+
+
+class ImportHookManager:
+    """
+    A handle that can be used to uninstall the Typeguard import hook.
+    """
+
+    def __init__(self, hook: MetaPathFinder):
+        self.hook = hook
+
+    def __enter__(self) -> None:
+        pass
+
+    def __exit__(
+        self,
+        exc_type: type[BaseException],
+        exc_val: BaseException,
+        exc_tb: TracebackType,
+    ) -> None:
+        self.uninstall()
+
+    def uninstall(self) -> None:
+        """Uninstall the import hook."""
+        try:
+            sys.meta_path.remove(self.hook)
+        except ValueError:
+            pass  # already removed
+
+
+def install_import_hook(
+    packages: Iterable[str] | None = None,
+    *,
+    cls: type[TypeguardFinder] = TypeguardFinder,
+) -> ImportHookManager:
+    """
+    Install an import hook that instruments functions for automatic type checking.
+
+    This only affects modules loaded **after** this hook has been installed.
+
+    :param packages: an iterable of package names to instrument, or ``None`` to
+        instrument all packages
+    :param cls: a custom meta path finder class
+    :return: a context manager that uninstalls the hook on exit (or when you call
+        ``.uninstall()``)
+
+    .. versionadded:: 2.6
+
+    """
+    if packages is None:
+        target_packages: list[str] | None = None
+    elif isinstance(packages, str):
+        target_packages = [packages]
+    else:
+        target_packages = list(packages)
+
+    for finder in sys.meta_path:
+        if (
+            isclass(finder)
+            and finder.__name__ == "PathFinder"
+            and hasattr(finder, "find_spec")
+        ):
+            break
+    else:
+        raise RuntimeError("Cannot find a PathFinder in sys.meta_path")
+
+    hook = cls(target_packages, finder)
+    sys.meta_path.insert(0, hook)
+    return ImportHookManager(hook)
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/_memo.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/_memo.py
new file mode 100644
index 0000000000000000000000000000000000000000..1d0d80c66d788e2f8f5e24ce14249319c54054c0
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/_memo.py
@@ -0,0 +1,48 @@
+from __future__ import annotations
+
+from typing import Any
+
+from typeguard._config import TypeCheckConfiguration, global_config
+
+
+class TypeCheckMemo:
+    """
+    Contains information necessary for type checkers to do their work.
+
+    .. attribute:: globals
+       :type: dict[str, Any]
+
+        Dictionary of global variables to use for resolving forward references.
+
+    .. attribute:: locals
+       :type: dict[str, Any]
+
+        Dictionary of local variables to use for resolving forward references.
+
+    .. attribute:: self_type
+       :type: type | None
+
+        When running type checks within an instance method or class method, this is the
+        class object that the first argument (usually named ``self`` or ``cls``) refers
+        to.
+
+    .. attribute:: config
+       :type: TypeCheckConfiguration
+
+         Contains the configuration for a particular set of type checking operations.
+    """
+
+    __slots__ = "globals", "locals", "self_type", "config"
+
+    def __init__(
+        self,
+        globals: dict[str, Any],
+        locals: dict[str, Any],
+        *,
+        self_type: type | None = None,
+        config: TypeCheckConfiguration = global_config,
+    ):
+        self.globals = globals
+        self.locals = locals
+        self.self_type = self_type
+        self.config = config
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/_pytest_plugin.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/_pytest_plugin.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b2f494ec7dbe5333c2798c0fcebb83cc3ac9907
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/_pytest_plugin.py
@@ -0,0 +1,127 @@
+from __future__ import annotations
+
+import sys
+import warnings
+from typing import TYPE_CHECKING, Any, Literal
+
+from typeguard._config import CollectionCheckStrategy, ForwardRefPolicy, global_config
+from typeguard._exceptions import InstrumentationWarning
+from typeguard._importhook import install_import_hook
+from typeguard._utils import qualified_name, resolve_reference
+
+if TYPE_CHECKING:
+    from pytest import Config, Parser
+
+
+def pytest_addoption(parser: Parser) -> None:
+    def add_ini_option(
+        opt_type: (
+            Literal["string", "paths", "pathlist", "args", "linelist", "bool"] | None
+        ),
+    ) -> None:
+        parser.addini(
+            group.options[-1].names()[0][2:],
+            group.options[-1].attrs()["help"],
+            opt_type,
+        )
+
+    group = parser.getgroup("typeguard")
+    group.addoption(
+        "--typeguard-packages",
+        action="store",
+        help="comma separated name list of packages and modules to instrument for "
+        "type checking, or :all: to instrument all modules loaded after typeguard",
+    )
+    add_ini_option("linelist")
+
+    group.addoption(
+        "--typeguard-debug-instrumentation",
+        action="store_true",
+        help="print all instrumented code to stderr",
+    )
+    add_ini_option("bool")
+
+    group.addoption(
+        "--typeguard-typecheck-fail-callback",
+        action="store",
+        help=(
+            "a module:varname (e.g. typeguard:warn_on_error) reference to a function "
+            "that is called (with the exception, and memo object as arguments) to "
+            "handle a TypeCheckError"
+        ),
+    )
+    add_ini_option("string")
+
+    group.addoption(
+        "--typeguard-forward-ref-policy",
+        action="store",
+        choices=list(ForwardRefPolicy.__members__),
+        help=(
+            "determines how to deal with unresolveable forward references in type "
+            "annotations"
+        ),
+    )
+    add_ini_option("string")
+
+    group.addoption(
+        "--typeguard-collection-check-strategy",
+        action="store",
+        choices=list(CollectionCheckStrategy.__members__),
+        help="determines how thoroughly to check collections (list, dict, etc)",
+    )
+    add_ini_option("string")
+
+
+def pytest_configure(config: Config) -> None:
+    def getoption(name: str) -> Any:
+        return config.getoption(name.replace("-", "_")) or config.getini(name)
+
+    packages: list[str] | None = []
+    if packages_option := config.getoption("typeguard_packages"):
+        packages = [pkg.strip() for pkg in packages_option.split(",")]
+    elif packages_ini := config.getini("typeguard-packages"):
+        packages = packages_ini
+
+    if packages:
+        if packages == [":all:"]:
+            packages = None
+        else:
+            already_imported_packages = sorted(
+                package for package in packages if package in sys.modules
+            )
+            if already_imported_packages:
+                warnings.warn(
+                    f"typeguard cannot check these packages because they are already "
+                    f"imported: {', '.join(already_imported_packages)}",
+                    InstrumentationWarning,
+                    stacklevel=1,
+                )
+
+        install_import_hook(packages=packages)
+
+    debug_option = getoption("typeguard-debug-instrumentation")
+    if debug_option:
+        global_config.debug_instrumentation = True
+
+    fail_callback_option = getoption("typeguard-typecheck-fail-callback")
+    if fail_callback_option:
+        callback = resolve_reference(fail_callback_option)
+        if not callable(callback):
+            raise TypeError(
+                f"{fail_callback_option} ({qualified_name(callback.__class__)}) is not "
+                f"a callable"
+            )
+
+        global_config.typecheck_fail_callback = callback
+
+    forward_ref_policy_option = getoption("typeguard-forward-ref-policy")
+    if forward_ref_policy_option:
+        forward_ref_policy = ForwardRefPolicy.__members__[forward_ref_policy_option]
+        global_config.forward_ref_policy = forward_ref_policy
+
+    collection_check_strategy_option = getoption("typeguard-collection-check-strategy")
+    if collection_check_strategy_option:
+        collection_check_strategy = CollectionCheckStrategy.__members__[
+            collection_check_strategy_option
+        ]
+        global_config.collection_check_strategy = collection_check_strategy
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/_suppression.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/_suppression.py
new file mode 100644
index 0000000000000000000000000000000000000000..bbbfbfbe8ef364d45a1db581562c73b323819b84
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/_suppression.py
@@ -0,0 +1,86 @@
+from __future__ import annotations
+
+import sys
+from collections.abc import Callable, Generator
+from contextlib import contextmanager
+from functools import update_wrapper
+from threading import Lock
+from typing import ContextManager, TypeVar, overload
+
+if sys.version_info >= (3, 10):
+    from typing import ParamSpec
+else:
+    from typing_extensions import ParamSpec
+
+P = ParamSpec("P")
+T = TypeVar("T")
+
+type_checks_suppressed = 0
+type_checks_suppress_lock = Lock()
+
+
+@overload
+def suppress_type_checks(func: Callable[P, T]) -> Callable[P, T]: ...
+
+
+@overload
+def suppress_type_checks() -> ContextManager[None]: ...
+
+
+def suppress_type_checks(
+    func: Callable[P, T] | None = None,
+) -> Callable[P, T] | ContextManager[None]:
+    """
+    Temporarily suppress all type checking.
+
+    This function has two operating modes, based on how it's used:
+
+    #. as a context manager (``with suppress_type_checks(): ...``)
+    #. as a decorator (``@suppress_type_checks``)
+
+    When used as a context manager, :func:`check_type` and any automatically
+    instrumented functions skip the actual type checking. These context managers can be
+    nested.
+
+    When used as a decorator, all type checking is suppressed while the function is
+    running.
+
+    Type checking will resume once no more context managers are active and no decorated
+    functions are running.
+
+    Both operating modes are thread-safe.
+
+    """
+
+    def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
+        global type_checks_suppressed
+
+        with type_checks_suppress_lock:
+            type_checks_suppressed += 1
+
+        assert func is not None
+        try:
+            return func(*args, **kwargs)
+        finally:
+            with type_checks_suppress_lock:
+                type_checks_suppressed -= 1
+
+    def cm() -> Generator[None, None, None]:
+        global type_checks_suppressed
+
+        with type_checks_suppress_lock:
+            type_checks_suppressed += 1
+
+        try:
+            yield
+        finally:
+            with type_checks_suppress_lock:
+                type_checks_suppressed -= 1
+
+    if func is None:
+        # Context manager mode
+        return contextmanager(cm)()
+    else:
+        # Decorator mode
+        update_wrapper(wrapper, func)
+        return wrapper
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/_transformer.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/_transformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..13ac3630e6c29ca32b2a84a3e6a85665b439cedf
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/_transformer.py
@@ -0,0 +1,1229 @@
+from __future__ import annotations
+
+import ast
+import builtins
+import sys
+import typing
+from ast import (
+    AST,
+    Add,
+    AnnAssign,
+    Assign,
+    AsyncFunctionDef,
+    Attribute,
+    AugAssign,
+    BinOp,
+    BitAnd,
+    BitOr,
+    BitXor,
+    Call,
+    ClassDef,
+    Constant,
+    Dict,
+    Div,
+    Expr,
+    Expression,
+    FloorDiv,
+    FunctionDef,
+    If,
+    Import,
+    ImportFrom,
+    Index,
+    List,
+    Load,
+    LShift,
+    MatMult,
+    Mod,
+    Module,
+    Mult,
+    Name,
+    NamedExpr,
+    NodeTransformer,
+    NodeVisitor,
+    Pass,
+    Pow,
+    Return,
+    RShift,
+    Starred,
+    Store,
+    Sub,
+    Subscript,
+    Tuple,
+    Yield,
+    YieldFrom,
+    alias,
+    copy_location,
+    expr,
+    fix_missing_locations,
+    keyword,
+    walk,
+)
+from collections import defaultdict
+from collections.abc import Generator, Sequence
+from contextlib import contextmanager
+from copy import deepcopy
+from dataclasses import dataclass, field
+from typing import Any, ClassVar, cast, overload
+
+generator_names = (
+    "typing.Generator",
+    "collections.abc.Generator",
+    "typing.Iterator",
+    "collections.abc.Iterator",
+    "typing.Iterable",
+    "collections.abc.Iterable",
+    "typing.AsyncIterator",
+    "collections.abc.AsyncIterator",
+    "typing.AsyncIterable",
+    "collections.abc.AsyncIterable",
+    "typing.AsyncGenerator",
+    "collections.abc.AsyncGenerator",
+)
+anytype_names = (
+    "typing.Any",
+    "typing_extensions.Any",
+)
+literal_names = (
+    "typing.Literal",
+    "typing_extensions.Literal",
+)
+annotated_names = (
+    "typing.Annotated",
+    "typing_extensions.Annotated",
+)
+ignore_decorators = (
+    "typing.no_type_check",
+    "typeguard.typeguard_ignore",
+)
+aug_assign_functions = {
+    Add: "iadd",
+    Sub: "isub",
+    Mult: "imul",
+    MatMult: "imatmul",
+    Div: "itruediv",
+    FloorDiv: "ifloordiv",
+    Mod: "imod",
+    Pow: "ipow",
+    LShift: "ilshift",
+    RShift: "irshift",
+    BitAnd: "iand",
+    BitXor: "ixor",
+    BitOr: "ior",
+}
+
+
+@dataclass
+class TransformMemo:
+    node: Module | ClassDef | FunctionDef | AsyncFunctionDef | None
+    parent: TransformMemo | None
+    path: tuple[str, ...]
+    joined_path: Constant = field(init=False)
+    return_annotation: expr | None = None
+    yield_annotation: expr | None = None
+    send_annotation: expr | None = None
+    is_async: bool = False
+    local_names: set[str] = field(init=False, default_factory=set)
+    imported_names: dict[str, str] = field(init=False, default_factory=dict)
+    ignored_names: set[str] = field(init=False, default_factory=set)
+    load_names: defaultdict[str, dict[str, Name]] = field(
+        init=False, default_factory=lambda: defaultdict(dict)
+    )
+    has_yield_expressions: bool = field(init=False, default=False)
+    has_return_expressions: bool = field(init=False, default=False)
+    memo_var_name: Name | None = field(init=False, default=None)
+    should_instrument: bool = field(init=False, default=True)
+    variable_annotations: dict[str, expr] = field(init=False, default_factory=dict)
+    configuration_overrides: dict[str, Any] = field(init=False, default_factory=dict)
+    code_inject_index: int = field(init=False, default=0)
+
+    def __post_init__(self) -> None:
+        elements: list[str] = []
+        memo = self
+        while isinstance(memo.node, (ClassDef, FunctionDef, AsyncFunctionDef)):
+            elements.insert(0, memo.node.name)
+            if not memo.parent:
+                break
+
+            memo = memo.parent
+            if isinstance(memo.node, (FunctionDef, AsyncFunctionDef)):
+                elements.insert(0, "")
+
+        self.joined_path = Constant(".".join(elements))
+
+        # Figure out where to insert instrumentation code
+        if self.node:
+            for index, child in enumerate(self.node.body):
+                if isinstance(child, ImportFrom) and child.module == "__future__":
+                    # (module only) __future__ imports must come first
+                    continue
+                elif (
+                    isinstance(child, Expr)
+                    and isinstance(child.value, Constant)
+                    and isinstance(child.value.value, str)
+                ):
+                    continue  # docstring
+
+                self.code_inject_index = index
+                break
+
+    def get_unused_name(self, name: str) -> str:
+        memo: TransformMemo | None = self
+        while memo is not None:
+            if name in memo.local_names:
+                memo = self
+                name += "_"
+            else:
+                memo = memo.parent
+
+        self.local_names.add(name)
+        return name
+
+    def is_ignored_name(self, expression: expr | Expr | None) -> bool:
+        top_expression = (
+            expression.value if isinstance(expression, Expr) else expression
+        )
+
+        if isinstance(top_expression, Attribute) and isinstance(
+            top_expression.value, Name
+        ):
+            name = top_expression.value.id
+        elif isinstance(top_expression, Name):
+            name = top_expression.id
+        else:
+            return False
+
+        memo: TransformMemo | None = self
+        while memo is not None:
+            if name in memo.ignored_names:
+                return True
+
+            memo = memo.parent
+
+        return False
+
+    def get_memo_name(self) -> Name:
+        if not self.memo_var_name:
+            self.memo_var_name = Name(id="memo", ctx=Load())
+
+        return self.memo_var_name
+
+    def get_import(self, module: str, name: str) -> Name:
+        if module in self.load_names and name in self.load_names[module]:
+            return self.load_names[module][name]
+
+        qualified_name = f"{module}.{name}"
+        if name in self.imported_names and self.imported_names[name] == qualified_name:
+            return Name(id=name, ctx=Load())
+
+        alias = self.get_unused_name(name)
+        node = self.load_names[module][name] = Name(id=alias, ctx=Load())
+        self.imported_names[name] = qualified_name
+        return node
+
+    def insert_imports(self, node: Module | FunctionDef | AsyncFunctionDef) -> None:
+        """Insert imports needed by injected code."""
+        if not self.load_names:
+            return
+
+        # Insert imports after any "from __future__ ..." imports and any docstring
+        for modulename, names in self.load_names.items():
+            aliases = [
+                alias(orig_name, new_name.id if orig_name != new_name.id else None)
+                for orig_name, new_name in sorted(names.items())
+            ]
+            node.body.insert(self.code_inject_index, ImportFrom(modulename, aliases, 0))
+
+    def name_matches(self, expression: expr | Expr | None, *names: str) -> bool:
+        if expression is None:
+            return False
+
+        path: list[str] = []
+        top_expression = (
+            expression.value if isinstance(expression, Expr) else expression
+        )
+
+        if isinstance(top_expression, Subscript):
+            top_expression = top_expression.value
+        elif isinstance(top_expression, Call):
+            top_expression = top_expression.func
+
+        while isinstance(top_expression, Attribute):
+            path.insert(0, top_expression.attr)
+            top_expression = top_expression.value
+
+        if not isinstance(top_expression, Name):
+            return False
+
+        if top_expression.id in self.imported_names:
+            translated = self.imported_names[top_expression.id]
+        elif hasattr(builtins, top_expression.id):
+            translated = "builtins." + top_expression.id
+        else:
+            translated = top_expression.id
+
+        path.insert(0, translated)
+        joined_path = ".".join(path)
+        if joined_path in names:
+            return True
+        elif self.parent:
+            return self.parent.name_matches(expression, *names)
+        else:
+            return False
+
+    def get_config_keywords(self) -> list[keyword]:
+        if self.parent and isinstance(self.parent.node, ClassDef):
+            overrides = self.parent.configuration_overrides.copy()
+        else:
+            overrides = {}
+
+        overrides.update(self.configuration_overrides)
+        return [keyword(key, value) for key, value in overrides.items()]
+
+
+class NameCollector(NodeVisitor):
+    def __init__(self) -> None:
+        self.names: set[str] = set()
+
+    def visit_Import(self, node: Import) -> None:
+        for name in node.names:
+            self.names.add(name.asname or name.name)
+
+    def visit_ImportFrom(self, node: ImportFrom) -> None:
+        for name in node.names:
+            self.names.add(name.asname or name.name)
+
+    def visit_Assign(self, node: Assign) -> None:
+        for target in node.targets:
+            if isinstance(target, Name):
+                self.names.add(target.id)
+
+    def visit_NamedExpr(self, node: NamedExpr) -> Any:
+        if isinstance(node.target, Name):
+            self.names.add(node.target.id)
+
+    def visit_FunctionDef(self, node: FunctionDef) -> None:
+        pass
+
+    def visit_ClassDef(self, node: ClassDef) -> None:
+        pass
+
+
+class GeneratorDetector(NodeVisitor):
+    """Detects if a function node is a generator function."""
+
+    contains_yields: bool = False
+    in_root_function: bool = False
+
+    def visit_Yield(self, node: Yield) -> Any:
+        self.contains_yields = True
+
+    def visit_YieldFrom(self, node: YieldFrom) -> Any:
+        self.contains_yields = True
+
+    def visit_ClassDef(self, node: ClassDef) -> Any:
+        pass
+
+    def visit_FunctionDef(self, node: FunctionDef | AsyncFunctionDef) -> Any:
+        if not self.in_root_function:
+            self.in_root_function = True
+            self.generic_visit(node)
+            self.in_root_function = False
+
+    def visit_AsyncFunctionDef(self, node: AsyncFunctionDef) -> Any:
+        self.visit_FunctionDef(node)
+
+
+class AnnotationTransformer(NodeTransformer):
+    type_substitutions: ClassVar[dict[str, tuple[str, str]]] = {
+        "builtins.dict": ("typing", "Dict"),
+        "builtins.list": ("typing", "List"),
+        "builtins.tuple": ("typing", "Tuple"),
+        "builtins.set": ("typing", "Set"),
+        "builtins.frozenset": ("typing", "FrozenSet"),
+    }
+
+    def __init__(self, transformer: TypeguardTransformer):
+        self.transformer = transformer
+        self._memo = transformer._memo
+        self._level = 0
+
+    def visit(self, node: AST) -> Any:
+        # Don't process Literals
+        if isinstance(node, expr) and self._memo.name_matches(node, *literal_names):
+            return node
+
+        self._level += 1
+        new_node = super().visit(node)
+        self._level -= 1
+
+        if isinstance(new_node, Expression) and not hasattr(new_node, "body"):
+            return None
+
+        # Return None if this new node matches a variation of typing.Any
+        if (
+            self._level == 0
+            and isinstance(new_node, expr)
+            and self._memo.name_matches(new_node, *anytype_names)
+        ):
+            return None
+
+        return new_node
+
+    def visit_BinOp(self, node: BinOp) -> Any:
+        self.generic_visit(node)
+
+        if isinstance(node.op, BitOr):
+            # If either branch of the BinOp has been transformed to `None`, it means
+            # that a type in the union was ignored, so the entire annotation should e
+            # ignored
+            if not hasattr(node, "left") or not hasattr(node, "right"):
+                return None
+
+            # Return Any if either side is Any
+            if self._memo.name_matches(node.left, *anytype_names):
+                return node.left
+            elif self._memo.name_matches(node.right, *anytype_names):
+                return node.right
+
+            if sys.version_info < (3, 10):
+                union_name = self.transformer._get_import("typing", "Union")
+                return Subscript(
+                    value=union_name,
+                    slice=Index(
+                        Tuple(elts=[node.left, node.right], ctx=Load()), ctx=Load()
+                    ),
+                    ctx=Load(),
+                )
+
+        return node
+
+    def visit_Attribute(self, node: Attribute) -> Any:
+        if self._memo.is_ignored_name(node):
+            return None
+
+        return node
+
+    def visit_Subscript(self, node: Subscript) -> Any:
+        if self._memo.is_ignored_name(node.value):
+            return None
+
+        # The subscript of typing(_extensions).Literal can be any arbitrary string, so
+        # don't try to evaluate it as code
+        if node.slice:
+            if isinstance(node.slice, Index):
+                # Python 3.8
+                slice_value = node.slice.value  # type: ignore[attr-defined]
+            else:
+                slice_value = node.slice
+
+            if isinstance(slice_value, Tuple):
+                if self._memo.name_matches(node.value, *annotated_names):
+                    # Only treat the first argument to typing.Annotated as a potential
+                    # forward reference
+                    items = cast(
+                        typing.List[expr],
+                        [self.visit(slice_value.elts[0])] + slice_value.elts[1:],
+                    )
+                else:
+                    items = cast(
+                        typing.List[expr],
+                        [self.visit(item) for item in slice_value.elts],
+                    )
+
+                # If this is a Union and any of the items is Any, erase the entire
+                # annotation
+                if self._memo.name_matches(node.value, "typing.Union") and any(
+                    item is None
+                    or (
+                        isinstance(item, expr)
+                        and self._memo.name_matches(item, *anytype_names)
+                    )
+                    for item in items
+                ):
+                    return None
+
+                # If all items in the subscript were Any, erase the subscript entirely
+                if all(item is None for item in items):
+                    return node.value
+
+                for index, item in enumerate(items):
+                    if item is None:
+                        items[index] = self.transformer._get_import("typing", "Any")
+
+                slice_value.elts = items
+            else:
+                self.generic_visit(node)
+
+                # If the transformer erased the slice entirely, just return the node
+                # value without the subscript (unless it's Optional, in which case erase
+                # the node entirely
+                if self._memo.name_matches(
+                    node.value, "typing.Optional"
+                ) and not hasattr(node, "slice"):
+                    return None
+                if sys.version_info >= (3, 9) and not hasattr(node, "slice"):
+                    return node.value
+                elif sys.version_info < (3, 9) and not hasattr(node.slice, "value"):
+                    return node.value
+
+        return node
+
+    def visit_Name(self, node: Name) -> Any:
+        if self._memo.is_ignored_name(node):
+            return None
+
+        if sys.version_info < (3, 9):
+            for typename, substitute in self.type_substitutions.items():
+                if self._memo.name_matches(node, typename):
+                    new_node = self.transformer._get_import(*substitute)
+                    return copy_location(new_node, node)
+
+        return node
+
+    def visit_Call(self, node: Call) -> Any:
+        # Don't recurse into calls
+        return node
+
+    def visit_Constant(self, node: Constant) -> Any:
+        if isinstance(node.value, str):
+            expression = ast.parse(node.value, mode="eval")
+            new_node = self.visit(expression)
+            if new_node:
+                return copy_location(new_node.body, node)
+            else:
+                return None
+
+        return node
+
+
+class TypeguardTransformer(NodeTransformer):
+    def __init__(
+        self, target_path: Sequence[str] | None = None, target_lineno: int | None = None
+    ) -> None:
+        self._target_path = tuple(target_path) if target_path else None
+        self._memo = self._module_memo = TransformMemo(None, None, ())
+        self.names_used_in_annotations: set[str] = set()
+        self.target_node: FunctionDef | AsyncFunctionDef | None = None
+        self.target_lineno = target_lineno
+
+    def generic_visit(self, node: AST) -> AST:
+        has_non_empty_body_initially = bool(getattr(node, "body", None))
+        initial_type = type(node)
+
+        node = super().generic_visit(node)
+
+        if (
+            type(node) is initial_type
+            and has_non_empty_body_initially
+            and hasattr(node, "body")
+            and not node.body
+        ):
+            # If we have still the same node type after transformation
+            # but we've optimised it's body away, we add a `pass` statement.
+            node.body = [Pass()]
+
+        return node
+
+    @contextmanager
+    def _use_memo(
+        self, node: ClassDef | FunctionDef | AsyncFunctionDef
+    ) -> Generator[None, Any, None]:
+        new_memo = TransformMemo(node, self._memo, self._memo.path + (node.name,))
+        old_memo = self._memo
+        self._memo = new_memo
+
+        if isinstance(node, (FunctionDef, AsyncFunctionDef)):
+            new_memo.should_instrument = (
+                self._target_path is None or new_memo.path == self._target_path
+            )
+            if new_memo.should_instrument:
+                # Check if the function is a generator function
+                detector = GeneratorDetector()
+                detector.visit(node)
+
+                # Extract yield, send and return types where possible from a subscripted
+                # annotation like Generator[int, str, bool]
+                return_annotation = deepcopy(node.returns)
+                if detector.contains_yields and new_memo.name_matches(
+                    return_annotation, *generator_names
+                ):
+                    if isinstance(return_annotation, Subscript):
+                        annotation_slice = return_annotation.slice
+
+                        # Python < 3.9
+                        if isinstance(annotation_slice, Index):
+                            annotation_slice = (
+                                annotation_slice.value  # type: ignore[attr-defined]
+                            )
+
+                        if isinstance(annotation_slice, Tuple):
+                            items = annotation_slice.elts
+                        else:
+                            items = [annotation_slice]
+
+                        if len(items) > 0:
+                            new_memo.yield_annotation = self._convert_annotation(
+                                items[0]
+                            )
+
+                        if len(items) > 1:
+                            new_memo.send_annotation = self._convert_annotation(
+                                items[1]
+                            )
+
+                        if len(items) > 2:
+                            new_memo.return_annotation = self._convert_annotation(
+                                items[2]
+                            )
+                else:
+                    new_memo.return_annotation = self._convert_annotation(
+                        return_annotation
+                    )
+
+        if isinstance(node, AsyncFunctionDef):
+            new_memo.is_async = True
+
+        yield
+        self._memo = old_memo
+
+    def _get_import(self, module: str, name: str) -> Name:
+        memo = self._memo if self._target_path else self._module_memo
+        return memo.get_import(module, name)
+
+    @overload
+    def _convert_annotation(self, annotation: None) -> None: ...
+
+    @overload
+    def _convert_annotation(self, annotation: expr) -> expr: ...
+
+    def _convert_annotation(self, annotation: expr | None) -> expr | None:
+        if annotation is None:
+            return None
+
+        # Convert PEP 604 unions (x | y) and generic built-in collections where
+        # necessary, and undo forward references
+        new_annotation = cast(expr, AnnotationTransformer(self).visit(annotation))
+        if isinstance(new_annotation, expr):
+            new_annotation = ast.copy_location(new_annotation, annotation)
+
+            # Store names used in the annotation
+            names = {node.id for node in walk(new_annotation) if isinstance(node, Name)}
+            self.names_used_in_annotations.update(names)
+
+        return new_annotation
+
+    def visit_Name(self, node: Name) -> Name:
+        self._memo.local_names.add(node.id)
+        return node
+
+    def visit_Module(self, node: Module) -> Module:
+        self._module_memo = self._memo = TransformMemo(node, None, ())
+        self.generic_visit(node)
+        self._module_memo.insert_imports(node)
+
+        fix_missing_locations(node)
+        return node
+
+    def visit_Import(self, node: Import) -> Import:
+        for name in node.names:
+            self._memo.local_names.add(name.asname or name.name)
+            self._memo.imported_names[name.asname or name.name] = name.name
+
+        return node
+
+    def visit_ImportFrom(self, node: ImportFrom) -> ImportFrom:
+        for name in node.names:
+            if name.name != "*":
+                alias = name.asname or name.name
+                self._memo.local_names.add(alias)
+                self._memo.imported_names[alias] = f"{node.module}.{name.name}"
+
+        return node
+
+    def visit_ClassDef(self, node: ClassDef) -> ClassDef | None:
+        self._memo.local_names.add(node.name)
+
+        # Eliminate top level classes not belonging to the target path
+        if (
+            self._target_path is not None
+            and not self._memo.path
+            and node.name != self._target_path[0]
+        ):
+            return None
+
+        with self._use_memo(node):
+            for decorator in node.decorator_list.copy():
+                if self._memo.name_matches(decorator, "typeguard.typechecked"):
+                    # Remove the decorator to prevent duplicate instrumentation
+                    node.decorator_list.remove(decorator)
+
+                    # Store any configuration overrides
+                    if isinstance(decorator, Call) and decorator.keywords:
+                        self._memo.configuration_overrides.update(
+                            {kw.arg: kw.value for kw in decorator.keywords if kw.arg}
+                        )
+
+            self.generic_visit(node)
+            return node
+
+    def visit_FunctionDef(
+        self, node: FunctionDef | AsyncFunctionDef
+    ) -> FunctionDef | AsyncFunctionDef | None:
+        """
+        Injects type checks for function arguments, and for a return of None if the
+        function is annotated to return something else than Any or None, and the body
+        ends without an explicit "return".
+
+        """
+        self._memo.local_names.add(node.name)
+
+        # Eliminate top level functions not belonging to the target path
+        if (
+            self._target_path is not None
+            and not self._memo.path
+            and node.name != self._target_path[0]
+        ):
+            return None
+
+        # Skip instrumentation if we're instrumenting the whole module and the function
+        # contains either @no_type_check or @typeguard_ignore
+        if self._target_path is None:
+            for decorator in node.decorator_list:
+                if self._memo.name_matches(decorator, *ignore_decorators):
+                    return node
+
+        with self._use_memo(node):
+            arg_annotations: dict[str, Any] = {}
+            if self._target_path is None or self._memo.path == self._target_path:
+                # Find line number we're supposed to match against
+                if node.decorator_list:
+                    first_lineno = node.decorator_list[0].lineno
+                else:
+                    first_lineno = node.lineno
+
+                for decorator in node.decorator_list.copy():
+                    if self._memo.name_matches(decorator, "typing.overload"):
+                        # Remove overloads entirely
+                        return None
+                    elif self._memo.name_matches(decorator, "typeguard.typechecked"):
+                        # Remove the decorator to prevent duplicate instrumentation
+                        node.decorator_list.remove(decorator)
+
+                        # Store any configuration overrides
+                        if isinstance(decorator, Call) and decorator.keywords:
+                            self._memo.configuration_overrides = {
+                                kw.arg: kw.value for kw in decorator.keywords if kw.arg
+                            }
+
+                if self.target_lineno == first_lineno:
+                    assert self.target_node is None
+                    self.target_node = node
+                    if node.decorator_list:
+                        self.target_lineno = node.decorator_list[0].lineno
+                    else:
+                        self.target_lineno = node.lineno
+
+                all_args = node.args.args + node.args.kwonlyargs + node.args.posonlyargs
+
+                # Ensure that any type shadowed by the positional or keyword-only
+                # argument names are ignored in this function
+                for arg in all_args:
+                    self._memo.ignored_names.add(arg.arg)
+
+                # Ensure that any type shadowed by the variable positional argument name
+                # (e.g. "args" in *args) is ignored this function
+                if node.args.vararg:
+                    self._memo.ignored_names.add(node.args.vararg.arg)
+
+                # Ensure that any type shadowed by the variable keywrod argument name
+                # (e.g. "kwargs" in *kwargs) is ignored this function
+                if node.args.kwarg:
+                    self._memo.ignored_names.add(node.args.kwarg.arg)
+
+                for arg in all_args:
+                    annotation = self._convert_annotation(deepcopy(arg.annotation))
+                    if annotation:
+                        arg_annotations[arg.arg] = annotation
+
+                if node.args.vararg:
+                    annotation_ = self._convert_annotation(node.args.vararg.annotation)
+                    if annotation_:
+                        if sys.version_info >= (3, 9):
+                            container = Name("tuple", ctx=Load())
+                        else:
+                            container = self._get_import("typing", "Tuple")
+
+                        subscript_slice: Tuple | Index = Tuple(
+                            [
+                                annotation_,
+                                Constant(Ellipsis),
+                            ],
+                            ctx=Load(),
+                        )
+                        if sys.version_info < (3, 9):
+                            subscript_slice = Index(subscript_slice, ctx=Load())
+
+                        arg_annotations[node.args.vararg.arg] = Subscript(
+                            container, subscript_slice, ctx=Load()
+                        )
+
+                if node.args.kwarg:
+                    annotation_ = self._convert_annotation(node.args.kwarg.annotation)
+                    if annotation_:
+                        if sys.version_info >= (3, 9):
+                            container = Name("dict", ctx=Load())
+                        else:
+                            container = self._get_import("typing", "Dict")
+
+                        subscript_slice = Tuple(
+                            [
+                                Name("str", ctx=Load()),
+                                annotation_,
+                            ],
+                            ctx=Load(),
+                        )
+                        if sys.version_info < (3, 9):
+                            subscript_slice = Index(subscript_slice, ctx=Load())
+
+                        arg_annotations[node.args.kwarg.arg] = Subscript(
+                            container, subscript_slice, ctx=Load()
+                        )
+
+                if arg_annotations:
+                    self._memo.variable_annotations.update(arg_annotations)
+
+            self.generic_visit(node)
+
+            if arg_annotations:
+                annotations_dict = Dict(
+                    keys=[Constant(key) for key in arg_annotations.keys()],
+                    values=[
+                        Tuple([Name(key, ctx=Load()), annotation], ctx=Load())
+                        for key, annotation in arg_annotations.items()
+                    ],
+                )
+                func_name = self._get_import(
+                    "typeguard._functions", "check_argument_types"
+                )
+                args = [
+                    self._memo.joined_path,
+                    annotations_dict,
+                    self._memo.get_memo_name(),
+                ]
+                node.body.insert(
+                    self._memo.code_inject_index, Expr(Call(func_name, args, []))
+                )
+
+            # Add a checked "return None" to the end if there's no explicit return
+            # Skip if the return annotation is None or Any
+            if (
+                self._memo.return_annotation
+                and (not self._memo.is_async or not self._memo.has_yield_expressions)
+                and not isinstance(node.body[-1], Return)
+                and (
+                    not isinstance(self._memo.return_annotation, Constant)
+                    or self._memo.return_annotation.value is not None
+                )
+            ):
+                func_name = self._get_import(
+                    "typeguard._functions", "check_return_type"
+                )
+                return_node = Return(
+                    Call(
+                        func_name,
+                        [
+                            self._memo.joined_path,
+                            Constant(None),
+                            self._memo.return_annotation,
+                            self._memo.get_memo_name(),
+                        ],
+                        [],
+                    )
+                )
+
+                # Replace a placeholder "pass" at the end
+                if isinstance(node.body[-1], Pass):
+                    copy_location(return_node, node.body[-1])
+                    del node.body[-1]
+
+                node.body.append(return_node)
+
+            # Insert code to create the call memo, if it was ever needed for this
+            # function
+            if self._memo.memo_var_name:
+                memo_kwargs: dict[str, Any] = {}
+                if self._memo.parent and isinstance(self._memo.parent.node, ClassDef):
+                    for decorator in node.decorator_list:
+                        if (
+                            isinstance(decorator, Name)
+                            and decorator.id == "staticmethod"
+                        ):
+                            break
+                        elif (
+                            isinstance(decorator, Name)
+                            and decorator.id == "classmethod"
+                        ):
+                            memo_kwargs["self_type"] = Name(
+                                id=node.args.args[0].arg, ctx=Load()
+                            )
+                            break
+                    else:
+                        if node.args.args:
+                            if node.name == "__new__":
+                                memo_kwargs["self_type"] = Name(
+                                    id=node.args.args[0].arg, ctx=Load()
+                                )
+                            else:
+                                memo_kwargs["self_type"] = Attribute(
+                                    Name(id=node.args.args[0].arg, ctx=Load()),
+                                    "__class__",
+                                    ctx=Load(),
+                                )
+
+                # Construct the function reference
+                # Nested functions get special treatment: the function name is added
+                # to free variables (and the closure of the resulting function)
+                names: list[str] = [node.name]
+                memo = self._memo.parent
+                while memo:
+                    if isinstance(memo.node, (FunctionDef, AsyncFunctionDef)):
+                        # This is a nested function. Use the function name as-is.
+                        del names[:-1]
+                        break
+                    elif not isinstance(memo.node, ClassDef):
+                        break
+
+                    names.insert(0, memo.node.name)
+                    memo = memo.parent
+
+                config_keywords = self._memo.get_config_keywords()
+                if config_keywords:
+                    memo_kwargs["config"] = Call(
+                        self._get_import("dataclasses", "replace"),
+                        [self._get_import("typeguard._config", "global_config")],
+                        config_keywords,
+                    )
+
+                self._memo.memo_var_name.id = self._memo.get_unused_name("memo")
+                memo_store_name = Name(id=self._memo.memo_var_name.id, ctx=Store())
+                globals_call = Call(Name(id="globals", ctx=Load()), [], [])
+                locals_call = Call(Name(id="locals", ctx=Load()), [], [])
+                memo_expr = Call(
+                    self._get_import("typeguard", "TypeCheckMemo"),
+                    [globals_call, locals_call],
+                    [keyword(key, value) for key, value in memo_kwargs.items()],
+                )
+                node.body.insert(
+                    self._memo.code_inject_index,
+                    Assign([memo_store_name], memo_expr),
+                )
+
+                self._memo.insert_imports(node)
+
+                # Special case the __new__() method to create a local alias from the
+                # class name to the first argument (usually "cls")
+                if (
+                    isinstance(node, FunctionDef)
+                    and node.args
+                    and self._memo.parent is not None
+                    and isinstance(self._memo.parent.node, ClassDef)
+                    and node.name == "__new__"
+                ):
+                    first_args_expr = Name(node.args.args[0].arg, ctx=Load())
+                    cls_name = Name(self._memo.parent.node.name, ctx=Store())
+                    node.body.insert(
+                        self._memo.code_inject_index,
+                        Assign([cls_name], first_args_expr),
+                    )
+
+                # Rmove any placeholder "pass" at the end
+                if isinstance(node.body[-1], Pass):
+                    del node.body[-1]
+
+        return node
+
+    def visit_AsyncFunctionDef(
+        self, node: AsyncFunctionDef
+    ) -> FunctionDef | AsyncFunctionDef | None:
+        return self.visit_FunctionDef(node)
+
+    def visit_Return(self, node: Return) -> Return:
+        """This injects type checks into "return" statements."""
+        self.generic_visit(node)
+        if (
+            self._memo.return_annotation
+            and self._memo.should_instrument
+            and not self._memo.is_ignored_name(self._memo.return_annotation)
+        ):
+            func_name = self._get_import("typeguard._functions", "check_return_type")
+            old_node = node
+            retval = old_node.value or Constant(None)
+            node = Return(
+                Call(
+                    func_name,
+                    [
+                        self._memo.joined_path,
+                        retval,
+                        self._memo.return_annotation,
+                        self._memo.get_memo_name(),
+                    ],
+                    [],
+                )
+            )
+            copy_location(node, old_node)
+
+        return node
+
+    def visit_Yield(self, node: Yield) -> Yield | Call:
+        """
+        This injects type checks into "yield" expressions, checking both the yielded
+        value and the value sent back to the generator, when appropriate.
+
+        """
+        self._memo.has_yield_expressions = True
+        self.generic_visit(node)
+
+        if (
+            self._memo.yield_annotation
+            and self._memo.should_instrument
+            and not self._memo.is_ignored_name(self._memo.yield_annotation)
+        ):
+            func_name = self._get_import("typeguard._functions", "check_yield_type")
+            yieldval = node.value or Constant(None)
+            node.value = Call(
+                func_name,
+                [
+                    self._memo.joined_path,
+                    yieldval,
+                    self._memo.yield_annotation,
+                    self._memo.get_memo_name(),
+                ],
+                [],
+            )
+
+        if (
+            self._memo.send_annotation
+            and self._memo.should_instrument
+            and not self._memo.is_ignored_name(self._memo.send_annotation)
+        ):
+            func_name = self._get_import("typeguard._functions", "check_send_type")
+            old_node = node
+            call_node = Call(
+                func_name,
+                [
+                    self._memo.joined_path,
+                    old_node,
+                    self._memo.send_annotation,
+                    self._memo.get_memo_name(),
+                ],
+                [],
+            )
+            copy_location(call_node, old_node)
+            return call_node
+
+        return node
+
+    def visit_AnnAssign(self, node: AnnAssign) -> Any:
+        """
+        This injects a type check into a local variable annotation-assignment within a
+        function body.
+
+        """
+        self.generic_visit(node)
+
+        if (
+            isinstance(self._memo.node, (FunctionDef, AsyncFunctionDef))
+            and node.annotation
+            and isinstance(node.target, Name)
+        ):
+            self._memo.ignored_names.add(node.target.id)
+            annotation = self._convert_annotation(deepcopy(node.annotation))
+            if annotation:
+                self._memo.variable_annotations[node.target.id] = annotation
+                if node.value:
+                    func_name = self._get_import(
+                        "typeguard._functions", "check_variable_assignment"
+                    )
+                    node.value = Call(
+                        func_name,
+                        [
+                            node.value,
+                            Constant(node.target.id),
+                            annotation,
+                            self._memo.get_memo_name(),
+                        ],
+                        [],
+                    )
+
+        return node
+
+    def visit_Assign(self, node: Assign) -> Any:
+        """
+        This injects a type check into a local variable assignment within a function
+        body. The variable must have been annotated earlier in the function body.
+
+        """
+        self.generic_visit(node)
+
+        # Only instrument function-local assignments
+        if isinstance(self._memo.node, (FunctionDef, AsyncFunctionDef)):
+            targets: list[dict[Constant, expr | None]] = []
+            check_required = False
+            for target in node.targets:
+                elts: Sequence[expr]
+                if isinstance(target, Name):
+                    elts = [target]
+                elif isinstance(target, Tuple):
+                    elts = target.elts
+                else:
+                    continue
+
+                annotations_: dict[Constant, expr | None] = {}
+                for exp in elts:
+                    prefix = ""
+                    if isinstance(exp, Starred):
+                        exp = exp.value
+                        prefix = "*"
+
+                    if isinstance(exp, Name):
+                        self._memo.ignored_names.add(exp.id)
+                        name = prefix + exp.id
+                        annotation = self._memo.variable_annotations.get(exp.id)
+                        if annotation:
+                            annotations_[Constant(name)] = annotation
+                            check_required = True
+                        else:
+                            annotations_[Constant(name)] = None
+
+                targets.append(annotations_)
+
+            if check_required:
+                # Replace missing annotations with typing.Any
+                for item in targets:
+                    for key, expression in item.items():
+                        if expression is None:
+                            item[key] = self._get_import("typing", "Any")
+
+                if len(targets) == 1 and len(targets[0]) == 1:
+                    func_name = self._get_import(
+                        "typeguard._functions", "check_variable_assignment"
+                    )
+                    target_varname = next(iter(targets[0]))
+                    node.value = Call(
+                        func_name,
+                        [
+                            node.value,
+                            target_varname,
+                            targets[0][target_varname],
+                            self._memo.get_memo_name(),
+                        ],
+                        [],
+                    )
+                elif targets:
+                    func_name = self._get_import(
+                        "typeguard._functions", "check_multi_variable_assignment"
+                    )
+                    targets_arg = List(
+                        [
+                            Dict(keys=list(target), values=list(target.values()))
+                            for target in targets
+                        ],
+                        ctx=Load(),
+                    )
+                    node.value = Call(
+                        func_name,
+                        [node.value, targets_arg, self._memo.get_memo_name()],
+                        [],
+                    )
+
+        return node
+
+    def visit_NamedExpr(self, node: NamedExpr) -> Any:
+        """This injects a type check into an assignment expression (a := foo())."""
+        self.generic_visit(node)
+
+        # Only instrument function-local assignments
+        if isinstance(self._memo.node, (FunctionDef, AsyncFunctionDef)) and isinstance(
+            node.target, Name
+        ):
+            self._memo.ignored_names.add(node.target.id)
+
+            # Bail out if no matching annotation is found
+            annotation = self._memo.variable_annotations.get(node.target.id)
+            if annotation is None:
+                return node
+
+            func_name = self._get_import(
+                "typeguard._functions", "check_variable_assignment"
+            )
+            node.value = Call(
+                func_name,
+                [
+                    node.value,
+                    Constant(node.target.id),
+                    annotation,
+                    self._memo.get_memo_name(),
+                ],
+                [],
+            )
+
+        return node
+
+    def visit_AugAssign(self, node: AugAssign) -> Any:
+        """
+        This injects a type check into an augmented assignment expression (a += 1).
+
+        """
+        self.generic_visit(node)
+
+        # Only instrument function-local assignments
+        if isinstance(self._memo.node, (FunctionDef, AsyncFunctionDef)) and isinstance(
+            node.target, Name
+        ):
+            # Bail out if no matching annotation is found
+            annotation = self._memo.variable_annotations.get(node.target.id)
+            if annotation is None:
+                return node
+
+            # Bail out if the operator is not found (newer Python version?)
+            try:
+                operator_func_name = aug_assign_functions[node.op.__class__]
+            except KeyError:
+                return node
+
+            operator_func = self._get_import("operator", operator_func_name)
+            operator_call = Call(
+                operator_func, [Name(node.target.id, ctx=Load()), node.value], []
+            )
+            check_call = Call(
+                self._get_import("typeguard._functions", "check_variable_assignment"),
+                [
+                    operator_call,
+                    Constant(node.target.id),
+                    annotation,
+                    self._memo.get_memo_name(),
+                ],
+                [],
+            )
+            return Assign(targets=[node.target], value=check_call)
+
+        return node
+
+    def visit_If(self, node: If) -> Any:
+        """
+        This blocks names from being collected from a module-level
+        "if typing.TYPE_CHECKING:" block, so that they won't be type checked.
+
+        """
+        self.generic_visit(node)
+
+        if (
+            self._memo is self._module_memo
+            and isinstance(node.test, Name)
+            and self._memo.name_matches(node.test, "typing.TYPE_CHECKING")
+        ):
+            collector = NameCollector()
+            collector.visit(node)
+            self._memo.ignored_names.update(collector.names)
+
+        return node
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/_union_transformer.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/_union_transformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..19617e6af5a0fd691b9d3793f9486ade2868d5bf
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/_union_transformer.py
@@ -0,0 +1,55 @@
+"""
+Transforms lazily evaluated PEP 604 unions into typing.Unions, for compatibility with
+Python versions older than 3.10.
+"""
+
+from __future__ import annotations
+
+from ast import (
+    BinOp,
+    BitOr,
+    Index,
+    Load,
+    Name,
+    NodeTransformer,
+    Subscript,
+    fix_missing_locations,
+    parse,
+)
+from ast import Tuple as ASTTuple
+from types import CodeType
+from typing import Any, Dict, FrozenSet, List, Set, Tuple, Union
+
+type_substitutions = {
+    "dict": Dict,
+    "list": List,
+    "tuple": Tuple,
+    "set": Set,
+    "frozenset": FrozenSet,
+    "Union": Union,
+}
+
+
+class UnionTransformer(NodeTransformer):
+    def __init__(self, union_name: Name | None = None):
+        self.union_name = union_name or Name(id="Union", ctx=Load())
+
+    def visit_BinOp(self, node: BinOp) -> Any:
+        self.generic_visit(node)
+        if isinstance(node.op, BitOr):
+            return Subscript(
+                value=self.union_name,
+                slice=Index(
+                    ASTTuple(elts=[node.left, node.right], ctx=Load()), ctx=Load()
+                ),
+                ctx=Load(),
+            )
+
+        return node
+
+
+def compile_type_hint(hint: str) -> CodeType:
+    parsed = parse(hint, "", "eval")
+    UnionTransformer().visit(parsed)
+    fix_missing_locations(parsed)
+    return compile(parsed, "", "eval", flags=0)
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/_utils.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..9bcc8417f8773115de078d307682b457af848052
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/_utils.py
@@ -0,0 +1,173 @@
+from __future__ import annotations
+
+import inspect
+import sys
+from importlib import import_module
+from inspect import currentframe
+from types import CodeType, FrameType, FunctionType
+from typing import TYPE_CHECKING, Any, Callable, ForwardRef, Union, cast, final
+from weakref import WeakValueDictionary
+
+if TYPE_CHECKING:
+    from ._memo import TypeCheckMemo
+
+if sys.version_info >= (3, 13):
+    from typing import get_args, get_origin
+
+    def evaluate_forwardref(forwardref: ForwardRef, memo: TypeCheckMemo) -> Any:
+        return forwardref._evaluate(
+            memo.globals, memo.locals, type_params=(), recursive_guard=frozenset()
+        )
+
+elif sys.version_info >= (3, 10):
+    from typing import get_args, get_origin
+
+    def evaluate_forwardref(forwardref: ForwardRef, memo: TypeCheckMemo) -> Any:
+        return forwardref._evaluate(
+            memo.globals, memo.locals, recursive_guard=frozenset()
+        )
+
+else:
+    from typing_extensions import get_args, get_origin
+
+    evaluate_extra_args: tuple[frozenset[Any], ...] = (
+        (frozenset(),) if sys.version_info >= (3, 9) else ()
+    )
+
+    def evaluate_forwardref(forwardref: ForwardRef, memo: TypeCheckMemo) -> Any:
+        from ._union_transformer import compile_type_hint, type_substitutions
+
+        if not forwardref.__forward_evaluated__:
+            forwardref.__forward_code__ = compile_type_hint(forwardref.__forward_arg__)
+
+        try:
+            return forwardref._evaluate(memo.globals, memo.locals, *evaluate_extra_args)
+        except NameError:
+            if sys.version_info < (3, 10):
+                # Try again, with the type substitutions (list -> List etc.) in place
+                new_globals = memo.globals.copy()
+                new_globals.setdefault("Union", Union)
+                if sys.version_info < (3, 9):
+                    new_globals.update(type_substitutions)
+
+                return forwardref._evaluate(
+                    new_globals, memo.locals or new_globals, *evaluate_extra_args
+                )
+
+            raise
+
+
+_functions_map: WeakValueDictionary[CodeType, FunctionType] = WeakValueDictionary()
+
+
+def get_type_name(type_: Any) -> str:
+    name: str
+    for attrname in "__name__", "_name", "__forward_arg__":
+        candidate = getattr(type_, attrname, None)
+        if isinstance(candidate, str):
+            name = candidate
+            break
+    else:
+        origin = get_origin(type_)
+        candidate = getattr(origin, "_name", None)
+        if candidate is None:
+            candidate = type_.__class__.__name__.strip("_")
+
+        if isinstance(candidate, str):
+            name = candidate
+        else:
+            return "(unknown)"
+
+    args = get_args(type_)
+    if args:
+        if name == "Literal":
+            formatted_args = ", ".join(repr(arg) for arg in args)
+        else:
+            formatted_args = ", ".join(get_type_name(arg) for arg in args)
+
+        name += f"[{formatted_args}]"
+
+    module = getattr(type_, "__module__", None)
+    if module and module not in (None, "typing", "typing_extensions", "builtins"):
+        name = module + "." + name
+
+    return name
+
+
+def qualified_name(obj: Any, *, add_class_prefix: bool = False) -> str:
+    """
+    Return the qualified name (e.g. package.module.Type) for the given object.
+
+    Builtins and types from the :mod:`typing` package get special treatment by having
+    the module name stripped from the generated name.
+
+    """
+    if obj is None:
+        return "None"
+    elif inspect.isclass(obj):
+        prefix = "class " if add_class_prefix else ""
+        type_ = obj
+    else:
+        prefix = ""
+        type_ = type(obj)
+
+    module = type_.__module__
+    qualname = type_.__qualname__
+    name = qualname if module in ("typing", "builtins") else f"{module}.{qualname}"
+    return prefix + name
+
+
+def function_name(func: Callable[..., Any]) -> str:
+    """
+    Return the qualified name of the given function.
+
+    Builtins and types from the :mod:`typing` package get special treatment by having
+    the module name stripped from the generated name.
+
+    """
+    # For partial functions and objects with __call__ defined, __qualname__ does not
+    # exist
+    module = getattr(func, "__module__", "")
+    qualname = (module + ".") if module not in ("builtins", "") else ""
+    return qualname + getattr(func, "__qualname__", repr(func))
+
+
+def resolve_reference(reference: str) -> Any:
+    modulename, varname = reference.partition(":")[::2]
+    if not modulename or not varname:
+        raise ValueError(f"{reference!r} is not a module:varname reference")
+
+    obj = import_module(modulename)
+    for attr in varname.split("."):
+        obj = getattr(obj, attr)
+
+    return obj
+
+
+def is_method_of(obj: object, cls: type) -> bool:
+    return (
+        inspect.isfunction(obj)
+        and obj.__module__ == cls.__module__
+        and obj.__qualname__.startswith(cls.__qualname__ + ".")
+    )
+
+
+def get_stacklevel() -> int:
+    level = 1
+    frame = cast(FrameType, currentframe()).f_back
+    while frame and frame.f_globals.get("__name__", "").startswith("typeguard."):
+        level += 1
+        frame = frame.f_back
+
+    return level
+
+
+@final
+class Unset:
+    __slots__ = ()
+
+    def __repr__(self) -> str:
+        return ""
+
+
+unset = Unset()
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/py.typed b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typeguard/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typing_extensions-4.12.2.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typing_extensions-4.12.2.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typing_extensions-4.12.2.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typing_extensions-4.12.2.dist-info/LICENSE b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typing_extensions-4.12.2.dist-info/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..f26bcf4d2de6eb136e31006ca3ab447d5e488adf
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typing_extensions-4.12.2.dist-info/LICENSE
@@ -0,0 +1,279 @@
+A. HISTORY OF THE SOFTWARE
+==========================
+
+Python was created in the early 1990s by Guido van Rossum at Stichting
+Mathematisch Centrum (CWI, see https://www.cwi.nl) in the Netherlands
+as a successor of a language called ABC.  Guido remains Python's
+principal author, although it includes many contributions from others.
+
+In 1995, Guido continued his work on Python at the Corporation for
+National Research Initiatives (CNRI, see https://www.cnri.reston.va.us)
+in Reston, Virginia where he released several versions of the
+software.
+
+In May 2000, Guido and the Python core development team moved to
+BeOpen.com to form the BeOpen PythonLabs team.  In October of the same
+year, the PythonLabs team moved to Digital Creations, which became
+Zope Corporation.  In 2001, the Python Software Foundation (PSF, see
+https://www.python.org/psf/) was formed, a non-profit organization
+created specifically to own Python-related Intellectual Property.
+Zope Corporation was a sponsoring member of the PSF.
+
+All Python releases are Open Source (see https://opensource.org for
+the Open Source Definition).  Historically, most, but not all, Python
+releases have also been GPL-compatible; the table below summarizes
+the various releases.
+
+    Release         Derived     Year        Owner       GPL-
+                    from                                compatible? (1)
+
+    0.9.0 thru 1.2              1991-1995   CWI         yes
+    1.3 thru 1.5.2  1.2         1995-1999   CNRI        yes
+    1.6             1.5.2       2000        CNRI        no
+    2.0             1.6         2000        BeOpen.com  no
+    1.6.1           1.6         2001        CNRI        yes (2)
+    2.1             2.0+1.6.1   2001        PSF         no
+    2.0.1           2.0+1.6.1   2001        PSF         yes
+    2.1.1           2.1+2.0.1   2001        PSF         yes
+    2.1.2           2.1.1       2002        PSF         yes
+    2.1.3           2.1.2       2002        PSF         yes
+    2.2 and above   2.1.1       2001-now    PSF         yes
+
+Footnotes:
+
+(1) GPL-compatible doesn't mean that we're distributing Python under
+    the GPL.  All Python licenses, unlike the GPL, let you distribute
+    a modified version without making your changes open source.  The
+    GPL-compatible licenses make it possible to combine Python with
+    other software that is released under the GPL; the others don't.
+
+(2) According to Richard Stallman, 1.6.1 is not GPL-compatible,
+    because its license has a choice of law clause.  According to
+    CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1
+    is "not incompatible" with the GPL.
+
+Thanks to the many outside volunteers who have worked under Guido's
+direction to make these releases possible.
+
+
+B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON
+===============================================================
+
+Python software and documentation are licensed under the
+Python Software Foundation License Version 2.
+
+Starting with Python 3.8.6, examples, recipes, and other code in
+the documentation are dual licensed under the PSF License Version 2
+and the Zero-Clause BSD license.
+
+Some software incorporated into Python is under different licenses.
+The licenses are listed with code falling under that license.
+
+
+PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
+--------------------------------------------
+
+1. This LICENSE AGREEMENT is between the Python Software Foundation
+("PSF"), and the Individual or Organization ("Licensee") accessing and
+otherwise using this software ("Python") in source or binary form and
+its associated documentation.
+
+2. Subject to the terms and conditions of this License Agreement, PSF hereby
+grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
+analyze, test, perform and/or display publicly, prepare derivative works,
+distribute, and otherwise use Python alone or in any derivative version,
+provided, however, that PSF's License Agreement and PSF's notice of copyright,
+i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
+2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Python Software Foundation;
+All Rights Reserved" are retained in Python alone or in any derivative version
+prepared by Licensee.
+
+3. In the event Licensee prepares a derivative work that is based on
+or incorporates Python or any part thereof, and wants to make
+the derivative work available to others as provided herein, then
+Licensee hereby agrees to include in any such work a brief summary of
+the changes made to Python.
+
+4. PSF is making Python available to Licensee on an "AS IS"
+basis.  PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
+IMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
+DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
+FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
+INFRINGE ANY THIRD PARTY RIGHTS.
+
+5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
+FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
+A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
+OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
+
+6. This License Agreement will automatically terminate upon a material
+breach of its terms and conditions.
+
+7. Nothing in this License Agreement shall be deemed to create any
+relationship of agency, partnership, or joint venture between PSF and
+Licensee.  This License Agreement does not grant permission to use PSF
+trademarks or trade name in a trademark sense to endorse or promote
+products or services of Licensee, or any third party.
+
+8. By copying, installing or otherwise using Python, Licensee
+agrees to be bound by the terms and conditions of this License
+Agreement.
+
+
+BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0
+-------------------------------------------
+
+BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
+
+1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an
+office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the
+Individual or Organization ("Licensee") accessing and otherwise using
+this software in source or binary form and its associated
+documentation ("the Software").
+
+2. Subject to the terms and conditions of this BeOpen Python License
+Agreement, BeOpen hereby grants Licensee a non-exclusive,
+royalty-free, world-wide license to reproduce, analyze, test, perform
+and/or display publicly, prepare derivative works, distribute, and
+otherwise use the Software alone or in any derivative version,
+provided, however, that the BeOpen Python License is retained in the
+Software, alone or in any derivative version prepared by Licensee.
+
+3. BeOpen is making the Software available to Licensee on an "AS IS"
+basis.  BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
+IMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND
+DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
+FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT
+INFRINGE ANY THIRD PARTY RIGHTS.
+
+4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE
+SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
+AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY
+DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
+
+5. This License Agreement will automatically terminate upon a material
+breach of its terms and conditions.
+
+6. This License Agreement shall be governed by and interpreted in all
+respects by the law of the State of California, excluding conflict of
+law provisions.  Nothing in this License Agreement shall be deemed to
+create any relationship of agency, partnership, or joint venture
+between BeOpen and Licensee.  This License Agreement does not grant
+permission to use BeOpen trademarks or trade names in a trademark
+sense to endorse or promote products or services of Licensee, or any
+third party.  As an exception, the "BeOpen Python" logos available at
+http://www.pythonlabs.com/logos.html may be used according to the
+permissions granted on that web page.
+
+7. By copying, installing or otherwise using the software, Licensee
+agrees to be bound by the terms and conditions of this License
+Agreement.
+
+
+CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
+---------------------------------------
+
+1. This LICENSE AGREEMENT is between the Corporation for National
+Research Initiatives, having an office at 1895 Preston White Drive,
+Reston, VA 20191 ("CNRI"), and the Individual or Organization
+("Licensee") accessing and otherwise using Python 1.6.1 software in
+source or binary form and its associated documentation.
+
+2. Subject to the terms and conditions of this License Agreement, CNRI
+hereby grants Licensee a nonexclusive, royalty-free, world-wide
+license to reproduce, analyze, test, perform and/or display publicly,
+prepare derivative works, distribute, and otherwise use Python 1.6.1
+alone or in any derivative version, provided, however, that CNRI's
+License Agreement and CNRI's notice of copyright, i.e., "Copyright (c)
+1995-2001 Corporation for National Research Initiatives; All Rights
+Reserved" are retained in Python 1.6.1 alone or in any derivative
+version prepared by Licensee.  Alternately, in lieu of CNRI's License
+Agreement, Licensee may substitute the following text (omitting the
+quotes): "Python 1.6.1 is made available subject to the terms and
+conditions in CNRI's License Agreement.  This Agreement together with
+Python 1.6.1 may be located on the internet using the following
+unique, persistent identifier (known as a handle): 1895.22/1013.  This
+Agreement may also be obtained from a proxy server on the internet
+using the following URL: http://hdl.handle.net/1895.22/1013".
+
+3. In the event Licensee prepares a derivative work that is based on
+or incorporates Python 1.6.1 or any part thereof, and wants to make
+the derivative work available to others as provided herein, then
+Licensee hereby agrees to include in any such work a brief summary of
+the changes made to Python 1.6.1.
+
+4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS"
+basis.  CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
+IMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND
+DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
+FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT
+INFRINGE ANY THIRD PARTY RIGHTS.
+
+5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
+1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
+A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,
+OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
+
+6. This License Agreement will automatically terminate upon a material
+breach of its terms and conditions.
+
+7. This License Agreement shall be governed by the federal
+intellectual property law of the United States, including without
+limitation the federal copyright law, and, to the extent such
+U.S. federal law does not apply, by the law of the Commonwealth of
+Virginia, excluding Virginia's conflict of law provisions.
+Notwithstanding the foregoing, with regard to derivative works based
+on Python 1.6.1 that incorporate non-separable material that was
+previously distributed under the GNU General Public License (GPL), the
+law of the Commonwealth of Virginia shall govern this License
+Agreement only as to issues arising under or with respect to
+Paragraphs 4, 5, and 7 of this License Agreement.  Nothing in this
+License Agreement shall be deemed to create any relationship of
+agency, partnership, or joint venture between CNRI and Licensee.  This
+License Agreement does not grant permission to use CNRI trademarks or
+trade name in a trademark sense to endorse or promote products or
+services of Licensee, or any third party.
+
+8. By clicking on the "ACCEPT" button where indicated, or by copying,
+installing or otherwise using Python 1.6.1, Licensee agrees to be
+bound by the terms and conditions of this License Agreement.
+
+        ACCEPT
+
+
+CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
+--------------------------------------------------
+
+Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam,
+The Netherlands.  All rights reserved.
+
+Permission to use, copy, modify, and distribute this software and its
+documentation for any purpose and without fee is hereby granted,
+provided that the above copyright notice appear in all copies and that
+both that copyright notice and this permission notice appear in
+supporting documentation, and that the name of Stichting Mathematisch
+Centrum or CWI not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
+THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
+FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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.
+
+ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION
+----------------------------------------------------------------------
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
+REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
+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.
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typing_extensions-4.12.2.dist-info/METADATA b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typing_extensions-4.12.2.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..f15e2b387737b14e013a83b32a766fe4eb0da611
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typing_extensions-4.12.2.dist-info/METADATA
@@ -0,0 +1,67 @@
+Metadata-Version: 2.1
+Name: typing_extensions
+Version: 4.12.2
+Summary: Backported and Experimental Type Hints for Python 3.8+
+Keywords: annotations,backport,checker,checking,function,hinting,hints,type,typechecking,typehinting,typehints,typing
+Author-email: "Guido van Rossum, Jukka Lehtosalo, Łukasz Langa, Michael Lee" 
+Requires-Python: >=3.8
+Description-Content-Type: text/markdown
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Environment :: Console
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: Python Software Foundation License
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3 :: Only
+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
+Project-URL: Bug Tracker, https://github.com/python/typing_extensions/issues
+Project-URL: Changes, https://github.com/python/typing_extensions/blob/main/CHANGELOG.md
+Project-URL: Documentation, https://typing-extensions.readthedocs.io/
+Project-URL: Home, https://github.com/python/typing_extensions
+Project-URL: Q & A, https://github.com/python/typing/discussions
+Project-URL: Repository, https://github.com/python/typing_extensions
+
+# Typing Extensions
+
+[![Chat at https://gitter.im/python/typing](https://badges.gitter.im/python/typing.svg)](https://gitter.im/python/typing)
+
+[Documentation](https://typing-extensions.readthedocs.io/en/latest/#) –
+[PyPI](https://pypi.org/project/typing-extensions/)
+
+## Overview
+
+The `typing_extensions` module serves two related purposes:
+
+- Enable use of new type system features on older Python versions. For example,
+  `typing.TypeGuard` is new in Python 3.10, but `typing_extensions` allows
+  users on previous Python versions to use it too.
+- Enable experimentation with new type system PEPs before they are accepted and
+  added to the `typing` module.
+
+`typing_extensions` is treated specially by static type checkers such as
+mypy and pyright. Objects defined in `typing_extensions` are treated the same
+way as equivalent forms in `typing`.
+
+`typing_extensions` uses
+[Semantic Versioning](https://semver.org/). The
+major version will be incremented only for backwards-incompatible changes.
+Therefore, it's safe to depend
+on `typing_extensions` like this: `typing_extensions >=x.y, <(x+1)`,
+where `x.y` is the first version that includes all features you need.
+
+## Included items
+
+See [the documentation](https://typing-extensions.readthedocs.io/en/latest/#) for a
+complete listing of module contents.
+
+## Contributing
+
+See [CONTRIBUTING.md](https://github.com/python/typing_extensions/blob/main/CONTRIBUTING.md)
+for how to contribute to `typing_extensions`.
+
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typing_extensions-4.12.2.dist-info/RECORD b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typing_extensions-4.12.2.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..bc7b45334dd59e2c386632c238648ed3cb5031bb
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typing_extensions-4.12.2.dist-info/RECORD
@@ -0,0 +1,7 @@
+__pycache__/typing_extensions.cpython-312.pyc,,
+typing_extensions-4.12.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+typing_extensions-4.12.2.dist-info/LICENSE,sha256=Oy-B_iHRgcSZxZolbI4ZaEVdZonSaaqFNzv7avQdo78,13936
+typing_extensions-4.12.2.dist-info/METADATA,sha256=BeUQIa8cnYbrjWx-N8TOznM9UGW5Gm2DicVpDtRA8W0,3018
+typing_extensions-4.12.2.dist-info/RECORD,,
+typing_extensions-4.12.2.dist-info/WHEEL,sha256=EZbGkh7Ie4PoZfRQ8I0ZuP9VklN_TvcZ6DSE5Uar4z4,81
+typing_extensions.py,sha256=gwekpyG9DVG3lxWKX4ni8u7nk3We5slG98mA9F3DJQw,134451
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typing_extensions-4.12.2.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typing_extensions-4.12.2.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..3b5e64b5e6c4a210201d1676a891fd57b15cda99
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typing_extensions-4.12.2.dist-info/WHEEL
@@ -0,0 +1,4 @@
+Wheel-Version: 1.0
+Generator: flit 3.9.0
+Root-Is-Purelib: true
+Tag: py3-none-any
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/typing_extensions.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typing_extensions.py
new file mode 100644
index 0000000000000000000000000000000000000000..dec429ca8723950097217d2140dd8daccb064e2d
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/typing_extensions.py
@@ -0,0 +1,3641 @@
+import abc
+import collections
+import collections.abc
+import contextlib
+import functools
+import inspect
+import operator
+import sys
+import types as _types
+import typing
+import warnings
+
+__all__ = [
+    # Super-special typing primitives.
+    'Any',
+    'ClassVar',
+    'Concatenate',
+    'Final',
+    'LiteralString',
+    'ParamSpec',
+    'ParamSpecArgs',
+    'ParamSpecKwargs',
+    'Self',
+    'Type',
+    'TypeVar',
+    'TypeVarTuple',
+    'Unpack',
+
+    # ABCs (from collections.abc).
+    'Awaitable',
+    'AsyncIterator',
+    'AsyncIterable',
+    'Coroutine',
+    'AsyncGenerator',
+    'AsyncContextManager',
+    'Buffer',
+    'ChainMap',
+
+    # Concrete collection types.
+    'ContextManager',
+    'Counter',
+    'Deque',
+    'DefaultDict',
+    'NamedTuple',
+    'OrderedDict',
+    'TypedDict',
+
+    # Structural checks, a.k.a. protocols.
+    'SupportsAbs',
+    'SupportsBytes',
+    'SupportsComplex',
+    'SupportsFloat',
+    'SupportsIndex',
+    'SupportsInt',
+    'SupportsRound',
+
+    # One-off things.
+    'Annotated',
+    'assert_never',
+    'assert_type',
+    'clear_overloads',
+    'dataclass_transform',
+    'deprecated',
+    'Doc',
+    'get_overloads',
+    'final',
+    'get_args',
+    'get_origin',
+    'get_original_bases',
+    'get_protocol_members',
+    'get_type_hints',
+    'IntVar',
+    'is_protocol',
+    'is_typeddict',
+    'Literal',
+    'NewType',
+    'overload',
+    'override',
+    'Protocol',
+    'reveal_type',
+    'runtime',
+    'runtime_checkable',
+    'Text',
+    'TypeAlias',
+    'TypeAliasType',
+    'TypeGuard',
+    'TypeIs',
+    'TYPE_CHECKING',
+    'Never',
+    'NoReturn',
+    'ReadOnly',
+    'Required',
+    'NotRequired',
+
+    # Pure aliases, have always been in typing
+    'AbstractSet',
+    'AnyStr',
+    'BinaryIO',
+    'Callable',
+    'Collection',
+    'Container',
+    'Dict',
+    'ForwardRef',
+    'FrozenSet',
+    'Generator',
+    'Generic',
+    'Hashable',
+    'IO',
+    'ItemsView',
+    'Iterable',
+    'Iterator',
+    'KeysView',
+    'List',
+    'Mapping',
+    'MappingView',
+    'Match',
+    'MutableMapping',
+    'MutableSequence',
+    'MutableSet',
+    'NoDefault',
+    'Optional',
+    'Pattern',
+    'Reversible',
+    'Sequence',
+    'Set',
+    'Sized',
+    'TextIO',
+    'Tuple',
+    'Union',
+    'ValuesView',
+    'cast',
+    'no_type_check',
+    'no_type_check_decorator',
+]
+
+# for backward compatibility
+PEP_560 = True
+GenericMeta = type
+_PEP_696_IMPLEMENTED = sys.version_info >= (3, 13, 0, "beta")
+
+# The functions below are modified copies of typing internal helpers.
+# They are needed by _ProtocolMeta and they provide support for PEP 646.
+
+
+class _Sentinel:
+    def __repr__(self):
+        return ""
+
+
+_marker = _Sentinel()
+
+
+if sys.version_info >= (3, 10):
+    def _should_collect_from_parameters(t):
+        return isinstance(
+            t, (typing._GenericAlias, _types.GenericAlias, _types.UnionType)
+        )
+elif sys.version_info >= (3, 9):
+    def _should_collect_from_parameters(t):
+        return isinstance(t, (typing._GenericAlias, _types.GenericAlias))
+else:
+    def _should_collect_from_parameters(t):
+        return isinstance(t, typing._GenericAlias) and not t._special
+
+
+NoReturn = typing.NoReturn
+
+# Some unconstrained type variables.  These are used by the container types.
+# (These are not for export.)
+T = typing.TypeVar('T')  # Any type.
+KT = typing.TypeVar('KT')  # Key type.
+VT = typing.TypeVar('VT')  # Value type.
+T_co = typing.TypeVar('T_co', covariant=True)  # Any type covariant containers.
+T_contra = typing.TypeVar('T_contra', contravariant=True)  # Ditto contravariant.
+
+
+if sys.version_info >= (3, 11):
+    from typing import Any
+else:
+
+    class _AnyMeta(type):
+        def __instancecheck__(self, obj):
+            if self is Any:
+                raise TypeError("typing_extensions.Any cannot be used with isinstance()")
+            return super().__instancecheck__(obj)
+
+        def __repr__(self):
+            if self is Any:
+                return "typing_extensions.Any"
+            return super().__repr__()
+
+    class Any(metaclass=_AnyMeta):
+        """Special type indicating an unconstrained type.
+        - Any is compatible with every type.
+        - Any assumed to have all methods.
+        - All values assumed to be instances of Any.
+        Note that all the above statements are true from the point of view of
+        static type checkers. At runtime, Any should not be used with instance
+        checks.
+        """
+        def __new__(cls, *args, **kwargs):
+            if cls is Any:
+                raise TypeError("Any cannot be instantiated")
+            return super().__new__(cls, *args, **kwargs)
+
+
+ClassVar = typing.ClassVar
+
+
+class _ExtensionsSpecialForm(typing._SpecialForm, _root=True):
+    def __repr__(self):
+        return 'typing_extensions.' + self._name
+
+
+Final = typing.Final
+
+if sys.version_info >= (3, 11):
+    final = typing.final
+else:
+    # @final exists in 3.8+, but we backport it for all versions
+    # before 3.11 to keep support for the __final__ attribute.
+    # See https://bugs.python.org/issue46342
+    def final(f):
+        """This decorator can be used to indicate to type checkers that
+        the decorated method cannot be overridden, and decorated class
+        cannot be subclassed. For example:
+
+            class Base:
+                @final
+                def done(self) -> None:
+                    ...
+            class Sub(Base):
+                def done(self) -> None:  # Error reported by type checker
+                    ...
+            @final
+            class Leaf:
+                ...
+            class Other(Leaf):  # Error reported by type checker
+                ...
+
+        There is no runtime checking of these properties. The decorator
+        sets the ``__final__`` attribute to ``True`` on the decorated object
+        to allow runtime introspection.
+        """
+        try:
+            f.__final__ = True
+        except (AttributeError, TypeError):
+            # Skip the attribute silently if it is not writable.
+            # AttributeError happens if the object has __slots__ or a
+            # read-only property, TypeError if it's a builtin class.
+            pass
+        return f
+
+
+def IntVar(name):
+    return typing.TypeVar(name)
+
+
+# A Literal bug was fixed in 3.11.0, 3.10.1 and 3.9.8
+if sys.version_info >= (3, 10, 1):
+    Literal = typing.Literal
+else:
+    def _flatten_literal_params(parameters):
+        """An internal helper for Literal creation: flatten Literals among parameters"""
+        params = []
+        for p in parameters:
+            if isinstance(p, _LiteralGenericAlias):
+                params.extend(p.__args__)
+            else:
+                params.append(p)
+        return tuple(params)
+
+    def _value_and_type_iter(params):
+        for p in params:
+            yield p, type(p)
+
+    class _LiteralGenericAlias(typing._GenericAlias, _root=True):
+        def __eq__(self, other):
+            if not isinstance(other, _LiteralGenericAlias):
+                return NotImplemented
+            these_args_deduped = set(_value_and_type_iter(self.__args__))
+            other_args_deduped = set(_value_and_type_iter(other.__args__))
+            return these_args_deduped == other_args_deduped
+
+        def __hash__(self):
+            return hash(frozenset(_value_and_type_iter(self.__args__)))
+
+    class _LiteralForm(_ExtensionsSpecialForm, _root=True):
+        def __init__(self, doc: str):
+            self._name = 'Literal'
+            self._doc = self.__doc__ = doc
+
+        def __getitem__(self, parameters):
+            if not isinstance(parameters, tuple):
+                parameters = (parameters,)
+
+            parameters = _flatten_literal_params(parameters)
+
+            val_type_pairs = list(_value_and_type_iter(parameters))
+            try:
+                deduped_pairs = set(val_type_pairs)
+            except TypeError:
+                # unhashable parameters
+                pass
+            else:
+                # similar logic to typing._deduplicate on Python 3.9+
+                if len(deduped_pairs) < len(val_type_pairs):
+                    new_parameters = []
+                    for pair in val_type_pairs:
+                        if pair in deduped_pairs:
+                            new_parameters.append(pair[0])
+                            deduped_pairs.remove(pair)
+                    assert not deduped_pairs, deduped_pairs
+                    parameters = tuple(new_parameters)
+
+            return _LiteralGenericAlias(self, parameters)
+
+    Literal = _LiteralForm(doc="""\
+                           A type that can be used to indicate to type checkers
+                           that the corresponding value has a value literally equivalent
+                           to the provided parameter. For example:
+
+                               var: Literal[4] = 4
+
+                           The type checker understands that 'var' is literally equal to
+                           the value 4 and no other value.
+
+                           Literal[...] cannot be subclassed. There is no runtime
+                           checking verifying that the parameter is actually a value
+                           instead of a type.""")
+
+
+_overload_dummy = typing._overload_dummy
+
+
+if hasattr(typing, "get_overloads"):  # 3.11+
+    overload = typing.overload
+    get_overloads = typing.get_overloads
+    clear_overloads = typing.clear_overloads
+else:
+    # {module: {qualname: {firstlineno: func}}}
+    _overload_registry = collections.defaultdict(
+        functools.partial(collections.defaultdict, dict)
+    )
+
+    def overload(func):
+        """Decorator for overloaded functions/methods.
+
+        In a stub file, place two or more stub definitions for the same
+        function in a row, each decorated with @overload.  For example:
+
+        @overload
+        def utf8(value: None) -> None: ...
+        @overload
+        def utf8(value: bytes) -> bytes: ...
+        @overload
+        def utf8(value: str) -> bytes: ...
+
+        In a non-stub file (i.e. a regular .py file), do the same but
+        follow it with an implementation.  The implementation should *not*
+        be decorated with @overload.  For example:
+
+        @overload
+        def utf8(value: None) -> None: ...
+        @overload
+        def utf8(value: bytes) -> bytes: ...
+        @overload
+        def utf8(value: str) -> bytes: ...
+        def utf8(value):
+            # implementation goes here
+
+        The overloads for a function can be retrieved at runtime using the
+        get_overloads() function.
+        """
+        # classmethod and staticmethod
+        f = getattr(func, "__func__", func)
+        try:
+            _overload_registry[f.__module__][f.__qualname__][
+                f.__code__.co_firstlineno
+            ] = func
+        except AttributeError:
+            # Not a normal function; ignore.
+            pass
+        return _overload_dummy
+
+    def get_overloads(func):
+        """Return all defined overloads for *func* as a sequence."""
+        # classmethod and staticmethod
+        f = getattr(func, "__func__", func)
+        if f.__module__ not in _overload_registry:
+            return []
+        mod_dict = _overload_registry[f.__module__]
+        if f.__qualname__ not in mod_dict:
+            return []
+        return list(mod_dict[f.__qualname__].values())
+
+    def clear_overloads():
+        """Clear all overloads in the registry."""
+        _overload_registry.clear()
+
+
+# This is not a real generic class.  Don't use outside annotations.
+Type = typing.Type
+
+# Various ABCs mimicking those in collections.abc.
+# A few are simply re-exported for completeness.
+Awaitable = typing.Awaitable
+Coroutine = typing.Coroutine
+AsyncIterable = typing.AsyncIterable
+AsyncIterator = typing.AsyncIterator
+Deque = typing.Deque
+DefaultDict = typing.DefaultDict
+OrderedDict = typing.OrderedDict
+Counter = typing.Counter
+ChainMap = typing.ChainMap
+Text = typing.Text
+TYPE_CHECKING = typing.TYPE_CHECKING
+
+
+if sys.version_info >= (3, 13, 0, "beta"):
+    from typing import AsyncContextManager, AsyncGenerator, ContextManager, Generator
+else:
+    def _is_dunder(attr):
+        return attr.startswith('__') and attr.endswith('__')
+
+    # Python <3.9 doesn't have typing._SpecialGenericAlias
+    _special_generic_alias_base = getattr(
+        typing, "_SpecialGenericAlias", typing._GenericAlias
+    )
+
+    class _SpecialGenericAlias(_special_generic_alias_base, _root=True):
+        def __init__(self, origin, nparams, *, inst=True, name=None, defaults=()):
+            if _special_generic_alias_base is typing._GenericAlias:
+                # Python <3.9
+                self.__origin__ = origin
+                self._nparams = nparams
+                super().__init__(origin, nparams, special=True, inst=inst, name=name)
+            else:
+                # Python >= 3.9
+                super().__init__(origin, nparams, inst=inst, name=name)
+            self._defaults = defaults
+
+        def __setattr__(self, attr, val):
+            allowed_attrs = {'_name', '_inst', '_nparams', '_defaults'}
+            if _special_generic_alias_base is typing._GenericAlias:
+                # Python <3.9
+                allowed_attrs.add("__origin__")
+            if _is_dunder(attr) or attr in allowed_attrs:
+                object.__setattr__(self, attr, val)
+            else:
+                setattr(self.__origin__, attr, val)
+
+        @typing._tp_cache
+        def __getitem__(self, params):
+            if not isinstance(params, tuple):
+                params = (params,)
+            msg = "Parameters to generic types must be types."
+            params = tuple(typing._type_check(p, msg) for p in params)
+            if (
+                self._defaults
+                and len(params) < self._nparams
+                and len(params) + len(self._defaults) >= self._nparams
+            ):
+                params = (*params, *self._defaults[len(params) - self._nparams:])
+            actual_len = len(params)
+
+            if actual_len != self._nparams:
+                if self._defaults:
+                    expected = f"at least {self._nparams - len(self._defaults)}"
+                else:
+                    expected = str(self._nparams)
+                if not self._nparams:
+                    raise TypeError(f"{self} is not a generic class")
+                raise TypeError(
+                    f"Too {'many' if actual_len > self._nparams else 'few'}"
+                    f" arguments for {self};"
+                    f" actual {actual_len}, expected {expected}"
+                )
+            return self.copy_with(params)
+
+    _NoneType = type(None)
+    Generator = _SpecialGenericAlias(
+        collections.abc.Generator, 3, defaults=(_NoneType, _NoneType)
+    )
+    AsyncGenerator = _SpecialGenericAlias(
+        collections.abc.AsyncGenerator, 2, defaults=(_NoneType,)
+    )
+    ContextManager = _SpecialGenericAlias(
+        contextlib.AbstractContextManager,
+        2,
+        name="ContextManager",
+        defaults=(typing.Optional[bool],)
+    )
+    AsyncContextManager = _SpecialGenericAlias(
+        contextlib.AbstractAsyncContextManager,
+        2,
+        name="AsyncContextManager",
+        defaults=(typing.Optional[bool],)
+    )
+
+
+_PROTO_ALLOWLIST = {
+    'collections.abc': [
+        'Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable',
+        'Hashable', 'Sized', 'Container', 'Collection', 'Reversible', 'Buffer',
+    ],
+    'contextlib': ['AbstractContextManager', 'AbstractAsyncContextManager'],
+    'typing_extensions': ['Buffer'],
+}
+
+
+_EXCLUDED_ATTRS = frozenset(typing.EXCLUDED_ATTRIBUTES) | {
+    "__match_args__", "__protocol_attrs__", "__non_callable_proto_members__",
+    "__final__",
+}
+
+
+def _get_protocol_attrs(cls):
+    attrs = set()
+    for base in cls.__mro__[:-1]:  # without object
+        if base.__name__ in {'Protocol', 'Generic'}:
+            continue
+        annotations = getattr(base, '__annotations__', {})
+        for attr in (*base.__dict__, *annotations):
+            if (not attr.startswith('_abc_') and attr not in _EXCLUDED_ATTRS):
+                attrs.add(attr)
+    return attrs
+
+
+def _caller(depth=2):
+    try:
+        return sys._getframe(depth).f_globals.get('__name__', '__main__')
+    except (AttributeError, ValueError):  # For platforms without _getframe()
+        return None
+
+
+# `__match_args__` attribute was removed from protocol members in 3.13,
+# we want to backport this change to older Python versions.
+if sys.version_info >= (3, 13):
+    Protocol = typing.Protocol
+else:
+    def _allow_reckless_class_checks(depth=3):
+        """Allow instance and class checks for special stdlib modules.
+        The abc and functools modules indiscriminately call isinstance() and
+        issubclass() on the whole MRO of a user class, which may contain protocols.
+        """
+        return _caller(depth) in {'abc', 'functools', None}
+
+    def _no_init(self, *args, **kwargs):
+        if type(self)._is_protocol:
+            raise TypeError('Protocols cannot be instantiated')
+
+    def _type_check_issubclass_arg_1(arg):
+        """Raise TypeError if `arg` is not an instance of `type`
+        in `issubclass(arg, )`.
+
+        In most cases, this is verified by type.__subclasscheck__.
+        Checking it again unnecessarily would slow down issubclass() checks,
+        so, we don't perform this check unless we absolutely have to.
+
+        For various error paths, however,
+        we want to ensure that *this* error message is shown to the user
+        where relevant, rather than a typing.py-specific error message.
+        """
+        if not isinstance(arg, type):
+            # Same error message as for issubclass(1, int).
+            raise TypeError('issubclass() arg 1 must be a class')
+
+    # Inheriting from typing._ProtocolMeta isn't actually desirable,
+    # but is necessary to allow typing.Protocol and typing_extensions.Protocol
+    # to mix without getting TypeErrors about "metaclass conflict"
+    class _ProtocolMeta(type(typing.Protocol)):
+        # This metaclass is somewhat unfortunate,
+        # but is necessary for several reasons...
+        #
+        # NOTE: DO NOT call super() in any methods in this class
+        # That would call the methods on typing._ProtocolMeta on Python 3.8-3.11
+        # and those are slow
+        def __new__(mcls, name, bases, namespace, **kwargs):
+            if name == "Protocol" and len(bases) < 2:
+                pass
+            elif {Protocol, typing.Protocol} & set(bases):
+                for base in bases:
+                    if not (
+                        base in {object, typing.Generic, Protocol, typing.Protocol}
+                        or base.__name__ in _PROTO_ALLOWLIST.get(base.__module__, [])
+                        or is_protocol(base)
+                    ):
+                        raise TypeError(
+                            f"Protocols can only inherit from other protocols, "
+                            f"got {base!r}"
+                        )
+            return abc.ABCMeta.__new__(mcls, name, bases, namespace, **kwargs)
+
+        def __init__(cls, *args, **kwargs):
+            abc.ABCMeta.__init__(cls, *args, **kwargs)
+            if getattr(cls, "_is_protocol", False):
+                cls.__protocol_attrs__ = _get_protocol_attrs(cls)
+
+        def __subclasscheck__(cls, other):
+            if cls is Protocol:
+                return type.__subclasscheck__(cls, other)
+            if (
+                getattr(cls, '_is_protocol', False)
+                and not _allow_reckless_class_checks()
+            ):
+                if not getattr(cls, '_is_runtime_protocol', False):
+                    _type_check_issubclass_arg_1(other)
+                    raise TypeError(
+                        "Instance and class checks can only be used with "
+                        "@runtime_checkable protocols"
+                    )
+                if (
+                    # this attribute is set by @runtime_checkable:
+                    cls.__non_callable_proto_members__
+                    and cls.__dict__.get("__subclasshook__") is _proto_hook
+                ):
+                    _type_check_issubclass_arg_1(other)
+                    non_method_attrs = sorted(cls.__non_callable_proto_members__)
+                    raise TypeError(
+                        "Protocols with non-method members don't support issubclass()."
+                        f" Non-method members: {str(non_method_attrs)[1:-1]}."
+                    )
+            return abc.ABCMeta.__subclasscheck__(cls, other)
+
+        def __instancecheck__(cls, instance):
+            # We need this method for situations where attributes are
+            # assigned in __init__.
+            if cls is Protocol:
+                return type.__instancecheck__(cls, instance)
+            if not getattr(cls, "_is_protocol", False):
+                # i.e., it's a concrete subclass of a protocol
+                return abc.ABCMeta.__instancecheck__(cls, instance)
+
+            if (
+                not getattr(cls, '_is_runtime_protocol', False) and
+                not _allow_reckless_class_checks()
+            ):
+                raise TypeError("Instance and class checks can only be used with"
+                                " @runtime_checkable protocols")
+
+            if abc.ABCMeta.__instancecheck__(cls, instance):
+                return True
+
+            for attr in cls.__protocol_attrs__:
+                try:
+                    val = inspect.getattr_static(instance, attr)
+                except AttributeError:
+                    break
+                # this attribute is set by @runtime_checkable:
+                if val is None and attr not in cls.__non_callable_proto_members__:
+                    break
+            else:
+                return True
+
+            return False
+
+        def __eq__(cls, other):
+            # Hack so that typing.Generic.__class_getitem__
+            # treats typing_extensions.Protocol
+            # as equivalent to typing.Protocol
+            if abc.ABCMeta.__eq__(cls, other) is True:
+                return True
+            return cls is Protocol and other is typing.Protocol
+
+        # This has to be defined, or the abc-module cache
+        # complains about classes with this metaclass being unhashable,
+        # if we define only __eq__!
+        def __hash__(cls) -> int:
+            return type.__hash__(cls)
+
+    @classmethod
+    def _proto_hook(cls, other):
+        if not cls.__dict__.get('_is_protocol', False):
+            return NotImplemented
+
+        for attr in cls.__protocol_attrs__:
+            for base in other.__mro__:
+                # Check if the members appears in the class dictionary...
+                if attr in base.__dict__:
+                    if base.__dict__[attr] is None:
+                        return NotImplemented
+                    break
+
+                # ...or in annotations, if it is a sub-protocol.
+                annotations = getattr(base, '__annotations__', {})
+                if (
+                    isinstance(annotations, collections.abc.Mapping)
+                    and attr in annotations
+                    and is_protocol(other)
+                ):
+                    break
+            else:
+                return NotImplemented
+        return True
+
+    class Protocol(typing.Generic, metaclass=_ProtocolMeta):
+        __doc__ = typing.Protocol.__doc__
+        __slots__ = ()
+        _is_protocol = True
+        _is_runtime_protocol = False
+
+        def __init_subclass__(cls, *args, **kwargs):
+            super().__init_subclass__(*args, **kwargs)
+
+            # Determine if this is a protocol or a concrete subclass.
+            if not cls.__dict__.get('_is_protocol', False):
+                cls._is_protocol = any(b is Protocol for b in cls.__bases__)
+
+            # Set (or override) the protocol subclass hook.
+            if '__subclasshook__' not in cls.__dict__:
+                cls.__subclasshook__ = _proto_hook
+
+            # Prohibit instantiation for protocol classes
+            if cls._is_protocol and cls.__init__ is Protocol.__init__:
+                cls.__init__ = _no_init
+
+
+if sys.version_info >= (3, 13):
+    runtime_checkable = typing.runtime_checkable
+else:
+    def runtime_checkable(cls):
+        """Mark a protocol class as a runtime protocol.
+
+        Such protocol can be used with isinstance() and issubclass().
+        Raise TypeError if applied to a non-protocol class.
+        This allows a simple-minded structural check very similar to
+        one trick ponies in collections.abc such as Iterable.
+
+        For example::
+
+            @runtime_checkable
+            class Closable(Protocol):
+                def close(self): ...
+
+            assert isinstance(open('/some/file'), Closable)
+
+        Warning: this will check only the presence of the required methods,
+        not their type signatures!
+        """
+        if not issubclass(cls, typing.Generic) or not getattr(cls, '_is_protocol', False):
+            raise TypeError(f'@runtime_checkable can be only applied to protocol classes,'
+                            f' got {cls!r}')
+        cls._is_runtime_protocol = True
+
+        # typing.Protocol classes on <=3.11 break if we execute this block,
+        # because typing.Protocol classes on <=3.11 don't have a
+        # `__protocol_attrs__` attribute, and this block relies on the
+        # `__protocol_attrs__` attribute. Meanwhile, typing.Protocol classes on 3.12.2+
+        # break if we *don't* execute this block, because *they* assume that all
+        # protocol classes have a `__non_callable_proto_members__` attribute
+        # (which this block sets)
+        if isinstance(cls, _ProtocolMeta) or sys.version_info >= (3, 12, 2):
+            # PEP 544 prohibits using issubclass()
+            # with protocols that have non-method members.
+            # See gh-113320 for why we compute this attribute here,
+            # rather than in `_ProtocolMeta.__init__`
+            cls.__non_callable_proto_members__ = set()
+            for attr in cls.__protocol_attrs__:
+                try:
+                    is_callable = callable(getattr(cls, attr, None))
+                except Exception as e:
+                    raise TypeError(
+                        f"Failed to determine whether protocol member {attr!r} "
+                        "is a method member"
+                    ) from e
+                else:
+                    if not is_callable:
+                        cls.__non_callable_proto_members__.add(attr)
+
+        return cls
+
+
+# The "runtime" alias exists for backwards compatibility.
+runtime = runtime_checkable
+
+
+# Our version of runtime-checkable protocols is faster on Python 3.8-3.11
+if sys.version_info >= (3, 12):
+    SupportsInt = typing.SupportsInt
+    SupportsFloat = typing.SupportsFloat
+    SupportsComplex = typing.SupportsComplex
+    SupportsBytes = typing.SupportsBytes
+    SupportsIndex = typing.SupportsIndex
+    SupportsAbs = typing.SupportsAbs
+    SupportsRound = typing.SupportsRound
+else:
+    @runtime_checkable
+    class SupportsInt(Protocol):
+        """An ABC with one abstract method __int__."""
+        __slots__ = ()
+
+        @abc.abstractmethod
+        def __int__(self) -> int:
+            pass
+
+    @runtime_checkable
+    class SupportsFloat(Protocol):
+        """An ABC with one abstract method __float__."""
+        __slots__ = ()
+
+        @abc.abstractmethod
+        def __float__(self) -> float:
+            pass
+
+    @runtime_checkable
+    class SupportsComplex(Protocol):
+        """An ABC with one abstract method __complex__."""
+        __slots__ = ()
+
+        @abc.abstractmethod
+        def __complex__(self) -> complex:
+            pass
+
+    @runtime_checkable
+    class SupportsBytes(Protocol):
+        """An ABC with one abstract method __bytes__."""
+        __slots__ = ()
+
+        @abc.abstractmethod
+        def __bytes__(self) -> bytes:
+            pass
+
+    @runtime_checkable
+    class SupportsIndex(Protocol):
+        __slots__ = ()
+
+        @abc.abstractmethod
+        def __index__(self) -> int:
+            pass
+
+    @runtime_checkable
+    class SupportsAbs(Protocol[T_co]):
+        """
+        An ABC with one abstract method __abs__ that is covariant in its return type.
+        """
+        __slots__ = ()
+
+        @abc.abstractmethod
+        def __abs__(self) -> T_co:
+            pass
+
+    @runtime_checkable
+    class SupportsRound(Protocol[T_co]):
+        """
+        An ABC with one abstract method __round__ that is covariant in its return type.
+        """
+        __slots__ = ()
+
+        @abc.abstractmethod
+        def __round__(self, ndigits: int = 0) -> T_co:
+            pass
+
+
+def _ensure_subclassable(mro_entries):
+    def inner(func):
+        if sys.implementation.name == "pypy" and sys.version_info < (3, 9):
+            cls_dict = {
+                "__call__": staticmethod(func),
+                "__mro_entries__": staticmethod(mro_entries)
+            }
+            t = type(func.__name__, (), cls_dict)
+            return functools.update_wrapper(t(), func)
+        else:
+            func.__mro_entries__ = mro_entries
+            return func
+    return inner
+
+
+# Update this to something like >=3.13.0b1 if and when
+# PEP 728 is implemented in CPython
+_PEP_728_IMPLEMENTED = False
+
+if _PEP_728_IMPLEMENTED:
+    # The standard library TypedDict in Python 3.8 does not store runtime information
+    # about which (if any) keys are optional.  See https://bugs.python.org/issue38834
+    # The standard library TypedDict in Python 3.9.0/1 does not honour the "total"
+    # keyword with old-style TypedDict().  See https://bugs.python.org/issue42059
+    # The standard library TypedDict below Python 3.11 does not store runtime
+    # information about optional and required keys when using Required or NotRequired.
+    # Generic TypedDicts are also impossible using typing.TypedDict on Python <3.11.
+    # Aaaand on 3.12 we add __orig_bases__ to TypedDict
+    # to enable better runtime introspection.
+    # On 3.13 we deprecate some odd ways of creating TypedDicts.
+    # Also on 3.13, PEP 705 adds the ReadOnly[] qualifier.
+    # PEP 728 (still pending) makes more changes.
+    TypedDict = typing.TypedDict
+    _TypedDictMeta = typing._TypedDictMeta
+    is_typeddict = typing.is_typeddict
+else:
+    # 3.10.0 and later
+    _TAKES_MODULE = "module" in inspect.signature(typing._type_check).parameters
+
+    def _get_typeddict_qualifiers(annotation_type):
+        while True:
+            annotation_origin = get_origin(annotation_type)
+            if annotation_origin is Annotated:
+                annotation_args = get_args(annotation_type)
+                if annotation_args:
+                    annotation_type = annotation_args[0]
+                else:
+                    break
+            elif annotation_origin is Required:
+                yield Required
+                annotation_type, = get_args(annotation_type)
+            elif annotation_origin is NotRequired:
+                yield NotRequired
+                annotation_type, = get_args(annotation_type)
+            elif annotation_origin is ReadOnly:
+                yield ReadOnly
+                annotation_type, = get_args(annotation_type)
+            else:
+                break
+
+    class _TypedDictMeta(type):
+        def __new__(cls, name, bases, ns, *, total=True, closed=False):
+            """Create new typed dict class object.
+
+            This method is called when TypedDict is subclassed,
+            or when TypedDict is instantiated. This way
+            TypedDict supports all three syntax forms described in its docstring.
+            Subclasses and instances of TypedDict return actual dictionaries.
+            """
+            for base in bases:
+                if type(base) is not _TypedDictMeta and base is not typing.Generic:
+                    raise TypeError('cannot inherit from both a TypedDict type '
+                                    'and a non-TypedDict base class')
+
+            if any(issubclass(b, typing.Generic) for b in bases):
+                generic_base = (typing.Generic,)
+            else:
+                generic_base = ()
+
+            # typing.py generally doesn't let you inherit from plain Generic, unless
+            # the name of the class happens to be "Protocol"
+            tp_dict = type.__new__(_TypedDictMeta, "Protocol", (*generic_base, dict), ns)
+            tp_dict.__name__ = name
+            if tp_dict.__qualname__ == "Protocol":
+                tp_dict.__qualname__ = name
+
+            if not hasattr(tp_dict, '__orig_bases__'):
+                tp_dict.__orig_bases__ = bases
+
+            annotations = {}
+            if "__annotations__" in ns:
+                own_annotations = ns["__annotations__"]
+            elif "__annotate__" in ns:
+                # TODO: Use inspect.VALUE here, and make the annotations lazily evaluated
+                own_annotations = ns["__annotate__"](1)
+            else:
+                own_annotations = {}
+            msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
+            if _TAKES_MODULE:
+                own_annotations = {
+                    n: typing._type_check(tp, msg, module=tp_dict.__module__)
+                    for n, tp in own_annotations.items()
+                }
+            else:
+                own_annotations = {
+                    n: typing._type_check(tp, msg)
+                    for n, tp in own_annotations.items()
+                }
+            required_keys = set()
+            optional_keys = set()
+            readonly_keys = set()
+            mutable_keys = set()
+            extra_items_type = None
+
+            for base in bases:
+                base_dict = base.__dict__
+
+                annotations.update(base_dict.get('__annotations__', {}))
+                required_keys.update(base_dict.get('__required_keys__', ()))
+                optional_keys.update(base_dict.get('__optional_keys__', ()))
+                readonly_keys.update(base_dict.get('__readonly_keys__', ()))
+                mutable_keys.update(base_dict.get('__mutable_keys__', ()))
+                base_extra_items_type = base_dict.get('__extra_items__', None)
+                if base_extra_items_type is not None:
+                    extra_items_type = base_extra_items_type
+
+            if closed and extra_items_type is None:
+                extra_items_type = Never
+            if closed and "__extra_items__" in own_annotations:
+                annotation_type = own_annotations.pop("__extra_items__")
+                qualifiers = set(_get_typeddict_qualifiers(annotation_type))
+                if Required in qualifiers:
+                    raise TypeError(
+                        "Special key __extra_items__ does not support "
+                        "Required"
+                    )
+                if NotRequired in qualifiers:
+                    raise TypeError(
+                        "Special key __extra_items__ does not support "
+                        "NotRequired"
+                    )
+                extra_items_type = annotation_type
+
+            annotations.update(own_annotations)
+            for annotation_key, annotation_type in own_annotations.items():
+                qualifiers = set(_get_typeddict_qualifiers(annotation_type))
+
+                if Required in qualifiers:
+                    required_keys.add(annotation_key)
+                elif NotRequired in qualifiers:
+                    optional_keys.add(annotation_key)
+                elif total:
+                    required_keys.add(annotation_key)
+                else:
+                    optional_keys.add(annotation_key)
+                if ReadOnly in qualifiers:
+                    mutable_keys.discard(annotation_key)
+                    readonly_keys.add(annotation_key)
+                else:
+                    mutable_keys.add(annotation_key)
+                    readonly_keys.discard(annotation_key)
+
+            tp_dict.__annotations__ = annotations
+            tp_dict.__required_keys__ = frozenset(required_keys)
+            tp_dict.__optional_keys__ = frozenset(optional_keys)
+            tp_dict.__readonly_keys__ = frozenset(readonly_keys)
+            tp_dict.__mutable_keys__ = frozenset(mutable_keys)
+            if not hasattr(tp_dict, '__total__'):
+                tp_dict.__total__ = total
+            tp_dict.__closed__ = closed
+            tp_dict.__extra_items__ = extra_items_type
+            return tp_dict
+
+        __call__ = dict  # static method
+
+        def __subclasscheck__(cls, other):
+            # Typed dicts are only for static structural subtyping.
+            raise TypeError('TypedDict does not support instance and class checks')
+
+        __instancecheck__ = __subclasscheck__
+
+    _TypedDict = type.__new__(_TypedDictMeta, 'TypedDict', (), {})
+
+    @_ensure_subclassable(lambda bases: (_TypedDict,))
+    def TypedDict(typename, fields=_marker, /, *, total=True, closed=False, **kwargs):
+        """A simple typed namespace. At runtime it is equivalent to a plain dict.
+
+        TypedDict creates a dictionary type such that a type checker will expect all
+        instances to have a certain set of keys, where each key is
+        associated with a value of a consistent type. This expectation
+        is not checked at runtime.
+
+        Usage::
+
+            class Point2D(TypedDict):
+                x: int
+                y: int
+                label: str
+
+            a: Point2D = {'x': 1, 'y': 2, 'label': 'good'}  # OK
+            b: Point2D = {'z': 3, 'label': 'bad'}           # Fails type check
+
+            assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
+
+        The type info can be accessed via the Point2D.__annotations__ dict, and
+        the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets.
+        TypedDict supports an additional equivalent form::
+
+            Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
+
+        By default, all keys must be present in a TypedDict. It is possible
+        to override this by specifying totality::
+
+            class Point2D(TypedDict, total=False):
+                x: int
+                y: int
+
+        This means that a Point2D TypedDict can have any of the keys omitted. A type
+        checker is only expected to support a literal False or True as the value of
+        the total argument. True is the default, and makes all items defined in the
+        class body be required.
+
+        The Required and NotRequired special forms can also be used to mark
+        individual keys as being required or not required::
+
+            class Point2D(TypedDict):
+                x: int  # the "x" key must always be present (Required is the default)
+                y: NotRequired[int]  # the "y" key can be omitted
+
+        See PEP 655 for more details on Required and NotRequired.
+        """
+        if fields is _marker or fields is None:
+            if fields is _marker:
+                deprecated_thing = "Failing to pass a value for the 'fields' parameter"
+            else:
+                deprecated_thing = "Passing `None` as the 'fields' parameter"
+
+            example = f"`{typename} = TypedDict({typename!r}, {{}})`"
+            deprecation_msg = (
+                f"{deprecated_thing} is deprecated and will be disallowed in "
+                "Python 3.15. To create a TypedDict class with 0 fields "
+                "using the functional syntax, pass an empty dictionary, e.g. "
+            ) + example + "."
+            warnings.warn(deprecation_msg, DeprecationWarning, stacklevel=2)
+            if closed is not False and closed is not True:
+                kwargs["closed"] = closed
+                closed = False
+            fields = kwargs
+        elif kwargs:
+            raise TypeError("TypedDict takes either a dict or keyword arguments,"
+                            " but not both")
+        if kwargs:
+            if sys.version_info >= (3, 13):
+                raise TypeError("TypedDict takes no keyword arguments")
+            warnings.warn(
+                "The kwargs-based syntax for TypedDict definitions is deprecated "
+                "in Python 3.11, will be removed in Python 3.13, and may not be "
+                "understood by third-party type checkers.",
+                DeprecationWarning,
+                stacklevel=2,
+            )
+
+        ns = {'__annotations__': dict(fields)}
+        module = _caller()
+        if module is not None:
+            # Setting correct module is necessary to make typed dict classes pickleable.
+            ns['__module__'] = module
+
+        td = _TypedDictMeta(typename, (), ns, total=total, closed=closed)
+        td.__orig_bases__ = (TypedDict,)
+        return td
+
+    if hasattr(typing, "_TypedDictMeta"):
+        _TYPEDDICT_TYPES = (typing._TypedDictMeta, _TypedDictMeta)
+    else:
+        _TYPEDDICT_TYPES = (_TypedDictMeta,)
+
+    def is_typeddict(tp):
+        """Check if an annotation is a TypedDict class
+
+        For example::
+            class Film(TypedDict):
+                title: str
+                year: int
+
+            is_typeddict(Film)  # => True
+            is_typeddict(Union[list, str])  # => False
+        """
+        # On 3.8, this would otherwise return True
+        if hasattr(typing, "TypedDict") and tp is typing.TypedDict:
+            return False
+        return isinstance(tp, _TYPEDDICT_TYPES)
+
+
+if hasattr(typing, "assert_type"):
+    assert_type = typing.assert_type
+
+else:
+    def assert_type(val, typ, /):
+        """Assert (to the type checker) that the value is of the given type.
+
+        When the type checker encounters a call to assert_type(), it
+        emits an error if the value is not of the specified type::
+
+            def greet(name: str) -> None:
+                assert_type(name, str)  # ok
+                assert_type(name, int)  # type checker error
+
+        At runtime this returns the first argument unchanged and otherwise
+        does nothing.
+        """
+        return val
+
+
+if hasattr(typing, "ReadOnly"):  # 3.13+
+    get_type_hints = typing.get_type_hints
+else:  # <=3.13
+    # replaces _strip_annotations()
+    def _strip_extras(t):
+        """Strips Annotated, Required and NotRequired from a given type."""
+        if isinstance(t, _AnnotatedAlias):
+            return _strip_extras(t.__origin__)
+        if hasattr(t, "__origin__") and t.__origin__ in (Required, NotRequired, ReadOnly):
+            return _strip_extras(t.__args__[0])
+        if isinstance(t, typing._GenericAlias):
+            stripped_args = tuple(_strip_extras(a) for a in t.__args__)
+            if stripped_args == t.__args__:
+                return t
+            return t.copy_with(stripped_args)
+        if hasattr(_types, "GenericAlias") and isinstance(t, _types.GenericAlias):
+            stripped_args = tuple(_strip_extras(a) for a in t.__args__)
+            if stripped_args == t.__args__:
+                return t
+            return _types.GenericAlias(t.__origin__, stripped_args)
+        if hasattr(_types, "UnionType") and isinstance(t, _types.UnionType):
+            stripped_args = tuple(_strip_extras(a) for a in t.__args__)
+            if stripped_args == t.__args__:
+                return t
+            return functools.reduce(operator.or_, stripped_args)
+
+        return t
+
+    def get_type_hints(obj, globalns=None, localns=None, include_extras=False):
+        """Return type hints for an object.
+
+        This is often the same as obj.__annotations__, but it handles
+        forward references encoded as string literals, adds Optional[t] if a
+        default value equal to None is set and recursively replaces all
+        'Annotated[T, ...]', 'Required[T]' or 'NotRequired[T]' with 'T'
+        (unless 'include_extras=True').
+
+        The argument may be a module, class, method, or function. The annotations
+        are returned as a dictionary. For classes, annotations include also
+        inherited members.
+
+        TypeError is raised if the argument is not of a type that can contain
+        annotations, and an empty dictionary is returned if no annotations are
+        present.
+
+        BEWARE -- the behavior of globalns and localns is counterintuitive
+        (unless you are familiar with how eval() and exec() work).  The
+        search order is locals first, then globals.
+
+        - If no dict arguments are passed, an attempt is made to use the
+          globals from obj (or the respective module's globals for classes),
+          and these are also used as the locals.  If the object does not appear
+          to have globals, an empty dictionary is used.
+
+        - If one dict argument is passed, it is used for both globals and
+          locals.
+
+        - If two dict arguments are passed, they specify globals and
+          locals, respectively.
+        """
+        if hasattr(typing, "Annotated"):  # 3.9+
+            hint = typing.get_type_hints(
+                obj, globalns=globalns, localns=localns, include_extras=True
+            )
+        else:  # 3.8
+            hint = typing.get_type_hints(obj, globalns=globalns, localns=localns)
+        if include_extras:
+            return hint
+        return {k: _strip_extras(t) for k, t in hint.items()}
+
+
+# Python 3.9+ has PEP 593 (Annotated)
+if hasattr(typing, 'Annotated'):
+    Annotated = typing.Annotated
+    # Not exported and not a public API, but needed for get_origin() and get_args()
+    # to work.
+    _AnnotatedAlias = typing._AnnotatedAlias
+# 3.8
+else:
+    class _AnnotatedAlias(typing._GenericAlias, _root=True):
+        """Runtime representation of an annotated type.
+
+        At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't'
+        with extra annotations. The alias behaves like a normal typing alias,
+        instantiating is the same as instantiating the underlying type, binding
+        it to types is also the same.
+        """
+        def __init__(self, origin, metadata):
+            if isinstance(origin, _AnnotatedAlias):
+                metadata = origin.__metadata__ + metadata
+                origin = origin.__origin__
+            super().__init__(origin, origin)
+            self.__metadata__ = metadata
+
+        def copy_with(self, params):
+            assert len(params) == 1
+            new_type = params[0]
+            return _AnnotatedAlias(new_type, self.__metadata__)
+
+        def __repr__(self):
+            return (f"typing_extensions.Annotated[{typing._type_repr(self.__origin__)}, "
+                    f"{', '.join(repr(a) for a in self.__metadata__)}]")
+
+        def __reduce__(self):
+            return operator.getitem, (
+                Annotated, (self.__origin__, *self.__metadata__)
+            )
+
+        def __eq__(self, other):
+            if not isinstance(other, _AnnotatedAlias):
+                return NotImplemented
+            if self.__origin__ != other.__origin__:
+                return False
+            return self.__metadata__ == other.__metadata__
+
+        def __hash__(self):
+            return hash((self.__origin__, self.__metadata__))
+
+    class Annotated:
+        """Add context specific metadata to a type.
+
+        Example: Annotated[int, runtime_check.Unsigned] indicates to the
+        hypothetical runtime_check module that this type is an unsigned int.
+        Every other consumer of this type can ignore this metadata and treat
+        this type as int.
+
+        The first argument to Annotated must be a valid type (and will be in
+        the __origin__ field), the remaining arguments are kept as a tuple in
+        the __extra__ field.
+
+        Details:
+
+        - It's an error to call `Annotated` with less than two arguments.
+        - Nested Annotated are flattened::
+
+            Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
+
+        - Instantiating an annotated type is equivalent to instantiating the
+        underlying type::
+
+            Annotated[C, Ann1](5) == C(5)
+
+        - Annotated can be used as a generic type alias::
+
+            Optimized = Annotated[T, runtime.Optimize()]
+            Optimized[int] == Annotated[int, runtime.Optimize()]
+
+            OptimizedList = Annotated[List[T], runtime.Optimize()]
+            OptimizedList[int] == Annotated[List[int], runtime.Optimize()]
+        """
+
+        __slots__ = ()
+
+        def __new__(cls, *args, **kwargs):
+            raise TypeError("Type Annotated cannot be instantiated.")
+
+        @typing._tp_cache
+        def __class_getitem__(cls, params):
+            if not isinstance(params, tuple) or len(params) < 2:
+                raise TypeError("Annotated[...] should be used "
+                                "with at least two arguments (a type and an "
+                                "annotation).")
+            allowed_special_forms = (ClassVar, Final)
+            if get_origin(params[0]) in allowed_special_forms:
+                origin = params[0]
+            else:
+                msg = "Annotated[t, ...]: t must be a type."
+                origin = typing._type_check(params[0], msg)
+            metadata = tuple(params[1:])
+            return _AnnotatedAlias(origin, metadata)
+
+        def __init_subclass__(cls, *args, **kwargs):
+            raise TypeError(
+                f"Cannot subclass {cls.__module__}.Annotated"
+            )
+
+# Python 3.8 has get_origin() and get_args() but those implementations aren't
+# Annotated-aware, so we can't use those. Python 3.9's versions don't support
+# ParamSpecArgs and ParamSpecKwargs, so only Python 3.10's versions will do.
+if sys.version_info[:2] >= (3, 10):
+    get_origin = typing.get_origin
+    get_args = typing.get_args
+# 3.8-3.9
+else:
+    try:
+        # 3.9+
+        from typing import _BaseGenericAlias
+    except ImportError:
+        _BaseGenericAlias = typing._GenericAlias
+    try:
+        # 3.9+
+        from typing import GenericAlias as _typing_GenericAlias
+    except ImportError:
+        _typing_GenericAlias = typing._GenericAlias
+
+    def get_origin(tp):
+        """Get the unsubscripted version of a type.
+
+        This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar
+        and Annotated. Return None for unsupported types. Examples::
+
+            get_origin(Literal[42]) is Literal
+            get_origin(int) is None
+            get_origin(ClassVar[int]) is ClassVar
+            get_origin(Generic) is Generic
+            get_origin(Generic[T]) is Generic
+            get_origin(Union[T, int]) is Union
+            get_origin(List[Tuple[T, T]][int]) == list
+            get_origin(P.args) is P
+        """
+        if isinstance(tp, _AnnotatedAlias):
+            return Annotated
+        if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias, _BaseGenericAlias,
+                           ParamSpecArgs, ParamSpecKwargs)):
+            return tp.__origin__
+        if tp is typing.Generic:
+            return typing.Generic
+        return None
+
+    def get_args(tp):
+        """Get type arguments with all substitutions performed.
+
+        For unions, basic simplifications used by Union constructor are performed.
+        Examples::
+            get_args(Dict[str, int]) == (str, int)
+            get_args(int) == ()
+            get_args(Union[int, Union[T, int], str][int]) == (int, str)
+            get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
+            get_args(Callable[[], T][int]) == ([], int)
+        """
+        if isinstance(tp, _AnnotatedAlias):
+            return (tp.__origin__, *tp.__metadata__)
+        if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias)):
+            if getattr(tp, "_special", False):
+                return ()
+            res = tp.__args__
+            if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis:
+                res = (list(res[:-1]), res[-1])
+            return res
+        return ()
+
+
+# 3.10+
+if hasattr(typing, 'TypeAlias'):
+    TypeAlias = typing.TypeAlias
+# 3.9
+elif sys.version_info[:2] >= (3, 9):
+    @_ExtensionsSpecialForm
+    def TypeAlias(self, parameters):
+        """Special marker indicating that an assignment should
+        be recognized as a proper type alias definition by type
+        checkers.
+
+        For example::
+
+            Predicate: TypeAlias = Callable[..., bool]
+
+        It's invalid when used anywhere except as in the example above.
+        """
+        raise TypeError(f"{self} is not subscriptable")
+# 3.8
+else:
+    TypeAlias = _ExtensionsSpecialForm(
+        'TypeAlias',
+        doc="""Special marker indicating that an assignment should
+        be recognized as a proper type alias definition by type
+        checkers.
+
+        For example::
+
+            Predicate: TypeAlias = Callable[..., bool]
+
+        It's invalid when used anywhere except as in the example
+        above."""
+    )
+
+
+if hasattr(typing, "NoDefault"):
+    NoDefault = typing.NoDefault
+else:
+    class NoDefaultTypeMeta(type):
+        def __setattr__(cls, attr, value):
+            # TypeError is consistent with the behavior of NoneType
+            raise TypeError(
+                f"cannot set {attr!r} attribute of immutable type {cls.__name__!r}"
+            )
+
+    class NoDefaultType(metaclass=NoDefaultTypeMeta):
+        """The type of the NoDefault singleton."""
+
+        __slots__ = ()
+
+        def __new__(cls):
+            return globals().get("NoDefault") or object.__new__(cls)
+
+        def __repr__(self):
+            return "typing_extensions.NoDefault"
+
+        def __reduce__(self):
+            return "NoDefault"
+
+    NoDefault = NoDefaultType()
+    del NoDefaultType, NoDefaultTypeMeta
+
+
+def _set_default(type_param, default):
+    type_param.has_default = lambda: default is not NoDefault
+    type_param.__default__ = default
+
+
+def _set_module(typevarlike):
+    # for pickling:
+    def_mod = _caller(depth=3)
+    if def_mod != 'typing_extensions':
+        typevarlike.__module__ = def_mod
+
+
+class _DefaultMixin:
+    """Mixin for TypeVarLike defaults."""
+
+    __slots__ = ()
+    __init__ = _set_default
+
+
+# Classes using this metaclass must provide a _backported_typevarlike ClassVar
+class _TypeVarLikeMeta(type):
+    def __instancecheck__(cls, __instance: Any) -> bool:
+        return isinstance(__instance, cls._backported_typevarlike)
+
+
+if _PEP_696_IMPLEMENTED:
+    from typing import TypeVar
+else:
+    # Add default and infer_variance parameters from PEP 696 and 695
+    class TypeVar(metaclass=_TypeVarLikeMeta):
+        """Type variable."""
+
+        _backported_typevarlike = typing.TypeVar
+
+        def __new__(cls, name, *constraints, bound=None,
+                    covariant=False, contravariant=False,
+                    default=NoDefault, infer_variance=False):
+            if hasattr(typing, "TypeAliasType"):
+                # PEP 695 implemented (3.12+), can pass infer_variance to typing.TypeVar
+                typevar = typing.TypeVar(name, *constraints, bound=bound,
+                                         covariant=covariant, contravariant=contravariant,
+                                         infer_variance=infer_variance)
+            else:
+                typevar = typing.TypeVar(name, *constraints, bound=bound,
+                                         covariant=covariant, contravariant=contravariant)
+                if infer_variance and (covariant or contravariant):
+                    raise ValueError("Variance cannot be specified with infer_variance.")
+                typevar.__infer_variance__ = infer_variance
+
+            _set_default(typevar, default)
+            _set_module(typevar)
+
+            def _tvar_prepare_subst(alias, args):
+                if (
+                    typevar.has_default()
+                    and alias.__parameters__.index(typevar) == len(args)
+                ):
+                    args += (typevar.__default__,)
+                return args
+
+            typevar.__typing_prepare_subst__ = _tvar_prepare_subst
+            return typevar
+
+        def __init_subclass__(cls) -> None:
+            raise TypeError(f"type '{__name__}.TypeVar' is not an acceptable base type")
+
+
+# Python 3.10+ has PEP 612
+if hasattr(typing, 'ParamSpecArgs'):
+    ParamSpecArgs = typing.ParamSpecArgs
+    ParamSpecKwargs = typing.ParamSpecKwargs
+# 3.8-3.9
+else:
+    class _Immutable:
+        """Mixin to indicate that object should not be copied."""
+        __slots__ = ()
+
+        def __copy__(self):
+            return self
+
+        def __deepcopy__(self, memo):
+            return self
+
+    class ParamSpecArgs(_Immutable):
+        """The args for a ParamSpec object.
+
+        Given a ParamSpec object P, P.args is an instance of ParamSpecArgs.
+
+        ParamSpecArgs objects have a reference back to their ParamSpec:
+
+        P.args.__origin__ is P
+
+        This type is meant for runtime introspection and has no special meaning to
+        static type checkers.
+        """
+        def __init__(self, origin):
+            self.__origin__ = origin
+
+        def __repr__(self):
+            return f"{self.__origin__.__name__}.args"
+
+        def __eq__(self, other):
+            if not isinstance(other, ParamSpecArgs):
+                return NotImplemented
+            return self.__origin__ == other.__origin__
+
+    class ParamSpecKwargs(_Immutable):
+        """The kwargs for a ParamSpec object.
+
+        Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs.
+
+        ParamSpecKwargs objects have a reference back to their ParamSpec:
+
+        P.kwargs.__origin__ is P
+
+        This type is meant for runtime introspection and has no special meaning to
+        static type checkers.
+        """
+        def __init__(self, origin):
+            self.__origin__ = origin
+
+        def __repr__(self):
+            return f"{self.__origin__.__name__}.kwargs"
+
+        def __eq__(self, other):
+            if not isinstance(other, ParamSpecKwargs):
+                return NotImplemented
+            return self.__origin__ == other.__origin__
+
+
+if _PEP_696_IMPLEMENTED:
+    from typing import ParamSpec
+
+# 3.10+
+elif hasattr(typing, 'ParamSpec'):
+
+    # Add default parameter - PEP 696
+    class ParamSpec(metaclass=_TypeVarLikeMeta):
+        """Parameter specification."""
+
+        _backported_typevarlike = typing.ParamSpec
+
+        def __new__(cls, name, *, bound=None,
+                    covariant=False, contravariant=False,
+                    infer_variance=False, default=NoDefault):
+            if hasattr(typing, "TypeAliasType"):
+                # PEP 695 implemented, can pass infer_variance to typing.TypeVar
+                paramspec = typing.ParamSpec(name, bound=bound,
+                                             covariant=covariant,
+                                             contravariant=contravariant,
+                                             infer_variance=infer_variance)
+            else:
+                paramspec = typing.ParamSpec(name, bound=bound,
+                                             covariant=covariant,
+                                             contravariant=contravariant)
+                paramspec.__infer_variance__ = infer_variance
+
+            _set_default(paramspec, default)
+            _set_module(paramspec)
+
+            def _paramspec_prepare_subst(alias, args):
+                params = alias.__parameters__
+                i = params.index(paramspec)
+                if i == len(args) and paramspec.has_default():
+                    args = [*args, paramspec.__default__]
+                if i >= len(args):
+                    raise TypeError(f"Too few arguments for {alias}")
+                # Special case where Z[[int, str, bool]] == Z[int, str, bool] in PEP 612.
+                if len(params) == 1 and not typing._is_param_expr(args[0]):
+                    assert i == 0
+                    args = (args,)
+                # Convert lists to tuples to help other libraries cache the results.
+                elif isinstance(args[i], list):
+                    args = (*args[:i], tuple(args[i]), *args[i + 1:])
+                return args
+
+            paramspec.__typing_prepare_subst__ = _paramspec_prepare_subst
+            return paramspec
+
+        def __init_subclass__(cls) -> None:
+            raise TypeError(f"type '{__name__}.ParamSpec' is not an acceptable base type")
+
+# 3.8-3.9
+else:
+
+    # Inherits from list as a workaround for Callable checks in Python < 3.9.2.
+    class ParamSpec(list, _DefaultMixin):
+        """Parameter specification variable.
+
+        Usage::
+
+           P = ParamSpec('P')
+
+        Parameter specification variables exist primarily for the benefit of static
+        type checkers.  They are used to forward the parameter types of one
+        callable to another callable, a pattern commonly found in higher order
+        functions and decorators.  They are only valid when used in ``Concatenate``,
+        or s the first argument to ``Callable``. In Python 3.10 and higher,
+        they are also supported in user-defined Generics at runtime.
+        See class Generic for more information on generic types.  An
+        example for annotating a decorator::
+
+           T = TypeVar('T')
+           P = ParamSpec('P')
+
+           def add_logging(f: Callable[P, T]) -> Callable[P, T]:
+               '''A type-safe decorator to add logging to a function.'''
+               def inner(*args: P.args, **kwargs: P.kwargs) -> T:
+                   logging.info(f'{f.__name__} was called')
+                   return f(*args, **kwargs)
+               return inner
+
+           @add_logging
+           def add_two(x: float, y: float) -> float:
+               '''Add two numbers together.'''
+               return x + y
+
+        Parameter specification variables defined with covariant=True or
+        contravariant=True can be used to declare covariant or contravariant
+        generic types.  These keyword arguments are valid, but their actual semantics
+        are yet to be decided.  See PEP 612 for details.
+
+        Parameter specification variables can be introspected. e.g.:
+
+           P.__name__ == 'T'
+           P.__bound__ == None
+           P.__covariant__ == False
+           P.__contravariant__ == False
+
+        Note that only parameter specification variables defined in global scope can
+        be pickled.
+        """
+
+        # Trick Generic __parameters__.
+        __class__ = typing.TypeVar
+
+        @property
+        def args(self):
+            return ParamSpecArgs(self)
+
+        @property
+        def kwargs(self):
+            return ParamSpecKwargs(self)
+
+        def __init__(self, name, *, bound=None, covariant=False, contravariant=False,
+                     infer_variance=False, default=NoDefault):
+            list.__init__(self, [self])
+            self.__name__ = name
+            self.__covariant__ = bool(covariant)
+            self.__contravariant__ = bool(contravariant)
+            self.__infer_variance__ = bool(infer_variance)
+            if bound:
+                self.__bound__ = typing._type_check(bound, 'Bound must be a type.')
+            else:
+                self.__bound__ = None
+            _DefaultMixin.__init__(self, default)
+
+            # for pickling:
+            def_mod = _caller()
+            if def_mod != 'typing_extensions':
+                self.__module__ = def_mod
+
+        def __repr__(self):
+            if self.__infer_variance__:
+                prefix = ''
+            elif self.__covariant__:
+                prefix = '+'
+            elif self.__contravariant__:
+                prefix = '-'
+            else:
+                prefix = '~'
+            return prefix + self.__name__
+
+        def __hash__(self):
+            return object.__hash__(self)
+
+        def __eq__(self, other):
+            return self is other
+
+        def __reduce__(self):
+            return self.__name__
+
+        # Hack to get typing._type_check to pass.
+        def __call__(self, *args, **kwargs):
+            pass
+
+
+# 3.8-3.9
+if not hasattr(typing, 'Concatenate'):
+    # Inherits from list as a workaround for Callable checks in Python < 3.9.2.
+    class _ConcatenateGenericAlias(list):
+
+        # Trick Generic into looking into this for __parameters__.
+        __class__ = typing._GenericAlias
+
+        # Flag in 3.8.
+        _special = False
+
+        def __init__(self, origin, args):
+            super().__init__(args)
+            self.__origin__ = origin
+            self.__args__ = args
+
+        def __repr__(self):
+            _type_repr = typing._type_repr
+            return (f'{_type_repr(self.__origin__)}'
+                    f'[{", ".join(_type_repr(arg) for arg in self.__args__)}]')
+
+        def __hash__(self):
+            return hash((self.__origin__, self.__args__))
+
+        # Hack to get typing._type_check to pass in Generic.
+        def __call__(self, *args, **kwargs):
+            pass
+
+        @property
+        def __parameters__(self):
+            return tuple(
+                tp for tp in self.__args__ if isinstance(tp, (typing.TypeVar, ParamSpec))
+            )
+
+
+# 3.8-3.9
+@typing._tp_cache
+def _concatenate_getitem(self, parameters):
+    if parameters == ():
+        raise TypeError("Cannot take a Concatenate of no types.")
+    if not isinstance(parameters, tuple):
+        parameters = (parameters,)
+    if not isinstance(parameters[-1], ParamSpec):
+        raise TypeError("The last parameter to Concatenate should be a "
+                        "ParamSpec variable.")
+    msg = "Concatenate[arg, ...]: each arg must be a type."
+    parameters = tuple(typing._type_check(p, msg) for p in parameters)
+    return _ConcatenateGenericAlias(self, parameters)
+
+
+# 3.10+
+if hasattr(typing, 'Concatenate'):
+    Concatenate = typing.Concatenate
+    _ConcatenateGenericAlias = typing._ConcatenateGenericAlias
+# 3.9
+elif sys.version_info[:2] >= (3, 9):
+    @_ExtensionsSpecialForm
+    def Concatenate(self, parameters):
+        """Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
+        higher order function which adds, removes or transforms parameters of a
+        callable.
+
+        For example::
+
+           Callable[Concatenate[int, P], int]
+
+        See PEP 612 for detailed information.
+        """
+        return _concatenate_getitem(self, parameters)
+# 3.8
+else:
+    class _ConcatenateForm(_ExtensionsSpecialForm, _root=True):
+        def __getitem__(self, parameters):
+            return _concatenate_getitem(self, parameters)
+
+    Concatenate = _ConcatenateForm(
+        'Concatenate',
+        doc="""Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
+        higher order function which adds, removes or transforms parameters of a
+        callable.
+
+        For example::
+
+           Callable[Concatenate[int, P], int]
+
+        See PEP 612 for detailed information.
+        """)
+
+# 3.10+
+if hasattr(typing, 'TypeGuard'):
+    TypeGuard = typing.TypeGuard
+# 3.9
+elif sys.version_info[:2] >= (3, 9):
+    @_ExtensionsSpecialForm
+    def TypeGuard(self, parameters):
+        """Special typing form used to annotate the return type of a user-defined
+        type guard function.  ``TypeGuard`` only accepts a single type argument.
+        At runtime, functions marked this way should return a boolean.
+
+        ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
+        type checkers to determine a more precise type of an expression within a
+        program's code flow.  Usually type narrowing is done by analyzing
+        conditional code flow and applying the narrowing to a block of code.  The
+        conditional expression here is sometimes referred to as a "type guard".
+
+        Sometimes it would be convenient to use a user-defined boolean function
+        as a type guard.  Such a function should use ``TypeGuard[...]`` as its
+        return type to alert static type checkers to this intention.
+
+        Using  ``-> TypeGuard`` tells the static type checker that for a given
+        function:
+
+        1. The return value is a boolean.
+        2. If the return value is ``True``, the type of its argument
+        is the type inside ``TypeGuard``.
+
+        For example::
+
+            def is_str(val: Union[str, float]):
+                # "isinstance" type guard
+                if isinstance(val, str):
+                    # Type of ``val`` is narrowed to ``str``
+                    ...
+                else:
+                    # Else, type of ``val`` is narrowed to ``float``.
+                    ...
+
+        Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
+        form of ``TypeA`` (it can even be a wider form) and this may lead to
+        type-unsafe results.  The main reason is to allow for things like
+        narrowing ``List[object]`` to ``List[str]`` even though the latter is not
+        a subtype of the former, since ``List`` is invariant.  The responsibility of
+        writing type-safe type guards is left to the user.
+
+        ``TypeGuard`` also works with type variables.  For more information, see
+        PEP 647 (User-Defined Type Guards).
+        """
+        item = typing._type_check(parameters, f'{self} accepts only a single type.')
+        return typing._GenericAlias(self, (item,))
+# 3.8
+else:
+    class _TypeGuardForm(_ExtensionsSpecialForm, _root=True):
+        def __getitem__(self, parameters):
+            item = typing._type_check(parameters,
+                                      f'{self._name} accepts only a single type')
+            return typing._GenericAlias(self, (item,))
+
+    TypeGuard = _TypeGuardForm(
+        'TypeGuard',
+        doc="""Special typing form used to annotate the return type of a user-defined
+        type guard function.  ``TypeGuard`` only accepts a single type argument.
+        At runtime, functions marked this way should return a boolean.
+
+        ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
+        type checkers to determine a more precise type of an expression within a
+        program's code flow.  Usually type narrowing is done by analyzing
+        conditional code flow and applying the narrowing to a block of code.  The
+        conditional expression here is sometimes referred to as a "type guard".
+
+        Sometimes it would be convenient to use a user-defined boolean function
+        as a type guard.  Such a function should use ``TypeGuard[...]`` as its
+        return type to alert static type checkers to this intention.
+
+        Using  ``-> TypeGuard`` tells the static type checker that for a given
+        function:
+
+        1. The return value is a boolean.
+        2. If the return value is ``True``, the type of its argument
+        is the type inside ``TypeGuard``.
+
+        For example::
+
+            def is_str(val: Union[str, float]):
+                # "isinstance" type guard
+                if isinstance(val, str):
+                    # Type of ``val`` is narrowed to ``str``
+                    ...
+                else:
+                    # Else, type of ``val`` is narrowed to ``float``.
+                    ...
+
+        Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
+        form of ``TypeA`` (it can even be a wider form) and this may lead to
+        type-unsafe results.  The main reason is to allow for things like
+        narrowing ``List[object]`` to ``List[str]`` even though the latter is not
+        a subtype of the former, since ``List`` is invariant.  The responsibility of
+        writing type-safe type guards is left to the user.
+
+        ``TypeGuard`` also works with type variables.  For more information, see
+        PEP 647 (User-Defined Type Guards).
+        """)
+
+# 3.13+
+if hasattr(typing, 'TypeIs'):
+    TypeIs = typing.TypeIs
+# 3.9
+elif sys.version_info[:2] >= (3, 9):
+    @_ExtensionsSpecialForm
+    def TypeIs(self, parameters):
+        """Special typing form used to annotate the return type of a user-defined
+        type narrower function.  ``TypeIs`` only accepts a single type argument.
+        At runtime, functions marked this way should return a boolean.
+
+        ``TypeIs`` aims to benefit *type narrowing* -- a technique used by static
+        type checkers to determine a more precise type of an expression within a
+        program's code flow.  Usually type narrowing is done by analyzing
+        conditional code flow and applying the narrowing to a block of code.  The
+        conditional expression here is sometimes referred to as a "type guard".
+
+        Sometimes it would be convenient to use a user-defined boolean function
+        as a type guard.  Such a function should use ``TypeIs[...]`` as its
+        return type to alert static type checkers to this intention.
+
+        Using  ``-> TypeIs`` tells the static type checker that for a given
+        function:
+
+        1. The return value is a boolean.
+        2. If the return value is ``True``, the type of its argument
+        is the intersection of the type inside ``TypeGuard`` and the argument's
+        previously known type.
+
+        For example::
+
+            def is_awaitable(val: object) -> TypeIs[Awaitable[Any]]:
+                return hasattr(val, '__await__')
+
+            def f(val: Union[int, Awaitable[int]]) -> int:
+                if is_awaitable(val):
+                    assert_type(val, Awaitable[int])
+                else:
+                    assert_type(val, int)
+
+        ``TypeIs`` also works with type variables.  For more information, see
+        PEP 742 (Narrowing types with TypeIs).
+        """
+        item = typing._type_check(parameters, f'{self} accepts only a single type.')
+        return typing._GenericAlias(self, (item,))
+# 3.8
+else:
+    class _TypeIsForm(_ExtensionsSpecialForm, _root=True):
+        def __getitem__(self, parameters):
+            item = typing._type_check(parameters,
+                                      f'{self._name} accepts only a single type')
+            return typing._GenericAlias(self, (item,))
+
+    TypeIs = _TypeIsForm(
+        'TypeIs',
+        doc="""Special typing form used to annotate the return type of a user-defined
+        type narrower function.  ``TypeIs`` only accepts a single type argument.
+        At runtime, functions marked this way should return a boolean.
+
+        ``TypeIs`` aims to benefit *type narrowing* -- a technique used by static
+        type checkers to determine a more precise type of an expression within a
+        program's code flow.  Usually type narrowing is done by analyzing
+        conditional code flow and applying the narrowing to a block of code.  The
+        conditional expression here is sometimes referred to as a "type guard".
+
+        Sometimes it would be convenient to use a user-defined boolean function
+        as a type guard.  Such a function should use ``TypeIs[...]`` as its
+        return type to alert static type checkers to this intention.
+
+        Using  ``-> TypeIs`` tells the static type checker that for a given
+        function:
+
+        1. The return value is a boolean.
+        2. If the return value is ``True``, the type of its argument
+        is the intersection of the type inside ``TypeGuard`` and the argument's
+        previously known type.
+
+        For example::
+
+            def is_awaitable(val: object) -> TypeIs[Awaitable[Any]]:
+                return hasattr(val, '__await__')
+
+            def f(val: Union[int, Awaitable[int]]) -> int:
+                if is_awaitable(val):
+                    assert_type(val, Awaitable[int])
+                else:
+                    assert_type(val, int)
+
+        ``TypeIs`` also works with type variables.  For more information, see
+        PEP 742 (Narrowing types with TypeIs).
+        """)
+
+
+# Vendored from cpython typing._SpecialFrom
+class _SpecialForm(typing._Final, _root=True):
+    __slots__ = ('_name', '__doc__', '_getitem')
+
+    def __init__(self, getitem):
+        self._getitem = getitem
+        self._name = getitem.__name__
+        self.__doc__ = getitem.__doc__
+
+    def __getattr__(self, item):
+        if item in {'__name__', '__qualname__'}:
+            return self._name
+
+        raise AttributeError(item)
+
+    def __mro_entries__(self, bases):
+        raise TypeError(f"Cannot subclass {self!r}")
+
+    def __repr__(self):
+        return f'typing_extensions.{self._name}'
+
+    def __reduce__(self):
+        return self._name
+
+    def __call__(self, *args, **kwds):
+        raise TypeError(f"Cannot instantiate {self!r}")
+
+    def __or__(self, other):
+        return typing.Union[self, other]
+
+    def __ror__(self, other):
+        return typing.Union[other, self]
+
+    def __instancecheck__(self, obj):
+        raise TypeError(f"{self} cannot be used with isinstance()")
+
+    def __subclasscheck__(self, cls):
+        raise TypeError(f"{self} cannot be used with issubclass()")
+
+    @typing._tp_cache
+    def __getitem__(self, parameters):
+        return self._getitem(self, parameters)
+
+
+if hasattr(typing, "LiteralString"):  # 3.11+
+    LiteralString = typing.LiteralString
+else:
+    @_SpecialForm
+    def LiteralString(self, params):
+        """Represents an arbitrary literal string.
+
+        Example::
+
+          from typing_extensions import LiteralString
+
+          def query(sql: LiteralString) -> ...:
+              ...
+
+          query("SELECT * FROM table")  # ok
+          query(f"SELECT * FROM {input()}")  # not ok
+
+        See PEP 675 for details.
+
+        """
+        raise TypeError(f"{self} is not subscriptable")
+
+
+if hasattr(typing, "Self"):  # 3.11+
+    Self = typing.Self
+else:
+    @_SpecialForm
+    def Self(self, params):
+        """Used to spell the type of "self" in classes.
+
+        Example::
+
+          from typing import Self
+
+          class ReturnsSelf:
+              def parse(self, data: bytes) -> Self:
+                  ...
+                  return self
+
+        """
+
+        raise TypeError(f"{self} is not subscriptable")
+
+
+if hasattr(typing, "Never"):  # 3.11+
+    Never = typing.Never
+else:
+    @_SpecialForm
+    def Never(self, params):
+        """The bottom type, a type that has no members.
+
+        This can be used to define a function that should never be
+        called, or a function that never returns::
+
+            from typing_extensions import Never
+
+            def never_call_me(arg: Never) -> None:
+                pass
+
+            def int_or_str(arg: int | str) -> None:
+                never_call_me(arg)  # type checker error
+                match arg:
+                    case int():
+                        print("It's an int")
+                    case str():
+                        print("It's a str")
+                    case _:
+                        never_call_me(arg)  # ok, arg is of type Never
+
+        """
+
+        raise TypeError(f"{self} is not subscriptable")
+
+
+if hasattr(typing, 'Required'):  # 3.11+
+    Required = typing.Required
+    NotRequired = typing.NotRequired
+elif sys.version_info[:2] >= (3, 9):  # 3.9-3.10
+    @_ExtensionsSpecialForm
+    def Required(self, parameters):
+        """A special typing construct to mark a key of a total=False TypedDict
+        as required. For example:
+
+            class Movie(TypedDict, total=False):
+                title: Required[str]
+                year: int
+
+            m = Movie(
+                title='The Matrix',  # typechecker error if key is omitted
+                year=1999,
+            )
+
+        There is no runtime checking that a required key is actually provided
+        when instantiating a related TypedDict.
+        """
+        item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
+        return typing._GenericAlias(self, (item,))
+
+    @_ExtensionsSpecialForm
+    def NotRequired(self, parameters):
+        """A special typing construct to mark a key of a TypedDict as
+        potentially missing. For example:
+
+            class Movie(TypedDict):
+                title: str
+                year: NotRequired[int]
+
+            m = Movie(
+                title='The Matrix',  # typechecker error if key is omitted
+                year=1999,
+            )
+        """
+        item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
+        return typing._GenericAlias(self, (item,))
+
+else:  # 3.8
+    class _RequiredForm(_ExtensionsSpecialForm, _root=True):
+        def __getitem__(self, parameters):
+            item = typing._type_check(parameters,
+                                      f'{self._name} accepts only a single type.')
+            return typing._GenericAlias(self, (item,))
+
+    Required = _RequiredForm(
+        'Required',
+        doc="""A special typing construct to mark a key of a total=False TypedDict
+        as required. For example:
+
+            class Movie(TypedDict, total=False):
+                title: Required[str]
+                year: int
+
+            m = Movie(
+                title='The Matrix',  # typechecker error if key is omitted
+                year=1999,
+            )
+
+        There is no runtime checking that a required key is actually provided
+        when instantiating a related TypedDict.
+        """)
+    NotRequired = _RequiredForm(
+        'NotRequired',
+        doc="""A special typing construct to mark a key of a TypedDict as
+        potentially missing. For example:
+
+            class Movie(TypedDict):
+                title: str
+                year: NotRequired[int]
+
+            m = Movie(
+                title='The Matrix',  # typechecker error if key is omitted
+                year=1999,
+            )
+        """)
+
+
+if hasattr(typing, 'ReadOnly'):
+    ReadOnly = typing.ReadOnly
+elif sys.version_info[:2] >= (3, 9):  # 3.9-3.12
+    @_ExtensionsSpecialForm
+    def ReadOnly(self, parameters):
+        """A special typing construct to mark an item of a TypedDict as read-only.
+
+        For example:
+
+            class Movie(TypedDict):
+                title: ReadOnly[str]
+                year: int
+
+            def mutate_movie(m: Movie) -> None:
+                m["year"] = 1992  # allowed
+                m["title"] = "The Matrix"  # typechecker error
+
+        There is no runtime checking for this property.
+        """
+        item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
+        return typing._GenericAlias(self, (item,))
+
+else:  # 3.8
+    class _ReadOnlyForm(_ExtensionsSpecialForm, _root=True):
+        def __getitem__(self, parameters):
+            item = typing._type_check(parameters,
+                                      f'{self._name} accepts only a single type.')
+            return typing._GenericAlias(self, (item,))
+
+    ReadOnly = _ReadOnlyForm(
+        'ReadOnly',
+        doc="""A special typing construct to mark a key of a TypedDict as read-only.
+
+        For example:
+
+            class Movie(TypedDict):
+                title: ReadOnly[str]
+                year: int
+
+            def mutate_movie(m: Movie) -> None:
+                m["year"] = 1992  # allowed
+                m["title"] = "The Matrix"  # typechecker error
+
+        There is no runtime checking for this propery.
+        """)
+
+
+_UNPACK_DOC = """\
+Type unpack operator.
+
+The type unpack operator takes the child types from some container type,
+such as `tuple[int, str]` or a `TypeVarTuple`, and 'pulls them out'. For
+example:
+
+  # For some generic class `Foo`:
+  Foo[Unpack[tuple[int, str]]]  # Equivalent to Foo[int, str]
+
+  Ts = TypeVarTuple('Ts')
+  # Specifies that `Bar` is generic in an arbitrary number of types.
+  # (Think of `Ts` as a tuple of an arbitrary number of individual
+  #  `TypeVar`s, which the `Unpack` is 'pulling out' directly into the
+  #  `Generic[]`.)
+  class Bar(Generic[Unpack[Ts]]): ...
+  Bar[int]  # Valid
+  Bar[int, str]  # Also valid
+
+From Python 3.11, this can also be done using the `*` operator:
+
+    Foo[*tuple[int, str]]
+    class Bar(Generic[*Ts]): ...
+
+The operator can also be used along with a `TypedDict` to annotate
+`**kwargs` in a function signature. For instance:
+
+  class Movie(TypedDict):
+    name: str
+    year: int
+
+  # This function expects two keyword arguments - *name* of type `str` and
+  # *year* of type `int`.
+  def foo(**kwargs: Unpack[Movie]): ...
+
+Note that there is only some runtime checking of this operator. Not
+everything the runtime allows may be accepted by static type checkers.
+
+For more information, see PEP 646 and PEP 692.
+"""
+
+
+if sys.version_info >= (3, 12):  # PEP 692 changed the repr of Unpack[]
+    Unpack = typing.Unpack
+
+    def _is_unpack(obj):
+        return get_origin(obj) is Unpack
+
+elif sys.version_info[:2] >= (3, 9):  # 3.9+
+    class _UnpackSpecialForm(_ExtensionsSpecialForm, _root=True):
+        def __init__(self, getitem):
+            super().__init__(getitem)
+            self.__doc__ = _UNPACK_DOC
+
+    class _UnpackAlias(typing._GenericAlias, _root=True):
+        __class__ = typing.TypeVar
+
+        @property
+        def __typing_unpacked_tuple_args__(self):
+            assert self.__origin__ is Unpack
+            assert len(self.__args__) == 1
+            arg, = self.__args__
+            if isinstance(arg, (typing._GenericAlias, _types.GenericAlias)):
+                if arg.__origin__ is not tuple:
+                    raise TypeError("Unpack[...] must be used with a tuple type")
+                return arg.__args__
+            return None
+
+    @_UnpackSpecialForm
+    def Unpack(self, parameters):
+        item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
+        return _UnpackAlias(self, (item,))
+
+    def _is_unpack(obj):
+        return isinstance(obj, _UnpackAlias)
+
+else:  # 3.8
+    class _UnpackAlias(typing._GenericAlias, _root=True):
+        __class__ = typing.TypeVar
+
+    class _UnpackForm(_ExtensionsSpecialForm, _root=True):
+        def __getitem__(self, parameters):
+            item = typing._type_check(parameters,
+                                      f'{self._name} accepts only a single type.')
+            return _UnpackAlias(self, (item,))
+
+    Unpack = _UnpackForm('Unpack', doc=_UNPACK_DOC)
+
+    def _is_unpack(obj):
+        return isinstance(obj, _UnpackAlias)
+
+
+if _PEP_696_IMPLEMENTED:
+    from typing import TypeVarTuple
+
+elif hasattr(typing, "TypeVarTuple"):  # 3.11+
+
+    def _unpack_args(*args):
+        newargs = []
+        for arg in args:
+            subargs = getattr(arg, '__typing_unpacked_tuple_args__', None)
+            if subargs is not None and not (subargs and subargs[-1] is ...):
+                newargs.extend(subargs)
+            else:
+                newargs.append(arg)
+        return newargs
+
+    # Add default parameter - PEP 696
+    class TypeVarTuple(metaclass=_TypeVarLikeMeta):
+        """Type variable tuple."""
+
+        _backported_typevarlike = typing.TypeVarTuple
+
+        def __new__(cls, name, *, default=NoDefault):
+            tvt = typing.TypeVarTuple(name)
+            _set_default(tvt, default)
+            _set_module(tvt)
+
+            def _typevartuple_prepare_subst(alias, args):
+                params = alias.__parameters__
+                typevartuple_index = params.index(tvt)
+                for param in params[typevartuple_index + 1:]:
+                    if isinstance(param, TypeVarTuple):
+                        raise TypeError(
+                            f"More than one TypeVarTuple parameter in {alias}"
+                        )
+
+                alen = len(args)
+                plen = len(params)
+                left = typevartuple_index
+                right = plen - typevartuple_index - 1
+                var_tuple_index = None
+                fillarg = None
+                for k, arg in enumerate(args):
+                    if not isinstance(arg, type):
+                        subargs = getattr(arg, '__typing_unpacked_tuple_args__', None)
+                        if subargs and len(subargs) == 2 and subargs[-1] is ...:
+                            if var_tuple_index is not None:
+                                raise TypeError(
+                                    "More than one unpacked "
+                                    "arbitrary-length tuple argument"
+                                )
+                            var_tuple_index = k
+                            fillarg = subargs[0]
+                if var_tuple_index is not None:
+                    left = min(left, var_tuple_index)
+                    right = min(right, alen - var_tuple_index - 1)
+                elif left + right > alen:
+                    raise TypeError(f"Too few arguments for {alias};"
+                                    f" actual {alen}, expected at least {plen - 1}")
+                if left == alen - right and tvt.has_default():
+                    replacement = _unpack_args(tvt.__default__)
+                else:
+                    replacement = args[left: alen - right]
+
+                return (
+                    *args[:left],
+                    *([fillarg] * (typevartuple_index - left)),
+                    replacement,
+                    *([fillarg] * (plen - right - left - typevartuple_index - 1)),
+                    *args[alen - right:],
+                )
+
+            tvt.__typing_prepare_subst__ = _typevartuple_prepare_subst
+            return tvt
+
+        def __init_subclass__(self, *args, **kwds):
+            raise TypeError("Cannot subclass special typing classes")
+
+else:  # <=3.10
+    class TypeVarTuple(_DefaultMixin):
+        """Type variable tuple.
+
+        Usage::
+
+            Ts = TypeVarTuple('Ts')
+
+        In the same way that a normal type variable is a stand-in for a single
+        type such as ``int``, a type variable *tuple* is a stand-in for a *tuple*
+        type such as ``Tuple[int, str]``.
+
+        Type variable tuples can be used in ``Generic`` declarations.
+        Consider the following example::
+
+            class Array(Generic[*Ts]): ...
+
+        The ``Ts`` type variable tuple here behaves like ``tuple[T1, T2]``,
+        where ``T1`` and ``T2`` are type variables. To use these type variables
+        as type parameters of ``Array``, we must *unpack* the type variable tuple using
+        the star operator: ``*Ts``. The signature of ``Array`` then behaves
+        as if we had simply written ``class Array(Generic[T1, T2]): ...``.
+        In contrast to ``Generic[T1, T2]``, however, ``Generic[*Shape]`` allows
+        us to parameterise the class with an *arbitrary* number of type parameters.
+
+        Type variable tuples can be used anywhere a normal ``TypeVar`` can.
+        This includes class definitions, as shown above, as well as function
+        signatures and variable annotations::
+
+            class Array(Generic[*Ts]):
+
+                def __init__(self, shape: Tuple[*Ts]):
+                    self._shape: Tuple[*Ts] = shape
+
+                def get_shape(self) -> Tuple[*Ts]:
+                    return self._shape
+
+            shape = (Height(480), Width(640))
+            x: Array[Height, Width] = Array(shape)
+            y = abs(x)  # Inferred type is Array[Height, Width]
+            z = x + x   #        ...    is Array[Height, Width]
+            x.get_shape()  #     ...    is tuple[Height, Width]
+
+        """
+
+        # Trick Generic __parameters__.
+        __class__ = typing.TypeVar
+
+        def __iter__(self):
+            yield self.__unpacked__
+
+        def __init__(self, name, *, default=NoDefault):
+            self.__name__ = name
+            _DefaultMixin.__init__(self, default)
+
+            # for pickling:
+            def_mod = _caller()
+            if def_mod != 'typing_extensions':
+                self.__module__ = def_mod
+
+            self.__unpacked__ = Unpack[self]
+
+        def __repr__(self):
+            return self.__name__
+
+        def __hash__(self):
+            return object.__hash__(self)
+
+        def __eq__(self, other):
+            return self is other
+
+        def __reduce__(self):
+            return self.__name__
+
+        def __init_subclass__(self, *args, **kwds):
+            if '_root' not in kwds:
+                raise TypeError("Cannot subclass special typing classes")
+
+
+if hasattr(typing, "reveal_type"):  # 3.11+
+    reveal_type = typing.reveal_type
+else:  # <=3.10
+    def reveal_type(obj: T, /) -> T:
+        """Reveal the inferred type of a variable.
+
+        When a static type checker encounters a call to ``reveal_type()``,
+        it will emit the inferred type of the argument::
+
+            x: int = 1
+            reveal_type(x)
+
+        Running a static type checker (e.g., ``mypy``) on this example
+        will produce output similar to 'Revealed type is "builtins.int"'.
+
+        At runtime, the function prints the runtime type of the
+        argument and returns it unchanged.
+
+        """
+        print(f"Runtime type is {type(obj).__name__!r}", file=sys.stderr)
+        return obj
+
+
+if hasattr(typing, "_ASSERT_NEVER_REPR_MAX_LENGTH"):  # 3.11+
+    _ASSERT_NEVER_REPR_MAX_LENGTH = typing._ASSERT_NEVER_REPR_MAX_LENGTH
+else:  # <=3.10
+    _ASSERT_NEVER_REPR_MAX_LENGTH = 100
+
+
+if hasattr(typing, "assert_never"):  # 3.11+
+    assert_never = typing.assert_never
+else:  # <=3.10
+    def assert_never(arg: Never, /) -> Never:
+        """Assert to the type checker that a line of code is unreachable.
+
+        Example::
+
+            def int_or_str(arg: int | str) -> None:
+                match arg:
+                    case int():
+                        print("It's an int")
+                    case str():
+                        print("It's a str")
+                    case _:
+                        assert_never(arg)
+
+        If a type checker finds that a call to assert_never() is
+        reachable, it will emit an error.
+
+        At runtime, this throws an exception when called.
+
+        """
+        value = repr(arg)
+        if len(value) > _ASSERT_NEVER_REPR_MAX_LENGTH:
+            value = value[:_ASSERT_NEVER_REPR_MAX_LENGTH] + '...'
+        raise AssertionError(f"Expected code to be unreachable, but got: {value}")
+
+
+if sys.version_info >= (3, 12):  # 3.12+
+    # dataclass_transform exists in 3.11 but lacks the frozen_default parameter
+    dataclass_transform = typing.dataclass_transform
+else:  # <=3.11
+    def dataclass_transform(
+        *,
+        eq_default: bool = True,
+        order_default: bool = False,
+        kw_only_default: bool = False,
+        frozen_default: bool = False,
+        field_specifiers: typing.Tuple[
+            typing.Union[typing.Type[typing.Any], typing.Callable[..., typing.Any]],
+            ...
+        ] = (),
+        **kwargs: typing.Any,
+    ) -> typing.Callable[[T], T]:
+        """Decorator that marks a function, class, or metaclass as providing
+        dataclass-like behavior.
+
+        Example:
+
+            from typing_extensions import dataclass_transform
+
+            _T = TypeVar("_T")
+
+            # Used on a decorator function
+            @dataclass_transform()
+            def create_model(cls: type[_T]) -> type[_T]:
+                ...
+                return cls
+
+            @create_model
+            class CustomerModel:
+                id: int
+                name: str
+
+            # Used on a base class
+            @dataclass_transform()
+            class ModelBase: ...
+
+            class CustomerModel(ModelBase):
+                id: int
+                name: str
+
+            # Used on a metaclass
+            @dataclass_transform()
+            class ModelMeta(type): ...
+
+            class ModelBase(metaclass=ModelMeta): ...
+
+            class CustomerModel(ModelBase):
+                id: int
+                name: str
+
+        Each of the ``CustomerModel`` classes defined in this example will now
+        behave similarly to a dataclass created with the ``@dataclasses.dataclass``
+        decorator. For example, the type checker will synthesize an ``__init__``
+        method.
+
+        The arguments to this decorator can be used to customize this behavior:
+        - ``eq_default`` indicates whether the ``eq`` parameter is assumed to be
+          True or False if it is omitted by the caller.
+        - ``order_default`` indicates whether the ``order`` parameter is
+          assumed to be True or False if it is omitted by the caller.
+        - ``kw_only_default`` indicates whether the ``kw_only`` parameter is
+          assumed to be True or False if it is omitted by the caller.
+        - ``frozen_default`` indicates whether the ``frozen`` parameter is
+          assumed to be True or False if it is omitted by the caller.
+        - ``field_specifiers`` specifies a static list of supported classes
+          or functions that describe fields, similar to ``dataclasses.field()``.
+
+        At runtime, this decorator records its arguments in the
+        ``__dataclass_transform__`` attribute on the decorated object.
+
+        See PEP 681 for details.
+
+        """
+        def decorator(cls_or_fn):
+            cls_or_fn.__dataclass_transform__ = {
+                "eq_default": eq_default,
+                "order_default": order_default,
+                "kw_only_default": kw_only_default,
+                "frozen_default": frozen_default,
+                "field_specifiers": field_specifiers,
+                "kwargs": kwargs,
+            }
+            return cls_or_fn
+        return decorator
+
+
+if hasattr(typing, "override"):  # 3.12+
+    override = typing.override
+else:  # <=3.11
+    _F = typing.TypeVar("_F", bound=typing.Callable[..., typing.Any])
+
+    def override(arg: _F, /) -> _F:
+        """Indicate that a method is intended to override a method in a base class.
+
+        Usage:
+
+            class Base:
+                def method(self) -> None:
+                    pass
+
+            class Child(Base):
+                @override
+                def method(self) -> None:
+                    super().method()
+
+        When this decorator is applied to a method, the type checker will
+        validate that it overrides a method with the same name on a base class.
+        This helps prevent bugs that may occur when a base class is changed
+        without an equivalent change to a child class.
+
+        There is no runtime checking of these properties. The decorator
+        sets the ``__override__`` attribute to ``True`` on the decorated object
+        to allow runtime introspection.
+
+        See PEP 698 for details.
+
+        """
+        try:
+            arg.__override__ = True
+        except (AttributeError, TypeError):
+            # Skip the attribute silently if it is not writable.
+            # AttributeError happens if the object has __slots__ or a
+            # read-only property, TypeError if it's a builtin class.
+            pass
+        return arg
+
+
+if hasattr(warnings, "deprecated"):
+    deprecated = warnings.deprecated
+else:
+    _T = typing.TypeVar("_T")
+
+    class deprecated:
+        """Indicate that a class, function or overload is deprecated.
+
+        When this decorator is applied to an object, the type checker
+        will generate a diagnostic on usage of the deprecated object.
+
+        Usage:
+
+            @deprecated("Use B instead")
+            class A:
+                pass
+
+            @deprecated("Use g instead")
+            def f():
+                pass
+
+            @overload
+            @deprecated("int support is deprecated")
+            def g(x: int) -> int: ...
+            @overload
+            def g(x: str) -> int: ...
+
+        The warning specified by *category* will be emitted at runtime
+        on use of deprecated objects. For functions, that happens on calls;
+        for classes, on instantiation and on creation of subclasses.
+        If the *category* is ``None``, no warning is emitted at runtime.
+        The *stacklevel* determines where the
+        warning is emitted. If it is ``1`` (the default), the warning
+        is emitted at the direct caller of the deprecated object; if it
+        is higher, it is emitted further up the stack.
+        Static type checker behavior is not affected by the *category*
+        and *stacklevel* arguments.
+
+        The deprecation message passed to the decorator is saved in the
+        ``__deprecated__`` attribute on the decorated object.
+        If applied to an overload, the decorator
+        must be after the ``@overload`` decorator for the attribute to
+        exist on the overload as returned by ``get_overloads()``.
+
+        See PEP 702 for details.
+
+        """
+        def __init__(
+            self,
+            message: str,
+            /,
+            *,
+            category: typing.Optional[typing.Type[Warning]] = DeprecationWarning,
+            stacklevel: int = 1,
+        ) -> None:
+            if not isinstance(message, str):
+                raise TypeError(
+                    "Expected an object of type str for 'message', not "
+                    f"{type(message).__name__!r}"
+                )
+            self.message = message
+            self.category = category
+            self.stacklevel = stacklevel
+
+        def __call__(self, arg: _T, /) -> _T:
+            # Make sure the inner functions created below don't
+            # retain a reference to self.
+            msg = self.message
+            category = self.category
+            stacklevel = self.stacklevel
+            if category is None:
+                arg.__deprecated__ = msg
+                return arg
+            elif isinstance(arg, type):
+                import functools
+                from types import MethodType
+
+                original_new = arg.__new__
+
+                @functools.wraps(original_new)
+                def __new__(cls, *args, **kwargs):
+                    if cls is arg:
+                        warnings.warn(msg, category=category, stacklevel=stacklevel + 1)
+                    if original_new is not object.__new__:
+                        return original_new(cls, *args, **kwargs)
+                    # Mirrors a similar check in object.__new__.
+                    elif cls.__init__ is object.__init__ and (args or kwargs):
+                        raise TypeError(f"{cls.__name__}() takes no arguments")
+                    else:
+                        return original_new(cls)
+
+                arg.__new__ = staticmethod(__new__)
+
+                original_init_subclass = arg.__init_subclass__
+                # We need slightly different behavior if __init_subclass__
+                # is a bound method (likely if it was implemented in Python)
+                if isinstance(original_init_subclass, MethodType):
+                    original_init_subclass = original_init_subclass.__func__
+
+                    @functools.wraps(original_init_subclass)
+                    def __init_subclass__(*args, **kwargs):
+                        warnings.warn(msg, category=category, stacklevel=stacklevel + 1)
+                        return original_init_subclass(*args, **kwargs)
+
+                    arg.__init_subclass__ = classmethod(__init_subclass__)
+                # Or otherwise, which likely means it's a builtin such as
+                # object's implementation of __init_subclass__.
+                else:
+                    @functools.wraps(original_init_subclass)
+                    def __init_subclass__(*args, **kwargs):
+                        warnings.warn(msg, category=category, stacklevel=stacklevel + 1)
+                        return original_init_subclass(*args, **kwargs)
+
+                    arg.__init_subclass__ = __init_subclass__
+
+                arg.__deprecated__ = __new__.__deprecated__ = msg
+                __init_subclass__.__deprecated__ = msg
+                return arg
+            elif callable(arg):
+                import functools
+
+                @functools.wraps(arg)
+                def wrapper(*args, **kwargs):
+                    warnings.warn(msg, category=category, stacklevel=stacklevel + 1)
+                    return arg(*args, **kwargs)
+
+                arg.__deprecated__ = wrapper.__deprecated__ = msg
+                return wrapper
+            else:
+                raise TypeError(
+                    "@deprecated decorator with non-None category must be applied to "
+                    f"a class or callable, not {arg!r}"
+                )
+
+
+# We have to do some monkey patching to deal with the dual nature of
+# Unpack/TypeVarTuple:
+# - We want Unpack to be a kind of TypeVar so it gets accepted in
+#   Generic[Unpack[Ts]]
+# - We want it to *not* be treated as a TypeVar for the purposes of
+#   counting generic parameters, so that when we subscript a generic,
+#   the runtime doesn't try to substitute the Unpack with the subscripted type.
+if not hasattr(typing, "TypeVarTuple"):
+    def _check_generic(cls, parameters, elen=_marker):
+        """Check correct count for parameters of a generic cls (internal helper).
+
+        This gives a nice error message in case of count mismatch.
+        """
+        if not elen:
+            raise TypeError(f"{cls} is not a generic class")
+        if elen is _marker:
+            if not hasattr(cls, "__parameters__") or not cls.__parameters__:
+                raise TypeError(f"{cls} is not a generic class")
+            elen = len(cls.__parameters__)
+        alen = len(parameters)
+        if alen != elen:
+            expect_val = elen
+            if hasattr(cls, "__parameters__"):
+                parameters = [p for p in cls.__parameters__ if not _is_unpack(p)]
+                num_tv_tuples = sum(isinstance(p, TypeVarTuple) for p in parameters)
+                if (num_tv_tuples > 0) and (alen >= elen - num_tv_tuples):
+                    return
+
+                # deal with TypeVarLike defaults
+                # required TypeVarLikes cannot appear after a defaulted one.
+                if alen < elen:
+                    # since we validate TypeVarLike default in _collect_type_vars
+                    # or _collect_parameters we can safely check parameters[alen]
+                    if (
+                        getattr(parameters[alen], '__default__', NoDefault)
+                        is not NoDefault
+                    ):
+                        return
+
+                    num_default_tv = sum(getattr(p, '__default__', NoDefault)
+                                         is not NoDefault for p in parameters)
+
+                    elen -= num_default_tv
+
+                    expect_val = f"at least {elen}"
+
+            things = "arguments" if sys.version_info >= (3, 10) else "parameters"
+            raise TypeError(f"Too {'many' if alen > elen else 'few'} {things}"
+                            f" for {cls}; actual {alen}, expected {expect_val}")
+else:
+    # Python 3.11+
+
+    def _check_generic(cls, parameters, elen):
+        """Check correct count for parameters of a generic cls (internal helper).
+
+        This gives a nice error message in case of count mismatch.
+        """
+        if not elen:
+            raise TypeError(f"{cls} is not a generic class")
+        alen = len(parameters)
+        if alen != elen:
+            expect_val = elen
+            if hasattr(cls, "__parameters__"):
+                parameters = [p for p in cls.__parameters__ if not _is_unpack(p)]
+
+                # deal with TypeVarLike defaults
+                # required TypeVarLikes cannot appear after a defaulted one.
+                if alen < elen:
+                    # since we validate TypeVarLike default in _collect_type_vars
+                    # or _collect_parameters we can safely check parameters[alen]
+                    if (
+                        getattr(parameters[alen], '__default__', NoDefault)
+                        is not NoDefault
+                    ):
+                        return
+
+                    num_default_tv = sum(getattr(p, '__default__', NoDefault)
+                                         is not NoDefault for p in parameters)
+
+                    elen -= num_default_tv
+
+                    expect_val = f"at least {elen}"
+
+            raise TypeError(f"Too {'many' if alen > elen else 'few'} arguments"
+                            f" for {cls}; actual {alen}, expected {expect_val}")
+
+if not _PEP_696_IMPLEMENTED:
+    typing._check_generic = _check_generic
+
+
+def _has_generic_or_protocol_as_origin() -> bool:
+    try:
+        frame = sys._getframe(2)
+    # - Catch AttributeError: not all Python implementations have sys._getframe()
+    # - Catch ValueError: maybe we're called from an unexpected module
+    #   and the call stack isn't deep enough
+    except (AttributeError, ValueError):
+        return False  # err on the side of leniency
+    else:
+        # If we somehow get invoked from outside typing.py,
+        # also err on the side of leniency
+        if frame.f_globals.get("__name__") != "typing":
+            return False
+        origin = frame.f_locals.get("origin")
+        # Cannot use "in" because origin may be an object with a buggy __eq__ that
+        # throws an error.
+        return origin is typing.Generic or origin is Protocol or origin is typing.Protocol
+
+
+_TYPEVARTUPLE_TYPES = {TypeVarTuple, getattr(typing, "TypeVarTuple", None)}
+
+
+def _is_unpacked_typevartuple(x) -> bool:
+    if get_origin(x) is not Unpack:
+        return False
+    args = get_args(x)
+    return (
+        bool(args)
+        and len(args) == 1
+        and type(args[0]) in _TYPEVARTUPLE_TYPES
+    )
+
+
+# Python 3.11+ _collect_type_vars was renamed to _collect_parameters
+if hasattr(typing, '_collect_type_vars'):
+    def _collect_type_vars(types, typevar_types=None):
+        """Collect all type variable contained in types in order of
+        first appearance (lexicographic order). For example::
+
+            _collect_type_vars((T, List[S, T])) == (T, S)
+        """
+        if typevar_types is None:
+            typevar_types = typing.TypeVar
+        tvars = []
+
+        # A required TypeVarLike cannot appear after a TypeVarLike with a default
+        # if it was a direct call to `Generic[]` or `Protocol[]`
+        enforce_default_ordering = _has_generic_or_protocol_as_origin()
+        default_encountered = False
+
+        # Also, a TypeVarLike with a default cannot appear after a TypeVarTuple
+        type_var_tuple_encountered = False
+
+        for t in types:
+            if _is_unpacked_typevartuple(t):
+                type_var_tuple_encountered = True
+            elif isinstance(t, typevar_types) and t not in tvars:
+                if enforce_default_ordering:
+                    has_default = getattr(t, '__default__', NoDefault) is not NoDefault
+                    if has_default:
+                        if type_var_tuple_encountered:
+                            raise TypeError('Type parameter with a default'
+                                            ' follows TypeVarTuple')
+                        default_encountered = True
+                    elif default_encountered:
+                        raise TypeError(f'Type parameter {t!r} without a default'
+                                        ' follows type parameter with a default')
+
+                tvars.append(t)
+            if _should_collect_from_parameters(t):
+                tvars.extend([t for t in t.__parameters__ if t not in tvars])
+        return tuple(tvars)
+
+    typing._collect_type_vars = _collect_type_vars
+else:
+    def _collect_parameters(args):
+        """Collect all type variables and parameter specifications in args
+        in order of first appearance (lexicographic order).
+
+        For example::
+
+            assert _collect_parameters((T, Callable[P, T])) == (T, P)
+        """
+        parameters = []
+
+        # A required TypeVarLike cannot appear after a TypeVarLike with default
+        # if it was a direct call to `Generic[]` or `Protocol[]`
+        enforce_default_ordering = _has_generic_or_protocol_as_origin()
+        default_encountered = False
+
+        # Also, a TypeVarLike with a default cannot appear after a TypeVarTuple
+        type_var_tuple_encountered = False
+
+        for t in args:
+            if isinstance(t, type):
+                # We don't want __parameters__ descriptor of a bare Python class.
+                pass
+            elif isinstance(t, tuple):
+                # `t` might be a tuple, when `ParamSpec` is substituted with
+                # `[T, int]`, or `[int, *Ts]`, etc.
+                for x in t:
+                    for collected in _collect_parameters([x]):
+                        if collected not in parameters:
+                            parameters.append(collected)
+            elif hasattr(t, '__typing_subst__'):
+                if t not in parameters:
+                    if enforce_default_ordering:
+                        has_default = (
+                            getattr(t, '__default__', NoDefault) is not NoDefault
+                        )
+
+                        if type_var_tuple_encountered and has_default:
+                            raise TypeError('Type parameter with a default'
+                                            ' follows TypeVarTuple')
+
+                        if has_default:
+                            default_encountered = True
+                        elif default_encountered:
+                            raise TypeError(f'Type parameter {t!r} without a default'
+                                            ' follows type parameter with a default')
+
+                    parameters.append(t)
+            else:
+                if _is_unpacked_typevartuple(t):
+                    type_var_tuple_encountered = True
+                for x in getattr(t, '__parameters__', ()):
+                    if x not in parameters:
+                        parameters.append(x)
+
+        return tuple(parameters)
+
+    if not _PEP_696_IMPLEMENTED:
+        typing._collect_parameters = _collect_parameters
+
+# Backport typing.NamedTuple as it exists in Python 3.13.
+# In 3.11, the ability to define generic `NamedTuple`s was supported.
+# This was explicitly disallowed in 3.9-3.10, and only half-worked in <=3.8.
+# On 3.12, we added __orig_bases__ to call-based NamedTuples
+# On 3.13, we deprecated kwargs-based NamedTuples
+if sys.version_info >= (3, 13):
+    NamedTuple = typing.NamedTuple
+else:
+    def _make_nmtuple(name, types, module, defaults=()):
+        fields = [n for n, t in types]
+        annotations = {n: typing._type_check(t, f"field {n} annotation must be a type")
+                       for n, t in types}
+        nm_tpl = collections.namedtuple(name, fields,
+                                        defaults=defaults, module=module)
+        nm_tpl.__annotations__ = nm_tpl.__new__.__annotations__ = annotations
+        # The `_field_types` attribute was removed in 3.9;
+        # in earlier versions, it is the same as the `__annotations__` attribute
+        if sys.version_info < (3, 9):
+            nm_tpl._field_types = annotations
+        return nm_tpl
+
+    _prohibited_namedtuple_fields = typing._prohibited
+    _special_namedtuple_fields = frozenset({'__module__', '__name__', '__annotations__'})
+
+    class _NamedTupleMeta(type):
+        def __new__(cls, typename, bases, ns):
+            assert _NamedTuple in bases
+            for base in bases:
+                if base is not _NamedTuple and base is not typing.Generic:
+                    raise TypeError(
+                        'can only inherit from a NamedTuple type and Generic')
+            bases = tuple(tuple if base is _NamedTuple else base for base in bases)
+            if "__annotations__" in ns:
+                types = ns["__annotations__"]
+            elif "__annotate__" in ns:
+                # TODO: Use inspect.VALUE here, and make the annotations lazily evaluated
+                types = ns["__annotate__"](1)
+            else:
+                types = {}
+            default_names = []
+            for field_name in types:
+                if field_name in ns:
+                    default_names.append(field_name)
+                elif default_names:
+                    raise TypeError(f"Non-default namedtuple field {field_name} "
+                                    f"cannot follow default field"
+                                    f"{'s' if len(default_names) > 1 else ''} "
+                                    f"{', '.join(default_names)}")
+            nm_tpl = _make_nmtuple(
+                typename, types.items(),
+                defaults=[ns[n] for n in default_names],
+                module=ns['__module__']
+            )
+            nm_tpl.__bases__ = bases
+            if typing.Generic in bases:
+                if hasattr(typing, '_generic_class_getitem'):  # 3.12+
+                    nm_tpl.__class_getitem__ = classmethod(typing._generic_class_getitem)
+                else:
+                    class_getitem = typing.Generic.__class_getitem__.__func__
+                    nm_tpl.__class_getitem__ = classmethod(class_getitem)
+            # update from user namespace without overriding special namedtuple attributes
+            for key, val in ns.items():
+                if key in _prohibited_namedtuple_fields:
+                    raise AttributeError("Cannot overwrite NamedTuple attribute " + key)
+                elif key not in _special_namedtuple_fields:
+                    if key not in nm_tpl._fields:
+                        setattr(nm_tpl, key, ns[key])
+                    try:
+                        set_name = type(val).__set_name__
+                    except AttributeError:
+                        pass
+                    else:
+                        try:
+                            set_name(val, nm_tpl, key)
+                        except BaseException as e:
+                            msg = (
+                                f"Error calling __set_name__ on {type(val).__name__!r} "
+                                f"instance {key!r} in {typename!r}"
+                            )
+                            # BaseException.add_note() existed on py311,
+                            # but the __set_name__ machinery didn't start
+                            # using add_note() until py312.
+                            # Making sure exceptions are raised in the same way
+                            # as in "normal" classes seems most important here.
+                            if sys.version_info >= (3, 12):
+                                e.add_note(msg)
+                                raise
+                            else:
+                                raise RuntimeError(msg) from e
+
+            if typing.Generic in bases:
+                nm_tpl.__init_subclass__()
+            return nm_tpl
+
+    _NamedTuple = type.__new__(_NamedTupleMeta, 'NamedTuple', (), {})
+
+    def _namedtuple_mro_entries(bases):
+        assert NamedTuple in bases
+        return (_NamedTuple,)
+
+    @_ensure_subclassable(_namedtuple_mro_entries)
+    def NamedTuple(typename, fields=_marker, /, **kwargs):
+        """Typed version of namedtuple.
+
+        Usage::
+
+            class Employee(NamedTuple):
+                name: str
+                id: int
+
+        This is equivalent to::
+
+            Employee = collections.namedtuple('Employee', ['name', 'id'])
+
+        The resulting class has an extra __annotations__ attribute, giving a
+        dict that maps field names to types.  (The field names are also in
+        the _fields attribute, which is part of the namedtuple API.)
+        An alternative equivalent functional syntax is also accepted::
+
+            Employee = NamedTuple('Employee', [('name', str), ('id', int)])
+        """
+        if fields is _marker:
+            if kwargs:
+                deprecated_thing = "Creating NamedTuple classes using keyword arguments"
+                deprecation_msg = (
+                    "{name} is deprecated and will be disallowed in Python {remove}. "
+                    "Use the class-based or functional syntax instead."
+                )
+            else:
+                deprecated_thing = "Failing to pass a value for the 'fields' parameter"
+                example = f"`{typename} = NamedTuple({typename!r}, [])`"
+                deprecation_msg = (
+                    "{name} is deprecated and will be disallowed in Python {remove}. "
+                    "To create a NamedTuple class with 0 fields "
+                    "using the functional syntax, "
+                    "pass an empty list, e.g. "
+                ) + example + "."
+        elif fields is None:
+            if kwargs:
+                raise TypeError(
+                    "Cannot pass `None` as the 'fields' parameter "
+                    "and also specify fields using keyword arguments"
+                )
+            else:
+                deprecated_thing = "Passing `None` as the 'fields' parameter"
+                example = f"`{typename} = NamedTuple({typename!r}, [])`"
+                deprecation_msg = (
+                    "{name} is deprecated and will be disallowed in Python {remove}. "
+                    "To create a NamedTuple class with 0 fields "
+                    "using the functional syntax, "
+                    "pass an empty list, e.g. "
+                ) + example + "."
+        elif kwargs:
+            raise TypeError("Either list of fields or keywords"
+                            " can be provided to NamedTuple, not both")
+        if fields is _marker or fields is None:
+            warnings.warn(
+                deprecation_msg.format(name=deprecated_thing, remove="3.15"),
+                DeprecationWarning,
+                stacklevel=2,
+            )
+            fields = kwargs.items()
+        nt = _make_nmtuple(typename, fields, module=_caller())
+        nt.__orig_bases__ = (NamedTuple,)
+        return nt
+
+
+if hasattr(collections.abc, "Buffer"):
+    Buffer = collections.abc.Buffer
+else:
+    class Buffer(abc.ABC):  # noqa: B024
+        """Base class for classes that implement the buffer protocol.
+
+        The buffer protocol allows Python objects to expose a low-level
+        memory buffer interface. Before Python 3.12, it is not possible
+        to implement the buffer protocol in pure Python code, or even
+        to check whether a class implements the buffer protocol. In
+        Python 3.12 and higher, the ``__buffer__`` method allows access
+        to the buffer protocol from Python code, and the
+        ``collections.abc.Buffer`` ABC allows checking whether a class
+        implements the buffer protocol.
+
+        To indicate support for the buffer protocol in earlier versions,
+        inherit from this ABC, either in a stub file or at runtime,
+        or use ABC registration. This ABC provides no methods, because
+        there is no Python-accessible methods shared by pre-3.12 buffer
+        classes. It is useful primarily for static checks.
+
+        """
+
+    # As a courtesy, register the most common stdlib buffer classes.
+    Buffer.register(memoryview)
+    Buffer.register(bytearray)
+    Buffer.register(bytes)
+
+
+# Backport of types.get_original_bases, available on 3.12+ in CPython
+if hasattr(_types, "get_original_bases"):
+    get_original_bases = _types.get_original_bases
+else:
+    def get_original_bases(cls, /):
+        """Return the class's "original" bases prior to modification by `__mro_entries__`.
+
+        Examples::
+
+            from typing import TypeVar, Generic
+            from typing_extensions import NamedTuple, TypedDict
+
+            T = TypeVar("T")
+            class Foo(Generic[T]): ...
+            class Bar(Foo[int], float): ...
+            class Baz(list[str]): ...
+            Eggs = NamedTuple("Eggs", [("a", int), ("b", str)])
+            Spam = TypedDict("Spam", {"a": int, "b": str})
+
+            assert get_original_bases(Bar) == (Foo[int], float)
+            assert get_original_bases(Baz) == (list[str],)
+            assert get_original_bases(Eggs) == (NamedTuple,)
+            assert get_original_bases(Spam) == (TypedDict,)
+            assert get_original_bases(int) == (object,)
+        """
+        try:
+            return cls.__dict__.get("__orig_bases__", cls.__bases__)
+        except AttributeError:
+            raise TypeError(
+                f'Expected an instance of type, not {type(cls).__name__!r}'
+            ) from None
+
+
+# NewType is a class on Python 3.10+, making it pickleable
+# The error message for subclassing instances of NewType was improved on 3.11+
+if sys.version_info >= (3, 11):
+    NewType = typing.NewType
+else:
+    class NewType:
+        """NewType creates simple unique types with almost zero
+        runtime overhead. NewType(name, tp) is considered a subtype of tp
+        by static type checkers. At runtime, NewType(name, tp) returns
+        a dummy callable that simply returns its argument. Usage::
+            UserId = NewType('UserId', int)
+            def name_by_id(user_id: UserId) -> str:
+                ...
+            UserId('user')          # Fails type check
+            name_by_id(42)          # Fails type check
+            name_by_id(UserId(42))  # OK
+            num = UserId(5) + 1     # type: int
+        """
+
+        def __call__(self, obj, /):
+            return obj
+
+        def __init__(self, name, tp):
+            self.__qualname__ = name
+            if '.' in name:
+                name = name.rpartition('.')[-1]
+            self.__name__ = name
+            self.__supertype__ = tp
+            def_mod = _caller()
+            if def_mod != 'typing_extensions':
+                self.__module__ = def_mod
+
+        def __mro_entries__(self, bases):
+            # We defined __mro_entries__ to get a better error message
+            # if a user attempts to subclass a NewType instance. bpo-46170
+            supercls_name = self.__name__
+
+            class Dummy:
+                def __init_subclass__(cls):
+                    subcls_name = cls.__name__
+                    raise TypeError(
+                        f"Cannot subclass an instance of NewType. "
+                        f"Perhaps you were looking for: "
+                        f"`{subcls_name} = NewType({subcls_name!r}, {supercls_name})`"
+                    )
+
+            return (Dummy,)
+
+        def __repr__(self):
+            return f'{self.__module__}.{self.__qualname__}'
+
+        def __reduce__(self):
+            return self.__qualname__
+
+        if sys.version_info >= (3, 10):
+            # PEP 604 methods
+            # It doesn't make sense to have these methods on Python <3.10
+
+            def __or__(self, other):
+                return typing.Union[self, other]
+
+            def __ror__(self, other):
+                return typing.Union[other, self]
+
+
+if hasattr(typing, "TypeAliasType"):
+    TypeAliasType = typing.TypeAliasType
+else:
+    def _is_unionable(obj):
+        """Corresponds to is_unionable() in unionobject.c in CPython."""
+        return obj is None or isinstance(obj, (
+            type,
+            _types.GenericAlias,
+            _types.UnionType,
+            TypeAliasType,
+        ))
+
+    class TypeAliasType:
+        """Create named, parameterized type aliases.
+
+        This provides a backport of the new `type` statement in Python 3.12:
+
+            type ListOrSet[T] = list[T] | set[T]
+
+        is equivalent to:
+
+            T = TypeVar("T")
+            ListOrSet = TypeAliasType("ListOrSet", list[T] | set[T], type_params=(T,))
+
+        The name ListOrSet can then be used as an alias for the type it refers to.
+
+        The type_params argument should contain all the type parameters used
+        in the value of the type alias. If the alias is not generic, this
+        argument is omitted.
+
+        Static type checkers should only support type aliases declared using
+        TypeAliasType that follow these rules:
+
+        - The first argument (the name) must be a string literal.
+        - The TypeAliasType instance must be immediately assigned to a variable
+          of the same name. (For example, 'X = TypeAliasType("Y", int)' is invalid,
+          as is 'X, Y = TypeAliasType("X", int), TypeAliasType("Y", int)').
+
+        """
+
+        def __init__(self, name: str, value, *, type_params=()):
+            if not isinstance(name, str):
+                raise TypeError("TypeAliasType name must be a string")
+            self.__value__ = value
+            self.__type_params__ = type_params
+
+            parameters = []
+            for type_param in type_params:
+                if isinstance(type_param, TypeVarTuple):
+                    parameters.extend(type_param)
+                else:
+                    parameters.append(type_param)
+            self.__parameters__ = tuple(parameters)
+            def_mod = _caller()
+            if def_mod != 'typing_extensions':
+                self.__module__ = def_mod
+            # Setting this attribute closes the TypeAliasType from further modification
+            self.__name__ = name
+
+        def __setattr__(self, name: str, value: object, /) -> None:
+            if hasattr(self, "__name__"):
+                self._raise_attribute_error(name)
+            super().__setattr__(name, value)
+
+        def __delattr__(self, name: str, /) -> Never:
+            self._raise_attribute_error(name)
+
+        def _raise_attribute_error(self, name: str) -> Never:
+            # Match the Python 3.12 error messages exactly
+            if name == "__name__":
+                raise AttributeError("readonly attribute")
+            elif name in {"__value__", "__type_params__", "__parameters__", "__module__"}:
+                raise AttributeError(
+                    f"attribute '{name}' of 'typing.TypeAliasType' objects "
+                    "is not writable"
+                )
+            else:
+                raise AttributeError(
+                    f"'typing.TypeAliasType' object has no attribute '{name}'"
+                )
+
+        def __repr__(self) -> str:
+            return self.__name__
+
+        def __getitem__(self, parameters):
+            if not isinstance(parameters, tuple):
+                parameters = (parameters,)
+            parameters = [
+                typing._type_check(
+                    item, f'Subscripting {self.__name__} requires a type.'
+                )
+                for item in parameters
+            ]
+            return typing._GenericAlias(self, tuple(parameters))
+
+        def __reduce__(self):
+            return self.__name__
+
+        def __init_subclass__(cls, *args, **kwargs):
+            raise TypeError(
+                "type 'typing_extensions.TypeAliasType' is not an acceptable base type"
+            )
+
+        # The presence of this method convinces typing._type_check
+        # that TypeAliasTypes are types.
+        def __call__(self):
+            raise TypeError("Type alias is not callable")
+
+        if sys.version_info >= (3, 10):
+            def __or__(self, right):
+                # For forward compatibility with 3.12, reject Unions
+                # that are not accepted by the built-in Union.
+                if not _is_unionable(right):
+                    return NotImplemented
+                return typing.Union[self, right]
+
+            def __ror__(self, left):
+                if not _is_unionable(left):
+                    return NotImplemented
+                return typing.Union[left, self]
+
+
+if hasattr(typing, "is_protocol"):
+    is_protocol = typing.is_protocol
+    get_protocol_members = typing.get_protocol_members
+else:
+    def is_protocol(tp: type, /) -> bool:
+        """Return True if the given type is a Protocol.
+
+        Example::
+
+            >>> from typing_extensions import Protocol, is_protocol
+            >>> class P(Protocol):
+            ...     def a(self) -> str: ...
+            ...     b: int
+            >>> is_protocol(P)
+            True
+            >>> is_protocol(int)
+            False
+        """
+        return (
+            isinstance(tp, type)
+            and getattr(tp, '_is_protocol', False)
+            and tp is not Protocol
+            and tp is not typing.Protocol
+        )
+
+    def get_protocol_members(tp: type, /) -> typing.FrozenSet[str]:
+        """Return the set of members defined in a Protocol.
+
+        Example::
+
+            >>> from typing_extensions import Protocol, get_protocol_members
+            >>> class P(Protocol):
+            ...     def a(self) -> str: ...
+            ...     b: int
+            >>> get_protocol_members(P)
+            frozenset({'a', 'b'})
+
+        Raise a TypeError for arguments that are not Protocols.
+        """
+        if not is_protocol(tp):
+            raise TypeError(f'{tp!r} is not a Protocol')
+        if hasattr(tp, '__protocol_attrs__'):
+            return frozenset(tp.__protocol_attrs__)
+        return frozenset(_get_protocol_attrs(tp))
+
+
+if hasattr(typing, "Doc"):
+    Doc = typing.Doc
+else:
+    class Doc:
+        """Define the documentation of a type annotation using ``Annotated``, to be
+         used in class attributes, function and method parameters, return values,
+         and variables.
+
+        The value should be a positional-only string literal to allow static tools
+        like editors and documentation generators to use it.
+
+        This complements docstrings.
+
+        The string value passed is available in the attribute ``documentation``.
+
+        Example::
+
+            >>> from typing_extensions import Annotated, Doc
+            >>> def hi(to: Annotated[str, Doc("Who to say hi to")]) -> None: ...
+        """
+        def __init__(self, documentation: str, /) -> None:
+            self.documentation = documentation
+
+        def __repr__(self) -> str:
+            return f"Doc({self.documentation!r})"
+
+        def __hash__(self) -> int:
+            return hash(self.documentation)
+
+        def __eq__(self, other: object) -> bool:
+            if not isinstance(other, Doc):
+                return NotImplemented
+            return self.documentation == other.documentation
+
+
+_CapsuleType = getattr(_types, "CapsuleType", None)
+
+if _CapsuleType is None:
+    try:
+        import _socket
+    except ImportError:
+        pass
+    else:
+        _CAPI = getattr(_socket, "CAPI", None)
+        if _CAPI is not None:
+            _CapsuleType = type(_CAPI)
+
+if _CapsuleType is not None:
+    CapsuleType = _CapsuleType
+    __all__.append("CapsuleType")
+
+
+# Aliases for items that have always been in typing.
+# Explicitly assign these (rather than using `from typing import *` at the top),
+# so that we get a CI error if one of these is deleted from typing.py
+# in a future version of Python
+AbstractSet = typing.AbstractSet
+AnyStr = typing.AnyStr
+BinaryIO = typing.BinaryIO
+Callable = typing.Callable
+Collection = typing.Collection
+Container = typing.Container
+Dict = typing.Dict
+ForwardRef = typing.ForwardRef
+FrozenSet = typing.FrozenSet
+Generic = typing.Generic
+Hashable = typing.Hashable
+IO = typing.IO
+ItemsView = typing.ItemsView
+Iterable = typing.Iterable
+Iterator = typing.Iterator
+KeysView = typing.KeysView
+List = typing.List
+Mapping = typing.Mapping
+MappingView = typing.MappingView
+Match = typing.Match
+MutableMapping = typing.MutableMapping
+MutableSequence = typing.MutableSequence
+MutableSet = typing.MutableSet
+Optional = typing.Optional
+Pattern = typing.Pattern
+Reversible = typing.Reversible
+Sequence = typing.Sequence
+Set = typing.Set
+Sized = typing.Sized
+TextIO = typing.TextIO
+Tuple = typing.Tuple
+Union = typing.Union
+ValuesView = typing.ValuesView
+cast = typing.cast
+no_type_check = typing.no_type_check
+no_type_check_decorator = typing.no_type_check_decorator
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/LICENSE.txt b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/LICENSE.txt
new file mode 100644
index 0000000000000000000000000000000000000000..a31470f14c5978d5fcc3bc173b8399b6c9a6443f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/LICENSE.txt
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2012 Daniel Holth  and contributors
+
+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.12/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/METADATA b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..f645dcb673aaa7e3e7e054d57af5e8c0992b70e8
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/METADATA
@@ -0,0 +1,66 @@
+Metadata-Version: 2.3
+Name: wheel
+Version: 0.45.1
+Summary: A built-package format for Python
+Keywords: wheel,packaging
+Author-email: Daniel Holth 
+Maintainer-email: Alex Grönholm 
+Requires-Python: >=3.8
+Description-Content-Type: text/x-rst
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: Topic :: System :: Archiving :: Packaging
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 3 :: Only
+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
+Requires-Dist: pytest >= 6.0.0 ; extra == "test"
+Requires-Dist: setuptools >= 65 ; extra == "test"
+Project-URL: Changelog, https://wheel.readthedocs.io/en/stable/news.html
+Project-URL: Documentation, https://wheel.readthedocs.io/
+Project-URL: Issue Tracker, https://github.com/pypa/wheel/issues
+Project-URL: Source, https://github.com/pypa/wheel
+Provides-Extra: test
+
+wheel
+=====
+
+This is a command line tool for manipulating Python wheel files, as defined in
+`PEP 427`_. It contains the following functionality:
+
+* Convert ``.egg`` archives into ``.whl``
+* Unpack wheel archives
+* Repack wheel archives
+* Add or remove tags in existing wheel archives
+
+.. _PEP 427: https://www.python.org/dev/peps/pep-0427/
+
+Historical note
+---------------
+
+This project used to contain the implementation of the setuptools_ ``bdist_wheel``
+command, but as of setuptools v70.1, it no longer needs ``wheel`` installed for that to
+work. Thus, you should install this **only** if you intend to use the ``wheel`` command
+line tool!
+
+.. _setuptools: https://pypi.org/project/setuptools/
+
+Documentation
+-------------
+
+The documentation_ can be found on Read The Docs.
+
+.. _documentation: https://wheel.readthedocs.io/
+
+Code of Conduct
+---------------
+
+Everyone interacting in the wheel project's codebases, issue trackers, chat
+rooms, and mailing lists is expected to follow the `PSF Code of Conduct`_.
+
+.. _PSF Code of Conduct: https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md
+
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/RECORD b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..c1535b697f8dd60212541f637c69c9dfb4f1c8f1
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/RECORD
@@ -0,0 +1,68 @@
+../../bin/wheel,sha256=pBhV19bQIgjS-r541fG3kLU6QtcyKaKdQ2RE9YIzeiU,249
+wheel-0.45.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+wheel-0.45.1.dist-info/LICENSE.txt,sha256=MMI2GGeRCPPo6h0qZYx8pBe9_IkcmO8aifpP8MmChlQ,1107
+wheel-0.45.1.dist-info/METADATA,sha256=mKz84H7m7jsxJyzeIcTVORiTb0NPMV39KvOIYhGgmjA,2313
+wheel-0.45.1.dist-info/RECORD,,
+wheel-0.45.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+wheel-0.45.1.dist-info/WHEEL,sha256=CpUCUxeHQbRN5UGRQHYRJorO5Af-Qy_fHMctcQ8DSGI,82
+wheel-0.45.1.dist-info/entry_points.txt,sha256=rTY1BbkPHhkGMm4Q3F0pIzJBzW2kMxoG1oriffvGdA0,104
+wheel/__init__.py,sha256=mrxMnvdXACur_LWegbUfh5g5ysWZrd63UJn890wvGNk,59
+wheel/__main__.py,sha256=NkMUnuTCGcOkgY0IBLgBCVC_BGGcWORx2K8jYGS12UE,455
+wheel/__pycache__/__init__.cpython-311.pyc,,
+wheel/__pycache__/__main__.cpython-311.pyc,,
+wheel/__pycache__/_bdist_wheel.cpython-311.pyc,,
+wheel/__pycache__/_setuptools_logging.cpython-311.pyc,,
+wheel/__pycache__/bdist_wheel.cpython-311.pyc,,
+wheel/__pycache__/macosx_libfile.cpython-311.pyc,,
+wheel/__pycache__/metadata.cpython-311.pyc,,
+wheel/__pycache__/util.cpython-311.pyc,,
+wheel/__pycache__/wheelfile.cpython-311.pyc,,
+wheel/_bdist_wheel.py,sha256=UghCQjSH_pVfcZh6oRjzSw_TQhcf3anSx1OkiLSL82M,21694
+wheel/_setuptools_logging.py,sha256=-5KC-lne0ilOUWIDfOkqapUWGMFZhuKYDIavIZiB5kM,781
+wheel/bdist_wheel.py,sha256=tpf9WufiSO1RuEMg5oPhIfSG8DMziCZ_4muCKF69Cqo,1107
+wheel/cli/__init__.py,sha256=Npq6_jKi03dhIcRnmbuFhwviVJxwO0tYEnEhWMv9cJo,4402
+wheel/cli/__pycache__/__init__.cpython-311.pyc,,
+wheel/cli/__pycache__/convert.cpython-311.pyc,,
+wheel/cli/__pycache__/pack.cpython-311.pyc,,
+wheel/cli/__pycache__/tags.cpython-311.pyc,,
+wheel/cli/__pycache__/unpack.cpython-311.pyc,,
+wheel/cli/convert.py,sha256=Bi0ntEXb9nTllCxWeTRQ4j-nPs3szWSEKipG_GgnMkQ,12634
+wheel/cli/pack.py,sha256=CAFcHdBVulvsHYJlndKVO7KMI9JqBTZz5ii0PKxxCOs,3103
+wheel/cli/tags.py,sha256=lHw-LaWrkS5Jy_qWcw-6pSjeNM6yAjDnqKI3E5JTTCU,4760
+wheel/cli/unpack.py,sha256=Y_J7ynxPSoFFTT7H0fMgbBlVErwyDGcObgme5MBuz58,1021
+wheel/macosx_libfile.py,sha256=k1x7CE3LPtOVGqj6NXQ1nTGYVPaeRrhVzUG_KPq3zDs,16572
+wheel/metadata.py,sha256=JC4p7jlQZu2bUTAQ2fevkqLjg_X6gnNyRhLn6OUO1tc,6171
+wheel/util.py,sha256=aL7aibHwYUgfc8WlolL5tXdkV4DatbJxZHb1kwHFJAU,423
+wheel/vendored/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+wheel/vendored/__pycache__/__init__.cpython-311.pyc,,
+wheel/vendored/packaging/LICENSE,sha256=ytHvW9NA1z4HS6YU0m996spceUDD2MNIUuZcSQlobEg,197
+wheel/vendored/packaging/LICENSE.APACHE,sha256=DVQuDIgE45qn836wDaWnYhSdxoLXgpRRKH4RuTjpRZQ,10174
+wheel/vendored/packaging/LICENSE.BSD,sha256=tw5-m3QvHMb5SLNMFqo5_-zpQZY2S8iP8NIYDwAo-sU,1344
+wheel/vendored/packaging/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+wheel/vendored/packaging/__pycache__/__init__.cpython-311.pyc,,
+wheel/vendored/packaging/__pycache__/_elffile.cpython-311.pyc,,
+wheel/vendored/packaging/__pycache__/_manylinux.cpython-311.pyc,,
+wheel/vendored/packaging/__pycache__/_musllinux.cpython-311.pyc,,
+wheel/vendored/packaging/__pycache__/_parser.cpython-311.pyc,,
+wheel/vendored/packaging/__pycache__/_structures.cpython-311.pyc,,
+wheel/vendored/packaging/__pycache__/_tokenizer.cpython-311.pyc,,
+wheel/vendored/packaging/__pycache__/markers.cpython-311.pyc,,
+wheel/vendored/packaging/__pycache__/requirements.cpython-311.pyc,,
+wheel/vendored/packaging/__pycache__/specifiers.cpython-311.pyc,,
+wheel/vendored/packaging/__pycache__/tags.cpython-311.pyc,,
+wheel/vendored/packaging/__pycache__/utils.cpython-311.pyc,,
+wheel/vendored/packaging/__pycache__/version.cpython-311.pyc,,
+wheel/vendored/packaging/_elffile.py,sha256=hbmK8OD6Z7fY6hwinHEUcD1by7czkGiNYu7ShnFEk2k,3266
+wheel/vendored/packaging/_manylinux.py,sha256=P7sdR5_7XBY09LVYYPhHmydMJIIwPXWsh4olk74Uuj4,9588
+wheel/vendored/packaging/_musllinux.py,sha256=z1s8To2hQ0vpn_d-O2i5qxGwEK8WmGlLt3d_26V7NeY,2674
+wheel/vendored/packaging/_parser.py,sha256=4tT4emSl2qTaU7VTQE1Xa9o1jMPCsBezsYBxyNMUN-s,10347
+wheel/vendored/packaging/_structures.py,sha256=q3eVNmbWJGG_S0Dit_S3Ao8qQqz_5PYTXFAKBZe5yr4,1431
+wheel/vendored/packaging/_tokenizer.py,sha256=alCtbwXhOFAmFGZ6BQ-wCTSFoRAJ2z-ysIf7__MTJ_k,5292
+wheel/vendored/packaging/markers.py,sha256=_TSPI1BhJYO7Bp9AzTmHQxIqHEVXaTjmDh9G-w8qzPA,8232
+wheel/vendored/packaging/requirements.py,sha256=dgoBeVprPu2YE6Q8nGfwOPTjATHbRa_ZGLyXhFEln6Q,2933
+wheel/vendored/packaging/specifiers.py,sha256=IWSt0SrLSP72heWhAC8UL0eGvas7XIQHjqiViVfmPKE,39778
+wheel/vendored/packaging/tags.py,sha256=fedHXiOHkBxNZTXotXv8uXPmMFU9ae-TKBujgYHigcA,18950
+wheel/vendored/packaging/utils.py,sha256=XgdmP3yx9-wQEFjO7OvMj9RjEf5JlR5HFFR69v7SQ9E,5268
+wheel/vendored/packaging/version.py,sha256=PFJaYZDxBgyxkfYhH3SQw4qfE9ICCWrTmitvq14y3bs,16234
+wheel/vendored/vendor.txt,sha256=Z2ENjB1i5prfez8CdM1Sdr3c6Zxv2rRRolMpLmBncAE,16
+wheel/wheelfile.py,sha256=USCttNlJwafxt51YYFFKG7jnxz8dfhbyqAZL6jMTA9s,8411
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/REQUESTED b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..e3c6feefa22927866e3fd5575379ea972b432aaf
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/WHEEL
@@ -0,0 +1,4 @@
+Wheel-Version: 1.0
+Generator: flit 3.10.1
+Root-Is-Purelib: true
+Tag: py3-none-any
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/entry_points.txt b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/entry_points.txt
new file mode 100644
index 0000000000000000000000000000000000000000..06c9f69debd05e53c3b6053a905805e616c61fad
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/entry_points.txt
@@ -0,0 +1,6 @@
+[console_scripts]
+wheel=wheel.cli:main
+
+[distutils.commands]
+bdist_wheel=wheel.bdist_wheel:bdist_wheel
+
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/__init__.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ab8f72d8b2e31b1cb8456ee1c4b8e62d4aba252
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/__init__.py
@@ -0,0 +1,3 @@
+from __future__ import annotations
+
+__version__ = "0.45.1"
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/__main__.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/__main__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0be74537494dc2cf18c2e3b318ffd22b886aef6b
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/__main__.py
@@ -0,0 +1,23 @@
+"""
+Wheel command line tool (enable python -m wheel syntax)
+"""
+
+from __future__ import annotations
+
+import sys
+
+
+def main():  # needed for console script
+    if __package__ == "":
+        # To be able to run 'python wheel-0.9.whl/wheel':
+        import os.path
+
+        path = os.path.dirname(os.path.dirname(__file__))
+        sys.path[0:0] = [path]
+    import wheel.cli
+
+    sys.exit(wheel.cli.main())
+
+
+if __name__ == "__main__":
+    sys.exit(main())
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ecc30ffa46865be7e1466980bf2ef3652b70bda5
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/__pycache__/__main__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/__pycache__/__main__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..182e1304f1ff0b7854d9dac78a024a07499af3ff
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/__pycache__/__main__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/__pycache__/_bdist_wheel.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/__pycache__/_bdist_wheel.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fadf49aa71d8058ecea82f8b15dd302bf0adaba1
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/__pycache__/_bdist_wheel.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/__pycache__/_setuptools_logging.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/__pycache__/_setuptools_logging.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f45476bc91818c037269c86005c6700324b69367
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/__pycache__/_setuptools_logging.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/__pycache__/bdist_wheel.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/__pycache__/bdist_wheel.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..42a1740eedcedecd53c73c8fa0e18383d1eebeaa
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/__pycache__/bdist_wheel.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/__pycache__/macosx_libfile.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/__pycache__/macosx_libfile.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..86d79df9b75000cc50922a3f5235a828c7283a05
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/__pycache__/macosx_libfile.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/__pycache__/metadata.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/__pycache__/metadata.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5d45039873bb9cb9f81d788e416a8e1b863f9162
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/__pycache__/metadata.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/__pycache__/util.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/__pycache__/util.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e841d1779ba53bb70b4a194856e979ef7a21e5e8
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/__pycache__/util.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/__pycache__/wheelfile.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/__pycache__/wheelfile.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c26cd890e3c70406548f179549bbd2568c90f340
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/__pycache__/wheelfile.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/_bdist_wheel.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/_bdist_wheel.py
new file mode 100644
index 0000000000000000000000000000000000000000..88973ebfb88f9521e5f0613b5cedf1204d10a8f1
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/_bdist_wheel.py
@@ -0,0 +1,613 @@
+"""
+Create a wheel (.whl) distribution.
+
+A wheel is a built archive format.
+"""
+
+from __future__ import annotations
+
+import os
+import re
+import shutil
+import stat
+import struct
+import sys
+import sysconfig
+import warnings
+from email.generator import BytesGenerator, Generator
+from email.policy import EmailPolicy
+from glob import iglob
+from shutil import rmtree
+from typing import TYPE_CHECKING, Callable, Iterable, Literal, Sequence, cast
+from zipfile import ZIP_DEFLATED, ZIP_STORED
+
+import setuptools
+from setuptools import Command
+
+from . import __version__ as wheel_version
+from .metadata import pkginfo_to_metadata
+from .util import log
+from .vendored.packaging import tags
+from .vendored.packaging import version as _packaging_version
+from .wheelfile import WheelFile
+
+if TYPE_CHECKING:
+    import types
+
+# ensure Python logging is configured
+try:
+    __import__("setuptools.logging")
+except ImportError:
+    # setuptools < ??
+    from . import _setuptools_logging
+
+    _setuptools_logging.configure()
+
+
+def safe_name(name: str) -> str:
+    """Convert an arbitrary string to a standard distribution name
+    Any runs of non-alphanumeric/. characters are replaced with a single '-'.
+    """
+    return re.sub("[^A-Za-z0-9.]+", "-", name)
+
+
+def safe_version(version: str) -> str:
+    """
+    Convert an arbitrary string to a standard version string
+    """
+    try:
+        # normalize the version
+        return str(_packaging_version.Version(version))
+    except _packaging_version.InvalidVersion:
+        version = version.replace(" ", ".")
+        return re.sub("[^A-Za-z0-9.]+", "-", version)
+
+
+setuptools_major_version = int(setuptools.__version__.split(".")[0])
+
+PY_LIMITED_API_PATTERN = r"cp3\d"
+
+
+def _is_32bit_interpreter() -> bool:
+    return struct.calcsize("P") == 4
+
+
+def python_tag() -> str:
+    return f"py{sys.version_info[0]}"
+
+
+def get_platform(archive_root: str | None) -> str:
+    """Return our platform name 'win32', 'linux_x86_64'"""
+    result = sysconfig.get_platform()
+    if result.startswith("macosx") and archive_root is not None:
+        from .macosx_libfile import calculate_macosx_platform_tag
+
+        result = calculate_macosx_platform_tag(archive_root, result)
+    elif _is_32bit_interpreter():
+        if result == "linux-x86_64":
+            # pip pull request #3497
+            result = "linux-i686"
+        elif result == "linux-aarch64":
+            # packaging pull request #234
+            # TODO armv8l, packaging pull request #690 => this did not land
+            # in pip/packaging yet
+            result = "linux-armv7l"
+
+    return result.replace("-", "_")
+
+
+def get_flag(
+    var: str, fallback: bool, expected: bool = True, warn: bool = True
+) -> bool:
+    """Use a fallback value for determining SOABI flags if the needed config
+    var is unset or unavailable."""
+    val = sysconfig.get_config_var(var)
+    if val is None:
+        if warn:
+            warnings.warn(
+                f"Config variable '{var}' is unset, Python ABI tag may be incorrect",
+                RuntimeWarning,
+                stacklevel=2,
+            )
+        return fallback
+    return val == expected
+
+
+def get_abi_tag() -> str | None:
+    """Return the ABI tag based on SOABI (if available) or emulate SOABI (PyPy2)."""
+    soabi: str = sysconfig.get_config_var("SOABI")
+    impl = tags.interpreter_name()
+    if not soabi and impl in ("cp", "pp") and hasattr(sys, "maxunicode"):
+        d = ""
+        m = ""
+        u = ""
+        if get_flag("Py_DEBUG", hasattr(sys, "gettotalrefcount"), warn=(impl == "cp")):
+            d = "d"
+
+        if get_flag(
+            "WITH_PYMALLOC",
+            impl == "cp",
+            warn=(impl == "cp" and sys.version_info < (3, 8)),
+        ) and sys.version_info < (3, 8):
+            m = "m"
+
+        abi = f"{impl}{tags.interpreter_version()}{d}{m}{u}"
+    elif soabi and impl == "cp" and soabi.startswith("cpython"):
+        # non-Windows
+        abi = "cp" + soabi.split("-")[1]
+    elif soabi and impl == "cp" and soabi.startswith("cp"):
+        # Windows
+        abi = soabi.split("-")[0]
+    elif soabi and impl == "pp":
+        # we want something like pypy36-pp73
+        abi = "-".join(soabi.split("-")[:2])
+        abi = abi.replace(".", "_").replace("-", "_")
+    elif soabi and impl == "graalpy":
+        abi = "-".join(soabi.split("-")[:3])
+        abi = abi.replace(".", "_").replace("-", "_")
+    elif soabi:
+        abi = soabi.replace(".", "_").replace("-", "_")
+    else:
+        abi = None
+
+    return abi
+
+
+def safer_name(name: str) -> str:
+    return safe_name(name).replace("-", "_")
+
+
+def safer_version(version: str) -> str:
+    return safe_version(version).replace("-", "_")
+
+
+def remove_readonly(
+    func: Callable[..., object],
+    path: str,
+    excinfo: tuple[type[Exception], Exception, types.TracebackType],
+) -> None:
+    remove_readonly_exc(func, path, excinfo[1])
+
+
+def remove_readonly_exc(func: Callable[..., object], path: str, exc: Exception) -> None:
+    os.chmod(path, stat.S_IWRITE)
+    func(path)
+
+
+class bdist_wheel(Command):
+    description = "create a wheel distribution"
+
+    supported_compressions = {
+        "stored": ZIP_STORED,
+        "deflated": ZIP_DEFLATED,
+    }
+
+    user_options = [
+        ("bdist-dir=", "b", "temporary directory for creating the distribution"),
+        (
+            "plat-name=",
+            "p",
+            "platform name to embed in generated filenames "
+            f"(default: {get_platform(None)})",
+        ),
+        (
+            "keep-temp",
+            "k",
+            "keep the pseudo-installation tree around after "
+            "creating the distribution archive",
+        ),
+        ("dist-dir=", "d", "directory to put final built distributions in"),
+        ("skip-build", None, "skip rebuilding everything (for testing/debugging)"),
+        (
+            "relative",
+            None,
+            "build the archive using relative paths (default: false)",
+        ),
+        (
+            "owner=",
+            "u",
+            "Owner name used when creating a tar file [default: current user]",
+        ),
+        (
+            "group=",
+            "g",
+            "Group name used when creating a tar file [default: current group]",
+        ),
+        ("universal", None, "make a universal wheel (default: false)"),
+        (
+            "compression=",
+            None,
+            "zipfile compression (one of: {}) (default: 'deflated')".format(
+                ", ".join(supported_compressions)
+            ),
+        ),
+        (
+            "python-tag=",
+            None,
+            f"Python implementation compatibility tag (default: '{python_tag()}')",
+        ),
+        (
+            "build-number=",
+            None,
+            "Build number for this particular version. "
+            "As specified in PEP-0427, this must start with a digit. "
+            "[default: None]",
+        ),
+        (
+            "py-limited-api=",
+            None,
+            "Python tag (cp32|cp33|cpNN) for abi3 wheel tag (default: false)",
+        ),
+    ]
+
+    boolean_options = ["keep-temp", "skip-build", "relative", "universal"]
+
+    def initialize_options(self):
+        self.bdist_dir: str = None
+        self.data_dir = None
+        self.plat_name: str | None = None
+        self.plat_tag = None
+        self.format = "zip"
+        self.keep_temp = False
+        self.dist_dir: str | None = None
+        self.egginfo_dir = None
+        self.root_is_pure: bool | None = None
+        self.skip_build = None
+        self.relative = False
+        self.owner = None
+        self.group = None
+        self.universal: bool = False
+        self.compression: str | int = "deflated"
+        self.python_tag: str = python_tag()
+        self.build_number: str | None = None
+        self.py_limited_api: str | Literal[False] = False
+        self.plat_name_supplied = False
+
+    def finalize_options(self):
+        if self.bdist_dir is None:
+            bdist_base = self.get_finalized_command("bdist").bdist_base
+            self.bdist_dir = os.path.join(bdist_base, "wheel")
+
+        egg_info = self.distribution.get_command_obj("egg_info")
+        egg_info.ensure_finalized()  # needed for correct `wheel_dist_name`
+
+        self.data_dir = self.wheel_dist_name + ".data"
+        self.plat_name_supplied = self.plat_name is not None
+
+        try:
+            self.compression = self.supported_compressions[self.compression]
+        except KeyError:
+            raise ValueError(f"Unsupported compression: {self.compression}") from None
+
+        need_options = ("dist_dir", "plat_name", "skip_build")
+
+        self.set_undefined_options("bdist", *zip(need_options, need_options))
+
+        self.root_is_pure = not (
+            self.distribution.has_ext_modules() or self.distribution.has_c_libraries()
+        )
+
+        if self.py_limited_api and not re.match(
+            PY_LIMITED_API_PATTERN, self.py_limited_api
+        ):
+            raise ValueError(f"py-limited-api must match '{PY_LIMITED_API_PATTERN}'")
+
+        # Support legacy [wheel] section for setting universal
+        wheel = self.distribution.get_option_dict("wheel")
+        if "universal" in wheel:
+            # please don't define this in your global configs
+            log.warning(
+                "The [wheel] section is deprecated. Use [bdist_wheel] instead.",
+            )
+            val = wheel["universal"][1].strip()
+            if val.lower() in ("1", "true", "yes"):
+                self.universal = True
+
+        if self.build_number is not None and not self.build_number[:1].isdigit():
+            raise ValueError("Build tag (build-number) must start with a digit.")
+
+    @property
+    def wheel_dist_name(self):
+        """Return distribution full name with - replaced with _"""
+        components = (
+            safer_name(self.distribution.get_name()),
+            safer_version(self.distribution.get_version()),
+        )
+        if self.build_number:
+            components += (self.build_number,)
+        return "-".join(components)
+
+    def get_tag(self) -> tuple[str, str, str]:
+        # bdist sets self.plat_name if unset, we should only use it for purepy
+        # wheels if the user supplied it.
+        if self.plat_name_supplied:
+            plat_name = cast(str, self.plat_name)
+        elif self.root_is_pure:
+            plat_name = "any"
+        else:
+            # macosx contains system version in platform name so need special handle
+            if self.plat_name and not self.plat_name.startswith("macosx"):
+                plat_name = self.plat_name
+            else:
+                # on macosx always limit the platform name to comply with any
+                # c-extension modules in bdist_dir, since the user can specify
+                # a higher MACOSX_DEPLOYMENT_TARGET via tools like CMake
+
+                # on other platforms, and on macosx if there are no c-extension
+                # modules, use the default platform name.
+                plat_name = get_platform(self.bdist_dir)
+
+            if _is_32bit_interpreter():
+                if plat_name in ("linux-x86_64", "linux_x86_64"):
+                    plat_name = "linux_i686"
+                if plat_name in ("linux-aarch64", "linux_aarch64"):
+                    # TODO armv8l, packaging pull request #690 => this did not land
+                    # in pip/packaging yet
+                    plat_name = "linux_armv7l"
+
+        plat_name = (
+            plat_name.lower().replace("-", "_").replace(".", "_").replace(" ", "_")
+        )
+
+        if self.root_is_pure:
+            if self.universal:
+                impl = "py2.py3"
+            else:
+                impl = self.python_tag
+            tag = (impl, "none", plat_name)
+        else:
+            impl_name = tags.interpreter_name()
+            impl_ver = tags.interpreter_version()
+            impl = impl_name + impl_ver
+            # We don't work on CPython 3.1, 3.0.
+            if self.py_limited_api and (impl_name + impl_ver).startswith("cp3"):
+                impl = self.py_limited_api
+                abi_tag = "abi3"
+            else:
+                abi_tag = str(get_abi_tag()).lower()
+            tag = (impl, abi_tag, plat_name)
+            # issue gh-374: allow overriding plat_name
+            supported_tags = [
+                (t.interpreter, t.abi, plat_name) for t in tags.sys_tags()
+            ]
+            assert (
+                tag in supported_tags
+            ), f"would build wheel with unsupported tag {tag}"
+        return tag
+
+    def run(self):
+        build_scripts = self.reinitialize_command("build_scripts")
+        build_scripts.executable = "python"
+        build_scripts.force = True
+
+        build_ext = self.reinitialize_command("build_ext")
+        build_ext.inplace = False
+
+        if not self.skip_build:
+            self.run_command("build")
+
+        install = self.reinitialize_command("install", reinit_subcommands=True)
+        install.root = self.bdist_dir
+        install.compile = False
+        install.skip_build = self.skip_build
+        install.warn_dir = False
+
+        # A wheel without setuptools scripts is more cross-platform.
+        # Use the (undocumented) `no_ep` option to setuptools'
+        # install_scripts command to avoid creating entry point scripts.
+        install_scripts = self.reinitialize_command("install_scripts")
+        install_scripts.no_ep = True
+
+        # Use a custom scheme for the archive, because we have to decide
+        # at installation time which scheme to use.
+        for key in ("headers", "scripts", "data", "purelib", "platlib"):
+            setattr(install, "install_" + key, os.path.join(self.data_dir, key))
+
+        basedir_observed = ""
+
+        if os.name == "nt":
+            # win32 barfs if any of these are ''; could be '.'?
+            # (distutils.command.install:change_roots bug)
+            basedir_observed = os.path.normpath(os.path.join(self.data_dir, ".."))
+            self.install_libbase = self.install_lib = basedir_observed
+
+        setattr(
+            install,
+            "install_purelib" if self.root_is_pure else "install_platlib",
+            basedir_observed,
+        )
+
+        log.info(f"installing to {self.bdist_dir}")
+
+        self.run_command("install")
+
+        impl_tag, abi_tag, plat_tag = self.get_tag()
+        archive_basename = f"{self.wheel_dist_name}-{impl_tag}-{abi_tag}-{plat_tag}"
+        if not self.relative:
+            archive_root = self.bdist_dir
+        else:
+            archive_root = os.path.join(
+                self.bdist_dir, self._ensure_relative(install.install_base)
+            )
+
+        self.set_undefined_options("install_egg_info", ("target", "egginfo_dir"))
+        distinfo_dirname = (
+            f"{safer_name(self.distribution.get_name())}-"
+            f"{safer_version(self.distribution.get_version())}.dist-info"
+        )
+        distinfo_dir = os.path.join(self.bdist_dir, distinfo_dirname)
+        self.egg2dist(self.egginfo_dir, distinfo_dir)
+
+        self.write_wheelfile(distinfo_dir)
+
+        # Make the archive
+        if not os.path.exists(self.dist_dir):
+            os.makedirs(self.dist_dir)
+
+        wheel_path = os.path.join(self.dist_dir, archive_basename + ".whl")
+        with WheelFile(wheel_path, "w", self.compression) as wf:
+            wf.write_files(archive_root)
+
+        # Add to 'Distribution.dist_files' so that the "upload" command works
+        getattr(self.distribution, "dist_files", []).append(
+            (
+                "bdist_wheel",
+                "{}.{}".format(*sys.version_info[:2]),  # like 3.7
+                wheel_path,
+            )
+        )
+
+        if not self.keep_temp:
+            log.info(f"removing {self.bdist_dir}")
+            if not self.dry_run:
+                if sys.version_info < (3, 12):
+                    rmtree(self.bdist_dir, onerror=remove_readonly)
+                else:
+                    rmtree(self.bdist_dir, onexc=remove_readonly_exc)
+
+    def write_wheelfile(
+        self, wheelfile_base: str, generator: str = f"bdist_wheel ({wheel_version})"
+    ):
+        from email.message import Message
+
+        msg = Message()
+        msg["Wheel-Version"] = "1.0"  # of the spec
+        msg["Generator"] = generator
+        msg["Root-Is-Purelib"] = str(self.root_is_pure).lower()
+        if self.build_number is not None:
+            msg["Build"] = self.build_number
+
+        # Doesn't work for bdist_wininst
+        impl_tag, abi_tag, plat_tag = self.get_tag()
+        for impl in impl_tag.split("."):
+            for abi in abi_tag.split("."):
+                for plat in plat_tag.split("."):
+                    msg["Tag"] = "-".join((impl, abi, plat))
+
+        wheelfile_path = os.path.join(wheelfile_base, "WHEEL")
+        log.info(f"creating {wheelfile_path}")
+        with open(wheelfile_path, "wb") as f:
+            BytesGenerator(f, maxheaderlen=0).flatten(msg)
+
+    def _ensure_relative(self, path: str) -> str:
+        # copied from dir_util, deleted
+        drive, path = os.path.splitdrive(path)
+        if path[0:1] == os.sep:
+            path = drive + path[1:]
+        return path
+
+    @property
+    def license_paths(self) -> Iterable[str]:
+        if setuptools_major_version >= 57:
+            # Setuptools has resolved any patterns to actual file names
+            return self.distribution.metadata.license_files or ()
+
+        files: set[str] = set()
+        metadata = self.distribution.get_option_dict("metadata")
+        if setuptools_major_version >= 42:
+            # Setuptools recognizes the license_files option but does not do globbing
+            patterns = cast(Sequence[str], self.distribution.metadata.license_files)
+        else:
+            # Prior to those, wheel is entirely responsible for handling license files
+            if "license_files" in metadata:
+                patterns = metadata["license_files"][1].split()
+            else:
+                patterns = ()
+
+        if "license_file" in metadata:
+            warnings.warn(
+                'The "license_file" option is deprecated. Use "license_files" instead.',
+                DeprecationWarning,
+                stacklevel=2,
+            )
+            files.add(metadata["license_file"][1])
+
+        if not files and not patterns and not isinstance(patterns, list):
+            patterns = ("LICEN[CS]E*", "COPYING*", "NOTICE*", "AUTHORS*")
+
+        for pattern in patterns:
+            for path in iglob(pattern):
+                if path.endswith("~"):
+                    log.debug(
+                        f'ignoring license file "{path}" as it looks like a backup'
+                    )
+                    continue
+
+                if path not in files and os.path.isfile(path):
+                    log.info(
+                        f'adding license file "{path}" (matched pattern "{pattern}")'
+                    )
+                    files.add(path)
+
+        return files
+
+    def egg2dist(self, egginfo_path: str, distinfo_path: str):
+        """Convert an .egg-info directory into a .dist-info directory"""
+
+        def adios(p: str) -> None:
+            """Appropriately delete directory, file or link."""
+            if os.path.exists(p) and not os.path.islink(p) and os.path.isdir(p):
+                shutil.rmtree(p)
+            elif os.path.exists(p):
+                os.unlink(p)
+
+        adios(distinfo_path)
+
+        if not os.path.exists(egginfo_path):
+            # There is no egg-info. This is probably because the egg-info
+            # file/directory is not named matching the distribution name used
+            # to name the archive file. Check for this case and report
+            # accordingly.
+            import glob
+
+            pat = os.path.join(os.path.dirname(egginfo_path), "*.egg-info")
+            possible = glob.glob(pat)
+            err = f"Egg metadata expected at {egginfo_path} but not found"
+            if possible:
+                alt = os.path.basename(possible[0])
+                err += f" ({alt} found - possible misnamed archive file?)"
+
+            raise ValueError(err)
+
+        if os.path.isfile(egginfo_path):
+            # .egg-info is a single file
+            pkg_info = pkginfo_to_metadata(egginfo_path, egginfo_path)
+            os.mkdir(distinfo_path)
+        else:
+            # .egg-info is a directory
+            pkginfo_path = os.path.join(egginfo_path, "PKG-INFO")
+            pkg_info = pkginfo_to_metadata(egginfo_path, pkginfo_path)
+
+            # ignore common egg metadata that is useless to wheel
+            shutil.copytree(
+                egginfo_path,
+                distinfo_path,
+                ignore=lambda x, y: {
+                    "PKG-INFO",
+                    "requires.txt",
+                    "SOURCES.txt",
+                    "not-zip-safe",
+                },
+            )
+
+            # delete dependency_links if it is only whitespace
+            dependency_links_path = os.path.join(distinfo_path, "dependency_links.txt")
+            with open(dependency_links_path, encoding="utf-8") as dependency_links_file:
+                dependency_links = dependency_links_file.read().strip()
+            if not dependency_links:
+                adios(dependency_links_path)
+
+        pkg_info_path = os.path.join(distinfo_path, "METADATA")
+        serialization_policy = EmailPolicy(
+            utf8=True,
+            mangle_from_=False,
+            max_line_length=0,
+        )
+        with open(pkg_info_path, "w", encoding="utf-8") as out:
+            Generator(out, policy=serialization_policy).flatten(pkg_info)
+
+        for license_path in self.license_paths:
+            filename = os.path.basename(license_path)
+            shutil.copy(license_path, os.path.join(distinfo_path, filename))
+
+        adios(egginfo_path)
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/_setuptools_logging.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/_setuptools_logging.py
new file mode 100644
index 0000000000000000000000000000000000000000..a1a2482ba29ac5290c8f7d7688452ec3faf59332
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/_setuptools_logging.py
@@ -0,0 +1,26 @@
+# copied from setuptools.logging, omitting monkeypatching
+from __future__ import annotations
+
+import logging
+import sys
+
+
+def _not_warning(record: logging.LogRecord) -> bool:
+    return record.levelno < logging.WARNING
+
+
+def configure() -> None:
+    """
+    Configure logging to emit warning and above to stderr
+    and everything else to stdout. This behavior is provided
+    for compatibility with distutils.log but may change in
+    the future.
+    """
+    err_handler = logging.StreamHandler()
+    err_handler.setLevel(logging.WARNING)
+    out_handler = logging.StreamHandler(sys.stdout)
+    out_handler.addFilter(_not_warning)
+    handlers = err_handler, out_handler
+    logging.basicConfig(
+        format="{message}", style="{", handlers=handlers, level=logging.DEBUG
+    )
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/bdist_wheel.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/bdist_wheel.py
new file mode 100644
index 0000000000000000000000000000000000000000..dd7b8629e5087fe35a2ea7ab6d3cbbb4cacf0031
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/bdist_wheel.py
@@ -0,0 +1,26 @@
+from typing import TYPE_CHECKING
+from warnings import warn
+
+warn(
+    "The 'wheel' package is no longer the canonical location of the 'bdist_wheel' "
+    "command, and will be removed in a future release. Please update to setuptools "
+    "v70.1 or later which contains an integrated version of this command.",
+    DeprecationWarning,
+    stacklevel=1,
+)
+
+if TYPE_CHECKING:
+    from ._bdist_wheel import bdist_wheel as bdist_wheel
+else:
+    try:
+        # Better integration/compatibility with setuptools:
+        # in the case new fixes or PEPs are implemented in setuptools
+        # there is no need to backport them to the deprecated code base.
+        # This is useful in the case of old packages in the ecosystem
+        # that are still used but have low maintenance.
+        from setuptools.command.bdist_wheel import bdist_wheel
+    except ImportError:
+        # Only used in the case of old setuptools versions.
+        # If the user wants to get the latest fixes/PEPs,
+        # they are encouraged to address the deprecation warning.
+        from ._bdist_wheel import bdist_wheel as bdist_wheel
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/cli/__init__.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/cli/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ba1217f5bdb6106c37ecc2be74d53ef2237b717
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/cli/__init__.py
@@ -0,0 +1,155 @@
+"""
+Wheel command-line utility.
+"""
+
+from __future__ import annotations
+
+import argparse
+import os
+import sys
+from argparse import ArgumentTypeError
+
+
+class WheelError(Exception):
+    pass
+
+
+def unpack_f(args: argparse.Namespace) -> None:
+    from .unpack import unpack
+
+    unpack(args.wheelfile, args.dest)
+
+
+def pack_f(args: argparse.Namespace) -> None:
+    from .pack import pack
+
+    pack(args.directory, args.dest_dir, args.build_number)
+
+
+def convert_f(args: argparse.Namespace) -> None:
+    from .convert import convert
+
+    convert(args.files, args.dest_dir, args.verbose)
+
+
+def tags_f(args: argparse.Namespace) -> None:
+    from .tags import tags
+
+    names = (
+        tags(
+            wheel,
+            args.python_tag,
+            args.abi_tag,
+            args.platform_tag,
+            args.build,
+            args.remove,
+        )
+        for wheel in args.wheel
+    )
+
+    for name in names:
+        print(name)
+
+
+def version_f(args: argparse.Namespace) -> None:
+    from .. import __version__
+
+    print(f"wheel {__version__}")
+
+
+def parse_build_tag(build_tag: str) -> str:
+    if build_tag and not build_tag[0].isdigit():
+        raise ArgumentTypeError("build tag must begin with a digit")
+    elif "-" in build_tag:
+        raise ArgumentTypeError("invalid character ('-') in build tag")
+
+    return build_tag
+
+
+TAGS_HELP = """\
+Make a new wheel with given tags. Any tags unspecified will remain the same.
+Starting the tags with a "+" will append to the existing tags. Starting with a
+"-" will remove a tag (use --option=-TAG syntax). Multiple tags can be
+separated by ".". The original file will remain unless --remove is given.  The
+output filename(s) will be displayed on stdout for further processing.
+"""
+
+
+def parser():
+    p = argparse.ArgumentParser()
+    s = p.add_subparsers(help="commands")
+
+    unpack_parser = s.add_parser("unpack", help="Unpack wheel")
+    unpack_parser.add_argument(
+        "--dest", "-d", help="Destination directory", default="."
+    )
+    unpack_parser.add_argument("wheelfile", help="Wheel file")
+    unpack_parser.set_defaults(func=unpack_f)
+
+    repack_parser = s.add_parser("pack", help="Repack wheel")
+    repack_parser.add_argument("directory", help="Root directory of the unpacked wheel")
+    repack_parser.add_argument(
+        "--dest-dir",
+        "-d",
+        default=os.path.curdir,
+        help="Directory to store the wheel (default %(default)s)",
+    )
+    repack_parser.add_argument(
+        "--build-number", help="Build tag to use in the wheel name"
+    )
+    repack_parser.set_defaults(func=pack_f)
+
+    convert_parser = s.add_parser("convert", help="Convert egg or wininst to wheel")
+    convert_parser.add_argument("files", nargs="*", help="Files to convert")
+    convert_parser.add_argument(
+        "--dest-dir",
+        "-d",
+        default=os.path.curdir,
+        help="Directory to store wheels (default %(default)s)",
+    )
+    convert_parser.add_argument("--verbose", "-v", action="store_true")
+    convert_parser.set_defaults(func=convert_f)
+
+    tags_parser = s.add_parser(
+        "tags", help="Add or replace the tags on a wheel", description=TAGS_HELP
+    )
+    tags_parser.add_argument("wheel", nargs="*", help="Existing wheel(s) to retag")
+    tags_parser.add_argument(
+        "--remove",
+        action="store_true",
+        help="Remove the original files, keeping only the renamed ones",
+    )
+    tags_parser.add_argument(
+        "--python-tag", metavar="TAG", help="Specify an interpreter tag(s)"
+    )
+    tags_parser.add_argument("--abi-tag", metavar="TAG", help="Specify an ABI tag(s)")
+    tags_parser.add_argument(
+        "--platform-tag", metavar="TAG", help="Specify a platform tag(s)"
+    )
+    tags_parser.add_argument(
+        "--build", type=parse_build_tag, metavar="BUILD", help="Specify a build tag"
+    )
+    tags_parser.set_defaults(func=tags_f)
+
+    version_parser = s.add_parser("version", help="Print version and exit")
+    version_parser.set_defaults(func=version_f)
+
+    help_parser = s.add_parser("help", help="Show this help")
+    help_parser.set_defaults(func=lambda args: p.print_help())
+
+    return p
+
+
+def main():
+    p = parser()
+    args = p.parse_args()
+    if not hasattr(args, "func"):
+        p.print_help()
+    else:
+        try:
+            args.func(args)
+            return 0
+        except WheelError as e:
+            print(e, file=sys.stderr)
+
+    return 1
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/cli/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/cli/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0e4e3012cb68002e90e8eaaf8ca4f85cda15af28
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/cli/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/cli/__pycache__/convert.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/cli/__pycache__/convert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cb8181e1273b8f7a27eb1ff9774efc1a8ded0b5e
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/cli/__pycache__/convert.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/cli/__pycache__/pack.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/cli/__pycache__/pack.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2d90320f5cb767018ac4f6d22347bad262d91ee1
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/cli/__pycache__/pack.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/cli/__pycache__/tags.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/cli/__pycache__/tags.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0948bc6a5542baad4a250ae74287e3c416923d06
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/cli/__pycache__/tags.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/cli/__pycache__/unpack.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/cli/__pycache__/unpack.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..67e6719dbaa02e2f060d4216d48d44470c0a580f
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/cli/__pycache__/unpack.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/cli/convert.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/cli/convert.py
new file mode 100644
index 0000000000000000000000000000000000000000..61d4775c58596ec12a0c4d4a548de430dee579bf
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/cli/convert.py
@@ -0,0 +1,332 @@
+from __future__ import annotations
+
+import os.path
+import re
+from abc import ABCMeta, abstractmethod
+from collections import defaultdict
+from collections.abc import Iterator
+from email.message import Message
+from email.parser import Parser
+from email.policy import EmailPolicy
+from glob import iglob
+from pathlib import Path
+from textwrap import dedent
+from zipfile import ZipFile
+
+from .. import __version__
+from ..metadata import generate_requirements
+from ..vendored.packaging.tags import parse_tag
+from ..wheelfile import WheelFile
+
+egg_filename_re = re.compile(
+    r"""
+    (?P.+?)-(?P.+?)
+    (-(?Ppy\d\.\d+)
+     (-(?P.+?))?
+    )?.egg$""",
+    re.VERBOSE,
+)
+egg_info_re = re.compile(
+    r"""
+    ^(?P.+?)-(?P.+?)
+    (-(?Ppy\d\.\d+)
+    )?.egg-info/""",
+    re.VERBOSE,
+)
+wininst_re = re.compile(
+    r"\.(?Pwin32|win-amd64)(?:-(?Ppy\d\.\d))?\.exe$"
+)
+pyd_re = re.compile(r"\.(?P[a-z0-9]+)-(?Pwin32|win_amd64)\.pyd$")
+serialization_policy = EmailPolicy(
+    utf8=True,
+    mangle_from_=False,
+    max_line_length=0,
+)
+GENERATOR = f"wheel {__version__}"
+
+
+def convert_requires(requires: str, metadata: Message) -> None:
+    extra: str | None = None
+    requirements: dict[str | None, list[str]] = defaultdict(list)
+    for line in requires.splitlines():
+        line = line.strip()
+        if not line:
+            continue
+
+        if line.startswith("[") and line.endswith("]"):
+            extra = line[1:-1]
+            continue
+
+        requirements[extra].append(line)
+
+    for key, value in generate_requirements(requirements):
+        metadata.add_header(key, value)
+
+
+def convert_pkg_info(pkginfo: str, metadata: Message):
+    parsed_message = Parser().parsestr(pkginfo)
+    for key, value in parsed_message.items():
+        key_lower = key.lower()
+        if value == "UNKNOWN":
+            continue
+
+        if key_lower == "description":
+            description_lines = value.splitlines()
+            value = "\n".join(
+                (
+                    description_lines[0].lstrip(),
+                    dedent("\n".join(description_lines[1:])),
+                    "\n",
+                )
+            )
+            metadata.set_payload(value)
+        elif key_lower == "home-page":
+            metadata.add_header("Project-URL", f"Homepage, {value}")
+        elif key_lower == "download-url":
+            metadata.add_header("Project-URL", f"Download, {value}")
+        else:
+            metadata.add_header(key, value)
+
+    metadata.replace_header("Metadata-Version", "2.4")
+
+
+def normalize(name: str) -> str:
+    return re.sub(r"[-_.]+", "-", name).lower().replace("-", "_")
+
+
+class ConvertSource(metaclass=ABCMeta):
+    name: str
+    version: str
+    pyver: str = "py2.py3"
+    abi: str = "none"
+    platform: str = "any"
+    metadata: Message
+
+    @property
+    def dist_info_dir(self) -> str:
+        return f"{self.name}-{self.version}.dist-info"
+
+    @abstractmethod
+    def generate_contents(self) -> Iterator[tuple[str, bytes]]:
+        pass
+
+
+class EggFileSource(ConvertSource):
+    def __init__(self, path: Path):
+        if not (match := egg_filename_re.match(path.name)):
+            raise ValueError(f"Invalid egg file name: {path.name}")
+
+        # Binary wheels are assumed to be for CPython
+        self.path = path
+        self.name = normalize(match.group("name"))
+        self.version = match.group("ver")
+        if pyver := match.group("pyver"):
+            self.pyver = pyver.replace(".", "")
+            if arch := match.group("arch"):
+                self.abi = self.pyver.replace("py", "cp")
+                self.platform = normalize(arch)
+
+        self.metadata = Message()
+
+    def generate_contents(self) -> Iterator[tuple[str, bytes]]:
+        with ZipFile(self.path, "r") as zip_file:
+            for filename in sorted(zip_file.namelist()):
+                # Skip pure directory entries
+                if filename.endswith("/"):
+                    continue
+
+                # Handle files in the egg-info directory specially, selectively moving
+                # them to the dist-info directory while converting as needed
+                if filename.startswith("EGG-INFO/"):
+                    if filename == "EGG-INFO/requires.txt":
+                        requires = zip_file.read(filename).decode("utf-8")
+                        convert_requires(requires, self.metadata)
+                    elif filename == "EGG-INFO/PKG-INFO":
+                        pkginfo = zip_file.read(filename).decode("utf-8")
+                        convert_pkg_info(pkginfo, self.metadata)
+                    elif filename == "EGG-INFO/entry_points.txt":
+                        yield (
+                            f"{self.dist_info_dir}/entry_points.txt",
+                            zip_file.read(filename),
+                        )
+
+                    continue
+
+                # For any other file, just pass it through
+                yield filename, zip_file.read(filename)
+
+
+class EggDirectorySource(EggFileSource):
+    def generate_contents(self) -> Iterator[tuple[str, bytes]]:
+        for dirpath, _, filenames in os.walk(self.path):
+            for filename in sorted(filenames):
+                path = Path(dirpath, filename)
+                if path.parent.name == "EGG-INFO":
+                    if path.name == "requires.txt":
+                        requires = path.read_text("utf-8")
+                        convert_requires(requires, self.metadata)
+                    elif path.name == "PKG-INFO":
+                        pkginfo = path.read_text("utf-8")
+                        convert_pkg_info(pkginfo, self.metadata)
+                        if name := self.metadata.get("Name"):
+                            self.name = normalize(name)
+
+                        if version := self.metadata.get("Version"):
+                            self.version = version
+                    elif path.name == "entry_points.txt":
+                        yield (
+                            f"{self.dist_info_dir}/entry_points.txt",
+                            path.read_bytes(),
+                        )
+
+                    continue
+
+                # For any other file, just pass it through
+                yield str(path.relative_to(self.path)), path.read_bytes()
+
+
+class WininstFileSource(ConvertSource):
+    """
+    Handles distributions created with ``bdist_wininst``.
+
+    The egginfo filename has the format::
+
+        name-ver(-pyver)(-arch).egg-info
+
+    The installer filename has the format::
+
+        name-ver.arch(-pyver).exe
+
+    Some things to note:
+
+    1. The installer filename is not definitive. An installer can be renamed
+       and work perfectly well as an installer. So more reliable data should
+       be used whenever possible.
+    2. The egg-info data should be preferred for the name and version, because
+       these come straight from the distutils metadata, and are mandatory.
+    3. The pyver from the egg-info data should be ignored, as it is
+       constructed from the version of Python used to build the installer,
+       which is irrelevant - the installer filename is correct here (even to
+       the point that when it's not there, any version is implied).
+    4. The architecture must be taken from the installer filename, as it is
+       not included in the egg-info data.
+    5. Architecture-neutral installers still have an architecture because the
+       installer format itself (being executable) is architecture-specific. We
+       should therefore ignore the architecture if the content is pure-python.
+    """
+
+    def __init__(self, path: Path):
+        self.path = path
+        self.metadata = Message()
+
+        # Determine the initial architecture and Python version from the file name
+        # (if possible)
+        if match := wininst_re.search(path.name):
+            self.platform = normalize(match.group("platform"))
+            if pyver := match.group("pyver"):
+                self.pyver = pyver.replace(".", "")
+
+        # Look for an .egg-info directory and any .pyd files for more precise info
+        egg_info_found = pyd_found = False
+        with ZipFile(self.path) as zip_file:
+            for filename in zip_file.namelist():
+                prefix, filename = filename.split("/", 1)
+                if not egg_info_found and (match := egg_info_re.match(filename)):
+                    egg_info_found = True
+                    self.name = normalize(match.group("name"))
+                    self.version = match.group("ver")
+                    if pyver := match.group("pyver"):
+                        self.pyver = pyver.replace(".", "")
+                elif not pyd_found and (match := pyd_re.search(filename)):
+                    pyd_found = True
+                    self.abi = match.group("abi")
+                    self.platform = match.group("platform")
+
+                if egg_info_found and pyd_found:
+                    break
+
+    def generate_contents(self) -> Iterator[tuple[str, bytes]]:
+        dist_info_dir = f"{self.name}-{self.version}.dist-info"
+        data_dir = f"{self.name}-{self.version}.data"
+        with ZipFile(self.path, "r") as zip_file:
+            for filename in sorted(zip_file.namelist()):
+                # Skip pure directory entries
+                if filename.endswith("/"):
+                    continue
+
+                # Handle files in the egg-info directory specially, selectively moving
+                # them to the dist-info directory while converting as needed
+                prefix, target_filename = filename.split("/", 1)
+                if egg_info_re.search(target_filename):
+                    basename = target_filename.rsplit("/", 1)[-1]
+                    if basename == "requires.txt":
+                        requires = zip_file.read(filename).decode("utf-8")
+                        convert_requires(requires, self.metadata)
+                    elif basename == "PKG-INFO":
+                        pkginfo = zip_file.read(filename).decode("utf-8")
+                        convert_pkg_info(pkginfo, self.metadata)
+                    elif basename == "entry_points.txt":
+                        yield (
+                            f"{dist_info_dir}/entry_points.txt",
+                            zip_file.read(filename),
+                        )
+
+                    continue
+                elif prefix == "SCRIPTS":
+                    target_filename = f"{data_dir}/scripts/{target_filename}"
+
+                # For any other file, just pass it through
+                yield target_filename, zip_file.read(filename)
+
+
+def convert(files: list[str], dest_dir: str, verbose: bool) -> None:
+    for pat in files:
+        for archive in iglob(pat):
+            path = Path(archive)
+            if path.suffix == ".egg":
+                if path.is_dir():
+                    source: ConvertSource = EggDirectorySource(path)
+                else:
+                    source = EggFileSource(path)
+            else:
+                source = WininstFileSource(path)
+
+            if verbose:
+                print(f"{archive}...", flush=True, end="")
+
+            dest_path = Path(dest_dir) / (
+                f"{source.name}-{source.version}-{source.pyver}-{source.abi}"
+                f"-{source.platform}.whl"
+            )
+            with WheelFile(dest_path, "w") as wheelfile:
+                for name_or_zinfo, contents in source.generate_contents():
+                    wheelfile.writestr(name_or_zinfo, contents)
+
+                # Write the METADATA file
+                wheelfile.writestr(
+                    f"{source.dist_info_dir}/METADATA",
+                    source.metadata.as_string(policy=serialization_policy).encode(
+                        "utf-8"
+                    ),
+                )
+
+                # Write the WHEEL file
+                wheel_message = Message()
+                wheel_message.add_header("Wheel-Version", "1.0")
+                wheel_message.add_header("Generator", GENERATOR)
+                wheel_message.add_header(
+                    "Root-Is-Purelib", str(source.platform == "any").lower()
+                )
+                tags = parse_tag(f"{source.pyver}-{source.abi}-{source.platform}")
+                for tag in sorted(tags, key=lambda tag: tag.interpreter):
+                    wheel_message.add_header("Tag", str(tag))
+
+                wheelfile.writestr(
+                    f"{source.dist_info_dir}/WHEEL",
+                    wheel_message.as_string(policy=serialization_policy).encode(
+                        "utf-8"
+                    ),
+                )
+
+            if verbose:
+                print("OK")
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/cli/pack.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/cli/pack.py
new file mode 100644
index 0000000000000000000000000000000000000000..64469c0c730c24449e77c23f46d0e3f68d647d67
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/cli/pack.py
@@ -0,0 +1,85 @@
+from __future__ import annotations
+
+import email.policy
+import os.path
+import re
+from email.generator import BytesGenerator
+from email.parser import BytesParser
+
+from wheel.cli import WheelError
+from wheel.wheelfile import WheelFile
+
+DIST_INFO_RE = re.compile(r"^(?P(?P.+?)-(?P\d.*?))\.dist-info$")
+
+
+def pack(directory: str, dest_dir: str, build_number: str | None) -> None:
+    """Repack a previously unpacked wheel directory into a new wheel file.
+
+    The .dist-info/WHEEL file must contain one or more tags so that the target
+    wheel file name can be determined.
+
+    :param directory: The unpacked wheel directory
+    :param dest_dir: Destination directory (defaults to the current directory)
+    """
+    # Find the .dist-info directory
+    dist_info_dirs = [
+        fn
+        for fn in os.listdir(directory)
+        if os.path.isdir(os.path.join(directory, fn)) and DIST_INFO_RE.match(fn)
+    ]
+    if len(dist_info_dirs) > 1:
+        raise WheelError(f"Multiple .dist-info directories found in {directory}")
+    elif not dist_info_dirs:
+        raise WheelError(f"No .dist-info directories found in {directory}")
+
+    # Determine the target wheel filename
+    dist_info_dir = dist_info_dirs[0]
+    name_version = DIST_INFO_RE.match(dist_info_dir).group("namever")
+
+    # Read the tags and the existing build number from .dist-info/WHEEL
+    wheel_file_path = os.path.join(directory, dist_info_dir, "WHEEL")
+    with open(wheel_file_path, "rb") as f:
+        info = BytesParser(policy=email.policy.compat32).parse(f)
+        tags: list[str] = info.get_all("Tag", [])
+        existing_build_number = info.get("Build")
+
+        if not tags:
+            raise WheelError(
+                f"No tags present in {dist_info_dir}/WHEEL; cannot determine target "
+                f"wheel filename"
+            )
+
+    # Set the wheel file name and add/replace/remove the Build tag in .dist-info/WHEEL
+    build_number = build_number if build_number is not None else existing_build_number
+    if build_number is not None:
+        del info["Build"]
+        if build_number:
+            info["Build"] = build_number
+            name_version += "-" + build_number
+
+        if build_number != existing_build_number:
+            with open(wheel_file_path, "wb") as f:
+                BytesGenerator(f, maxheaderlen=0).flatten(info)
+
+    # Reassemble the tags for the wheel file
+    tagline = compute_tagline(tags)
+
+    # Repack the wheel
+    wheel_path = os.path.join(dest_dir, f"{name_version}-{tagline}.whl")
+    with WheelFile(wheel_path, "w") as wf:
+        print(f"Repacking wheel as {wheel_path}...", end="", flush=True)
+        wf.write_files(directory)
+
+    print("OK")
+
+
+def compute_tagline(tags: list[str]) -> str:
+    """Compute a tagline from a list of tags.
+
+    :param tags: A list of tags
+    :return: A tagline
+    """
+    impls = sorted({tag.split("-")[0] for tag in tags})
+    abivers = sorted({tag.split("-")[1] for tag in tags})
+    platforms = sorted({tag.split("-")[2] for tag in tags})
+    return "-".join([".".join(impls), ".".join(abivers), ".".join(platforms)])
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/cli/tags.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/cli/tags.py
new file mode 100644
index 0000000000000000000000000000000000000000..88da72e9ec4a31e2427bdb2bcf2b3e0ce3c0beb0
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/cli/tags.py
@@ -0,0 +1,139 @@
+from __future__ import annotations
+
+import email.policy
+import itertools
+import os
+from collections.abc import Iterable
+from email.parser import BytesParser
+
+from ..wheelfile import WheelFile
+
+
+def _compute_tags(original_tags: Iterable[str], new_tags: str | None) -> set[str]:
+    """Add or replace tags. Supports dot-separated tags"""
+    if new_tags is None:
+        return set(original_tags)
+
+    if new_tags.startswith("+"):
+        return {*original_tags, *new_tags[1:].split(".")}
+
+    if new_tags.startswith("-"):
+        return set(original_tags) - set(new_tags[1:].split("."))
+
+    return set(new_tags.split("."))
+
+
+def tags(
+    wheel: str,
+    python_tags: str | None = None,
+    abi_tags: str | None = None,
+    platform_tags: str | None = None,
+    build_tag: str | None = None,
+    remove: bool = False,
+) -> str:
+    """Change the tags on a wheel file.
+
+    The tags are left unchanged if they are not specified. To specify "none",
+    use ["none"]. To append to the previous tags, a tag should start with a
+    "+".  If a tag starts with "-", it will be removed from existing tags.
+    Processing is done left to right.
+
+    :param wheel: The paths to the wheels
+    :param python_tags: The Python tags to set
+    :param abi_tags: The ABI tags to set
+    :param platform_tags: The platform tags to set
+    :param build_tag: The build tag to set
+    :param remove: Remove the original wheel
+    """
+    with WheelFile(wheel, "r") as f:
+        assert f.filename, f"{f.filename} must be available"
+
+        wheel_info = f.read(f.dist_info_path + "/WHEEL")
+        info = BytesParser(policy=email.policy.compat32).parsebytes(wheel_info)
+
+        original_wheel_name = os.path.basename(f.filename)
+        namever = f.parsed_filename.group("namever")
+        build = f.parsed_filename.group("build")
+        original_python_tags = f.parsed_filename.group("pyver").split(".")
+        original_abi_tags = f.parsed_filename.group("abi").split(".")
+        original_plat_tags = f.parsed_filename.group("plat").split(".")
+
+    tags: list[str] = info.get_all("Tag", [])
+    existing_build_tag = info.get("Build")
+
+    impls = {tag.split("-")[0] for tag in tags}
+    abivers = {tag.split("-")[1] for tag in tags}
+    platforms = {tag.split("-")[2] for tag in tags}
+
+    if impls != set(original_python_tags):
+        msg = f"Wheel internal tags {impls!r} != filename tags {original_python_tags!r}"
+        raise AssertionError(msg)
+
+    if abivers != set(original_abi_tags):
+        msg = f"Wheel internal tags {abivers!r} != filename tags {original_abi_tags!r}"
+        raise AssertionError(msg)
+
+    if platforms != set(original_plat_tags):
+        msg = (
+            f"Wheel internal tags {platforms!r} != filename tags {original_plat_tags!r}"
+        )
+        raise AssertionError(msg)
+
+    if existing_build_tag != build:
+        msg = (
+            f"Incorrect filename '{build}' "
+            f"& *.dist-info/WHEEL '{existing_build_tag}' build numbers"
+        )
+        raise AssertionError(msg)
+
+    # Start changing as needed
+    if build_tag is not None:
+        build = build_tag
+
+    final_python_tags = sorted(_compute_tags(original_python_tags, python_tags))
+    final_abi_tags = sorted(_compute_tags(original_abi_tags, abi_tags))
+    final_plat_tags = sorted(_compute_tags(original_plat_tags, platform_tags))
+
+    final_tags = [
+        namever,
+        ".".join(final_python_tags),
+        ".".join(final_abi_tags),
+        ".".join(final_plat_tags),
+    ]
+    if build:
+        final_tags.insert(1, build)
+
+    final_wheel_name = "-".join(final_tags) + ".whl"
+
+    if original_wheel_name != final_wheel_name:
+        del info["Tag"], info["Build"]
+        for a, b, c in itertools.product(
+            final_python_tags, final_abi_tags, final_plat_tags
+        ):
+            info["Tag"] = f"{a}-{b}-{c}"
+        if build:
+            info["Build"] = build
+
+        original_wheel_path = os.path.join(
+            os.path.dirname(f.filename), original_wheel_name
+        )
+        final_wheel_path = os.path.join(os.path.dirname(f.filename), final_wheel_name)
+
+        with WheelFile(original_wheel_path, "r") as fin, WheelFile(
+            final_wheel_path, "w"
+        ) as fout:
+            fout.comment = fin.comment  # preserve the comment
+            for item in fin.infolist():
+                if item.is_dir():
+                    continue
+                if item.filename == f.dist_info_path + "/RECORD":
+                    continue
+                if item.filename == f.dist_info_path + "/WHEEL":
+                    fout.writestr(item, info.as_bytes())
+                else:
+                    fout.writestr(item, fin.read(item))
+
+        if remove:
+            os.remove(original_wheel_path)
+
+    return final_wheel_name
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/cli/unpack.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/cli/unpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..d48840e6ec0512225233bf02d1d7ce203415b04c
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/cli/unpack.py
@@ -0,0 +1,30 @@
+from __future__ import annotations
+
+from pathlib import Path
+
+from ..wheelfile import WheelFile
+
+
+def unpack(path: str, dest: str = ".") -> None:
+    """Unpack a wheel.
+
+    Wheel content will be unpacked to {dest}/{name}-{ver}, where {name}
+    is the package name and {ver} its version.
+
+    :param path: The path to the wheel.
+    :param dest: Destination directory (default to current directory).
+    """
+    with WheelFile(path) as wf:
+        namever = wf.parsed_filename.group("namever")
+        destination = Path(dest) / namever
+        print(f"Unpacking to: {destination}...", end="", flush=True)
+        for zinfo in wf.filelist:
+            wf.extract(zinfo, destination)
+
+            # Set permissions to the same values as they were set in the archive
+            # We have to do this manually due to
+            # https://github.com/python/cpython/issues/59999
+            permissions = zinfo.external_attr >> 16 & 0o777
+            destination.joinpath(zinfo.filename).chmod(permissions)
+
+    print("OK")
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/macosx_libfile.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/macosx_libfile.py
new file mode 100644
index 0000000000000000000000000000000000000000..abdfc9eda1d4c1f33270c155e1610fe73bd54263
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/macosx_libfile.py
@@ -0,0 +1,482 @@
+"""
+This module contains function to analyse dynamic library
+headers to extract system information
+
+Currently only for MacOSX
+
+Library file on macosx system starts with Mach-O or Fat field.
+This can be distinguish by first 32 bites and it is called magic number.
+Proper value of magic number is with suffix _MAGIC. Suffix _CIGAM means
+reversed bytes order.
+Both fields can occur in two types: 32 and 64 bytes.
+
+FAT field inform that this library contains few version of library
+(typically for different types version). It contains
+information where Mach-O headers starts.
+
+Each section started with Mach-O header contains one library
+(So if file starts with this field it contains only one version).
+
+After filed Mach-O there are section fields.
+Each of them starts with two fields:
+cmd - magic number for this command
+cmdsize - total size occupied by this section information.
+
+In this case only sections LC_VERSION_MIN_MACOSX (for macosx 10.13 and earlier)
+and LC_BUILD_VERSION (for macosx 10.14 and newer) are interesting,
+because them contains information about minimal system version.
+
+Important remarks:
+- For fat files this implementation looks for maximum number version.
+  It not check if it is 32 or 64 and do not compare it with currently built package.
+  So it is possible to false report higher version that needed.
+- All structures signatures are taken form macosx header files.
+- I think that binary format will be more stable than `otool` output.
+  and if apple introduce some changes both implementation will need to be updated.
+- The system compile will set the deployment target no lower than
+  11.0 for arm64 builds. For "Universal 2" builds use the x86_64 deployment
+  target when the arm64 target is 11.0.
+"""
+
+from __future__ import annotations
+
+import ctypes
+import os
+import sys
+from io import BufferedIOBase
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Union
+
+    StrPath = Union[str, os.PathLike[str]]
+
+"""here the needed const and struct from mach-o header files"""
+
+FAT_MAGIC = 0xCAFEBABE
+FAT_CIGAM = 0xBEBAFECA
+FAT_MAGIC_64 = 0xCAFEBABF
+FAT_CIGAM_64 = 0xBFBAFECA
+MH_MAGIC = 0xFEEDFACE
+MH_CIGAM = 0xCEFAEDFE
+MH_MAGIC_64 = 0xFEEDFACF
+MH_CIGAM_64 = 0xCFFAEDFE
+
+LC_VERSION_MIN_MACOSX = 0x24
+LC_BUILD_VERSION = 0x32
+
+CPU_TYPE_ARM64 = 0x0100000C
+
+mach_header_fields = [
+    ("magic", ctypes.c_uint32),
+    ("cputype", ctypes.c_int),
+    ("cpusubtype", ctypes.c_int),
+    ("filetype", ctypes.c_uint32),
+    ("ncmds", ctypes.c_uint32),
+    ("sizeofcmds", ctypes.c_uint32),
+    ("flags", ctypes.c_uint32),
+]
+"""
+struct mach_header {
+    uint32_t	magic;		/* mach magic number identifier */
+    cpu_type_t	cputype;	/* cpu specifier */
+    cpu_subtype_t	cpusubtype;	/* machine specifier */
+    uint32_t	filetype;	/* type of file */
+    uint32_t	ncmds;		/* number of load commands */
+    uint32_t	sizeofcmds;	/* the size of all the load commands */
+    uint32_t	flags;		/* flags */
+};
+typedef integer_t cpu_type_t;
+typedef integer_t cpu_subtype_t;
+"""
+
+mach_header_fields_64 = mach_header_fields + [("reserved", ctypes.c_uint32)]
+"""
+struct mach_header_64 {
+    uint32_t	magic;		/* mach magic number identifier */
+    cpu_type_t	cputype;	/* cpu specifier */
+    cpu_subtype_t	cpusubtype;	/* machine specifier */
+    uint32_t	filetype;	/* type of file */
+    uint32_t	ncmds;		/* number of load commands */
+    uint32_t	sizeofcmds;	/* the size of all the load commands */
+    uint32_t	flags;		/* flags */
+    uint32_t	reserved;	/* reserved */
+};
+"""
+
+fat_header_fields = [("magic", ctypes.c_uint32), ("nfat_arch", ctypes.c_uint32)]
+"""
+struct fat_header {
+    uint32_t	magic;		/* FAT_MAGIC or FAT_MAGIC_64 */
+    uint32_t	nfat_arch;	/* number of structs that follow */
+};
+"""
+
+fat_arch_fields = [
+    ("cputype", ctypes.c_int),
+    ("cpusubtype", ctypes.c_int),
+    ("offset", ctypes.c_uint32),
+    ("size", ctypes.c_uint32),
+    ("align", ctypes.c_uint32),
+]
+"""
+struct fat_arch {
+    cpu_type_t	cputype;	/* cpu specifier (int) */
+    cpu_subtype_t	cpusubtype;	/* machine specifier (int) */
+    uint32_t	offset;		/* file offset to this object file */
+    uint32_t	size;		/* size of this object file */
+    uint32_t	align;		/* alignment as a power of 2 */
+};
+"""
+
+fat_arch_64_fields = [
+    ("cputype", ctypes.c_int),
+    ("cpusubtype", ctypes.c_int),
+    ("offset", ctypes.c_uint64),
+    ("size", ctypes.c_uint64),
+    ("align", ctypes.c_uint32),
+    ("reserved", ctypes.c_uint32),
+]
+"""
+struct fat_arch_64 {
+    cpu_type_t	cputype;	/* cpu specifier (int) */
+    cpu_subtype_t	cpusubtype;	/* machine specifier (int) */
+    uint64_t	offset;		/* file offset to this object file */
+    uint64_t	size;		/* size of this object file */
+    uint32_t	align;		/* alignment as a power of 2 */
+    uint32_t	reserved;	/* reserved */
+};
+"""
+
+segment_base_fields = [("cmd", ctypes.c_uint32), ("cmdsize", ctypes.c_uint32)]
+"""base for reading segment info"""
+
+segment_command_fields = [
+    ("cmd", ctypes.c_uint32),
+    ("cmdsize", ctypes.c_uint32),
+    ("segname", ctypes.c_char * 16),
+    ("vmaddr", ctypes.c_uint32),
+    ("vmsize", ctypes.c_uint32),
+    ("fileoff", ctypes.c_uint32),
+    ("filesize", ctypes.c_uint32),
+    ("maxprot", ctypes.c_int),
+    ("initprot", ctypes.c_int),
+    ("nsects", ctypes.c_uint32),
+    ("flags", ctypes.c_uint32),
+]
+"""
+struct segment_command { /* for 32-bit architectures */
+    uint32_t	cmd;		/* LC_SEGMENT */
+    uint32_t	cmdsize;	/* includes sizeof section structs */
+    char		segname[16];	/* segment name */
+    uint32_t	vmaddr;		/* memory address of this segment */
+    uint32_t	vmsize;		/* memory size of this segment */
+    uint32_t	fileoff;	/* file offset of this segment */
+    uint32_t	filesize;	/* amount to map from the file */
+    vm_prot_t	maxprot;	/* maximum VM protection */
+    vm_prot_t	initprot;	/* initial VM protection */
+    uint32_t	nsects;		/* number of sections in segment */
+    uint32_t	flags;		/* flags */
+};
+typedef int vm_prot_t;
+"""
+
+segment_command_fields_64 = [
+    ("cmd", ctypes.c_uint32),
+    ("cmdsize", ctypes.c_uint32),
+    ("segname", ctypes.c_char * 16),
+    ("vmaddr", ctypes.c_uint64),
+    ("vmsize", ctypes.c_uint64),
+    ("fileoff", ctypes.c_uint64),
+    ("filesize", ctypes.c_uint64),
+    ("maxprot", ctypes.c_int),
+    ("initprot", ctypes.c_int),
+    ("nsects", ctypes.c_uint32),
+    ("flags", ctypes.c_uint32),
+]
+"""
+struct segment_command_64 { /* for 64-bit architectures */
+    uint32_t	cmd;		/* LC_SEGMENT_64 */
+    uint32_t	cmdsize;	/* includes sizeof section_64 structs */
+    char		segname[16];	/* segment name */
+    uint64_t	vmaddr;		/* memory address of this segment */
+    uint64_t	vmsize;		/* memory size of this segment */
+    uint64_t	fileoff;	/* file offset of this segment */
+    uint64_t	filesize;	/* amount to map from the file */
+    vm_prot_t	maxprot;	/* maximum VM protection */
+    vm_prot_t	initprot;	/* initial VM protection */
+    uint32_t	nsects;		/* number of sections in segment */
+    uint32_t	flags;		/* flags */
+};
+"""
+
+version_min_command_fields = segment_base_fields + [
+    ("version", ctypes.c_uint32),
+    ("sdk", ctypes.c_uint32),
+]
+"""
+struct version_min_command {
+    uint32_t	cmd;		/* LC_VERSION_MIN_MACOSX or
+                               LC_VERSION_MIN_IPHONEOS or
+                               LC_VERSION_MIN_WATCHOS or
+                               LC_VERSION_MIN_TVOS */
+    uint32_t	cmdsize;	/* sizeof(struct min_version_command) */
+    uint32_t	version;	/* X.Y.Z is encoded in nibbles xxxx.yy.zz */
+    uint32_t	sdk;		/* X.Y.Z is encoded in nibbles xxxx.yy.zz */
+};
+"""
+
+build_version_command_fields = segment_base_fields + [
+    ("platform", ctypes.c_uint32),
+    ("minos", ctypes.c_uint32),
+    ("sdk", ctypes.c_uint32),
+    ("ntools", ctypes.c_uint32),
+]
+"""
+struct build_version_command {
+    uint32_t	cmd;		/* LC_BUILD_VERSION */
+    uint32_t	cmdsize;	/* sizeof(struct build_version_command) plus */
+                                /* ntools * sizeof(struct build_tool_version) */
+    uint32_t	platform;	/* platform */
+    uint32_t	minos;		/* X.Y.Z is encoded in nibbles xxxx.yy.zz */
+    uint32_t	sdk;		/* X.Y.Z is encoded in nibbles xxxx.yy.zz */
+    uint32_t	ntools;		/* number of tool entries following this */
+};
+"""
+
+
+def swap32(x: int) -> int:
+    return (
+        ((x << 24) & 0xFF000000)
+        | ((x << 8) & 0x00FF0000)
+        | ((x >> 8) & 0x0000FF00)
+        | ((x >> 24) & 0x000000FF)
+    )
+
+
+def get_base_class_and_magic_number(
+    lib_file: BufferedIOBase,
+    seek: int | None = None,
+) -> tuple[type[ctypes.Structure], int]:
+    if seek is None:
+        seek = lib_file.tell()
+    else:
+        lib_file.seek(seek)
+    magic_number = ctypes.c_uint32.from_buffer_copy(
+        lib_file.read(ctypes.sizeof(ctypes.c_uint32))
+    ).value
+
+    # Handle wrong byte order
+    if magic_number in [FAT_CIGAM, FAT_CIGAM_64, MH_CIGAM, MH_CIGAM_64]:
+        if sys.byteorder == "little":
+            BaseClass = ctypes.BigEndianStructure
+        else:
+            BaseClass = ctypes.LittleEndianStructure
+
+        magic_number = swap32(magic_number)
+    else:
+        BaseClass = ctypes.Structure
+
+    lib_file.seek(seek)
+    return BaseClass, magic_number
+
+
+def read_data(struct_class: type[ctypes.Structure], lib_file: BufferedIOBase):
+    return struct_class.from_buffer_copy(lib_file.read(ctypes.sizeof(struct_class)))
+
+
+def extract_macosx_min_system_version(path_to_lib: str):
+    with open(path_to_lib, "rb") as lib_file:
+        BaseClass, magic_number = get_base_class_and_magic_number(lib_file, 0)
+        if magic_number not in [FAT_MAGIC, FAT_MAGIC_64, MH_MAGIC, MH_MAGIC_64]:
+            return
+
+        if magic_number in [FAT_MAGIC, FAT_CIGAM_64]:
+
+            class FatHeader(BaseClass):
+                _fields_ = fat_header_fields
+
+            fat_header = read_data(FatHeader, lib_file)
+            if magic_number == FAT_MAGIC:
+
+                class FatArch(BaseClass):
+                    _fields_ = fat_arch_fields
+
+            else:
+
+                class FatArch(BaseClass):
+                    _fields_ = fat_arch_64_fields
+
+            fat_arch_list = [
+                read_data(FatArch, lib_file) for _ in range(fat_header.nfat_arch)
+            ]
+
+            versions_list: list[tuple[int, int, int]] = []
+            for el in fat_arch_list:
+                try:
+                    version = read_mach_header(lib_file, el.offset)
+                    if version is not None:
+                        if el.cputype == CPU_TYPE_ARM64 and len(fat_arch_list) != 1:
+                            # Xcode will not set the deployment target below 11.0.0
+                            # for the arm64 architecture. Ignore the arm64 deployment
+                            # in fat binaries when the target is 11.0.0, that way
+                            # the other architectures can select a lower deployment
+                            # target.
+                            # This is safe because there is no arm64 variant for
+                            # macOS 10.15 or earlier.
+                            if version == (11, 0, 0):
+                                continue
+                        versions_list.append(version)
+                except ValueError:
+                    pass
+
+            if len(versions_list) > 0:
+                return max(versions_list)
+            else:
+                return None
+
+        else:
+            try:
+                return read_mach_header(lib_file, 0)
+            except ValueError:
+                """when some error during read library files"""
+                return None
+
+
+def read_mach_header(
+    lib_file: BufferedIOBase,
+    seek: int | None = None,
+) -> tuple[int, int, int] | None:
+    """
+    This function parses a Mach-O header and extracts
+    information about the minimal macOS version.
+
+    :param lib_file: reference to opened library file with pointer
+    """
+    base_class, magic_number = get_base_class_and_magic_number(lib_file, seek)
+    arch = "32" if magic_number == MH_MAGIC else "64"
+
+    class SegmentBase(base_class):
+        _fields_ = segment_base_fields
+
+    if arch == "32":
+
+        class MachHeader(base_class):
+            _fields_ = mach_header_fields
+
+    else:
+
+        class MachHeader(base_class):
+            _fields_ = mach_header_fields_64
+
+    mach_header = read_data(MachHeader, lib_file)
+    for _i in range(mach_header.ncmds):
+        pos = lib_file.tell()
+        segment_base = read_data(SegmentBase, lib_file)
+        lib_file.seek(pos)
+        if segment_base.cmd == LC_VERSION_MIN_MACOSX:
+
+            class VersionMinCommand(base_class):
+                _fields_ = version_min_command_fields
+
+            version_info = read_data(VersionMinCommand, lib_file)
+            return parse_version(version_info.version)
+        elif segment_base.cmd == LC_BUILD_VERSION:
+
+            class VersionBuild(base_class):
+                _fields_ = build_version_command_fields
+
+            version_info = read_data(VersionBuild, lib_file)
+            return parse_version(version_info.minos)
+        else:
+            lib_file.seek(pos + segment_base.cmdsize)
+            continue
+
+
+def parse_version(version: int) -> tuple[int, int, int]:
+    x = (version & 0xFFFF0000) >> 16
+    y = (version & 0x0000FF00) >> 8
+    z = version & 0x000000FF
+    return x, y, z
+
+
+def calculate_macosx_platform_tag(archive_root: StrPath, platform_tag: str) -> str:
+    """
+    Calculate proper macosx platform tag basing on files which are included to wheel
+
+    Example platform tag `macosx-10.14-x86_64`
+    """
+    prefix, base_version, suffix = platform_tag.split("-")
+    base_version = tuple(int(x) for x in base_version.split("."))
+    base_version = base_version[:2]
+    if base_version[0] > 10:
+        base_version = (base_version[0], 0)
+    assert len(base_version) == 2
+    if "MACOSX_DEPLOYMENT_TARGET" in os.environ:
+        deploy_target = tuple(
+            int(x) for x in os.environ["MACOSX_DEPLOYMENT_TARGET"].split(".")
+        )
+        deploy_target = deploy_target[:2]
+        if deploy_target[0] > 10:
+            deploy_target = (deploy_target[0], 0)
+        if deploy_target < base_version:
+            sys.stderr.write(
+                "[WARNING] MACOSX_DEPLOYMENT_TARGET is set to a lower value ({}) than "
+                "the version on which the Python interpreter was compiled ({}), and "
+                "will be ignored.\n".format(
+                    ".".join(str(x) for x in deploy_target),
+                    ".".join(str(x) for x in base_version),
+                )
+            )
+        else:
+            base_version = deploy_target
+
+    assert len(base_version) == 2
+    start_version = base_version
+    versions_dict: dict[str, tuple[int, int]] = {}
+    for dirpath, _dirnames, filenames in os.walk(archive_root):
+        for filename in filenames:
+            if filename.endswith(".dylib") or filename.endswith(".so"):
+                lib_path = os.path.join(dirpath, filename)
+                min_ver = extract_macosx_min_system_version(lib_path)
+                if min_ver is not None:
+                    min_ver = min_ver[0:2]
+                    if min_ver[0] > 10:
+                        min_ver = (min_ver[0], 0)
+                    versions_dict[lib_path] = min_ver
+
+    if len(versions_dict) > 0:
+        base_version = max(base_version, max(versions_dict.values()))
+
+    # macosx platform tag do not support minor bugfix release
+    fin_base_version = "_".join([str(x) for x in base_version])
+    if start_version < base_version:
+        problematic_files = [k for k, v in versions_dict.items() if v > start_version]
+        problematic_files = "\n".join(problematic_files)
+        if len(problematic_files) == 1:
+            files_form = "this file"
+        else:
+            files_form = "these files"
+        error_message = (
+            "[WARNING] This wheel needs a higher macOS version than {}  "
+            "To silence this warning, set MACOSX_DEPLOYMENT_TARGET to at least "
+            + fin_base_version
+            + " or recreate "
+            + files_form
+            + " with lower "
+            "MACOSX_DEPLOYMENT_TARGET:  \n" + problematic_files
+        )
+
+        if "MACOSX_DEPLOYMENT_TARGET" in os.environ:
+            error_message = error_message.format(
+                "is set in MACOSX_DEPLOYMENT_TARGET variable."
+            )
+        else:
+            error_message = error_message.format(
+                "the version your Python interpreter is compiled against."
+            )
+
+        sys.stderr.write(error_message)
+
+    platform_tag = prefix + "_" + fin_base_version + "_" + suffix
+    return platform_tag
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/metadata.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/metadata.py
new file mode 100644
index 0000000000000000000000000000000000000000..b8098fa8599a1f142ee33ee551b7a874f5f98840
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/metadata.py
@@ -0,0 +1,183 @@
+"""
+Tools for converting old- to new-style metadata.
+"""
+
+from __future__ import annotations
+
+import functools
+import itertools
+import os.path
+import re
+import textwrap
+from email.message import Message
+from email.parser import Parser
+from typing import Generator, Iterable, Iterator, Literal
+
+from .vendored.packaging.requirements import Requirement
+
+
+def _nonblank(str: str) -> bool | Literal[""]:
+    return str and not str.startswith("#")
+
+
+@functools.singledispatch
+def yield_lines(iterable: Iterable[str]) -> Iterator[str]:
+    r"""
+    Yield valid lines of a string or iterable.
+    >>> list(yield_lines(''))
+    []
+    >>> list(yield_lines(['foo', 'bar']))
+    ['foo', 'bar']
+    >>> list(yield_lines('foo\nbar'))
+    ['foo', 'bar']
+    >>> list(yield_lines('\nfoo\n#bar\nbaz #comment'))
+    ['foo', 'baz #comment']
+    >>> list(yield_lines(['foo\nbar', 'baz', 'bing\n\n\n']))
+    ['foo', 'bar', 'baz', 'bing']
+    """
+    return itertools.chain.from_iterable(map(yield_lines, iterable))
+
+
+@yield_lines.register(str)
+def _(text: str) -> Iterator[str]:
+    return filter(_nonblank, map(str.strip, text.splitlines()))
+
+
+def split_sections(
+    s: str | Iterator[str],
+) -> Generator[tuple[str | None, list[str]], None, None]:
+    """Split a string or iterable thereof into (section, content) pairs
+    Each ``section`` is a stripped version of the section header ("[section]")
+    and each ``content`` is a list of stripped lines excluding blank lines and
+    comment-only lines.  If there are any such lines before the first section
+    header, they're returned in a first ``section`` of ``None``.
+    """
+    section = None
+    content: list[str] = []
+    for line in yield_lines(s):
+        if line.startswith("["):
+            if line.endswith("]"):
+                if section or content:
+                    yield section, content
+                section = line[1:-1].strip()
+                content = []
+            else:
+                raise ValueError("Invalid section heading", line)
+        else:
+            content.append(line)
+
+    # wrap up last segment
+    yield section, content
+
+
+def safe_extra(extra: str) -> str:
+    """Convert an arbitrary string to a standard 'extra' name
+    Any runs of non-alphanumeric characters are replaced with a single '_',
+    and the result is always lowercased.
+    """
+    return re.sub("[^A-Za-z0-9.-]+", "_", extra).lower()
+
+
+def safe_name(name: str) -> str:
+    """Convert an arbitrary string to a standard distribution name
+    Any runs of non-alphanumeric/. characters are replaced with a single '-'.
+    """
+    return re.sub("[^A-Za-z0-9.]+", "-", name)
+
+
+def requires_to_requires_dist(requirement: Requirement) -> str:
+    """Return the version specifier for a requirement in PEP 345/566 fashion."""
+    if requirement.url:
+        return " @ " + requirement.url
+
+    requires_dist: list[str] = []
+    for spec in requirement.specifier:
+        requires_dist.append(spec.operator + spec.version)
+
+    if requires_dist:
+        return " " + ",".join(sorted(requires_dist))
+    else:
+        return ""
+
+
+def convert_requirements(requirements: list[str]) -> Iterator[str]:
+    """Yield Requires-Dist: strings for parsed requirements strings."""
+    for req in requirements:
+        parsed_requirement = Requirement(req)
+        spec = requires_to_requires_dist(parsed_requirement)
+        extras = ",".join(sorted(safe_extra(e) for e in parsed_requirement.extras))
+        if extras:
+            extras = f"[{extras}]"
+
+        yield safe_name(parsed_requirement.name) + extras + spec
+
+
+def generate_requirements(
+    extras_require: dict[str | None, list[str]],
+) -> Iterator[tuple[str, str]]:
+    """
+    Convert requirements from a setup()-style dictionary to
+    ('Requires-Dist', 'requirement') and ('Provides-Extra', 'extra') tuples.
+
+    extras_require is a dictionary of {extra: [requirements]} as passed to setup(),
+    using the empty extra {'': [requirements]} to hold install_requires.
+    """
+    for extra, depends in extras_require.items():
+        condition = ""
+        extra = extra or ""
+        if ":" in extra:  # setuptools extra:condition syntax
+            extra, condition = extra.split(":", 1)
+
+        extra = safe_extra(extra)
+        if extra:
+            yield "Provides-Extra", extra
+            if condition:
+                condition = "(" + condition + ") and "
+            condition += f"extra == '{extra}'"
+
+        if condition:
+            condition = " ; " + condition
+
+        for new_req in convert_requirements(depends):
+            canonical_req = str(Requirement(new_req + condition))
+            yield "Requires-Dist", canonical_req
+
+
+def pkginfo_to_metadata(egg_info_path: str, pkginfo_path: str) -> Message:
+    """
+    Convert .egg-info directory with PKG-INFO to the Metadata 2.1 format
+    """
+    with open(pkginfo_path, encoding="utf-8") as headers:
+        pkg_info = Parser().parse(headers)
+
+    pkg_info.replace_header("Metadata-Version", "2.1")
+    # Those will be regenerated from `requires.txt`.
+    del pkg_info["Provides-Extra"]
+    del pkg_info["Requires-Dist"]
+    requires_path = os.path.join(egg_info_path, "requires.txt")
+    if os.path.exists(requires_path):
+        with open(requires_path, encoding="utf-8") as requires_file:
+            requires = requires_file.read()
+
+        parsed_requirements = sorted(split_sections(requires), key=lambda x: x[0] or "")
+        for extra, reqs in parsed_requirements:
+            for key, value in generate_requirements({extra: reqs}):
+                if (key, value) not in pkg_info.items():
+                    pkg_info[key] = value
+
+    description = pkg_info["Description"]
+    if description:
+        description_lines = pkg_info["Description"].splitlines()
+        dedented_description = "\n".join(
+            # if the first line of long_description is blank,
+            # the first line here will be indented.
+            (
+                description_lines[0].lstrip(),
+                textwrap.dedent("\n".join(description_lines[1:])),
+                "\n",
+            )
+        )
+        pkg_info.set_payload(dedented_description)
+        del pkg_info["Description"]
+
+    return pkg_info
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/util.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/util.py
new file mode 100644
index 0000000000000000000000000000000000000000..c928aa403b75e1ae392b4af5fe13147a095bbd30
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/util.py
@@ -0,0 +1,17 @@
+from __future__ import annotations
+
+import base64
+import logging
+
+log = logging.getLogger("wheel")
+
+
+def urlsafe_b64encode(data: bytes) -> bytes:
+    """urlsafe_b64encode without padding"""
+    return base64.urlsafe_b64encode(data).rstrip(b"=")
+
+
+def urlsafe_b64decode(data: bytes) -> bytes:
+    """urlsafe_b64decode without padding"""
+    pad = b"=" * (4 - (len(data) & 3))
+    return base64.urlsafe_b64decode(data + pad)
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/__init__.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5ea332a76e71a5b09a3ce0734edafb1ec15459ef
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/LICENSE b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..6f62d44e4ef733c0e713afcd2371fed7f2b3de67
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/LICENSE
@@ -0,0 +1,3 @@
+This software is made available under the terms of *either* of the licenses
+found in LICENSE.APACHE or LICENSE.BSD. Contributions to this software is made
+under the terms of *both* these licenses.
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/LICENSE.APACHE b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/LICENSE.APACHE
new file mode 100644
index 0000000000000000000000000000000000000000..f433b1a53f5b830a205fd2df78e2b34974656c7b
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/LICENSE.APACHE
@@ -0,0 +1,177 @@
+
+                                 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
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/LICENSE.BSD b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/LICENSE.BSD
new file mode 100644
index 0000000000000000000000000000000000000000..42ce7b75c92fb01a3f6ed17eea363f756b7da582
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/LICENSE.BSD
@@ -0,0 +1,23 @@
+Copyright (c) Donald Stufft and individual contributors.
+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.
+
+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.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__init__.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6f63f93a0b0578e5d62e30c90633da4b6eb96a2c
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/_elffile.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/_elffile.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cdc2a709f5409e6a0450ac7fc51fbaa3a95f0593
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/_elffile.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/_manylinux.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/_manylinux.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d171c92bb616214348f09fade7b7a678892769a1
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/_manylinux.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/_musllinux.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/_musllinux.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..71f767b48c11ebd80ac6deaee46482f74170c04b
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/_musllinux.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/_parser.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/_parser.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dd3db38b6bb40136aaa177ad2ec63d224efbb1d9
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/_parser.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/_structures.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/_structures.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..201be20be9f5567a8bf93beeb06e990fd68e3720
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/_structures.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/_tokenizer.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/_tokenizer.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e0e1816be048266bbd2948cb511a070390004ad2
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/_tokenizer.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/markers.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/markers.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0fe5810c939a9d9e70812d3893cd52d03b0a869e
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/markers.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/requirements.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/requirements.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f259422ef2321dc8c6f722472374a593602599e5
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/requirements.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/specifiers.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/specifiers.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3739b4a92caf057ed31610e832136be67212f163
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/specifiers.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/tags.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/tags.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7255da6a9a911900dcabf4dd39e9e3bc76f90b11
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/tags.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..121ed128143af1975996499893dddf8f656c0cc6
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/utils.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/version.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/version.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7b1440885a13465b11afa23b746d07b9d9946789
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/__pycache__/version.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/_elffile.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/_elffile.py
new file mode 100644
index 0000000000000000000000000000000000000000..6fb19b30bb53c18f38a9ef02dd7c4478670fb962
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/_elffile.py
@@ -0,0 +1,108 @@
+"""
+ELF file parser.
+
+This provides a class ``ELFFile`` that parses an ELF executable in a similar
+interface to ``ZipFile``. Only the read interface is implemented.
+
+Based on: https://gist.github.com/lyssdod/f51579ae8d93c8657a5564aefc2ffbca
+ELF header: https://refspecs.linuxfoundation.org/elf/gabi4+/ch4.eheader.html
+"""
+
+import enum
+import os
+import struct
+from typing import IO, Optional, Tuple
+
+
+class ELFInvalid(ValueError):
+    pass
+
+
+class EIClass(enum.IntEnum):
+    C32 = 1
+    C64 = 2
+
+
+class EIData(enum.IntEnum):
+    Lsb = 1
+    Msb = 2
+
+
+class EMachine(enum.IntEnum):
+    I386 = 3
+    S390 = 22
+    Arm = 40
+    X8664 = 62
+    AArc64 = 183
+
+
+class ELFFile:
+    """
+    Representation of an ELF executable.
+    """
+
+    def __init__(self, f: IO[bytes]) -> None:
+        self._f = f
+
+        try:
+            ident = self._read("16B")
+        except struct.error:
+            raise ELFInvalid("unable to parse identification")
+        magic = bytes(ident[:4])
+        if magic != b"\x7fELF":
+            raise ELFInvalid(f"invalid magic: {magic!r}")
+
+        self.capacity = ident[4]  # Format for program header (bitness).
+        self.encoding = ident[5]  # Data structure encoding (endianness).
+
+        try:
+            # e_fmt: Format for program header.
+            # p_fmt: Format for section header.
+            # p_idx: Indexes to find p_type, p_offset, and p_filesz.
+            e_fmt, self._p_fmt, self._p_idx = {
+                (1, 1): ("HHIIIIIHHH", ">IIIIIIII", (0, 1, 4)),  # 32-bit MSB.
+                (2, 1): ("HHIQQQIHHH", ">IIQQQQQQ", (0, 2, 5)),  # 64-bit MSB.
+            }[(self.capacity, self.encoding)]
+        except KeyError:
+            raise ELFInvalid(
+                f"unrecognized capacity ({self.capacity}) or "
+                f"encoding ({self.encoding})"
+            )
+
+        try:
+            (
+                _,
+                self.machine,  # Architecture type.
+                _,
+                _,
+                self._e_phoff,  # Offset of program header.
+                _,
+                self.flags,  # Processor-specific flags.
+                _,
+                self._e_phentsize,  # Size of section.
+                self._e_phnum,  # Number of sections.
+            ) = self._read(e_fmt)
+        except struct.error as e:
+            raise ELFInvalid("unable to parse machine and section information") from e
+
+    def _read(self, fmt: str) -> Tuple[int, ...]:
+        return struct.unpack(fmt, self._f.read(struct.calcsize(fmt)))
+
+    @property
+    def interpreter(self) -> Optional[str]:
+        """
+        The path recorded in the ``PT_INTERP`` section header.
+        """
+        for index in range(self._e_phnum):
+            self._f.seek(self._e_phoff + self._e_phentsize * index)
+            try:
+                data = self._read(self._p_fmt)
+            except struct.error:
+                continue
+            if data[self._p_idx[0]] != 3:  # Not PT_INTERP.
+                continue
+            self._f.seek(data[self._p_idx[1]])
+            return os.fsdecode(self._f.read(data[self._p_idx[2]])).strip("\0")
+        return None
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/_manylinux.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/_manylinux.py
new file mode 100644
index 0000000000000000000000000000000000000000..1f5f4ab3e514d1846d3bd189bf081fdb1528ba08
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/_manylinux.py
@@ -0,0 +1,260 @@
+import collections
+import contextlib
+import functools
+import os
+import re
+import sys
+import warnings
+from typing import Dict, Generator, Iterator, NamedTuple, Optional, Sequence, Tuple
+
+from ._elffile import EIClass, EIData, ELFFile, EMachine
+
+EF_ARM_ABIMASK = 0xFF000000
+EF_ARM_ABI_VER5 = 0x05000000
+EF_ARM_ABI_FLOAT_HARD = 0x00000400
+
+
+# `os.PathLike` not a generic type until Python 3.9, so sticking with `str`
+# as the type for `path` until then.
+@contextlib.contextmanager
+def _parse_elf(path: str) -> Generator[Optional[ELFFile], None, None]:
+    try:
+        with open(path, "rb") as f:
+            yield ELFFile(f)
+    except (OSError, TypeError, ValueError):
+        yield None
+
+
+def _is_linux_armhf(executable: str) -> bool:
+    # hard-float ABI can be detected from the ELF header of the running
+    # process
+    # https://static.docs.arm.com/ihi0044/g/aaelf32.pdf
+    with _parse_elf(executable) as f:
+        return (
+            f is not None
+            and f.capacity == EIClass.C32
+            and f.encoding == EIData.Lsb
+            and f.machine == EMachine.Arm
+            and f.flags & EF_ARM_ABIMASK == EF_ARM_ABI_VER5
+            and f.flags & EF_ARM_ABI_FLOAT_HARD == EF_ARM_ABI_FLOAT_HARD
+        )
+
+
+def _is_linux_i686(executable: str) -> bool:
+    with _parse_elf(executable) as f:
+        return (
+            f is not None
+            and f.capacity == EIClass.C32
+            and f.encoding == EIData.Lsb
+            and f.machine == EMachine.I386
+        )
+
+
+def _have_compatible_abi(executable: str, archs: Sequence[str]) -> bool:
+    if "armv7l" in archs:
+        return _is_linux_armhf(executable)
+    if "i686" in archs:
+        return _is_linux_i686(executable)
+    allowed_archs = {
+        "x86_64",
+        "aarch64",
+        "ppc64",
+        "ppc64le",
+        "s390x",
+        "loongarch64",
+        "riscv64",
+    }
+    return any(arch in allowed_archs for arch in archs)
+
+
+# If glibc ever changes its major version, we need to know what the last
+# minor version was, so we can build the complete list of all versions.
+# For now, guess what the highest minor version might be, assume it will
+# be 50 for testing. Once this actually happens, update the dictionary
+# with the actual value.
+_LAST_GLIBC_MINOR: Dict[int, int] = collections.defaultdict(lambda: 50)
+
+
+class _GLibCVersion(NamedTuple):
+    major: int
+    minor: int
+
+
+def _glibc_version_string_confstr() -> Optional[str]:
+    """
+    Primary implementation of glibc_version_string using os.confstr.
+    """
+    # os.confstr is quite a bit faster than ctypes.DLL. It's also less likely
+    # to be broken or missing. This strategy is used in the standard library
+    # platform module.
+    # https://github.com/python/cpython/blob/fcf1d003bf4f0100c/Lib/platform.py#L175-L183
+    try:
+        # Should be a string like "glibc 2.17".
+        version_string: Optional[str] = os.confstr("CS_GNU_LIBC_VERSION")
+        assert version_string is not None
+        _, version = version_string.rsplit()
+    except (AssertionError, AttributeError, OSError, ValueError):
+        # os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)...
+        return None
+    return version
+
+
+def _glibc_version_string_ctypes() -> Optional[str]:
+    """
+    Fallback implementation of glibc_version_string using ctypes.
+    """
+    try:
+        import ctypes
+    except ImportError:
+        return None
+
+    # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen
+    # manpage says, "If filename is NULL, then the returned handle is for the
+    # main program". This way we can let the linker do the work to figure out
+    # which libc our process is actually using.
+    #
+    # We must also handle the special case where the executable is not a
+    # dynamically linked executable. This can occur when using musl libc,
+    # for example. In this situation, dlopen() will error, leading to an
+    # OSError. Interestingly, at least in the case of musl, there is no
+    # errno set on the OSError. The single string argument used to construct
+    # OSError comes from libc itself and is therefore not portable to
+    # hard code here. In any case, failure to call dlopen() means we
+    # can proceed, so we bail on our attempt.
+    try:
+        process_namespace = ctypes.CDLL(None)
+    except OSError:
+        return None
+
+    try:
+        gnu_get_libc_version = process_namespace.gnu_get_libc_version
+    except AttributeError:
+        # Symbol doesn't exist -> therefore, we are not linked to
+        # glibc.
+        return None
+
+    # Call gnu_get_libc_version, which returns a string like "2.5"
+    gnu_get_libc_version.restype = ctypes.c_char_p
+    version_str: str = gnu_get_libc_version()
+    # py2 / py3 compatibility:
+    if not isinstance(version_str, str):
+        version_str = version_str.decode("ascii")
+
+    return version_str
+
+
+def _glibc_version_string() -> Optional[str]:
+    """Returns glibc version string, or None if not using glibc."""
+    return _glibc_version_string_confstr() or _glibc_version_string_ctypes()
+
+
+def _parse_glibc_version(version_str: str) -> Tuple[int, int]:
+    """Parse glibc version.
+
+    We use a regexp instead of str.split because we want to discard any
+    random junk that might come after the minor version -- this might happen
+    in patched/forked versions of glibc (e.g. Linaro's version of glibc
+    uses version strings like "2.20-2014.11"). See gh-3588.
+    """
+    m = re.match(r"(?P[0-9]+)\.(?P[0-9]+)", version_str)
+    if not m:
+        warnings.warn(
+            f"Expected glibc version with 2 components major.minor,"
+            f" got: {version_str}",
+            RuntimeWarning,
+        )
+        return -1, -1
+    return int(m.group("major")), int(m.group("minor"))
+
+
+@functools.lru_cache
+def _get_glibc_version() -> Tuple[int, int]:
+    version_str = _glibc_version_string()
+    if version_str is None:
+        return (-1, -1)
+    return _parse_glibc_version(version_str)
+
+
+# From PEP 513, PEP 600
+def _is_compatible(arch: str, version: _GLibCVersion) -> bool:
+    sys_glibc = _get_glibc_version()
+    if sys_glibc < version:
+        return False
+    # Check for presence of _manylinux module.
+    try:
+        import _manylinux
+    except ImportError:
+        return True
+    if hasattr(_manylinux, "manylinux_compatible"):
+        result = _manylinux.manylinux_compatible(version[0], version[1], arch)
+        if result is not None:
+            return bool(result)
+        return True
+    if version == _GLibCVersion(2, 5):
+        if hasattr(_manylinux, "manylinux1_compatible"):
+            return bool(_manylinux.manylinux1_compatible)
+    if version == _GLibCVersion(2, 12):
+        if hasattr(_manylinux, "manylinux2010_compatible"):
+            return bool(_manylinux.manylinux2010_compatible)
+    if version == _GLibCVersion(2, 17):
+        if hasattr(_manylinux, "manylinux2014_compatible"):
+            return bool(_manylinux.manylinux2014_compatible)
+    return True
+
+
+_LEGACY_MANYLINUX_MAP = {
+    # CentOS 7 w/ glibc 2.17 (PEP 599)
+    (2, 17): "manylinux2014",
+    # CentOS 6 w/ glibc 2.12 (PEP 571)
+    (2, 12): "manylinux2010",
+    # CentOS 5 w/ glibc 2.5 (PEP 513)
+    (2, 5): "manylinux1",
+}
+
+
+def platform_tags(archs: Sequence[str]) -> Iterator[str]:
+    """Generate manylinux tags compatible to the current platform.
+
+    :param archs: Sequence of compatible architectures.
+        The first one shall be the closest to the actual architecture and be the part of
+        platform tag after the ``linux_`` prefix, e.g. ``x86_64``.
+        The ``linux_`` prefix is assumed as a prerequisite for the current platform to
+        be manylinux-compatible.
+
+    :returns: An iterator of compatible manylinux tags.
+    """
+    if not _have_compatible_abi(sys.executable, archs):
+        return
+    # Oldest glibc to be supported regardless of architecture is (2, 17).
+    too_old_glibc2 = _GLibCVersion(2, 16)
+    if set(archs) & {"x86_64", "i686"}:
+        # On x86/i686 also oldest glibc to be supported is (2, 5).
+        too_old_glibc2 = _GLibCVersion(2, 4)
+    current_glibc = _GLibCVersion(*_get_glibc_version())
+    glibc_max_list = [current_glibc]
+    # We can assume compatibility across glibc major versions.
+    # https://sourceware.org/bugzilla/show_bug.cgi?id=24636
+    #
+    # Build a list of maximum glibc versions so that we can
+    # output the canonical list of all glibc from current_glibc
+    # down to too_old_glibc2, including all intermediary versions.
+    for glibc_major in range(current_glibc.major - 1, 1, -1):
+        glibc_minor = _LAST_GLIBC_MINOR[glibc_major]
+        glibc_max_list.append(_GLibCVersion(glibc_major, glibc_minor))
+    for arch in archs:
+        for glibc_max in glibc_max_list:
+            if glibc_max.major == too_old_glibc2.major:
+                min_minor = too_old_glibc2.minor
+            else:
+                # For other glibc major versions oldest supported is (x, 0).
+                min_minor = -1
+            for glibc_minor in range(glibc_max.minor, min_minor, -1):
+                glibc_version = _GLibCVersion(glibc_max.major, glibc_minor)
+                tag = "manylinux_{}_{}".format(*glibc_version)
+                if _is_compatible(arch, glibc_version):
+                    yield f"{tag}_{arch}"
+                # Handle the legacy manylinux1, manylinux2010, manylinux2014 tags.
+                if glibc_version in _LEGACY_MANYLINUX_MAP:
+                    legacy_tag = _LEGACY_MANYLINUX_MAP[glibc_version]
+                    if _is_compatible(arch, glibc_version):
+                        yield f"{legacy_tag}_{arch}"
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/_musllinux.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/_musllinux.py
new file mode 100644
index 0000000000000000000000000000000000000000..eb4251b5c1e82772b2b0ea539943da5141fd55ec
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/_musllinux.py
@@ -0,0 +1,83 @@
+"""PEP 656 support.
+
+This module implements logic to detect if the currently running Python is
+linked against musl, and what musl version is used.
+"""
+
+import functools
+import re
+import subprocess
+import sys
+from typing import Iterator, NamedTuple, Optional, Sequence
+
+from ._elffile import ELFFile
+
+
+class _MuslVersion(NamedTuple):
+    major: int
+    minor: int
+
+
+def _parse_musl_version(output: str) -> Optional[_MuslVersion]:
+    lines = [n for n in (n.strip() for n in output.splitlines()) if n]
+    if len(lines) < 2 or lines[0][:4] != "musl":
+        return None
+    m = re.match(r"Version (\d+)\.(\d+)", lines[1])
+    if not m:
+        return None
+    return _MuslVersion(major=int(m.group(1)), minor=int(m.group(2)))
+
+
+@functools.lru_cache
+def _get_musl_version(executable: str) -> Optional[_MuslVersion]:
+    """Detect currently-running musl runtime version.
+
+    This is done by checking the specified executable's dynamic linking
+    information, and invoking the loader to parse its output for a version
+    string. If the loader is musl, the output would be something like::
+
+        musl libc (x86_64)
+        Version 1.2.2
+        Dynamic Program Loader
+    """
+    try:
+        with open(executable, "rb") as f:
+            ld = ELFFile(f).interpreter
+    except (OSError, TypeError, ValueError):
+        return None
+    if ld is None or "musl" not in ld:
+        return None
+    proc = subprocess.run([ld], stderr=subprocess.PIPE, text=True)
+    return _parse_musl_version(proc.stderr)
+
+
+def platform_tags(archs: Sequence[str]) -> Iterator[str]:
+    """Generate musllinux tags compatible to the current platform.
+
+    :param archs: Sequence of compatible architectures.
+        The first one shall be the closest to the actual architecture and be the part of
+        platform tag after the ``linux_`` prefix, e.g. ``x86_64``.
+        The ``linux_`` prefix is assumed as a prerequisite for the current platform to
+        be musllinux-compatible.
+
+    :returns: An iterator of compatible musllinux tags.
+    """
+    sys_musl = _get_musl_version(sys.executable)
+    if sys_musl is None:  # Python not dynamically linked against musl.
+        return
+    for arch in archs:
+        for minor in range(sys_musl.minor, -1, -1):
+            yield f"musllinux_{sys_musl.major}_{minor}_{arch}"
+
+
+if __name__ == "__main__":  # pragma: no cover
+    import sysconfig
+
+    plat = sysconfig.get_platform()
+    assert plat.startswith("linux-"), "not linux"
+
+    print("plat:", plat)
+    print("musl:", _get_musl_version(sys.executable))
+    print("tags:", end=" ")
+    for t in platform_tags(re.sub(r"[.-]", "_", plat.split("-", 1)[-1])):
+        print(t, end="\n      ")
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/_parser.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/_parser.py
new file mode 100644
index 0000000000000000000000000000000000000000..513686a2190f9911c08ca1ca263f37b799f44702
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/_parser.py
@@ -0,0 +1,356 @@
+"""Handwritten parser of dependency specifiers.
+
+The docstring for each __parse_* function contains EBNF-inspired grammar representing
+the implementation.
+"""
+
+import ast
+from typing import Any, List, NamedTuple, Optional, Tuple, Union
+
+from ._tokenizer import DEFAULT_RULES, Tokenizer
+
+
+class Node:
+    def __init__(self, value: str) -> None:
+        self.value = value
+
+    def __str__(self) -> str:
+        return self.value
+
+    def __repr__(self) -> str:
+        return f"<{self.__class__.__name__}('{self}')>"
+
+    def serialize(self) -> str:
+        raise NotImplementedError
+
+
+class Variable(Node):
+    def serialize(self) -> str:
+        return str(self)
+
+
+class Value(Node):
+    def serialize(self) -> str:
+        return f'"{self}"'
+
+
+class Op(Node):
+    def serialize(self) -> str:
+        return str(self)
+
+
+MarkerVar = Union[Variable, Value]
+MarkerItem = Tuple[MarkerVar, Op, MarkerVar]
+# MarkerAtom = Union[MarkerItem, List["MarkerAtom"]]
+# MarkerList = List[Union["MarkerList", MarkerAtom, str]]
+# mypy does not support recursive type definition
+# https://github.com/python/mypy/issues/731
+MarkerAtom = Any
+MarkerList = List[Any]
+
+
+class ParsedRequirement(NamedTuple):
+    name: str
+    url: str
+    extras: List[str]
+    specifier: str
+    marker: Optional[MarkerList]
+
+
+# --------------------------------------------------------------------------------------
+# Recursive descent parser for dependency specifier
+# --------------------------------------------------------------------------------------
+def parse_requirement(source: str) -> ParsedRequirement:
+    return _parse_requirement(Tokenizer(source, rules=DEFAULT_RULES))
+
+
+def _parse_requirement(tokenizer: Tokenizer) -> ParsedRequirement:
+    """
+    requirement = WS? IDENTIFIER WS? extras WS? requirement_details
+    """
+    tokenizer.consume("WS")
+
+    name_token = tokenizer.expect(
+        "IDENTIFIER", expected="package name at the start of dependency specifier"
+    )
+    name = name_token.text
+    tokenizer.consume("WS")
+
+    extras = _parse_extras(tokenizer)
+    tokenizer.consume("WS")
+
+    url, specifier, marker = _parse_requirement_details(tokenizer)
+    tokenizer.expect("END", expected="end of dependency specifier")
+
+    return ParsedRequirement(name, url, extras, specifier, marker)
+
+
+def _parse_requirement_details(
+    tokenizer: Tokenizer,
+) -> Tuple[str, str, Optional[MarkerList]]:
+    """
+    requirement_details = AT URL (WS requirement_marker?)?
+                        | specifier WS? (requirement_marker)?
+    """
+
+    specifier = ""
+    url = ""
+    marker = None
+
+    if tokenizer.check("AT"):
+        tokenizer.read()
+        tokenizer.consume("WS")
+
+        url_start = tokenizer.position
+        url = tokenizer.expect("URL", expected="URL after @").text
+        if tokenizer.check("END", peek=True):
+            return (url, specifier, marker)
+
+        tokenizer.expect("WS", expected="whitespace after URL")
+
+        # The input might end after whitespace.
+        if tokenizer.check("END", peek=True):
+            return (url, specifier, marker)
+
+        marker = _parse_requirement_marker(
+            tokenizer, span_start=url_start, after="URL and whitespace"
+        )
+    else:
+        specifier_start = tokenizer.position
+        specifier = _parse_specifier(tokenizer)
+        tokenizer.consume("WS")
+
+        if tokenizer.check("END", peek=True):
+            return (url, specifier, marker)
+
+        marker = _parse_requirement_marker(
+            tokenizer,
+            span_start=specifier_start,
+            after=(
+                "version specifier"
+                if specifier
+                else "name and no valid version specifier"
+            ),
+        )
+
+    return (url, specifier, marker)
+
+
+def _parse_requirement_marker(
+    tokenizer: Tokenizer, *, span_start: int, after: str
+) -> MarkerList:
+    """
+    requirement_marker = SEMICOLON marker WS?
+    """
+
+    if not tokenizer.check("SEMICOLON"):
+        tokenizer.raise_syntax_error(
+            f"Expected end or semicolon (after {after})",
+            span_start=span_start,
+        )
+    tokenizer.read()
+
+    marker = _parse_marker(tokenizer)
+    tokenizer.consume("WS")
+
+    return marker
+
+
+def _parse_extras(tokenizer: Tokenizer) -> List[str]:
+    """
+    extras = (LEFT_BRACKET wsp* extras_list? wsp* RIGHT_BRACKET)?
+    """
+    if not tokenizer.check("LEFT_BRACKET", peek=True):
+        return []
+
+    with tokenizer.enclosing_tokens(
+        "LEFT_BRACKET",
+        "RIGHT_BRACKET",
+        around="extras",
+    ):
+        tokenizer.consume("WS")
+        extras = _parse_extras_list(tokenizer)
+        tokenizer.consume("WS")
+
+    return extras
+
+
+def _parse_extras_list(tokenizer: Tokenizer) -> List[str]:
+    """
+    extras_list = identifier (wsp* ',' wsp* identifier)*
+    """
+    extras: List[str] = []
+
+    if not tokenizer.check("IDENTIFIER"):
+        return extras
+
+    extras.append(tokenizer.read().text)
+
+    while True:
+        tokenizer.consume("WS")
+        if tokenizer.check("IDENTIFIER", peek=True):
+            tokenizer.raise_syntax_error("Expected comma between extra names")
+        elif not tokenizer.check("COMMA"):
+            break
+
+        tokenizer.read()
+        tokenizer.consume("WS")
+
+        extra_token = tokenizer.expect("IDENTIFIER", expected="extra name after comma")
+        extras.append(extra_token.text)
+
+    return extras
+
+
+def _parse_specifier(tokenizer: Tokenizer) -> str:
+    """
+    specifier = LEFT_PARENTHESIS WS? version_many WS? RIGHT_PARENTHESIS
+              | WS? version_many WS?
+    """
+    with tokenizer.enclosing_tokens(
+        "LEFT_PARENTHESIS",
+        "RIGHT_PARENTHESIS",
+        around="version specifier",
+    ):
+        tokenizer.consume("WS")
+        parsed_specifiers = _parse_version_many(tokenizer)
+        tokenizer.consume("WS")
+
+    return parsed_specifiers
+
+
+def _parse_version_many(tokenizer: Tokenizer) -> str:
+    """
+    version_many = (SPECIFIER (WS? COMMA WS? SPECIFIER)*)?
+    """
+    parsed_specifiers = ""
+    while tokenizer.check("SPECIFIER"):
+        span_start = tokenizer.position
+        parsed_specifiers += tokenizer.read().text
+        if tokenizer.check("VERSION_PREFIX_TRAIL", peek=True):
+            tokenizer.raise_syntax_error(
+                ".* suffix can only be used with `==` or `!=` operators",
+                span_start=span_start,
+                span_end=tokenizer.position + 1,
+            )
+        if tokenizer.check("VERSION_LOCAL_LABEL_TRAIL", peek=True):
+            tokenizer.raise_syntax_error(
+                "Local version label can only be used with `==` or `!=` operators",
+                span_start=span_start,
+                span_end=tokenizer.position,
+            )
+        tokenizer.consume("WS")
+        if not tokenizer.check("COMMA"):
+            break
+        parsed_specifiers += tokenizer.read().text
+        tokenizer.consume("WS")
+
+    return parsed_specifiers
+
+
+# --------------------------------------------------------------------------------------
+# Recursive descent parser for marker expression
+# --------------------------------------------------------------------------------------
+def parse_marker(source: str) -> MarkerList:
+    return _parse_full_marker(Tokenizer(source, rules=DEFAULT_RULES))
+
+
+def _parse_full_marker(tokenizer: Tokenizer) -> MarkerList:
+    retval = _parse_marker(tokenizer)
+    tokenizer.expect("END", expected="end of marker expression")
+    return retval
+
+
+def _parse_marker(tokenizer: Tokenizer) -> MarkerList:
+    """
+    marker = marker_atom (BOOLOP marker_atom)+
+    """
+    expression = [_parse_marker_atom(tokenizer)]
+    while tokenizer.check("BOOLOP"):
+        token = tokenizer.read()
+        expr_right = _parse_marker_atom(tokenizer)
+        expression.extend((token.text, expr_right))
+    return expression
+
+
+def _parse_marker_atom(tokenizer: Tokenizer) -> MarkerAtom:
+    """
+    marker_atom = WS? LEFT_PARENTHESIS WS? marker WS? RIGHT_PARENTHESIS WS?
+                | WS? marker_item WS?
+    """
+
+    tokenizer.consume("WS")
+    if tokenizer.check("LEFT_PARENTHESIS", peek=True):
+        with tokenizer.enclosing_tokens(
+            "LEFT_PARENTHESIS",
+            "RIGHT_PARENTHESIS",
+            around="marker expression",
+        ):
+            tokenizer.consume("WS")
+            marker: MarkerAtom = _parse_marker(tokenizer)
+            tokenizer.consume("WS")
+    else:
+        marker = _parse_marker_item(tokenizer)
+    tokenizer.consume("WS")
+    return marker
+
+
+def _parse_marker_item(tokenizer: Tokenizer) -> MarkerItem:
+    """
+    marker_item = WS? marker_var WS? marker_op WS? marker_var WS?
+    """
+    tokenizer.consume("WS")
+    marker_var_left = _parse_marker_var(tokenizer)
+    tokenizer.consume("WS")
+    marker_op = _parse_marker_op(tokenizer)
+    tokenizer.consume("WS")
+    marker_var_right = _parse_marker_var(tokenizer)
+    tokenizer.consume("WS")
+    return (marker_var_left, marker_op, marker_var_right)
+
+
+def _parse_marker_var(tokenizer: Tokenizer) -> MarkerVar:
+    """
+    marker_var = VARIABLE | QUOTED_STRING
+    """
+    if tokenizer.check("VARIABLE"):
+        return process_env_var(tokenizer.read().text.replace(".", "_"))
+    elif tokenizer.check("QUOTED_STRING"):
+        return process_python_str(tokenizer.read().text)
+    else:
+        tokenizer.raise_syntax_error(
+            message="Expected a marker variable or quoted string"
+        )
+
+
+def process_env_var(env_var: str) -> Variable:
+    if env_var in ("platform_python_implementation", "python_implementation"):
+        return Variable("platform_python_implementation")
+    else:
+        return Variable(env_var)
+
+
+def process_python_str(python_str: str) -> Value:
+    value = ast.literal_eval(python_str)
+    return Value(str(value))
+
+
+def _parse_marker_op(tokenizer: Tokenizer) -> Op:
+    """
+    marker_op = IN | NOT IN | OP
+    """
+    if tokenizer.check("IN"):
+        tokenizer.read()
+        return Op("in")
+    elif tokenizer.check("NOT"):
+        tokenizer.read()
+        tokenizer.expect("WS", expected="whitespace after 'not'")
+        tokenizer.expect("IN", expected="'in' after 'not'")
+        return Op("not in")
+    elif tokenizer.check("OP"):
+        return Op(tokenizer.read().text)
+    else:
+        return tokenizer.raise_syntax_error(
+            "Expected marker operator, one of "
+            "<=, <, !=, ==, >=, >, ~=, ===, in, not in"
+        )
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/_structures.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/_structures.py
new file mode 100644
index 0000000000000000000000000000000000000000..90a6465f9682c886363eea5327dac64bf623a6ff
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/_structures.py
@@ -0,0 +1,61 @@
+# This file is dual licensed under the terms of the Apache License, Version
+# 2.0, and the BSD License. See the LICENSE file in the root of this repository
+# for complete details.
+
+
+class InfinityType:
+    def __repr__(self) -> str:
+        return "Infinity"
+
+    def __hash__(self) -> int:
+        return hash(repr(self))
+
+    def __lt__(self, other: object) -> bool:
+        return False
+
+    def __le__(self, other: object) -> bool:
+        return False
+
+    def __eq__(self, other: object) -> bool:
+        return isinstance(other, self.__class__)
+
+    def __gt__(self, other: object) -> bool:
+        return True
+
+    def __ge__(self, other: object) -> bool:
+        return True
+
+    def __neg__(self: object) -> "NegativeInfinityType":
+        return NegativeInfinity
+
+
+Infinity = InfinityType()
+
+
+class NegativeInfinityType:
+    def __repr__(self) -> str:
+        return "-Infinity"
+
+    def __hash__(self) -> int:
+        return hash(repr(self))
+
+    def __lt__(self, other: object) -> bool:
+        return True
+
+    def __le__(self, other: object) -> bool:
+        return True
+
+    def __eq__(self, other: object) -> bool:
+        return isinstance(other, self.__class__)
+
+    def __gt__(self, other: object) -> bool:
+        return False
+
+    def __ge__(self, other: object) -> bool:
+        return False
+
+    def __neg__(self: object) -> InfinityType:
+        return Infinity
+
+
+NegativeInfinity = NegativeInfinityType()
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/_tokenizer.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/_tokenizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..dd0d648d49a7c1a62d25ce5c9107aa448a8a22d1
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/_tokenizer.py
@@ -0,0 +1,192 @@
+import contextlib
+import re
+from dataclasses import dataclass
+from typing import Dict, Iterator, NoReturn, Optional, Tuple, Union
+
+from .specifiers import Specifier
+
+
+@dataclass
+class Token:
+    name: str
+    text: str
+    position: int
+
+
+class ParserSyntaxError(Exception):
+    """The provided source text could not be parsed correctly."""
+
+    def __init__(
+        self,
+        message: str,
+        *,
+        source: str,
+        span: Tuple[int, int],
+    ) -> None:
+        self.span = span
+        self.message = message
+        self.source = source
+
+        super().__init__()
+
+    def __str__(self) -> str:
+        marker = " " * self.span[0] + "~" * (self.span[1] - self.span[0]) + "^"
+        return "\n    ".join([self.message, self.source, marker])
+
+
+DEFAULT_RULES: "Dict[str, Union[str, re.Pattern[str]]]" = {
+    "LEFT_PARENTHESIS": r"\(",
+    "RIGHT_PARENTHESIS": r"\)",
+    "LEFT_BRACKET": r"\[",
+    "RIGHT_BRACKET": r"\]",
+    "SEMICOLON": r";",
+    "COMMA": r",",
+    "QUOTED_STRING": re.compile(
+        r"""
+            (
+                ('[^']*')
+                |
+                ("[^"]*")
+            )
+        """,
+        re.VERBOSE,
+    ),
+    "OP": r"(===|==|~=|!=|<=|>=|<|>)",
+    "BOOLOP": r"\b(or|and)\b",
+    "IN": r"\bin\b",
+    "NOT": r"\bnot\b",
+    "VARIABLE": re.compile(
+        r"""
+            \b(
+                python_version
+                |python_full_version
+                |os[._]name
+                |sys[._]platform
+                |platform_(release|system)
+                |platform[._](version|machine|python_implementation)
+                |python_implementation
+                |implementation_(name|version)
+                |extra
+            )\b
+        """,
+        re.VERBOSE,
+    ),
+    "SPECIFIER": re.compile(
+        Specifier._operator_regex_str + Specifier._version_regex_str,
+        re.VERBOSE | re.IGNORECASE,
+    ),
+    "AT": r"\@",
+    "URL": r"[^ \t]+",
+    "IDENTIFIER": r"\b[a-zA-Z0-9][a-zA-Z0-9._-]*\b",
+    "VERSION_PREFIX_TRAIL": r"\.\*",
+    "VERSION_LOCAL_LABEL_TRAIL": r"\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*",
+    "WS": r"[ \t]+",
+    "END": r"$",
+}
+
+
+class Tokenizer:
+    """Context-sensitive token parsing.
+
+    Provides methods to examine the input stream to check whether the next token
+    matches.
+    """
+
+    def __init__(
+        self,
+        source: str,
+        *,
+        rules: "Dict[str, Union[str, re.Pattern[str]]]",
+    ) -> None:
+        self.source = source
+        self.rules: Dict[str, re.Pattern[str]] = {
+            name: re.compile(pattern) for name, pattern in rules.items()
+        }
+        self.next_token: Optional[Token] = None
+        self.position = 0
+
+    def consume(self, name: str) -> None:
+        """Move beyond provided token name, if at current position."""
+        if self.check(name):
+            self.read()
+
+    def check(self, name: str, *, peek: bool = False) -> bool:
+        """Check whether the next token has the provided name.
+
+        By default, if the check succeeds, the token *must* be read before
+        another check. If `peek` is set to `True`, the token is not loaded and
+        would need to be checked again.
+        """
+        assert (
+            self.next_token is None
+        ), f"Cannot check for {name!r}, already have {self.next_token!r}"
+        assert name in self.rules, f"Unknown token name: {name!r}"
+
+        expression = self.rules[name]
+
+        match = expression.match(self.source, self.position)
+        if match is None:
+            return False
+        if not peek:
+            self.next_token = Token(name, match[0], self.position)
+        return True
+
+    def expect(self, name: str, *, expected: str) -> Token:
+        """Expect a certain token name next, failing with a syntax error otherwise.
+
+        The token is *not* read.
+        """
+        if not self.check(name):
+            raise self.raise_syntax_error(f"Expected {expected}")
+        return self.read()
+
+    def read(self) -> Token:
+        """Consume the next token and return it."""
+        token = self.next_token
+        assert token is not None
+
+        self.position += len(token.text)
+        self.next_token = None
+
+        return token
+
+    def raise_syntax_error(
+        self,
+        message: str,
+        *,
+        span_start: Optional[int] = None,
+        span_end: Optional[int] = None,
+    ) -> NoReturn:
+        """Raise ParserSyntaxError at the given position."""
+        span = (
+            self.position if span_start is None else span_start,
+            self.position if span_end is None else span_end,
+        )
+        raise ParserSyntaxError(
+            message,
+            source=self.source,
+            span=span,
+        )
+
+    @contextlib.contextmanager
+    def enclosing_tokens(
+        self, open_token: str, close_token: str, *, around: str
+    ) -> Iterator[None]:
+        if self.check(open_token):
+            open_position = self.position
+            self.read()
+        else:
+            open_position = None
+
+        yield
+
+        if open_position is None:
+            return
+
+        if not self.check(close_token):
+            self.raise_syntax_error(
+                f"Expected matching {close_token} for {open_token}, after {around}",
+                span_start=open_position,
+            )
+
+        self.read()
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/markers.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/markers.py
new file mode 100644
index 0000000000000000000000000000000000000000..c96d22a5a445e7353cd2454dec4255d3785c07b3
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/markers.py
@@ -0,0 +1,253 @@
+# This file is dual licensed under the terms of the Apache License, Version
+# 2.0, and the BSD License. See the LICENSE file in the root of this repository
+# for complete details.
+
+import operator
+import os
+import platform
+import sys
+from typing import Any, Callable, Dict, List, Optional, Tuple, Union
+
+from ._parser import (
+    MarkerAtom,
+    MarkerList,
+    Op,
+    Value,
+    Variable,
+)
+from ._parser import (
+    parse_marker as _parse_marker,
+)
+from ._tokenizer import ParserSyntaxError
+from .specifiers import InvalidSpecifier, Specifier
+from .utils import canonicalize_name
+
+__all__ = [
+    "InvalidMarker",
+    "UndefinedComparison",
+    "UndefinedEnvironmentName",
+    "Marker",
+    "default_environment",
+]
+
+Operator = Callable[[str, str], bool]
+
+
+class InvalidMarker(ValueError):
+    """
+    An invalid marker was found, users should refer to PEP 508.
+    """
+
+
+class UndefinedComparison(ValueError):
+    """
+    An invalid operation was attempted on a value that doesn't support it.
+    """
+
+
+class UndefinedEnvironmentName(ValueError):
+    """
+    A name was attempted to be used that does not exist inside of the
+    environment.
+    """
+
+
+def _normalize_extra_values(results: Any) -> Any:
+    """
+    Normalize extra values.
+    """
+    if isinstance(results[0], tuple):
+        lhs, op, rhs = results[0]
+        if isinstance(lhs, Variable) and lhs.value == "extra":
+            normalized_extra = canonicalize_name(rhs.value)
+            rhs = Value(normalized_extra)
+        elif isinstance(rhs, Variable) and rhs.value == "extra":
+            normalized_extra = canonicalize_name(lhs.value)
+            lhs = Value(normalized_extra)
+        results[0] = lhs, op, rhs
+    return results
+
+
+def _format_marker(
+    marker: Union[List[str], MarkerAtom, str], first: Optional[bool] = True
+) -> str:
+    assert isinstance(marker, (list, tuple, str))
+
+    # Sometimes we have a structure like [[...]] which is a single item list
+    # where the single item is itself it's own list. In that case we want skip
+    # the rest of this function so that we don't get extraneous () on the
+    # outside.
+    if (
+        isinstance(marker, list)
+        and len(marker) == 1
+        and isinstance(marker[0], (list, tuple))
+    ):
+        return _format_marker(marker[0])
+
+    if isinstance(marker, list):
+        inner = (_format_marker(m, first=False) for m in marker)
+        if first:
+            return " ".join(inner)
+        else:
+            return "(" + " ".join(inner) + ")"
+    elif isinstance(marker, tuple):
+        return " ".join([m.serialize() for m in marker])
+    else:
+        return marker
+
+
+_operators: Dict[str, Operator] = {
+    "in": lambda lhs, rhs: lhs in rhs,
+    "not in": lambda lhs, rhs: lhs not in rhs,
+    "<": operator.lt,
+    "<=": operator.le,
+    "==": operator.eq,
+    "!=": operator.ne,
+    ">=": operator.ge,
+    ">": operator.gt,
+}
+
+
+def _eval_op(lhs: str, op: Op, rhs: str) -> bool:
+    try:
+        spec = Specifier("".join([op.serialize(), rhs]))
+    except InvalidSpecifier:
+        pass
+    else:
+        return spec.contains(lhs, prereleases=True)
+
+    oper: Optional[Operator] = _operators.get(op.serialize())
+    if oper is None:
+        raise UndefinedComparison(f"Undefined {op!r} on {lhs!r} and {rhs!r}.")
+
+    return oper(lhs, rhs)
+
+
+def _normalize(*values: str, key: str) -> Tuple[str, ...]:
+    # PEP 685 – Comparison of extra names for optional distribution dependencies
+    # https://peps.python.org/pep-0685/
+    # > When comparing extra names, tools MUST normalize the names being
+    # > compared using the semantics outlined in PEP 503 for names
+    if key == "extra":
+        return tuple(canonicalize_name(v) for v in values)
+
+    # other environment markers don't have such standards
+    return values
+
+
+def _evaluate_markers(markers: MarkerList, environment: Dict[str, str]) -> bool:
+    groups: List[List[bool]] = [[]]
+
+    for marker in markers:
+        assert isinstance(marker, (list, tuple, str))
+
+        if isinstance(marker, list):
+            groups[-1].append(_evaluate_markers(marker, environment))
+        elif isinstance(marker, tuple):
+            lhs, op, rhs = marker
+
+            if isinstance(lhs, Variable):
+                environment_key = lhs.value
+                lhs_value = environment[environment_key]
+                rhs_value = rhs.value
+            else:
+                lhs_value = lhs.value
+                environment_key = rhs.value
+                rhs_value = environment[environment_key]
+
+            lhs_value, rhs_value = _normalize(lhs_value, rhs_value, key=environment_key)
+            groups[-1].append(_eval_op(lhs_value, op, rhs_value))
+        else:
+            assert marker in ["and", "or"]
+            if marker == "or":
+                groups.append([])
+
+    return any(all(item) for item in groups)
+
+
+def format_full_version(info: "sys._version_info") -> str:
+    version = "{0.major}.{0.minor}.{0.micro}".format(info)
+    kind = info.releaselevel
+    if kind != "final":
+        version += kind[0] + str(info.serial)
+    return version
+
+
+def default_environment() -> Dict[str, str]:
+    iver = format_full_version(sys.implementation.version)
+    implementation_name = sys.implementation.name
+    return {
+        "implementation_name": implementation_name,
+        "implementation_version": iver,
+        "os_name": os.name,
+        "platform_machine": platform.machine(),
+        "platform_release": platform.release(),
+        "platform_system": platform.system(),
+        "platform_version": platform.version(),
+        "python_full_version": platform.python_version(),
+        "platform_python_implementation": platform.python_implementation(),
+        "python_version": ".".join(platform.python_version_tuple()[:2]),
+        "sys_platform": sys.platform,
+    }
+
+
+class Marker:
+    def __init__(self, marker: str) -> None:
+        # Note: We create a Marker object without calling this constructor in
+        #       packaging.requirements.Requirement. If any additional logic is
+        #       added here, make sure to mirror/adapt Requirement.
+        try:
+            self._markers = _normalize_extra_values(_parse_marker(marker))
+            # The attribute `_markers` can be described in terms of a recursive type:
+            # MarkerList = List[Union[Tuple[Node, ...], str, MarkerList]]
+            #
+            # For example, the following expression:
+            # python_version > "3.6" or (python_version == "3.6" and os_name == "unix")
+            #
+            # is parsed into:
+            # [
+            #     (, ')>, ),
+            #     'and',
+            #     [
+            #         (, , ),
+            #         'or',
+            #         (, , )
+            #     ]
+            # ]
+        except ParserSyntaxError as e:
+            raise InvalidMarker(str(e)) from e
+
+    def __str__(self) -> str:
+        return _format_marker(self._markers)
+
+    def __repr__(self) -> str:
+        return f""
+
+    def __hash__(self) -> int:
+        return hash((self.__class__.__name__, str(self)))
+
+    def __eq__(self, other: Any) -> bool:
+        if not isinstance(other, Marker):
+            return NotImplemented
+
+        return str(self) == str(other)
+
+    def evaluate(self, environment: Optional[Dict[str, str]] = None) -> bool:
+        """Evaluate a marker.
+
+        Return the boolean from evaluating the given marker against the
+        environment. environment is an optional argument to override all or
+        part of the determined environment.
+
+        The environment is determined from the current Python process.
+        """
+        current_environment = default_environment()
+        current_environment["extra"] = ""
+        if environment is not None:
+            current_environment.update(environment)
+            # The API used to allow setting extra to None. We need to handle this
+            # case for backwards compatibility.
+            if current_environment["extra"] is None:
+                current_environment["extra"] = ""
+
+        return _evaluate_markers(self._markers, current_environment)
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/requirements.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/requirements.py
new file mode 100644
index 0000000000000000000000000000000000000000..bdc43a7e98d87dba0c2069bfb4554f71d228cad4
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/requirements.py
@@ -0,0 +1,90 @@
+# This file is dual licensed under the terms of the Apache License, Version
+# 2.0, and the BSD License. See the LICENSE file in the root of this repository
+# for complete details.
+
+from typing import Any, Iterator, Optional, Set
+
+from ._parser import parse_requirement as _parse_requirement
+from ._tokenizer import ParserSyntaxError
+from .markers import Marker, _normalize_extra_values
+from .specifiers import SpecifierSet
+from .utils import canonicalize_name
+
+
+class InvalidRequirement(ValueError):
+    """
+    An invalid requirement was found, users should refer to PEP 508.
+    """
+
+
+class Requirement:
+    """Parse a requirement.
+
+    Parse a given requirement string into its parts, such as name, specifier,
+    URL, and extras. Raises InvalidRequirement on a badly-formed requirement
+    string.
+    """
+
+    # TODO: Can we test whether something is contained within a requirement?
+    #       If so how do we do that? Do we need to test against the _name_ of
+    #       the thing as well as the version? What about the markers?
+    # TODO: Can we normalize the name and extra name?
+
+    def __init__(self, requirement_string: str) -> None:
+        try:
+            parsed = _parse_requirement(requirement_string)
+        except ParserSyntaxError as e:
+            raise InvalidRequirement(str(e)) from e
+
+        self.name: str = parsed.name
+        self.url: Optional[str] = parsed.url or None
+        self.extras: Set[str] = set(parsed.extras or [])
+        self.specifier: SpecifierSet = SpecifierSet(parsed.specifier)
+        self.marker: Optional[Marker] = None
+        if parsed.marker is not None:
+            self.marker = Marker.__new__(Marker)
+            self.marker._markers = _normalize_extra_values(parsed.marker)
+
+    def _iter_parts(self, name: str) -> Iterator[str]:
+        yield name
+
+        if self.extras:
+            formatted_extras = ",".join(sorted(self.extras))
+            yield f"[{formatted_extras}]"
+
+        if self.specifier:
+            yield str(self.specifier)
+
+        if self.url:
+            yield f"@ {self.url}"
+            if self.marker:
+                yield " "
+
+        if self.marker:
+            yield f"; {self.marker}"
+
+    def __str__(self) -> str:
+        return "".join(self._iter_parts(self.name))
+
+    def __repr__(self) -> str:
+        return f""
+
+    def __hash__(self) -> int:
+        return hash(
+            (
+                self.__class__.__name__,
+                *self._iter_parts(canonicalize_name(self.name)),
+            )
+        )
+
+    def __eq__(self, other: Any) -> bool:
+        if not isinstance(other, Requirement):
+            return NotImplemented
+
+        return (
+            canonicalize_name(self.name) == canonicalize_name(other.name)
+            and self.extras == other.extras
+            and self.specifier == other.specifier
+            and self.url == other.url
+            and self.marker == other.marker
+        )
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/specifiers.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/specifiers.py
new file mode 100644
index 0000000000000000000000000000000000000000..6d4066ae2770a3112f37d0e30d9a98fe59c4861f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/specifiers.py
@@ -0,0 +1,1011 @@
+# This file is dual licensed under the terms of the Apache License, Version
+# 2.0, and the BSD License. See the LICENSE file in the root of this repository
+# for complete details.
+"""
+.. testsetup::
+
+    from packaging.specifiers import Specifier, SpecifierSet, InvalidSpecifier
+    from packaging.version import Version
+"""
+
+import abc
+import itertools
+import re
+from typing import Callable, Iterable, Iterator, List, Optional, Tuple, TypeVar, Union
+
+from .utils import canonicalize_version
+from .version import Version
+
+UnparsedVersion = Union[Version, str]
+UnparsedVersionVar = TypeVar("UnparsedVersionVar", bound=UnparsedVersion)
+CallableOperator = Callable[[Version, str], bool]
+
+
+def _coerce_version(version: UnparsedVersion) -> Version:
+    if not isinstance(version, Version):
+        version = Version(version)
+    return version
+
+
+class InvalidSpecifier(ValueError):
+    """
+    Raised when attempting to create a :class:`Specifier` with a specifier
+    string that is invalid.
+
+    >>> Specifier("lolwat")
+    Traceback (most recent call last):
+        ...
+    packaging.specifiers.InvalidSpecifier: Invalid specifier: 'lolwat'
+    """
+
+
+class BaseSpecifier(metaclass=abc.ABCMeta):
+    @abc.abstractmethod
+    def __str__(self) -> str:
+        """
+        Returns the str representation of this Specifier-like object. This
+        should be representative of the Specifier itself.
+        """
+
+    @abc.abstractmethod
+    def __hash__(self) -> int:
+        """
+        Returns a hash value for this Specifier-like object.
+        """
+
+    @abc.abstractmethod
+    def __eq__(self, other: object) -> bool:
+        """
+        Returns a boolean representing whether or not the two Specifier-like
+        objects are equal.
+
+        :param other: The other object to check against.
+        """
+
+    @property
+    @abc.abstractmethod
+    def prereleases(self) -> Optional[bool]:
+        """Whether or not pre-releases as a whole are allowed.
+
+        This can be set to either ``True`` or ``False`` to explicitly enable or disable
+        prereleases or it can be set to ``None`` (the default) to use default semantics.
+        """
+
+    @prereleases.setter
+    def prereleases(self, value: bool) -> None:
+        """Setter for :attr:`prereleases`.
+
+        :param value: The value to set.
+        """
+
+    @abc.abstractmethod
+    def contains(self, item: str, prereleases: Optional[bool] = None) -> bool:
+        """
+        Determines if the given item is contained within this specifier.
+        """
+
+    @abc.abstractmethod
+    def filter(
+        self, iterable: Iterable[UnparsedVersionVar], prereleases: Optional[bool] = None
+    ) -> Iterator[UnparsedVersionVar]:
+        """
+        Takes an iterable of items and filters them so that only items which
+        are contained within this specifier are allowed in it.
+        """
+
+
+class Specifier(BaseSpecifier):
+    """This class abstracts handling of version specifiers.
+
+    .. tip::
+
+        It is generally not required to instantiate this manually. You should instead
+        prefer to work with :class:`SpecifierSet` instead, which can parse
+        comma-separated version specifiers (which is what package metadata contains).
+    """
+
+    _operator_regex_str = r"""
+        (?P(~=|==|!=|<=|>=|<|>|===))
+        """
+    _version_regex_str = r"""
+        (?P
+            (?:
+                # The identity operators allow for an escape hatch that will
+                # do an exact string match of the version you wish to install.
+                # This will not be parsed by PEP 440 and we cannot determine
+                # any semantic meaning from it. This operator is discouraged
+                # but included entirely as an escape hatch.
+                (?<====)  # Only match for the identity operator
+                \s*
+                [^\s;)]*  # The arbitrary version can be just about anything,
+                          # we match everything except for whitespace, a
+                          # semi-colon for marker support, and a closing paren
+                          # since versions can be enclosed in them.
+            )
+            |
+            (?:
+                # The (non)equality operators allow for wild card and local
+                # versions to be specified so we have to define these two
+                # operators separately to enable that.
+                (?<===|!=)            # Only match for equals and not equals
+
+                \s*
+                v?
+                (?:[0-9]+!)?          # epoch
+                [0-9]+(?:\.[0-9]+)*   # release
+
+                # You cannot use a wild card and a pre-release, post-release, a dev or
+                # local version together so group them with a | and make them optional.
+                (?:
+                    \.\*  # Wild card syntax of .*
+                    |
+                    (?:                                  # pre release
+                        [-_\.]?
+                        (alpha|beta|preview|pre|a|b|c|rc)
+                        [-_\.]?
+                        [0-9]*
+                    )?
+                    (?:                                  # post release
+                        (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*)
+                    )?
+                    (?:[-_\.]?dev[-_\.]?[0-9]*)?         # dev release
+                    (?:\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*)? # local
+                )?
+            )
+            |
+            (?:
+                # The compatible operator requires at least two digits in the
+                # release segment.
+                (?<=~=)               # Only match for the compatible operator
+
+                \s*
+                v?
+                (?:[0-9]+!)?          # epoch
+                [0-9]+(?:\.[0-9]+)+   # release  (We have a + instead of a *)
+                (?:                   # pre release
+                    [-_\.]?
+                    (alpha|beta|preview|pre|a|b|c|rc)
+                    [-_\.]?
+                    [0-9]*
+                )?
+                (?:                                   # post release
+                    (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*)
+                )?
+                (?:[-_\.]?dev[-_\.]?[0-9]*)?          # dev release
+            )
+            |
+            (?:
+                # All other operators only allow a sub set of what the
+                # (non)equality operators do. Specifically they do not allow
+                # local versions to be specified nor do they allow the prefix
+                # matching wild cards.
+                (?=": "greater_than_equal",
+        "<": "less_than",
+        ">": "greater_than",
+        "===": "arbitrary",
+    }
+
+    def __init__(self, spec: str = "", prereleases: Optional[bool] = None) -> None:
+        """Initialize a Specifier instance.
+
+        :param spec:
+            The string representation of a specifier which will be parsed and
+            normalized before use.
+        :param prereleases:
+            This tells the specifier if it should accept prerelease versions if
+            applicable or not. The default of ``None`` will autodetect it from the
+            given specifiers.
+        :raises InvalidSpecifier:
+            If the given specifier is invalid (i.e. bad syntax).
+        """
+        match = self._regex.search(spec)
+        if not match:
+            raise InvalidSpecifier(f"Invalid specifier: '{spec}'")
+
+        self._spec: Tuple[str, str] = (
+            match.group("operator").strip(),
+            match.group("version").strip(),
+        )
+
+        # Store whether or not this Specifier should accept prereleases
+        self._prereleases = prereleases
+
+    # https://github.com/python/mypy/pull/13475#pullrequestreview-1079784515
+    @property  # type: ignore[override]
+    def prereleases(self) -> bool:
+        # If there is an explicit prereleases set for this, then we'll just
+        # blindly use that.
+        if self._prereleases is not None:
+            return self._prereleases
+
+        # Look at all of our specifiers and determine if they are inclusive
+        # operators, and if they are if they are including an explicit
+        # prerelease.
+        operator, version = self._spec
+        if operator in ["==", ">=", "<=", "~=", "==="]:
+            # The == specifier can include a trailing .*, if it does we
+            # want to remove before parsing.
+            if operator == "==" and version.endswith(".*"):
+                version = version[:-2]
+
+            # Parse the version, and if it is a pre-release than this
+            # specifier allows pre-releases.
+            if Version(version).is_prerelease:
+                return True
+
+        return False
+
+    @prereleases.setter
+    def prereleases(self, value: bool) -> None:
+        self._prereleases = value
+
+    @property
+    def operator(self) -> str:
+        """The operator of this specifier.
+
+        >>> Specifier("==1.2.3").operator
+        '=='
+        """
+        return self._spec[0]
+
+    @property
+    def version(self) -> str:
+        """The version of this specifier.
+
+        >>> Specifier("==1.2.3").version
+        '1.2.3'
+        """
+        return self._spec[1]
+
+    def __repr__(self) -> str:
+        """A representation of the Specifier that shows all internal state.
+
+        >>> Specifier('>=1.0.0')
+        =1.0.0')>
+        >>> Specifier('>=1.0.0', prereleases=False)
+        =1.0.0', prereleases=False)>
+        >>> Specifier('>=1.0.0', prereleases=True)
+        =1.0.0', prereleases=True)>
+        """
+        pre = (
+            f", prereleases={self.prereleases!r}"
+            if self._prereleases is not None
+            else ""
+        )
+
+        return f"<{self.__class__.__name__}({str(self)!r}{pre})>"
+
+    def __str__(self) -> str:
+        """A string representation of the Specifier that can be round-tripped.
+
+        >>> str(Specifier('>=1.0.0'))
+        '>=1.0.0'
+        >>> str(Specifier('>=1.0.0', prereleases=False))
+        '>=1.0.0'
+        """
+        return "{}{}".format(*self._spec)
+
+    @property
+    def _canonical_spec(self) -> Tuple[str, str]:
+        canonical_version = canonicalize_version(
+            self._spec[1],
+            strip_trailing_zero=(self._spec[0] != "~="),
+        )
+        return self._spec[0], canonical_version
+
+    def __hash__(self) -> int:
+        return hash(self._canonical_spec)
+
+    def __eq__(self, other: object) -> bool:
+        """Whether or not the two Specifier-like objects are equal.
+
+        :param other: The other object to check against.
+
+        The value of :attr:`prereleases` is ignored.
+
+        >>> Specifier("==1.2.3") == Specifier("== 1.2.3.0")
+        True
+        >>> (Specifier("==1.2.3", prereleases=False) ==
+        ...  Specifier("==1.2.3", prereleases=True))
+        True
+        >>> Specifier("==1.2.3") == "==1.2.3"
+        True
+        >>> Specifier("==1.2.3") == Specifier("==1.2.4")
+        False
+        >>> Specifier("==1.2.3") == Specifier("~=1.2.3")
+        False
+        """
+        if isinstance(other, str):
+            try:
+                other = self.__class__(str(other))
+            except InvalidSpecifier:
+                return NotImplemented
+        elif not isinstance(other, self.__class__):
+            return NotImplemented
+
+        return self._canonical_spec == other._canonical_spec
+
+    def _get_operator(self, op: str) -> CallableOperator:
+        operator_callable: CallableOperator = getattr(
+            self, f"_compare_{self._operators[op]}"
+        )
+        return operator_callable
+
+    def _compare_compatible(self, prospective: Version, spec: str) -> bool:
+        # Compatible releases have an equivalent combination of >= and ==. That
+        # is that ~=2.2 is equivalent to >=2.2,==2.*. This allows us to
+        # implement this in terms of the other specifiers instead of
+        # implementing it ourselves. The only thing we need to do is construct
+        # the other specifiers.
+
+        # We want everything but the last item in the version, but we want to
+        # ignore suffix segments.
+        prefix = _version_join(
+            list(itertools.takewhile(_is_not_suffix, _version_split(spec)))[:-1]
+        )
+
+        # Add the prefix notation to the end of our string
+        prefix += ".*"
+
+        return self._get_operator(">=")(prospective, spec) and self._get_operator("==")(
+            prospective, prefix
+        )
+
+    def _compare_equal(self, prospective: Version, spec: str) -> bool:
+        # We need special logic to handle prefix matching
+        if spec.endswith(".*"):
+            # In the case of prefix matching we want to ignore local segment.
+            normalized_prospective = canonicalize_version(
+                prospective.public, strip_trailing_zero=False
+            )
+            # Get the normalized version string ignoring the trailing .*
+            normalized_spec = canonicalize_version(spec[:-2], strip_trailing_zero=False)
+            # Split the spec out by bangs and dots, and pretend that there is
+            # an implicit dot in between a release segment and a pre-release segment.
+            split_spec = _version_split(normalized_spec)
+
+            # Split the prospective version out by bangs and dots, and pretend
+            # that there is an implicit dot in between a release segment and
+            # a pre-release segment.
+            split_prospective = _version_split(normalized_prospective)
+
+            # 0-pad the prospective version before shortening it to get the correct
+            # shortened version.
+            padded_prospective, _ = _pad_version(split_prospective, split_spec)
+
+            # Shorten the prospective version to be the same length as the spec
+            # so that we can determine if the specifier is a prefix of the
+            # prospective version or not.
+            shortened_prospective = padded_prospective[: len(split_spec)]
+
+            return shortened_prospective == split_spec
+        else:
+            # Convert our spec string into a Version
+            spec_version = Version(spec)
+
+            # If the specifier does not have a local segment, then we want to
+            # act as if the prospective version also does not have a local
+            # segment.
+            if not spec_version.local:
+                prospective = Version(prospective.public)
+
+            return prospective == spec_version
+
+    def _compare_not_equal(self, prospective: Version, spec: str) -> bool:
+        return not self._compare_equal(prospective, spec)
+
+    def _compare_less_than_equal(self, prospective: Version, spec: str) -> bool:
+        # NB: Local version identifiers are NOT permitted in the version
+        # specifier, so local version labels can be universally removed from
+        # the prospective version.
+        return Version(prospective.public) <= Version(spec)
+
+    def _compare_greater_than_equal(self, prospective: Version, spec: str) -> bool:
+        # NB: Local version identifiers are NOT permitted in the version
+        # specifier, so local version labels can be universally removed from
+        # the prospective version.
+        return Version(prospective.public) >= Version(spec)
+
+    def _compare_less_than(self, prospective: Version, spec_str: str) -> bool:
+        # Convert our spec to a Version instance, since we'll want to work with
+        # it as a version.
+        spec = Version(spec_str)
+
+        # Check to see if the prospective version is less than the spec
+        # version. If it's not we can short circuit and just return False now
+        # instead of doing extra unneeded work.
+        if not prospective < spec:
+            return False
+
+        # This special case is here so that, unless the specifier itself
+        # includes is a pre-release version, that we do not accept pre-release
+        # versions for the version mentioned in the specifier (e.g. <3.1 should
+        # not match 3.1.dev0, but should match 3.0.dev0).
+        if not spec.is_prerelease and prospective.is_prerelease:
+            if Version(prospective.base_version) == Version(spec.base_version):
+                return False
+
+        # If we've gotten to here, it means that prospective version is both
+        # less than the spec version *and* it's not a pre-release of the same
+        # version in the spec.
+        return True
+
+    def _compare_greater_than(self, prospective: Version, spec_str: str) -> bool:
+        # Convert our spec to a Version instance, since we'll want to work with
+        # it as a version.
+        spec = Version(spec_str)
+
+        # Check to see if the prospective version is greater than the spec
+        # version. If it's not we can short circuit and just return False now
+        # instead of doing extra unneeded work.
+        if not prospective > spec:
+            return False
+
+        # This special case is here so that, unless the specifier itself
+        # includes is a post-release version, that we do not accept
+        # post-release versions for the version mentioned in the specifier
+        # (e.g. >3.1 should not match 3.0.post0, but should match 3.2.post0).
+        if not spec.is_postrelease and prospective.is_postrelease:
+            if Version(prospective.base_version) == Version(spec.base_version):
+                return False
+
+        # Ensure that we do not allow a local version of the version mentioned
+        # in the specifier, which is technically greater than, to match.
+        if prospective.local is not None:
+            if Version(prospective.base_version) == Version(spec.base_version):
+                return False
+
+        # If we've gotten to here, it means that prospective version is both
+        # greater than the spec version *and* it's not a pre-release of the
+        # same version in the spec.
+        return True
+
+    def _compare_arbitrary(self, prospective: Version, spec: str) -> bool:
+        return str(prospective).lower() == str(spec).lower()
+
+    def __contains__(self, item: Union[str, Version]) -> bool:
+        """Return whether or not the item is contained in this specifier.
+
+        :param item: The item to check for.
+
+        This is used for the ``in`` operator and behaves the same as
+        :meth:`contains` with no ``prereleases`` argument passed.
+
+        >>> "1.2.3" in Specifier(">=1.2.3")
+        True
+        >>> Version("1.2.3") in Specifier(">=1.2.3")
+        True
+        >>> "1.0.0" in Specifier(">=1.2.3")
+        False
+        >>> "1.3.0a1" in Specifier(">=1.2.3")
+        False
+        >>> "1.3.0a1" in Specifier(">=1.2.3", prereleases=True)
+        True
+        """
+        return self.contains(item)
+
+    def contains(
+        self, item: UnparsedVersion, prereleases: Optional[bool] = None
+    ) -> bool:
+        """Return whether or not the item is contained in this specifier.
+
+        :param item:
+            The item to check for, which can be a version string or a
+            :class:`Version` instance.
+        :param prereleases:
+            Whether or not to match prereleases with this Specifier. If set to
+            ``None`` (the default), it uses :attr:`prereleases` to determine
+            whether or not prereleases are allowed.
+
+        >>> Specifier(">=1.2.3").contains("1.2.3")
+        True
+        >>> Specifier(">=1.2.3").contains(Version("1.2.3"))
+        True
+        >>> Specifier(">=1.2.3").contains("1.0.0")
+        False
+        >>> Specifier(">=1.2.3").contains("1.3.0a1")
+        False
+        >>> Specifier(">=1.2.3", prereleases=True).contains("1.3.0a1")
+        True
+        >>> Specifier(">=1.2.3").contains("1.3.0a1", prereleases=True)
+        True
+        """
+
+        # Determine if prereleases are to be allowed or not.
+        if prereleases is None:
+            prereleases = self.prereleases
+
+        # Normalize item to a Version, this allows us to have a shortcut for
+        # "2.0" in Specifier(">=2")
+        normalized_item = _coerce_version(item)
+
+        # Determine if we should be supporting prereleases in this specifier
+        # or not, if we do not support prereleases than we can short circuit
+        # logic if this version is a prereleases.
+        if normalized_item.is_prerelease and not prereleases:
+            return False
+
+        # Actually do the comparison to determine if this item is contained
+        # within this Specifier or not.
+        operator_callable: CallableOperator = self._get_operator(self.operator)
+        return operator_callable(normalized_item, self.version)
+
+    def filter(
+        self, iterable: Iterable[UnparsedVersionVar], prereleases: Optional[bool] = None
+    ) -> Iterator[UnparsedVersionVar]:
+        """Filter items in the given iterable, that match the specifier.
+
+        :param iterable:
+            An iterable that can contain version strings and :class:`Version` instances.
+            The items in the iterable will be filtered according to the specifier.
+        :param prereleases:
+            Whether or not to allow prereleases in the returned iterator. If set to
+            ``None`` (the default), it will be intelligently decide whether to allow
+            prereleases or not (based on the :attr:`prereleases` attribute, and
+            whether the only versions matching are prereleases).
+
+        This method is smarter than just ``filter(Specifier().contains, [...])``
+        because it implements the rule from :pep:`440` that a prerelease item
+        SHOULD be accepted if no other versions match the given specifier.
+
+        >>> list(Specifier(">=1.2.3").filter(["1.2", "1.3", "1.5a1"]))
+        ['1.3']
+        >>> list(Specifier(">=1.2.3").filter(["1.2", "1.2.3", "1.3", Version("1.4")]))
+        ['1.2.3', '1.3', ]
+        >>> list(Specifier(">=1.2.3").filter(["1.2", "1.5a1"]))
+        ['1.5a1']
+        >>> list(Specifier(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True))
+        ['1.3', '1.5a1']
+        >>> list(Specifier(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"]))
+        ['1.3', '1.5a1']
+        """
+
+        yielded = False
+        found_prereleases = []
+
+        kw = {"prereleases": prereleases if prereleases is not None else True}
+
+        # Attempt to iterate over all the values in the iterable and if any of
+        # them match, yield them.
+        for version in iterable:
+            parsed_version = _coerce_version(version)
+
+            if self.contains(parsed_version, **kw):
+                # If our version is a prerelease, and we were not set to allow
+                # prereleases, then we'll store it for later in case nothing
+                # else matches this specifier.
+                if parsed_version.is_prerelease and not (
+                    prereleases or self.prereleases
+                ):
+                    found_prereleases.append(version)
+                # Either this is not a prerelease, or we should have been
+                # accepting prereleases from the beginning.
+                else:
+                    yielded = True
+                    yield version
+
+        # Now that we've iterated over everything, determine if we've yielded
+        # any values, and if we have not and we have any prereleases stored up
+        # then we will go ahead and yield the prereleases.
+        if not yielded and found_prereleases:
+            for version in found_prereleases:
+                yield version
+
+
+_prefix_regex = re.compile(r"^([0-9]+)((?:a|b|c|rc)[0-9]+)$")
+
+
+def _version_split(version: str) -> List[str]:
+    """Split version into components.
+
+    The split components are intended for version comparison. The logic does
+    not attempt to retain the original version string, so joining the
+    components back with :func:`_version_join` may not produce the original
+    version string.
+    """
+    result: List[str] = []
+
+    epoch, _, rest = version.rpartition("!")
+    result.append(epoch or "0")
+
+    for item in rest.split("."):
+        match = _prefix_regex.search(item)
+        if match:
+            result.extend(match.groups())
+        else:
+            result.append(item)
+    return result
+
+
+def _version_join(components: List[str]) -> str:
+    """Join split version components into a version string.
+
+    This function assumes the input came from :func:`_version_split`, where the
+    first component must be the epoch (either empty or numeric), and all other
+    components numeric.
+    """
+    epoch, *rest = components
+    return f"{epoch}!{'.'.join(rest)}"
+
+
+def _is_not_suffix(segment: str) -> bool:
+    return not any(
+        segment.startswith(prefix) for prefix in ("dev", "a", "b", "rc", "post")
+    )
+
+
+def _pad_version(left: List[str], right: List[str]) -> Tuple[List[str], List[str]]:
+    left_split, right_split = [], []
+
+    # Get the release segment of our versions
+    left_split.append(list(itertools.takewhile(lambda x: x.isdigit(), left)))
+    right_split.append(list(itertools.takewhile(lambda x: x.isdigit(), right)))
+
+    # Get the rest of our versions
+    left_split.append(left[len(left_split[0]) :])
+    right_split.append(right[len(right_split[0]) :])
+
+    # Insert our padding
+    left_split.insert(1, ["0"] * max(0, len(right_split[0]) - len(left_split[0])))
+    right_split.insert(1, ["0"] * max(0, len(left_split[0]) - len(right_split[0])))
+
+    return (
+        list(itertools.chain.from_iterable(left_split)),
+        list(itertools.chain.from_iterable(right_split)),
+    )
+
+
+class SpecifierSet(BaseSpecifier):
+    """This class abstracts handling of a set of version specifiers.
+
+    It can be passed a single specifier (``>=3.0``), a comma-separated list of
+    specifiers (``>=3.0,!=3.1``), or no specifier at all.
+    """
+
+    def __init__(
+        self, specifiers: str = "", prereleases: Optional[bool] = None
+    ) -> None:
+        """Initialize a SpecifierSet instance.
+
+        :param specifiers:
+            The string representation of a specifier or a comma-separated list of
+            specifiers which will be parsed and normalized before use.
+        :param prereleases:
+            This tells the SpecifierSet if it should accept prerelease versions if
+            applicable or not. The default of ``None`` will autodetect it from the
+            given specifiers.
+
+        :raises InvalidSpecifier:
+            If the given ``specifiers`` are not parseable than this exception will be
+            raised.
+        """
+
+        # Split on `,` to break each individual specifier into it's own item, and
+        # strip each item to remove leading/trailing whitespace.
+        split_specifiers = [s.strip() for s in specifiers.split(",") if s.strip()]
+
+        # Make each individual specifier a Specifier and save in a frozen set for later.
+        self._specs = frozenset(map(Specifier, split_specifiers))
+
+        # Store our prereleases value so we can use it later to determine if
+        # we accept prereleases or not.
+        self._prereleases = prereleases
+
+    @property
+    def prereleases(self) -> Optional[bool]:
+        # If we have been given an explicit prerelease modifier, then we'll
+        # pass that through here.
+        if self._prereleases is not None:
+            return self._prereleases
+
+        # If we don't have any specifiers, and we don't have a forced value,
+        # then we'll just return None since we don't know if this should have
+        # pre-releases or not.
+        if not self._specs:
+            return None
+
+        # Otherwise we'll see if any of the given specifiers accept
+        # prereleases, if any of them do we'll return True, otherwise False.
+        return any(s.prereleases for s in self._specs)
+
+    @prereleases.setter
+    def prereleases(self, value: bool) -> None:
+        self._prereleases = value
+
+    def __repr__(self) -> str:
+        """A representation of the specifier set that shows all internal state.
+
+        Note that the ordering of the individual specifiers within the set may not
+        match the input string.
+
+        >>> SpecifierSet('>=1.0.0,!=2.0.0')
+        =1.0.0')>
+        >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=False)
+        =1.0.0', prereleases=False)>
+        >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=True)
+        =1.0.0', prereleases=True)>
+        """
+        pre = (
+            f", prereleases={self.prereleases!r}"
+            if self._prereleases is not None
+            else ""
+        )
+
+        return f""
+
+    def __str__(self) -> str:
+        """A string representation of the specifier set that can be round-tripped.
+
+        Note that the ordering of the individual specifiers within the set may not
+        match the input string.
+
+        >>> str(SpecifierSet(">=1.0.0,!=1.0.1"))
+        '!=1.0.1,>=1.0.0'
+        >>> str(SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False))
+        '!=1.0.1,>=1.0.0'
+        """
+        return ",".join(sorted(str(s) for s in self._specs))
+
+    def __hash__(self) -> int:
+        return hash(self._specs)
+
+    def __and__(self, other: Union["SpecifierSet", str]) -> "SpecifierSet":
+        """Return a SpecifierSet which is a combination of the two sets.
+
+        :param other: The other object to combine with.
+
+        >>> SpecifierSet(">=1.0.0,!=1.0.1") & '<=2.0.0,!=2.0.1'
+        =1.0.0')>
+        >>> SpecifierSet(">=1.0.0,!=1.0.1") & SpecifierSet('<=2.0.0,!=2.0.1')
+        =1.0.0')>
+        """
+        if isinstance(other, str):
+            other = SpecifierSet(other)
+        elif not isinstance(other, SpecifierSet):
+            return NotImplemented
+
+        specifier = SpecifierSet()
+        specifier._specs = frozenset(self._specs | other._specs)
+
+        if self._prereleases is None and other._prereleases is not None:
+            specifier._prereleases = other._prereleases
+        elif self._prereleases is not None and other._prereleases is None:
+            specifier._prereleases = self._prereleases
+        elif self._prereleases == other._prereleases:
+            specifier._prereleases = self._prereleases
+        else:
+            raise ValueError(
+                "Cannot combine SpecifierSets with True and False prerelease "
+                "overrides."
+            )
+
+        return specifier
+
+    def __eq__(self, other: object) -> bool:
+        """Whether or not the two SpecifierSet-like objects are equal.
+
+        :param other: The other object to check against.
+
+        The value of :attr:`prereleases` is ignored.
+
+        >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.1")
+        True
+        >>> (SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False) ==
+        ...  SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True))
+        True
+        >>> SpecifierSet(">=1.0.0,!=1.0.1") == ">=1.0.0,!=1.0.1"
+        True
+        >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0")
+        False
+        >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.2")
+        False
+        """
+        if isinstance(other, (str, Specifier)):
+            other = SpecifierSet(str(other))
+        elif not isinstance(other, SpecifierSet):
+            return NotImplemented
+
+        return self._specs == other._specs
+
+    def __len__(self) -> int:
+        """Returns the number of specifiers in this specifier set."""
+        return len(self._specs)
+
+    def __iter__(self) -> Iterator[Specifier]:
+        """
+        Returns an iterator over all the underlying :class:`Specifier` instances
+        in this specifier set.
+
+        >>> sorted(SpecifierSet(">=1.0.0,!=1.0.1"), key=str)
+        [, =1.0.0')>]
+        """
+        return iter(self._specs)
+
+    def __contains__(self, item: UnparsedVersion) -> bool:
+        """Return whether or not the item is contained in this specifier.
+
+        :param item: The item to check for.
+
+        This is used for the ``in`` operator and behaves the same as
+        :meth:`contains` with no ``prereleases`` argument passed.
+
+        >>> "1.2.3" in SpecifierSet(">=1.0.0,!=1.0.1")
+        True
+        >>> Version("1.2.3") in SpecifierSet(">=1.0.0,!=1.0.1")
+        True
+        >>> "1.0.1" in SpecifierSet(">=1.0.0,!=1.0.1")
+        False
+        >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1")
+        False
+        >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True)
+        True
+        """
+        return self.contains(item)
+
+    def contains(
+        self,
+        item: UnparsedVersion,
+        prereleases: Optional[bool] = None,
+        installed: Optional[bool] = None,
+    ) -> bool:
+        """Return whether or not the item is contained in this SpecifierSet.
+
+        :param item:
+            The item to check for, which can be a version string or a
+            :class:`Version` instance.
+        :param prereleases:
+            Whether or not to match prereleases with this SpecifierSet. If set to
+            ``None`` (the default), it uses :attr:`prereleases` to determine
+            whether or not prereleases are allowed.
+
+        >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.2.3")
+        True
+        >>> SpecifierSet(">=1.0.0,!=1.0.1").contains(Version("1.2.3"))
+        True
+        >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.0.1")
+        False
+        >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1")
+        False
+        >>> SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True).contains("1.3.0a1")
+        True
+        >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1", prereleases=True)
+        True
+        """
+        # Ensure that our item is a Version instance.
+        if not isinstance(item, Version):
+            item = Version(item)
+
+        # Determine if we're forcing a prerelease or not, if we're not forcing
+        # one for this particular filter call, then we'll use whatever the
+        # SpecifierSet thinks for whether or not we should support prereleases.
+        if prereleases is None:
+            prereleases = self.prereleases
+
+        # We can determine if we're going to allow pre-releases by looking to
+        # see if any of the underlying items supports them. If none of them do
+        # and this item is a pre-release then we do not allow it and we can
+        # short circuit that here.
+        # Note: This means that 1.0.dev1 would not be contained in something
+        #       like >=1.0.devabc however it would be in >=1.0.debabc,>0.0.dev0
+        if not prereleases and item.is_prerelease:
+            return False
+
+        if installed and item.is_prerelease:
+            item = Version(item.base_version)
+
+        # We simply dispatch to the underlying specs here to make sure that the
+        # given version is contained within all of them.
+        # Note: This use of all() here means that an empty set of specifiers
+        #       will always return True, this is an explicit design decision.
+        return all(s.contains(item, prereleases=prereleases) for s in self._specs)
+
+    def filter(
+        self, iterable: Iterable[UnparsedVersionVar], prereleases: Optional[bool] = None
+    ) -> Iterator[UnparsedVersionVar]:
+        """Filter items in the given iterable, that match the specifiers in this set.
+
+        :param iterable:
+            An iterable that can contain version strings and :class:`Version` instances.
+            The items in the iterable will be filtered according to the specifier.
+        :param prereleases:
+            Whether or not to allow prereleases in the returned iterator. If set to
+            ``None`` (the default), it will be intelligently decide whether to allow
+            prereleases or not (based on the :attr:`prereleases` attribute, and
+            whether the only versions matching are prereleases).
+
+        This method is smarter than just ``filter(SpecifierSet(...).contains, [...])``
+        because it implements the rule from :pep:`440` that a prerelease item
+        SHOULD be accepted if no other versions match the given specifier.
+
+        >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", "1.5a1"]))
+        ['1.3']
+        >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", Version("1.4")]))
+        ['1.3', ]
+        >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.5a1"]))
+        []
+        >>> list(SpecifierSet(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True))
+        ['1.3', '1.5a1']
+        >>> list(SpecifierSet(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"]))
+        ['1.3', '1.5a1']
+
+        An "empty" SpecifierSet will filter items based on the presence of prerelease
+        versions in the set.
+
+        >>> list(SpecifierSet("").filter(["1.3", "1.5a1"]))
+        ['1.3']
+        >>> list(SpecifierSet("").filter(["1.5a1"]))
+        ['1.5a1']
+        >>> list(SpecifierSet("", prereleases=True).filter(["1.3", "1.5a1"]))
+        ['1.3', '1.5a1']
+        >>> list(SpecifierSet("").filter(["1.3", "1.5a1"], prereleases=True))
+        ['1.3', '1.5a1']
+        """
+        # Determine if we're forcing a prerelease or not, if we're not forcing
+        # one for this particular filter call, then we'll use whatever the
+        # SpecifierSet thinks for whether or not we should support prereleases.
+        if prereleases is None:
+            prereleases = self.prereleases
+
+        # If we have any specifiers, then we want to wrap our iterable in the
+        # filter method for each one, this will act as a logical AND amongst
+        # each specifier.
+        if self._specs:
+            for spec in self._specs:
+                iterable = spec.filter(iterable, prereleases=bool(prereleases))
+            return iter(iterable)
+        # If we do not have any specifiers, then we need to have a rough filter
+        # which will filter out any pre-releases, unless there are no final
+        # releases.
+        else:
+            filtered: List[UnparsedVersionVar] = []
+            found_prereleases: List[UnparsedVersionVar] = []
+
+            for item in iterable:
+                parsed_version = _coerce_version(item)
+
+                # Store any item which is a pre-release for later unless we've
+                # already found a final version or we are accepting prereleases
+                if parsed_version.is_prerelease and not prereleases:
+                    if not filtered:
+                        found_prereleases.append(item)
+                else:
+                    filtered.append(item)
+
+            # If we've found no items except for pre-releases, then we'll go
+            # ahead and use the pre-releases
+            if not filtered and found_prereleases and prereleases is None:
+                return iter(found_prereleases)
+
+            return iter(filtered)
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/tags.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/tags.py
new file mode 100644
index 0000000000000000000000000000000000000000..89f1926137dd2d2a6bd63616bf5b9f722fc8d584
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/tags.py
@@ -0,0 +1,571 @@
+# This file is dual licensed under the terms of the Apache License, Version
+# 2.0, and the BSD License. See the LICENSE file in the root of this repository
+# for complete details.
+
+import logging
+import platform
+import re
+import struct
+import subprocess
+import sys
+import sysconfig
+from importlib.machinery import EXTENSION_SUFFIXES
+from typing import (
+    Dict,
+    FrozenSet,
+    Iterable,
+    Iterator,
+    List,
+    Optional,
+    Sequence,
+    Tuple,
+    Union,
+    cast,
+)
+
+from . import _manylinux, _musllinux
+
+logger = logging.getLogger(__name__)
+
+PythonVersion = Sequence[int]
+MacVersion = Tuple[int, int]
+
+INTERPRETER_SHORT_NAMES: Dict[str, str] = {
+    "python": "py",  # Generic.
+    "cpython": "cp",
+    "pypy": "pp",
+    "ironpython": "ip",
+    "jython": "jy",
+}
+
+
+_32_BIT_INTERPRETER = struct.calcsize("P") == 4
+
+
+class Tag:
+    """
+    A representation of the tag triple for a wheel.
+
+    Instances are considered immutable and thus are hashable. Equality checking
+    is also supported.
+    """
+
+    __slots__ = ["_interpreter", "_abi", "_platform", "_hash"]
+
+    def __init__(self, interpreter: str, abi: str, platform: str) -> None:
+        self._interpreter = interpreter.lower()
+        self._abi = abi.lower()
+        self._platform = platform.lower()
+        # The __hash__ of every single element in a Set[Tag] will be evaluated each time
+        # that a set calls its `.disjoint()` method, which may be called hundreds of
+        # times when scanning a page of links for packages with tags matching that
+        # Set[Tag]. Pre-computing the value here produces significant speedups for
+        # downstream consumers.
+        self._hash = hash((self._interpreter, self._abi, self._platform))
+
+    @property
+    def interpreter(self) -> str:
+        return self._interpreter
+
+    @property
+    def abi(self) -> str:
+        return self._abi
+
+    @property
+    def platform(self) -> str:
+        return self._platform
+
+    def __eq__(self, other: object) -> bool:
+        if not isinstance(other, Tag):
+            return NotImplemented
+
+        return (
+            (self._hash == other._hash)  # Short-circuit ASAP for perf reasons.
+            and (self._platform == other._platform)
+            and (self._abi == other._abi)
+            and (self._interpreter == other._interpreter)
+        )
+
+    def __hash__(self) -> int:
+        return self._hash
+
+    def __str__(self) -> str:
+        return f"{self._interpreter}-{self._abi}-{self._platform}"
+
+    def __repr__(self) -> str:
+        return f"<{self} @ {id(self)}>"
+
+
+def parse_tag(tag: str) -> FrozenSet[Tag]:
+    """
+    Parses the provided tag (e.g. `py3-none-any`) into a frozenset of Tag instances.
+
+    Returning a set is required due to the possibility that the tag is a
+    compressed tag set.
+    """
+    tags = set()
+    interpreters, abis, platforms = tag.split("-")
+    for interpreter in interpreters.split("."):
+        for abi in abis.split("."):
+            for platform_ in platforms.split("."):
+                tags.add(Tag(interpreter, abi, platform_))
+    return frozenset(tags)
+
+
+def _get_config_var(name: str, warn: bool = False) -> Union[int, str, None]:
+    value: Union[int, str, None] = sysconfig.get_config_var(name)
+    if value is None and warn:
+        logger.debug(
+            "Config variable '%s' is unset, Python ABI tag may be incorrect", name
+        )
+    return value
+
+
+def _normalize_string(string: str) -> str:
+    return string.replace(".", "_").replace("-", "_").replace(" ", "_")
+
+
+def _is_threaded_cpython(abis: List[str]) -> bool:
+    """
+    Determine if the ABI corresponds to a threaded (`--disable-gil`) build.
+
+    The threaded builds are indicated by a "t" in the abiflags.
+    """
+    if len(abis) == 0:
+        return False
+    # expect e.g., cp313
+    m = re.match(r"cp\d+(.*)", abis[0])
+    if not m:
+        return False
+    abiflags = m.group(1)
+    return "t" in abiflags
+
+
+def _abi3_applies(python_version: PythonVersion, threading: bool) -> bool:
+    """
+    Determine if the Python version supports abi3.
+
+    PEP 384 was first implemented in Python 3.2. The threaded (`--disable-gil`)
+    builds do not support abi3.
+    """
+    return len(python_version) > 1 and tuple(python_version) >= (3, 2) and not threading
+
+
+def _cpython_abis(py_version: PythonVersion, warn: bool = False) -> List[str]:
+    py_version = tuple(py_version)  # To allow for version comparison.
+    abis = []
+    version = _version_nodot(py_version[:2])
+    threading = debug = pymalloc = ucs4 = ""
+    with_debug = _get_config_var("Py_DEBUG", warn)
+    has_refcount = hasattr(sys, "gettotalrefcount")
+    # Windows doesn't set Py_DEBUG, so checking for support of debug-compiled
+    # extension modules is the best option.
+    # https://github.com/pypa/pip/issues/3383#issuecomment-173267692
+    has_ext = "_d.pyd" in EXTENSION_SUFFIXES
+    if with_debug or (with_debug is None and (has_refcount or has_ext)):
+        debug = "d"
+    if py_version >= (3, 13) and _get_config_var("Py_GIL_DISABLED", warn):
+        threading = "t"
+    if py_version < (3, 8):
+        with_pymalloc = _get_config_var("WITH_PYMALLOC", warn)
+        if with_pymalloc or with_pymalloc is None:
+            pymalloc = "m"
+        if py_version < (3, 3):
+            unicode_size = _get_config_var("Py_UNICODE_SIZE", warn)
+            if unicode_size == 4 or (
+                unicode_size is None and sys.maxunicode == 0x10FFFF
+            ):
+                ucs4 = "u"
+    elif debug:
+        # Debug builds can also load "normal" extension modules.
+        # We can also assume no UCS-4 or pymalloc requirement.
+        abis.append(f"cp{version}{threading}")
+    abis.insert(0, f"cp{version}{threading}{debug}{pymalloc}{ucs4}")
+    return abis
+
+
+def cpython_tags(
+    python_version: Optional[PythonVersion] = None,
+    abis: Optional[Iterable[str]] = None,
+    platforms: Optional[Iterable[str]] = None,
+    *,
+    warn: bool = False,
+) -> Iterator[Tag]:
+    """
+    Yields the tags for a CPython interpreter.
+
+    The tags consist of:
+    - cp--
+    - cp-abi3-
+    - cp-none-
+    - cp-abi3-  # Older Python versions down to 3.2.
+
+    If python_version only specifies a major version then user-provided ABIs and
+    the 'none' ABItag will be used.
+
+    If 'abi3' or 'none' are specified in 'abis' then they will be yielded at
+    their normal position and not at the beginning.
+    """
+    if not python_version:
+        python_version = sys.version_info[:2]
+
+    interpreter = f"cp{_version_nodot(python_version[:2])}"
+
+    if abis is None:
+        if len(python_version) > 1:
+            abis = _cpython_abis(python_version, warn)
+        else:
+            abis = []
+    abis = list(abis)
+    # 'abi3' and 'none' are explicitly handled later.
+    for explicit_abi in ("abi3", "none"):
+        try:
+            abis.remove(explicit_abi)
+        except ValueError:
+            pass
+
+    platforms = list(platforms or platform_tags())
+    for abi in abis:
+        for platform_ in platforms:
+            yield Tag(interpreter, abi, platform_)
+
+    threading = _is_threaded_cpython(abis)
+    use_abi3 = _abi3_applies(python_version, threading)
+    if use_abi3:
+        yield from (Tag(interpreter, "abi3", platform_) for platform_ in platforms)
+    yield from (Tag(interpreter, "none", platform_) for platform_ in platforms)
+
+    if use_abi3:
+        for minor_version in range(python_version[1] - 1, 1, -1):
+            for platform_ in platforms:
+                interpreter = "cp{version}".format(
+                    version=_version_nodot((python_version[0], minor_version))
+                )
+                yield Tag(interpreter, "abi3", platform_)
+
+
+def _generic_abi() -> List[str]:
+    """
+    Return the ABI tag based on EXT_SUFFIX.
+    """
+    # The following are examples of `EXT_SUFFIX`.
+    # We want to keep the parts which are related to the ABI and remove the
+    # parts which are related to the platform:
+    # - linux:   '.cpython-310-x86_64-linux-gnu.so' => cp310
+    # - mac:     '.cpython-310-darwin.so'           => cp310
+    # - win:     '.cp310-win_amd64.pyd'             => cp310
+    # - win:     '.pyd'                             => cp37 (uses _cpython_abis())
+    # - pypy:    '.pypy38-pp73-x86_64-linux-gnu.so' => pypy38_pp73
+    # - graalpy: '.graalpy-38-native-x86_64-darwin.dylib'
+    #                                               => graalpy_38_native
+
+    ext_suffix = _get_config_var("EXT_SUFFIX", warn=True)
+    if not isinstance(ext_suffix, str) or ext_suffix[0] != ".":
+        raise SystemError("invalid sysconfig.get_config_var('EXT_SUFFIX')")
+    parts = ext_suffix.split(".")
+    if len(parts) < 3:
+        # CPython3.7 and earlier uses ".pyd" on Windows.
+        return _cpython_abis(sys.version_info[:2])
+    soabi = parts[1]
+    if soabi.startswith("cpython"):
+        # non-windows
+        abi = "cp" + soabi.split("-")[1]
+    elif soabi.startswith("cp"):
+        # windows
+        abi = soabi.split("-")[0]
+    elif soabi.startswith("pypy"):
+        abi = "-".join(soabi.split("-")[:2])
+    elif soabi.startswith("graalpy"):
+        abi = "-".join(soabi.split("-")[:3])
+    elif soabi:
+        # pyston, ironpython, others?
+        abi = soabi
+    else:
+        return []
+    return [_normalize_string(abi)]
+
+
+def generic_tags(
+    interpreter: Optional[str] = None,
+    abis: Optional[Iterable[str]] = None,
+    platforms: Optional[Iterable[str]] = None,
+    *,
+    warn: bool = False,
+) -> Iterator[Tag]:
+    """
+    Yields the tags for a generic interpreter.
+
+    The tags consist of:
+    - --
+
+    The "none" ABI will be added if it was not explicitly provided.
+    """
+    if not interpreter:
+        interp_name = interpreter_name()
+        interp_version = interpreter_version(warn=warn)
+        interpreter = "".join([interp_name, interp_version])
+    if abis is None:
+        abis = _generic_abi()
+    else:
+        abis = list(abis)
+    platforms = list(platforms or platform_tags())
+    if "none" not in abis:
+        abis.append("none")
+    for abi in abis:
+        for platform_ in platforms:
+            yield Tag(interpreter, abi, platform_)
+
+
+def _py_interpreter_range(py_version: PythonVersion) -> Iterator[str]:
+    """
+    Yields Python versions in descending order.
+
+    After the latest version, the major-only version will be yielded, and then
+    all previous versions of that major version.
+    """
+    if len(py_version) > 1:
+        yield f"py{_version_nodot(py_version[:2])}"
+    yield f"py{py_version[0]}"
+    if len(py_version) > 1:
+        for minor in range(py_version[1] - 1, -1, -1):
+            yield f"py{_version_nodot((py_version[0], minor))}"
+
+
+def compatible_tags(
+    python_version: Optional[PythonVersion] = None,
+    interpreter: Optional[str] = None,
+    platforms: Optional[Iterable[str]] = None,
+) -> Iterator[Tag]:
+    """
+    Yields the sequence of tags that are compatible with a specific version of Python.
+
+    The tags consist of:
+    - py*-none-
+    - -none-any  # ... if `interpreter` is provided.
+    - py*-none-any
+    """
+    if not python_version:
+        python_version = sys.version_info[:2]
+    platforms = list(platforms or platform_tags())
+    for version in _py_interpreter_range(python_version):
+        for platform_ in platforms:
+            yield Tag(version, "none", platform_)
+    if interpreter:
+        yield Tag(interpreter, "none", "any")
+    for version in _py_interpreter_range(python_version):
+        yield Tag(version, "none", "any")
+
+
+def _mac_arch(arch: str, is_32bit: bool = _32_BIT_INTERPRETER) -> str:
+    if not is_32bit:
+        return arch
+
+    if arch.startswith("ppc"):
+        return "ppc"
+
+    return "i386"
+
+
+def _mac_binary_formats(version: MacVersion, cpu_arch: str) -> List[str]:
+    formats = [cpu_arch]
+    if cpu_arch == "x86_64":
+        if version < (10, 4):
+            return []
+        formats.extend(["intel", "fat64", "fat32"])
+
+    elif cpu_arch == "i386":
+        if version < (10, 4):
+            return []
+        formats.extend(["intel", "fat32", "fat"])
+
+    elif cpu_arch == "ppc64":
+        # TODO: Need to care about 32-bit PPC for ppc64 through 10.2?
+        if version > (10, 5) or version < (10, 4):
+            return []
+        formats.append("fat64")
+
+    elif cpu_arch == "ppc":
+        if version > (10, 6):
+            return []
+        formats.extend(["fat32", "fat"])
+
+    if cpu_arch in {"arm64", "x86_64"}:
+        formats.append("universal2")
+
+    if cpu_arch in {"x86_64", "i386", "ppc64", "ppc", "intel"}:
+        formats.append("universal")
+
+    return formats
+
+
+def mac_platforms(
+    version: Optional[MacVersion] = None, arch: Optional[str] = None
+) -> Iterator[str]:
+    """
+    Yields the platform tags for a macOS system.
+
+    The `version` parameter is a two-item tuple specifying the macOS version to
+    generate platform tags for. The `arch` parameter is the CPU architecture to
+    generate platform tags for. Both parameters default to the appropriate value
+    for the current system.
+    """
+    version_str, _, cpu_arch = platform.mac_ver()
+    if version is None:
+        version = cast("MacVersion", tuple(map(int, version_str.split(".")[:2])))
+        if version == (10, 16):
+            # When built against an older macOS SDK, Python will report macOS 10.16
+            # instead of the real version.
+            version_str = subprocess.run(
+                [
+                    sys.executable,
+                    "-sS",
+                    "-c",
+                    "import platform; print(platform.mac_ver()[0])",
+                ],
+                check=True,
+                env={"SYSTEM_VERSION_COMPAT": "0"},
+                stdout=subprocess.PIPE,
+                text=True,
+            ).stdout
+            version = cast("MacVersion", tuple(map(int, version_str.split(".")[:2])))
+    else:
+        version = version
+    if arch is None:
+        arch = _mac_arch(cpu_arch)
+    else:
+        arch = arch
+
+    if (10, 0) <= version and version < (11, 0):
+        # Prior to Mac OS 11, each yearly release of Mac OS bumped the
+        # "minor" version number.  The major version was always 10.
+        for minor_version in range(version[1], -1, -1):
+            compat_version = 10, minor_version
+            binary_formats = _mac_binary_formats(compat_version, arch)
+            for binary_format in binary_formats:
+                yield "macosx_{major}_{minor}_{binary_format}".format(
+                    major=10, minor=minor_version, binary_format=binary_format
+                )
+
+    if version >= (11, 0):
+        # Starting with Mac OS 11, each yearly release bumps the major version
+        # number.   The minor versions are now the midyear updates.
+        for major_version in range(version[0], 10, -1):
+            compat_version = major_version, 0
+            binary_formats = _mac_binary_formats(compat_version, arch)
+            for binary_format in binary_formats:
+                yield "macosx_{major}_{minor}_{binary_format}".format(
+                    major=major_version, minor=0, binary_format=binary_format
+                )
+
+    if version >= (11, 0):
+        # Mac OS 11 on x86_64 is compatible with binaries from previous releases.
+        # Arm64 support was introduced in 11.0, so no Arm binaries from previous
+        # releases exist.
+        #
+        # However, the "universal2" binary format can have a
+        # macOS version earlier than 11.0 when the x86_64 part of the binary supports
+        # that version of macOS.
+        if arch == "x86_64":
+            for minor_version in range(16, 3, -1):
+                compat_version = 10, minor_version
+                binary_formats = _mac_binary_formats(compat_version, arch)
+                for binary_format in binary_formats:
+                    yield "macosx_{major}_{minor}_{binary_format}".format(
+                        major=compat_version[0],
+                        minor=compat_version[1],
+                        binary_format=binary_format,
+                    )
+        else:
+            for minor_version in range(16, 3, -1):
+                compat_version = 10, minor_version
+                binary_format = "universal2"
+                yield "macosx_{major}_{minor}_{binary_format}".format(
+                    major=compat_version[0],
+                    minor=compat_version[1],
+                    binary_format=binary_format,
+                )
+
+
+def _linux_platforms(is_32bit: bool = _32_BIT_INTERPRETER) -> Iterator[str]:
+    linux = _normalize_string(sysconfig.get_platform())
+    if not linux.startswith("linux_"):
+        # we should never be here, just yield the sysconfig one and return
+        yield linux
+        return
+    if is_32bit:
+        if linux == "linux_x86_64":
+            linux = "linux_i686"
+        elif linux == "linux_aarch64":
+            linux = "linux_armv8l"
+    _, arch = linux.split("_", 1)
+    archs = {"armv8l": ["armv8l", "armv7l"]}.get(arch, [arch])
+    yield from _manylinux.platform_tags(archs)
+    yield from _musllinux.platform_tags(archs)
+    for arch in archs:
+        yield f"linux_{arch}"
+
+
+def _generic_platforms() -> Iterator[str]:
+    yield _normalize_string(sysconfig.get_platform())
+
+
+def platform_tags() -> Iterator[str]:
+    """
+    Provides the platform tags for this installation.
+    """
+    if platform.system() == "Darwin":
+        return mac_platforms()
+    elif platform.system() == "Linux":
+        return _linux_platforms()
+    else:
+        return _generic_platforms()
+
+
+def interpreter_name() -> str:
+    """
+    Returns the name of the running interpreter.
+
+    Some implementations have a reserved, two-letter abbreviation which will
+    be returned when appropriate.
+    """
+    name = sys.implementation.name
+    return INTERPRETER_SHORT_NAMES.get(name) or name
+
+
+def interpreter_version(*, warn: bool = False) -> str:
+    """
+    Returns the version of the running interpreter.
+    """
+    version = _get_config_var("py_version_nodot", warn=warn)
+    if version:
+        version = str(version)
+    else:
+        version = _version_nodot(sys.version_info[:2])
+    return version
+
+
+def _version_nodot(version: PythonVersion) -> str:
+    return "".join(map(str, version))
+
+
+def sys_tags(*, warn: bool = False) -> Iterator[Tag]:
+    """
+    Returns the sequence of tag triples for the running interpreter.
+
+    The order of the sequence corresponds to priority order for the
+    interpreter, from most to least important.
+    """
+
+    interp_name = interpreter_name()
+    if interp_name == "cp":
+        yield from cpython_tags(warn=warn)
+    else:
+        yield from generic_tags()
+
+    if interp_name == "pp":
+        interp = "pp3"
+    elif interp_name == "cp":
+        interp = "cp" + interpreter_version(warn=warn)
+    else:
+        interp = None
+    yield from compatible_tags(interpreter=interp)
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/utils.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..c2c2f75aa806282d322c76c2117c0f0fdfb09d25
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/utils.py
@@ -0,0 +1,172 @@
+# This file is dual licensed under the terms of the Apache License, Version
+# 2.0, and the BSD License. See the LICENSE file in the root of this repository
+# for complete details.
+
+import re
+from typing import FrozenSet, NewType, Tuple, Union, cast
+
+from .tags import Tag, parse_tag
+from .version import InvalidVersion, Version
+
+BuildTag = Union[Tuple[()], Tuple[int, str]]
+NormalizedName = NewType("NormalizedName", str)
+
+
+class InvalidName(ValueError):
+    """
+    An invalid distribution name; users should refer to the packaging user guide.
+    """
+
+
+class InvalidWheelFilename(ValueError):
+    """
+    An invalid wheel filename was found, users should refer to PEP 427.
+    """
+
+
+class InvalidSdistFilename(ValueError):
+    """
+    An invalid sdist filename was found, users should refer to the packaging user guide.
+    """
+
+
+# Core metadata spec for `Name`
+_validate_regex = re.compile(
+    r"^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$", re.IGNORECASE
+)
+_canonicalize_regex = re.compile(r"[-_.]+")
+_normalized_regex = re.compile(r"^([a-z0-9]|[a-z0-9]([a-z0-9-](?!--))*[a-z0-9])$")
+# PEP 427: The build number must start with a digit.
+_build_tag_regex = re.compile(r"(\d+)(.*)")
+
+
+def canonicalize_name(name: str, *, validate: bool = False) -> NormalizedName:
+    if validate and not _validate_regex.match(name):
+        raise InvalidName(f"name is invalid: {name!r}")
+    # This is taken from PEP 503.
+    value = _canonicalize_regex.sub("-", name).lower()
+    return cast(NormalizedName, value)
+
+
+def is_normalized_name(name: str) -> bool:
+    return _normalized_regex.match(name) is not None
+
+
+def canonicalize_version(
+    version: Union[Version, str], *, strip_trailing_zero: bool = True
+) -> str:
+    """
+    This is very similar to Version.__str__, but has one subtle difference
+    with the way it handles the release segment.
+    """
+    if isinstance(version, str):
+        try:
+            parsed = Version(version)
+        except InvalidVersion:
+            # Legacy versions cannot be normalized
+            return version
+    else:
+        parsed = version
+
+    parts = []
+
+    # Epoch
+    if parsed.epoch != 0:
+        parts.append(f"{parsed.epoch}!")
+
+    # Release segment
+    release_segment = ".".join(str(x) for x in parsed.release)
+    if strip_trailing_zero:
+        # NB: This strips trailing '.0's to normalize
+        release_segment = re.sub(r"(\.0)+$", "", release_segment)
+    parts.append(release_segment)
+
+    # Pre-release
+    if parsed.pre is not None:
+        parts.append("".join(str(x) for x in parsed.pre))
+
+    # Post-release
+    if parsed.post is not None:
+        parts.append(f".post{parsed.post}")
+
+    # Development release
+    if parsed.dev is not None:
+        parts.append(f".dev{parsed.dev}")
+
+    # Local version segment
+    if parsed.local is not None:
+        parts.append(f"+{parsed.local}")
+
+    return "".join(parts)
+
+
+def parse_wheel_filename(
+    filename: str,
+) -> Tuple[NormalizedName, Version, BuildTag, FrozenSet[Tag]]:
+    if not filename.endswith(".whl"):
+        raise InvalidWheelFilename(
+            f"Invalid wheel filename (extension must be '.whl'): {filename}"
+        )
+
+    filename = filename[:-4]
+    dashes = filename.count("-")
+    if dashes not in (4, 5):
+        raise InvalidWheelFilename(
+            f"Invalid wheel filename (wrong number of parts): {filename}"
+        )
+
+    parts = filename.split("-", dashes - 2)
+    name_part = parts[0]
+    # See PEP 427 for the rules on escaping the project name.
+    if "__" in name_part or re.match(r"^[\w\d._]*$", name_part, re.UNICODE) is None:
+        raise InvalidWheelFilename(f"Invalid project name: {filename}")
+    name = canonicalize_name(name_part)
+
+    try:
+        version = Version(parts[1])
+    except InvalidVersion as e:
+        raise InvalidWheelFilename(
+            f"Invalid wheel filename (invalid version): {filename}"
+        ) from e
+
+    if dashes == 5:
+        build_part = parts[2]
+        build_match = _build_tag_regex.match(build_part)
+        if build_match is None:
+            raise InvalidWheelFilename(
+                f"Invalid build number: {build_part} in '{filename}'"
+            )
+        build = cast(BuildTag, (int(build_match.group(1)), build_match.group(2)))
+    else:
+        build = ()
+    tags = parse_tag(parts[-1])
+    return (name, version, build, tags)
+
+
+def parse_sdist_filename(filename: str) -> Tuple[NormalizedName, Version]:
+    if filename.endswith(".tar.gz"):
+        file_stem = filename[: -len(".tar.gz")]
+    elif filename.endswith(".zip"):
+        file_stem = filename[: -len(".zip")]
+    else:
+        raise InvalidSdistFilename(
+            f"Invalid sdist filename (extension must be '.tar.gz' or '.zip'):"
+            f" {filename}"
+        )
+
+    # We are requiring a PEP 440 version, which cannot contain dashes,
+    # so we split on the last dash.
+    name_part, sep, version_part = file_stem.rpartition("-")
+    if not sep:
+        raise InvalidSdistFilename(f"Invalid sdist filename: {filename}")
+
+    name = canonicalize_name(name_part)
+
+    try:
+        version = Version(version_part)
+    except InvalidVersion as e:
+        raise InvalidSdistFilename(
+            f"Invalid sdist filename (invalid version): {filename}"
+        ) from e
+
+    return (name, version)
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/version.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/version.py
new file mode 100644
index 0000000000000000000000000000000000000000..cda8e99935c8d92010b84437ae83d75031245d61
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/packaging/version.py
@@ -0,0 +1,561 @@
+# This file is dual licensed under the terms of the Apache License, Version
+# 2.0, and the BSD License. See the LICENSE file in the root of this repository
+# for complete details.
+"""
+.. testsetup::
+
+    from packaging.version import parse, Version
+"""
+
+import itertools
+import re
+from typing import Any, Callable, NamedTuple, Optional, SupportsInt, Tuple, Union
+
+from ._structures import Infinity, InfinityType, NegativeInfinity, NegativeInfinityType
+
+__all__ = ["VERSION_PATTERN", "parse", "Version", "InvalidVersion"]
+
+LocalType = Tuple[Union[int, str], ...]
+
+CmpPrePostDevType = Union[InfinityType, NegativeInfinityType, Tuple[str, int]]
+CmpLocalType = Union[
+    NegativeInfinityType,
+    Tuple[Union[Tuple[int, str], Tuple[NegativeInfinityType, Union[int, str]]], ...],
+]
+CmpKey = Tuple[
+    int,
+    Tuple[int, ...],
+    CmpPrePostDevType,
+    CmpPrePostDevType,
+    CmpPrePostDevType,
+    CmpLocalType,
+]
+VersionComparisonMethod = Callable[[CmpKey, CmpKey], bool]
+
+
+class _Version(NamedTuple):
+    epoch: int
+    release: Tuple[int, ...]
+    dev: Optional[Tuple[str, int]]
+    pre: Optional[Tuple[str, int]]
+    post: Optional[Tuple[str, int]]
+    local: Optional[LocalType]
+
+
+def parse(version: str) -> "Version":
+    """Parse the given version string.
+
+    >>> parse('1.0.dev1')
+    
+
+    :param version: The version string to parse.
+    :raises InvalidVersion: When the version string is not a valid version.
+    """
+    return Version(version)
+
+
+class InvalidVersion(ValueError):
+    """Raised when a version string is not a valid version.
+
+    >>> Version("invalid")
+    Traceback (most recent call last):
+        ...
+    packaging.version.InvalidVersion: Invalid version: 'invalid'
+    """
+
+
+class _BaseVersion:
+    _key: Tuple[Any, ...]
+
+    def __hash__(self) -> int:
+        return hash(self._key)
+
+    # Please keep the duplicated `isinstance` check
+    # in the six comparisons hereunder
+    # unless you find a way to avoid adding overhead function calls.
+    def __lt__(self, other: "_BaseVersion") -> bool:
+        if not isinstance(other, _BaseVersion):
+            return NotImplemented
+
+        return self._key < other._key
+
+    def __le__(self, other: "_BaseVersion") -> bool:
+        if not isinstance(other, _BaseVersion):
+            return NotImplemented
+
+        return self._key <= other._key
+
+    def __eq__(self, other: object) -> bool:
+        if not isinstance(other, _BaseVersion):
+            return NotImplemented
+
+        return self._key == other._key
+
+    def __ge__(self, other: "_BaseVersion") -> bool:
+        if not isinstance(other, _BaseVersion):
+            return NotImplemented
+
+        return self._key >= other._key
+
+    def __gt__(self, other: "_BaseVersion") -> bool:
+        if not isinstance(other, _BaseVersion):
+            return NotImplemented
+
+        return self._key > other._key
+
+    def __ne__(self, other: object) -> bool:
+        if not isinstance(other, _BaseVersion):
+            return NotImplemented
+
+        return self._key != other._key
+
+
+# Deliberately not anchored to the start and end of the string, to make it
+# easier for 3rd party code to reuse
+_VERSION_PATTERN = r"""
+    v?
+    (?:
+        (?:(?P[0-9]+)!)?                           # epoch
+        (?P[0-9]+(?:\.[0-9]+)*)                  # release segment
+        (?P
                                          # pre-release
+            [-_\.]?
+            (?Palpha|a|beta|b|preview|pre|c|rc)
+            [-_\.]?
+            (?P[0-9]+)?
+        )?
+        (?P                                         # post release
+            (?:-(?P[0-9]+))
+            |
+            (?:
+                [-_\.]?
+                (?Ppost|rev|r)
+                [-_\.]?
+                (?P[0-9]+)?
+            )
+        )?
+        (?P                                          # dev release
+            [-_\.]?
+            (?Pdev)
+            [-_\.]?
+            (?P[0-9]+)?
+        )?
+    )
+    (?:\+(?P[a-z0-9]+(?:[-_\.][a-z0-9]+)*))?       # local version
+"""
+
+VERSION_PATTERN = _VERSION_PATTERN
+"""
+A string containing the regular expression used to match a valid version.
+
+The pattern is not anchored at either end, and is intended for embedding in larger
+expressions (for example, matching a version number as part of a file name). The
+regular expression should be compiled with the ``re.VERBOSE`` and ``re.IGNORECASE``
+flags set.
+
+:meta hide-value:
+"""
+
+
+class Version(_BaseVersion):
+    """This class abstracts handling of a project's versions.
+
+    A :class:`Version` instance is comparison aware and can be compared and
+    sorted using the standard Python interfaces.
+
+    >>> v1 = Version("1.0a5")
+    >>> v2 = Version("1.0")
+    >>> v1
+    
+    >>> v2
+    
+    >>> v1 < v2
+    True
+    >>> v1 == v2
+    False
+    >>> v1 > v2
+    False
+    >>> v1 >= v2
+    False
+    >>> v1 <= v2
+    True
+    """
+
+    _regex = re.compile(r"^\s*" + VERSION_PATTERN + r"\s*$", re.VERBOSE | re.IGNORECASE)
+    _key: CmpKey
+
+    def __init__(self, version: str) -> None:
+        """Initialize a Version object.
+
+        :param version:
+            The string representation of a version which will be parsed and normalized
+            before use.
+        :raises InvalidVersion:
+            If the ``version`` does not conform to PEP 440 in any way then this
+            exception will be raised.
+        """
+
+        # Validate the version and parse it into pieces
+        match = self._regex.search(version)
+        if not match:
+            raise InvalidVersion(f"Invalid version: '{version}'")
+
+        # Store the parsed out pieces of the version
+        self._version = _Version(
+            epoch=int(match.group("epoch")) if match.group("epoch") else 0,
+            release=tuple(int(i) for i in match.group("release").split(".")),
+            pre=_parse_letter_version(match.group("pre_l"), match.group("pre_n")),
+            post=_parse_letter_version(
+                match.group("post_l"), match.group("post_n1") or match.group("post_n2")
+            ),
+            dev=_parse_letter_version(match.group("dev_l"), match.group("dev_n")),
+            local=_parse_local_version(match.group("local")),
+        )
+
+        # Generate a key which will be used for sorting
+        self._key = _cmpkey(
+            self._version.epoch,
+            self._version.release,
+            self._version.pre,
+            self._version.post,
+            self._version.dev,
+            self._version.local,
+        )
+
+    def __repr__(self) -> str:
+        """A representation of the Version that shows all internal state.
+
+        >>> Version('1.0.0')
+        
+        """
+        return f""
+
+    def __str__(self) -> str:
+        """A string representation of the version that can be rounded-tripped.
+
+        >>> str(Version("1.0a5"))
+        '1.0a5'
+        """
+        parts = []
+
+        # Epoch
+        if self.epoch != 0:
+            parts.append(f"{self.epoch}!")
+
+        # Release segment
+        parts.append(".".join(str(x) for x in self.release))
+
+        # Pre-release
+        if self.pre is not None:
+            parts.append("".join(str(x) for x in self.pre))
+
+        # Post-release
+        if self.post is not None:
+            parts.append(f".post{self.post}")
+
+        # Development release
+        if self.dev is not None:
+            parts.append(f".dev{self.dev}")
+
+        # Local version segment
+        if self.local is not None:
+            parts.append(f"+{self.local}")
+
+        return "".join(parts)
+
+    @property
+    def epoch(self) -> int:
+        """The epoch of the version.
+
+        >>> Version("2.0.0").epoch
+        0
+        >>> Version("1!2.0.0").epoch
+        1
+        """
+        return self._version.epoch
+
+    @property
+    def release(self) -> Tuple[int, ...]:
+        """The components of the "release" segment of the version.
+
+        >>> Version("1.2.3").release
+        (1, 2, 3)
+        >>> Version("2.0.0").release
+        (2, 0, 0)
+        >>> Version("1!2.0.0.post0").release
+        (2, 0, 0)
+
+        Includes trailing zeroes but not the epoch or any pre-release / development /
+        post-release suffixes.
+        """
+        return self._version.release
+
+    @property
+    def pre(self) -> Optional[Tuple[str, int]]:
+        """The pre-release segment of the version.
+
+        >>> print(Version("1.2.3").pre)
+        None
+        >>> Version("1.2.3a1").pre
+        ('a', 1)
+        >>> Version("1.2.3b1").pre
+        ('b', 1)
+        >>> Version("1.2.3rc1").pre
+        ('rc', 1)
+        """
+        return self._version.pre
+
+    @property
+    def post(self) -> Optional[int]:
+        """The post-release number of the version.
+
+        >>> print(Version("1.2.3").post)
+        None
+        >>> Version("1.2.3.post1").post
+        1
+        """
+        return self._version.post[1] if self._version.post else None
+
+    @property
+    def dev(self) -> Optional[int]:
+        """The development number of the version.
+
+        >>> print(Version("1.2.3").dev)
+        None
+        >>> Version("1.2.3.dev1").dev
+        1
+        """
+        return self._version.dev[1] if self._version.dev else None
+
+    @property
+    def local(self) -> Optional[str]:
+        """The local version segment of the version.
+
+        >>> print(Version("1.2.3").local)
+        None
+        >>> Version("1.2.3+abc").local
+        'abc'
+        """
+        if self._version.local:
+            return ".".join(str(x) for x in self._version.local)
+        else:
+            return None
+
+    @property
+    def public(self) -> str:
+        """The public portion of the version.
+
+        >>> Version("1.2.3").public
+        '1.2.3'
+        >>> Version("1.2.3+abc").public
+        '1.2.3'
+        >>> Version("1.2.3+abc.dev1").public
+        '1.2.3'
+        """
+        return str(self).split("+", 1)[0]
+
+    @property
+    def base_version(self) -> str:
+        """The "base version" of the version.
+
+        >>> Version("1.2.3").base_version
+        '1.2.3'
+        >>> Version("1.2.3+abc").base_version
+        '1.2.3'
+        >>> Version("1!1.2.3+abc.dev1").base_version
+        '1!1.2.3'
+
+        The "base version" is the public version of the project without any pre or post
+        release markers.
+        """
+        parts = []
+
+        # Epoch
+        if self.epoch != 0:
+            parts.append(f"{self.epoch}!")
+
+        # Release segment
+        parts.append(".".join(str(x) for x in self.release))
+
+        return "".join(parts)
+
+    @property
+    def is_prerelease(self) -> bool:
+        """Whether this version is a pre-release.
+
+        >>> Version("1.2.3").is_prerelease
+        False
+        >>> Version("1.2.3a1").is_prerelease
+        True
+        >>> Version("1.2.3b1").is_prerelease
+        True
+        >>> Version("1.2.3rc1").is_prerelease
+        True
+        >>> Version("1.2.3dev1").is_prerelease
+        True
+        """
+        return self.dev is not None or self.pre is not None
+
+    @property
+    def is_postrelease(self) -> bool:
+        """Whether this version is a post-release.
+
+        >>> Version("1.2.3").is_postrelease
+        False
+        >>> Version("1.2.3.post1").is_postrelease
+        True
+        """
+        return self.post is not None
+
+    @property
+    def is_devrelease(self) -> bool:
+        """Whether this version is a development release.
+
+        >>> Version("1.2.3").is_devrelease
+        False
+        >>> Version("1.2.3.dev1").is_devrelease
+        True
+        """
+        return self.dev is not None
+
+    @property
+    def major(self) -> int:
+        """The first item of :attr:`release` or ``0`` if unavailable.
+
+        >>> Version("1.2.3").major
+        1
+        """
+        return self.release[0] if len(self.release) >= 1 else 0
+
+    @property
+    def minor(self) -> int:
+        """The second item of :attr:`release` or ``0`` if unavailable.
+
+        >>> Version("1.2.3").minor
+        2
+        >>> Version("1").minor
+        0
+        """
+        return self.release[1] if len(self.release) >= 2 else 0
+
+    @property
+    def micro(self) -> int:
+        """The third item of :attr:`release` or ``0`` if unavailable.
+
+        >>> Version("1.2.3").micro
+        3
+        >>> Version("1").micro
+        0
+        """
+        return self.release[2] if len(self.release) >= 3 else 0
+
+
+def _parse_letter_version(
+    letter: Optional[str], number: Union[str, bytes, SupportsInt, None]
+) -> Optional[Tuple[str, int]]:
+    if letter:
+        # We consider there to be an implicit 0 in a pre-release if there is
+        # not a numeral associated with it.
+        if number is None:
+            number = 0
+
+        # We normalize any letters to their lower case form
+        letter = letter.lower()
+
+        # We consider some words to be alternate spellings of other words and
+        # in those cases we want to normalize the spellings to our preferred
+        # spelling.
+        if letter == "alpha":
+            letter = "a"
+        elif letter == "beta":
+            letter = "b"
+        elif letter in ["c", "pre", "preview"]:
+            letter = "rc"
+        elif letter in ["rev", "r"]:
+            letter = "post"
+
+        return letter, int(number)
+    if not letter and number:
+        # We assume if we are given a number, but we are not given a letter
+        # then this is using the implicit post release syntax (e.g. 1.0-1)
+        letter = "post"
+
+        return letter, int(number)
+
+    return None
+
+
+_local_version_separators = re.compile(r"[\._-]")
+
+
+def _parse_local_version(local: Optional[str]) -> Optional[LocalType]:
+    """
+    Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
+    """
+    if local is not None:
+        return tuple(
+            part.lower() if not part.isdigit() else int(part)
+            for part in _local_version_separators.split(local)
+        )
+    return None
+
+
+def _cmpkey(
+    epoch: int,
+    release: Tuple[int, ...],
+    pre: Optional[Tuple[str, int]],
+    post: Optional[Tuple[str, int]],
+    dev: Optional[Tuple[str, int]],
+    local: Optional[LocalType],
+) -> CmpKey:
+    # When we compare a release version, we want to compare it with all of the
+    # trailing zeros removed. So we'll use a reverse the list, drop all the now
+    # leading zeros until we come to something non zero, then take the rest
+    # re-reverse it back into the correct order and make it a tuple and use
+    # that for our sorting key.
+    _release = tuple(
+        reversed(list(itertools.dropwhile(lambda x: x == 0, reversed(release))))
+    )
+
+    # We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
+    # We'll do this by abusing the pre segment, but we _only_ want to do this
+    # if there is not a pre or a post segment. If we have one of those then
+    # the normal sorting rules will handle this case correctly.
+    if pre is None and post is None and dev is not None:
+        _pre: CmpPrePostDevType = NegativeInfinity
+    # Versions without a pre-release (except as noted above) should sort after
+    # those with one.
+    elif pre is None:
+        _pre = Infinity
+    else:
+        _pre = pre
+
+    # Versions without a post segment should sort before those with one.
+    if post is None:
+        _post: CmpPrePostDevType = NegativeInfinity
+
+    else:
+        _post = post
+
+    # Versions without a development segment should sort after those with one.
+    if dev is None:
+        _dev: CmpPrePostDevType = Infinity
+
+    else:
+        _dev = dev
+
+    if local is None:
+        # Versions without a local segment should sort before those with one.
+        _local: CmpLocalType = NegativeInfinity
+    else:
+        # Versions with a local segment need that segment parsed to implement
+        # the sorting rules in PEP440.
+        # - Alpha numeric segments sort before numeric segments
+        # - Alpha numeric segments sort lexicographically
+        # - Numeric segments sort numerically
+        # - Shorter versions sort before longer versions when the prefixes
+        #   match exactly
+        _local = tuple(
+            (i, "") if isinstance(i, int) else (NegativeInfinity, i) for i in local
+        )
+
+    return epoch, _release, _pre, _post, _dev, _local
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/vendor.txt b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/vendor.txt
new file mode 100644
index 0000000000000000000000000000000000000000..14666103a82ea7fced3d8cffb8a9b2a9e03fb492
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/vendored/vendor.txt
@@ -0,0 +1 @@
+packaging==24.0
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/wheelfile.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/wheelfile.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a0f4596c566420135991713ee75ca29c4cff3ed
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/wheel/wheelfile.py
@@ -0,0 +1,227 @@
+from __future__ import annotations
+
+import csv
+import hashlib
+import os.path
+import re
+import stat
+import time
+from io import StringIO, TextIOWrapper
+from typing import IO, TYPE_CHECKING, Literal
+from zipfile import ZIP_DEFLATED, ZipFile, ZipInfo
+
+from wheel.cli import WheelError
+from wheel.util import log, urlsafe_b64decode, urlsafe_b64encode
+
+if TYPE_CHECKING:
+    from typing import Protocol, Sized, Union
+
+    from typing_extensions import Buffer
+
+    StrPath = Union[str, os.PathLike[str]]
+
+    class SizedBuffer(Sized, Buffer, Protocol): ...
+
+
+# Non-greedy matching of an optional build number may be too clever (more
+# invalid wheel filenames will match). Separate regex for .dist-info?
+WHEEL_INFO_RE = re.compile(
+    r"""^(?P(?P[^\s-]+?)-(?P[^\s-]+?))(-(?P\d[^\s-]*))?
+     -(?P[^\s-]+?)-(?P[^\s-]+?)-(?P\S+)\.whl$""",
+    re.VERBOSE,
+)
+MINIMUM_TIMESTAMP = 315532800  # 1980-01-01 00:00:00 UTC
+
+
+def get_zipinfo_datetime(timestamp: float | None = None):
+    # Some applications need reproducible .whl files, but they can't do this without
+    # forcing the timestamp of the individual ZipInfo objects. See issue #143.
+    timestamp = int(os.environ.get("SOURCE_DATE_EPOCH", timestamp or time.time()))
+    timestamp = max(timestamp, MINIMUM_TIMESTAMP)
+    return time.gmtime(timestamp)[0:6]
+
+
+class WheelFile(ZipFile):
+    """A ZipFile derivative class that also reads SHA-256 hashes from
+    .dist-info/RECORD and checks any read files against those.
+    """
+
+    _default_algorithm = hashlib.sha256
+
+    def __init__(
+        self,
+        file: StrPath,
+        mode: Literal["r", "w", "x", "a"] = "r",
+        compression: int = ZIP_DEFLATED,
+    ):
+        basename = os.path.basename(file)
+        self.parsed_filename = WHEEL_INFO_RE.match(basename)
+        if not basename.endswith(".whl") or self.parsed_filename is None:
+            raise WheelError(f"Bad wheel filename {basename!r}")
+
+        ZipFile.__init__(self, file, mode, compression=compression, allowZip64=True)
+
+        self.dist_info_path = "{}.dist-info".format(
+            self.parsed_filename.group("namever")
+        )
+        self.record_path = self.dist_info_path + "/RECORD"
+        self._file_hashes: dict[str, tuple[None, None] | tuple[int, bytes]] = {}
+        self._file_sizes = {}
+        if mode == "r":
+            # Ignore RECORD and any embedded wheel signatures
+            self._file_hashes[self.record_path] = None, None
+            self._file_hashes[self.record_path + ".jws"] = None, None
+            self._file_hashes[self.record_path + ".p7s"] = None, None
+
+            # Fill in the expected hashes by reading them from RECORD
+            try:
+                record = self.open(self.record_path)
+            except KeyError:
+                raise WheelError(f"Missing {self.record_path} file") from None
+
+            with record:
+                for line in csv.reader(
+                    TextIOWrapper(record, newline="", encoding="utf-8")
+                ):
+                    path, hash_sum, size = line
+                    if not hash_sum:
+                        continue
+
+                    algorithm, hash_sum = hash_sum.split("=")
+                    try:
+                        hashlib.new(algorithm)
+                    except ValueError:
+                        raise WheelError(
+                            f"Unsupported hash algorithm: {algorithm}"
+                        ) from None
+
+                    if algorithm.lower() in {"md5", "sha1"}:
+                        raise WheelError(
+                            f"Weak hash algorithm ({algorithm}) is not permitted by "
+                            f"PEP 427"
+                        )
+
+                    self._file_hashes[path] = (
+                        algorithm,
+                        urlsafe_b64decode(hash_sum.encode("ascii")),
+                    )
+
+    def open(
+        self,
+        name_or_info: str | ZipInfo,
+        mode: Literal["r", "w"] = "r",
+        pwd: bytes | None = None,
+    ) -> IO[bytes]:
+        def _update_crc(newdata: bytes) -> None:
+            eof = ef._eof
+            update_crc_orig(newdata)
+            running_hash.update(newdata)
+            if eof and running_hash.digest() != expected_hash:
+                raise WheelError(f"Hash mismatch for file '{ef_name}'")
+
+        ef_name = (
+            name_or_info.filename if isinstance(name_or_info, ZipInfo) else name_or_info
+        )
+        if (
+            mode == "r"
+            and not ef_name.endswith("/")
+            and ef_name not in self._file_hashes
+        ):
+            raise WheelError(f"No hash found for file '{ef_name}'")
+
+        ef = ZipFile.open(self, name_or_info, mode, pwd)
+        if mode == "r" and not ef_name.endswith("/"):
+            algorithm, expected_hash = self._file_hashes[ef_name]
+            if expected_hash is not None:
+                # Monkey patch the _update_crc method to also check for the hash from
+                # RECORD
+                running_hash = hashlib.new(algorithm)
+                update_crc_orig, ef._update_crc = ef._update_crc, _update_crc
+
+        return ef
+
+    def write_files(self, base_dir: str):
+        log.info(f"creating '{self.filename}' and adding '{base_dir}' to it")
+        deferred: list[tuple[str, str]] = []
+        for root, dirnames, filenames in os.walk(base_dir):
+            # Sort the directory names so that `os.walk` will walk them in a
+            # defined order on the next iteration.
+            dirnames.sort()
+            for name in sorted(filenames):
+                path = os.path.normpath(os.path.join(root, name))
+                if os.path.isfile(path):
+                    arcname = os.path.relpath(path, base_dir).replace(os.path.sep, "/")
+                    if arcname == self.record_path:
+                        pass
+                    elif root.endswith(".dist-info"):
+                        deferred.append((path, arcname))
+                    else:
+                        self.write(path, arcname)
+
+        deferred.sort()
+        for path, arcname in deferred:
+            self.write(path, arcname)
+
+    def write(
+        self,
+        filename: str,
+        arcname: str | None = None,
+        compress_type: int | None = None,
+    ) -> None:
+        with open(filename, "rb") as f:
+            st = os.fstat(f.fileno())
+            data = f.read()
+
+        zinfo = ZipInfo(
+            arcname or filename, date_time=get_zipinfo_datetime(st.st_mtime)
+        )
+        zinfo.external_attr = (stat.S_IMODE(st.st_mode) | stat.S_IFMT(st.st_mode)) << 16
+        zinfo.compress_type = compress_type or self.compression
+        self.writestr(zinfo, data, compress_type)
+
+    def writestr(
+        self,
+        zinfo_or_arcname: str | ZipInfo,
+        data: SizedBuffer | str,
+        compress_type: int | None = None,
+    ):
+        if isinstance(zinfo_or_arcname, str):
+            zinfo_or_arcname = ZipInfo(
+                zinfo_or_arcname, date_time=get_zipinfo_datetime()
+            )
+            zinfo_or_arcname.compress_type = self.compression
+            zinfo_or_arcname.external_attr = (0o664 | stat.S_IFREG) << 16
+
+        if isinstance(data, str):
+            data = data.encode("utf-8")
+
+        ZipFile.writestr(self, zinfo_or_arcname, data, compress_type)
+        fname = (
+            zinfo_or_arcname.filename
+            if isinstance(zinfo_or_arcname, ZipInfo)
+            else zinfo_or_arcname
+        )
+        log.info(f"adding '{fname}'")
+        if fname != self.record_path:
+            hash_ = self._default_algorithm(data)
+            self._file_hashes[fname] = (
+                hash_.name,
+                urlsafe_b64encode(hash_.digest()).decode("ascii"),
+            )
+            self._file_sizes[fname] = len(data)
+
+    def close(self):
+        # Write RECORD
+        if self.fp is not None and self.mode == "w" and self._file_hashes:
+            data = StringIO()
+            writer = csv.writer(data, delimiter=",", quotechar='"', lineterminator="\n")
+            writer.writerows(
+                (
+                    (fname, algorithm + "=" + hash_, self._file_sizes[fname])
+                    for fname, (algorithm, hash_) in self._file_hashes.items()
+                )
+            )
+            writer.writerow((format(self.record_path), "", ""))
+            self.writestr(self.record_path, data.getvalue())
+
+        ZipFile.close(self)
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/LICENSE b/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..1bb5a44356f00884a71ceeefd24ded6caaba2418
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/LICENSE
@@ -0,0 +1,17 @@
+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.12/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/METADATA b/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..1399281717f23d7a37cb8c56153afedf0c73c860
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/METADATA
@@ -0,0 +1,102 @@
+Metadata-Version: 2.1
+Name: zipp
+Version: 3.19.2
+Summary: Backport of pathlib-compatible object wrapper for zip files
+Author-email: "Jason R. Coombs" 
+Project-URL: Homepage, https://github.com/jaraco/zipp
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3 :: Only
+Requires-Python: >=3.8
+Description-Content-Type: text/x-rst
+License-File: LICENSE
+Provides-Extra: doc
+Requires-Dist: sphinx >=3.5 ; extra == 'doc'
+Requires-Dist: jaraco.packaging >=9.3 ; extra == 'doc'
+Requires-Dist: rst.linker >=1.9 ; extra == 'doc'
+Requires-Dist: furo ; extra == 'doc'
+Requires-Dist: sphinx-lint ; extra == 'doc'
+Requires-Dist: jaraco.tidelift >=1.4 ; extra == 'doc'
+Provides-Extra: test
+Requires-Dist: pytest !=8.1.*,>=6 ; extra == 'test'
+Requires-Dist: pytest-checkdocs >=2.4 ; extra == 'test'
+Requires-Dist: pytest-cov ; extra == 'test'
+Requires-Dist: pytest-mypy ; extra == 'test'
+Requires-Dist: pytest-enabler >=2.2 ; extra == 'test'
+Requires-Dist: pytest-ruff >=0.2.1 ; extra == 'test'
+Requires-Dist: jaraco.itertools ; extra == 'test'
+Requires-Dist: jaraco.functools ; extra == 'test'
+Requires-Dist: more-itertools ; extra == 'test'
+Requires-Dist: big-O ; extra == 'test'
+Requires-Dist: pytest-ignore-flaky ; extra == 'test'
+Requires-Dist: jaraco.test ; extra == 'test'
+Requires-Dist: importlib-resources ; (python_version < "3.9") and extra == 'test'
+
+.. image:: https://img.shields.io/pypi/v/zipp.svg
+   :target: https://pypi.org/project/zipp
+
+.. image:: https://img.shields.io/pypi/pyversions/zipp.svg
+
+.. image:: https://github.com/jaraco/zipp/actions/workflows/main.yml/badge.svg
+   :target: https://github.com/jaraco/zipp/actions?query=workflow%3A%22tests%22
+   :alt: tests
+
+.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v2.json
+    :target: https://github.com/astral-sh/ruff
+    :alt: Ruff
+
+.. .. image:: https://readthedocs.org/projects/PROJECT_RTD/badge/?version=latest
+..    :target: https://PROJECT_RTD.readthedocs.io/en/latest/?badge=latest
+
+.. image:: https://img.shields.io/badge/skeleton-2024-informational
+   :target: https://blog.jaraco.com/skeleton
+
+.. image:: https://tidelift.com/badges/package/pypi/zipp
+   :target: https://tidelift.com/subscription/pkg/pypi-zipp?utm_source=pypi-zipp&utm_medium=readme
+
+
+A pathlib-compatible Zipfile object wrapper. Official backport of the standard library
+`Path object `_.
+
+
+Compatibility
+=============
+
+New features are introduced in this third-party library and later merged
+into CPython. The following table indicates which versions of this library
+were contributed to different versions in the standard library:
+
+.. list-table::
+   :header-rows: 1
+
+   * - zipp
+     - stdlib
+   * - 3.18
+     - 3.13
+   * - 3.16
+     - 3.12
+   * - 3.5
+     - 3.11
+   * - 3.2
+     - 3.10
+   * - 3.3 ??
+     - 3.9
+   * - 1.0
+     - 3.8
+
+
+Usage
+=====
+
+Use ``zipp.Path`` in place of ``zipfile.Path`` on any Python.
+
+For Enterprise
+==============
+
+Available as part of the Tidelift Subscription.
+
+This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use.
+
+`Learn more `_.
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/RECORD b/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..77c02835d891989ded4fbb04d1fdbdb92c208c10
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/RECORD
@@ -0,0 +1,15 @@
+zipp-3.19.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+zipp-3.19.2.dist-info/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023
+zipp-3.19.2.dist-info/METADATA,sha256=UIrk_kMIHGSwsKKChYizqMw0MMZpPRZ2ZiVpQAsN_bE,3575
+zipp-3.19.2.dist-info/RECORD,,
+zipp-3.19.2.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+zipp-3.19.2.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
+zipp-3.19.2.dist-info/top_level.txt,sha256=iAbdoSHfaGqBfVb2XuR9JqSQHCoOsOtG6y9C_LSpqFw,5
+zipp/__init__.py,sha256=QuI1g00G4fRAcGt-HqbV0oWIkmSgedCGGYsHHYzNa8A,13412
+zipp/__pycache__/__init__.cpython-312.pyc,,
+zipp/__pycache__/glob.cpython-312.pyc,,
+zipp/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+zipp/compat/__pycache__/__init__.cpython-312.pyc,,
+zipp/compat/__pycache__/py310.cpython-312.pyc,,
+zipp/compat/py310.py,sha256=eZpkW0zRtunkhEh8jjX3gCGe22emoKCBJw72Zt4RkhA,219
+zipp/glob.py,sha256=etWpnfEoRyfUvrUsi6sTiGmErvPwe6HzY6pT8jg_lUI,3082
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/REQUESTED b/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..bab98d675883cc7567a79df485cd7b4f015e376f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: bdist_wheel (0.43.0)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/top_level.txt b/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..e82f676f82a3381fa909d1e6578c7a22044fafca
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/top_level.txt
@@ -0,0 +1 @@
+zipp
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp/__init__.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d65297b8354b934f687de1ab79c1f8cdf30050ff
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp/__init__.py
@@ -0,0 +1,501 @@
+import io
+import posixpath
+import zipfile
+import itertools
+import contextlib
+import pathlib
+import re
+import stat
+import sys
+
+from .compat.py310 import text_encoding
+from .glob import Translator
+
+
+__all__ = ['Path']
+
+
+def _parents(path):
+    """
+    Given a path with elements separated by
+    posixpath.sep, generate all parents of that path.
+
+    >>> list(_parents('b/d'))
+    ['b']
+    >>> list(_parents('/b/d/'))
+    ['/b']
+    >>> list(_parents('b/d/f/'))
+    ['b/d', 'b']
+    >>> list(_parents('b'))
+    []
+    >>> list(_parents(''))
+    []
+    """
+    return itertools.islice(_ancestry(path), 1, None)
+
+
+def _ancestry(path):
+    """
+    Given a path with elements separated by
+    posixpath.sep, generate all elements of that path
+
+    >>> list(_ancestry('b/d'))
+    ['b/d', 'b']
+    >>> list(_ancestry('/b/d/'))
+    ['/b/d', '/b']
+    >>> list(_ancestry('b/d/f/'))
+    ['b/d/f', 'b/d', 'b']
+    >>> list(_ancestry('b'))
+    ['b']
+    >>> list(_ancestry(''))
+    []
+    """
+    path = path.rstrip(posixpath.sep)
+    while path and path != posixpath.sep:
+        yield path
+        path, tail = posixpath.split(path)
+
+
+_dedupe = dict.fromkeys
+"""Deduplicate an iterable in original order"""
+
+
+def _difference(minuend, subtrahend):
+    """
+    Return items in minuend not in subtrahend, retaining order
+    with O(1) lookup.
+    """
+    return itertools.filterfalse(set(subtrahend).__contains__, minuend)
+
+
+class InitializedState:
+    """
+    Mix-in to save the initialization state for pickling.
+    """
+
+    def __init__(self, *args, **kwargs):
+        self.__args = args
+        self.__kwargs = kwargs
+        super().__init__(*args, **kwargs)
+
+    def __getstate__(self):
+        return self.__args, self.__kwargs
+
+    def __setstate__(self, state):
+        args, kwargs = state
+        super().__init__(*args, **kwargs)
+
+
+class SanitizedNames:
+    """
+    ZipFile mix-in to ensure names are sanitized.
+    """
+
+    def namelist(self):
+        return list(map(self._sanitize, super().namelist()))
+
+    @staticmethod
+    def _sanitize(name):
+        r"""
+        Ensure a relative path with posix separators and no dot names.
+
+        Modeled after
+        https://github.com/python/cpython/blob/bcc1be39cb1d04ad9fc0bd1b9193d3972835a57c/Lib/zipfile/__init__.py#L1799-L1813
+        but provides consistent cross-platform behavior.
+
+        >>> san = SanitizedNames._sanitize
+        >>> san('/foo/bar')
+        'foo/bar'
+        >>> san('//foo.txt')
+        'foo.txt'
+        >>> san('foo/.././bar.txt')
+        'foo/bar.txt'
+        >>> san('foo../.bar.txt')
+        'foo../.bar.txt'
+        >>> san('\\foo\\bar.txt')
+        'foo/bar.txt'
+        >>> san('D:\\foo.txt')
+        'D/foo.txt'
+        >>> san('\\\\server\\share\\file.txt')
+        'server/share/file.txt'
+        >>> san('\\\\?\\GLOBALROOT\\Volume3')
+        '?/GLOBALROOT/Volume3'
+        >>> san('\\\\.\\PhysicalDrive1\\root')
+        'PhysicalDrive1/root'
+
+        Retain any trailing slash.
+        >>> san('abc/')
+        'abc/'
+
+        Raises a ValueError if the result is empty.
+        >>> san('../..')
+        Traceback (most recent call last):
+        ...
+        ValueError: Empty filename
+        """
+
+        def allowed(part):
+            return part and part not in {'..', '.'}
+
+        # Remove the drive letter.
+        # Don't use ntpath.splitdrive, because that also strips UNC paths
+        bare = re.sub('^([A-Z]):', r'\1', name, flags=re.IGNORECASE)
+        clean = bare.replace('\\', '/')
+        parts = clean.split('/')
+        joined = '/'.join(filter(allowed, parts))
+        if not joined:
+            raise ValueError("Empty filename")
+        return joined + '/' * name.endswith('/')
+
+
+class CompleteDirs(InitializedState, SanitizedNames, zipfile.ZipFile):
+    """
+    A ZipFile subclass that ensures that implied directories
+    are always included in the namelist.
+
+    >>> list(CompleteDirs._implied_dirs(['foo/bar.txt', 'foo/bar/baz.txt']))
+    ['foo/', 'foo/bar/']
+    >>> list(CompleteDirs._implied_dirs(['foo/bar.txt', 'foo/bar/baz.txt', 'foo/bar/']))
+    ['foo/']
+    """
+
+    @staticmethod
+    def _implied_dirs(names):
+        parents = itertools.chain.from_iterable(map(_parents, names))
+        as_dirs = (p + posixpath.sep for p in parents)
+        return _dedupe(_difference(as_dirs, names))
+
+    def namelist(self):
+        names = super().namelist()
+        return names + list(self._implied_dirs(names))
+
+    def _name_set(self):
+        return set(self.namelist())
+
+    def resolve_dir(self, name):
+        """
+        If the name represents a directory, return that name
+        as a directory (with the trailing slash).
+        """
+        names = self._name_set()
+        dirname = name + '/'
+        dir_match = name not in names and dirname in names
+        return dirname if dir_match else name
+
+    def getinfo(self, name):
+        """
+        Supplement getinfo for implied dirs.
+        """
+        try:
+            return super().getinfo(name)
+        except KeyError:
+            if not name.endswith('/') or name not in self._name_set():
+                raise
+            return zipfile.ZipInfo(filename=name)
+
+    @classmethod
+    def make(cls, source):
+        """
+        Given a source (filename or zipfile), return an
+        appropriate CompleteDirs subclass.
+        """
+        if isinstance(source, CompleteDirs):
+            return source
+
+        if not isinstance(source, zipfile.ZipFile):
+            return cls(source)
+
+        # Only allow for FastLookup when supplied zipfile is read-only
+        if 'r' not in source.mode:
+            cls = CompleteDirs
+
+        source.__class__ = cls
+        return source
+
+    @classmethod
+    def inject(cls, zf: zipfile.ZipFile) -> zipfile.ZipFile:
+        """
+        Given a writable zip file zf, inject directory entries for
+        any directories implied by the presence of children.
+        """
+        for name in cls._implied_dirs(zf.namelist()):
+            zf.writestr(name, b"")
+        return zf
+
+
+class FastLookup(CompleteDirs):
+    """
+    ZipFile subclass to ensure implicit
+    dirs exist and are resolved rapidly.
+    """
+
+    def namelist(self):
+        with contextlib.suppress(AttributeError):
+            return self.__names
+        self.__names = super().namelist()
+        return self.__names
+
+    def _name_set(self):
+        with contextlib.suppress(AttributeError):
+            return self.__lookup
+        self.__lookup = super()._name_set()
+        return self.__lookup
+
+
+def _extract_text_encoding(encoding=None, *args, **kwargs):
+    # compute stack level so that the caller of the caller sees any warning.
+    is_pypy = sys.implementation.name == 'pypy'
+    stack_level = 3 + is_pypy
+    return text_encoding(encoding, stack_level), args, kwargs
+
+
+class Path:
+    """
+    A :class:`importlib.resources.abc.Traversable` interface for zip files.
+
+    Implements many of the features users enjoy from
+    :class:`pathlib.Path`.
+
+    Consider a zip file with this structure::
+
+        .
+        ├── a.txt
+        └── b
+            ├── c.txt
+            └── d
+                └── e.txt
+
+    >>> data = io.BytesIO()
+    >>> zf = zipfile.ZipFile(data, 'w')
+    >>> zf.writestr('a.txt', 'content of a')
+    >>> zf.writestr('b/c.txt', 'content of c')
+    >>> zf.writestr('b/d/e.txt', 'content of e')
+    >>> zf.filename = 'mem/abcde.zip'
+
+    Path accepts the zipfile object itself or a filename
+
+    >>> path = Path(zf)
+
+    From there, several path operations are available.
+
+    Directory iteration (including the zip file itself):
+
+    >>> a, b = path.iterdir()
+    >>> a
+    Path('mem/abcde.zip', 'a.txt')
+    >>> b
+    Path('mem/abcde.zip', 'b/')
+
+    name property:
+
+    >>> b.name
+    'b'
+
+    join with divide operator:
+
+    >>> c = b / 'c.txt'
+    >>> c
+    Path('mem/abcde.zip', 'b/c.txt')
+    >>> c.name
+    'c.txt'
+
+    Read text:
+
+    >>> c.read_text(encoding='utf-8')
+    'content of c'
+
+    existence:
+
+    >>> c.exists()
+    True
+    >>> (b / 'missing.txt').exists()
+    False
+
+    Coercion to string:
+
+    >>> import os
+    >>> str(c).replace(os.sep, posixpath.sep)
+    'mem/abcde.zip/b/c.txt'
+
+    At the root, ``name``, ``filename``, and ``parent``
+    resolve to the zipfile.
+
+    >>> str(path)
+    'mem/abcde.zip/'
+    >>> path.name
+    'abcde.zip'
+    >>> path.filename == pathlib.Path('mem/abcde.zip')
+    True
+    >>> str(path.parent)
+    'mem'
+
+    If the zipfile has no filename, such attributes are not
+    valid and accessing them will raise an Exception.
+
+    >>> zf.filename = None
+    >>> path.name
+    Traceback (most recent call last):
+    ...
+    TypeError: ...
+
+    >>> path.filename
+    Traceback (most recent call last):
+    ...
+    TypeError: ...
+
+    >>> path.parent
+    Traceback (most recent call last):
+    ...
+    TypeError: ...
+
+    # workaround python/cpython#106763
+    >>> pass
+    """
+
+    __repr = "{self.__class__.__name__}({self.root.filename!r}, {self.at!r})"
+
+    def __init__(self, root, at=""):
+        """
+        Construct a Path from a ZipFile or filename.
+
+        Note: When the source is an existing ZipFile object,
+        its type (__class__) will be mutated to a
+        specialized type. If the caller wishes to retain the
+        original type, the caller should either create a
+        separate ZipFile object or pass a filename.
+        """
+        self.root = FastLookup.make(root)
+        self.at = at
+
+    def __eq__(self, other):
+        """
+        >>> Path(zipfile.ZipFile(io.BytesIO(), 'w')) == 'foo'
+        False
+        """
+        if self.__class__ is not other.__class__:
+            return NotImplemented
+        return (self.root, self.at) == (other.root, other.at)
+
+    def __hash__(self):
+        return hash((self.root, self.at))
+
+    def open(self, mode='r', *args, pwd=None, **kwargs):
+        """
+        Open this entry as text or binary following the semantics
+        of ``pathlib.Path.open()`` by passing arguments through
+        to io.TextIOWrapper().
+        """
+        if self.is_dir():
+            raise IsADirectoryError(self)
+        zip_mode = mode[0]
+        if not self.exists() and zip_mode == 'r':
+            raise FileNotFoundError(self)
+        stream = self.root.open(self.at, zip_mode, pwd=pwd)
+        if 'b' in mode:
+            if args or kwargs:
+                raise ValueError("encoding args invalid for binary operation")
+            return stream
+        # Text mode:
+        encoding, args, kwargs = _extract_text_encoding(*args, **kwargs)
+        return io.TextIOWrapper(stream, encoding, *args, **kwargs)
+
+    def _base(self):
+        return pathlib.PurePosixPath(self.at or self.root.filename)
+
+    @property
+    def name(self):
+        return self._base().name
+
+    @property
+    def suffix(self):
+        return self._base().suffix
+
+    @property
+    def suffixes(self):
+        return self._base().suffixes
+
+    @property
+    def stem(self):
+        return self._base().stem
+
+    @property
+    def filename(self):
+        return pathlib.Path(self.root.filename).joinpath(self.at)
+
+    def read_text(self, *args, **kwargs):
+        encoding, args, kwargs = _extract_text_encoding(*args, **kwargs)
+        with self.open('r', encoding, *args, **kwargs) as strm:
+            return strm.read()
+
+    def read_bytes(self):
+        with self.open('rb') as strm:
+            return strm.read()
+
+    def _is_child(self, path):
+        return posixpath.dirname(path.at.rstrip("/")) == self.at.rstrip("/")
+
+    def _next(self, at):
+        return self.__class__(self.root, at)
+
+    def is_dir(self):
+        return not self.at or self.at.endswith("/")
+
+    def is_file(self):
+        return self.exists() and not self.is_dir()
+
+    def exists(self):
+        return self.at in self.root._name_set()
+
+    def iterdir(self):
+        if not self.is_dir():
+            raise ValueError("Can't listdir a file")
+        subs = map(self._next, self.root.namelist())
+        return filter(self._is_child, subs)
+
+    def match(self, path_pattern):
+        return pathlib.PurePosixPath(self.at).match(path_pattern)
+
+    def is_symlink(self):
+        """
+        Return whether this path is a symlink.
+        """
+        info = self.root.getinfo(self.at)
+        mode = info.external_attr >> 16
+        return stat.S_ISLNK(mode)
+
+    def glob(self, pattern):
+        if not pattern:
+            raise ValueError(f"Unacceptable pattern: {pattern!r}")
+
+        prefix = re.escape(self.at)
+        tr = Translator(seps='/')
+        matches = re.compile(prefix + tr.translate(pattern)).fullmatch
+        names = (data.filename for data in self.root.filelist)
+        return map(self._next, filter(matches, names))
+
+    def rglob(self, pattern):
+        return self.glob(f'**/{pattern}')
+
+    def relative_to(self, other, *extra):
+        return posixpath.relpath(str(self), str(other.joinpath(*extra)))
+
+    def __str__(self):
+        return posixpath.join(self.root.filename, self.at)
+
+    def __repr__(self):
+        return self.__repr.format(self=self)
+
+    def joinpath(self, *other):
+        next = posixpath.join(self.at, *other)
+        return self._next(self.root.resolve_dir(next))
+
+    __truediv__ = joinpath
+
+    @property
+    def parent(self):
+        if not self.at:
+            return self.filename.parent
+        parent_at = posixpath.dirname(self.at.rstrip('/'))
+        if parent_at:
+            parent_at += '/'
+        return self._next(parent_at)
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..437462b06386fc21b6511b311ce6fe629eedede1
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp/__pycache__/glob.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp/__pycache__/glob.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8b4ea4372fad47e4a10036ae0991308ff461e883
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp/__pycache__/glob.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp/compat/__init__.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp/compat/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp/compat/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp/compat/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..92deaae0a4176c16bb8837744877ffe1efd1fa4e
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp/compat/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp/compat/__pycache__/py310.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp/compat/__pycache__/py310.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f627cece2ff0e10c67419e7fc5bdc5c315183236
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp/compat/__pycache__/py310.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp/compat/py310.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp/compat/py310.py
new file mode 100644
index 0000000000000000000000000000000000000000..d5ca53e037b267ff1b196b3b208dea0acdebe4c5
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp/compat/py310.py
@@ -0,0 +1,11 @@
+import sys
+import io
+
+
+def _text_encoding(encoding, stacklevel=2, /):  # pragma: no cover
+    return encoding
+
+
+text_encoding = (
+    io.text_encoding if sys.version_info > (3, 10) else _text_encoding  # type: ignore
+)
diff --git a/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp/glob.py b/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp/glob.py
new file mode 100644
index 0000000000000000000000000000000000000000..69c41d77c3f6549bd58d778dfe978a6ed728ede5
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/_vendor/zipp/glob.py
@@ -0,0 +1,106 @@
+import os
+import re
+
+
+_default_seps = os.sep + str(os.altsep) * bool(os.altsep)
+
+
+class Translator:
+    """
+    >>> Translator('xyz')
+    Traceback (most recent call last):
+    ...
+    AssertionError: Invalid separators
+
+    >>> Translator('')
+    Traceback (most recent call last):
+    ...
+    AssertionError: Invalid separators
+    """
+
+    seps: str
+
+    def __init__(self, seps: str = _default_seps):
+        assert seps and set(seps) <= set(_default_seps), "Invalid separators"
+        self.seps = seps
+
+    def translate(self, pattern):
+        """
+        Given a glob pattern, produce a regex that matches it.
+        """
+        return self.extend(self.translate_core(pattern))
+
+    def extend(self, pattern):
+        r"""
+        Extend regex for pattern-wide concerns.
+
+        Apply '(?s:)' to create a non-matching group that
+        matches newlines (valid on Unix).
+
+        Append '\Z' to imply fullmatch even when match is used.
+        """
+        return rf'(?s:{pattern})\Z'
+
+    def translate_core(self, pattern):
+        r"""
+        Given a glob pattern, produce a regex that matches it.
+
+        >>> t = Translator()
+        >>> t.translate_core('*.txt').replace('\\\\', '')
+        '[^/]*\\.txt'
+        >>> t.translate_core('a?txt')
+        'a[^/]txt'
+        >>> t.translate_core('**/*').replace('\\\\', '')
+        '.*/[^/][^/]*'
+        """
+        self.restrict_rglob(pattern)
+        return ''.join(map(self.replace, separate(self.star_not_empty(pattern))))
+
+    def replace(self, match):
+        """
+        Perform the replacements for a match from :func:`separate`.
+        """
+        return match.group('set') or (
+            re.escape(match.group(0))
+            .replace('\\*\\*', r'.*')
+            .replace('\\*', rf'[^{re.escape(self.seps)}]*')
+            .replace('\\?', r'[^/]')
+        )
+
+    def restrict_rglob(self, pattern):
+        """
+        Raise ValueError if ** appears in anything but a full path segment.
+
+        >>> Translator().translate('**foo')
+        Traceback (most recent call last):
+        ...
+        ValueError: ** must appear alone in a path segment
+        """
+        seps_pattern = rf'[{re.escape(self.seps)}]+'
+        segments = re.split(seps_pattern, pattern)
+        if any('**' in segment and segment != '**' for segment in segments):
+            raise ValueError("** must appear alone in a path segment")
+
+    def star_not_empty(self, pattern):
+        """
+        Ensure that * will not match an empty segment.
+        """
+
+        def handle_segment(match):
+            segment = match.group(0)
+            return '?*' if segment == '*' else segment
+
+        not_seps_pattern = rf'[^{re.escape(self.seps)}]+'
+        return re.sub(not_seps_pattern, handle_segment, pattern)
+
+
+def separate(pattern):
+    """
+    Separate out character sets to avoid translating their contents.
+
+    >>> [m.group(0) for m in separate('*.txt')]
+    ['*.txt']
+    >>> [m.group(0) for m in separate('a[?]txt')]
+    ['a', '[?]', 'txt']
+    """
+    return re.finditer(r'([^\[]+)|(?P[\[].*?[\]])|([\[][^\]]*$)', pattern)
diff --git a/.venv/lib/python3.12/site-packages/setuptools/archive_util.py b/.venv/lib/python3.12/site-packages/setuptools/archive_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..1a02010bb2af2be0487730d6a32080877b9ac220
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/archive_util.py
@@ -0,0 +1,219 @@
+"""Utilities for extracting common archive formats"""
+
+import contextlib
+import os
+import posixpath
+import shutil
+import tarfile
+import zipfile
+
+from ._path import ensure_directory
+
+from distutils.errors import DistutilsError
+
+__all__ = [
+    "unpack_archive",
+    "unpack_zipfile",
+    "unpack_tarfile",
+    "default_filter",
+    "UnrecognizedFormat",
+    "extraction_drivers",
+    "unpack_directory",
+]
+
+
+class UnrecognizedFormat(DistutilsError):
+    """Couldn't recognize the archive type"""
+
+
+def default_filter(src, dst):
+    """The default progress/filter callback; returns True for all files"""
+    return dst
+
+
+def unpack_archive(
+    filename, extract_dir, progress_filter=default_filter, drivers=None
+) -> None:
+    """Unpack `filename` to `extract_dir`, or raise ``UnrecognizedFormat``
+
+    `progress_filter` is a function taking two arguments: a source path
+    internal to the archive ('/'-separated), and a filesystem path where it
+    will be extracted.  The callback must return the desired extract path
+    (which may be the same as the one passed in), or else ``None`` to skip
+    that file or directory.  The callback can thus be used to report on the
+    progress of the extraction, as well as to filter the items extracted or
+    alter their extraction paths.
+
+    `drivers`, if supplied, must be a non-empty sequence of functions with the
+    same signature as this function (minus the `drivers` argument), that raise
+    ``UnrecognizedFormat`` if they do not support extracting the designated
+    archive type.  The `drivers` are tried in sequence until one is found that
+    does not raise an error, or until all are exhausted (in which case
+    ``UnrecognizedFormat`` is raised).  If you do not supply a sequence of
+    drivers, the module's ``extraction_drivers`` constant will be used, which
+    means that ``unpack_zipfile`` and ``unpack_tarfile`` will be tried, in that
+    order.
+    """
+    for driver in drivers or extraction_drivers:
+        try:
+            driver(filename, extract_dir, progress_filter)
+        except UnrecognizedFormat:
+            continue
+        else:
+            return
+    else:
+        raise UnrecognizedFormat(f"Not a recognized archive type: {filename}")
+
+
+def unpack_directory(filename, extract_dir, progress_filter=default_filter) -> None:
+    """ "Unpack" a directory, using the same interface as for archives
+
+    Raises ``UnrecognizedFormat`` if `filename` is not a directory
+    """
+    if not os.path.isdir(filename):
+        raise UnrecognizedFormat(f"{filename} is not a directory")
+
+    paths = {
+        filename: ('', extract_dir),
+    }
+    for base, dirs, files in os.walk(filename):
+        src, dst = paths[base]
+        for d in dirs:
+            paths[os.path.join(base, d)] = src + d + '/', os.path.join(dst, d)
+        for f in files:
+            target = os.path.join(dst, f)
+            target = progress_filter(src + f, target)
+            if not target:
+                # skip non-files
+                continue
+            ensure_directory(target)
+            f = os.path.join(base, f)
+            shutil.copyfile(f, target)
+            shutil.copystat(f, target)
+
+
+def unpack_zipfile(filename, extract_dir, progress_filter=default_filter) -> None:
+    """Unpack zip `filename` to `extract_dir`
+
+    Raises ``UnrecognizedFormat`` if `filename` is not a zipfile (as determined
+    by ``zipfile.is_zipfile()``).  See ``unpack_archive()`` for an explanation
+    of the `progress_filter` argument.
+    """
+
+    if not zipfile.is_zipfile(filename):
+        raise UnrecognizedFormat(f"{filename} is not a zip file")
+
+    with zipfile.ZipFile(filename) as z:
+        _unpack_zipfile_obj(z, extract_dir, progress_filter)
+
+
+def _unpack_zipfile_obj(zipfile_obj, extract_dir, progress_filter=default_filter):
+    """Internal/private API used by other parts of setuptools.
+    Similar to ``unpack_zipfile``, but receives an already opened :obj:`zipfile.ZipFile`
+    object instead of a filename.
+    """
+    for info in zipfile_obj.infolist():
+        name = info.filename
+
+        # don't extract absolute paths or ones with .. in them
+        if name.startswith('/') or '..' in name.split('/'):
+            continue
+
+        target = os.path.join(extract_dir, *name.split('/'))
+        target = progress_filter(name, target)
+        if not target:
+            continue
+        if name.endswith('/'):
+            # directory
+            ensure_directory(target)
+        else:
+            # file
+            ensure_directory(target)
+            data = zipfile_obj.read(info.filename)
+            with open(target, 'wb') as f:
+                f.write(data)
+        unix_attributes = info.external_attr >> 16
+        if unix_attributes:
+            os.chmod(target, unix_attributes)
+
+
+def _resolve_tar_file_or_dir(tar_obj, tar_member_obj):
+    """Resolve any links and extract link targets as normal files."""
+    while tar_member_obj is not None and (
+        tar_member_obj.islnk() or tar_member_obj.issym()
+    ):
+        linkpath = tar_member_obj.linkname
+        if tar_member_obj.issym():
+            base = posixpath.dirname(tar_member_obj.name)
+            linkpath = posixpath.join(base, linkpath)
+            linkpath = posixpath.normpath(linkpath)
+        tar_member_obj = tar_obj._getmember(linkpath)
+
+    is_file_or_dir = tar_member_obj is not None and (
+        tar_member_obj.isfile() or tar_member_obj.isdir()
+    )
+    if is_file_or_dir:
+        return tar_member_obj
+
+    raise LookupError('Got unknown file type')
+
+
+def _iter_open_tar(tar_obj, extract_dir, progress_filter):
+    """Emit member-destination pairs from a tar archive."""
+    # don't do any chowning!
+    tar_obj.chown = lambda *args: None
+
+    with contextlib.closing(tar_obj):
+        for member in tar_obj:
+            name = member.name
+            # don't extract absolute paths or ones with .. in them
+            if name.startswith('/') or '..' in name.split('/'):
+                continue
+
+            prelim_dst = os.path.join(extract_dir, *name.split('/'))
+
+            try:
+                member = _resolve_tar_file_or_dir(tar_obj, member)
+            except LookupError:
+                continue
+
+            final_dst = progress_filter(name, prelim_dst)
+            if not final_dst:
+                continue
+
+            if final_dst.endswith(os.sep):
+                final_dst = final_dst[:-1]
+
+            yield member, final_dst
+
+
+def unpack_tarfile(filename, extract_dir, progress_filter=default_filter) -> bool:
+    """Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir`
+
+    Raises ``UnrecognizedFormat`` if `filename` is not a tarfile (as determined
+    by ``tarfile.open()``).  See ``unpack_archive()`` for an explanation
+    of the `progress_filter` argument.
+    """
+    try:
+        tarobj = tarfile.open(filename)
+    except tarfile.TarError as e:
+        raise UnrecognizedFormat(
+            f"{filename} is not a compressed or uncompressed tar file"
+        ) from e
+
+    for member, final_dst in _iter_open_tar(
+        tarobj,
+        extract_dir,
+        progress_filter,
+    ):
+        try:
+            # XXX Ugh
+            tarobj._extract_member(member, final_dst)
+        except tarfile.ExtractError:
+            # chown/chmod/mkfifo/mknode/makedev failed
+            pass
+
+    return True
+
+
+extraction_drivers = unpack_directory, unpack_zipfile, unpack_tarfile
diff --git a/.venv/lib/python3.12/site-packages/setuptools/build_meta.py b/.venv/lib/python3.12/site-packages/setuptools/build_meta.py
new file mode 100644
index 0000000000000000000000000000000000000000..00fa5e1f7048c8781cfc4838f705e122fd547825
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/build_meta.py
@@ -0,0 +1,560 @@
+"""A PEP 517 interface to setuptools
+
+Previously, when a user or a command line tool (let's call it a "frontend")
+needed to make a request of setuptools to take a certain action, for
+example, generating a list of installation requirements, the frontend
+would call "setup.py egg_info" or "setup.py bdist_wheel" on the command line.
+
+PEP 517 defines a different method of interfacing with setuptools. Rather
+than calling "setup.py" directly, the frontend should:
+
+  1. Set the current directory to the directory with a setup.py file
+  2. Import this module into a safe python interpreter (one in which
+     setuptools can potentially set global variables or crash hard).
+  3. Call one of the functions defined in PEP 517.
+
+What each function does is defined in PEP 517. However, here is a "casual"
+definition of the functions (this definition should not be relied on for
+bug reports or API stability):
+
+  - `build_wheel`: build a wheel in the folder and return the basename
+  - `get_requires_for_build_wheel`: get the `setup_requires` to build
+  - `prepare_metadata_for_build_wheel`: get the `install_requires`
+  - `build_sdist`: build an sdist in the folder and return the basename
+  - `get_requires_for_build_sdist`: get the `setup_requires` to build
+
+Again, this is not a formal definition! Just a "taste" of the module.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import io
+import os
+import shlex
+import shutil
+import sys
+import tempfile
+import tokenize
+import warnings
+from collections.abc import Iterable, Iterator, Mapping
+from pathlib import Path
+from typing import TYPE_CHECKING, Union
+
+import setuptools
+
+from . import errors
+from ._path import StrPath, same_path
+from ._reqs import parse_strings
+from .warnings import SetuptoolsDeprecationWarning
+
+import distutils
+from distutils.util import strtobool
+
+if TYPE_CHECKING:
+    from typing_extensions import TypeAlias
+
+__all__ = [
+    'get_requires_for_build_sdist',
+    'get_requires_for_build_wheel',
+    'prepare_metadata_for_build_wheel',
+    'build_wheel',
+    'build_sdist',
+    'get_requires_for_build_editable',
+    'prepare_metadata_for_build_editable',
+    'build_editable',
+    '__legacy__',
+    'SetupRequirementsError',
+]
+
+SETUPTOOLS_ENABLE_FEATURES = os.getenv("SETUPTOOLS_ENABLE_FEATURES", "").lower()
+LEGACY_EDITABLE = "legacy-editable" in SETUPTOOLS_ENABLE_FEATURES.replace("_", "-")
+
+
+class SetupRequirementsError(BaseException):
+    def __init__(self, specifiers) -> None:
+        self.specifiers = specifiers
+
+
+class Distribution(setuptools.dist.Distribution):
+    def fetch_build_eggs(self, specifiers):
+        specifier_list = list(parse_strings(specifiers))
+
+        raise SetupRequirementsError(specifier_list)
+
+    @classmethod
+    @contextlib.contextmanager
+    def patch(cls):
+        """
+        Replace
+        distutils.dist.Distribution with this class
+        for the duration of this context.
+        """
+        orig = distutils.core.Distribution
+        distutils.core.Distribution = cls  # type: ignore[misc] # monkeypatching
+        try:
+            yield
+        finally:
+            distutils.core.Distribution = orig  # type: ignore[misc] # monkeypatching
+
+
+@contextlib.contextmanager
+def no_install_setup_requires():
+    """Temporarily disable installing setup_requires
+
+    Under PEP 517, the backend reports build dependencies to the frontend,
+    and the frontend is responsible for ensuring they're installed.
+    So setuptools (acting as a backend) should not try to install them.
+    """
+    orig = setuptools._install_setup_requires
+    setuptools._install_setup_requires = lambda attrs: None
+    try:
+        yield
+    finally:
+        setuptools._install_setup_requires = orig
+
+
+def _get_immediate_subdirectories(a_dir):
+    return [
+        name for name in os.listdir(a_dir) if os.path.isdir(os.path.join(a_dir, name))
+    ]
+
+
+def _file_with_extension(directory: StrPath, extension: str | tuple[str, ...]):
+    matching = (f for f in os.listdir(directory) if f.endswith(extension))
+    try:
+        (file,) = matching
+    except ValueError:
+        raise ValueError(
+            'No distribution was found. Ensure that `setup.py` '
+            'is not empty and that it calls `setup()`.'
+        ) from None
+    return file
+
+
+def _open_setup_script(setup_script):
+    if not os.path.exists(setup_script):
+        # Supply a default setup.py
+        return io.StringIO("from setuptools import setup; setup()")
+
+    return tokenize.open(setup_script)
+
+
+@contextlib.contextmanager
+def suppress_known_deprecation():
+    with warnings.catch_warnings():
+        warnings.filterwarnings('ignore', 'setup.py install is deprecated')
+        yield
+
+
+_ConfigSettings: TypeAlias = Union[Mapping[str, Union[str, list[str], None]], None]
+"""
+Currently the user can run::
+
+    pip install -e . --config-settings key=value
+    python -m build -C--key=value -C key=value
+
+- pip will pass both key and value as strings and overwriting repeated keys
+  (pypa/pip#11059).
+- build will accumulate values associated with repeated keys in a list.
+  It will also accept keys with no associated value.
+  This means that an option passed by build can be ``str | list[str] | None``.
+- PEP 517 specifies that ``config_settings`` is an optional dict.
+"""
+
+
+class _ConfigSettingsTranslator:
+    """Translate ``config_settings`` into distutils-style command arguments.
+    Only a limited number of options is currently supported.
+    """
+
+    # See pypa/setuptools#1928 pypa/setuptools#2491
+
+    def _get_config(self, key: str, config_settings: _ConfigSettings) -> list[str]:
+        """
+        Get the value of a specific key in ``config_settings`` as a list of strings.
+
+        >>> fn = _ConfigSettingsTranslator()._get_config
+        >>> fn("--global-option", None)
+        []
+        >>> fn("--global-option", {})
+        []
+        >>> fn("--global-option", {'--global-option': 'foo'})
+        ['foo']
+        >>> fn("--global-option", {'--global-option': ['foo']})
+        ['foo']
+        >>> fn("--global-option", {'--global-option': 'foo'})
+        ['foo']
+        >>> fn("--global-option", {'--global-option': 'foo bar'})
+        ['foo', 'bar']
+        """
+        cfg = config_settings or {}
+        opts = cfg.get(key) or []
+        return shlex.split(opts) if isinstance(opts, str) else opts
+
+    def _global_args(self, config_settings: _ConfigSettings) -> Iterator[str]:
+        """
+        Let the user specify ``verbose`` or ``quiet`` + escape hatch via
+        ``--global-option``.
+        Note: ``-v``, ``-vv``, ``-vvv`` have similar effects in setuptools,
+        so we just have to cover the basic scenario ``-v``.
+
+        >>> fn = _ConfigSettingsTranslator()._global_args
+        >>> list(fn(None))
+        []
+        >>> list(fn({"verbose": "False"}))
+        ['-q']
+        >>> list(fn({"verbose": "1"}))
+        ['-v']
+        >>> list(fn({"--verbose": None}))
+        ['-v']
+        >>> list(fn({"verbose": "true", "--global-option": "-q --no-user-cfg"}))
+        ['-v', '-q', '--no-user-cfg']
+        >>> list(fn({"--quiet": None}))
+        ['-q']
+        """
+        cfg = config_settings or {}
+        falsey = {"false", "no", "0", "off"}
+        if "verbose" in cfg or "--verbose" in cfg:
+            level = str(cfg.get("verbose") or cfg.get("--verbose") or "1")
+            yield ("-q" if level.lower() in falsey else "-v")
+        if "quiet" in cfg or "--quiet" in cfg:
+            level = str(cfg.get("quiet") or cfg.get("--quiet") or "1")
+            yield ("-v" if level.lower() in falsey else "-q")
+
+        yield from self._get_config("--global-option", config_settings)
+
+    def __dist_info_args(self, config_settings: _ConfigSettings) -> Iterator[str]:
+        """
+        The ``dist_info`` command accepts ``tag-date`` and ``tag-build``.
+
+        .. warning::
+           We cannot use this yet as it requires the ``sdist`` and ``bdist_wheel``
+           commands run in ``build_sdist`` and ``build_wheel`` to reuse the egg-info
+           directory created in ``prepare_metadata_for_build_wheel``.
+
+        >>> fn = _ConfigSettingsTranslator()._ConfigSettingsTranslator__dist_info_args
+        >>> list(fn(None))
+        []
+        >>> list(fn({"tag-date": "False"}))
+        ['--no-date']
+        >>> list(fn({"tag-date": None}))
+        ['--no-date']
+        >>> list(fn({"tag-date": "true", "tag-build": ".a"}))
+        ['--tag-date', '--tag-build', '.a']
+        """
+        cfg = config_settings or {}
+        if "tag-date" in cfg:
+            val = strtobool(str(cfg["tag-date"] or "false"))
+            yield ("--tag-date" if val else "--no-date")
+        if "tag-build" in cfg:
+            yield from ["--tag-build", str(cfg["tag-build"])]
+
+    def _editable_args(self, config_settings: _ConfigSettings) -> Iterator[str]:
+        """
+        The ``editable_wheel`` command accepts ``editable-mode=strict``.
+
+        >>> fn = _ConfigSettingsTranslator()._editable_args
+        >>> list(fn(None))
+        []
+        >>> list(fn({"editable-mode": "strict"}))
+        ['--mode', 'strict']
+        """
+        cfg = config_settings or {}
+        mode = cfg.get("editable-mode") or cfg.get("editable_mode")
+        if not mode:
+            return
+        yield from ["--mode", str(mode)]
+
+    def _arbitrary_args(self, config_settings: _ConfigSettings) -> Iterator[str]:
+        """
+        Users may expect to pass arbitrary lists of arguments to a command
+        via "--global-option" (example provided in PEP 517 of a "escape hatch").
+
+        >>> fn = _ConfigSettingsTranslator()._arbitrary_args
+        >>> list(fn(None))
+        []
+        >>> list(fn({}))
+        []
+        >>> list(fn({'--build-option': 'foo'}))
+        ['foo']
+        >>> list(fn({'--build-option': ['foo']}))
+        ['foo']
+        >>> list(fn({'--build-option': 'foo'}))
+        ['foo']
+        >>> list(fn({'--build-option': 'foo bar'}))
+        ['foo', 'bar']
+        >>> list(fn({'--global-option': 'foo'}))
+        []
+        """
+        yield from self._get_config("--build-option", config_settings)
+
+
+class _BuildMetaBackend(_ConfigSettingsTranslator):
+    def _get_build_requires(
+        self, config_settings: _ConfigSettings, requirements: list[str]
+    ):
+        sys.argv = [
+            *sys.argv[:1],
+            *self._global_args(config_settings),
+            "egg_info",
+        ]
+        try:
+            with Distribution.patch():
+                self.run_setup()
+        except SetupRequirementsError as e:
+            requirements += e.specifiers
+
+        return requirements
+
+    def run_setup(self, setup_script: str = 'setup.py'):
+        # Note that we can reuse our build directory between calls
+        # Correctness comes first, then optimization later
+        __file__ = os.path.abspath(setup_script)
+        __name__ = '__main__'
+
+        with _open_setup_script(__file__) as f:
+            code = f.read().replace(r'\r\n', r'\n')
+
+        try:
+            exec(code, locals())
+        except SystemExit as e:
+            if e.code:
+                raise
+            # We ignore exit code indicating success
+            SetuptoolsDeprecationWarning.emit(
+                "Running `setup.py` directly as CLI tool is deprecated.",
+                "Please avoid using `sys.exit(0)` or similar statements "
+                "that don't fit in the paradigm of a configuration file.",
+                see_url="https://blog.ganssle.io/articles/2021/10/"
+                "setup-py-deprecated.html",
+            )
+
+    def get_requires_for_build_wheel(self, config_settings: _ConfigSettings = None):
+        return self._get_build_requires(config_settings, requirements=[])
+
+    def get_requires_for_build_sdist(self, config_settings: _ConfigSettings = None):
+        return self._get_build_requires(config_settings, requirements=[])
+
+    def _bubble_up_info_directory(
+        self, metadata_directory: StrPath, suffix: str
+    ) -> str:
+        """
+        PEP 517 requires that the .dist-info directory be placed in the
+        metadata_directory. To comply, we MUST copy the directory to the root.
+
+        Returns the basename of the info directory, e.g. `proj-0.0.0.dist-info`.
+        """
+        info_dir = self._find_info_directory(metadata_directory, suffix)
+        if not same_path(info_dir.parent, metadata_directory):
+            shutil.move(str(info_dir), metadata_directory)
+            # PEP 517 allow other files and dirs to exist in metadata_directory
+        return info_dir.name
+
+    def _find_info_directory(self, metadata_directory: StrPath, suffix: str) -> Path:
+        for parent, dirs, _ in os.walk(metadata_directory):
+            candidates = [f for f in dirs if f.endswith(suffix)]
+
+            if len(candidates) != 0 or len(dirs) != 1:
+                assert len(candidates) == 1, f"Multiple {suffix} directories found"
+                return Path(parent, candidates[0])
+
+        msg = f"No {suffix} directory found in {metadata_directory}"
+        raise errors.InternalError(msg)
+
+    def prepare_metadata_for_build_wheel(
+        self, metadata_directory: StrPath, config_settings: _ConfigSettings = None
+    ):
+        sys.argv = [
+            *sys.argv[:1],
+            *self._global_args(config_settings),
+            "dist_info",
+            "--output-dir",
+            str(metadata_directory),
+            "--keep-egg-info",
+        ]
+        with no_install_setup_requires():
+            self.run_setup()
+
+        self._bubble_up_info_directory(metadata_directory, ".egg-info")
+        return self._bubble_up_info_directory(metadata_directory, ".dist-info")
+
+    def _build_with_temp_dir(
+        self,
+        setup_command: Iterable[str],
+        result_extension: str | tuple[str, ...],
+        result_directory: StrPath,
+        config_settings: _ConfigSettings,
+        arbitrary_args: Iterable[str] = (),
+    ):
+        result_directory = os.path.abspath(result_directory)
+
+        # Build in a temporary directory, then copy to the target.
+        os.makedirs(result_directory, exist_ok=True)
+
+        with tempfile.TemporaryDirectory(
+            prefix=".tmp-", dir=result_directory
+        ) as tmp_dist_dir:
+            sys.argv = [
+                *sys.argv[:1],
+                *self._global_args(config_settings),
+                *setup_command,
+                "--dist-dir",
+                tmp_dist_dir,
+                *arbitrary_args,
+            ]
+            with no_install_setup_requires():
+                self.run_setup()
+
+            result_basename = _file_with_extension(tmp_dist_dir, result_extension)
+            result_path = os.path.join(result_directory, result_basename)
+            if os.path.exists(result_path):
+                # os.rename will fail overwriting on non-Unix.
+                os.remove(result_path)
+            os.rename(os.path.join(tmp_dist_dir, result_basename), result_path)
+
+        return result_basename
+
+    def build_wheel(
+        self,
+        wheel_directory: StrPath,
+        config_settings: _ConfigSettings = None,
+        metadata_directory: StrPath | None = None,
+    ):
+        def _build(cmd: list[str]):
+            with suppress_known_deprecation():
+                return self._build_with_temp_dir(
+                    cmd,
+                    '.whl',
+                    wheel_directory,
+                    config_settings,
+                    self._arbitrary_args(config_settings),
+                )
+
+        if metadata_directory is None:
+            return _build(['bdist_wheel'])
+
+        try:
+            return _build(['bdist_wheel', '--dist-info-dir', str(metadata_directory)])
+        except SystemExit as ex:  # pragma: nocover
+            # pypa/setuptools#4683
+            if "--dist-info-dir not recognized" not in str(ex):
+                raise
+            _IncompatibleBdistWheel.emit()
+            return _build(['bdist_wheel'])
+
+    def build_sdist(
+        self, sdist_directory: StrPath, config_settings: _ConfigSettings = None
+    ):
+        return self._build_with_temp_dir(
+            ['sdist', '--formats', 'gztar'], '.tar.gz', sdist_directory, config_settings
+        )
+
+    def _get_dist_info_dir(self, metadata_directory: StrPath | None) -> str | None:
+        if not metadata_directory:
+            return None
+        dist_info_candidates = list(Path(metadata_directory).glob("*.dist-info"))
+        assert len(dist_info_candidates) <= 1
+        return str(dist_info_candidates[0]) if dist_info_candidates else None
+
+    if not LEGACY_EDITABLE:
+        # PEP660 hooks:
+        # build_editable
+        # get_requires_for_build_editable
+        # prepare_metadata_for_build_editable
+        def build_editable(
+            self,
+            wheel_directory: StrPath,
+            config_settings: _ConfigSettings = None,
+            metadata_directory: StrPath | None = None,
+        ):
+            # XXX can or should we hide our editable_wheel command normally?
+            info_dir = self._get_dist_info_dir(metadata_directory)
+            opts = ["--dist-info-dir", info_dir] if info_dir else []
+            cmd = ["editable_wheel", *opts, *self._editable_args(config_settings)]
+            with suppress_known_deprecation():
+                return self._build_with_temp_dir(
+                    cmd, ".whl", wheel_directory, config_settings
+                )
+
+        def get_requires_for_build_editable(
+            self, config_settings: _ConfigSettings = None
+        ):
+            return self.get_requires_for_build_wheel(config_settings)
+
+        def prepare_metadata_for_build_editable(
+            self, metadata_directory: StrPath, config_settings: _ConfigSettings = None
+        ):
+            return self.prepare_metadata_for_build_wheel(
+                metadata_directory, config_settings
+            )
+
+
+class _BuildMetaLegacyBackend(_BuildMetaBackend):
+    """Compatibility backend for setuptools
+
+    This is a version of setuptools.build_meta that endeavors
+    to maintain backwards
+    compatibility with pre-PEP 517 modes of invocation. It
+    exists as a temporary
+    bridge between the old packaging mechanism and the new
+    packaging mechanism,
+    and will eventually be removed.
+    """
+
+    def run_setup(self, setup_script: str = 'setup.py'):
+        # In order to maintain compatibility with scripts assuming that
+        # the setup.py script is in a directory on the PYTHONPATH, inject
+        # '' into sys.path. (pypa/setuptools#1642)
+        sys_path = list(sys.path)  # Save the original path
+
+        script_dir = os.path.dirname(os.path.abspath(setup_script))
+        if script_dir not in sys.path:
+            sys.path.insert(0, script_dir)
+
+        # Some setup.py scripts (e.g. in pygame and numpy) use sys.argv[0] to
+        # get the directory of the source code. They expect it to refer to the
+        # setup.py script.
+        sys_argv_0 = sys.argv[0]
+        sys.argv[0] = setup_script
+
+        try:
+            super().run_setup(setup_script=setup_script)
+        finally:
+            # While PEP 517 frontends should be calling each hook in a fresh
+            # subprocess according to the standard (and thus it should not be
+            # strictly necessary to restore the old sys.path), we'll restore
+            # the original path so that the path manipulation does not persist
+            # within the hook after run_setup is called.
+            sys.path[:] = sys_path
+            sys.argv[0] = sys_argv_0
+
+
+class _IncompatibleBdistWheel(SetuptoolsDeprecationWarning):
+    _SUMMARY = "wheel.bdist_wheel is deprecated, please import it from setuptools"
+    _DETAILS = """
+    Ensure that any custom bdist_wheel implementation is a subclass of
+    setuptools.command.bdist_wheel.bdist_wheel.
+    """
+    _DUE_DATE = (2025, 10, 15)
+    # Initially introduced in 2024/10/15, but maybe too disruptive to be enforced?
+    _SEE_URL = "https://github.com/pypa/wheel/pull/631"
+
+
+# The primary backend
+_BACKEND = _BuildMetaBackend()
+
+get_requires_for_build_wheel = _BACKEND.get_requires_for_build_wheel
+get_requires_for_build_sdist = _BACKEND.get_requires_for_build_sdist
+prepare_metadata_for_build_wheel = _BACKEND.prepare_metadata_for_build_wheel
+build_wheel = _BACKEND.build_wheel
+build_sdist = _BACKEND.build_sdist
+
+if not LEGACY_EDITABLE:
+    get_requires_for_build_editable = _BACKEND.get_requires_for_build_editable
+    prepare_metadata_for_build_editable = _BACKEND.prepare_metadata_for_build_editable
+    build_editable = _BACKEND.build_editable
+
+
+# The legacy backend
+__legacy__ = _BuildMetaLegacyBackend()
diff --git a/.venv/lib/python3.12/site-packages/setuptools/cli-32.exe b/.venv/lib/python3.12/site-packages/setuptools/cli-32.exe
new file mode 100644
index 0000000000000000000000000000000000000000..65c3cd99cc7433f271a5b9387abdd1ddb949d1a6
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/cli-32.exe differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/cli-64.exe b/.venv/lib/python3.12/site-packages/setuptools/cli-64.exe
new file mode 100644
index 0000000000000000000000000000000000000000..3ea50eebfe3f0113b231a318cc1ad6e238afd60d
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/cli-64.exe differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/cli-arm64.exe b/.venv/lib/python3.12/site-packages/setuptools/cli-arm64.exe
new file mode 100644
index 0000000000000000000000000000000000000000..da96455a07a0bad4cde5dc5626544325f82c722b
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/cli-arm64.exe differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/cli.exe b/.venv/lib/python3.12/site-packages/setuptools/cli.exe
new file mode 100644
index 0000000000000000000000000000000000000000..65c3cd99cc7433f271a5b9387abdd1ddb949d1a6
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/cli.exe differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/__init__.py b/.venv/lib/python3.12/site-packages/setuptools/command/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..50e6c2f54f38db5bf5175a7a4db219815785f1bc
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/command/__init__.py
@@ -0,0 +1,21 @@
+# mypy: disable_error_code=call-overload
+# pyright: reportCallIssue=false, reportArgumentType=false
+# Can't disable on the exact line because distutils doesn't exists on Python 3.12
+# and type-checkers aren't aware of distutils_hack,
+# causing distutils.command.bdist.bdist.format_commands to be Any.
+
+import sys
+
+from distutils.command.bdist import bdist
+
+if 'egg' not in bdist.format_commands:
+    try:
+        # format_commands is a dict in vendored distutils
+        # It used to be a list in older (stdlib) distutils
+        # We support both for backwards compatibility
+        bdist.format_commands['egg'] = ('bdist_egg', "Python .egg file")
+    except TypeError:
+        bdist.format_command['egg'] = ('bdist_egg', "Python .egg file")
+        bdist.format_commands.append('egg')
+
+del bdist, sys
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3bdbabc3d7e526360e96cb6fc01025ff0033a567
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/_requirestxt.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/_requirestxt.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..36976a570123a173f8262c7a53706141b0c5a2dd
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/_requirestxt.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/alias.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/alias.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7777f638ecd8a60d61608cdc917691616ad7eac2
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/alias.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/bdist_egg.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/bdist_egg.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..47e2b634faebdfee2124ceba91d980e3594358bb
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/bdist_egg.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/bdist_rpm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/bdist_rpm.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..de789ba3ef6283b156170189b067579cc629b38f
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/bdist_rpm.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/bdist_wheel.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/bdist_wheel.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2e734c65b34245494e2e2972e2501e902cee480f
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/bdist_wheel.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/build.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/build.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..389926fb9b00b3312f7efb7efc92bd6df08a1707
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/build.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/build_clib.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/build_clib.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..37ca073d2015e8e0f0c72a3b5162385ec40361db
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/build_clib.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/build_ext.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/build_ext.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..447eaf7aac24988de073c5318a7586b2595a300e
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/build_ext.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/build_py.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/build_py.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bfaa546972a058accaeb8b498cddfec86bd9a1e0
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/build_py.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/develop.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/develop.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bec7f115597634b2d2eec8f0f94a2ec5fca38599
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/develop.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/dist_info.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/dist_info.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..985cf6cdc0ee439ec6309845bea14c25281e29ed
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/dist_info.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/easy_install.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/easy_install.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4690f462868bdf2e8bec69252da9dcd003e85f08
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/easy_install.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:4a51707fb7e04e5bf4a1d0eaf7590f576a3cafbdb8ef42a25d3ebf5660a05368
+size 110553
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/editable_wheel.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/editable_wheel.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..096f63b3628ef1dc8b40a7e8e0c02c3cb6a08015
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/editable_wheel.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/egg_info.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/egg_info.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dc9b482347096783999a91c9c7791b45110bcefc
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/egg_info.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/install.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/install.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3dadf1b4e58ef6588529563c24555bd446db1b22
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/install.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/install_egg_info.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/install_egg_info.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1187bdab895396dce2aeb004de115301527d4b3c
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/install_egg_info.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/install_lib.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/install_lib.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7966e92e0eac6927e235b1d17455df6e4cdf0a49
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/install_lib.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/install_scripts.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/install_scripts.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d5c48158d1ccf00e5fc2934f3c9c9f74daf3a08e
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/install_scripts.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/rotate.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/rotate.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..628f345fd9930f4a9eb1d746e023f8ef5cc628aa
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/rotate.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/saveopts.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/saveopts.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dff4030110e8ebc4c5b5df9e39b07474c1cbb408
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/saveopts.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/sdist.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/sdist.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fc42fc81c2898e5757ef80a66f100ef9a65c27c0
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/sdist.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/setopt.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/setopt.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5207cd9cb7e185d872b1110c417ccf4dcaae1594
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/setopt.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/test.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/test.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cd4bc3cc91c1dd072a6504d7380e292339d40c31
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/command/__pycache__/test.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/_requirestxt.py b/.venv/lib/python3.12/site-packages/setuptools/command/_requirestxt.py
new file mode 100644
index 0000000000000000000000000000000000000000..9029b125141158d4b12de1db8215819ce6ccf437
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/command/_requirestxt.py
@@ -0,0 +1,131 @@
+"""Helper code used to generate ``requires.txt`` files in the egg-info directory.
+
+The ``requires.txt`` file has an specific format:
+    - Environment markers need to be part of the section headers and
+      should not be part of the requirement spec itself.
+
+See https://setuptools.pypa.io/en/latest/deprecated/python_eggs.html#requires-txt
+"""
+
+from __future__ import annotations
+
+import io
+from collections import defaultdict
+from collections.abc import Mapping
+from itertools import filterfalse
+from typing import TypeVar
+
+from jaraco.text import yield_lines
+from packaging.requirements import Requirement
+
+from .. import _reqs
+from .._reqs import _StrOrIter
+
+# dict can work as an ordered set
+_T = TypeVar("_T")
+_Ordered = dict[_T, None]
+
+
+def _prepare(
+    install_requires: _StrOrIter, extras_require: Mapping[str, _StrOrIter]
+) -> tuple[list[str], dict[str, list[str]]]:
+    """Given values for ``install_requires`` and ``extras_require``
+    create modified versions in a way that can be written in ``requires.txt``
+    """
+    extras = _convert_extras_requirements(extras_require)
+    return _move_install_requirements_markers(install_requires, extras)
+
+
+def _convert_extras_requirements(
+    extras_require: Mapping[str, _StrOrIter],
+) -> defaultdict[str, _Ordered[Requirement]]:
+    """
+    Convert requirements in `extras_require` of the form
+    `"extra": ["barbazquux; {marker}"]` to
+    `"extra:{marker}": ["barbazquux"]`.
+    """
+    output = defaultdict[str, _Ordered[Requirement]](dict)
+    for section, v in extras_require.items():
+        # Do not strip empty sections.
+        output[section]
+        for r in _reqs.parse(v):
+            output[section + _suffix_for(r)].setdefault(r)
+
+    return output
+
+
+def _move_install_requirements_markers(
+    install_requires: _StrOrIter, extras_require: Mapping[str, _Ordered[Requirement]]
+) -> tuple[list[str], dict[str, list[str]]]:
+    """
+    The ``requires.txt`` file has an specific format:
+        - Environment markers need to be part of the section headers and
+          should not be part of the requirement spec itself.
+
+    Move requirements in ``install_requires`` that are using environment
+    markers ``extras_require``.
+    """
+
+    # divide the install_requires into two sets, simple ones still
+    # handled by install_requires and more complex ones handled by extras_require.
+
+    inst_reqs = list(_reqs.parse(install_requires))
+    simple_reqs = filter(_no_marker, inst_reqs)
+    complex_reqs = filterfalse(_no_marker, inst_reqs)
+    simple_install_requires = list(map(str, simple_reqs))
+
+    for r in complex_reqs:
+        extras_require[':' + str(r.marker)].setdefault(r)
+
+    expanded_extras = dict(
+        # list(dict.fromkeys(...))  ensures a list of unique strings
+        (k, list(dict.fromkeys(str(r) for r in map(_clean_req, v))))
+        for k, v in extras_require.items()
+    )
+
+    return simple_install_requires, expanded_extras
+
+
+def _suffix_for(req):
+    """Return the 'extras_require' suffix for a given requirement."""
+    return ':' + str(req.marker) if req.marker else ''
+
+
+def _clean_req(req):
+    """Given a Requirement, remove environment markers and return it"""
+    r = Requirement(str(req))  # create a copy before modifying
+    r.marker = None
+    return r
+
+
+def _no_marker(req):
+    return not req.marker
+
+
+def _write_requirements(stream, reqs):
+    lines = yield_lines(reqs or ())
+
+    def append_cr(line):
+        return line + '\n'
+
+    lines = map(append_cr, lines)
+    stream.writelines(lines)
+
+
+def write_requirements(cmd, basename, filename):
+    dist = cmd.distribution
+    data = io.StringIO()
+    install_requires, extras_require = _prepare(
+        dist.install_requires or (), dist.extras_require or {}
+    )
+    _write_requirements(data, install_requires)
+    for extra in sorted(extras_require):
+        data.write('\n[{extra}]\n'.format(**vars()))
+        _write_requirements(data, extras_require[extra])
+    cmd.write_or_delete_file("requirements", filename, data.getvalue())
+
+
+def write_setup_requirements(cmd, basename, filename):
+    data = io.StringIO()
+    _write_requirements(data, cmd.distribution.setup_requires)
+    cmd.write_or_delete_file("setup-requirements", filename, data.getvalue())
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/alias.py b/.venv/lib/python3.12/site-packages/setuptools/command/alias.py
new file mode 100644
index 0000000000000000000000000000000000000000..b8d74af71d4464abf899b9f872b5741f23167165
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/command/alias.py
@@ -0,0 +1,77 @@
+from setuptools.command.setopt import config_file, edit_config, option_base
+
+from distutils.errors import DistutilsOptionError
+
+
+def shquote(arg):
+    """Quote an argument for later parsing by shlex.split()"""
+    for c in '"', "'", "\\", "#":
+        if c in arg:
+            return repr(arg)
+    if arg.split() != [arg]:
+        return repr(arg)
+    return arg
+
+
+class alias(option_base):
+    """Define a shortcut that invokes one or more commands"""
+
+    description = "define a shortcut to invoke one or more commands"
+    command_consumes_arguments = True
+
+    user_options = [
+        ('remove', 'r', 'remove (unset) the alias'),
+    ] + option_base.user_options
+
+    boolean_options = option_base.boolean_options + ['remove']
+
+    def initialize_options(self):
+        option_base.initialize_options(self)
+        self.args = None
+        self.remove = None
+
+    def finalize_options(self) -> None:
+        option_base.finalize_options(self)
+        if self.remove and len(self.args) != 1:
+            raise DistutilsOptionError(
+                "Must specify exactly one argument (the alias name) when using --remove"
+            )
+
+    def run(self) -> None:
+        aliases = self.distribution.get_option_dict('aliases')
+
+        if not self.args:
+            print("Command Aliases")
+            print("---------------")
+            for alias in aliases:
+                print("setup.py alias", format_alias(alias, aliases))
+            return
+
+        elif len(self.args) == 1:
+            (alias,) = self.args
+            if self.remove:
+                command = None
+            elif alias in aliases:
+                print("setup.py alias", format_alias(alias, aliases))
+                return
+            else:
+                print(f"No alias definition found for {alias!r}")
+                return
+        else:
+            alias = self.args[0]
+            command = ' '.join(map(shquote, self.args[1:]))
+
+        edit_config(self.filename, {'aliases': {alias: command}}, self.dry_run)
+
+
+def format_alias(name, aliases):
+    source, command = aliases[name]
+    if source == config_file('global'):
+        source = '--global-config '
+    elif source == config_file('user'):
+        source = '--user-config '
+    elif source == config_file('local'):
+        source = ''
+    else:
+        source = f'--filename={source!r}'
+    return source + name + ' ' + command
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/bdist_egg.py b/.venv/lib/python3.12/site-packages/setuptools/command/bdist_egg.py
new file mode 100644
index 0000000000000000000000000000000000000000..7f66c3ba6a7f554e910800a21c5ccc3733abf07d
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/command/bdist_egg.py
@@ -0,0 +1,479 @@
+"""setuptools.command.bdist_egg
+
+Build .egg distributions"""
+
+from __future__ import annotations
+
+import marshal
+import os
+import re
+import sys
+import textwrap
+from sysconfig import get_path, get_python_version
+from types import CodeType
+from typing import TYPE_CHECKING, Literal
+
+from setuptools import Command
+from setuptools.extension import Library
+
+from .._path import StrPathT, ensure_directory
+
+from distutils import log
+from distutils.dir_util import mkpath, remove_tree
+
+if TYPE_CHECKING:
+    from typing_extensions import TypeAlias
+
+# Same as zipfile._ZipFileMode from typeshed
+_ZipFileMode: TypeAlias = Literal["r", "w", "x", "a"]
+
+
+def _get_purelib():
+    return get_path("purelib")
+
+
+def strip_module(filename):
+    if '.' in filename:
+        filename = os.path.splitext(filename)[0]
+    if filename.endswith('module'):
+        filename = filename[:-6]
+    return filename
+
+
+def sorted_walk(dir):
+    """Do os.walk in a reproducible way,
+    independent of indeterministic filesystem readdir order
+    """
+    for base, dirs, files in os.walk(dir):
+        dirs.sort()
+        files.sort()
+        yield base, dirs, files
+
+
+def write_stub(resource, pyfile) -> None:
+    _stub_template = textwrap.dedent(
+        """
+        def __bootstrap__():
+            global __bootstrap__, __loader__, __file__
+            import sys, pkg_resources, importlib.util
+            __file__ = pkg_resources.resource_filename(__name__, %r)
+            __loader__ = None; del __bootstrap__, __loader__
+            spec = importlib.util.spec_from_file_location(__name__,__file__)
+            mod = importlib.util.module_from_spec(spec)
+            spec.loader.exec_module(mod)
+        __bootstrap__()
+        """
+    ).lstrip()
+    with open(pyfile, 'w', encoding="utf-8") as f:
+        f.write(_stub_template % resource)
+
+
+class bdist_egg(Command):
+    description = 'create an "egg" distribution'
+
+    user_options = [
+        ('bdist-dir=', 'b', "temporary directory for creating the distribution"),
+        (
+            'plat-name=',
+            'p',
+            "platform name to embed in generated filenames "
+            "(by default uses `pkg_resources.get_build_platform()`)",
+        ),
+        ('exclude-source-files', None, "remove all .py files from the generated egg"),
+        (
+            'keep-temp',
+            'k',
+            "keep the pseudo-installation tree around after "
+            "creating the distribution archive",
+        ),
+        ('dist-dir=', 'd', "directory to put final built distributions in"),
+        ('skip-build', None, "skip rebuilding everything (for testing/debugging)"),
+    ]
+
+    boolean_options = ['keep-temp', 'skip-build', 'exclude-source-files']
+
+    def initialize_options(self):
+        self.bdist_dir = None
+        self.plat_name = None
+        self.keep_temp = False
+        self.dist_dir = None
+        self.skip_build = False
+        self.egg_output = None
+        self.exclude_source_files = None
+
+    def finalize_options(self) -> None:
+        ei_cmd = self.ei_cmd = self.get_finalized_command("egg_info")
+        self.egg_info = ei_cmd.egg_info
+
+        if self.bdist_dir is None:
+            bdist_base = self.get_finalized_command('bdist').bdist_base
+            self.bdist_dir = os.path.join(bdist_base, 'egg')
+
+        if self.plat_name is None:
+            from pkg_resources import get_build_platform
+
+            self.plat_name = get_build_platform()
+
+        self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'))
+
+        if self.egg_output is None:
+            # Compute filename of the output egg
+            basename = ei_cmd._get_egg_basename(
+                py_version=get_python_version(),
+                platform=self.distribution.has_ext_modules() and self.plat_name,
+            )
+
+            self.egg_output = os.path.join(self.dist_dir, basename + '.egg')
+
+    def do_install_data(self) -> None:
+        # Hack for packages that install data to install's --install-lib
+        self.get_finalized_command('install').install_lib = self.bdist_dir
+
+        site_packages = os.path.normcase(os.path.realpath(_get_purelib()))
+        old, self.distribution.data_files = self.distribution.data_files, []
+
+        for item in old:
+            if isinstance(item, tuple) and len(item) == 2:
+                if os.path.isabs(item[0]):
+                    realpath = os.path.realpath(item[0])
+                    normalized = os.path.normcase(realpath)
+                    if normalized == site_packages or normalized.startswith(
+                        site_packages + os.sep
+                    ):
+                        item = realpath[len(site_packages) + 1 :], item[1]
+                        # XXX else: raise ???
+            self.distribution.data_files.append(item)
+
+        try:
+            log.info("installing package data to %s", self.bdist_dir)
+            self.call_command('install_data', force=False, root=None)
+        finally:
+            self.distribution.data_files = old
+
+    def get_outputs(self):
+        return [self.egg_output]
+
+    def call_command(self, cmdname, **kw):
+        """Invoke reinitialized command `cmdname` with keyword args"""
+        for dirname in INSTALL_DIRECTORY_ATTRS:
+            kw.setdefault(dirname, self.bdist_dir)
+        kw.setdefault('skip_build', self.skip_build)
+        kw.setdefault('dry_run', self.dry_run)
+        cmd = self.reinitialize_command(cmdname, **kw)
+        self.run_command(cmdname)
+        return cmd
+
+    def run(self):  # noqa: C901  # is too complex (14)  # FIXME
+        # Generate metadata first
+        self.run_command("egg_info")
+        # We run install_lib before install_data, because some data hacks
+        # pull their data path from the install_lib command.
+        log.info("installing library code to %s", self.bdist_dir)
+        instcmd = self.get_finalized_command('install')
+        old_root = instcmd.root
+        instcmd.root = None
+        if self.distribution.has_c_libraries() and not self.skip_build:
+            self.run_command('build_clib')
+        cmd = self.call_command('install_lib', warn_dir=False)
+        instcmd.root = old_root
+
+        all_outputs, ext_outputs = self.get_ext_outputs()
+        self.stubs = []
+        to_compile = []
+        for p, ext_name in enumerate(ext_outputs):
+            filename, _ext = os.path.splitext(ext_name)
+            pyfile = os.path.join(self.bdist_dir, strip_module(filename) + '.py')
+            self.stubs.append(pyfile)
+            log.info("creating stub loader for %s", ext_name)
+            if not self.dry_run:
+                write_stub(os.path.basename(ext_name), pyfile)
+            to_compile.append(pyfile)
+            ext_outputs[p] = ext_name.replace(os.sep, '/')
+
+        if to_compile:
+            cmd.byte_compile(to_compile)
+        if self.distribution.data_files:
+            self.do_install_data()
+
+        # Make the EGG-INFO directory
+        archive_root = self.bdist_dir
+        egg_info = os.path.join(archive_root, 'EGG-INFO')
+        self.mkpath(egg_info)
+        if self.distribution.scripts:
+            script_dir = os.path.join(egg_info, 'scripts')
+            log.info("installing scripts to %s", script_dir)
+            self.call_command('install_scripts', install_dir=script_dir, no_ep=True)
+
+        self.copy_metadata_to(egg_info)
+        native_libs = os.path.join(egg_info, "native_libs.txt")
+        if all_outputs:
+            log.info("writing %s", native_libs)
+            if not self.dry_run:
+                ensure_directory(native_libs)
+                with open(native_libs, 'wt', encoding="utf-8") as libs_file:
+                    libs_file.write('\n'.join(all_outputs))
+                    libs_file.write('\n')
+        elif os.path.isfile(native_libs):
+            log.info("removing %s", native_libs)
+            if not self.dry_run:
+                os.unlink(native_libs)
+
+        write_safety_flag(os.path.join(archive_root, 'EGG-INFO'), self.zip_safe())
+
+        if os.path.exists(os.path.join(self.egg_info, 'depends.txt')):
+            log.warn(
+                "WARNING: 'depends.txt' will not be used by setuptools 0.6!\n"
+                "Use the install_requires/extras_require setup() args instead."
+            )
+
+        if self.exclude_source_files:
+            self.zap_pyfiles()
+
+        # Make the archive
+        make_zipfile(
+            self.egg_output,
+            archive_root,
+            verbose=self.verbose,
+            dry_run=self.dry_run,
+            mode=self.gen_header(),
+        )
+        if not self.keep_temp:
+            remove_tree(self.bdist_dir, dry_run=self.dry_run)
+
+        # Add to 'Distribution.dist_files' so that the "upload" command works
+        getattr(self.distribution, 'dist_files', []).append((
+            'bdist_egg',
+            get_python_version(),
+            self.egg_output,
+        ))
+
+    def zap_pyfiles(self):
+        log.info("Removing .py files from temporary directory")
+        for base, dirs, files in walk_egg(self.bdist_dir):
+            for name in files:
+                path = os.path.join(base, name)
+
+                if name.endswith('.py'):
+                    log.debug("Deleting %s", path)
+                    os.unlink(path)
+
+                if base.endswith('__pycache__'):
+                    path_old = path
+
+                    pattern = r'(?P.+)\.(?P[^.]+)\.pyc'
+                    m = re.match(pattern, name)
+                    path_new = os.path.join(base, os.pardir, m.group('name') + '.pyc')
+                    log.info(f"Renaming file from [{path_old}] to [{path_new}]")
+                    try:
+                        os.remove(path_new)
+                    except OSError:
+                        pass
+                    os.rename(path_old, path_new)
+
+    def zip_safe(self):
+        safe = getattr(self.distribution, 'zip_safe', None)
+        if safe is not None:
+            return safe
+        log.warn("zip_safe flag not set; analyzing archive contents...")
+        return analyze_egg(self.bdist_dir, self.stubs)
+
+    def gen_header(self) -> Literal["w"]:
+        return 'w'
+
+    def copy_metadata_to(self, target_dir) -> None:
+        "Copy metadata (egg info) to the target_dir"
+        # normalize the path (so that a forward-slash in egg_info will
+        # match using startswith below)
+        norm_egg_info = os.path.normpath(self.egg_info)
+        prefix = os.path.join(norm_egg_info, '')
+        for path in self.ei_cmd.filelist.files:
+            if path.startswith(prefix):
+                target = os.path.join(target_dir, path[len(prefix) :])
+                ensure_directory(target)
+                self.copy_file(path, target)
+
+    def get_ext_outputs(self):
+        """Get a list of relative paths to C extensions in the output distro"""
+
+        all_outputs = []
+        ext_outputs = []
+
+        paths = {self.bdist_dir: ''}
+        for base, dirs, files in sorted_walk(self.bdist_dir):
+            all_outputs.extend(
+                paths[base] + filename
+                for filename in files
+                if os.path.splitext(filename)[1].lower() in NATIVE_EXTENSIONS
+            )
+            for filename in dirs:
+                paths[os.path.join(base, filename)] = paths[base] + filename + '/'
+
+        if self.distribution.has_ext_modules():
+            build_cmd = self.get_finalized_command('build_ext')
+            for ext in build_cmd.extensions:
+                if isinstance(ext, Library):
+                    continue
+                fullname = build_cmd.get_ext_fullname(ext.name)
+                filename = build_cmd.get_ext_filename(fullname)
+                if not os.path.basename(filename).startswith('dl-'):
+                    if os.path.exists(os.path.join(self.bdist_dir, filename)):
+                        ext_outputs.append(filename)
+
+        return all_outputs, ext_outputs
+
+
+NATIVE_EXTENSIONS: dict[str, None] = dict.fromkeys('.dll .so .dylib .pyd'.split())
+
+
+def walk_egg(egg_dir):
+    """Walk an unpacked egg's contents, skipping the metadata directory"""
+    walker = sorted_walk(egg_dir)
+    base, dirs, files = next(walker)
+    if 'EGG-INFO' in dirs:
+        dirs.remove('EGG-INFO')
+    yield base, dirs, files
+    yield from walker
+
+
+def analyze_egg(egg_dir, stubs):
+    # check for existing flag in EGG-INFO
+    for flag, fn in safety_flags.items():
+        if os.path.exists(os.path.join(egg_dir, 'EGG-INFO', fn)):
+            return flag
+    if not can_scan():
+        return False
+    safe = True
+    for base, dirs, files in walk_egg(egg_dir):
+        for name in files:
+            if name.endswith('.py') or name.endswith('.pyw'):
+                continue
+            elif name.endswith('.pyc') or name.endswith('.pyo'):
+                # always scan, even if we already know we're not safe
+                safe = scan_module(egg_dir, base, name, stubs) and safe
+    return safe
+
+
+def write_safety_flag(egg_dir, safe) -> None:
+    # Write or remove zip safety flag file(s)
+    for flag, fn in safety_flags.items():
+        fn = os.path.join(egg_dir, fn)
+        if os.path.exists(fn):
+            if safe is None or bool(safe) != flag:
+                os.unlink(fn)
+        elif safe is not None and bool(safe) == flag:
+            with open(fn, 'wt', encoding="utf-8") as f:
+                f.write('\n')
+
+
+safety_flags = {
+    True: 'zip-safe',
+    False: 'not-zip-safe',
+}
+
+
+def scan_module(egg_dir, base, name, stubs):
+    """Check whether module possibly uses unsafe-for-zipfile stuff"""
+
+    filename = os.path.join(base, name)
+    if filename[:-1] in stubs:
+        return True  # Extension module
+    pkg = base[len(egg_dir) + 1 :].replace(os.sep, '.')
+    module = pkg + (pkg and '.' or '') + os.path.splitext(name)[0]
+    skip = 16  # skip magic & reserved? & date & file size
+    f = open(filename, 'rb')
+    f.read(skip)
+    code = marshal.load(f)
+    f.close()
+    safe = True
+    symbols = dict.fromkeys(iter_symbols(code))
+    for bad in ['__file__', '__path__']:
+        if bad in symbols:
+            log.warn("%s: module references %s", module, bad)
+            safe = False
+    if 'inspect' in symbols:
+        for bad in [
+            'getsource',
+            'getabsfile',
+            'getfile',
+            'getsourcefile',
+            'getsourcelines',
+            'findsource',
+            'getcomments',
+            'getframeinfo',
+            'getinnerframes',
+            'getouterframes',
+            'stack',
+            'trace',
+        ]:
+            if bad in symbols:
+                log.warn("%s: module MAY be using inspect.%s", module, bad)
+                safe = False
+    return safe
+
+
+def iter_symbols(code):
+    """Yield names and strings used by `code` and its nested code objects"""
+    yield from code.co_names
+    for const in code.co_consts:
+        if isinstance(const, str):
+            yield const
+        elif isinstance(const, CodeType):
+            yield from iter_symbols(const)
+
+
+def can_scan() -> bool:
+    if not sys.platform.startswith('java') and sys.platform != 'cli':
+        # CPython, PyPy, etc.
+        return True
+    log.warn("Unable to analyze compiled code on this platform.")
+    log.warn(
+        "Please ask the author to include a 'zip_safe'"
+        " setting (either True or False) in the package's setup.py"
+    )
+    return False
+
+
+# Attribute names of options for commands that might need to be convinced to
+# install to the egg build directory
+
+INSTALL_DIRECTORY_ATTRS = ['install_lib', 'install_dir', 'install_data', 'install_base']
+
+
+def make_zipfile(
+    zip_filename: StrPathT,
+    base_dir,
+    verbose: bool = False,
+    dry_run: bool = False,
+    compress=True,
+    mode: _ZipFileMode = 'w',
+) -> StrPathT:
+    """Create a zip file from all the files under 'base_dir'.  The output
+    zip file will be named 'base_dir' + ".zip".  Uses either the "zipfile"
+    Python module (if available) or the InfoZIP "zip" utility (if installed
+    and found on the default search path).  If neither tool is available,
+    raises DistutilsExecError.  Returns the name of the output zip file.
+    """
+    import zipfile
+
+    mkpath(os.path.dirname(zip_filename), dry_run=dry_run)  # type: ignore[arg-type] # python/mypy#18075
+    log.info("creating '%s' and adding '%s' to it", zip_filename, base_dir)
+
+    def visit(z, dirname, names):
+        for name in names:
+            path = os.path.normpath(os.path.join(dirname, name))
+            if os.path.isfile(path):
+                p = path[len(base_dir) + 1 :]
+                if not dry_run:
+                    z.write(path, p)
+                log.debug("adding '%s'", p)
+
+    compression = zipfile.ZIP_DEFLATED if compress else zipfile.ZIP_STORED
+    if not dry_run:
+        z = zipfile.ZipFile(zip_filename, mode, compression=compression)
+        for dirname, dirs, files in sorted_walk(base_dir):
+            visit(z, dirname, files)
+        z.close()
+    else:
+        for dirname, dirs, files in sorted_walk(base_dir):
+            visit(None, dirname, files)
+    return zip_filename
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/bdist_rpm.py b/.venv/lib/python3.12/site-packages/setuptools/command/bdist_rpm.py
new file mode 100644
index 0000000000000000000000000000000000000000..6dbb27002a8cc7f1cafd4f5cbb75ba39aa7430e2
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/command/bdist_rpm.py
@@ -0,0 +1,42 @@
+from ..dist import Distribution
+from ..warnings import SetuptoolsDeprecationWarning
+
+import distutils.command.bdist_rpm as orig
+
+
+class bdist_rpm(orig.bdist_rpm):
+    """
+    Override the default bdist_rpm behavior to do the following:
+
+    1. Run egg_info to ensure the name and version are properly calculated.
+    2. Always run 'install' using --single-version-externally-managed to
+       disable eggs in RPM distributions.
+    """
+
+    distribution: Distribution  # override distutils.dist.Distribution with setuptools.dist.Distribution
+
+    def run(self) -> None:
+        SetuptoolsDeprecationWarning.emit(
+            "Deprecated command",
+            """
+            bdist_rpm is deprecated and will be removed in a future version.
+            Use bdist_wheel (wheel packages) instead.
+            """,
+            see_url="https://github.com/pypa/setuptools/issues/1988",
+            due_date=(2023, 10, 30),  # Deprecation introduced in 22 Oct 2021.
+        )
+
+        # ensure distro name is up-to-date
+        self.run_command('egg_info')
+
+        orig.bdist_rpm.run(self)
+
+    def _make_spec_file(self):
+        spec = orig.bdist_rpm._make_spec_file(self)
+        return [
+            line.replace(
+                "setup.py install ",
+                "setup.py install --single-version-externally-managed ",
+            ).replace("%setup", "%setup -n %{name}-%{unmangled_version}")
+            for line in spec
+        ]
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/bdist_wheel.py b/.venv/lib/python3.12/site-packages/setuptools/command/bdist_wheel.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e3f637bcc31e6b49f2f9415934f553e9cf55c4a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/command/bdist_wheel.py
@@ -0,0 +1,604 @@
+"""
+Create a wheel (.whl) distribution.
+
+A wheel is a built archive format.
+"""
+
+from __future__ import annotations
+
+import os
+import re
+import shutil
+import struct
+import sys
+import sysconfig
+import warnings
+from collections.abc import Iterable, Sequence
+from email.generator import BytesGenerator
+from glob import iglob
+from typing import Literal, cast
+from zipfile import ZIP_DEFLATED, ZIP_STORED
+
+from packaging import tags, version as _packaging_version
+from wheel.wheelfile import WheelFile
+
+from .. import Command, __version__, _shutil
+from .._core_metadata import _safe_license_file
+from .._normalization import safer_name
+from ..warnings import SetuptoolsDeprecationWarning
+from .egg_info import egg_info as egg_info_cls
+
+from distutils import log
+
+
+def safe_version(version: str) -> str:
+    """
+    Convert an arbitrary string to a standard version string
+    """
+    try:
+        # normalize the version
+        return str(_packaging_version.Version(version))
+    except _packaging_version.InvalidVersion:
+        version = version.replace(" ", ".")
+        return re.sub("[^A-Za-z0-9.]+", "-", version)
+
+
+setuptools_major_version = int(__version__.split(".")[0])
+
+PY_LIMITED_API_PATTERN = r"cp3\d"
+
+
+def _is_32bit_interpreter() -> bool:
+    return struct.calcsize("P") == 4
+
+
+def python_tag() -> str:
+    return f"py{sys.version_info.major}"
+
+
+def get_platform(archive_root: str | None) -> str:
+    """Return our platform name 'win32', 'linux_x86_64'"""
+    result = sysconfig.get_platform()
+    if result.startswith("macosx") and archive_root is not None:  # pragma: no cover
+        from wheel.macosx_libfile import calculate_macosx_platform_tag
+
+        result = calculate_macosx_platform_tag(archive_root, result)
+    elif _is_32bit_interpreter():
+        if result == "linux-x86_64":
+            # pip pull request #3497
+            result = "linux-i686"
+        elif result == "linux-aarch64":
+            # packaging pull request #234
+            # TODO armv8l, packaging pull request #690 => this did not land
+            # in pip/packaging yet
+            result = "linux-armv7l"
+
+    return result.replace("-", "_")
+
+
+def get_flag(
+    var: str, fallback: bool, expected: bool = True, warn: bool = True
+) -> bool:
+    """Use a fallback value for determining SOABI flags if the needed config
+    var is unset or unavailable."""
+    val = sysconfig.get_config_var(var)
+    if val is None:
+        if warn:
+            warnings.warn(
+                f"Config variable '{var}' is unset, Python ABI tag may be incorrect",
+                RuntimeWarning,
+                stacklevel=2,
+            )
+        return fallback
+    return val == expected
+
+
+def get_abi_tag() -> str | None:
+    """Return the ABI tag based on SOABI (if available) or emulate SOABI (PyPy2)."""
+    soabi: str = sysconfig.get_config_var("SOABI")
+    impl = tags.interpreter_name()
+    if not soabi and impl in ("cp", "pp") and hasattr(sys, "maxunicode"):
+        d = ""
+        u = ""
+        if get_flag("Py_DEBUG", hasattr(sys, "gettotalrefcount"), warn=(impl == "cp")):
+            d = "d"
+
+        abi = f"{impl}{tags.interpreter_version()}{d}{u}"
+    elif soabi and impl == "cp" and soabi.startswith("cpython"):
+        # non-Windows
+        abi = "cp" + soabi.split("-")[1]
+    elif soabi and impl == "cp" and soabi.startswith("cp"):
+        # Windows
+        abi = soabi.split("-")[0]
+        if hasattr(sys, "gettotalrefcount"):
+            # using debug build; append "d" flag
+            abi += "d"
+    elif soabi and impl == "pp":
+        # we want something like pypy36-pp73
+        abi = "-".join(soabi.split("-")[:2])
+        abi = abi.replace(".", "_").replace("-", "_")
+    elif soabi and impl == "graalpy":
+        abi = "-".join(soabi.split("-")[:3])
+        abi = abi.replace(".", "_").replace("-", "_")
+    elif soabi:
+        abi = soabi.replace(".", "_").replace("-", "_")
+    else:
+        abi = None
+
+    return abi
+
+
+def safer_version(version: str) -> str:
+    return safe_version(version).replace("-", "_")
+
+
+class bdist_wheel(Command):
+    description = "create a wheel distribution"
+
+    supported_compressions = {
+        "stored": ZIP_STORED,
+        "deflated": ZIP_DEFLATED,
+    }
+
+    user_options = [
+        ("bdist-dir=", "b", "temporary directory for creating the distribution"),
+        (
+            "plat-name=",
+            "p",
+            "platform name to embed in generated filenames "
+            f"[default: {get_platform(None)}]",
+        ),
+        (
+            "keep-temp",
+            "k",
+            "keep the pseudo-installation tree around after "
+            "creating the distribution archive",
+        ),
+        ("dist-dir=", "d", "directory to put final built distributions in"),
+        ("skip-build", None, "skip rebuilding everything (for testing/debugging)"),
+        (
+            "relative",
+            None,
+            "build the archive using relative paths [default: false]",
+        ),
+        (
+            "owner=",
+            "u",
+            "Owner name used when creating a tar file [default: current user]",
+        ),
+        (
+            "group=",
+            "g",
+            "Group name used when creating a tar file [default: current group]",
+        ),
+        ("universal", None, "*DEPRECATED* make a universal wheel [default: false]"),
+        (
+            "compression=",
+            None,
+            f"zipfile compression (one of: {', '.join(supported_compressions)}) [default: 'deflated']",
+        ),
+        (
+            "python-tag=",
+            None,
+            f"Python implementation compatibility tag [default: '{python_tag()}']",
+        ),
+        (
+            "build-number=",
+            None,
+            "Build number for this particular version. "
+            "As specified in PEP-0427, this must start with a digit. "
+            "[default: None]",
+        ),
+        (
+            "py-limited-api=",
+            None,
+            "Python tag (cp32|cp33|cpNN) for abi3 wheel tag [default: false]",
+        ),
+        (
+            "dist-info-dir=",
+            None,
+            "directory where a pre-generated dist-info can be found (e.g. as a "
+            "result of calling the PEP517 'prepare_metadata_for_build_wheel' "
+            "method)",
+        ),
+    ]
+
+    boolean_options = ["keep-temp", "skip-build", "relative", "universal"]
+
+    def initialize_options(self) -> None:
+        self.bdist_dir: str | None = None
+        self.data_dir = ""
+        self.plat_name: str | None = None
+        self.plat_tag: str | None = None
+        self.format = "zip"
+        self.keep_temp = False
+        self.dist_dir: str | None = None
+        self.dist_info_dir = None
+        self.egginfo_dir: str | None = None
+        self.root_is_pure: bool | None = None
+        self.skip_build = False
+        self.relative = False
+        self.owner = None
+        self.group = None
+        self.universal = False
+        self.compression: str | int = "deflated"
+        self.python_tag = python_tag()
+        self.build_number: str | None = None
+        self.py_limited_api: str | Literal[False] = False
+        self.plat_name_supplied = False
+
+    def finalize_options(self) -> None:
+        if not self.bdist_dir:
+            bdist_base = self.get_finalized_command("bdist").bdist_base
+            self.bdist_dir = os.path.join(bdist_base, "wheel")
+
+        if self.dist_info_dir is None:
+            egg_info = cast(egg_info_cls, self.distribution.get_command_obj("egg_info"))
+            egg_info.ensure_finalized()  # needed for correct `wheel_dist_name`
+
+        self.data_dir = self.wheel_dist_name + ".data"
+        self.plat_name_supplied = bool(self.plat_name)
+
+        need_options = ("dist_dir", "plat_name", "skip_build")
+
+        self.set_undefined_options("bdist", *zip(need_options, need_options))
+
+        self.root_is_pure = not (
+            self.distribution.has_ext_modules() or self.distribution.has_c_libraries()
+        )
+
+        self._validate_py_limited_api()
+
+        # Support legacy [wheel] section for setting universal
+        wheel = self.distribution.get_option_dict("wheel")
+        if "universal" in wheel:  # pragma: no cover
+            # please don't define this in your global configs
+            log.warn("The [wheel] section is deprecated. Use [bdist_wheel] instead.")
+            val = wheel["universal"][1].strip()
+            if val.lower() in ("1", "true", "yes"):
+                self.universal = True
+
+        if self.universal:
+            SetuptoolsDeprecationWarning.emit(
+                "bdist_wheel.universal is deprecated",
+                """
+                With Python 2.7 end-of-life, support for building universal wheels
+                (i.e., wheels that support both Python 2 and Python 3)
+                is being obviated.
+                Please discontinue using this option, or if you still need it,
+                file an issue with pypa/setuptools describing your use case.
+                """,
+                due_date=(2025, 8, 30),  # Introduced in 2024-08-30
+            )
+
+        if self.build_number is not None and not self.build_number[:1].isdigit():
+            raise ValueError("Build tag (build-number) must start with a digit.")
+
+    def _validate_py_limited_api(self) -> None:
+        if not self.py_limited_api:
+            return
+
+        if not re.match(PY_LIMITED_API_PATTERN, self.py_limited_api):
+            raise ValueError(f"py-limited-api must match '{PY_LIMITED_API_PATTERN}'")
+
+        if sysconfig.get_config_var("Py_GIL_DISABLED"):
+            raise ValueError(
+                f"`py_limited_api={self.py_limited_api!r}` not supported. "
+                "`Py_LIMITED_API` is currently incompatible with "
+                "`Py_GIL_DISABLED`."
+                "See https://github.com/python/cpython/issues/111506."
+            )
+
+    @property
+    def wheel_dist_name(self) -> str:
+        """Return distribution full name with - replaced with _"""
+        components = [
+            safer_name(self.distribution.get_name()),
+            safer_version(self.distribution.get_version()),
+        ]
+        if self.build_number:
+            components.append(self.build_number)
+        return "-".join(components)
+
+    def get_tag(self) -> tuple[str, str, str]:
+        # bdist sets self.plat_name if unset, we should only use it for purepy
+        # wheels if the user supplied it.
+        if self.plat_name_supplied and self.plat_name:
+            plat_name = self.plat_name
+        elif self.root_is_pure:
+            plat_name = "any"
+        else:
+            # macosx contains system version in platform name so need special handle
+            if self.plat_name and not self.plat_name.startswith("macosx"):
+                plat_name = self.plat_name
+            else:
+                # on macosx always limit the platform name to comply with any
+                # c-extension modules in bdist_dir, since the user can specify
+                # a higher MACOSX_DEPLOYMENT_TARGET via tools like CMake
+
+                # on other platforms, and on macosx if there are no c-extension
+                # modules, use the default platform name.
+                plat_name = get_platform(self.bdist_dir)
+
+            if _is_32bit_interpreter():
+                if plat_name in ("linux-x86_64", "linux_x86_64"):
+                    plat_name = "linux_i686"
+                if plat_name in ("linux-aarch64", "linux_aarch64"):
+                    # TODO armv8l, packaging pull request #690 => this did not land
+                    # in pip/packaging yet
+                    plat_name = "linux_armv7l"
+
+        plat_name = (
+            plat_name.lower().replace("-", "_").replace(".", "_").replace(" ", "_")
+        )
+
+        if self.root_is_pure:
+            if self.universal:
+                impl = "py2.py3"
+            else:
+                impl = self.python_tag
+            tag = (impl, "none", plat_name)
+        else:
+            impl_name = tags.interpreter_name()
+            impl_ver = tags.interpreter_version()
+            impl = impl_name + impl_ver
+            # We don't work on CPython 3.1, 3.0.
+            if self.py_limited_api and (impl_name + impl_ver).startswith("cp3"):
+                impl = self.py_limited_api
+                abi_tag = "abi3"
+            else:
+                abi_tag = str(get_abi_tag()).lower()
+            tag = (impl, abi_tag, plat_name)
+            # issue gh-374: allow overriding plat_name
+            supported_tags = [
+                (t.interpreter, t.abi, plat_name) for t in tags.sys_tags()
+            ]
+            assert tag in supported_tags, (
+                f"would build wheel with unsupported tag {tag}"
+            )
+        return tag
+
+    def run(self):
+        build_scripts = self.reinitialize_command("build_scripts")
+        build_scripts.executable = "python"
+        build_scripts.force = True
+
+        build_ext = self.reinitialize_command("build_ext")
+        build_ext.inplace = False
+
+        if not self.skip_build:
+            self.run_command("build")
+
+        install = self.reinitialize_command("install", reinit_subcommands=True)
+        install.root = self.bdist_dir
+        install.compile = False
+        install.skip_build = self.skip_build
+        install.warn_dir = False
+
+        # A wheel without setuptools scripts is more cross-platform.
+        # Use the (undocumented) `no_ep` option to setuptools'
+        # install_scripts command to avoid creating entry point scripts.
+        install_scripts = self.reinitialize_command("install_scripts")
+        install_scripts.no_ep = True
+
+        # Use a custom scheme for the archive, because we have to decide
+        # at installation time which scheme to use.
+        for key in ("headers", "scripts", "data", "purelib", "platlib"):
+            setattr(install, "install_" + key, os.path.join(self.data_dir, key))
+
+        basedir_observed = ""
+
+        if os.name == "nt":
+            # win32 barfs if any of these are ''; could be '.'?
+            # (distutils.command.install:change_roots bug)
+            basedir_observed = os.path.normpath(os.path.join(self.data_dir, ".."))
+            self.install_libbase = self.install_lib = basedir_observed
+
+        setattr(
+            install,
+            "install_purelib" if self.root_is_pure else "install_platlib",
+            basedir_observed,
+        )
+
+        log.info(f"installing to {self.bdist_dir}")
+
+        self.run_command("install")
+
+        impl_tag, abi_tag, plat_tag = self.get_tag()
+        archive_basename = f"{self.wheel_dist_name}-{impl_tag}-{abi_tag}-{plat_tag}"
+        if not self.relative:
+            archive_root = self.bdist_dir
+        else:
+            archive_root = os.path.join(
+                self.bdist_dir, self._ensure_relative(install.install_base)
+            )
+
+        self.set_undefined_options("install_egg_info", ("target", "egginfo_dir"))
+        distinfo_dirname = (
+            f"{safer_name(self.distribution.get_name())}-"
+            f"{safer_version(self.distribution.get_version())}.dist-info"
+        )
+        distinfo_dir = os.path.join(self.bdist_dir, distinfo_dirname)
+        if self.dist_info_dir:
+            # Use the given dist-info directly.
+            log.debug(f"reusing {self.dist_info_dir}")
+            shutil.copytree(self.dist_info_dir, distinfo_dir)
+            # Egg info is still generated, so remove it now to avoid it getting
+            # copied into the wheel.
+            _shutil.rmtree(self.egginfo_dir)
+        else:
+            # Convert the generated egg-info into dist-info.
+            self.egg2dist(self.egginfo_dir, distinfo_dir)
+
+        self.write_wheelfile(distinfo_dir)
+
+        # Make the archive
+        if not os.path.exists(self.dist_dir):
+            os.makedirs(self.dist_dir)
+
+        wheel_path = os.path.join(self.dist_dir, archive_basename + ".whl")
+        with WheelFile(wheel_path, "w", self._zip_compression()) as wf:
+            wf.write_files(archive_root)
+
+        # Add to 'Distribution.dist_files' so that the "upload" command works
+        getattr(self.distribution, "dist_files", []).append((
+            "bdist_wheel",
+            f"{sys.version_info.major}.{sys.version_info.minor}",
+            wheel_path,
+        ))
+
+        if not self.keep_temp:
+            log.info(f"removing {self.bdist_dir}")
+            if not self.dry_run:
+                _shutil.rmtree(self.bdist_dir)
+
+    def write_wheelfile(
+        self, wheelfile_base: str, generator: str = f"setuptools ({__version__})"
+    ) -> None:
+        from email.message import Message
+
+        msg = Message()
+        msg["Wheel-Version"] = "1.0"  # of the spec
+        msg["Generator"] = generator
+        msg["Root-Is-Purelib"] = str(self.root_is_pure).lower()
+        if self.build_number is not None:
+            msg["Build"] = self.build_number
+
+        # Doesn't work for bdist_wininst
+        impl_tag, abi_tag, plat_tag = self.get_tag()
+        for impl in impl_tag.split("."):
+            for abi in abi_tag.split("."):
+                for plat in plat_tag.split("."):
+                    msg["Tag"] = "-".join((impl, abi, plat))
+
+        wheelfile_path = os.path.join(wheelfile_base, "WHEEL")
+        log.info(f"creating {wheelfile_path}")
+        with open(wheelfile_path, "wb") as f:
+            BytesGenerator(f, maxheaderlen=0).flatten(msg)
+
+    def _ensure_relative(self, path: str) -> str:
+        # copied from dir_util, deleted
+        drive, path = os.path.splitdrive(path)
+        if path[0:1] == os.sep:
+            path = drive + path[1:]
+        return path
+
+    @property
+    def license_paths(self) -> Iterable[str]:
+        if setuptools_major_version >= 57:
+            # Setuptools has resolved any patterns to actual file names
+            return self.distribution.metadata.license_files or ()
+
+        files = set[str]()
+        metadata = self.distribution.get_option_dict("metadata")
+        if setuptools_major_version >= 42:
+            # Setuptools recognizes the license_files option but does not do globbing
+            patterns = cast(Sequence[str], self.distribution.metadata.license_files)
+        else:
+            # Prior to those, wheel is entirely responsible for handling license files
+            if "license_files" in metadata:
+                patterns = metadata["license_files"][1].split()
+            else:
+                patterns = ()
+
+        if "license_file" in metadata:
+            warnings.warn(
+                'The "license_file" option is deprecated. Use "license_files" instead.',
+                DeprecationWarning,
+                stacklevel=2,
+            )
+            files.add(metadata["license_file"][1])
+
+        if not files and not patterns and not isinstance(patterns, list):
+            patterns = ("LICEN[CS]E*", "COPYING*", "NOTICE*", "AUTHORS*")
+
+        for pattern in patterns:
+            for path in iglob(pattern):
+                if path.endswith("~"):
+                    log.debug(
+                        f'ignoring license file "{path}" as it looks like a backup'
+                    )
+                    continue
+
+                if path not in files and os.path.isfile(path):
+                    log.info(
+                        f'adding license file "{path}" (matched pattern "{pattern}")'
+                    )
+                    files.add(path)
+
+        return files
+
+    def egg2dist(self, egginfo_path: str, distinfo_path: str) -> None:
+        """Convert an .egg-info directory into a .dist-info directory"""
+
+        def adios(p: str) -> None:
+            """Appropriately delete directory, file or link."""
+            if os.path.exists(p) and not os.path.islink(p) and os.path.isdir(p):
+                _shutil.rmtree(p)
+            elif os.path.exists(p):
+                os.unlink(p)
+
+        adios(distinfo_path)
+
+        if not os.path.exists(egginfo_path):
+            # There is no egg-info. This is probably because the egg-info
+            # file/directory is not named matching the distribution name used
+            # to name the archive file. Check for this case and report
+            # accordingly.
+            import glob
+
+            pat = os.path.join(os.path.dirname(egginfo_path), "*.egg-info")
+            possible = glob.glob(pat)
+            err = f"Egg metadata expected at {egginfo_path} but not found"
+            if possible:
+                alt = os.path.basename(possible[0])
+                err += f" ({alt} found - possible misnamed archive file?)"
+
+            raise ValueError(err)
+
+        # .egg-info is a directory
+        pkginfo_path = os.path.join(egginfo_path, "PKG-INFO")
+
+        # ignore common egg metadata that is useless to wheel
+        shutil.copytree(
+            egginfo_path,
+            distinfo_path,
+            ignore=lambda x, y: {
+                "PKG-INFO",
+                "requires.txt",
+                "SOURCES.txt",
+                "not-zip-safe",
+            },
+        )
+
+        # delete dependency_links if it is only whitespace
+        dependency_links_path = os.path.join(distinfo_path, "dependency_links.txt")
+        with open(dependency_links_path, encoding="utf-8") as dependency_links_file:
+            dependency_links = dependency_links_file.read().strip()
+        if not dependency_links:
+            adios(dependency_links_path)
+
+        metadata_path = os.path.join(distinfo_path, "METADATA")
+        shutil.copy(pkginfo_path, metadata_path)
+
+        licenses_folder_path = os.path.join(distinfo_path, "licenses")
+        for license_path in self.license_paths:
+            safe_path = _safe_license_file(license_path)
+            dist_info_license_path = os.path.join(licenses_folder_path, safe_path)
+            os.makedirs(os.path.dirname(dist_info_license_path), exist_ok=True)
+            shutil.copy(license_path, dist_info_license_path)
+
+        adios(egginfo_path)
+
+    def _zip_compression(self) -> int:
+        if (
+            isinstance(self.compression, int)
+            and self.compression in self.supported_compressions.values()
+        ):
+            return self.compression
+
+        compression = self.supported_compressions.get(str(self.compression))
+        if compression is not None:
+            return compression
+
+        raise ValueError(f"Unsupported compression: {self.compression!r}")
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/build.py b/.venv/lib/python3.12/site-packages/setuptools/command/build.py
new file mode 100644
index 0000000000000000000000000000000000000000..54cbb8d2e7bf41de4e187613718879f2a4c3d8d3
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/command/build.py
@@ -0,0 +1,135 @@
+from __future__ import annotations
+
+from typing import Protocol
+
+from ..dist import Distribution
+
+from distutils.command.build import build as _build
+
+_ORIGINAL_SUBCOMMANDS = {"build_py", "build_clib", "build_ext", "build_scripts"}
+
+
+class build(_build):
+    distribution: Distribution  # override distutils.dist.Distribution with setuptools.dist.Distribution
+
+    # copy to avoid sharing the object with parent class
+    sub_commands = _build.sub_commands[:]
+
+
+class SubCommand(Protocol):
+    """In order to support editable installations (see :pep:`660`) all
+    build subcommands **SHOULD** implement this protocol. They also **MUST** inherit
+    from ``setuptools.Command``.
+
+    When creating an :pep:`editable wheel <660>`, ``setuptools`` will try to evaluate
+    custom ``build`` subcommands using the following procedure:
+
+    1. ``setuptools`` will set the ``editable_mode`` attribute to ``True``
+    2. ``setuptools`` will execute the ``run()`` command.
+
+       .. important::
+          Subcommands **SHOULD** take advantage of ``editable_mode=True`` to adequate
+          its behaviour or perform optimisations.
+
+          For example, if a subcommand doesn't need to generate an extra file and
+          all it does is to copy a source file into the build directory,
+          ``run()`` **SHOULD** simply "early return".
+
+          Similarly, if the subcommand creates files that would be placed alongside
+          Python files in the final distribution, during an editable install
+          the command **SHOULD** generate these files "in place" (i.e. write them to
+          the original source directory, instead of using the build directory).
+          Note that ``get_output_mapping()`` should reflect that and include mappings
+          for "in place" builds accordingly.
+
+    3. ``setuptools`` use any knowledge it can derive from the return values of
+       ``get_outputs()`` and ``get_output_mapping()`` to create an editable wheel.
+       When relevant ``setuptools`` **MAY** attempt to use file links based on the value
+       of ``get_output_mapping()``. Alternatively, ``setuptools`` **MAY** attempt to use
+       :doc:`import hooks ` to redirect any attempt to import
+       to the directory with the original source code and other files built in place.
+
+    Please note that custom sub-commands **SHOULD NOT** rely on ``run()`` being
+    executed (or not) to provide correct return values for ``get_outputs()``,
+    ``get_output_mapping()`` or ``get_source_files()``. The ``get_*`` methods should
+    work independently of ``run()``.
+    """
+
+    editable_mode: bool = False
+    """Boolean flag that will be set to ``True`` when setuptools is used for an
+    editable installation (see :pep:`660`).
+    Implementations **SHOULD** explicitly set the default value of this attribute to
+    ``False``.
+    When subcommands run, they can use this flag to perform optimizations or change
+    their behaviour accordingly.
+    """
+
+    build_lib: str
+    """String representing the directory where the build artifacts should be stored,
+    e.g. ``build/lib``.
+    For example, if a distribution wants to provide a Python module named ``pkg.mod``,
+    then a corresponding file should be written to ``{build_lib}/package/module.py``.
+    A way of thinking about this is that the files saved under ``build_lib``
+    would be eventually copied to one of the directories in :obj:`site.PREFIXES`
+    upon installation.
+
+    A command that produces platform-independent files (e.g. compiling text templates
+    into Python functions), **CAN** initialize ``build_lib`` by copying its value from
+    the ``build_py`` command. On the other hand, a command that produces
+    platform-specific files **CAN** initialize ``build_lib`` by copying its value from
+    the ``build_ext`` command. In general this is done inside the ``finalize_options``
+    method with the help of the ``set_undefined_options`` command::
+
+        def finalize_options(self):
+            self.set_undefined_options("build_py", ("build_lib", "build_lib"))
+            ...
+    """
+
+    def initialize_options(self) -> None:
+        """(Required by the original :class:`setuptools.Command` interface)"""
+        ...
+
+    def finalize_options(self) -> None:
+        """(Required by the original :class:`setuptools.Command` interface)"""
+        ...
+
+    def run(self) -> None:
+        """(Required by the original :class:`setuptools.Command` interface)"""
+        ...
+
+    def get_source_files(self) -> list[str]:
+        """
+        Return a list of all files that are used by the command to create the expected
+        outputs.
+        For example, if your build command transpiles Java files into Python, you should
+        list here all the Java files.
+        The primary purpose of this function is to help populating the ``sdist``
+        with all the files necessary to build the distribution.
+        All files should be strings relative to the project root directory.
+        """
+        ...
+
+    def get_outputs(self) -> list[str]:
+        """
+        Return a list of files intended for distribution as they would have been
+        produced by the build.
+        These files should be strings in the form of
+        ``"{build_lib}/destination/file/path"``.
+
+        .. note::
+           The return value of ``get_output()`` should include all files used as keys
+           in ``get_output_mapping()`` plus files that are generated during the build
+           and don't correspond to any source file already present in the project.
+        """
+        ...
+
+    def get_output_mapping(self) -> dict[str, str]:
+        """
+        Return a mapping between destination files as they would be produced by the
+        build (dict keys) into the respective existing (source) files (dict values).
+        Existing (source) files should be represented as strings relative to the project
+        root directory.
+        Destination files should be strings in the form of
+        ``"{build_lib}/destination/file/path"``.
+        """
+        ...
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/build_clib.py b/.venv/lib/python3.12/site-packages/setuptools/command/build_clib.py
new file mode 100644
index 0000000000000000000000000000000000000000..f376f4ce4d2afc4a58f1fa0e85624136edc93835
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/command/build_clib.py
@@ -0,0 +1,103 @@
+from ..dist import Distribution
+from ..modified import newer_pairwise_group
+
+import distutils.command.build_clib as orig
+from distutils import log
+from distutils.errors import DistutilsSetupError
+
+
+class build_clib(orig.build_clib):
+    """
+    Override the default build_clib behaviour to do the following:
+
+    1. Implement a rudimentary timestamp-based dependency system
+       so 'compile()' doesn't run every time.
+    2. Add more keys to the 'build_info' dictionary:
+        * obj_deps - specify dependencies for each object compiled.
+                     this should be a dictionary mapping a key
+                     with the source filename to a list of
+                     dependencies. Use an empty string for global
+                     dependencies.
+        * cflags   - specify a list of additional flags to pass to
+                     the compiler.
+    """
+
+    distribution: Distribution  # override distutils.dist.Distribution with setuptools.dist.Distribution
+
+    def build_libraries(self, libraries) -> None:
+        for lib_name, build_info in libraries:
+            sources = build_info.get('sources')
+            if sources is None or not isinstance(sources, (list, tuple)):
+                raise DistutilsSetupError(
+                    f"in 'libraries' option (library '{lib_name}'), "
+                    "'sources' must be present and must be "
+                    "a list of source filenames"
+                )
+            sources = sorted(list(sources))
+
+            log.info("building '%s' library", lib_name)
+
+            # Make sure everything is the correct type.
+            # obj_deps should be a dictionary of keys as sources
+            # and a list/tuple of files that are its dependencies.
+            obj_deps = build_info.get('obj_deps', dict())
+            if not isinstance(obj_deps, dict):
+                raise DistutilsSetupError(
+                    f"in 'libraries' option (library '{lib_name}'), "
+                    "'obj_deps' must be a dictionary of "
+                    "type 'source: list'"
+                )
+            dependencies = []
+
+            # Get the global dependencies that are specified by the '' key.
+            # These will go into every source's dependency list.
+            global_deps = obj_deps.get('', list())
+            if not isinstance(global_deps, (list, tuple)):
+                raise DistutilsSetupError(
+                    f"in 'libraries' option (library '{lib_name}'), "
+                    "'obj_deps' must be a dictionary of "
+                    "type 'source: list'"
+                )
+
+            # Build the list to be used by newer_pairwise_group
+            # each source will be auto-added to its dependencies.
+            for source in sources:
+                src_deps = [source]
+                src_deps.extend(global_deps)
+                extra_deps = obj_deps.get(source, list())
+                if not isinstance(extra_deps, (list, tuple)):
+                    raise DistutilsSetupError(
+                        f"in 'libraries' option (library '{lib_name}'), "
+                        "'obj_deps' must be a dictionary of "
+                        "type 'source: list'"
+                    )
+                src_deps.extend(extra_deps)
+                dependencies.append(src_deps)
+
+            expected_objects = self.compiler.object_filenames(
+                sources,
+                output_dir=self.build_temp,
+            )
+
+            if newer_pairwise_group(dependencies, expected_objects) != ([], []):
+                # First, compile the source code to object files in the library
+                # directory.  (This should probably change to putting object
+                # files in a temporary build directory.)
+                macros = build_info.get('macros')
+                include_dirs = build_info.get('include_dirs')
+                cflags = build_info.get('cflags')
+                self.compiler.compile(
+                    sources,
+                    output_dir=self.build_temp,
+                    macros=macros,
+                    include_dirs=include_dirs,
+                    extra_postargs=cflags,
+                    debug=self.debug,
+                )
+
+            # Now "link" the object files together into a static library.
+            # (On Unix at least, this isn't really linking -- it just
+            # builds an archive.  Whatever.)
+            self.compiler.create_static_lib(
+                expected_objects, lib_name, output_dir=self.build_clib, debug=self.debug
+            )
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/build_ext.py b/.venv/lib/python3.12/site-packages/setuptools/command/build_ext.py
new file mode 100644
index 0000000000000000000000000000000000000000..be833a379c71c3a6b1a85a89f8e9703c66d79824
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/command/build_ext.py
@@ -0,0 +1,469 @@
+from __future__ import annotations
+
+import itertools
+import os
+import sys
+from collections.abc import Iterator
+from importlib.machinery import EXTENSION_SUFFIXES
+from importlib.util import cache_from_source as _compiled_file_name
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+from setuptools.dist import Distribution
+from setuptools.errors import BaseError
+from setuptools.extension import Extension, Library
+
+from distutils import log
+from distutils.ccompiler import new_compiler
+from distutils.sysconfig import customize_compiler, get_config_var
+
+if TYPE_CHECKING:
+    # Cython not installed on CI tests, causing _build_ext to be `Any`
+    from distutils.command.build_ext import build_ext as _build_ext
+else:
+    try:
+        # Attempt to use Cython for building extensions, if available
+        from Cython.Distutils.build_ext import build_ext as _build_ext
+
+        # Additionally, assert that the compiler module will load
+        # also. Ref #1229.
+        __import__('Cython.Compiler.Main')
+    except ImportError:
+        from distutils.command.build_ext import build_ext as _build_ext
+
+# make sure _config_vars is initialized
+get_config_var("LDSHARED")
+# Not publicly exposed in typeshed distutils stubs, but this is done on purpose
+# See https://github.com/pypa/setuptools/pull/4228#issuecomment-1959856400
+from distutils.sysconfig import _config_vars as _CONFIG_VARS  # noqa: E402
+
+
+def _customize_compiler_for_shlib(compiler):
+    if sys.platform == "darwin":
+        # building .dylib requires additional compiler flags on OSX; here we
+        # temporarily substitute the pyconfig.h variables so that distutils'
+        # 'customize_compiler' uses them before we build the shared libraries.
+        tmp = _CONFIG_VARS.copy()
+        try:
+            # XXX Help!  I don't have any idea whether these are right...
+            _CONFIG_VARS['LDSHARED'] = (
+                "gcc -Wl,-x -dynamiclib -undefined dynamic_lookup"
+            )
+            _CONFIG_VARS['CCSHARED'] = " -dynamiclib"
+            _CONFIG_VARS['SO'] = ".dylib"
+            customize_compiler(compiler)
+        finally:
+            _CONFIG_VARS.clear()
+            _CONFIG_VARS.update(tmp)
+    else:
+        customize_compiler(compiler)
+
+
+have_rtld = False
+use_stubs = False
+libtype = 'shared'
+
+if sys.platform == "darwin":
+    use_stubs = True
+elif os.name != 'nt':
+    try:
+        import dl  # type: ignore[import-not-found] # https://github.com/python/mypy/issues/13002
+
+        use_stubs = have_rtld = hasattr(dl, 'RTLD_NOW')
+    except ImportError:
+        pass
+
+
+def if_dl(s):
+    return s if have_rtld else ''
+
+
+def get_abi3_suffix():
+    """Return the file extension for an abi3-compliant Extension()"""
+    for suffix in EXTENSION_SUFFIXES:
+        if '.abi3' in suffix:  # Unix
+            return suffix
+        elif suffix == '.pyd':  # Windows
+            return suffix
+    return None
+
+
+class build_ext(_build_ext):
+    distribution: Distribution  # override distutils.dist.Distribution with setuptools.dist.Distribution
+    editable_mode = False
+    inplace = False
+
+    def run(self):
+        """Build extensions in build directory, then copy if --inplace"""
+        old_inplace, self.inplace = self.inplace, False
+        _build_ext.run(self)
+        self.inplace = old_inplace
+        if old_inplace:
+            self.copy_extensions_to_source()
+
+    def _get_inplace_equivalent(self, build_py, ext: Extension) -> tuple[str, str]:
+        fullname = self.get_ext_fullname(ext.name)
+        filename = self.get_ext_filename(fullname)
+        modpath = fullname.split('.')
+        package = '.'.join(modpath[:-1])
+        package_dir = build_py.get_package_dir(package)
+        inplace_file = os.path.join(package_dir, os.path.basename(filename))
+        regular_file = os.path.join(self.build_lib, filename)
+        return (inplace_file, regular_file)
+
+    def copy_extensions_to_source(self) -> None:
+        build_py = self.get_finalized_command('build_py')
+        for ext in self.extensions:
+            inplace_file, regular_file = self._get_inplace_equivalent(build_py, ext)
+
+            # Always copy, even if source is older than destination, to ensure
+            # that the right extensions for the current Python/platform are
+            # used.
+            if os.path.exists(regular_file) or not ext.optional:
+                self.copy_file(regular_file, inplace_file, level=self.verbose)
+
+            if ext._needs_stub:
+                inplace_stub = self._get_equivalent_stub(ext, inplace_file)
+                self._write_stub_file(inplace_stub, ext, compile=True)
+                # Always compile stub and remove the original (leave the cache behind)
+                # (this behaviour was observed in previous iterations of the code)
+
+    def _get_equivalent_stub(self, ext: Extension, output_file: str) -> str:
+        dir_ = os.path.dirname(output_file)
+        _, _, name = ext.name.rpartition(".")
+        return f"{os.path.join(dir_, name)}.py"
+
+    def _get_output_mapping(self) -> Iterator[tuple[str, str]]:
+        if not self.inplace:
+            return
+
+        build_py = self.get_finalized_command('build_py')
+        opt = self.get_finalized_command('install_lib').optimize or ""
+
+        for ext in self.extensions:
+            inplace_file, regular_file = self._get_inplace_equivalent(build_py, ext)
+            yield (regular_file, inplace_file)
+
+            if ext._needs_stub:
+                # This version of `build_ext` always builds artifacts in another dir,
+                # when "inplace=True" is given it just copies them back.
+                # This is done in the `copy_extensions_to_source` function, which
+                # always compile stub files via `_compile_and_remove_stub`.
+                # At the end of the process, a `.pyc` stub file is created without the
+                # corresponding `.py`.
+
+                inplace_stub = self._get_equivalent_stub(ext, inplace_file)
+                regular_stub = self._get_equivalent_stub(ext, regular_file)
+                inplace_cache = _compiled_file_name(inplace_stub, optimization=opt)
+                output_cache = _compiled_file_name(regular_stub, optimization=opt)
+                yield (output_cache, inplace_cache)
+
+    def get_ext_filename(self, fullname: str) -> str:
+        so_ext = os.getenv('SETUPTOOLS_EXT_SUFFIX')
+        if so_ext:
+            filename = os.path.join(*fullname.split('.')) + so_ext
+        else:
+            filename = _build_ext.get_ext_filename(self, fullname)
+            ext_suffix = get_config_var('EXT_SUFFIX')
+            if not isinstance(ext_suffix, str):
+                raise OSError(
+                    "Configuration variable EXT_SUFFIX not found for this platform "
+                    "and environment variable SETUPTOOLS_EXT_SUFFIX is missing"
+                )
+            so_ext = ext_suffix
+
+        if fullname in self.ext_map:
+            ext = self.ext_map[fullname]
+            abi3_suffix = get_abi3_suffix()
+            if ext.py_limited_api and abi3_suffix:  # Use abi3
+                filename = filename[: -len(so_ext)] + abi3_suffix
+            if isinstance(ext, Library):
+                fn, ext = os.path.splitext(filename)
+                return self.shlib_compiler.library_filename(fn, libtype)
+            elif use_stubs and ext._links_to_dynamic:
+                d, fn = os.path.split(filename)
+                return os.path.join(d, 'dl-' + fn)
+        return filename
+
+    def initialize_options(self):
+        _build_ext.initialize_options(self)
+        self.shlib_compiler = None
+        self.shlibs = []
+        self.ext_map = {}
+        self.editable_mode = False
+
+    def finalize_options(self) -> None:
+        _build_ext.finalize_options(self)
+        self.extensions = self.extensions or []
+        self.check_extensions_list(self.extensions)
+        self.shlibs = [ext for ext in self.extensions if isinstance(ext, Library)]
+        if self.shlibs:
+            self.setup_shlib_compiler()
+        for ext in self.extensions:
+            ext._full_name = self.get_ext_fullname(ext.name)
+        for ext in self.extensions:
+            fullname = ext._full_name
+            self.ext_map[fullname] = ext
+
+            # distutils 3.1 will also ask for module names
+            # XXX what to do with conflicts?
+            self.ext_map[fullname.split('.')[-1]] = ext
+
+            ltd = self.shlibs and self.links_to_dynamic(ext) or False
+            ns = ltd and use_stubs and not isinstance(ext, Library)
+            ext._links_to_dynamic = ltd
+            ext._needs_stub = ns
+            filename = ext._file_name = self.get_ext_filename(fullname)
+            libdir = os.path.dirname(os.path.join(self.build_lib, filename))
+            if ltd and libdir not in ext.library_dirs:
+                ext.library_dirs.append(libdir)
+            if ltd and use_stubs and os.curdir not in ext.runtime_library_dirs:
+                ext.runtime_library_dirs.append(os.curdir)
+
+        if self.editable_mode:
+            self.inplace = True
+
+    def setup_shlib_compiler(self):
+        compiler = self.shlib_compiler = new_compiler(
+            compiler=self.compiler, dry_run=self.dry_run, force=self.force
+        )
+        _customize_compiler_for_shlib(compiler)
+
+        if self.include_dirs is not None:
+            compiler.set_include_dirs(self.include_dirs)
+        if self.define is not None:
+            # 'define' option is a list of (name,value) tuples
+            for name, value in self.define:
+                compiler.define_macro(name, value)
+        if self.undef is not None:
+            for macro in self.undef:
+                compiler.undefine_macro(macro)
+        if self.libraries is not None:
+            compiler.set_libraries(self.libraries)
+        if self.library_dirs is not None:
+            compiler.set_library_dirs(self.library_dirs)
+        if self.rpath is not None:
+            compiler.set_runtime_library_dirs(self.rpath)
+        if self.link_objects is not None:
+            compiler.set_link_objects(self.link_objects)
+
+        # hack so distutils' build_extension() builds a library instead
+        compiler.link_shared_object = link_shared_object.__get__(compiler)  # type: ignore[method-assign]
+
+    def get_export_symbols(self, ext):
+        if isinstance(ext, Library):
+            return ext.export_symbols
+        return _build_ext.get_export_symbols(self, ext)
+
+    def build_extension(self, ext) -> None:
+        ext._convert_pyx_sources_to_lang()
+        _compiler = self.compiler
+        try:
+            if isinstance(ext, Library):
+                self.compiler = self.shlib_compiler
+            _build_ext.build_extension(self, ext)
+            if ext._needs_stub:
+                build_lib = self.get_finalized_command('build_py').build_lib
+                self.write_stub(build_lib, ext)
+        finally:
+            self.compiler = _compiler
+
+    def links_to_dynamic(self, ext):
+        """Return true if 'ext' links to a dynamic lib in the same package"""
+        # XXX this should check to ensure the lib is actually being built
+        # XXX as dynamic, and not just using a locally-found version or a
+        # XXX static-compiled version
+        libnames = dict.fromkeys([lib._full_name for lib in self.shlibs])
+        pkg = '.'.join(ext._full_name.split('.')[:-1] + [''])
+        return any(pkg + libname in libnames for libname in ext.libraries)
+
+    def get_source_files(self) -> list[str]:
+        return [*_build_ext.get_source_files(self), *self._get_internal_depends()]
+
+    def _get_internal_depends(self) -> Iterator[str]:
+        """Yield ``ext.depends`` that are contained by the project directory"""
+        project_root = Path(self.distribution.src_root or os.curdir).resolve()
+        depends = (dep for ext in self.extensions for dep in ext.depends)
+
+        def skip(orig_path: str, reason: str) -> None:
+            log.info(
+                "dependency %s won't be automatically "
+                "included in the manifest: the path %s",
+                orig_path,
+                reason,
+            )
+
+        for dep in depends:
+            path = Path(dep)
+
+            if path.is_absolute():
+                skip(dep, "must be relative")
+                continue
+
+            if ".." in path.parts:
+                skip(dep, "can't have `..` segments")
+                continue
+
+            try:
+                resolved = (project_root / path).resolve(strict=True)
+            except OSError:
+                skip(dep, "doesn't exist")
+                continue
+
+            try:
+                resolved.relative_to(project_root)
+            except ValueError:
+                skip(dep, "must be inside the project root")
+                continue
+
+            yield path.as_posix()
+
+    def get_outputs(self) -> list[str]:
+        if self.inplace:
+            return list(self.get_output_mapping().keys())
+        return sorted(_build_ext.get_outputs(self) + self.__get_stubs_outputs())
+
+    def get_output_mapping(self) -> dict[str, str]:
+        """See :class:`setuptools.commands.build.SubCommand`"""
+        mapping = self._get_output_mapping()
+        return dict(sorted(mapping, key=lambda x: x[0]))
+
+    def __get_stubs_outputs(self):
+        # assemble the base name for each extension that needs a stub
+        ns_ext_bases = (
+            os.path.join(self.build_lib, *ext._full_name.split('.'))
+            for ext in self.extensions
+            if ext._needs_stub
+        )
+        # pair each base with the extension
+        pairs = itertools.product(ns_ext_bases, self.__get_output_extensions())
+        return list(base + fnext for base, fnext in pairs)
+
+    def __get_output_extensions(self):
+        yield '.py'
+        yield '.pyc'
+        if self.get_finalized_command('build_py').optimize:
+            yield '.pyo'
+
+    def write_stub(self, output_dir, ext, compile=False) -> None:
+        stub_file = os.path.join(output_dir, *ext._full_name.split('.')) + '.py'
+        self._write_stub_file(stub_file, ext, compile)
+
+    def _write_stub_file(self, stub_file: str, ext: Extension, compile=False):
+        log.info("writing stub loader for %s to %s", ext._full_name, stub_file)
+        if compile and os.path.exists(stub_file):
+            raise BaseError(stub_file + " already exists! Please delete.")
+        if not self.dry_run:
+            with open(stub_file, 'w', encoding="utf-8") as f:
+                content = '\n'.join([
+                    "def __bootstrap__():",
+                    "   global __bootstrap__, __file__, __loader__",
+                    "   import sys, os, pkg_resources, importlib.util" + if_dl(", dl"),
+                    "   __file__ = pkg_resources.resource_filename"
+                    f"(__name__,{os.path.basename(ext._file_name)!r})",
+                    "   del __bootstrap__",
+                    "   if '__loader__' in globals():",
+                    "       del __loader__",
+                    if_dl("   old_flags = sys.getdlopenflags()"),
+                    "   old_dir = os.getcwd()",
+                    "   try:",
+                    "     os.chdir(os.path.dirname(__file__))",
+                    if_dl("     sys.setdlopenflags(dl.RTLD_NOW)"),
+                    "     spec = importlib.util.spec_from_file_location(",
+                    "                __name__, __file__)",
+                    "     mod = importlib.util.module_from_spec(spec)",
+                    "     spec.loader.exec_module(mod)",
+                    "   finally:",
+                    if_dl("     sys.setdlopenflags(old_flags)"),
+                    "     os.chdir(old_dir)",
+                    "__bootstrap__()",
+                    "",  # terminal \n
+                ])
+                f.write(content)
+        if compile:
+            self._compile_and_remove_stub(stub_file)
+
+    def _compile_and_remove_stub(self, stub_file: str):
+        from distutils.util import byte_compile
+
+        byte_compile([stub_file], optimize=0, force=True, dry_run=self.dry_run)
+        optimize = self.get_finalized_command('install_lib').optimize
+        if optimize > 0:
+            byte_compile(
+                [stub_file],
+                optimize=optimize,
+                force=True,
+                dry_run=self.dry_run,
+            )
+        if os.path.exists(stub_file) and not self.dry_run:
+            os.unlink(stub_file)
+
+
+if use_stubs or os.name == 'nt':
+    # Build shared libraries
+    #
+    def link_shared_object(
+        self,
+        objects,
+        output_libname,
+        output_dir=None,
+        libraries=None,
+        library_dirs=None,
+        runtime_library_dirs=None,
+        export_symbols=None,
+        debug: bool = False,
+        extra_preargs=None,
+        extra_postargs=None,
+        build_temp=None,
+        target_lang=None,
+    ) -> None:
+        self.link(
+            self.SHARED_LIBRARY,
+            objects,
+            output_libname,
+            output_dir,
+            libraries,
+            library_dirs,
+            runtime_library_dirs,
+            export_symbols,
+            debug,
+            extra_preargs,
+            extra_postargs,
+            build_temp,
+            target_lang,
+        )
+
+else:
+    # Build static libraries everywhere else
+    libtype = 'static'
+
+    def link_shared_object(
+        self,
+        objects,
+        output_libname,
+        output_dir=None,
+        libraries=None,
+        library_dirs=None,
+        runtime_library_dirs=None,
+        export_symbols=None,
+        debug: bool = False,
+        extra_preargs=None,
+        extra_postargs=None,
+        build_temp=None,
+        target_lang=None,
+    ) -> None:
+        # XXX we need to either disallow these attrs on Library instances,
+        # or warn/abort here if set, or something...
+        # libraries=None, library_dirs=None, runtime_library_dirs=None,
+        # export_symbols=None, extra_preargs=None, extra_postargs=None,
+        # build_temp=None
+
+        assert output_dir is None  # distutils build_ext doesn't pass this
+        output_dir, filename = os.path.split(output_libname)
+        basename, _ext = os.path.splitext(filename)
+        if self.library_filename("x").startswith('lib'):
+            # strip 'lib' prefix; this is kludgy if some platform uses
+            # a different prefix
+            basename = basename[3:]
+
+        self.create_static_lib(objects, basename, output_dir, debug, target_lang)
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/build_py.py b/.venv/lib/python3.12/site-packages/setuptools/command/build_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..2f6fcb7cdcb39a61007acbb399c84125cce93c9f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/command/build_py.py
@@ -0,0 +1,400 @@
+from __future__ import annotations
+
+import fnmatch
+import itertools
+import os
+import stat
+import textwrap
+from collections.abc import Iterable, Iterator
+from functools import partial
+from glob import glob
+from pathlib import Path
+
+from more_itertools import unique_everseen
+
+from .._path import StrPath, StrPathT
+from ..dist import Distribution
+from ..warnings import SetuptoolsDeprecationWarning
+
+import distutils.command.build_py as orig
+import distutils.errors
+from distutils.util import convert_path
+
+_IMPLICIT_DATA_FILES = ('*.pyi', 'py.typed')
+
+
+def make_writable(target) -> None:
+    os.chmod(target, os.stat(target).st_mode | stat.S_IWRITE)
+
+
+class build_py(orig.build_py):
+    """Enhanced 'build_py' command that includes data files with packages
+
+    The data files are specified via a 'package_data' argument to 'setup()'.
+    See 'setuptools.dist.Distribution' for more details.
+
+    Also, this version of the 'build_py' command allows you to specify both
+    'py_modules' and 'packages' in the same setup operation.
+    """
+
+    distribution: Distribution  # override distutils.dist.Distribution with setuptools.dist.Distribution
+    editable_mode: bool = False
+    existing_egg_info_dir: StrPath | None = None  #: Private API, internal use only.
+
+    def finalize_options(self):
+        orig.build_py.finalize_options(self)
+        self.package_data = self.distribution.package_data
+        self.exclude_package_data = self.distribution.exclude_package_data or {}
+        if 'data_files' in self.__dict__:
+            del self.__dict__['data_files']
+
+    def copy_file(  # type: ignore[override] # No overload, no bytes support
+        self,
+        infile: StrPath,
+        outfile: StrPathT,
+        preserve_mode: bool = True,
+        preserve_times: bool = True,
+        link: str | None = None,
+        level: object = 1,
+    ) -> tuple[StrPathT | str, bool]:
+        # Overwrite base class to allow using links
+        if link:
+            infile = str(Path(infile).resolve())
+            outfile = str(Path(outfile).resolve())  # type: ignore[assignment] # Re-assigning a str when outfile is StrPath is ok
+        return super().copy_file(  # pyright: ignore[reportReturnType] # pypa/distutils#309
+            infile, outfile, preserve_mode, preserve_times, link, level
+        )
+
+    def run(self) -> None:
+        """Build modules, packages, and copy data files to build directory"""
+        if not (self.py_modules or self.packages) or self.editable_mode:
+            return
+
+        if self.py_modules:
+            self.build_modules()
+
+        if self.packages:
+            self.build_packages()
+            self.build_package_data()
+
+        # Only compile actual .py files, using our base class' idea of what our
+        # output files are.
+        self.byte_compile(orig.build_py.get_outputs(self, include_bytecode=False))
+
+    def __getattr__(self, attr: str):
+        "lazily compute data files"
+        if attr == 'data_files':
+            self.data_files = self._get_data_files()
+            return self.data_files
+        return orig.build_py.__getattr__(self, attr)
+
+    def _get_data_files(self):
+        """Generate list of '(package,src_dir,build_dir,filenames)' tuples"""
+        self.analyze_manifest()
+        return list(map(self._get_pkg_data_files, self.packages or ()))
+
+    def get_data_files_without_manifest(self):
+        """
+        Generate list of ``(package,src_dir,build_dir,filenames)`` tuples,
+        but without triggering any attempt to analyze or build the manifest.
+        """
+        # Prevent eventual errors from unset `manifest_files`
+        # (that would otherwise be set by `analyze_manifest`)
+        self.__dict__.setdefault('manifest_files', {})
+        return list(map(self._get_pkg_data_files, self.packages or ()))
+
+    def _get_pkg_data_files(self, package):
+        # Locate package source directory
+        src_dir = self.get_package_dir(package)
+
+        # Compute package build directory
+        build_dir = os.path.join(*([self.build_lib] + package.split('.')))
+
+        # Strip directory from globbed filenames
+        filenames = [
+            os.path.relpath(file, src_dir)
+            for file in self.find_data_files(package, src_dir)
+        ]
+        return package, src_dir, build_dir, filenames
+
+    def find_data_files(self, package, src_dir):
+        """Return filenames for package's data files in 'src_dir'"""
+        patterns = self._get_platform_patterns(
+            self.package_data,
+            package,
+            src_dir,
+            extra_patterns=_IMPLICIT_DATA_FILES,
+        )
+        globs_expanded = map(partial(glob, recursive=True), patterns)
+        # flatten the expanded globs into an iterable of matches
+        globs_matches = itertools.chain.from_iterable(globs_expanded)
+        glob_files = filter(os.path.isfile, globs_matches)
+        files = itertools.chain(
+            self.manifest_files.get(package, []),
+            glob_files,
+        )
+        return self.exclude_data_files(package, src_dir, files)
+
+    def get_outputs(self, include_bytecode: bool = True) -> list[str]:  # type: ignore[override] # Using a real boolean instead of 0|1
+        """See :class:`setuptools.commands.build.SubCommand`"""
+        if self.editable_mode:
+            return list(self.get_output_mapping().keys())
+        return super().get_outputs(include_bytecode)
+
+    def get_output_mapping(self) -> dict[str, str]:
+        """See :class:`setuptools.commands.build.SubCommand`"""
+        mapping = itertools.chain(
+            self._get_package_data_output_mapping(),
+            self._get_module_mapping(),
+        )
+        return dict(sorted(mapping, key=lambda x: x[0]))
+
+    def _get_module_mapping(self) -> Iterator[tuple[str, str]]:
+        """Iterate over all modules producing (dest, src) pairs."""
+        for package, module, module_file in self.find_all_modules():
+            package = package.split('.')
+            filename = self.get_module_outfile(self.build_lib, package, module)
+            yield (filename, module_file)
+
+    def _get_package_data_output_mapping(self) -> Iterator[tuple[str, str]]:
+        """Iterate over package data producing (dest, src) pairs."""
+        for package, src_dir, build_dir, filenames in self.data_files:
+            for filename in filenames:
+                target = os.path.join(build_dir, filename)
+                srcfile = os.path.join(src_dir, filename)
+                yield (target, srcfile)
+
+    def build_package_data(self) -> None:
+        """Copy data files into build directory"""
+        for target, srcfile in self._get_package_data_output_mapping():
+            self.mkpath(os.path.dirname(target))
+            _outf, _copied = self.copy_file(srcfile, target)
+            make_writable(target)
+
+    def analyze_manifest(self) -> None:
+        self.manifest_files: dict[str, list[str]] = {}
+        if not self.distribution.include_package_data:
+            return
+        src_dirs: dict[str, str] = {}
+        for package in self.packages or ():
+            # Locate package source directory
+            src_dirs[assert_relative(self.get_package_dir(package))] = package
+
+        if (
+            self.existing_egg_info_dir
+            and Path(self.existing_egg_info_dir, "SOURCES.txt").exists()
+        ):
+            egg_info_dir = self.existing_egg_info_dir
+            manifest = Path(egg_info_dir, "SOURCES.txt")
+            files = manifest.read_text(encoding="utf-8").splitlines()
+        else:
+            self.run_command('egg_info')
+            ei_cmd = self.get_finalized_command('egg_info')
+            egg_info_dir = ei_cmd.egg_info
+            files = ei_cmd.filelist.files
+
+        check = _IncludePackageDataAbuse()
+        for path in self._filter_build_files(files, egg_info_dir):
+            d, f = os.path.split(assert_relative(path))
+            prev = None
+            oldf = f
+            while d and d != prev and d not in src_dirs:
+                prev = d
+                d, df = os.path.split(d)
+                f = os.path.join(df, f)
+            if d in src_dirs:
+                if f == oldf:
+                    if check.is_module(f):
+                        continue  # it's a module, not data
+                else:
+                    importable = check.importable_subpackage(src_dirs[d], f)
+                    if importable:
+                        check.warn(importable)
+                self.manifest_files.setdefault(src_dirs[d], []).append(path)
+
+    def _filter_build_files(
+        self, files: Iterable[str], egg_info: StrPath
+    ) -> Iterator[str]:
+        """
+        ``build_meta`` may try to create egg_info outside of the project directory,
+        and this can be problematic for certain plugins (reported in issue #3500).
+
+        Extensions might also include between their sources files created on the
+        ``build_lib`` and ``build_temp`` directories.
+
+        This function should filter this case of invalid files out.
+        """
+        build = self.get_finalized_command("build")
+        build_dirs = (egg_info, self.build_lib, build.build_temp, build.build_base)
+        norm_dirs = [os.path.normpath(p) for p in build_dirs if p]
+
+        for file in files:
+            norm_path = os.path.normpath(file)
+            if not os.path.isabs(file) or all(d not in norm_path for d in norm_dirs):
+                yield file
+
+    def get_data_files(self) -> None:
+        pass  # Lazily compute data files in _get_data_files() function.
+
+    def check_package(self, package, package_dir):
+        """Check namespace packages' __init__ for declare_namespace"""
+        try:
+            return self.packages_checked[package]
+        except KeyError:
+            pass
+
+        init_py = orig.build_py.check_package(self, package, package_dir)
+        self.packages_checked[package] = init_py
+
+        if not init_py or not self.distribution.namespace_packages:
+            return init_py
+
+        for pkg in self.distribution.namespace_packages:
+            if pkg == package or pkg.startswith(package + '.'):
+                break
+        else:
+            return init_py
+
+        with open(init_py, 'rb') as f:
+            contents = f.read()
+        if b'declare_namespace' not in contents:
+            raise distutils.errors.DistutilsError(
+                f"Namespace package problem: {package} is a namespace package, but "
+                "its\n__init__.py does not call declare_namespace()! Please "
+                'fix it.\n(See the setuptools manual under '
+                '"Namespace Packages" for details.)\n"'
+            )
+        return init_py
+
+    def initialize_options(self):
+        self.packages_checked = {}
+        orig.build_py.initialize_options(self)
+        self.editable_mode = False
+        self.existing_egg_info_dir = None
+
+    def get_package_dir(self, package):
+        res = orig.build_py.get_package_dir(self, package)
+        if self.distribution.src_root is not None:
+            return os.path.join(self.distribution.src_root, res)
+        return res
+
+    def exclude_data_files(self, package, src_dir, files):
+        """Filter filenames for package's data files in 'src_dir'"""
+        files = list(files)
+        patterns = self._get_platform_patterns(
+            self.exclude_package_data,
+            package,
+            src_dir,
+        )
+        match_groups = (fnmatch.filter(files, pattern) for pattern in patterns)
+        # flatten the groups of matches into an iterable of matches
+        matches = itertools.chain.from_iterable(match_groups)
+        bad = set(matches)
+        keepers = (fn for fn in files if fn not in bad)
+        # ditch dupes
+        return list(unique_everseen(keepers))
+
+    @staticmethod
+    def _get_platform_patterns(spec, package, src_dir, extra_patterns=()):
+        """
+        yield platform-specific path patterns (suitable for glob
+        or fn_match) from a glob-based spec (such as
+        self.package_data or self.exclude_package_data)
+        matching package in src_dir.
+        """
+        raw_patterns = itertools.chain(
+            extra_patterns,
+            spec.get('', []),
+            spec.get(package, []),
+        )
+        return (
+            # Each pattern has to be converted to a platform-specific path
+            os.path.join(src_dir, convert_path(pattern))
+            for pattern in raw_patterns
+        )
+
+
+def assert_relative(path):
+    if not os.path.isabs(path):
+        return path
+    from distutils.errors import DistutilsSetupError
+
+    msg = (
+        textwrap.dedent(
+            """
+        Error: setup script specifies an absolute path:
+
+            %s
+
+        setup() arguments must *always* be /-separated paths relative to the
+        setup.py directory, *never* absolute paths.
+        """
+        ).lstrip()
+        % path
+    )
+    raise DistutilsSetupError(msg)
+
+
+class _IncludePackageDataAbuse:
+    """Inform users that package or module is included as 'data file'"""
+
+    class _Warning(SetuptoolsDeprecationWarning):
+        _SUMMARY = """
+        Package {importable!r} is absent from the `packages` configuration.
+        """
+
+        _DETAILS = """
+        ############################
+        # Package would be ignored #
+        ############################
+        Python recognizes {importable!r} as an importable package[^1],
+        but it is absent from setuptools' `packages` configuration.
+
+        This leads to an ambiguous overall configuration. If you want to distribute this
+        package, please make sure that {importable!r} is explicitly added
+        to the `packages` configuration field.
+
+        Alternatively, you can also rely on setuptools' discovery methods
+        (for example by using `find_namespace_packages(...)`/`find_namespace:`
+        instead of `find_packages(...)`/`find:`).
+
+        You can read more about "package discovery" on setuptools documentation page:
+
+        - https://setuptools.pypa.io/en/latest/userguide/package_discovery.html
+
+        If you don't want {importable!r} to be distributed and are
+        already explicitly excluding {importable!r} via
+        `find_namespace_packages(...)/find_namespace` or `find_packages(...)/find`,
+        you can try to use `exclude_package_data`, or `include-package-data=False` in
+        combination with a more fine grained `package-data` configuration.
+
+        You can read more about "package data files" on setuptools documentation page:
+
+        - https://setuptools.pypa.io/en/latest/userguide/datafiles.html
+
+
+        [^1]: For Python, any directory (with suitable naming) can be imported,
+              even if it does not contain any `.py` files.
+              On the other hand, currently there is no concept of package data
+              directory, all directories are treated like packages.
+        """
+        # _DUE_DATE: still not defined as this is particularly controversial.
+        # Warning initially introduced in May 2022. See issue #3340 for discussion.
+
+    def __init__(self):
+        self._already_warned = set()
+
+    def is_module(self, file):
+        return file.endswith(".py") and file[: -len(".py")].isidentifier()
+
+    def importable_subpackage(self, parent, file):
+        pkg = Path(file).parent
+        parts = list(itertools.takewhile(str.isidentifier, pkg.parts))
+        if parts:
+            return ".".join([parent, *parts])
+        return None
+
+    def warn(self, importable):
+        if importable not in self._already_warned:
+            self._Warning.emit(importable=importable)
+            self._already_warned.add(importable)
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/develop.py b/.venv/lib/python3.12/site-packages/setuptools/command/develop.py
new file mode 100644
index 0000000000000000000000000000000000000000..7eee29d491f72d8b0869493013a781d88c0aa3cd
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/command/develop.py
@@ -0,0 +1,195 @@
+import glob
+import os
+
+import setuptools
+from setuptools import _normalization, _path, namespaces
+from setuptools.command.easy_install import easy_install
+
+from ..unicode_utils import _read_utf8_with_fallback
+
+from distutils import log
+from distutils.errors import DistutilsOptionError
+from distutils.util import convert_path
+
+
+class develop(namespaces.DevelopInstaller, easy_install):
+    """Set up package for development"""
+
+    description = "install package in 'development mode'"
+
+    user_options = easy_install.user_options + [
+        ("uninstall", "u", "Uninstall this source package"),
+        ("egg-path=", None, "Set the path to be used in the .egg-link file"),
+    ]
+
+    boolean_options = easy_install.boolean_options + ['uninstall']
+
+    command_consumes_arguments = False  # override base
+
+    def run(self):
+        if self.uninstall:
+            self.multi_version = True
+            self.uninstall_link()
+            self.uninstall_namespaces()
+        else:
+            self.install_for_development()
+        self.warn_deprecated_options()
+
+    def initialize_options(self):
+        self.uninstall = None
+        self.egg_path = None
+        easy_install.initialize_options(self)
+        self.setup_path = None
+        self.always_copy_from = '.'  # always copy eggs installed in curdir
+
+    def finalize_options(self) -> None:
+        import pkg_resources
+
+        ei = self.get_finalized_command("egg_info")
+        self.args = [ei.egg_name]
+
+        easy_install.finalize_options(self)
+        self.expand_basedirs()
+        self.expand_dirs()
+        # pick up setup-dir .egg files only: no .egg-info
+        self.package_index.scan(glob.glob('*.egg'))
+
+        egg_link_fn = (
+            _normalization.filename_component_broken(ei.egg_name) + '.egg-link'
+        )
+        self.egg_link = os.path.join(self.install_dir, egg_link_fn)
+        self.egg_base = ei.egg_base
+        if self.egg_path is None:
+            self.egg_path = os.path.abspath(ei.egg_base)
+
+        target = _path.normpath(self.egg_base)
+        egg_path = _path.normpath(os.path.join(self.install_dir, self.egg_path))
+        if egg_path != target:
+            raise DistutilsOptionError(
+                "--egg-path must be a relative path from the install"
+                " directory to " + target
+            )
+
+        # Make a distribution for the package's source
+        self.dist = pkg_resources.Distribution(
+            target,
+            pkg_resources.PathMetadata(target, os.path.abspath(ei.egg_info)),
+            project_name=ei.egg_name,
+        )
+
+        self.setup_path = self._resolve_setup_path(
+            self.egg_base,
+            self.install_dir,
+            self.egg_path,
+        )
+
+    @staticmethod
+    def _resolve_setup_path(egg_base, install_dir, egg_path):
+        """
+        Generate a path from egg_base back to '.' where the
+        setup script resides and ensure that path points to the
+        setup path from $install_dir/$egg_path.
+        """
+        path_to_setup = egg_base.replace(os.sep, '/').rstrip('/')
+        if path_to_setup != os.curdir:
+            path_to_setup = '../' * (path_to_setup.count('/') + 1)
+        resolved = _path.normpath(os.path.join(install_dir, egg_path, path_to_setup))
+        curdir = _path.normpath(os.curdir)
+        if resolved != curdir:
+            raise DistutilsOptionError(
+                "Can't get a consistent path to setup script from"
+                " installation directory",
+                resolved,
+                curdir,
+            )
+        return path_to_setup
+
+    def install_for_development(self) -> None:
+        self.run_command('egg_info')
+
+        # Build extensions in-place
+        self.reinitialize_command('build_ext', inplace=True)
+        self.run_command('build_ext')
+
+        if setuptools.bootstrap_install_from:
+            self.easy_install(setuptools.bootstrap_install_from)
+            setuptools.bootstrap_install_from = None
+
+        self.install_namespaces()
+
+        # create an .egg-link in the installation dir, pointing to our egg
+        log.info("Creating %s (link to %s)", self.egg_link, self.egg_base)
+        if not self.dry_run:
+            with open(self.egg_link, "w", encoding="utf-8") as f:
+                f.write(self.egg_path + "\n" + self.setup_path)
+        # postprocess the installed distro, fixing up .pth, installing scripts,
+        # and handling requirements
+        self.process_distribution(None, self.dist, not self.no_deps)
+
+    def uninstall_link(self) -> None:
+        if os.path.exists(self.egg_link):
+            log.info("Removing %s (link to %s)", self.egg_link, self.egg_base)
+
+            contents = [
+                line.rstrip()
+                for line in _read_utf8_with_fallback(self.egg_link).splitlines()
+            ]
+
+            if contents not in ([self.egg_path], [self.egg_path, self.setup_path]):
+                log.warn("Link points to %s: uninstall aborted", contents)
+                return
+            if not self.dry_run:
+                os.unlink(self.egg_link)
+        if not self.dry_run:
+            self.update_pth(self.dist)  # remove any .pth link to us
+        if self.distribution.scripts:
+            # XXX should also check for entry point scripts!
+            log.warn("Note: you must uninstall or replace scripts manually!")
+
+    def install_egg_scripts(self, dist):
+        if dist is not self.dist:
+            # Installing a dependency, so fall back to normal behavior
+            return easy_install.install_egg_scripts(self, dist)
+
+        # create wrapper scripts in the script dir, pointing to dist.scripts
+
+        # new-style...
+        self.install_wrapper_scripts(dist)
+
+        # ...and old-style
+        for script_name in self.distribution.scripts or []:
+            script_path = os.path.abspath(convert_path(script_name))
+            script_name = os.path.basename(script_path)
+            script_text = _read_utf8_with_fallback(script_path)
+            self.install_script(dist, script_name, script_text, script_path)
+
+        return None
+
+    def install_wrapper_scripts(self, dist):
+        dist = VersionlessRequirement(dist)
+        return easy_install.install_wrapper_scripts(self, dist)
+
+
+class VersionlessRequirement:
+    """
+    Adapt a pkg_resources.Distribution to simply return the project
+    name as the 'requirement' so that scripts will work across
+    multiple versions.
+
+    >>> from pkg_resources import Distribution
+    >>> dist = Distribution(project_name='foo', version='1.0')
+    >>> str(dist.as_requirement())
+    'foo==1.0'
+    >>> adapted_dist = VersionlessRequirement(dist)
+    >>> str(adapted_dist.as_requirement())
+    'foo'
+    """
+
+    def __init__(self, dist) -> None:
+        self.__dist = dist
+
+    def __getattr__(self, name: str):
+        return getattr(self.__dist, name)
+
+    def as_requirement(self):
+        return self.project_name
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/dist_info.py b/.venv/lib/python3.12/site-packages/setuptools/command/dist_info.py
new file mode 100644
index 0000000000000000000000000000000000000000..dca01ff0ce355dfd375512e4a06b05b909ee41b6
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/command/dist_info.py
@@ -0,0 +1,103 @@
+"""
+Create a dist_info directory
+As defined in the wheel specification
+"""
+
+import os
+import shutil
+from contextlib import contextmanager
+from pathlib import Path
+from typing import cast
+
+from .. import _normalization
+from .._shutil import rmdir as _rm
+from .egg_info import egg_info as egg_info_cls
+
+from distutils import log
+from distutils.core import Command
+
+
+class dist_info(Command):
+    """
+    This command is private and reserved for internal use of setuptools,
+    users should rely on ``setuptools.build_meta`` APIs.
+    """
+
+    description = "DO NOT CALL DIRECTLY, INTERNAL ONLY: create .dist-info directory"
+
+    user_options = [
+        (
+            'output-dir=',
+            'o',
+            "directory inside of which the .dist-info will be"
+            "created [default: top of the source tree]",
+        ),
+        ('tag-date', 'd', "Add date stamp (e.g. 20050528) to version number"),
+        ('tag-build=', 'b', "Specify explicit tag to add to version number"),
+        ('no-date', 'D', "Don't include date stamp [default]"),
+        ('keep-egg-info', None, "*TRANSITIONAL* will be removed in the future"),
+    ]
+
+    boolean_options = ['tag-date', 'keep-egg-info']
+    negative_opt = {'no-date': 'tag-date'}
+
+    def initialize_options(self):
+        self.output_dir = None
+        self.name = None
+        self.dist_info_dir = None
+        self.tag_date = None
+        self.tag_build = None
+        self.keep_egg_info = False
+
+    def finalize_options(self) -> None:
+        dist = self.distribution
+        project_dir = dist.src_root or os.curdir
+        self.output_dir = Path(self.output_dir or project_dir)
+
+        egg_info = cast(egg_info_cls, self.reinitialize_command("egg_info"))
+        egg_info.egg_base = str(self.output_dir)
+
+        if self.tag_date:
+            egg_info.tag_date = self.tag_date
+        else:
+            self.tag_date = egg_info.tag_date
+
+        if self.tag_build:
+            egg_info.tag_build = self.tag_build
+        else:
+            self.tag_build = egg_info.tag_build
+
+        egg_info.finalize_options()
+        self.egg_info = egg_info
+
+        name = _normalization.safer_name(dist.get_name())
+        version = _normalization.safer_best_effort_version(dist.get_version())
+        self.name = f"{name}-{version}"
+        self.dist_info_dir = os.path.join(self.output_dir, f"{self.name}.dist-info")
+
+    @contextmanager
+    def _maybe_bkp_dir(self, dir_path: str, requires_bkp: bool):
+        if requires_bkp:
+            bkp_name = f"{dir_path}.__bkp__"
+            _rm(bkp_name, ignore_errors=True)
+            shutil.copytree(dir_path, bkp_name, dirs_exist_ok=True, symlinks=True)
+            try:
+                yield
+            finally:
+                _rm(dir_path, ignore_errors=True)
+                shutil.move(bkp_name, dir_path)
+        else:
+            yield
+
+    def run(self) -> None:
+        self.output_dir.mkdir(parents=True, exist_ok=True)
+        self.egg_info.run()
+        egg_info_dir = self.egg_info.egg_info
+        assert os.path.isdir(egg_info_dir), ".egg-info dir should have been created"
+
+        log.info(f"creating '{os.path.abspath(self.dist_info_dir)}'")
+        bdist_wheel = self.get_finalized_command('bdist_wheel')
+
+        # TODO: if bdist_wheel if merged into setuptools, just add "keep_egg_info" there
+        with self._maybe_bkp_dir(egg_info_dir, self.keep_egg_info):
+            bdist_wheel.egg2dist(egg_info_dir, self.dist_info_dir)
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/easy_install.py b/.venv/lib/python3.12/site-packages/setuptools/command/easy_install.py
new file mode 100644
index 0000000000000000000000000000000000000000..eb1b4c1fcc21dbebf23b5669913a59aaf3ce104a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/command/easy_install.py
@@ -0,0 +1,2365 @@
+"""
+Easy Install
+------------
+
+A tool for doing automatic download/extract/build of distutils-based Python
+packages.  For detailed documentation, see the accompanying EasyInstall.txt
+file, or visit the `EasyInstall home page`__.
+
+__ https://setuptools.pypa.io/en/latest/deprecated/easy_install.html
+
+"""
+
+from __future__ import annotations
+
+import configparser
+import contextlib
+import io
+import os
+import random
+import re
+import shlex
+import shutil
+import site
+import stat
+import struct
+import subprocess
+import sys
+import sysconfig
+import tempfile
+import textwrap
+import warnings
+import zipfile
+import zipimport
+from collections.abc import Iterable
+from glob import glob
+from sysconfig import get_path
+from typing import TYPE_CHECKING, NoReturn, TypedDict
+
+from jaraco.text import yield_lines
+
+import pkg_resources
+from pkg_resources import (
+    DEVELOP_DIST,
+    Distribution,
+    DistributionNotFound,
+    EggMetadata,
+    Environment,
+    PathMetadata,
+    Requirement,
+    VersionConflict,
+    WorkingSet,
+    find_distributions,
+    get_distribution,
+    normalize_path,
+    resource_string,
+)
+from setuptools import Command
+from setuptools.archive_util import unpack_archive
+from setuptools.command import bdist_egg, egg_info, setopt
+from setuptools.package_index import URL_SCHEME, PackageIndex, parse_requirement_arg
+from setuptools.sandbox import run_setup
+from setuptools.warnings import SetuptoolsDeprecationWarning, SetuptoolsWarning
+from setuptools.wheel import Wheel
+
+from .._path import ensure_directory
+from .._shutil import attempt_chmod_verbose as chmod, rmtree as _rmtree
+from ..compat import py39, py312
+
+from distutils import dir_util, log
+from distutils.command import install
+from distutils.command.build_scripts import first_line_re
+from distutils.errors import (
+    DistutilsArgError,
+    DistutilsError,
+    DistutilsOptionError,
+    DistutilsPlatformError,
+)
+from distutils.util import convert_path, get_platform, subst_vars
+
+if TYPE_CHECKING:
+    from typing_extensions import Self
+
+# Turn on PEP440Warnings
+warnings.filterwarnings("default", category=pkg_resources.PEP440Warning)
+
+__all__ = [
+    'easy_install',
+    'PthDistributions',
+    'extract_wininst_cfg',
+    'get_exe_prefixes',
+]
+
+
+def is_64bit():
+    return struct.calcsize("P") == 8
+
+
+def _to_bytes(s):
+    return s.encode('utf8')
+
+
+def isascii(s):
+    try:
+        s.encode('ascii')
+    except UnicodeError:
+        return False
+    return True
+
+
+def _one_liner(text):
+    return textwrap.dedent(text).strip().replace('\n', '; ')
+
+
+class easy_install(Command):
+    """Manage a download/build/install process"""
+
+    description = "Find/get/install Python packages"
+    command_consumes_arguments = True
+
+    user_options = [
+        ('prefix=', None, "installation prefix"),
+        ("zip-ok", "z", "install package as a zipfile"),
+        ("multi-version", "m", "make apps have to require() a version"),
+        ("upgrade", "U", "force upgrade (searches PyPI for latest versions)"),
+        ("install-dir=", "d", "install package to DIR"),
+        ("script-dir=", "s", "install scripts to DIR"),
+        ("exclude-scripts", "x", "Don't install scripts"),
+        ("always-copy", "a", "Copy all needed packages to install dir"),
+        ("index-url=", "i", "base URL of Python Package Index"),
+        ("find-links=", "f", "additional URL(s) to search for packages"),
+        ("build-directory=", "b", "download/extract/build in DIR; keep the results"),
+        (
+            'optimize=',
+            'O',
+            'also compile with optimization: -O1 for "python -O", '
+            '-O2 for "python -OO", and -O0 to disable [default: -O0]',
+        ),
+        ('record=', None, "filename in which to record list of installed files"),
+        ('always-unzip', 'Z', "don't install as a zipfile, no matter what"),
+        ('site-dirs=', 'S', "list of directories where .pth files work"),
+        ('editable', 'e', "Install specified packages in editable form"),
+        ('no-deps', 'N', "don't install dependencies"),
+        ('allow-hosts=', 'H', "pattern(s) that hostnames must match"),
+        ('local-snapshots-ok', 'l', "allow building eggs from local checkouts"),
+        ('version', None, "print version information and exit"),
+        (
+            'no-find-links',
+            None,
+            "Don't load find-links defined in packages being installed",
+        ),
+        ('user', None, f"install in user site-package '{site.USER_SITE}'"),
+    ]
+    boolean_options = [
+        'zip-ok',
+        'multi-version',
+        'exclude-scripts',
+        'upgrade',
+        'always-copy',
+        'editable',
+        'no-deps',
+        'local-snapshots-ok',
+        'version',
+        'user',
+    ]
+
+    negative_opt = {'always-unzip': 'zip-ok'}
+    create_index = PackageIndex
+
+    def initialize_options(self):
+        EasyInstallDeprecationWarning.emit()
+
+        # the --user option seems to be an opt-in one,
+        # so the default should be False.
+        self.user = False
+        self.zip_ok = self.local_snapshots_ok = None
+        self.install_dir = self.script_dir = self.exclude_scripts = None
+        self.index_url = None
+        self.find_links = None
+        self.build_directory = None
+        self.args = None
+        self.optimize = self.record = None
+        self.upgrade = self.always_copy = self.multi_version = None
+        self.editable = self.no_deps = self.allow_hosts = None
+        self.root = self.prefix = self.no_report = None
+        self.version = None
+        self.install_purelib = None  # for pure module distributions
+        self.install_platlib = None  # non-pure (dists w/ extensions)
+        self.install_headers = None  # for C/C++ headers
+        self.install_lib = None  # set to either purelib or platlib
+        self.install_scripts = None
+        self.install_data = None
+        self.install_base = None
+        self.install_platbase = None
+        self.install_userbase = site.USER_BASE
+        self.install_usersite = site.USER_SITE
+        self.no_find_links = None
+
+        # Options not specifiable via command line
+        self.package_index = None
+        self.pth_file = self.always_copy_from = None
+        self.site_dirs = None
+        self.installed_projects = {}
+        # Always read easy_install options, even if we are subclassed, or have
+        # an independent instance created.  This ensures that defaults will
+        # always come from the standard configuration file(s)' "easy_install"
+        # section, even if this is a "develop" or "install" command, or some
+        # other embedding.
+        self._dry_run = None
+        self.verbose = self.distribution.verbose
+        self.distribution._set_command_options(
+            self, self.distribution.get_option_dict('easy_install')
+        )
+
+    def delete_blockers(self, blockers) -> None:
+        extant_blockers = (
+            filename
+            for filename in blockers
+            if os.path.exists(filename) or os.path.islink(filename)
+        )
+        list(map(self._delete_path, extant_blockers))
+
+    def _delete_path(self, path):
+        log.info("Deleting %s", path)
+        if self.dry_run:
+            return
+
+        is_tree = os.path.isdir(path) and not os.path.islink(path)
+        remover = _rmtree if is_tree else os.unlink
+        remover(path)
+
+    @staticmethod
+    def _render_version():
+        """
+        Render the Setuptools version and installation details, then exit.
+        """
+        ver = f'{sys.version_info.major}.{sys.version_info.minor}'
+        dist = get_distribution('setuptools')
+        print(f'setuptools {dist.version} from {dist.location} (Python {ver})')
+        raise SystemExit
+
+    def finalize_options(self) -> None:  # noqa: C901  # is too complex (25)  # FIXME
+        self.version and self._render_version()
+
+        py_version = sys.version.split()[0]
+
+        self.config_vars = dict(sysconfig.get_config_vars())
+
+        self.config_vars.update({
+            'dist_name': self.distribution.get_name(),
+            'dist_version': self.distribution.get_version(),
+            'dist_fullname': self.distribution.get_fullname(),
+            'py_version': py_version,
+            'py_version_short': f'{sys.version_info.major}.{sys.version_info.minor}',
+            'py_version_nodot': f'{sys.version_info.major}{sys.version_info.minor}',
+            'sys_prefix': self.config_vars['prefix'],
+            'sys_exec_prefix': self.config_vars['exec_prefix'],
+            # Only POSIX systems have abiflags
+            'abiflags': getattr(sys, 'abiflags', ''),
+            # Only python 3.9+ has platlibdir
+            'platlibdir': getattr(sys, 'platlibdir', 'lib'),
+        })
+        with contextlib.suppress(AttributeError):
+            # only for distutils outside stdlib
+            self.config_vars.update({
+                'implementation_lower': install._get_implementation().lower(),
+                'implementation': install._get_implementation(),
+            })
+
+        # pypa/distutils#113 Python 3.9 compat
+        self.config_vars.setdefault(
+            'py_version_nodot_plat',
+            getattr(sys, 'windir', '').replace('.', ''),
+        )
+
+        self.config_vars['userbase'] = self.install_userbase
+        self.config_vars['usersite'] = self.install_usersite
+        if self.user and not site.ENABLE_USER_SITE:
+            log.warn("WARNING: The user site-packages directory is disabled.")
+
+        self._fix_install_dir_for_user_site()
+
+        self.expand_basedirs()
+        self.expand_dirs()
+
+        self._expand(
+            'install_dir',
+            'script_dir',
+            'build_directory',
+            'site_dirs',
+        )
+        # If a non-default installation directory was specified, default the
+        # script directory to match it.
+        if self.script_dir is None:
+            self.script_dir = self.install_dir
+
+        if self.no_find_links is None:
+            self.no_find_links = False
+
+        # Let install_dir get set by install_lib command, which in turn
+        # gets its info from the install command, and takes into account
+        # --prefix and --home and all that other crud.
+        self.set_undefined_options('install_lib', ('install_dir', 'install_dir'))
+        # Likewise, set default script_dir from 'install_scripts.install_dir'
+        self.set_undefined_options('install_scripts', ('install_dir', 'script_dir'))
+
+        if self.user and self.install_purelib:
+            self.install_dir = self.install_purelib
+            self.script_dir = self.install_scripts
+        # default --record from the install command
+        self.set_undefined_options('install', ('record', 'record'))
+        self.all_site_dirs = get_site_dirs()
+        self.all_site_dirs.extend(self._process_site_dirs(self.site_dirs))
+
+        if not self.editable:
+            self.check_site_dir()
+        default_index = os.getenv("__EASYINSTALL_INDEX", "https://pypi.org/simple/")
+        # ^ Private API for testing purposes only
+        self.index_url = self.index_url or default_index
+        self.shadow_path = self.all_site_dirs[:]
+        for path_item in self.install_dir, normalize_path(self.script_dir):
+            if path_item not in self.shadow_path:
+                self.shadow_path.insert(0, path_item)
+
+        if self.allow_hosts is not None:
+            hosts = [s.strip() for s in self.allow_hosts.split(',')]
+        else:
+            hosts = ['*']
+        if self.package_index is None:
+            self.package_index = self.create_index(
+                self.index_url,
+                search_path=self.shadow_path,
+                hosts=hosts,
+            )
+        self.local_index = Environment(self.shadow_path + sys.path)
+
+        if self.find_links is not None:
+            if isinstance(self.find_links, str):
+                self.find_links = self.find_links.split()
+        else:
+            self.find_links = []
+        if self.local_snapshots_ok:
+            self.package_index.scan_egg_links(self.shadow_path + sys.path)
+        if not self.no_find_links:
+            self.package_index.add_find_links(self.find_links)
+        self.set_undefined_options('install_lib', ('optimize', 'optimize'))
+        self.optimize = self._validate_optimize(self.optimize)
+
+        if self.editable and not self.build_directory:
+            raise DistutilsArgError(
+                "Must specify a build directory (-b) when using --editable"
+            )
+        if not self.args:
+            raise DistutilsArgError(
+                "No urls, filenames, or requirements specified (see --help)"
+            )
+
+        self.outputs: list[str] = []
+
+    @staticmethod
+    def _process_site_dirs(site_dirs):
+        if site_dirs is None:
+            return
+
+        normpath = map(normalize_path, sys.path)
+        site_dirs = [os.path.expanduser(s.strip()) for s in site_dirs.split(',')]
+        for d in site_dirs:
+            if not os.path.isdir(d):
+                log.warn("%s (in --site-dirs) does not exist", d)
+            elif normalize_path(d) not in normpath:
+                raise DistutilsOptionError(d + " (in --site-dirs) is not on sys.path")
+            else:
+                yield normalize_path(d)
+
+    @staticmethod
+    def _validate_optimize(value):
+        try:
+            value = int(value)
+            if value not in range(3):
+                raise ValueError
+        except ValueError as e:
+            raise DistutilsOptionError("--optimize must be 0, 1, or 2") from e
+
+        return value
+
+    def _fix_install_dir_for_user_site(self):
+        """
+        Fix the install_dir if "--user" was used.
+        """
+        if not self.user:
+            return
+
+        self.create_home_path()
+        if self.install_userbase is None:
+            msg = "User base directory is not specified"
+            raise DistutilsPlatformError(msg)
+        self.install_base = self.install_platbase = self.install_userbase
+        scheme_name = f'{os.name}_user'
+        self.select_scheme(scheme_name)
+
+    def _expand_attrs(self, attrs):
+        for attr in attrs:
+            val = getattr(self, attr)
+            if val is not None:
+                if os.name == 'posix' or os.name == 'nt':
+                    val = os.path.expanduser(val)
+                val = subst_vars(val, self.config_vars)
+                setattr(self, attr, val)
+
+    def expand_basedirs(self) -> None:
+        """Calls `os.path.expanduser` on install_base, install_platbase and
+        root."""
+        self._expand_attrs(['install_base', 'install_platbase', 'root'])
+
+    def expand_dirs(self) -> None:
+        """Calls `os.path.expanduser` on install dirs."""
+        dirs = [
+            'install_purelib',
+            'install_platlib',
+            'install_lib',
+            'install_headers',
+            'install_scripts',
+            'install_data',
+        ]
+        self._expand_attrs(dirs)
+
+    def run(self, show_deprecation: bool = True) -> None:
+        if show_deprecation:
+            self.announce(
+                "WARNING: The easy_install command is deprecated "
+                "and will be removed in a future version.",
+                log.WARN,
+            )
+        if self.verbose != self.distribution.verbose:
+            log.set_verbosity(self.verbose)
+        try:
+            for spec in self.args:
+                self.easy_install(spec, not self.no_deps)
+            if self.record:
+                outputs = self.outputs
+                if self.root:  # strip any package prefix
+                    root_len = len(self.root)
+                    for counter in range(len(outputs)):
+                        outputs[counter] = outputs[counter][root_len:]
+                from distutils import file_util
+
+                self.execute(
+                    file_util.write_file,
+                    (self.record, outputs),
+                    f"writing list of installed files to '{self.record}'",
+                )
+            self.warn_deprecated_options()
+        finally:
+            log.set_verbosity(self.distribution.verbose)
+
+    def pseudo_tempname(self):
+        """Return a pseudo-tempname base in the install directory.
+        This code is intentionally naive; if a malicious party can write to
+        the target directory you're already in deep doodoo.
+        """
+        try:
+            pid = os.getpid()
+        except Exception:
+            pid = random.randint(0, sys.maxsize)
+        return os.path.join(self.install_dir, f"test-easy-install-{pid}")
+
+    def warn_deprecated_options(self) -> None:
+        pass
+
+    def check_site_dir(self) -> None:  # is too complex (12)  # FIXME
+        """Verify that self.install_dir is .pth-capable dir, if needed"""
+
+        instdir = normalize_path(self.install_dir)
+        pth_file = os.path.join(instdir, 'easy-install.pth')
+
+        if not os.path.exists(instdir):
+            try:
+                os.makedirs(instdir)
+            except OSError:
+                self.cant_write_to_target()
+
+        # Is it a configured, PYTHONPATH, implicit, or explicit site dir?
+        is_site_dir = instdir in self.all_site_dirs
+
+        if not is_site_dir and not self.multi_version:
+            # No?  Then directly test whether it does .pth file processing
+            is_site_dir = self.check_pth_processing()
+        else:
+            # make sure we can write to target dir
+            testfile = self.pseudo_tempname() + '.write-test'
+            test_exists = os.path.exists(testfile)
+            try:
+                if test_exists:
+                    os.unlink(testfile)
+                open(testfile, 'wb').close()
+                os.unlink(testfile)
+            except OSError:
+                self.cant_write_to_target()
+
+        if not is_site_dir and not self.multi_version:
+            # Can't install non-multi to non-site dir with easy_install
+            pythonpath = os.environ.get('PYTHONPATH', '')
+            log.warn(self.__no_default_msg, self.install_dir, pythonpath)
+
+        if is_site_dir:
+            if self.pth_file is None:
+                self.pth_file = PthDistributions(pth_file, self.all_site_dirs)
+        else:
+            self.pth_file = None
+
+        if self.multi_version and not os.path.exists(pth_file):
+            self.pth_file = None  # don't create a .pth file
+        self.install_dir = instdir
+
+    __cant_write_msg = textwrap.dedent(
+        """
+        can't create or remove files in install directory
+
+        The following error occurred while trying to add or remove files in the
+        installation directory:
+
+            %s
+
+        The installation directory you specified (via --install-dir, --prefix, or
+        the distutils default setting) was:
+
+            %s
+        """
+    ).lstrip()
+
+    __not_exists_id = textwrap.dedent(
+        """
+        This directory does not currently exist.  Please create it and try again, or
+        choose a different installation directory (using the -d or --install-dir
+        option).
+        """
+    ).lstrip()
+
+    __access_msg = textwrap.dedent(
+        """
+        Perhaps your account does not have write access to this directory?  If the
+        installation directory is a system-owned directory, you may need to sign in
+        as the administrator or "root" account.  If you do not have administrative
+        access to this machine, you may wish to choose a different installation
+        directory, preferably one that is listed in your PYTHONPATH environment
+        variable.
+
+        For information on other options, you may wish to consult the
+        documentation at:
+
+          https://setuptools.pypa.io/en/latest/deprecated/easy_install.html
+
+        Please make the appropriate changes for your system and try again.
+        """
+    ).lstrip()
+
+    def cant_write_to_target(self) -> NoReturn:
+        msg = self.__cant_write_msg % (
+            sys.exc_info()[1],
+            self.install_dir,
+        )
+
+        if not os.path.exists(self.install_dir):
+            msg += '\n' + self.__not_exists_id
+        else:
+            msg += '\n' + self.__access_msg
+        raise DistutilsError(msg)
+
+    def check_pth_processing(self):  # noqa: C901
+        """Empirically verify whether .pth files are supported in inst. dir"""
+        instdir = self.install_dir
+        log.info("Checking .pth file support in %s", instdir)
+        pth_file = self.pseudo_tempname() + ".pth"
+        ok_file = pth_file + '.ok'
+        ok_exists = os.path.exists(ok_file)
+        tmpl = (
+            _one_liner(
+                """
+            import os
+            f = open({ok_file!r}, 'w', encoding="utf-8")
+            f.write('OK')
+            f.close()
+            """
+            )
+            + '\n'
+        )
+        try:
+            if ok_exists:
+                os.unlink(ok_file)
+            dirname = os.path.dirname(ok_file)
+            os.makedirs(dirname, exist_ok=True)
+            f = open(pth_file, 'w', encoding=py312.PTH_ENCODING)
+            # ^-- Python<3.13 require encoding="locale" instead of "utf-8",
+            #     see python/cpython#77102.
+        except OSError:
+            self.cant_write_to_target()
+        else:
+            try:
+                f.write(tmpl.format(**locals()))
+                f.close()
+                f = None
+                executable = sys.executable
+                if os.name == 'nt':
+                    dirname, basename = os.path.split(executable)
+                    alt = os.path.join(dirname, 'pythonw.exe')
+                    use_alt = basename.lower() == 'python.exe' and os.path.exists(alt)
+                    if use_alt:
+                        # use pythonw.exe to avoid opening a console window
+                        executable = alt
+
+                from distutils.spawn import spawn
+
+                spawn([executable, '-E', '-c', 'pass'], 0)
+
+                if os.path.exists(ok_file):
+                    log.info("TEST PASSED: %s appears to support .pth files", instdir)
+                    return True
+            finally:
+                if f:
+                    f.close()
+                if os.path.exists(ok_file):
+                    os.unlink(ok_file)
+                if os.path.exists(pth_file):
+                    os.unlink(pth_file)
+        if not self.multi_version:
+            log.warn("TEST FAILED: %s does NOT support .pth files", instdir)
+        return False
+
+    def install_egg_scripts(self, dist) -> None:
+        """Write all the scripts for `dist`, unless scripts are excluded"""
+        if not self.exclude_scripts and dist.metadata_isdir('scripts'):
+            for script_name in dist.metadata_listdir('scripts'):
+                if dist.metadata_isdir('scripts/' + script_name):
+                    # The "script" is a directory, likely a Python 3
+                    # __pycache__ directory, so skip it.
+                    continue
+                self.install_script(
+                    dist, script_name, dist.get_metadata('scripts/' + script_name)
+                )
+        self.install_wrapper_scripts(dist)
+
+    def add_output(self, path) -> None:
+        if os.path.isdir(path):
+            for base, dirs, files in os.walk(path):
+                for filename in files:
+                    self.outputs.append(os.path.join(base, filename))
+        else:
+            self.outputs.append(path)
+
+    def not_editable(self, spec) -> None:
+        if self.editable:
+            raise DistutilsArgError(
+                f"Invalid argument {spec!r}: you can't use filenames or URLs "
+                "with --editable (except via the --find-links option)."
+            )
+
+    def check_editable(self, spec) -> None:
+        if not self.editable:
+            return
+
+        if os.path.exists(os.path.join(self.build_directory, spec.key)):
+            raise DistutilsArgError(
+                f"{spec.key!r} already exists in {self.build_directory}; can't do a checkout there"
+            )
+
+    @contextlib.contextmanager
+    def _tmpdir(self):
+        tmpdir = tempfile.mkdtemp(prefix="easy_install-")
+        try:
+            # cast to str as workaround for #709 and #710 and #712
+            yield str(tmpdir)
+        finally:
+            os.path.exists(tmpdir) and _rmtree(tmpdir)
+
+    def easy_install(self, spec, deps: bool = False) -> Distribution | None:
+        with self._tmpdir() as tmpdir:
+            if not isinstance(spec, Requirement):
+                if URL_SCHEME(spec):
+                    # It's a url, download it to tmpdir and process
+                    self.not_editable(spec)
+                    dl = self.package_index.download(spec, tmpdir)
+                    return self.install_item(None, dl, tmpdir, deps, True)
+
+                elif os.path.exists(spec):
+                    # Existing file or directory, just process it directly
+                    self.not_editable(spec)
+                    return self.install_item(None, spec, tmpdir, deps, True)
+                else:
+                    spec = parse_requirement_arg(spec)
+
+            self.check_editable(spec)
+            dist = self.package_index.fetch_distribution(
+                spec,
+                tmpdir,
+                self.upgrade,
+                self.editable,
+                not self.always_copy,
+                self.local_index,
+            )
+            if dist is None:
+                msg = f"Could not find suitable distribution for {spec!r}"
+                if self.always_copy:
+                    msg += " (--always-copy skips system and development eggs)"
+                raise DistutilsError(msg)
+            elif dist.precedence == DEVELOP_DIST:
+                # .egg-info dists don't need installing, just process deps
+                self.process_distribution(spec, dist, deps, "Using")
+                return dist
+            else:
+                return self.install_item(spec, dist.location, tmpdir, deps)
+
+    def install_item(
+        self, spec, download, tmpdir, deps, install_needed: bool = False
+    ) -> Distribution | None:
+        # Installation is also needed if file in tmpdir or is not an egg
+        install_needed = install_needed or bool(self.always_copy)
+        install_needed = install_needed or os.path.dirname(download) == tmpdir
+        install_needed = install_needed or not download.endswith('.egg')
+        install_needed = install_needed or (
+            self.always_copy_from is not None
+            and os.path.dirname(normalize_path(download))
+            == normalize_path(self.always_copy_from)
+        )
+
+        if spec and not install_needed:
+            # at this point, we know it's a local .egg, we just don't know if
+            # it's already installed.
+            for dist in self.local_index[spec.project_name]:
+                if dist.location == download:
+                    break
+            else:
+                install_needed = True  # it's not in the local index
+
+        log.info("Processing %s", os.path.basename(download))
+
+        if install_needed:
+            dists = self.install_eggs(spec, download, tmpdir)
+            for dist in dists:
+                self.process_distribution(spec, dist, deps)
+        else:
+            dists = [self.egg_distribution(download)]
+            self.process_distribution(spec, dists[0], deps, "Using")
+
+        if spec is not None:
+            for dist in dists:
+                if dist in spec:
+                    return dist
+        return None
+
+    def select_scheme(self, name):
+        try:
+            install._select_scheme(self, name)
+        except AttributeError:
+            # stdlib distutils
+            install.install.select_scheme(self, name.replace('posix', 'unix'))
+
+    # FIXME: 'easy_install.process_distribution' is too complex (12)
+    def process_distribution(  # noqa: C901
+        self,
+        requirement,
+        dist,
+        deps: bool = True,
+        *info,
+    ) -> None:
+        self.update_pth(dist)
+        self.package_index.add(dist)
+        if dist in self.local_index[dist.key]:
+            self.local_index.remove(dist)
+        self.local_index.add(dist)
+        self.install_egg_scripts(dist)
+        self.installed_projects[dist.key] = dist
+        log.info(self.installation_report(requirement, dist, *info))
+        if dist.has_metadata('dependency_links.txt') and not self.no_find_links:
+            self.package_index.add_find_links(
+                dist.get_metadata_lines('dependency_links.txt')
+            )
+        if not deps and not self.always_copy:
+            return
+        elif requirement is not None and dist.key != requirement.key:
+            log.warn("Skipping dependencies for %s", dist)
+            return  # XXX this is not the distribution we were looking for
+        elif requirement is None or dist not in requirement:
+            # if we wound up with a different version, resolve what we've got
+            distreq = dist.as_requirement()
+            requirement = Requirement(str(distreq))
+        log.info("Processing dependencies for %s", requirement)
+        try:
+            distros = WorkingSet([]).resolve(
+                [requirement], self.local_index, self.easy_install
+            )
+        except DistributionNotFound as e:
+            raise DistutilsError(str(e)) from e
+        except VersionConflict as e:
+            raise DistutilsError(e.report()) from e
+        if self.always_copy or self.always_copy_from:
+            # Force all the relevant distros to be copied or activated
+            for dist in distros:
+                if dist.key not in self.installed_projects:
+                    self.easy_install(dist.as_requirement())
+        log.info("Finished processing dependencies for %s", requirement)
+
+    def should_unzip(self, dist) -> bool:
+        if self.zip_ok is not None:
+            return not self.zip_ok
+        if dist.has_metadata('not-zip-safe'):
+            return True
+        if not dist.has_metadata('zip-safe'):
+            return True
+        return False
+
+    def maybe_move(self, spec, dist_filename, setup_base):
+        dst = os.path.join(self.build_directory, spec.key)
+        if os.path.exists(dst):
+            msg = "%r already exists in %s; build directory %s will not be kept"
+            log.warn(msg, spec.key, self.build_directory, setup_base)
+            return setup_base
+        if os.path.isdir(dist_filename):
+            setup_base = dist_filename
+        else:
+            if os.path.dirname(dist_filename) == setup_base:
+                os.unlink(dist_filename)  # get it out of the tmp dir
+            contents = os.listdir(setup_base)
+            if len(contents) == 1:
+                dist_filename = os.path.join(setup_base, contents[0])
+                if os.path.isdir(dist_filename):
+                    # if the only thing there is a directory, move it instead
+                    setup_base = dist_filename
+        ensure_directory(dst)
+        shutil.move(setup_base, dst)
+        return dst
+
+    def install_wrapper_scripts(self, dist) -> None:
+        if self.exclude_scripts:
+            return
+        for args in ScriptWriter.best().get_args(dist):
+            self.write_script(*args)
+
+    def install_script(self, dist, script_name, script_text, dev_path=None) -> None:
+        """Generate a legacy script wrapper and install it"""
+        spec = str(dist.as_requirement())
+        is_script = is_python_script(script_text, script_name)
+
+        if is_script:
+            body = self._load_template(dev_path) % locals()
+            script_text = ScriptWriter.get_header(script_text) + body
+        self.write_script(script_name, _to_bytes(script_text), 'b')
+
+    @staticmethod
+    def _load_template(dev_path):
+        """
+        There are a couple of template scripts in the package. This
+        function loads one of them and prepares it for use.
+        """
+        # See https://github.com/pypa/setuptools/issues/134 for info
+        # on script file naming and downstream issues with SVR4
+        name = 'script.tmpl'
+        if dev_path:
+            name = name.replace('.tmpl', ' (dev).tmpl')
+
+        raw_bytes = resource_string('setuptools', name)
+        return raw_bytes.decode('utf-8')
+
+    def write_script(self, script_name, contents, mode: str = "t", blockers=()) -> None:
+        """Write an executable file to the scripts directory"""
+        self.delete_blockers(  # clean up old .py/.pyw w/o a script
+            [os.path.join(self.script_dir, x) for x in blockers]
+        )
+        log.info("Installing %s script to %s", script_name, self.script_dir)
+        target = os.path.join(self.script_dir, script_name)
+        self.add_output(target)
+
+        if self.dry_run:
+            return
+
+        mask = current_umask()
+        ensure_directory(target)
+        if os.path.exists(target):
+            os.unlink(target)
+
+        encoding = None if "b" in mode else "utf-8"
+        with open(target, "w" + mode, encoding=encoding) as f:
+            f.write(contents)
+        chmod(target, 0o777 - mask)
+
+    def install_eggs(self, spec, dist_filename, tmpdir) -> list[Distribution]:
+        # .egg dirs or files are already built, so just return them
+        installer_map = {
+            '.egg': self.install_egg,
+            '.exe': self.install_exe,
+            '.whl': self.install_wheel,
+        }
+        try:
+            install_dist = installer_map[dist_filename.lower()[-4:]]
+        except KeyError:
+            pass
+        else:
+            return [install_dist(dist_filename, tmpdir)]
+
+        # Anything else, try to extract and build
+        setup_base = tmpdir
+        if os.path.isfile(dist_filename) and not dist_filename.endswith('.py'):
+            unpack_archive(dist_filename, tmpdir, self.unpack_progress)
+        elif os.path.isdir(dist_filename):
+            setup_base = os.path.abspath(dist_filename)
+
+        if (
+            setup_base.startswith(tmpdir)  # something we downloaded
+            and self.build_directory
+            and spec is not None
+        ):
+            setup_base = self.maybe_move(spec, dist_filename, setup_base)
+
+        # Find the setup.py file
+        setup_script = os.path.join(setup_base, 'setup.py')
+
+        if not os.path.exists(setup_script):
+            setups = glob(os.path.join(setup_base, '*', 'setup.py'))
+            if not setups:
+                raise DistutilsError(
+                    f"Couldn't find a setup script in {os.path.abspath(dist_filename)}"
+                )
+            if len(setups) > 1:
+                raise DistutilsError(
+                    f"Multiple setup scripts in {os.path.abspath(dist_filename)}"
+                )
+            setup_script = setups[0]
+
+        # Now run it, and return the result
+        if self.editable:
+            log.info(self.report_editable(spec, setup_script))
+            return []
+        else:
+            return self.build_and_install(setup_script, setup_base)
+
+    def egg_distribution(self, egg_path):
+        if os.path.isdir(egg_path):
+            metadata = PathMetadata(egg_path, os.path.join(egg_path, 'EGG-INFO'))
+        else:
+            metadata = EggMetadata(zipimport.zipimporter(egg_path))
+        return Distribution.from_filename(egg_path, metadata=metadata)
+
+    # FIXME: 'easy_install.install_egg' is too complex (11)
+    def install_egg(self, egg_path, tmpdir):
+        destination = os.path.join(
+            self.install_dir,
+            os.path.basename(egg_path),
+        )
+        destination = os.path.abspath(destination)
+        if not self.dry_run:
+            ensure_directory(destination)
+
+        dist = self.egg_distribution(egg_path)
+        if not (
+            os.path.exists(destination) and os.path.samefile(egg_path, destination)
+        ):
+            if os.path.isdir(destination) and not os.path.islink(destination):
+                dir_util.remove_tree(destination, dry_run=self.dry_run)
+            elif os.path.exists(destination):
+                self.execute(
+                    os.unlink,
+                    (destination,),
+                    "Removing " + destination,
+                )
+            try:
+                new_dist_is_zipped = False
+                if os.path.isdir(egg_path):
+                    if egg_path.startswith(tmpdir):
+                        f, m = shutil.move, "Moving"
+                    else:
+                        f, m = shutil.copytree, "Copying"
+                elif self.should_unzip(dist):
+                    self.mkpath(destination)
+                    f, m = self.unpack_and_compile, "Extracting"
+                else:
+                    new_dist_is_zipped = True
+                    if egg_path.startswith(tmpdir):
+                        f, m = shutil.move, "Moving"
+                    else:
+                        f, m = shutil.copy2, "Copying"
+                self.execute(
+                    f,
+                    (egg_path, destination),
+                    (m + " %s to %s")
+                    % (os.path.basename(egg_path), os.path.dirname(destination)),
+                )
+                update_dist_caches(
+                    destination,
+                    fix_zipimporter_caches=new_dist_is_zipped,
+                )
+            except Exception:
+                update_dist_caches(destination, fix_zipimporter_caches=False)
+                raise
+
+        self.add_output(destination)
+        return self.egg_distribution(destination)
+
+    def install_exe(self, dist_filename, tmpdir):
+        # See if it's valid, get data
+        cfg = extract_wininst_cfg(dist_filename)
+        if cfg is None:
+            raise DistutilsError(
+                f"{dist_filename} is not a valid distutils Windows .exe"
+            )
+        # Create a dummy distribution object until we build the real distro
+        dist = Distribution(
+            None,
+            project_name=cfg.get('metadata', 'name'),
+            version=cfg.get('metadata', 'version'),
+            platform=get_platform(),
+        )
+
+        # Convert the .exe to an unpacked egg
+        egg_path = os.path.join(tmpdir, dist.egg_name() + '.egg')
+        dist.location = egg_path
+        egg_tmp = egg_path + '.tmp'
+        _egg_info = os.path.join(egg_tmp, 'EGG-INFO')
+        pkg_inf = os.path.join(_egg_info, 'PKG-INFO')
+        ensure_directory(pkg_inf)  # make sure EGG-INFO dir exists
+        dist._provider = PathMetadata(egg_tmp, _egg_info)  # XXX
+        self.exe_to_egg(dist_filename, egg_tmp)
+
+        # Write EGG-INFO/PKG-INFO
+        if not os.path.exists(pkg_inf):
+            with open(pkg_inf, 'w', encoding="utf-8") as f:
+                f.write('Metadata-Version: 1.0\n')
+                for k, v in cfg.items('metadata'):
+                    if k != 'target_version':
+                        k = k.replace('_', '-').title()
+                        f.write(f'{k}: {v}\n')
+        script_dir = os.path.join(_egg_info, 'scripts')
+        # delete entry-point scripts to avoid duping
+        self.delete_blockers([
+            os.path.join(script_dir, args[0]) for args in ScriptWriter.get_args(dist)
+        ])
+        # Build .egg file from tmpdir
+        bdist_egg.make_zipfile(
+            egg_path,
+            egg_tmp,
+            verbose=self.verbose,
+            dry_run=self.dry_run,
+        )
+        # install the .egg
+        return self.install_egg(egg_path, tmpdir)
+
+    # FIXME: 'easy_install.exe_to_egg' is too complex (12)
+    def exe_to_egg(self, dist_filename, egg_tmp) -> None:  # noqa: C901
+        """Extract a bdist_wininst to the directories an egg would use"""
+        # Check for .pth file and set up prefix translations
+        prefixes = get_exe_prefixes(dist_filename)
+        to_compile = []
+        native_libs = []
+        top_level = set()
+
+        def process(src, dst):
+            s = src.lower()
+            for old, new in prefixes:
+                if s.startswith(old):
+                    src = new + src[len(old) :]
+                    parts = src.split('/')
+                    dst = os.path.join(egg_tmp, *parts)
+                    dl = dst.lower()
+                    if dl.endswith('.pyd') or dl.endswith('.dll'):
+                        parts[-1] = bdist_egg.strip_module(parts[-1])
+                        top_level.add([os.path.splitext(parts[0])[0]])
+                        native_libs.append(src)
+                    elif dl.endswith('.py') and old != 'SCRIPTS/':
+                        top_level.add([os.path.splitext(parts[0])[0]])
+                        to_compile.append(dst)
+                    return dst
+            if not src.endswith('.pth'):
+                log.warn("WARNING: can't process %s", src)
+            return None
+
+        # extract, tracking .pyd/.dll->native_libs and .py -> to_compile
+        unpack_archive(dist_filename, egg_tmp, process)
+        stubs = []
+        for res in native_libs:
+            if res.lower().endswith('.pyd'):  # create stubs for .pyd's
+                parts = res.split('/')
+                resource = parts[-1]
+                parts[-1] = bdist_egg.strip_module(parts[-1]) + '.py'
+                pyfile = os.path.join(egg_tmp, *parts)
+                to_compile.append(pyfile)
+                stubs.append(pyfile)
+                bdist_egg.write_stub(resource, pyfile)
+        self.byte_compile(to_compile)  # compile .py's
+        bdist_egg.write_safety_flag(
+            os.path.join(egg_tmp, 'EGG-INFO'), bdist_egg.analyze_egg(egg_tmp, stubs)
+        )  # write zip-safety flag
+
+        for name in 'top_level', 'native_libs':
+            if locals()[name]:
+                txt = os.path.join(egg_tmp, 'EGG-INFO', name + '.txt')
+                if not os.path.exists(txt):
+                    with open(txt, 'w', encoding="utf-8") as f:
+                        f.write('\n'.join(locals()[name]) + '\n')
+
+    def install_wheel(self, wheel_path, tmpdir):
+        wheel = Wheel(wheel_path)
+        assert wheel.is_compatible()
+        destination = os.path.join(self.install_dir, wheel.egg_name())
+        destination = os.path.abspath(destination)
+        if not self.dry_run:
+            ensure_directory(destination)
+        if os.path.isdir(destination) and not os.path.islink(destination):
+            dir_util.remove_tree(destination, dry_run=self.dry_run)
+        elif os.path.exists(destination):
+            self.execute(
+                os.unlink,
+                (destination,),
+                "Removing " + destination,
+            )
+        try:
+            self.execute(
+                wheel.install_as_egg,
+                (destination,),
+                (
+                    f"Installing {os.path.basename(wheel_path)} to {os.path.dirname(destination)}"
+                ),
+            )
+        finally:
+            update_dist_caches(destination, fix_zipimporter_caches=False)
+        self.add_output(destination)
+        return self.egg_distribution(destination)
+
+    __mv_warning = textwrap.dedent(
+        """
+        Because this distribution was installed --multi-version, before you can
+        import modules from this package in an application, you will need to
+        'import pkg_resources' and then use a 'require()' call similar to one of
+        these examples, in order to select the desired version:
+
+            pkg_resources.require("%(name)s")  # latest installed version
+            pkg_resources.require("%(name)s==%(version)s")  # this exact version
+            pkg_resources.require("%(name)s>=%(version)s")  # this version or higher
+        """
+    ).lstrip()
+
+    __id_warning = textwrap.dedent(
+        """
+        Note also that the installation directory must be on sys.path at runtime for
+        this to work.  (e.g. by being the application's script directory, by being on
+        PYTHONPATH, or by being added to sys.path by your code.)
+        """
+    )
+
+    def installation_report(self, req, dist, what: str = "Installed") -> str:
+        """Helpful installation message for display to package users"""
+        msg = "\n%(what)s %(eggloc)s%(extras)s"
+        if self.multi_version and not self.no_report:
+            msg += '\n' + self.__mv_warning
+            if self.install_dir not in map(normalize_path, sys.path):
+                msg += '\n' + self.__id_warning
+
+        eggloc = dist.location
+        name = dist.project_name
+        version = dist.version
+        extras = ''  # TODO: self.report_extras(req, dist)
+        return msg % locals()
+
+    __editable_msg = textwrap.dedent(
+        """
+        Extracted editable version of %(spec)s to %(dirname)s
+
+        If it uses setuptools in its setup script, you can activate it in
+        "development" mode by going to that directory and running::
+
+            %(python)s setup.py develop
+
+        See the setuptools documentation for the "develop" command for more info.
+        """
+    ).lstrip()
+
+    def report_editable(self, spec, setup_script):
+        dirname = os.path.dirname(setup_script)
+        python = sys.executable
+        return '\n' + self.__editable_msg % locals()
+
+    def run_setup(self, setup_script, setup_base, args) -> None:
+        sys.modules.setdefault('distutils.command.bdist_egg', bdist_egg)
+        sys.modules.setdefault('distutils.command.egg_info', egg_info)
+
+        args = list(args)
+        if self.verbose > 2:
+            v = 'v' * (self.verbose - 1)
+            args.insert(0, '-' + v)
+        elif self.verbose < 2:
+            args.insert(0, '-q')
+        if self.dry_run:
+            args.insert(0, '-n')
+        log.info("Running %s %s", setup_script[len(setup_base) + 1 :], ' '.join(args))
+        try:
+            run_setup(setup_script, args)
+        except SystemExit as v:
+            raise DistutilsError(f"Setup script exited with {v.args[0]}") from v
+
+    def build_and_install(self, setup_script, setup_base):
+        args = ['bdist_egg', '--dist-dir']
+
+        dist_dir = tempfile.mkdtemp(
+            prefix='egg-dist-tmp-', dir=os.path.dirname(setup_script)
+        )
+        try:
+            self._set_fetcher_options(os.path.dirname(setup_script))
+            args.append(dist_dir)
+
+            self.run_setup(setup_script, setup_base, args)
+            all_eggs = Environment([dist_dir])
+            eggs = [
+                self.install_egg(dist.location, setup_base)
+                for key in all_eggs
+                for dist in all_eggs[key]
+            ]
+            if not eggs and not self.dry_run:
+                log.warn("No eggs found in %s (setup script problem?)", dist_dir)
+            return eggs
+        finally:
+            _rmtree(dist_dir)
+            log.set_verbosity(self.verbose)  # restore our log verbosity
+
+    def _set_fetcher_options(self, base):
+        """
+        When easy_install is about to run bdist_egg on a source dist, that
+        source dist might have 'setup_requires' directives, requiring
+        additional fetching. Ensure the fetcher options given to easy_install
+        are available to that command as well.
+        """
+        # find the fetch options from easy_install and write them out
+        # to the setup.cfg file.
+        ei_opts = self.distribution.get_option_dict('easy_install').copy()
+        fetch_directives = (
+            'find_links',
+            'site_dirs',
+            'index_url',
+            'optimize',
+            'allow_hosts',
+        )
+        fetch_options = {}
+        for key, val in ei_opts.items():
+            if key not in fetch_directives:
+                continue
+            fetch_options[key] = val[1]
+        # create a settings dictionary suitable for `edit_config`
+        settings = dict(easy_install=fetch_options)
+        cfg_filename = os.path.join(base, 'setup.cfg')
+        setopt.edit_config(cfg_filename, settings)
+
+    def update_pth(self, dist) -> None:  # noqa: C901  # is too complex (11)  # FIXME
+        if self.pth_file is None:
+            return
+
+        for d in self.pth_file[dist.key]:  # drop old entries
+            if not self.multi_version and d.location == dist.location:
+                continue
+
+            log.info("Removing %s from easy-install.pth file", d)
+            self.pth_file.remove(d)
+            if d.location in self.shadow_path:
+                self.shadow_path.remove(d.location)
+
+        if not self.multi_version:
+            if dist.location in self.pth_file.paths:
+                log.info(
+                    "%s is already the active version in easy-install.pth",
+                    dist,
+                )
+            else:
+                log.info("Adding %s to easy-install.pth file", dist)
+                self.pth_file.add(dist)  # add new entry
+                if dist.location not in self.shadow_path:
+                    self.shadow_path.append(dist.location)
+
+        if self.dry_run:
+            return
+
+        self.pth_file.save()
+
+        if dist.key != 'setuptools':
+            return
+
+        # Ensure that setuptools itself never becomes unavailable!
+        # XXX should this check for latest version?
+        filename = os.path.join(self.install_dir, 'setuptools.pth')
+        if os.path.islink(filename):
+            os.unlink(filename)
+
+        with open(filename, 'wt', encoding=py312.PTH_ENCODING) as f:
+            # ^-- Python<3.13 require encoding="locale" instead of "utf-8",
+            #     see python/cpython#77102.
+            f.write(self.pth_file.make_relative(dist.location) + '\n')
+
+    def unpack_progress(self, src, dst):
+        # Progress filter for unpacking
+        log.debug("Unpacking %s to %s", src, dst)
+        return dst  # only unpack-and-compile skips files for dry run
+
+    def unpack_and_compile(self, egg_path, destination) -> None:
+        to_compile = []
+        to_chmod = []
+
+        def pf(src, dst):
+            if dst.endswith('.py') and not src.startswith('EGG-INFO/'):
+                to_compile.append(dst)
+            elif dst.endswith('.dll') or dst.endswith('.so'):
+                to_chmod.append(dst)
+            self.unpack_progress(src, dst)
+            return not self.dry_run and dst or None
+
+        unpack_archive(egg_path, destination, pf)
+        self.byte_compile(to_compile)
+        if not self.dry_run:
+            for f in to_chmod:
+                mode = ((os.stat(f)[stat.ST_MODE]) | 0o555) & 0o7755
+                chmod(f, mode)
+
+    def byte_compile(self, to_compile) -> None:
+        if sys.dont_write_bytecode:
+            return
+
+        from distutils.util import byte_compile
+
+        try:
+            # try to make the byte compile messages quieter
+            log.set_verbosity(self.verbose - 1)
+
+            byte_compile(to_compile, optimize=0, force=True, dry_run=self.dry_run)
+            if self.optimize:
+                byte_compile(
+                    to_compile,
+                    optimize=self.optimize,
+                    force=True,
+                    dry_run=self.dry_run,
+                )
+        finally:
+            log.set_verbosity(self.verbose)  # restore original verbosity
+
+    __no_default_msg = textwrap.dedent(
+        """
+        bad install directory or PYTHONPATH
+
+        You are attempting to install a package to a directory that is not
+        on PYTHONPATH and which Python does not read ".pth" files from.  The
+        installation directory you specified (via --install-dir, --prefix, or
+        the distutils default setting) was:
+
+            %s
+
+        and your PYTHONPATH environment variable currently contains:
+
+            %r
+
+        Here are some of your options for correcting the problem:
+
+        * You can choose a different installation directory, i.e., one that is
+          on PYTHONPATH or supports .pth files
+
+        * You can add the installation directory to the PYTHONPATH environment
+          variable.  (It must then also be on PYTHONPATH whenever you run
+          Python and want to use the package(s) you are installing.)
+
+        * You can set up the installation directory to support ".pth" files by
+          using one of the approaches described here:
+
+          https://setuptools.pypa.io/en/latest/deprecated/easy_install.html#custom-installation-locations
+
+
+        Please make the appropriate changes for your system and try again.
+        """
+    ).strip()
+
+    def create_home_path(self) -> None:
+        """Create directories under ~."""
+        if not self.user:
+            return
+        home = convert_path(os.path.expanduser("~"))
+        for path in only_strs(self.config_vars.values()):
+            if path.startswith(home) and not os.path.isdir(path):
+                self.debug_print(f"os.makedirs('{path}', 0o700)")
+                os.makedirs(path, 0o700)
+
+    INSTALL_SCHEMES = dict(
+        posix=dict(
+            install_dir='$base/lib/python$py_version_short/site-packages',
+            script_dir='$base/bin',
+        ),
+    )
+
+    DEFAULT_SCHEME = dict(
+        install_dir='$base/Lib/site-packages',
+        script_dir='$base/Scripts',
+    )
+
+    def _expand(self, *attrs):
+        config_vars = self.get_finalized_command('install').config_vars
+
+        if self.prefix:
+            # Set default install_dir/scripts from --prefix
+            config_vars = dict(config_vars)
+            config_vars['base'] = self.prefix
+            scheme = self.INSTALL_SCHEMES.get(os.name, self.DEFAULT_SCHEME)
+            for attr, val in scheme.items():
+                if getattr(self, attr, None) is None:
+                    setattr(self, attr, val)
+
+        from distutils.util import subst_vars
+
+        for attr in attrs:
+            val = getattr(self, attr)
+            if val is not None:
+                val = subst_vars(val, config_vars)
+                if os.name == 'posix':
+                    val = os.path.expanduser(val)
+                setattr(self, attr, val)
+
+
+def _pythonpath():
+    items = os.environ.get('PYTHONPATH', '').split(os.pathsep)
+    return filter(None, items)
+
+
+def get_site_dirs():
+    """
+    Return a list of 'site' dirs
+    """
+
+    sitedirs = []
+
+    # start with PYTHONPATH
+    sitedirs.extend(_pythonpath())
+
+    prefixes = [sys.prefix]
+    if sys.exec_prefix != sys.prefix:
+        prefixes.append(sys.exec_prefix)
+    for prefix in prefixes:
+        if not prefix:
+            continue
+
+        if sys.platform in ('os2emx', 'riscos'):
+            sitedirs.append(os.path.join(prefix, "Lib", "site-packages"))
+        elif os.sep == '/':
+            sitedirs.extend([
+                os.path.join(
+                    prefix,
+                    "lib",
+                    f"python{sys.version_info.major}.{sys.version_info.minor}",
+                    "site-packages",
+                ),
+                os.path.join(prefix, "lib", "site-python"),
+            ])
+        else:
+            sitedirs.extend([
+                prefix,
+                os.path.join(prefix, "lib", "site-packages"),
+            ])
+        if sys.platform != 'darwin':
+            continue
+
+        # for framework builds *only* we add the standard Apple
+        # locations. Currently only per-user, but /Library and
+        # /Network/Library could be added too
+        if 'Python.framework' not in prefix:
+            continue
+
+        home = os.environ.get('HOME')
+        if not home:
+            continue
+
+        home_sp = os.path.join(
+            home,
+            'Library',
+            'Python',
+            f'{sys.version_info.major}.{sys.version_info.minor}',
+            'site-packages',
+        )
+        sitedirs.append(home_sp)
+    lib_paths = get_path('purelib'), get_path('platlib')
+
+    sitedirs.extend(s for s in lib_paths if s not in sitedirs)
+
+    if site.ENABLE_USER_SITE:
+        sitedirs.append(site.USER_SITE)
+
+    with contextlib.suppress(AttributeError):
+        sitedirs.extend(site.getsitepackages())
+
+    return list(map(normalize_path, sitedirs))
+
+
+def expand_paths(inputs):  # noqa: C901  # is too complex (11)  # FIXME
+    """Yield sys.path directories that might contain "old-style" packages"""
+
+    seen = set()
+
+    for dirname in inputs:
+        dirname = normalize_path(dirname)
+        if dirname in seen:
+            continue
+
+        seen.add(dirname)
+        if not os.path.isdir(dirname):
+            continue
+
+        files = os.listdir(dirname)
+        yield dirname, files
+
+        for name in files:
+            if not name.endswith('.pth'):
+                # We only care about the .pth files
+                continue
+            if name in ('easy-install.pth', 'setuptools.pth'):
+                # Ignore .pth files that we control
+                continue
+
+            # Read the .pth file
+            content = _read_pth(os.path.join(dirname, name))
+            lines = list(yield_lines(content))
+
+            # Yield existing non-dupe, non-import directory lines from it
+            for line in lines:
+                if line.startswith("import"):
+                    continue
+
+                line = normalize_path(line.rstrip())
+                if line in seen:
+                    continue
+
+                seen.add(line)
+                if not os.path.isdir(line):
+                    continue
+
+                yield line, os.listdir(line)
+
+
+def extract_wininst_cfg(dist_filename):
+    """Extract configuration data from a bdist_wininst .exe
+
+    Returns a configparser.RawConfigParser, or None
+    """
+    f = open(dist_filename, 'rb')
+    try:
+        endrec = zipfile._EndRecData(f)
+        if endrec is None:
+            return None
+
+        prepended = (endrec[9] - endrec[5]) - endrec[6]
+        if prepended < 12:  # no wininst data here
+            return None
+        f.seek(prepended - 12)
+
+        tag, cfglen, _bmlen = struct.unpack("egg path translations for a given .exe file"""
+
+    prefixes = [
+        ('PURELIB/', ''),
+        ('PLATLIB/pywin32_system32', ''),
+        ('PLATLIB/', ''),
+        ('SCRIPTS/', 'EGG-INFO/scripts/'),
+        ('DATA/lib/site-packages', ''),
+    ]
+    z = zipfile.ZipFile(exe_filename)
+    try:
+        for info in z.infolist():
+            name = info.filename
+            parts = name.split('/')
+            if len(parts) == 3 and parts[2] == 'PKG-INFO':
+                if parts[1].endswith('.egg-info'):
+                    prefixes.insert(0, ('/'.join(parts[:2]), 'EGG-INFO/'))
+                    break
+            if len(parts) != 2 or not name.endswith('.pth'):
+                continue
+            if name.endswith('-nspkg.pth'):
+                continue
+            if parts[0].upper() in ('PURELIB', 'PLATLIB'):
+                contents = z.read(name).decode()
+                for pth in yield_lines(contents):
+                    pth = pth.strip().replace('\\', '/')
+                    if not pth.startswith('import'):
+                        prefixes.append(((f'{parts[0]}/{pth}/'), ''))
+    finally:
+        z.close()
+    prefixes = [(x.lower(), y) for x, y in prefixes]
+    prefixes.sort()
+    prefixes.reverse()
+    return prefixes
+
+
+class PthDistributions(Environment):
+    """A .pth file with Distribution paths in it"""
+
+    def __init__(self, filename, sitedirs=()) -> None:
+        self.filename = filename
+        self.sitedirs = list(map(normalize_path, sitedirs))
+        self.basedir = normalize_path(os.path.dirname(self.filename))
+        self.paths, self.dirty = self._load()
+        # keep a copy if someone manually updates the paths attribute on the instance
+        self._init_paths = self.paths[:]
+        super().__init__([], None, None)
+        for path in yield_lines(self.paths):
+            list(map(self.add, find_distributions(path, True)))
+
+    def _load_raw(self):
+        paths = []
+        dirty = saw_import = False
+        seen = set(self.sitedirs)
+        content = _read_pth(self.filename)
+        for line in content.splitlines():
+            path = line.rstrip()
+            # still keep imports and empty/commented lines for formatting
+            paths.append(path)
+            if line.startswith(('import ', 'from ')):
+                saw_import = True
+                continue
+            stripped_path = path.strip()
+            if not stripped_path or stripped_path.startswith('#'):
+                continue
+            # skip non-existent paths, in case somebody deleted a package
+            # manually, and duplicate paths as well
+            normalized_path = normalize_path(os.path.join(self.basedir, path))
+            if normalized_path in seen or not os.path.exists(normalized_path):
+                log.debug("cleaned up dirty or duplicated %r", path)
+                dirty = True
+                paths.pop()
+                continue
+            seen.add(normalized_path)
+        # remove any trailing empty/blank line
+        while paths and not paths[-1].strip():
+            paths.pop()
+            dirty = True
+        return paths, dirty or (paths and saw_import)
+
+    def _load(self):
+        if os.path.isfile(self.filename):
+            return self._load_raw()
+        return [], False
+
+    def save(self) -> None:
+        """Write changed .pth file back to disk"""
+        # first reload the file
+        last_paths, last_dirty = self._load()
+        # and check that there are no difference with what we have.
+        # there can be difference if someone else has written to the file
+        # since we first loaded it.
+        # we don't want to lose the eventual new paths added since then.
+        for path in last_paths[:]:
+            if path not in self.paths:
+                self.paths.append(path)
+                log.info("detected new path %r", path)
+                last_dirty = True
+            else:
+                last_paths.remove(path)
+        # also, re-check that all paths are still valid before saving them
+        for path in self.paths[:]:
+            if path not in last_paths and not path.startswith((
+                'import ',
+                'from ',
+                '#',
+            )):
+                absolute_path = os.path.join(self.basedir, path)
+                if not os.path.exists(absolute_path):
+                    self.paths.remove(path)
+                    log.info("removing now non-existent path %r", path)
+                    last_dirty = True
+
+        self.dirty |= last_dirty or self.paths != self._init_paths
+        if not self.dirty:
+            return
+
+        rel_paths = list(map(self.make_relative, self.paths))
+        if rel_paths:
+            log.debug("Saving %s", self.filename)
+            lines = self._wrap_lines(rel_paths)
+            data = '\n'.join(lines) + '\n'
+            if os.path.islink(self.filename):
+                os.unlink(self.filename)
+            with open(self.filename, 'wt', encoding=py312.PTH_ENCODING) as f:
+                # ^-- Python<3.13 require encoding="locale" instead of "utf-8",
+                #     see python/cpython#77102.
+                f.write(data)
+        elif os.path.exists(self.filename):
+            log.debug("Deleting empty %s", self.filename)
+            os.unlink(self.filename)
+
+        self.dirty = False
+        self._init_paths[:] = self.paths[:]
+
+    @staticmethod
+    def _wrap_lines(lines):
+        return lines
+
+    def add(self, dist) -> None:
+        """Add `dist` to the distribution map"""
+        new_path = dist.location not in self.paths and (
+            dist.location not in self.sitedirs
+            or
+            # account for '.' being in PYTHONPATH
+            dist.location == os.getcwd()
+        )
+        if new_path:
+            self.paths.append(dist.location)
+            self.dirty = True
+        super().add(dist)
+
+    def remove(self, dist) -> None:
+        """Remove `dist` from the distribution map"""
+        while dist.location in self.paths:
+            self.paths.remove(dist.location)
+            self.dirty = True
+        super().remove(dist)
+
+    def make_relative(self, path):
+        npath, last = os.path.split(normalize_path(path))
+        baselen = len(self.basedir)
+        parts = [last]
+        sep = os.altsep == '/' and '/' or os.sep
+        while len(npath) >= baselen:
+            if npath == self.basedir:
+                parts.append(os.curdir)
+                parts.reverse()
+                return sep.join(parts)
+            npath, last = os.path.split(npath)
+            parts.append(last)
+        else:
+            return path
+
+
+class RewritePthDistributions(PthDistributions):
+    @classmethod
+    def _wrap_lines(cls, lines):
+        yield cls.prelude
+        yield from lines
+        yield cls.postlude
+
+    prelude = _one_liner(
+        """
+        import sys
+        sys.__plen = len(sys.path)
+        """
+    )
+    postlude = _one_liner(
+        """
+        import sys
+        new = sys.path[sys.__plen:]
+        del sys.path[sys.__plen:]
+        p = getattr(sys, '__egginsert', 0)
+        sys.path[p:p] = new
+        sys.__egginsert = p + len(new)
+        """
+    )
+
+
+if os.environ.get('SETUPTOOLS_SYS_PATH_TECHNIQUE', 'raw') == 'rewrite':
+    PthDistributions = RewritePthDistributions  # type: ignore[misc]  # Overwriting type
+
+
+def _first_line_re():
+    """
+    Return a regular expression based on first_line_re suitable for matching
+    strings.
+    """
+    if isinstance(first_line_re.pattern, str):
+        return first_line_re
+
+    # first_line_re in Python >=3.1.4 and >=3.2.1 is a bytes pattern.
+    return re.compile(first_line_re.pattern.decode())
+
+
+def update_dist_caches(dist_path, fix_zipimporter_caches):
+    """
+    Fix any globally cached `dist_path` related data
+
+    `dist_path` should be a path of a newly installed egg distribution (zipped
+    or unzipped).
+
+    sys.path_importer_cache contains finder objects that have been cached when
+    importing data from the original distribution. Any such finders need to be
+    cleared since the replacement distribution might be packaged differently,
+    e.g. a zipped egg distribution might get replaced with an unzipped egg
+    folder or vice versa. Having the old finders cached may then cause Python
+    to attempt loading modules from the replacement distribution using an
+    incorrect loader.
+
+    zipimport.zipimporter objects are Python loaders charged with importing
+    data packaged inside zip archives. If stale loaders referencing the
+    original distribution, are left behind, they can fail to load modules from
+    the replacement distribution. E.g. if an old zipimport.zipimporter instance
+    is used to load data from a new zipped egg archive, it may cause the
+    operation to attempt to locate the requested data in the wrong location -
+    one indicated by the original distribution's zip archive directory
+    information. Such an operation may then fail outright, e.g. report having
+    read a 'bad local file header', or even worse, it may fail silently &
+    return invalid data.
+
+    zipimport._zip_directory_cache contains cached zip archive directory
+    information for all existing zipimport.zipimporter instances and all such
+    instances connected to the same archive share the same cached directory
+    information.
+
+    If asked, and the underlying Python implementation allows it, we can fix
+    all existing zipimport.zipimporter instances instead of having to track
+    them down and remove them one by one, by updating their shared cached zip
+    archive directory information. This, of course, assumes that the
+    replacement distribution is packaged as a zipped egg.
+
+    If not asked to fix existing zipimport.zipimporter instances, we still do
+    our best to clear any remaining zipimport.zipimporter related cached data
+    that might somehow later get used when attempting to load data from the new
+    distribution and thus cause such load operations to fail. Note that when
+    tracking down such remaining stale data, we can not catch every conceivable
+    usage from here, and we clear only those that we know of and have found to
+    cause problems if left alive. Any remaining caches should be updated by
+    whomever is in charge of maintaining them, i.e. they should be ready to
+    handle us replacing their zip archives with new distributions at runtime.
+
+    """
+    # There are several other known sources of stale zipimport.zipimporter
+    # instances that we do not clear here, but might if ever given a reason to
+    # do so:
+    # * Global setuptools pkg_resources.working_set (a.k.a. 'master working
+    # set') may contain distributions which may in turn contain their
+    #   zipimport.zipimporter loaders.
+    # * Several zipimport.zipimporter loaders held by local variables further
+    #   up the function call stack when running the setuptools installation.
+    # * Already loaded modules may have their __loader__ attribute set to the
+    #   exact loader instance used when importing them. Python 3.4 docs state
+    #   that this information is intended mostly for introspection and so is
+    #   not expected to cause us problems.
+    normalized_path = normalize_path(dist_path)
+    _uncache(normalized_path, sys.path_importer_cache)
+    if fix_zipimporter_caches:
+        _replace_zip_directory_cache_data(normalized_path)
+    else:
+        # Here, even though we do not want to fix existing and now stale
+        # zipimporter cache information, we still want to remove it. Related to
+        # Python's zip archive directory information cache, we clear each of
+        # its stale entries in two phases:
+        #   1. Clear the entry so attempting to access zip archive information
+        #      via any existing stale zipimport.zipimporter instances fails.
+        #   2. Remove the entry from the cache so any newly constructed
+        #      zipimport.zipimporter instances do not end up using old stale
+        #      zip archive directory information.
+        # This whole stale data removal step does not seem strictly necessary,
+        # but has been left in because it was done before we started replacing
+        # the zip archive directory information cache content if possible, and
+        # there are no relevant unit tests that we can depend on to tell us if
+        # this is really needed.
+        _remove_and_clear_zip_directory_cache_data(normalized_path)
+
+
+def _collect_zipimporter_cache_entries(normalized_path, cache):
+    """
+    Return zipimporter cache entry keys related to a given normalized path.
+
+    Alternative path spellings (e.g. those using different character case or
+    those using alternative path separators) related to the same path are
+    included. Any sub-path entries are included as well, i.e. those
+    corresponding to zip archives embedded in other zip archives.
+
+    """
+    result = []
+    prefix_len = len(normalized_path)
+    for p in cache:
+        np = normalize_path(p)
+        if np.startswith(normalized_path) and np[prefix_len : prefix_len + 1] in (
+            os.sep,
+            '',
+        ):
+            result.append(p)
+    return result
+
+
+def _update_zipimporter_cache(normalized_path, cache, updater=None):
+    """
+    Update zipimporter cache data for a given normalized path.
+
+    Any sub-path entries are processed as well, i.e. those corresponding to zip
+    archives embedded in other zip archives.
+
+    Given updater is a callable taking a cache entry key and the original entry
+    (after already removing the entry from the cache), and expected to update
+    the entry and possibly return a new one to be inserted in its place.
+    Returning None indicates that the entry should not be replaced with a new
+    one. If no updater is given, the cache entries are simply removed without
+    any additional processing, the same as if the updater simply returned None.
+
+    """
+    for p in _collect_zipimporter_cache_entries(normalized_path, cache):
+        # N.B. pypy's custom zipimport._zip_directory_cache implementation does
+        # not support the complete dict interface:
+        # * Does not support item assignment, thus not allowing this function
+        #    to be used only for removing existing cache entries.
+        #  * Does not support the dict.pop() method, forcing us to use the
+        #    get/del patterns instead. For more detailed information see the
+        #    following links:
+        #      https://github.com/pypa/setuptools/issues/202#issuecomment-202913420
+        #      https://foss.heptapod.net/pypy/pypy/-/blob/144c4e65cb6accb8e592f3a7584ea38265d1873c/pypy/module/zipimport/interp_zipimport.py
+        old_entry = cache[p]
+        del cache[p]
+        new_entry = updater and updater(p, old_entry)
+        if new_entry is not None:
+            cache[p] = new_entry
+
+
+def _uncache(normalized_path, cache):
+    _update_zipimporter_cache(normalized_path, cache)
+
+
+def _remove_and_clear_zip_directory_cache_data(normalized_path):
+    def clear_and_remove_cached_zip_archive_directory_data(path, old_entry):
+        old_entry.clear()
+
+    _update_zipimporter_cache(
+        normalized_path,
+        zipimport._zip_directory_cache,
+        updater=clear_and_remove_cached_zip_archive_directory_data,
+    )
+
+
+# PyPy Python implementation does not allow directly writing to the
+# zipimport._zip_directory_cache and so prevents us from attempting to correct
+# its content. The best we can do there is clear the problematic cache content
+# and have PyPy repopulate it as needed. The downside is that if there are any
+# stale zipimport.zipimporter instances laying around, attempting to use them
+# will fail due to not having its zip archive directory information available
+# instead of being automatically corrected to use the new correct zip archive
+# directory information.
+if '__pypy__' in sys.builtin_module_names:
+    _replace_zip_directory_cache_data = _remove_and_clear_zip_directory_cache_data
+else:
+
+    def _replace_zip_directory_cache_data(normalized_path):
+        def replace_cached_zip_archive_directory_data(path, old_entry):
+            # N.B. In theory, we could load the zip directory information just
+            # once for all updated path spellings, and then copy it locally and
+            # update its contained path strings to contain the correct
+            # spelling, but that seems like a way too invasive move (this cache
+            # structure is not officially documented anywhere and could in
+            # theory change with new Python releases) for no significant
+            # benefit.
+            old_entry.clear()
+            zipimport.zipimporter(path)
+            old_entry.update(zipimport._zip_directory_cache[path])
+            return old_entry
+
+        _update_zipimporter_cache(
+            normalized_path,
+            zipimport._zip_directory_cache,
+            updater=replace_cached_zip_archive_directory_data,
+        )
+
+
+def is_python(text, filename=''):
+    "Is this string a valid Python script?"
+    try:
+        compile(text, filename, 'exec')
+    except (SyntaxError, TypeError):
+        return False
+    else:
+        return True
+
+
+def is_sh(executable):
+    """Determine if the specified executable is a .sh (contains a #! line)"""
+    try:
+        with open(executable, encoding='latin-1') as fp:
+            magic = fp.read(2)
+    except OSError:
+        return executable
+    return magic == '#!'
+
+
+def nt_quote_arg(arg):
+    """Quote a command line argument according to Windows parsing rules"""
+    return subprocess.list2cmdline([arg])
+
+
+def is_python_script(script_text, filename):
+    """Is this text, as a whole, a Python script? (as opposed to shell/bat/etc."""
+    if filename.endswith('.py') or filename.endswith('.pyw'):
+        return True  # extension says it's Python
+    if is_python(script_text, filename):
+        return True  # it's syntactically valid Python
+    if script_text.startswith('#!'):
+        # It begins with a '#!' line, so check if 'python' is in it somewhere
+        return 'python' in script_text.splitlines()[0].lower()
+
+    return False  # Not any Python I can recognize
+
+
+class _SplitArgs(TypedDict, total=False):
+    comments: bool
+    posix: bool
+
+
+class CommandSpec(list):
+    """
+    A command spec for a #! header, specified as a list of arguments akin to
+    those passed to Popen.
+    """
+
+    options: list[str] = []
+    split_args = _SplitArgs()
+
+    @classmethod
+    def best(cls):
+        """
+        Choose the best CommandSpec class based on environmental conditions.
+        """
+        return cls
+
+    @classmethod
+    def _sys_executable(cls):
+        _default = os.path.normpath(sys.executable)
+        return os.environ.get('__PYVENV_LAUNCHER__', _default)
+
+    @classmethod
+    def from_param(cls, param: Self | str | Iterable[str] | None) -> Self:
+        """
+        Construct a CommandSpec from a parameter to build_scripts, which may
+        be None.
+        """
+        if isinstance(param, cls):
+            return param
+        if isinstance(param, str):
+            return cls.from_string(param)
+        if isinstance(param, Iterable):
+            return cls(param)
+        if param is None:
+            return cls.from_environment()
+        raise TypeError(f"Argument has an unsupported type {type(param)}")
+
+    @classmethod
+    def from_environment(cls):
+        return cls([cls._sys_executable()])
+
+    @classmethod
+    def from_string(cls, string: str) -> Self:
+        """
+        Construct a command spec from a simple string representing a command
+        line parseable by shlex.split.
+        """
+        items = shlex.split(string, **cls.split_args)
+        return cls(items)
+
+    def install_options(self, script_text: str):
+        self.options = shlex.split(self._extract_options(script_text))
+        cmdline = subprocess.list2cmdline(self)
+        if not isascii(cmdline):
+            self.options[:0] = ['-x']
+
+    @staticmethod
+    def _extract_options(orig_script):
+        """
+        Extract any options from the first line of the script.
+        """
+        first = (orig_script + '\n').splitlines()[0]
+        match = _first_line_re().match(first)
+        options = match.group(1) or '' if match else ''
+        return options.strip()
+
+    def as_header(self):
+        return self._render(self + list(self.options))
+
+    @staticmethod
+    def _strip_quotes(item):
+        _QUOTES = '"\''
+        for q in _QUOTES:
+            if item.startswith(q) and item.endswith(q):
+                return item[1:-1]
+        return item
+
+    @staticmethod
+    def _render(items):
+        cmdline = subprocess.list2cmdline(
+            CommandSpec._strip_quotes(item.strip()) for item in items
+        )
+        return '#!' + cmdline + '\n'
+
+
+# For pbr compat; will be removed in a future version.
+sys_executable = CommandSpec._sys_executable()
+
+
+class WindowsCommandSpec(CommandSpec):
+    split_args = _SplitArgs(posix=False)
+
+
+class ScriptWriter:
+    """
+    Encapsulates behavior around writing entry point scripts for console and
+    gui apps.
+    """
+
+    template = textwrap.dedent(
+        r"""
+        # EASY-INSTALL-ENTRY-SCRIPT: %(spec)r,%(group)r,%(name)r
+        import re
+        import sys
+
+        # for compatibility with easy_install; see #2198
+        __requires__ = %(spec)r
+
+        try:
+            from importlib.metadata import distribution
+        except ImportError:
+            try:
+                from importlib_metadata import distribution
+            except ImportError:
+                from pkg_resources import load_entry_point
+
+
+        def importlib_load_entry_point(spec, group, name):
+            dist_name, _, _ = spec.partition('==')
+            matches = (
+                entry_point
+                for entry_point in distribution(dist_name).entry_points
+                if entry_point.group == group and entry_point.name == name
+            )
+            return next(matches).load()
+
+
+        globals().setdefault('load_entry_point', importlib_load_entry_point)
+
+
+        if __name__ == '__main__':
+            sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
+            sys.exit(load_entry_point(%(spec)r, %(group)r, %(name)r)())
+        """
+    ).lstrip()
+
+    command_spec_class = CommandSpec
+
+    @classmethod
+    def get_args(cls, dist, header=None):
+        """
+        Yield write_script() argument tuples for a distribution's
+        console_scripts and gui_scripts entry points.
+        """
+        if header is None:
+            header = cls.get_header()
+        spec = str(dist.as_requirement())
+        for type_ in 'console', 'gui':
+            group = type_ + '_scripts'
+            for name in dist.get_entry_map(group).keys():
+                cls._ensure_safe_name(name)
+                script_text = cls.template % locals()
+                args = cls._get_script_args(type_, name, header, script_text)
+                yield from args
+
+    @staticmethod
+    def _ensure_safe_name(name):
+        """
+        Prevent paths in *_scripts entry point names.
+        """
+        has_path_sep = re.search(r'[\\/]', name)
+        if has_path_sep:
+            raise ValueError("Path separators not allowed in script names")
+
+    @classmethod
+    def best(cls):
+        """
+        Select the best ScriptWriter for this environment.
+        """
+        if sys.platform == 'win32' or (os.name == 'java' and os._name == 'nt'):
+            return WindowsScriptWriter.best()
+        else:
+            return cls
+
+    @classmethod
+    def _get_script_args(cls, type_, name, header, script_text):
+        # Simply write the stub with no extension.
+        yield (name, header + script_text)
+
+    @classmethod
+    def get_header(
+        cls,
+        script_text: str = "",
+        executable: str | CommandSpec | Iterable[str] | None = None,
+    ) -> str:
+        """Create a #! line, getting options (if any) from script_text"""
+        cmd = cls.command_spec_class.best().from_param(executable)
+        cmd.install_options(script_text)
+        return cmd.as_header()
+
+
+class WindowsScriptWriter(ScriptWriter):
+    command_spec_class = WindowsCommandSpec
+
+    @classmethod
+    def best(cls):
+        """
+        Select the best ScriptWriter suitable for Windows
+        """
+        writer_lookup = dict(
+            executable=WindowsExecutableLauncherWriter,
+            natural=cls,
+        )
+        # for compatibility, use the executable launcher by default
+        launcher = os.environ.get('SETUPTOOLS_LAUNCHER', 'executable')
+        return writer_lookup[launcher]
+
+    @classmethod
+    def _get_script_args(cls, type_, name, header, script_text):
+        "For Windows, add a .py extension"
+        ext = dict(console='.pya', gui='.pyw')[type_]
+        if ext not in os.environ['PATHEXT'].lower().split(';'):
+            msg = (
+                "{ext} not listed in PATHEXT; scripts will not be "
+                "recognized as executables."
+            ).format(**locals())
+            SetuptoolsWarning.emit(msg)
+        old = ['.pya', '.py', '-script.py', '.pyc', '.pyo', '.pyw', '.exe']
+        old.remove(ext)
+        header = cls._adjust_header(type_, header)
+        blockers = [name + x for x in old]
+        yield name + ext, header + script_text, 't', blockers
+
+    @classmethod
+    def _adjust_header(cls, type_, orig_header):
+        """
+        Make sure 'pythonw' is used for gui and 'python' is used for
+        console (regardless of what sys.executable is).
+        """
+        pattern = 'pythonw.exe'
+        repl = 'python.exe'
+        if type_ == 'gui':
+            pattern, repl = repl, pattern
+        pattern_ob = re.compile(re.escape(pattern), re.IGNORECASE)
+        new_header = pattern_ob.sub(string=orig_header, repl=repl)
+        return new_header if cls._use_header(new_header) else orig_header
+
+    @staticmethod
+    def _use_header(new_header):
+        """
+        Should _adjust_header use the replaced header?
+
+        On non-windows systems, always use. On
+        Windows systems, only use the replaced header if it resolves
+        to an executable on the system.
+        """
+        clean_header = new_header[2:-1].strip('"')
+        return sys.platform != 'win32' or shutil.which(clean_header)
+
+
+class WindowsExecutableLauncherWriter(WindowsScriptWriter):
+    @classmethod
+    def _get_script_args(cls, type_, name, header, script_text):
+        """
+        For Windows, add a .py extension and an .exe launcher
+        """
+        if type_ == 'gui':
+            launcher_type = 'gui'
+            ext = '-script.pyw'
+            old = ['.pyw']
+        else:
+            launcher_type = 'cli'
+            ext = '-script.py'
+            old = ['.py', '.pyc', '.pyo']
+        hdr = cls._adjust_header(type_, header)
+        blockers = [name + x for x in old]
+        yield (name + ext, hdr + script_text, 't', blockers)
+        yield (
+            name + '.exe',
+            get_win_launcher(launcher_type),
+            'b',  # write in binary mode
+        )
+        if not is_64bit():
+            # install a manifest for the launcher to prevent Windows
+            # from detecting it as an installer (which it will for
+            #  launchers like easy_install.exe). Consider only
+            #  adding a manifest for launchers detected as installers.
+            #  See Distribute #143 for details.
+            m_name = name + '.exe.manifest'
+            yield (m_name, load_launcher_manifest(name), 't')
+
+
+def get_win_launcher(type):
+    """
+    Load the Windows launcher (executable) suitable for launching a script.
+
+    `type` should be either 'cli' or 'gui'
+
+    Returns the executable as a byte string.
+    """
+    launcher_fn = f'{type}.exe'
+    if is_64bit():
+        if get_platform() == "win-arm64":
+            launcher_fn = launcher_fn.replace(".", "-arm64.")
+        else:
+            launcher_fn = launcher_fn.replace(".", "-64.")
+    else:
+        launcher_fn = launcher_fn.replace(".", "-32.")
+    return resource_string('setuptools', launcher_fn)
+
+
+def load_launcher_manifest(name):
+    manifest = pkg_resources.resource_string(__name__, 'launcher manifest.xml')
+    return manifest.decode('utf-8') % vars()
+
+
+def current_umask():
+    tmp = os.umask(0o022)
+    os.umask(tmp)
+    return tmp
+
+
+def only_strs(values):
+    """
+    Exclude non-str values. Ref #3063.
+    """
+    return filter(lambda val: isinstance(val, str), values)
+
+
+def _read_pth(fullname: str) -> str:
+    # Python<3.13 require encoding="locale" instead of "utf-8", see python/cpython#77102
+    # In the case old versions of setuptools are producing `pth` files with
+    # different encodings that might be problematic... So we fallback to "locale".
+
+    try:
+        with open(fullname, encoding=py312.PTH_ENCODING) as f:
+            return f.read()
+    except UnicodeDecodeError:  # pragma: no cover
+        # This error may only happen for Python >= 3.13
+        # TODO: Possible deprecation warnings to be added in the future:
+        #       ``.pth file {fullname!r} is not UTF-8.``
+        #       Your environment contain {fullname!r} that cannot be read as UTF-8.
+        #       This is likely to have been produced with an old version of setuptools.
+        #       Please be mindful that this is deprecated and in the future, non-utf8
+        #       .pth files may cause setuptools to fail.
+        with open(fullname, encoding=py39.LOCALE_ENCODING) as f:
+            return f.read()
+
+
+class EasyInstallDeprecationWarning(SetuptoolsDeprecationWarning):
+    _SUMMARY = "easy_install command is deprecated."
+    _DETAILS = """
+    Please avoid running ``setup.py`` and ``easy_install``.
+    Instead, use pypa/build, pypa/installer or other
+    standards-based tools.
+    """
+    _SEE_URL = "https://github.com/pypa/setuptools/issues/917"
+    # _DUE_DATE not defined yet
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/editable_wheel.py b/.venv/lib/python3.12/site-packages/setuptools/command/editable_wheel.py
new file mode 100644
index 0000000000000000000000000000000000000000..1a544ec258196616a4242b679c20b061c1c4010d
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/command/editable_wheel.py
@@ -0,0 +1,925 @@
+"""
+Create a wheel that, when installed, will make the source package 'editable'
+(add it to the interpreter's path, including metadata) per PEP 660. Replaces
+'setup.py develop'.
+
+.. note::
+   One of the mechanisms briefly mentioned in PEP 660 to implement editable installs is
+   to create a separated directory inside ``build`` and use a .pth file to point to that
+   directory. In the context of this file such directory is referred as
+   *auxiliary build directory* or ``auxiliary_dir``.
+"""
+
+from __future__ import annotations
+
+import io
+import logging
+import os
+import shutil
+import traceback
+from collections.abc import Iterable, Iterator, Mapping
+from contextlib import suppress
+from enum import Enum
+from inspect import cleandoc
+from itertools import chain, starmap
+from pathlib import Path
+from tempfile import TemporaryDirectory
+from types import TracebackType
+from typing import TYPE_CHECKING, Protocol, TypeVar, cast
+
+from .. import Command, _normalization, _path, _shutil, errors, namespaces
+from .._path import StrPath
+from ..compat import py312
+from ..discovery import find_package_path
+from ..dist import Distribution
+from ..warnings import InformationOnly, SetuptoolsDeprecationWarning, SetuptoolsWarning
+from .build import build as build_cls
+from .build_py import build_py as build_py_cls
+from .dist_info import dist_info as dist_info_cls
+from .egg_info import egg_info as egg_info_cls
+from .install import install as install_cls
+from .install_scripts import install_scripts as install_scripts_cls
+
+if TYPE_CHECKING:
+    from typing_extensions import Self
+
+    from .._vendor.wheel.wheelfile import WheelFile
+
+_P = TypeVar("_P", bound=StrPath)
+_logger = logging.getLogger(__name__)
+
+
+class _EditableMode(Enum):
+    """
+    Possible editable installation modes:
+    `lenient` (new files automatically added to the package - DEFAULT);
+    `strict` (requires a new installation when files are added/removed); or
+    `compat` (attempts to emulate `python setup.py develop` - DEPRECATED).
+    """
+
+    STRICT = "strict"
+    LENIENT = "lenient"
+    COMPAT = "compat"  # TODO: Remove `compat` after Dec/2022.
+
+    @classmethod
+    def convert(cls, mode: str | None) -> _EditableMode:
+        if not mode:
+            return _EditableMode.LENIENT  # default
+
+        _mode = mode.upper()
+        if _mode not in _EditableMode.__members__:
+            raise errors.OptionError(f"Invalid editable mode: {mode!r}. Try: 'strict'.")
+
+        if _mode == "COMPAT":
+            SetuptoolsDeprecationWarning.emit(
+                "Compat editable installs",
+                """
+                The 'compat' editable mode is transitional and will be removed
+                in future versions of `setuptools`.
+                Please adapt your code accordingly to use either the 'strict' or the
+                'lenient' modes.
+                """,
+                see_docs="userguide/development_mode.html",
+                # TODO: define due_date
+                # There is a series of shortcomings with the available editable install
+                # methods, and they are very controversial. This is something that still
+                # needs work.
+                # Moreover, `pip` is still hiding this warning, so users are not aware.
+            )
+
+        return _EditableMode[_mode]
+
+
+_STRICT_WARNING = """
+New or renamed files may not be automatically picked up without a new installation.
+"""
+
+_LENIENT_WARNING = """
+Options like `package-data`, `include/exclude-package-data` or
+`packages.find.exclude/include` may have no effect.
+"""
+
+
+class editable_wheel(Command):
+    """Build 'editable' wheel for development.
+    This command is private and reserved for internal use of setuptools,
+    users should rely on ``setuptools.build_meta`` APIs.
+    """
+
+    description = "DO NOT CALL DIRECTLY, INTERNAL ONLY: create PEP 660 editable wheel"
+
+    user_options = [
+        ("dist-dir=", "d", "directory to put final built distributions in"),
+        ("dist-info-dir=", "I", "path to a pre-build .dist-info directory"),
+        ("mode=", None, cleandoc(_EditableMode.__doc__ or "")),
+    ]
+
+    def initialize_options(self):
+        self.dist_dir = None
+        self.dist_info_dir = None
+        self.project_dir = None
+        self.mode = None
+
+    def finalize_options(self) -> None:
+        dist = self.distribution
+        self.project_dir = dist.src_root or os.curdir
+        self.package_dir = dist.package_dir or {}
+        self.dist_dir = Path(self.dist_dir or os.path.join(self.project_dir, "dist"))
+
+    def run(self) -> None:
+        try:
+            self.dist_dir.mkdir(exist_ok=True)
+            self._ensure_dist_info()
+
+            # Add missing dist_info files
+            self.reinitialize_command("bdist_wheel")
+            bdist_wheel = self.get_finalized_command("bdist_wheel")
+            bdist_wheel.write_wheelfile(self.dist_info_dir)
+
+            self._create_wheel_file(bdist_wheel)
+        except Exception:
+            traceback.print_exc()
+            project = self.distribution.name or self.distribution.get_name()
+            _DebuggingTips.emit(project=project)
+            raise
+
+    def _ensure_dist_info(self):
+        if self.dist_info_dir is None:
+            dist_info = cast(dist_info_cls, self.reinitialize_command("dist_info"))
+            dist_info.output_dir = self.dist_dir
+            dist_info.ensure_finalized()
+            dist_info.run()
+            self.dist_info_dir = dist_info.dist_info_dir
+        else:
+            assert str(self.dist_info_dir).endswith(".dist-info")
+            assert Path(self.dist_info_dir, "METADATA").exists()
+
+    def _install_namespaces(self, installation_dir, pth_prefix):
+        # XXX: Only required to support the deprecated namespace practice
+        dist = self.distribution
+        if not dist.namespace_packages:
+            return
+
+        src_root = Path(self.project_dir, self.package_dir.get("", ".")).resolve()
+        installer = _NamespaceInstaller(dist, installation_dir, pth_prefix, src_root)
+        installer.install_namespaces()
+
+    def _find_egg_info_dir(self) -> str | None:
+        parent_dir = Path(self.dist_info_dir).parent if self.dist_info_dir else Path()
+        candidates = map(str, parent_dir.glob("*.egg-info"))
+        return next(candidates, None)
+
+    def _configure_build(
+        self, name: str, unpacked_wheel: StrPath, build_lib: StrPath, tmp_dir: StrPath
+    ):
+        """Configure commands to behave in the following ways:
+
+        - Build commands can write to ``build_lib`` if they really want to...
+          (but this folder is expected to be ignored and modules are expected to live
+          in the project directory...)
+        - Binary extensions should be built in-place (editable_mode = True)
+        - Data/header/script files are not part of the "editable" specification
+          so they are written directly to the unpacked_wheel directory.
+        """
+        # Non-editable files (data, headers, scripts) are written directly to the
+        # unpacked_wheel
+
+        dist = self.distribution
+        wheel = str(unpacked_wheel)
+        build_lib = str(build_lib)
+        data = str(Path(unpacked_wheel, f"{name}.data", "data"))
+        headers = str(Path(unpacked_wheel, f"{name}.data", "headers"))
+        scripts = str(Path(unpacked_wheel, f"{name}.data", "scripts"))
+
+        # egg-info may be generated again to create a manifest (used for package data)
+        egg_info = cast(
+            egg_info_cls, dist.reinitialize_command("egg_info", reinit_subcommands=True)
+        )
+        egg_info.egg_base = str(tmp_dir)
+        egg_info.ignore_egg_info_in_manifest = True
+
+        build = cast(
+            build_cls, dist.reinitialize_command("build", reinit_subcommands=True)
+        )
+        install = cast(
+            install_cls, dist.reinitialize_command("install", reinit_subcommands=True)
+        )
+
+        build.build_platlib = build.build_purelib = build.build_lib = build_lib
+        install.install_purelib = install.install_platlib = install.install_lib = wheel
+        install.install_scripts = build.build_scripts = scripts
+        install.install_headers = headers
+        install.install_data = data
+
+        install_scripts = cast(
+            install_scripts_cls, dist.get_command_obj("install_scripts")
+        )
+        install_scripts.no_ep = True
+
+        build.build_temp = str(tmp_dir)
+
+        build_py = cast(build_py_cls, dist.get_command_obj("build_py"))
+        build_py.compile = False
+        build_py.existing_egg_info_dir = self._find_egg_info_dir()
+
+        self._set_editable_mode()
+
+        build.ensure_finalized()
+        install.ensure_finalized()
+
+    def _set_editable_mode(self):
+        """Set the ``editable_mode`` flag in the build sub-commands"""
+        dist = self.distribution
+        build = dist.get_command_obj("build")
+        for cmd_name in build.get_sub_commands():
+            cmd = dist.get_command_obj(cmd_name)
+            if hasattr(cmd, "editable_mode"):
+                cmd.editable_mode = True
+            elif hasattr(cmd, "inplace"):
+                cmd.inplace = True  # backward compatibility with distutils
+
+    def _collect_build_outputs(self) -> tuple[list[str], dict[str, str]]:
+        files: list[str] = []
+        mapping: dict[str, str] = {}
+        build = self.get_finalized_command("build")
+
+        for cmd_name in build.get_sub_commands():
+            cmd = self.get_finalized_command(cmd_name)
+            if hasattr(cmd, "get_outputs"):
+                files.extend(cmd.get_outputs() or [])
+            if hasattr(cmd, "get_output_mapping"):
+                mapping.update(cmd.get_output_mapping() or {})
+
+        return files, mapping
+
+    def _run_build_commands(
+        self,
+        dist_name: str,
+        unpacked_wheel: StrPath,
+        build_lib: StrPath,
+        tmp_dir: StrPath,
+    ) -> tuple[list[str], dict[str, str]]:
+        self._configure_build(dist_name, unpacked_wheel, build_lib, tmp_dir)
+        self._run_build_subcommands()
+        files, mapping = self._collect_build_outputs()
+        self._run_install("headers")
+        self._run_install("scripts")
+        self._run_install("data")
+        return files, mapping
+
+    def _run_build_subcommands(self) -> None:
+        """
+        Issue #3501 indicates that some plugins/customizations might rely on:
+
+        1. ``build_py`` not running
+        2. ``build_py`` always copying files to ``build_lib``
+
+        However both these assumptions may be false in editable_wheel.
+        This method implements a temporary workaround to support the ecosystem
+        while the implementations catch up.
+        """
+        # TODO: Once plugins/customizations had the chance to catch up, replace
+        #       `self._run_build_subcommands()` with `self.run_command("build")`.
+        #       Also remove _safely_run, TestCustomBuildPy. Suggested date: Aug/2023.
+        build = self.get_finalized_command("build")
+        for name in build.get_sub_commands():
+            cmd = self.get_finalized_command(name)
+            if name == "build_py" and type(cmd) is not build_py_cls:
+                self._safely_run(name)
+            else:
+                self.run_command(name)
+
+    def _safely_run(self, cmd_name: str):
+        try:
+            return self.run_command(cmd_name)
+        except Exception:
+            SetuptoolsDeprecationWarning.emit(
+                "Customization incompatible with editable install",
+                f"""
+                {traceback.format_exc()}
+
+                If you are seeing this warning it is very likely that a setuptools
+                plugin or customization overrides the `{cmd_name}` command, without
+                taking into consideration how editable installs run build steps
+                starting from setuptools v64.0.0.
+
+                Plugin authors and developers relying on custom build steps are
+                encouraged to update their `{cmd_name}` implementation considering the
+                information about editable installs in
+                https://setuptools.pypa.io/en/latest/userguide/extension.html.
+
+                For the time being `setuptools` will silence this error and ignore
+                the faulty command, but this behavior will change in future versions.
+                """,
+                # TODO: define due_date
+                # There is a series of shortcomings with the available editable install
+                # methods, and they are very controversial. This is something that still
+                # needs work.
+            )
+
+    def _create_wheel_file(self, bdist_wheel):
+        from wheel.wheelfile import WheelFile
+
+        dist_info = self.get_finalized_command("dist_info")
+        dist_name = dist_info.name
+        tag = "-".join(bdist_wheel.get_tag())
+        build_tag = "0.editable"  # According to PEP 427 needs to start with digit
+        archive_name = f"{dist_name}-{build_tag}-{tag}.whl"
+        wheel_path = Path(self.dist_dir, archive_name)
+        if wheel_path.exists():
+            wheel_path.unlink()
+
+        unpacked_wheel = TemporaryDirectory(suffix=archive_name)
+        build_lib = TemporaryDirectory(suffix=".build-lib")
+        build_tmp = TemporaryDirectory(suffix=".build-temp")
+
+        with unpacked_wheel as unpacked, build_lib as lib, build_tmp as tmp:
+            unpacked_dist_info = Path(unpacked, Path(self.dist_info_dir).name)
+            shutil.copytree(self.dist_info_dir, unpacked_dist_info)
+            self._install_namespaces(unpacked, dist_name)
+            files, mapping = self._run_build_commands(dist_name, unpacked, lib, tmp)
+            strategy = self._select_strategy(dist_name, tag, lib)
+            with strategy, WheelFile(wheel_path, "w") as wheel_obj:
+                strategy(wheel_obj, files, mapping)
+                wheel_obj.write_files(unpacked)
+
+        return wheel_path
+
+    def _run_install(self, category: str):
+        has_category = getattr(self.distribution, f"has_{category}", None)
+        if has_category and has_category():
+            _logger.info(f"Installing {category} as non editable")
+            self.run_command(f"install_{category}")
+
+    def _select_strategy(
+        self,
+        name: str,
+        tag: str,
+        build_lib: StrPath,
+    ) -> EditableStrategy:
+        """Decides which strategy to use to implement an editable installation."""
+        build_name = f"__editable__.{name}-{tag}"
+        project_dir = Path(self.project_dir)
+        mode = _EditableMode.convert(self.mode)
+
+        if mode is _EditableMode.STRICT:
+            auxiliary_dir = _empty_dir(Path(self.project_dir, "build", build_name))
+            return _LinkTree(self.distribution, name, auxiliary_dir, build_lib)
+
+        packages = _find_packages(self.distribution)
+        has_simple_layout = _simple_layout(packages, self.package_dir, project_dir)
+        is_compat_mode = mode is _EditableMode.COMPAT
+        if set(self.package_dir) == {""} and has_simple_layout or is_compat_mode:
+            # src-layout(ish) is relatively safe for a simple pth file
+            src_dir = self.package_dir.get("", ".")
+            return _StaticPth(self.distribution, name, [Path(project_dir, src_dir)])
+
+        # Use a MetaPathFinder to avoid adding accidental top-level packages/modules
+        return _TopLevelFinder(self.distribution, name)
+
+
+class EditableStrategy(Protocol):
+    def __call__(
+        self, wheel: WheelFile, files: list[str], mapping: Mapping[str, str]
+    ) -> object: ...
+    def __enter__(self) -> Self: ...
+    def __exit__(
+        self,
+        _exc_type: type[BaseException] | None,
+        _exc_value: BaseException | None,
+        _traceback: TracebackType | None,
+    ) -> object: ...
+
+
+class _StaticPth:
+    def __init__(self, dist: Distribution, name: str, path_entries: list[Path]) -> None:
+        self.dist = dist
+        self.name = name
+        self.path_entries = path_entries
+
+    def __call__(self, wheel: WheelFile, files: list[str], mapping: Mapping[str, str]):
+        entries = "\n".join(str(p.resolve()) for p in self.path_entries)
+        contents = _encode_pth(f"{entries}\n")
+        wheel.writestr(f"__editable__.{self.name}.pth", contents)
+
+    def __enter__(self) -> Self:
+        msg = f"""
+        Editable install will be performed using .pth file to extend `sys.path` with:
+        {list(map(os.fspath, self.path_entries))!r}
+        """
+        _logger.warning(msg + _LENIENT_WARNING)
+        return self
+
+    def __exit__(
+        self,
+        _exc_type: object,
+        _exc_value: object,
+        _traceback: object,
+    ) -> None:
+        pass
+
+
+class _LinkTree(_StaticPth):
+    """
+    Creates a ``.pth`` file that points to a link tree in the ``auxiliary_dir``.
+
+    This strategy will only link files (not dirs), so it can be implemented in
+    any OS, even if that means using hardlinks instead of symlinks.
+
+    By collocating ``auxiliary_dir`` and the original source code, limitations
+    with hardlinks should be avoided.
+    """
+
+    def __init__(
+        self,
+        dist: Distribution,
+        name: str,
+        auxiliary_dir: StrPath,
+        build_lib: StrPath,
+    ) -> None:
+        self.auxiliary_dir = Path(auxiliary_dir)
+        self.build_lib = Path(build_lib).resolve()
+        self._file = dist.get_command_obj("build_py").copy_file
+        super().__init__(dist, name, [self.auxiliary_dir])
+
+    def __call__(self, wheel: WheelFile, files: list[str], mapping: Mapping[str, str]):
+        self._create_links(files, mapping)
+        super().__call__(wheel, files, mapping)
+
+    def _normalize_output(self, file: str) -> str | None:
+        # Files relative to build_lib will be normalized to None
+        with suppress(ValueError):
+            path = Path(file).resolve().relative_to(self.build_lib)
+            return str(path).replace(os.sep, '/')
+        return None
+
+    def _create_file(self, relative_output: str, src_file: str, link=None):
+        dest = self.auxiliary_dir / relative_output
+        if not dest.parent.is_dir():
+            dest.parent.mkdir(parents=True)
+        self._file(src_file, dest, link=link)
+
+    def _create_links(self, outputs, output_mapping: Mapping[str, str]):
+        self.auxiliary_dir.mkdir(parents=True, exist_ok=True)
+        link_type = "sym" if _can_symlink_files(self.auxiliary_dir) else "hard"
+        normalised = ((self._normalize_output(k), v) for k, v in output_mapping.items())
+        # remove files that are not relative to build_lib
+        mappings = {k: v for k, v in normalised if k is not None}
+
+        for output in outputs:
+            relative = self._normalize_output(output)
+            if relative and relative not in mappings:
+                self._create_file(relative, output)
+
+        for relative, src in mappings.items():
+            self._create_file(relative, src, link=link_type)
+
+    def __enter__(self) -> Self:
+        msg = "Strict editable install will be performed using a link tree.\n"
+        _logger.warning(msg + _STRICT_WARNING)
+        return self
+
+    def __exit__(
+        self,
+        _exc_type: object,
+        _exc_value: object,
+        _traceback: object,
+    ) -> None:
+        msg = f"""\n
+        Strict editable installation performed using the auxiliary directory:
+            {self.auxiliary_dir}
+
+        Please be careful to not remove this directory, otherwise you might not be able
+        to import/use your package.
+        """
+        InformationOnly.emit("Editable installation.", msg)
+
+
+class _TopLevelFinder:
+    def __init__(self, dist: Distribution, name: str) -> None:
+        self.dist = dist
+        self.name = name
+
+    def template_vars(self) -> tuple[str, str, dict[str, str], dict[str, list[str]]]:
+        src_root = self.dist.src_root or os.curdir
+        top_level = chain(_find_packages(self.dist), _find_top_level_modules(self.dist))
+        package_dir = self.dist.package_dir or {}
+        roots = _find_package_roots(top_level, package_dir, src_root)
+
+        namespaces_ = dict(
+            chain(
+                _find_namespaces(self.dist.packages or [], roots),
+                ((ns, []) for ns in _find_virtual_namespaces(roots)),
+            )
+        )
+
+        legacy_namespaces = {
+            pkg: find_package_path(pkg, roots, self.dist.src_root or "")
+            for pkg in self.dist.namespace_packages or []
+        }
+
+        mapping = {**roots, **legacy_namespaces}
+        # ^-- We need to explicitly add the legacy_namespaces to the mapping to be
+        #     able to import their modules even if another package sharing the same
+        #     namespace is installed in a conventional (non-editable) way.
+
+        name = f"__editable__.{self.name}.finder"
+        finder = _normalization.safe_identifier(name)
+        return finder, name, mapping, namespaces_
+
+    def get_implementation(self) -> Iterator[tuple[str, bytes]]:
+        finder, name, mapping, namespaces_ = self.template_vars()
+
+        content = bytes(_finder_template(name, mapping, namespaces_), "utf-8")
+        yield (f"{finder}.py", content)
+
+        content = _encode_pth(f"import {finder}; {finder}.install()")
+        yield (f"__editable__.{self.name}.pth", content)
+
+    def __call__(self, wheel: WheelFile, files: list[str], mapping: Mapping[str, str]):
+        for file, content in self.get_implementation():
+            wheel.writestr(file, content)
+
+    def __enter__(self) -> Self:
+        msg = "Editable install will be performed using a meta path finder.\n"
+        _logger.warning(msg + _LENIENT_WARNING)
+        return self
+
+    def __exit__(
+        self,
+        _exc_type: object,
+        _exc_value: object,
+        _traceback: object,
+    ) -> None:
+        msg = """\n
+        Please be careful with folders in your working directory with the same
+        name as your package as they may take precedence during imports.
+        """
+        InformationOnly.emit("Editable installation.", msg)
+
+
+def _encode_pth(content: str) -> bytes:
+    """
+    Prior to Python 3.13 (see https://github.com/python/cpython/issues/77102),
+    .pth files are always read with 'locale' encoding, the recommendation
+    from the cpython core developers is to write them as ``open(path, "w")``
+    and ignore warnings (see python/cpython#77102, pypa/setuptools#3937).
+    This function tries to simulate this behavior without having to create an
+    actual file, in a way that supports a range of active Python versions.
+    (There seems to be some variety in the way different version of Python handle
+    ``encoding=None``, not all of them use ``locale.getpreferredencoding(False)``
+    or ``locale.getencoding()``).
+    """
+    with io.BytesIO() as buffer:
+        wrapper = io.TextIOWrapper(buffer, encoding=py312.PTH_ENCODING)
+        # TODO: Python 3.13 replace the whole function with `bytes(content, "utf-8")`
+        wrapper.write(content)
+        wrapper.flush()
+        buffer.seek(0)
+        return buffer.read()
+
+
+def _can_symlink_files(base_dir: Path) -> bool:
+    with TemporaryDirectory(dir=str(base_dir.resolve())) as tmp:
+        path1, path2 = Path(tmp, "file1.txt"), Path(tmp, "file2.txt")
+        path1.write_text("file1", encoding="utf-8")
+        with suppress(AttributeError, NotImplementedError, OSError):
+            os.symlink(path1, path2)
+            if path2.is_symlink() and path2.read_text(encoding="utf-8") == "file1":
+                return True
+
+        try:
+            os.link(path1, path2)  # Ensure hard links can be created
+        except Exception as ex:
+            msg = (
+                "File system does not seem to support either symlinks or hard links. "
+                "Strict editable installs require one of them to be supported."
+            )
+            raise LinksNotSupported(msg) from ex
+        return False
+
+
+def _simple_layout(
+    packages: Iterable[str], package_dir: dict[str, str], project_dir: StrPath
+) -> bool:
+    """Return ``True`` if:
+    - all packages are contained by the same parent directory, **and**
+    - all packages become importable if the parent directory is added to ``sys.path``.
+
+    >>> _simple_layout(['a'], {"": "src"}, "/tmp/myproj")
+    True
+    >>> _simple_layout(['a', 'a.b'], {"": "src"}, "/tmp/myproj")
+    True
+    >>> _simple_layout(['a', 'a.b'], {}, "/tmp/myproj")
+    True
+    >>> _simple_layout(['a', 'a.a1', 'a.a1.a2', 'b'], {"": "src"}, "/tmp/myproj")
+    True
+    >>> _simple_layout(['a', 'a.a1', 'a.a1.a2', 'b'], {"a": "a", "b": "b"}, ".")
+    True
+    >>> _simple_layout(['a', 'a.a1', 'a.a1.a2', 'b'], {"a": "_a", "b": "_b"}, ".")
+    False
+    >>> _simple_layout(['a', 'a.a1', 'a.a1.a2', 'b'], {"a": "_a"}, "/tmp/myproj")
+    False
+    >>> _simple_layout(['a', 'a.a1', 'a.a1.a2', 'b'], {"a.a1.a2": "_a2"}, ".")
+    False
+    >>> _simple_layout(['a', 'a.b'], {"": "src", "a.b": "_ab"}, "/tmp/myproj")
+    False
+    >>> # Special cases, no packages yet:
+    >>> _simple_layout([], {"": "src"}, "/tmp/myproj")
+    True
+    >>> _simple_layout([], {"a": "_a", "": "src"}, "/tmp/myproj")
+    False
+    """
+    layout = {pkg: find_package_path(pkg, package_dir, project_dir) for pkg in packages}
+    if not layout:
+        return set(package_dir) in ({}, {""})
+    parent = os.path.commonpath(starmap(_parent_path, layout.items()))
+    return all(
+        _path.same_path(Path(parent, *key.split('.')), value)
+        for key, value in layout.items()
+    )
+
+
+def _parent_path(pkg, pkg_path):
+    """Infer the parent path containing a package, that if added to ``sys.path`` would
+    allow importing that package.
+    When ``pkg`` is directly mapped into a directory with a different name, return its
+    own path.
+    >>> _parent_path("a", "src/a")
+    'src'
+    >>> _parent_path("b", "src/c")
+    'src/c'
+    """
+    parent = pkg_path[: -len(pkg)] if pkg_path.endswith(pkg) else pkg_path
+    return parent.rstrip("/" + os.sep)
+
+
+def _find_packages(dist: Distribution) -> Iterator[str]:
+    yield from iter(dist.packages or [])
+
+    py_modules = dist.py_modules or []
+    nested_modules = [mod for mod in py_modules if "." in mod]
+    if dist.ext_package:
+        yield dist.ext_package
+    else:
+        ext_modules = dist.ext_modules or []
+        nested_modules += [x.name for x in ext_modules if "." in x.name]
+
+    for module in nested_modules:
+        package, _, _ = module.rpartition(".")
+        yield package
+
+
+def _find_top_level_modules(dist: Distribution) -> Iterator[str]:
+    py_modules = dist.py_modules or []
+    yield from (mod for mod in py_modules if "." not in mod)
+
+    if not dist.ext_package:
+        ext_modules = dist.ext_modules or []
+        yield from (x.name for x in ext_modules if "." not in x.name)
+
+
+def _find_package_roots(
+    packages: Iterable[str],
+    package_dir: Mapping[str, str],
+    src_root: StrPath,
+) -> dict[str, str]:
+    pkg_roots: dict[str, str] = {
+        pkg: _absolute_root(find_package_path(pkg, package_dir, src_root))
+        for pkg in sorted(packages)
+    }
+
+    return _remove_nested(pkg_roots)
+
+
+def _absolute_root(path: StrPath) -> str:
+    """Works for packages and top-level modules"""
+    path_ = Path(path)
+    parent = path_.parent
+
+    if path_.exists():
+        return str(path_.resolve())
+    else:
+        return str(parent.resolve() / path_.name)
+
+
+def _find_virtual_namespaces(pkg_roots: dict[str, str]) -> Iterator[str]:
+    """By carefully designing ``package_dir``, it is possible to implement the logical
+    structure of PEP 420 in a package without the corresponding directories.
+
+    Moreover a parent package can be purposefully/accidentally skipped in the discovery
+    phase (e.g. ``find_packages(include=["mypkg.*"])``, when ``mypkg.foo`` is included
+    by ``mypkg`` itself is not).
+    We consider this case to also be a virtual namespace (ignoring the original
+    directory) to emulate a non-editable installation.
+
+    This function will try to find these kinds of namespaces.
+    """
+    for pkg in pkg_roots:
+        if "." not in pkg:
+            continue
+        parts = pkg.split(".")
+        for i in range(len(parts) - 1, 0, -1):
+            partial_name = ".".join(parts[:i])
+            path = Path(find_package_path(partial_name, pkg_roots, ""))
+            if not path.exists() or partial_name not in pkg_roots:
+                # partial_name not in pkg_roots ==> purposefully/accidentally skipped
+                yield partial_name
+
+
+def _find_namespaces(
+    packages: list[str], pkg_roots: dict[str, str]
+) -> Iterator[tuple[str, list[str]]]:
+    for pkg in packages:
+        path = find_package_path(pkg, pkg_roots, "")
+        if Path(path).exists() and not Path(path, "__init__.py").exists():
+            yield (pkg, [path])
+
+
+def _remove_nested(pkg_roots: dict[str, str]) -> dict[str, str]:
+    output = dict(pkg_roots.copy())
+
+    for pkg, path in reversed(list(pkg_roots.items())):
+        if any(
+            pkg != other and _is_nested(pkg, path, other, other_path)
+            for other, other_path in pkg_roots.items()
+        ):
+            output.pop(pkg)
+
+    return output
+
+
+def _is_nested(pkg: str, pkg_path: str, parent: str, parent_path: str) -> bool:
+    """
+    Return ``True`` if ``pkg`` is nested inside ``parent`` both logically and in the
+    file system.
+    >>> _is_nested("a.b", "path/a/b", "a", "path/a")
+    True
+    >>> _is_nested("a.b", "path/a/b", "a", "otherpath/a")
+    False
+    >>> _is_nested("a.b", "path/a/b", "c", "path/c")
+    False
+    >>> _is_nested("a.a", "path/a/a", "a", "path/a")
+    True
+    >>> _is_nested("b.a", "path/b/a", "a", "path/a")
+    False
+    """
+    norm_pkg_path = _path.normpath(pkg_path)
+    rest = pkg.replace(parent, "", 1).strip(".").split(".")
+    return pkg.startswith(parent) and norm_pkg_path == _path.normpath(
+        Path(parent_path, *rest)
+    )
+
+
+def _empty_dir(dir_: _P) -> _P:
+    """Create a directory ensured to be empty. Existing files may be removed."""
+    _shutil.rmtree(dir_, ignore_errors=True)
+    os.makedirs(dir_)
+    return dir_
+
+
+class _NamespaceInstaller(namespaces.Installer):
+    def __init__(self, distribution, installation_dir, editable_name, src_root) -> None:
+        self.distribution = distribution
+        self.src_root = src_root
+        self.installation_dir = installation_dir
+        self.editable_name = editable_name
+        self.outputs: list[str] = []
+        self.dry_run = False
+
+    def _get_nspkg_file(self):
+        """Installation target."""
+        return os.path.join(self.installation_dir, self.editable_name + self.nspkg_ext)
+
+    def _get_root(self):
+        """Where the modules/packages should be loaded from."""
+        return repr(str(self.src_root))
+
+
+_FINDER_TEMPLATE = """\
+from __future__ import annotations
+import sys
+from importlib.machinery import ModuleSpec, PathFinder
+from importlib.machinery import all_suffixes as module_suffixes
+from importlib.util import spec_from_file_location
+from itertools import chain
+from pathlib import Path
+
+MAPPING: dict[str, str] = {mapping!r}
+NAMESPACES: dict[str, list[str]] = {namespaces!r}
+PATH_PLACEHOLDER = {name!r} + ".__path_hook__"
+
+
+class _EditableFinder:  # MetaPathFinder
+    @classmethod
+    def find_spec(cls, fullname: str, path=None, target=None) -> ModuleSpec | None:  # type: ignore
+        # Top-level packages and modules (we know these exist in the FS)
+        if fullname in MAPPING:
+            pkg_path = MAPPING[fullname]
+            return cls._find_spec(fullname, Path(pkg_path))
+
+        # Handle immediate children modules (required for namespaces to work)
+        # To avoid problems with case sensitivity in the file system we delegate
+        # to the importlib.machinery implementation.
+        parent, _, child = fullname.rpartition(".")
+        if parent and parent in MAPPING:
+            return PathFinder.find_spec(fullname, path=[MAPPING[parent]])
+
+        # Other levels of nesting should be handled automatically by importlib
+        # using the parent path.
+        return None
+
+    @classmethod
+    def _find_spec(cls, fullname: str, candidate_path: Path) -> ModuleSpec | None:
+        init = candidate_path / "__init__.py"
+        candidates = (candidate_path.with_suffix(x) for x in module_suffixes())
+        for candidate in chain([init], candidates):
+            if candidate.exists():
+                return spec_from_file_location(fullname, candidate)
+        return None
+
+
+class _EditableNamespaceFinder:  # PathEntryFinder
+    @classmethod
+    def _path_hook(cls, path) -> type[_EditableNamespaceFinder]:
+        if path == PATH_PLACEHOLDER:
+            return cls
+        raise ImportError
+
+    @classmethod
+    def _paths(cls, fullname: str) -> list[str]:
+        paths = NAMESPACES[fullname]
+        if not paths and fullname in MAPPING:
+            paths = [MAPPING[fullname]]
+        # Always add placeholder, for 2 reasons:
+        # 1. __path__ cannot be empty for the spec to be considered namespace.
+        # 2. In the case of nested namespaces, we need to force
+        #    import machinery to query _EditableNamespaceFinder again.
+        return [*paths, PATH_PLACEHOLDER]
+
+    @classmethod
+    def find_spec(cls, fullname: str, target=None) -> ModuleSpec | None:  # type: ignore
+        if fullname in NAMESPACES:
+            spec = ModuleSpec(fullname, None, is_package=True)
+            spec.submodule_search_locations = cls._paths(fullname)
+            return spec
+        return None
+
+    @classmethod
+    def find_module(cls, _fullname) -> None:
+        return None
+
+
+def install():
+    if not any(finder == _EditableFinder for finder in sys.meta_path):
+        sys.meta_path.append(_EditableFinder)
+
+    if not NAMESPACES:
+        return
+
+    if not any(hook == _EditableNamespaceFinder._path_hook for hook in sys.path_hooks):
+        # PathEntryFinder is needed to create NamespaceSpec without private APIS
+        sys.path_hooks.append(_EditableNamespaceFinder._path_hook)
+    if PATH_PLACEHOLDER not in sys.path:
+        sys.path.append(PATH_PLACEHOLDER)  # Used just to trigger the path hook
+"""
+
+
+def _finder_template(
+    name: str, mapping: Mapping[str, str], namespaces: dict[str, list[str]]
+) -> str:
+    """Create a string containing the code for the``MetaPathFinder`` and
+    ``PathEntryFinder``.
+    """
+    mapping = dict(sorted(mapping.items(), key=lambda p: p[0]))
+    return _FINDER_TEMPLATE.format(name=name, mapping=mapping, namespaces=namespaces)
+
+
+class LinksNotSupported(errors.FileError):
+    """File system does not seem to support either symlinks or hard links."""
+
+
+class _DebuggingTips(SetuptoolsWarning):
+    _SUMMARY = "Problem in editable installation."
+    _DETAILS = """
+    An error happened while installing `{project}` in editable mode.
+
+    The following steps are recommended to help debug this problem:
+
+    - Try to install the project normally, without using the editable mode.
+      Does the error still persist?
+      (If it does, try fixing the problem before attempting the editable mode).
+    - If you are using binary extensions, make sure you have all OS-level
+      dependencies installed (e.g. compilers, toolchains, binary libraries, ...).
+    - Try the latest version of setuptools (maybe the error was already fixed).
+    - If you (or your project dependencies) are using any setuptools extension
+      or customization, make sure they support the editable mode.
+
+    After following the steps above, if the problem still persists and
+    you think this is related to how setuptools handles editable installations,
+    please submit a reproducible example
+    (see https://stackoverflow.com/help/minimal-reproducible-example) to:
+
+        https://github.com/pypa/setuptools/issues
+    """
+    _SEE_DOCS = "userguide/development_mode.html"
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/egg_info.py b/.venv/lib/python3.12/site-packages/setuptools/command/egg_info.py
new file mode 100644
index 0000000000000000000000000000000000000000..f77631168fcdb60e14ddd757e18b4c301473aa82
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/command/egg_info.py
@@ -0,0 +1,720 @@
+"""setuptools.command.egg_info
+
+Create a distribution's .egg-info directory and contents"""
+
+import functools
+import os
+import re
+import sys
+import time
+from collections.abc import Callable
+
+import packaging
+import packaging.requirements
+import packaging.version
+
+import setuptools.unicode_utils as unicode_utils
+from setuptools import Command
+from setuptools.command import bdist_egg
+from setuptools.command.sdist import sdist, walk_revctrl
+from setuptools.command.setopt import edit_config
+from setuptools.glob import glob
+
+from .. import _entry_points, _normalization
+from .._importlib import metadata
+from ..warnings import SetuptoolsDeprecationWarning
+from . import _requirestxt
+
+import distutils.errors
+import distutils.filelist
+from distutils import log
+from distutils.errors import DistutilsInternalError
+from distutils.filelist import FileList as _FileList
+from distutils.util import convert_path
+
+PY_MAJOR = f'{sys.version_info.major}.{sys.version_info.minor}'
+
+
+def translate_pattern(glob):  # noqa: C901  # is too complex (14)  # FIXME
+    """
+    Translate a file path glob like '*.txt' in to a regular expression.
+    This differs from fnmatch.translate which allows wildcards to match
+    directory separators. It also knows about '**/' which matches any number of
+    directories.
+    """
+    pat = ''
+
+    # This will split on '/' within [character classes]. This is deliberate.
+    chunks = glob.split(os.path.sep)
+
+    sep = re.escape(os.sep)
+    valid_char = f'[^{sep}]'
+
+    for c, chunk in enumerate(chunks):
+        last_chunk = c == len(chunks) - 1
+
+        # Chunks that are a literal ** are globstars. They match anything.
+        if chunk == '**':
+            if last_chunk:
+                # Match anything if this is the last component
+                pat += '.*'
+            else:
+                # Match '(name/)*'
+                pat += f'(?:{valid_char}+{sep})*'
+            continue  # Break here as the whole path component has been handled
+
+        # Find any special characters in the remainder
+        i = 0
+        chunk_len = len(chunk)
+        while i < chunk_len:
+            char = chunk[i]
+            if char == '*':
+                # Match any number of name characters
+                pat += valid_char + '*'
+            elif char == '?':
+                # Match a name character
+                pat += valid_char
+            elif char == '[':
+                # Character class
+                inner_i = i + 1
+                # Skip initial !/] chars
+                if inner_i < chunk_len and chunk[inner_i] == '!':
+                    inner_i = inner_i + 1
+                if inner_i < chunk_len and chunk[inner_i] == ']':
+                    inner_i = inner_i + 1
+
+                # Loop till the closing ] is found
+                while inner_i < chunk_len and chunk[inner_i] != ']':
+                    inner_i = inner_i + 1
+
+                if inner_i >= chunk_len:
+                    # Got to the end of the string without finding a closing ]
+                    # Do not treat this as a matching group, but as a literal [
+                    pat += re.escape(char)
+                else:
+                    # Grab the insides of the [brackets]
+                    inner = chunk[i + 1 : inner_i]
+                    char_class = ''
+
+                    # Class negation
+                    if inner[0] == '!':
+                        char_class = '^'
+                        inner = inner[1:]
+
+                    char_class += re.escape(inner)
+                    pat += f'[{char_class}]'
+
+                    # Skip to the end ]
+                    i = inner_i
+            else:
+                pat += re.escape(char)
+            i += 1
+
+        # Join each chunk with the dir separator
+        if not last_chunk:
+            pat += sep
+
+    pat += r'\Z'
+    return re.compile(pat, flags=re.MULTILINE | re.DOTALL)
+
+
+class InfoCommon:
+    tag_build = None
+    tag_date = None
+
+    @property
+    def name(self):
+        return _normalization.safe_name(self.distribution.get_name())
+
+    def tagged_version(self):
+        tagged = self._maybe_tag(self.distribution.get_version())
+        return _normalization.safe_version(tagged)
+
+    def _maybe_tag(self, version):
+        """
+        egg_info may be called more than once for a distribution,
+        in which case the version string already contains all tags.
+        """
+        return (
+            version
+            if self.vtags and self._already_tagged(version)
+            else version + self.vtags
+        )
+
+    def _already_tagged(self, version: str) -> bool:
+        # Depending on their format, tags may change with version normalization.
+        # So in addition the regular tags, we have to search for the normalized ones.
+        return version.endswith(self.vtags) or version.endswith(self._safe_tags())
+
+    def _safe_tags(self) -> str:
+        # To implement this we can rely on `safe_version` pretending to be version 0
+        # followed by tags. Then we simply discard the starting 0 (fake version number)
+        try:
+            return _normalization.safe_version(f"0{self.vtags}")[1:]
+        except packaging.version.InvalidVersion:
+            return _normalization.safe_name(self.vtags.replace(' ', '.'))
+
+    def tags(self) -> str:
+        version = ''
+        if self.tag_build:
+            version += self.tag_build
+        if self.tag_date:
+            version += time.strftime("%Y%m%d")
+        return version
+
+    vtags = property(tags)
+
+
+class egg_info(InfoCommon, Command):
+    description = "create a distribution's .egg-info directory"
+
+    user_options = [
+        (
+            'egg-base=',
+            'e',
+            "directory containing .egg-info directories"
+            " [default: top of the source tree]",
+        ),
+        ('tag-date', 'd', "Add date stamp (e.g. 20050528) to version number"),
+        ('tag-build=', 'b', "Specify explicit tag to add to version number"),
+        ('no-date', 'D', "Don't include date stamp [default]"),
+    ]
+
+    boolean_options = ['tag-date']
+    negative_opt = {
+        'no-date': 'tag-date',
+    }
+
+    def initialize_options(self):
+        self.egg_base = None
+        self.egg_name = None
+        self.egg_info = None
+        self.egg_version = None
+        self.ignore_egg_info_in_manifest = False
+
+    ####################################
+    # allow the 'tag_svn_revision' to be detected and
+    # set, supporting sdists built on older Setuptools.
+    @property
+    def tag_svn_revision(self) -> None:
+        pass
+
+    @tag_svn_revision.setter
+    def tag_svn_revision(self, value):
+        pass
+
+    ####################################
+
+    def save_version_info(self, filename) -> None:
+        """
+        Materialize the value of date into the
+        build tag. Install build keys in a deterministic order
+        to avoid arbitrary reordering on subsequent builds.
+        """
+        # follow the order these keys would have been added
+        # when PYTHONHASHSEED=0
+        egg_info = dict(tag_build=self.tags(), tag_date=0)
+        edit_config(filename, dict(egg_info=egg_info))
+
+    def finalize_options(self) -> None:
+        # Note: we need to capture the current value returned
+        # by `self.tagged_version()`, so we can later update
+        # `self.distribution.metadata.version` without
+        # repercussions.
+        self.egg_name = self.name
+        self.egg_version = self.tagged_version()
+        parsed_version = packaging.version.Version(self.egg_version)
+
+        try:
+            is_version = isinstance(parsed_version, packaging.version.Version)
+            spec = "%s==%s" if is_version else "%s===%s"
+            packaging.requirements.Requirement(spec % (self.egg_name, self.egg_version))
+        except ValueError as e:
+            raise distutils.errors.DistutilsOptionError(
+                f"Invalid distribution name or version syntax: {self.egg_name}-{self.egg_version}"
+            ) from e
+
+        if self.egg_base is None:
+            dirs = self.distribution.package_dir
+            self.egg_base = (dirs or {}).get('', os.curdir)
+
+        self.ensure_dirname('egg_base')
+        self.egg_info = _normalization.filename_component(self.egg_name) + '.egg-info'
+        if self.egg_base != os.curdir:
+            self.egg_info = os.path.join(self.egg_base, self.egg_info)
+
+        # Set package version for the benefit of dumber commands
+        # (e.g. sdist, bdist_wininst, etc.)
+        #
+        self.distribution.metadata.version = self.egg_version
+
+    def _get_egg_basename(self, py_version=PY_MAJOR, platform=None):
+        """Compute filename of the output egg. Private API."""
+        return _egg_basename(self.egg_name, self.egg_version, py_version, platform)
+
+    def write_or_delete_file(self, what, filename, data, force: bool = False) -> None:
+        """Write `data` to `filename` or delete if empty
+
+        If `data` is non-empty, this routine is the same as ``write_file()``.
+        If `data` is empty but not ``None``, this is the same as calling
+        ``delete_file(filename)`.  If `data` is ``None``, then this is a no-op
+        unless `filename` exists, in which case a warning is issued about the
+        orphaned file (if `force` is false), or deleted (if `force` is true).
+        """
+        if data:
+            self.write_file(what, filename, data)
+        elif os.path.exists(filename):
+            if data is None and not force:
+                log.warn("%s not set in setup(), but %s exists", what, filename)
+                return
+            else:
+                self.delete_file(filename)
+
+    def write_file(self, what, filename, data) -> None:
+        """Write `data` to `filename` (if not a dry run) after announcing it
+
+        `what` is used in a log message to identify what is being written
+        to the file.
+        """
+        log.info("writing %s to %s", what, filename)
+        data = data.encode("utf-8")
+        if not self.dry_run:
+            f = open(filename, 'wb')
+            f.write(data)
+            f.close()
+
+    def delete_file(self, filename) -> None:
+        """Delete `filename` (if not a dry run) after announcing it"""
+        log.info("deleting %s", filename)
+        if not self.dry_run:
+            os.unlink(filename)
+
+    def run(self) -> None:
+        # Pre-load to avoid iterating over entry-points while an empty .egg-info
+        # exists in sys.path. See pypa/pyproject-hooks#206
+        writers = list(metadata.entry_points(group='egg_info.writers'))
+
+        self.mkpath(self.egg_info)
+        try:
+            os.utime(self.egg_info, None)
+        except OSError as e:
+            msg = f"Cannot update time stamp of directory '{self.egg_info}'"
+            raise distutils.errors.DistutilsFileError(msg) from e
+        for ep in writers:
+            writer = ep.load()
+            writer(self, ep.name, os.path.join(self.egg_info, ep.name))
+
+        # Get rid of native_libs.txt if it was put there by older bdist_egg
+        nl = os.path.join(self.egg_info, "native_libs.txt")
+        if os.path.exists(nl):
+            self.delete_file(nl)
+
+        self.find_sources()
+
+    def find_sources(self) -> None:
+        """Generate SOURCES.txt manifest file"""
+        manifest_filename = os.path.join(self.egg_info, "SOURCES.txt")
+        mm = manifest_maker(self.distribution)
+        mm.ignore_egg_info_dir = self.ignore_egg_info_in_manifest
+        mm.manifest = manifest_filename
+        mm.run()
+        self.filelist = mm.filelist
+
+
+class FileList(_FileList):
+    # Implementations of the various MANIFEST.in commands
+
+    def __init__(
+        self, warn=None, debug_print=None, ignore_egg_info_dir: bool = False
+    ) -> None:
+        super().__init__(warn, debug_print)
+        self.ignore_egg_info_dir = ignore_egg_info_dir
+
+    def process_template_line(self, line) -> None:
+        # Parse the line: split it up, make sure the right number of words
+        # is there, and return the relevant words.  'action' is always
+        # defined: it's the first word of the line.  Which of the other
+        # three are defined depends on the action; it'll be either
+        # patterns, (dir and patterns), or (dir_pattern).
+        (action, patterns, dir, dir_pattern) = self._parse_template_line(line)
+
+        action_map: dict[str, Callable] = {
+            'include': self.include,
+            'exclude': self.exclude,
+            'global-include': self.global_include,
+            'global-exclude': self.global_exclude,
+            'recursive-include': functools.partial(
+                self.recursive_include,
+                dir,
+            ),
+            'recursive-exclude': functools.partial(
+                self.recursive_exclude,
+                dir,
+            ),
+            'graft': self.graft,
+            'prune': self.prune,
+        }
+        log_map = {
+            'include': "warning: no files found matching '%s'",
+            'exclude': ("warning: no previously-included files found matching '%s'"),
+            'global-include': (
+                "warning: no files found matching '%s' anywhere in distribution"
+            ),
+            'global-exclude': (
+                "warning: no previously-included files matching "
+                "'%s' found anywhere in distribution"
+            ),
+            'recursive-include': (
+                "warning: no files found matching '%s' under directory '%s'"
+            ),
+            'recursive-exclude': (
+                "warning: no previously-included files matching "
+                "'%s' found under directory '%s'"
+            ),
+            'graft': "warning: no directories found matching '%s'",
+            'prune': "no previously-included directories found matching '%s'",
+        }
+
+        try:
+            process_action = action_map[action]
+        except KeyError:
+            msg = f"Invalid MANIFEST.in: unknown action {action!r} in {line!r}"
+            raise DistutilsInternalError(msg) from None
+
+        # OK, now we know that the action is valid and we have the
+        # right number of words on the line for that action -- so we
+        # can proceed with minimal error-checking.
+
+        action_is_recursive = action.startswith('recursive-')
+        if action in {'graft', 'prune'}:
+            patterns = [dir_pattern]
+        extra_log_args = (dir,) if action_is_recursive else ()
+        log_tmpl = log_map[action]
+
+        self.debug_print(
+            ' '.join(
+                [action] + ([dir] if action_is_recursive else []) + patterns,
+            )
+        )
+        for pattern in patterns:
+            if not process_action(pattern):
+                log.warn(log_tmpl, pattern, *extra_log_args)
+
+    def _remove_files(self, predicate):
+        """
+        Remove all files from the file list that match the predicate.
+        Return True if any matching files were removed
+        """
+        found = False
+        for i in range(len(self.files) - 1, -1, -1):
+            if predicate(self.files[i]):
+                self.debug_print(" removing " + self.files[i])
+                del self.files[i]
+                found = True
+        return found
+
+    def include(self, pattern):
+        """Include files that match 'pattern'."""
+        found = [f for f in glob(pattern) if not os.path.isdir(f)]
+        self.extend(found)
+        return bool(found)
+
+    def exclude(self, pattern):
+        """Exclude files that match 'pattern'."""
+        match = translate_pattern(pattern)
+        return self._remove_files(match.match)
+
+    def recursive_include(self, dir, pattern):
+        """
+        Include all files anywhere in 'dir/' that match the pattern.
+        """
+        full_pattern = os.path.join(dir, '**', pattern)
+        found = [f for f in glob(full_pattern, recursive=True) if not os.path.isdir(f)]
+        self.extend(found)
+        return bool(found)
+
+    def recursive_exclude(self, dir, pattern):
+        """
+        Exclude any file anywhere in 'dir/' that match the pattern.
+        """
+        match = translate_pattern(os.path.join(dir, '**', pattern))
+        return self._remove_files(match.match)
+
+    def graft(self, dir):
+        """Include all files from 'dir/'."""
+        found = [
+            item
+            for match_dir in glob(dir)
+            for item in distutils.filelist.findall(match_dir)
+        ]
+        self.extend(found)
+        return bool(found)
+
+    def prune(self, dir):
+        """Filter out files from 'dir/'."""
+        match = translate_pattern(os.path.join(dir, '**'))
+        return self._remove_files(match.match)
+
+    def global_include(self, pattern):
+        """
+        Include all files anywhere in the current directory that match the
+        pattern. This is very inefficient on large file trees.
+        """
+        if self.allfiles is None:
+            self.findall()
+        match = translate_pattern(os.path.join('**', pattern))
+        found = [f for f in self.allfiles if match.match(f)]
+        self.extend(found)
+        return bool(found)
+
+    def global_exclude(self, pattern):
+        """
+        Exclude all files anywhere that match the pattern.
+        """
+        match = translate_pattern(os.path.join('**', pattern))
+        return self._remove_files(match.match)
+
+    def append(self, item) -> None:
+        if item.endswith('\r'):  # Fix older sdists built on Windows
+            item = item[:-1]
+        path = convert_path(item)
+
+        if self._safe_path(path):
+            self.files.append(path)
+
+    def extend(self, paths) -> None:
+        self.files.extend(filter(self._safe_path, paths))
+
+    def _repair(self):
+        """
+        Replace self.files with only safe paths
+
+        Because some owners of FileList manipulate the underlying
+        ``files`` attribute directly, this method must be called to
+        repair those paths.
+        """
+        self.files = list(filter(self._safe_path, self.files))
+
+    def _safe_path(self, path):
+        enc_warn = "'%s' not %s encodable -- skipping"
+
+        # To avoid accidental trans-codings errors, first to unicode
+        u_path = unicode_utils.filesys_decode(path)
+        if u_path is None:
+            log.warn(f"'{path}' in unexpected encoding -- skipping")
+            return False
+
+        # Must ensure utf-8 encodability
+        utf8_path = unicode_utils.try_encode(u_path, "utf-8")
+        if utf8_path is None:
+            log.warn(enc_warn, path, 'utf-8')
+            return False
+
+        try:
+            # ignore egg-info paths
+            is_egg_info = ".egg-info" in u_path or b".egg-info" in utf8_path
+            if self.ignore_egg_info_dir and is_egg_info:
+                return False
+            # accept is either way checks out
+            if os.path.exists(u_path) or os.path.exists(utf8_path):
+                return True
+        # this will catch any encode errors decoding u_path
+        except UnicodeEncodeError:
+            log.warn(enc_warn, path, sys.getfilesystemencoding())
+
+
+class manifest_maker(sdist):
+    template = "MANIFEST.in"
+
+    def initialize_options(self) -> None:
+        self.use_defaults = True
+        self.prune = True
+        self.manifest_only = True
+        self.force_manifest = True
+        self.ignore_egg_info_dir = False
+
+    def finalize_options(self) -> None:
+        pass
+
+    def run(self) -> None:
+        self.filelist = FileList(ignore_egg_info_dir=self.ignore_egg_info_dir)
+        if not os.path.exists(self.manifest):
+            self.write_manifest()  # it must exist so it'll get in the list
+        self.add_defaults()
+        if os.path.exists(self.template):
+            self.read_template()
+        self.add_license_files()
+        self._add_referenced_files()
+        self.prune_file_list()
+        self.filelist.sort()
+        self.filelist.remove_duplicates()
+        self.write_manifest()
+
+    def _manifest_normalize(self, path):
+        path = unicode_utils.filesys_decode(path)
+        return path.replace(os.sep, '/')
+
+    def write_manifest(self) -> None:
+        """
+        Write the file list in 'self.filelist' to the manifest file
+        named by 'self.manifest'.
+        """
+        self.filelist._repair()
+
+        # Now _repairs should encodability, but not unicode
+        files = [self._manifest_normalize(f) for f in self.filelist.files]
+        msg = f"writing manifest file '{self.manifest}'"
+        self.execute(write_file, (self.manifest, files), msg)
+
+    def warn(self, msg) -> None:
+        if not self._should_suppress_warning(msg):
+            sdist.warn(self, msg)
+
+    @staticmethod
+    def _should_suppress_warning(msg):
+        """
+        suppress missing-file warnings from sdist
+        """
+        return re.match(r"standard file .*not found", msg)
+
+    def add_defaults(self) -> None:
+        sdist.add_defaults(self)
+        self.filelist.append(self.template)
+        self.filelist.append(self.manifest)
+        rcfiles = list(walk_revctrl())
+        if rcfiles:
+            self.filelist.extend(rcfiles)
+        elif os.path.exists(self.manifest):
+            self.read_manifest()
+
+        if os.path.exists("setup.py"):
+            # setup.py should be included by default, even if it's not
+            # the script called to create the sdist
+            self.filelist.append("setup.py")
+
+        ei_cmd = self.get_finalized_command('egg_info')
+        self.filelist.graft(ei_cmd.egg_info)
+
+    def add_license_files(self) -> None:
+        license_files = self.distribution.metadata.license_files or []
+        for lf in license_files:
+            log.info("adding license file '%s'", lf)
+        self.filelist.extend(license_files)
+
+    def _add_referenced_files(self):
+        """Add files referenced by the config (e.g. `file:` directive) to filelist"""
+        referenced = getattr(self.distribution, '_referenced_files', [])
+        # ^-- fallback if dist comes from distutils or is a custom class
+        for rf in referenced:
+            log.debug("adding file referenced by config '%s'", rf)
+        self.filelist.extend(referenced)
+
+    def _safe_data_files(self, build_py):
+        """
+        The parent class implementation of this method
+        (``sdist``) will try to include data files, which
+        might cause recursion problems when
+        ``include_package_data=True``.
+
+        Therefore, avoid triggering any attempt of
+        analyzing/building the manifest again.
+        """
+        if hasattr(build_py, 'get_data_files_without_manifest'):
+            return build_py.get_data_files_without_manifest()
+
+        SetuptoolsDeprecationWarning.emit(
+            "`build_py` command does not inherit from setuptools' `build_py`.",
+            """
+            Custom 'build_py' does not implement 'get_data_files_without_manifest'.
+            Please extend command classes from setuptools instead of distutils.
+            """,
+            see_url="https://peps.python.org/pep-0632/",
+            # due_date not defined yet, old projects might still do it?
+        )
+        return build_py.get_data_files()
+
+
+def write_file(filename, contents) -> None:
+    """Create a file with the specified name and write 'contents' (a
+    sequence of strings without line terminators) to it.
+    """
+    contents = "\n".join(contents)
+
+    # assuming the contents has been vetted for utf-8 encoding
+    contents = contents.encode("utf-8")
+
+    with open(filename, "wb") as f:  # always write POSIX-style manifest
+        f.write(contents)
+
+
+def write_pkg_info(cmd, basename, filename) -> None:
+    log.info("writing %s", filename)
+    if not cmd.dry_run:
+        metadata = cmd.distribution.metadata
+        metadata.version, oldver = cmd.egg_version, metadata.version
+        metadata.name, oldname = cmd.egg_name, metadata.name
+
+        try:
+            # write unescaped data to PKG-INFO, so older pkg_resources
+            # can still parse it
+            metadata.write_pkg_info(cmd.egg_info)
+        finally:
+            metadata.name, metadata.version = oldname, oldver
+
+        safe = getattr(cmd.distribution, 'zip_safe', None)
+
+        bdist_egg.write_safety_flag(cmd.egg_info, safe)
+
+
+def warn_depends_obsolete(cmd, basename, filename) -> None:
+    """
+    Unused: left to avoid errors when updating (from source) from <= 67.8.
+    Old installations have a .dist-info directory with the entry-point
+    ``depends.txt = setuptools.command.egg_info:warn_depends_obsolete``.
+    This may trigger errors when running the first egg_info in build_meta.
+    TODO: Remove this function in a version sufficiently > 68.
+    """
+
+
+# Export API used in entry_points
+write_requirements = _requirestxt.write_requirements
+write_setup_requirements = _requirestxt.write_setup_requirements
+
+
+def write_toplevel_names(cmd, basename, filename) -> None:
+    pkgs = dict.fromkeys([
+        k.split('.', 1)[0] for k in cmd.distribution.iter_distribution_names()
+    ])
+    cmd.write_file("top-level names", filename, '\n'.join(sorted(pkgs)) + '\n')
+
+
+def overwrite_arg(cmd, basename, filename) -> None:
+    write_arg(cmd, basename, filename, True)
+
+
+def write_arg(cmd, basename, filename, force: bool = False) -> None:
+    argname = os.path.splitext(basename)[0]
+    value = getattr(cmd.distribution, argname, None)
+    if value is not None:
+        value = '\n'.join(value) + '\n'
+    cmd.write_or_delete_file(argname, filename, value, force)
+
+
+def write_entries(cmd, basename, filename) -> None:
+    eps = _entry_points.load(cmd.distribution.entry_points)
+    defn = _entry_points.render(eps)
+    cmd.write_or_delete_file('entry points', filename, defn, True)
+
+
+def _egg_basename(egg_name, egg_version, py_version=None, platform=None):
+    """Compute filename of the output egg. Private API."""
+    name = _normalization.filename_component(egg_name)
+    version = _normalization.filename_component(egg_version)
+    egg = f"{name}-{version}-py{py_version or PY_MAJOR}"
+    if platform:
+        egg += f"-{platform}"
+    return egg
+
+
+class EggInfoDeprecationWarning(SetuptoolsDeprecationWarning):
+    """Deprecated behavior warning for EggInfo, bypassing suppression."""
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/install.py b/.venv/lib/python3.12/site-packages/setuptools/command/install.py
new file mode 100644
index 0000000000000000000000000000000000000000..15ef36468889d55718711edbe9c4e061c48ee6e8
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/command/install.py
@@ -0,0 +1,183 @@
+from __future__ import annotations
+
+import glob
+import inspect
+import platform
+from collections.abc import Callable
+from typing import TYPE_CHECKING, Any, ClassVar, cast
+
+import setuptools
+
+from ..dist import Distribution
+from ..warnings import SetuptoolsDeprecationWarning, SetuptoolsWarning
+from .bdist_egg import bdist_egg as bdist_egg_cls
+
+import distutils.command.install as orig
+from distutils.errors import DistutilsArgError
+
+if TYPE_CHECKING:
+    # This is only used for a type-cast, don't import at runtime or it'll cause deprecation warnings
+    from .easy_install import easy_install as easy_install_cls
+else:
+    easy_install_cls = None
+
+
+def __getattr__(name: str):  # pragma: no cover
+    if name == "_install":
+        SetuptoolsDeprecationWarning.emit(
+            "`setuptools.command._install` was an internal implementation detail "
+            + "that was left in for numpy<1.9 support.",
+            due_date=(2025, 5, 2),  # Originally added on 2024-11-01
+        )
+        return orig.install
+    raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
+
+
+class install(orig.install):
+    """Use easy_install to install the package, w/dependencies"""
+
+    distribution: Distribution  # override distutils.dist.Distribution with setuptools.dist.Distribution
+
+    user_options = orig.install.user_options + [
+        ('old-and-unmanageable', None, "Try not to use this!"),
+        (
+            'single-version-externally-managed',
+            None,
+            "used by system package builders to create 'flat' eggs",
+        ),
+    ]
+    boolean_options = orig.install.boolean_options + [
+        'old-and-unmanageable',
+        'single-version-externally-managed',
+    ]
+    # Type the same as distutils.command.install.install.sub_commands
+    # Must keep the second tuple item potentially None due to invariance
+    new_commands: ClassVar[list[tuple[str, Callable[[Any], bool] | None]]] = [
+        ('install_egg_info', lambda self: True),
+        ('install_scripts', lambda self: True),
+    ]
+    _nc = dict(new_commands)
+
+    def initialize_options(self):
+        SetuptoolsDeprecationWarning.emit(
+            "setup.py install is deprecated.",
+            """
+            Please avoid running ``setup.py`` directly.
+            Instead, use pypa/build, pypa/installer or other
+            standards-based tools.
+            """,
+            see_url="https://blog.ganssle.io/articles/2021/10/setup-py-deprecated.html",
+            # TODO: Document how to bootstrap setuptools without install
+            #       (e.g. by unzipping the wheel file)
+            #       and then add a due_date to this warning.
+        )
+
+        super().initialize_options()
+        self.old_and_unmanageable = None
+        self.single_version_externally_managed = None
+
+    def finalize_options(self) -> None:
+        super().finalize_options()
+        if self.root:
+            self.single_version_externally_managed = True
+        elif self.single_version_externally_managed:
+            if not self.root and not self.record:
+                raise DistutilsArgError(
+                    "You must specify --record or --root when building system packages"
+                )
+
+    def handle_extra_path(self):
+        if self.root or self.single_version_externally_managed:
+            # explicit backward-compatibility mode, allow extra_path to work
+            return orig.install.handle_extra_path(self)
+
+        # Ignore extra_path when installing an egg (or being run by another
+        # command without --root or --single-version-externally-managed
+        self.path_file = None
+        self.extra_dirs = ''
+        return None
+
+    def run(self):
+        # Explicit request for old-style install?  Just do it
+        if self.old_and_unmanageable or self.single_version_externally_managed:
+            return super().run()
+
+        if not self._called_from_setup(inspect.currentframe()):
+            # Run in backward-compatibility mode to support bdist_* commands.
+            super().run()
+        else:
+            self.do_egg_install()
+
+        return None
+
+    @staticmethod
+    def _called_from_setup(run_frame):
+        """
+        Attempt to detect whether run() was called from setup() or by another
+        command.  If called by setup(), the parent caller will be the
+        'run_command' method in 'distutils.dist', and *its* caller will be
+        the 'run_commands' method.  If called any other way, the
+        immediate caller *might* be 'run_command', but it won't have been
+        called by 'run_commands'. Return True in that case or if a call stack
+        is unavailable. Return False otherwise.
+        """
+        if run_frame is None:
+            msg = "Call stack not available. bdist_* commands may fail."
+            SetuptoolsWarning.emit(msg)
+            if platform.python_implementation() == 'IronPython':
+                msg = "For best results, pass -X:Frames to enable call stack."
+                SetuptoolsWarning.emit(msg)
+            return True
+
+        frames = inspect.getouterframes(run_frame)
+        for frame in frames[2:4]:
+            (caller,) = frame[:1]
+            info = inspect.getframeinfo(caller)
+            caller_module = caller.f_globals.get('__name__', '')
+
+            if caller_module == "setuptools.dist" and info.function == "run_command":
+                # Starting from v61.0.0 setuptools overwrites dist.run_command
+                continue
+
+            return caller_module == 'distutils.dist' and info.function == 'run_commands'
+
+        return False
+
+    def do_egg_install(self) -> None:
+        easy_install = self.distribution.get_command_class('easy_install')
+
+        cmd = cast(
+            # We'd want to cast easy_install as type[easy_install_cls] but a bug in
+            # mypy makes it think easy_install() returns a Command on Python 3.12+
+            # https://github.com/python/mypy/issues/18088
+            easy_install_cls,
+            easy_install(  # type: ignore[call-arg]
+                self.distribution,
+                args="x",
+                root=self.root,
+                record=self.record,
+            ),
+        )
+        cmd.ensure_finalized()  # finalize before bdist_egg munges install cmd
+        cmd.always_copy_from = '.'  # make sure local-dir eggs get installed
+
+        # pick up setup-dir .egg files only: no .egg-info
+        cmd.package_index.scan(glob.glob('*.egg'))
+
+        self.run_command('bdist_egg')
+        bdist_egg = cast(bdist_egg_cls, self.distribution.get_command_obj('bdist_egg'))
+        args = [bdist_egg.egg_output]
+
+        if setuptools.bootstrap_install_from:
+            # Bootstrap self-installation of setuptools
+            args.insert(0, setuptools.bootstrap_install_from)
+
+        cmd.args = args
+        cmd.run(show_deprecation=False)
+        setuptools.bootstrap_install_from = None
+
+
+# XXX Python 3.1 doesn't see _nc if this is inside the class
+install.sub_commands = [
+    cmd for cmd in orig.install.sub_commands if cmd[0] not in install._nc
+] + install.new_commands
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/install_egg_info.py b/.venv/lib/python3.12/site-packages/setuptools/command/install_egg_info.py
new file mode 100644
index 0000000000000000000000000000000000000000..44f22ccf51cc3fb1662b326c3150845356d77fc3
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/command/install_egg_info.py
@@ -0,0 +1,58 @@
+import os
+
+from setuptools import Command, namespaces
+from setuptools.archive_util import unpack_archive
+
+from .._path import ensure_directory
+
+from distutils import dir_util, log
+
+
+class install_egg_info(namespaces.Installer, Command):
+    """Install an .egg-info directory for the package"""
+
+    description = "Install an .egg-info directory for the package"
+
+    user_options = [
+        ('install-dir=', 'd', "directory to install to"),
+    ]
+
+    def initialize_options(self):
+        self.install_dir = None
+
+    def finalize_options(self) -> None:
+        self.set_undefined_options('install_lib', ('install_dir', 'install_dir'))
+        ei_cmd = self.get_finalized_command("egg_info")
+        basename = f"{ei_cmd._get_egg_basename()}.egg-info"
+        self.source = ei_cmd.egg_info
+        self.target = os.path.join(self.install_dir, basename)
+        self.outputs: list[str] = []
+
+    def run(self) -> None:
+        self.run_command('egg_info')
+        if os.path.isdir(self.target) and not os.path.islink(self.target):
+            dir_util.remove_tree(self.target, dry_run=self.dry_run)
+        elif os.path.exists(self.target):
+            self.execute(os.unlink, (self.target,), "Removing " + self.target)
+        if not self.dry_run:
+            ensure_directory(self.target)
+        self.execute(self.copytree, (), f"Copying {self.source} to {self.target}")
+        self.install_namespaces()
+
+    def get_outputs(self):
+        return self.outputs
+
+    def copytree(self) -> None:
+        # Copy the .egg-info tree to site-packages
+        def skimmer(src, dst):
+            # filter out source-control directories; note that 'src' is always
+            # a '/'-separated path, regardless of platform.  'dst' is a
+            # platform-specific path.
+            for skip in '.svn/', 'CVS/':
+                if src.startswith(skip) or '/' + skip in src:
+                    return None
+            self.outputs.append(dst)
+            log.debug("Copying %s to %s", src, dst)
+            return dst
+
+        unpack_archive(self.source, self.target, skimmer)
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/install_lib.py b/.venv/lib/python3.12/site-packages/setuptools/command/install_lib.py
new file mode 100644
index 0000000000000000000000000000000000000000..8e1e07271028386e138585cac7619ab0338017cc
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/command/install_lib.py
@@ -0,0 +1,137 @@
+from __future__ import annotations
+
+import os
+import sys
+from itertools import product, starmap
+
+from .._path import StrPath
+from ..dist import Distribution
+
+import distutils.command.install_lib as orig
+
+
+class install_lib(orig.install_lib):
+    """Don't add compiled flags to filenames of non-Python files"""
+
+    distribution: Distribution  # override distutils.dist.Distribution with setuptools.dist.Distribution
+
+    def run(self) -> None:
+        self.build()
+        outfiles = self.install()
+        if outfiles is not None:
+            # always compile, in case we have any extension stubs to deal with
+            self.byte_compile(outfiles)
+
+    def get_exclusions(self):
+        """
+        Return a collections.Sized collections.Container of paths to be
+        excluded for single_version_externally_managed installations.
+        """
+        all_packages = (
+            pkg
+            for ns_pkg in self._get_SVEM_NSPs()
+            for pkg in self._all_packages(ns_pkg)
+        )
+
+        excl_specs = product(all_packages, self._gen_exclusion_paths())
+        return set(starmap(self._exclude_pkg_path, excl_specs))
+
+    def _exclude_pkg_path(self, pkg, exclusion_path):
+        """
+        Given a package name and exclusion path within that package,
+        compute the full exclusion path.
+        """
+        parts = pkg.split('.') + [exclusion_path]
+        return os.path.join(self.install_dir, *parts)
+
+    @staticmethod
+    def _all_packages(pkg_name):
+        """
+        >>> list(install_lib._all_packages('foo.bar.baz'))
+        ['foo.bar.baz', 'foo.bar', 'foo']
+        """
+        while pkg_name:
+            yield pkg_name
+            pkg_name, _sep, _child = pkg_name.rpartition('.')
+
+    def _get_SVEM_NSPs(self):
+        """
+        Get namespace packages (list) but only for
+        single_version_externally_managed installations and empty otherwise.
+        """
+        # TODO: is it necessary to short-circuit here? i.e. what's the cost
+        # if get_finalized_command is called even when namespace_packages is
+        # False?
+        if not self.distribution.namespace_packages:
+            return []
+
+        install_cmd = self.get_finalized_command('install')
+        svem = install_cmd.single_version_externally_managed
+
+        return self.distribution.namespace_packages if svem else []
+
+    @staticmethod
+    def _gen_exclusion_paths():
+        """
+        Generate file paths to be excluded for namespace packages (bytecode
+        cache files).
+        """
+        # always exclude the package module itself
+        yield '__init__.py'
+
+        yield '__init__.pyc'
+        yield '__init__.pyo'
+
+        if not hasattr(sys, 'implementation'):
+            return
+
+        base = os.path.join('__pycache__', '__init__.' + sys.implementation.cache_tag)
+        yield base + '.pyc'
+        yield base + '.pyo'
+        yield base + '.opt-1.pyc'
+        yield base + '.opt-2.pyc'
+
+    def copy_tree(
+        self,
+        infile: StrPath,
+        outfile: str,
+        # override: Using actual booleans
+        preserve_mode: bool = True,  # type: ignore[override]
+        preserve_times: bool = True,  # type: ignore[override]
+        preserve_symlinks: bool = False,  # type: ignore[override]
+        level: object = 1,
+    ) -> list[str]:
+        assert preserve_mode
+        assert preserve_times
+        assert not preserve_symlinks
+        exclude = self.get_exclusions()
+
+        if not exclude:
+            return orig.install_lib.copy_tree(self, infile, outfile)
+
+        # Exclude namespace package __init__.py* files from the output
+
+        from setuptools.archive_util import unpack_directory
+
+        from distutils import log
+
+        outfiles: list[str] = []
+
+        def pf(src: str, dst: str):
+            if dst in exclude:
+                log.warn("Skipping installation of %s (namespace package)", dst)
+                return False
+
+            log.info("copying %s -> %s", src, os.path.dirname(dst))
+            outfiles.append(dst)
+            return dst
+
+        unpack_directory(infile, outfile, pf)
+        return outfiles
+
+    def get_outputs(self):
+        outputs = orig.install_lib.get_outputs(self)
+        exclude = self.get_exclusions()
+        if exclude:
+            return [f for f in outputs if f not in exclude]
+        return outputs
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/install_scripts.py b/.venv/lib/python3.12/site-packages/setuptools/command/install_scripts.py
new file mode 100644
index 0000000000000000000000000000000000000000..4401cf693d2642abce449dee238c037038633fec
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/command/install_scripts.py
@@ -0,0 +1,73 @@
+from __future__ import annotations
+
+import os
+import sys
+
+from .._path import ensure_directory
+from ..dist import Distribution
+
+import distutils.command.install_scripts as orig
+from distutils import log
+
+
+class install_scripts(orig.install_scripts):
+    """Do normal script install, plus any egg_info wrapper scripts"""
+
+    distribution: Distribution  # override distutils.dist.Distribution with setuptools.dist.Distribution
+
+    def initialize_options(self) -> None:
+        orig.install_scripts.initialize_options(self)
+        self.no_ep = False
+
+    def run(self) -> None:
+        self.run_command("egg_info")
+        if self.distribution.scripts:
+            orig.install_scripts.run(self)  # run first to set up self.outfiles
+        else:
+            self.outfiles: list[str] = []
+        if self.no_ep:
+            # don't install entry point scripts into .egg file!
+            return
+        self._install_ep_scripts()
+
+    def _install_ep_scripts(self):
+        # Delay import side-effects
+        from pkg_resources import Distribution, PathMetadata
+
+        from . import easy_install as ei
+
+        ei_cmd = self.get_finalized_command("egg_info")
+        dist = Distribution(
+            ei_cmd.egg_base,
+            PathMetadata(ei_cmd.egg_base, ei_cmd.egg_info),
+            ei_cmd.egg_name,
+            ei_cmd.egg_version,
+        )
+        bs_cmd = self.get_finalized_command('build_scripts')
+        exec_param = getattr(bs_cmd, 'executable', None)
+        writer = ei.ScriptWriter
+        if exec_param == sys.executable:
+            # In case the path to the Python executable contains a space, wrap
+            # it so it's not split up.
+            exec_param = [exec_param]
+        # resolve the writer to the environment
+        writer = writer.best()
+        cmd = writer.command_spec_class.best().from_param(exec_param)
+        for args in writer.get_args(dist, cmd.as_header()):
+            self.write_script(*args)
+
+    def write_script(self, script_name, contents, mode: str = "t", *ignored) -> None:
+        """Write an executable file to the scripts directory"""
+        from setuptools.command.easy_install import chmod, current_umask
+
+        log.info("Installing %s script to %s", script_name, self.install_dir)
+        target = os.path.join(self.install_dir, script_name)
+        self.outfiles.append(target)
+
+        encoding = None if "b" in mode else "utf-8"
+        mask = current_umask()
+        if not self.dry_run:
+            ensure_directory(target)
+            with open(target, "w" + mode, encoding=encoding) as f:
+                f.write(contents)
+            chmod(target, 0o777 - mask)
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/launcher manifest.xml b/.venv/lib/python3.12/site-packages/setuptools/command/launcher manifest.xml
new file mode 100644
index 0000000000000000000000000000000000000000..5972a96d8ded85cc14147ffc1400ec67c3b5a578
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/command/launcher manifest.xml	
@@ -0,0 +1,15 @@
+
+
+    
+    
+    
+        
+            
+                
+            
+        
+    
+
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/rotate.py b/.venv/lib/python3.12/site-packages/setuptools/command/rotate.py
new file mode 100644
index 0000000000000000000000000000000000000000..acdce07baaf3e4fc87552c39d7ee6e0271fe2a72
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/command/rotate.py
@@ -0,0 +1,65 @@
+from __future__ import annotations
+
+import os
+from typing import ClassVar
+
+from .. import Command, _shutil
+
+from distutils import log
+from distutils.errors import DistutilsOptionError
+from distutils.util import convert_path
+
+
+class rotate(Command):
+    """Delete older distributions"""
+
+    description = "delete older distributions, keeping N newest files"
+    user_options = [
+        ('match=', 'm', "patterns to match (required)"),
+        ('dist-dir=', 'd', "directory where the distributions are"),
+        ('keep=', 'k', "number of matching distributions to keep"),
+    ]
+
+    boolean_options: ClassVar[list[str]] = []
+
+    def initialize_options(self):
+        self.match = None
+        self.dist_dir = None
+        self.keep = None
+
+    def finalize_options(self) -> None:
+        if self.match is None:
+            raise DistutilsOptionError(
+                "Must specify one or more (comma-separated) match patterns "
+                "(e.g. '.zip' or '.egg')"
+            )
+        if self.keep is None:
+            raise DistutilsOptionError("Must specify number of files to keep")
+        try:
+            self.keep = int(self.keep)
+        except ValueError as e:
+            raise DistutilsOptionError("--keep must be an integer") from e
+        if isinstance(self.match, str):
+            self.match = [convert_path(p.strip()) for p in self.match.split(',')]
+        self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'))
+
+    def run(self) -> None:
+        self.run_command("egg_info")
+        from glob import glob
+
+        for pattern in self.match:
+            pattern = self.distribution.get_name() + '*' + pattern
+            files = glob(os.path.join(self.dist_dir, pattern))
+            files = [(os.path.getmtime(f), f) for f in files]
+            files.sort()
+            files.reverse()
+
+            log.info("%d file(s) matching %s", len(files), pattern)
+            files = files[self.keep :]
+            for t, f in files:
+                log.info("Deleting %s", f)
+                if not self.dry_run:
+                    if os.path.isdir(f):
+                        _shutil.rmtree(f)
+                    else:
+                        os.unlink(f)
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/saveopts.py b/.venv/lib/python3.12/site-packages/setuptools/command/saveopts.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a2cbce6e2aad396f4a5ee9788d53387237df96d
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/command/saveopts.py
@@ -0,0 +1,21 @@
+from setuptools.command.setopt import edit_config, option_base
+
+
+class saveopts(option_base):
+    """Save command-line options to a file"""
+
+    description = "save supplied options to setup.cfg or other config file"
+
+    def run(self) -> None:
+        dist = self.distribution
+        settings: dict[str, dict[str, str]] = {}
+
+        for cmd in dist.command_options:
+            if cmd == 'saveopts':
+                continue  # don't save our own options!
+
+            for opt, (src, val) in dist.get_option_dict(cmd).items():
+                if src == "command line":
+                    settings.setdefault(cmd, {})[opt] = val
+
+        edit_config(self.filename, settings, self.dry_run)
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/sdist.py b/.venv/lib/python3.12/site-packages/setuptools/command/sdist.py
new file mode 100644
index 0000000000000000000000000000000000000000..9631cf3114778a8865917d02878525fc0127a253
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/command/sdist.py
@@ -0,0 +1,217 @@
+from __future__ import annotations
+
+import contextlib
+import os
+import re
+from itertools import chain
+from typing import ClassVar
+
+from .._importlib import metadata
+from ..dist import Distribution
+from .build import _ORIGINAL_SUBCOMMANDS
+
+import distutils.command.sdist as orig
+from distutils import log
+
+_default_revctrl = list
+
+
+def walk_revctrl(dirname=''):
+    """Find all files under revision control"""
+    for ep in metadata.entry_points(group='setuptools.file_finders'):
+        yield from ep.load()(dirname)
+
+
+class sdist(orig.sdist):
+    """Smart sdist that finds anything supported by revision control"""
+
+    user_options = [
+        ('formats=', None, "formats for source distribution (comma-separated list)"),
+        (
+            'keep-temp',
+            'k',
+            "keep the distribution tree around after creating " + "archive file(s)",
+        ),
+        (
+            'dist-dir=',
+            'd',
+            "directory to put the source distribution archive(s) in [default: dist]",
+        ),
+        (
+            'owner=',
+            'u',
+            "Owner name used when creating a tar file [default: current user]",
+        ),
+        (
+            'group=',
+            'g',
+            "Group name used when creating a tar file [default: current group]",
+        ),
+    ]
+
+    distribution: Distribution  # override distutils.dist.Distribution with setuptools.dist.Distribution
+    negative_opt: ClassVar[dict[str, str]] = {}
+
+    README_EXTENSIONS = ['', '.rst', '.txt', '.md']
+    READMES = tuple(f'README{ext}' for ext in README_EXTENSIONS)
+
+    def run(self) -> None:
+        self.run_command('egg_info')
+        ei_cmd = self.get_finalized_command('egg_info')
+        self.filelist = ei_cmd.filelist
+        self.filelist.append(os.path.join(ei_cmd.egg_info, 'SOURCES.txt'))
+        self.check_readme()
+
+        # Run sub commands
+        for cmd_name in self.get_sub_commands():
+            self.run_command(cmd_name)
+
+        self.make_distribution()
+
+        dist_files = getattr(self.distribution, 'dist_files', [])
+        for file in self.archive_files:
+            data = ('sdist', '', file)
+            if data not in dist_files:
+                dist_files.append(data)
+
+    def initialize_options(self) -> None:
+        orig.sdist.initialize_options(self)
+
+    def make_distribution(self) -> None:
+        """
+        Workaround for #516
+        """
+        with self._remove_os_link():
+            orig.sdist.make_distribution(self)
+
+    @staticmethod
+    @contextlib.contextmanager
+    def _remove_os_link():
+        """
+        In a context, remove and restore os.link if it exists
+        """
+
+        class NoValue:
+            pass
+
+        orig_val = getattr(os, 'link', NoValue)
+        try:
+            del os.link
+        except Exception:
+            pass
+        try:
+            yield
+        finally:
+            if orig_val is not NoValue:
+                os.link = orig_val
+
+    def add_defaults(self) -> None:
+        super().add_defaults()
+        self._add_defaults_build_sub_commands()
+
+    def _add_defaults_optional(self):
+        super()._add_defaults_optional()
+        if os.path.isfile('pyproject.toml'):
+            self.filelist.append('pyproject.toml')
+
+    def _add_defaults_python(self):
+        """getting python files"""
+        if self.distribution.has_pure_modules():
+            build_py = self.get_finalized_command('build_py')
+            self.filelist.extend(build_py.get_source_files())
+            self._add_data_files(self._safe_data_files(build_py))
+
+    def _add_defaults_build_sub_commands(self):
+        build = self.get_finalized_command("build")
+        missing_cmds = set(build.get_sub_commands()) - _ORIGINAL_SUBCOMMANDS
+        # ^-- the original built-in sub-commands are already handled by default.
+        cmds = (self.get_finalized_command(c) for c in missing_cmds)
+        files = (c.get_source_files() for c in cmds if hasattr(c, "get_source_files"))
+        self.filelist.extend(chain.from_iterable(files))
+
+    def _safe_data_files(self, build_py):
+        """
+        Since the ``sdist`` class is also used to compute the MANIFEST
+        (via :obj:`setuptools.command.egg_info.manifest_maker`),
+        there might be recursion problems when trying to obtain the list of
+        data_files and ``include_package_data=True`` (which in turn depends on
+        the files included in the MANIFEST).
+
+        To avoid that, ``manifest_maker`` should be able to overwrite this
+        method and avoid recursive attempts to build/analyze the MANIFEST.
+        """
+        return build_py.data_files
+
+    def _add_data_files(self, data_files):
+        """
+        Add data files as found in build_py.data_files.
+        """
+        self.filelist.extend(
+            os.path.join(src_dir, name)
+            for _, src_dir, _, filenames in data_files
+            for name in filenames
+        )
+
+    def _add_defaults_data_files(self):
+        try:
+            super()._add_defaults_data_files()
+        except TypeError:
+            log.warn("data_files contains unexpected objects")
+
+    def prune_file_list(self) -> None:
+        super().prune_file_list()
+        # Prevent accidental inclusion of test-related cache dirs at the project root
+        sep = re.escape(os.sep)
+        self.filelist.exclude_pattern(r"^(\.tox|\.nox|\.venv)" + sep, is_regex=True)
+
+    def check_readme(self) -> None:
+        for f in self.READMES:
+            if os.path.exists(f):
+                return
+        else:
+            self.warn(
+                "standard file not found: should have one of " + ', '.join(self.READMES)
+            )
+
+    def make_release_tree(self, base_dir, files) -> None:
+        orig.sdist.make_release_tree(self, base_dir, files)
+
+        # Save any egg_info command line options used to create this sdist
+        dest = os.path.join(base_dir, 'setup.cfg')
+        if hasattr(os, 'link') and os.path.exists(dest):
+            # unlink and re-copy, since it might be hard-linked, and
+            # we don't want to change the source version
+            os.unlink(dest)
+            self.copy_file('setup.cfg', dest)
+
+        self.get_finalized_command('egg_info').save_version_info(dest)
+
+    def _manifest_is_not_generated(self):
+        # check for special comment used in 2.7.1 and higher
+        if not os.path.isfile(self.manifest):
+            return False
+
+        with open(self.manifest, 'rb') as fp:
+            first_line = fp.readline()
+        return first_line != b'# file GENERATED by distutils, do NOT edit\n'
+
+    def read_manifest(self):
+        """Read the manifest file (named by 'self.manifest') and use it to
+        fill in 'self.filelist', the list of files to include in the source
+        distribution.
+        """
+        log.info("reading manifest file '%s'", self.manifest)
+        manifest = open(self.manifest, 'rb')
+        for bytes_line in manifest:
+            # The manifest must contain UTF-8. See #303.
+            try:
+                line = bytes_line.decode('UTF-8')
+            except UnicodeDecodeError:
+                log.warn(f"{line!r} not UTF-8 decodable -- skipping")
+                continue
+            # ignore comments and blank lines
+            line = line.strip()
+            if line.startswith('#') or not line:
+                continue
+            self.filelist.append(line)
+        manifest.close()
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/setopt.py b/.venv/lib/python3.12/site-packages/setuptools/command/setopt.py
new file mode 100644
index 0000000000000000000000000000000000000000..678a0593d6739db316bd4008860a613b59892f1f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/command/setopt.py
@@ -0,0 +1,141 @@
+import configparser
+import os
+
+from .. import Command
+from ..unicode_utils import _cfg_read_utf8_with_fallback
+
+import distutils
+from distutils import log
+from distutils.errors import DistutilsOptionError
+from distutils.util import convert_path
+
+__all__ = ['config_file', 'edit_config', 'option_base', 'setopt']
+
+
+def config_file(kind="local"):
+    """Get the filename of the distutils, local, global, or per-user config
+
+    `kind` must be one of "local", "global", or "user"
+    """
+    if kind == 'local':
+        return 'setup.cfg'
+    if kind == 'global':
+        return os.path.join(os.path.dirname(distutils.__file__), 'distutils.cfg')
+    if kind == 'user':
+        dot = os.name == 'posix' and '.' or ''
+        return os.path.expanduser(convert_path(f"~/{dot}pydistutils.cfg"))
+    raise ValueError("config_file() type must be 'local', 'global', or 'user'", kind)
+
+
+def edit_config(filename, settings, dry_run=False):
+    """Edit a configuration file to include `settings`
+
+    `settings` is a dictionary of dictionaries or ``None`` values, keyed by
+    command/section name.  A ``None`` value means to delete the entire section,
+    while a dictionary lists settings to be changed or deleted in that section.
+    A setting of ``None`` means to delete that setting.
+    """
+    log.debug("Reading configuration from %s", filename)
+    opts = configparser.RawConfigParser()
+    opts.optionxform = lambda optionstr: optionstr  # type: ignore[method-assign] # overriding method
+    _cfg_read_utf8_with_fallback(opts, filename)
+
+    for section, options in settings.items():
+        if options is None:
+            log.info("Deleting section [%s] from %s", section, filename)
+            opts.remove_section(section)
+        else:
+            if not opts.has_section(section):
+                log.debug("Adding new section [%s] to %s", section, filename)
+                opts.add_section(section)
+            for option, value in options.items():
+                if value is None:
+                    log.debug("Deleting %s.%s from %s", section, option, filename)
+                    opts.remove_option(section, option)
+                    if not opts.options(section):
+                        log.info(
+                            "Deleting empty [%s] section from %s", section, filename
+                        )
+                        opts.remove_section(section)
+                else:
+                    log.debug(
+                        "Setting %s.%s to %r in %s", section, option, value, filename
+                    )
+                    opts.set(section, option, value)
+
+    log.info("Writing %s", filename)
+    if not dry_run:
+        with open(filename, 'w', encoding="utf-8") as f:
+            opts.write(f)
+
+
+class option_base(Command):
+    """Abstract base class for commands that mess with config files"""
+
+    user_options = [
+        ('global-config', 'g', "save options to the site-wide distutils.cfg file"),
+        ('user-config', 'u', "save options to the current user's pydistutils.cfg file"),
+        ('filename=', 'f', "configuration file to use (default=setup.cfg)"),
+    ]
+
+    boolean_options = [
+        'global-config',
+        'user-config',
+    ]
+
+    def initialize_options(self):
+        self.global_config = None
+        self.user_config = None
+        self.filename = None
+
+    def finalize_options(self):
+        filenames = []
+        if self.global_config:
+            filenames.append(config_file('global'))
+        if self.user_config:
+            filenames.append(config_file('user'))
+        if self.filename is not None:
+            filenames.append(self.filename)
+        if not filenames:
+            filenames.append(config_file('local'))
+        if len(filenames) > 1:
+            raise DistutilsOptionError(
+                "Must specify only one configuration file option", filenames
+            )
+        (self.filename,) = filenames
+
+
+class setopt(option_base):
+    """Save command-line options to a file"""
+
+    description = "set an option in setup.cfg or another config file"
+
+    user_options = [
+        ('command=', 'c', 'command to set an option for'),
+        ('option=', 'o', 'option to set'),
+        ('set-value=', 's', 'value of the option'),
+        ('remove', 'r', 'remove (unset) the value'),
+    ] + option_base.user_options
+
+    boolean_options = option_base.boolean_options + ['remove']
+
+    def initialize_options(self):
+        option_base.initialize_options(self)
+        self.command = None
+        self.option = None
+        self.set_value = None
+        self.remove = None
+
+    def finalize_options(self) -> None:
+        option_base.finalize_options(self)
+        if self.command is None or self.option is None:
+            raise DistutilsOptionError("Must specify --command *and* --option")
+        if self.set_value is None and not self.remove:
+            raise DistutilsOptionError("Must specify --set-value or --remove")
+
+    def run(self) -> None:
+        edit_config(
+            self.filename,
+            {self.command: {self.option.replace('-', '_'): self.set_value}},
+            self.dry_run,
+        )
diff --git a/.venv/lib/python3.12/site-packages/setuptools/command/test.py b/.venv/lib/python3.12/site-packages/setuptools/command/test.py
new file mode 100644
index 0000000000000000000000000000000000000000..341b11a20eb2cce98cdeeebea9ba2de0282d5d38
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/command/test.py
@@ -0,0 +1,45 @@
+from __future__ import annotations
+
+from setuptools import Command
+from setuptools.warnings import SetuptoolsDeprecationWarning
+
+
+# Would restrict to Literal["test"], but mypy doesn't support it: https://github.com/python/mypy/issues/8203
+def __getattr__(name: str) -> type[_test]:
+    if name == 'test':
+        SetuptoolsDeprecationWarning.emit(
+            "The test command is disabled and references to it are deprecated.",
+            "Please remove any references to `setuptools.command.test` in all "
+            "supported versions of the affected package.",
+            due_date=(2024, 11, 15),
+            stacklevel=2,
+        )
+        return _test
+    raise AttributeError(name)
+
+
+class _test(Command):
+    """
+    Stub to warn when test command is referenced or used.
+    """
+
+    description = "stub for old test command (do not use)"
+
+    user_options = [
+        ('test-module=', 'm', "Run 'test_suite' in specified module"),
+        (
+            'test-suite=',
+            's',
+            "Run single test, case or suite (e.g. 'module.test_suite')",
+        ),
+        ('test-runner=', 'r', "Test runner to use"),
+    ]
+
+    def initialize_options(self):
+        pass
+
+    def finalize_options(self):
+        pass
+
+    def run(self):
+        raise RuntimeError("Support for the test command was removed in Setuptools 72")
diff --git a/.venv/lib/python3.12/site-packages/setuptools/compat/__init__.py b/.venv/lib/python3.12/site-packages/setuptools/compat/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/setuptools/compat/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/compat/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..196890d96df508a40e8d0a22f670ec8649776dad
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/compat/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/compat/__pycache__/py310.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/compat/__pycache__/py310.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8db30f69f291631ec084bb093919948a04707057
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/compat/__pycache__/py310.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/compat/__pycache__/py311.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/compat/__pycache__/py311.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..325f0a60304a37673d35323d60dca38e34e69c04
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/compat/__pycache__/py311.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/compat/__pycache__/py312.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/compat/__pycache__/py312.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f56f6ffb7abe529e4c2004a271eced73b7612525
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/compat/__pycache__/py312.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/compat/__pycache__/py39.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/compat/__pycache__/py39.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b23002b387a6e8d9e0e3e8fa80377f2a4f70736e
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/compat/__pycache__/py39.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/compat/py310.py b/.venv/lib/python3.12/site-packages/setuptools/compat/py310.py
new file mode 100644
index 0000000000000000000000000000000000000000..b3912f8e02a57a5b9ba738673a21a596e94c1122
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/compat/py310.py
@@ -0,0 +1,9 @@
+import sys
+
+__all__ = ['tomllib']
+
+
+if sys.version_info >= (3, 11):
+    import tomllib
+else:  # pragma: no cover
+    import tomli as tomllib
diff --git a/.venv/lib/python3.12/site-packages/setuptools/compat/py311.py b/.venv/lib/python3.12/site-packages/setuptools/compat/py311.py
new file mode 100644
index 0000000000000000000000000000000000000000..52b58af32a28817deeaf592cc795f311434e39e7
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/compat/py311.py
@@ -0,0 +1,27 @@
+from __future__ import annotations
+
+import shutil
+import sys
+from typing import TYPE_CHECKING, Any, Callable
+
+if TYPE_CHECKING:
+    from _typeshed import ExcInfo, StrOrBytesPath
+    from typing_extensions import TypeAlias
+
+# Same as shutil._OnExcCallback from typeshed
+_OnExcCallback: TypeAlias = Callable[[Callable[..., Any], str, BaseException], object]
+
+
+def shutil_rmtree(
+    path: StrOrBytesPath,
+    ignore_errors: bool = False,
+    onexc: _OnExcCallback | None = None,
+) -> None:
+    if sys.version_info >= (3, 12):
+        return shutil.rmtree(path, ignore_errors, onexc=onexc)
+
+    def _handler(fn: Callable[..., Any], path: str, excinfo: ExcInfo) -> None:
+        if onexc:
+            onexc(fn, path, excinfo[1])
+
+    return shutil.rmtree(path, ignore_errors, onerror=_handler)
diff --git a/.venv/lib/python3.12/site-packages/setuptools/compat/py312.py b/.venv/lib/python3.12/site-packages/setuptools/compat/py312.py
new file mode 100644
index 0000000000000000000000000000000000000000..b20c5f697a861a680c4a747baf9ca9c901e72978
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/compat/py312.py
@@ -0,0 +1,13 @@
+from __future__ import annotations
+
+import sys
+
+if sys.version_info >= (3, 12, 4):
+    # Python 3.13 should support `.pth` files encoded in UTF-8
+    # See discussion in https://github.com/python/cpython/issues/77102
+    PTH_ENCODING: str | None = "utf-8"
+else:
+    from .py39 import LOCALE_ENCODING
+
+    # PTH_ENCODING = "locale"
+    PTH_ENCODING = LOCALE_ENCODING
diff --git a/.venv/lib/python3.12/site-packages/setuptools/compat/py39.py b/.venv/lib/python3.12/site-packages/setuptools/compat/py39.py
new file mode 100644
index 0000000000000000000000000000000000000000..04a4abe5a9e61596f97dc3d1b0b3da93a558158f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/compat/py39.py
@@ -0,0 +1,9 @@
+import sys
+
+# Explicitly use the ``"locale"`` encoding in versions that support it,
+# otherwise just rely on the implicit handling of ``encoding=None``.
+# Since all platforms that support ``EncodingWarning`` also support
+# ``encoding="locale"``, this can be used to suppress the warning.
+# However, please try to use UTF-8 when possible
+# (.pth files are the notorious exception: python/cpython#77102, pypa/setuptools#3937).
+LOCALE_ENCODING = "locale" if sys.version_info >= (3, 10) else None
diff --git a/.venv/lib/python3.12/site-packages/setuptools/config/NOTICE b/.venv/lib/python3.12/site-packages/setuptools/config/NOTICE
new file mode 100644
index 0000000000000000000000000000000000000000..01864511b0f52a6bf944f70b5e15b75364791935
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/config/NOTICE
@@ -0,0 +1,10 @@
+The following files include code from opensource projects
+(either as direct copies or modified versions):
+
+- `setuptools.schema.json`, `distutils.schema.json`:
+    - project: `validate-pyproject` - licensed under MPL-2.0
+      (https://github.com/abravalheri/validate-pyproject):
+
+      This Source Code Form is subject to the terms of the Mozilla Public
+      License, v. 2.0. If a copy of the MPL was not distributed with this file,
+      You can obtain one at https://mozilla.org/MPL/2.0/.
diff --git a/.venv/lib/python3.12/site-packages/setuptools/config/__init__.py b/.venv/lib/python3.12/site-packages/setuptools/config/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fcc7d008d6c9b3ab2610f2a1b05c4c1eeb5e1416
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/config/__init__.py
@@ -0,0 +1,43 @@
+"""For backward compatibility, expose main functions from
+``setuptools.config.setupcfg``
+"""
+
+from functools import wraps
+from typing import Callable, TypeVar, cast
+
+from ..warnings import SetuptoolsDeprecationWarning
+from . import setupcfg
+
+Fn = TypeVar("Fn", bound=Callable)
+
+__all__ = ('parse_configuration', 'read_configuration')
+
+
+def _deprecation_notice(fn: Fn) -> Fn:
+    @wraps(fn)
+    def _wrapper(*args, **kwargs):
+        SetuptoolsDeprecationWarning.emit(
+            "Deprecated API usage.",
+            f"""
+            As setuptools moves its configuration towards `pyproject.toml`,
+            `{__name__}.{fn.__name__}` became deprecated.
+
+            For the time being, you can use the `{setupcfg.__name__}` module
+            to access a backward compatible API, but this module is provisional
+            and might be removed in the future.
+
+            To read project metadata, consider using
+            ``build.util.project_wheel_metadata`` (https://pypi.org/project/build/).
+            For simple scenarios, you can also try parsing the file directly
+            with the help of ``configparser``.
+            """,
+            # due_date not defined yet, because the community still heavily relies on it
+            # Warning introduced in 24 Mar 2022
+        )
+        return fn(*args, **kwargs)
+
+    return cast(Fn, _wrapper)
+
+
+read_configuration = _deprecation_notice(setupcfg.read_configuration)
+parse_configuration = _deprecation_notice(setupcfg.parse_configuration)
diff --git a/.venv/lib/python3.12/site-packages/setuptools/config/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/config/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..88413a975c9edc4422f6c50a6ab005c39157b27b
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/config/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/config/__pycache__/_apply_pyprojecttoml.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/config/__pycache__/_apply_pyprojecttoml.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..428e37ccab2ba1abcba143ecdcc101d6ffa14b57
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/config/__pycache__/_apply_pyprojecttoml.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/config/__pycache__/expand.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/config/__pycache__/expand.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..db505b0925f25b9f17aabf1dbef634c0eebaa7a6
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/config/__pycache__/expand.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/config/__pycache__/pyprojecttoml.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/config/__pycache__/pyprojecttoml.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2ada41d6382537cba21bb6b905dc645a3389d77f
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/config/__pycache__/pyprojecttoml.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/config/__pycache__/setupcfg.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/config/__pycache__/setupcfg.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b7821ac5de500b3d41718d73a4d5bd5e39352df4
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/config/__pycache__/setupcfg.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/config/_apply_pyprojecttoml.py b/.venv/lib/python3.12/site-packages/setuptools/config/_apply_pyprojecttoml.py
new file mode 100644
index 0000000000000000000000000000000000000000..9088bc1383c87d3ed62a5a4dc44481ffafa1e35e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/config/_apply_pyprojecttoml.py
@@ -0,0 +1,526 @@
+"""Translation layer between pyproject config and setuptools distribution and
+metadata objects.
+
+The distribution and metadata objects are modeled after (an old version of)
+core metadata, therefore configs in the format specified for ``pyproject.toml``
+need to be processed before being applied.
+
+**PRIVATE MODULE**: API reserved for setuptools internal usage only.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+from collections.abc import Mapping
+from email.headerregistry import Address
+from functools import partial, reduce
+from inspect import cleandoc
+from itertools import chain
+from types import MappingProxyType
+from typing import TYPE_CHECKING, Any, Callable, TypeVar, Union
+
+from .. import _static
+from .._path import StrPath
+from ..errors import InvalidConfigError, RemovedConfigError
+from ..extension import Extension
+from ..warnings import SetuptoolsDeprecationWarning, SetuptoolsWarning
+
+if TYPE_CHECKING:
+    from typing_extensions import TypeAlias
+
+    from setuptools._importlib import metadata
+    from setuptools.dist import Distribution
+
+    from distutils.dist import _OptionsList  # Comes from typeshed
+
+
+EMPTY: Mapping = MappingProxyType({})  # Immutable dict-like
+_ProjectReadmeValue: TypeAlias = Union[str, dict[str, str]]
+_Correspondence: TypeAlias = Callable[["Distribution", Any, Union[StrPath, None]], None]
+_T = TypeVar("_T")
+
+_logger = logging.getLogger(__name__)
+
+
+def apply(dist: Distribution, config: dict, filename: StrPath) -> Distribution:
+    """Apply configuration dict read with :func:`read_configuration`"""
+
+    if not config:
+        return dist  # short-circuit unrelated pyproject.toml file
+
+    root_dir = os.path.dirname(filename) or "."
+
+    _apply_project_table(dist, config, root_dir)
+    _apply_tool_table(dist, config, filename)
+
+    current_directory = os.getcwd()
+    os.chdir(root_dir)
+    try:
+        dist._finalize_requires()
+        dist._finalize_license_expression()
+        dist._finalize_license_files()
+    finally:
+        os.chdir(current_directory)
+
+    return dist
+
+
+def _apply_project_table(dist: Distribution, config: dict, root_dir: StrPath):
+    orig_config = config.get("project", {})
+    if not orig_config:
+        return  # short-circuit
+
+    project_table = {k: _static.attempt_conversion(v) for k, v in orig_config.items()}
+    _handle_missing_dynamic(dist, project_table)
+    _unify_entry_points(project_table)
+
+    for field, value in project_table.items():
+        norm_key = json_compatible_key(field)
+        corresp = PYPROJECT_CORRESPONDENCE.get(norm_key, norm_key)
+        if callable(corresp):
+            corresp(dist, value, root_dir)
+        else:
+            _set_config(dist, corresp, value)
+
+
+def _apply_tool_table(dist: Distribution, config: dict, filename: StrPath):
+    tool_table = config.get("tool", {}).get("setuptools", {})
+    if not tool_table:
+        return  # short-circuit
+
+    if "license-files" in tool_table:
+        if "license-files" in config.get("project", {}):
+            # https://github.com/pypa/setuptools/pull/4837#discussion_r2004983349
+            raise InvalidConfigError(
+                "'project.license-files' is defined already. "
+                "Remove 'tool.setuptools.license-files'."
+            )
+
+        pypa_guides = "guides/writing-pyproject-toml/#license-files"
+        SetuptoolsDeprecationWarning.emit(
+            "'tool.setuptools.license-files' is deprecated in favor of "
+            "'project.license-files' (available on setuptools>=77.0.0).",
+            see_url=f"https://packaging.python.org/en/latest/{pypa_guides}",
+            due_date=(2026, 2, 18),  # Warning introduced on 2025-02-18
+        )
+
+    for field, value in tool_table.items():
+        norm_key = json_compatible_key(field)
+
+        if norm_key in TOOL_TABLE_REMOVALS:
+            suggestion = cleandoc(TOOL_TABLE_REMOVALS[norm_key])
+            msg = f"""
+            The parameter `tool.setuptools.{field}` was long deprecated
+            and has been removed from `pyproject.toml`.
+            """
+            raise RemovedConfigError("\n".join([cleandoc(msg), suggestion]))
+
+        norm_key = TOOL_TABLE_RENAMES.get(norm_key, norm_key)
+        corresp = TOOL_TABLE_CORRESPONDENCE.get(norm_key, norm_key)
+        if callable(corresp):
+            corresp(dist, value)
+        else:
+            _set_config(dist, corresp, value)
+
+    _copy_command_options(config, dist, filename)
+
+
+def _handle_missing_dynamic(dist: Distribution, project_table: dict):
+    """Be temporarily forgiving with ``dynamic`` fields not listed in ``dynamic``"""
+    dynamic = set(project_table.get("dynamic", []))
+    for field, getter in _PREVIOUSLY_DEFINED.items():
+        if not (field in project_table or field in dynamic):
+            value = getter(dist)
+            if value:
+                _MissingDynamic.emit(field=field, value=value)
+                project_table[field] = _RESET_PREVIOUSLY_DEFINED.get(field)
+
+
+def json_compatible_key(key: str) -> str:
+    """As defined in :pep:`566#json-compatible-metadata`"""
+    return key.lower().replace("-", "_")
+
+
+def _set_config(dist: Distribution, field: str, value: Any):
+    val = _PREPROCESS.get(field, _noop)(dist, value)
+    setter = getattr(dist.metadata, f"set_{field}", None)
+    if setter:
+        setter(val)
+    elif hasattr(dist.metadata, field) or field in SETUPTOOLS_PATCHES:
+        setattr(dist.metadata, field, val)
+    else:
+        setattr(dist, field, val)
+
+
+_CONTENT_TYPES = {
+    ".md": "text/markdown",
+    ".rst": "text/x-rst",
+    ".txt": "text/plain",
+}
+
+
+def _guess_content_type(file: str) -> str | None:
+    _, ext = os.path.splitext(file.lower())
+    if not ext:
+        return None
+
+    if ext in _CONTENT_TYPES:
+        return _static.Str(_CONTENT_TYPES[ext])
+
+    valid = ", ".join(f"{k} ({v})" for k, v in _CONTENT_TYPES.items())
+    msg = f"only the following file extensions are recognized: {valid}."
+    raise ValueError(f"Undefined content type for {file}, {msg}")
+
+
+def _long_description(
+    dist: Distribution, val: _ProjectReadmeValue, root_dir: StrPath | None
+):
+    from setuptools.config import expand
+
+    file: str | tuple[()]
+    if isinstance(val, str):
+        file = val
+        text = expand.read_files(file, root_dir)
+        ctype = _guess_content_type(file)
+    else:
+        file = val.get("file") or ()
+        text = val.get("text") or expand.read_files(file, root_dir)
+        ctype = val["content-type"]
+
+    # XXX: Is it completely safe to assume static?
+    _set_config(dist, "long_description", _static.Str(text))
+
+    if ctype:
+        _set_config(dist, "long_description_content_type", _static.Str(ctype))
+
+    if file:
+        dist._referenced_files.add(file)
+
+
+def _license(dist: Distribution, val: str | dict, root_dir: StrPath | None):
+    from setuptools.config import expand
+
+    if isinstance(val, str):
+        if getattr(dist.metadata, "license", None):
+            SetuptoolsWarning.emit("`license` overwritten by `pyproject.toml`")
+            dist.metadata.license = None
+        _set_config(dist, "license_expression", _static.Str(val))
+    else:
+        pypa_guides = "guides/writing-pyproject-toml/#license"
+        SetuptoolsDeprecationWarning.emit(
+            "`project.license` as a TOML table is deprecated",
+            "Please use a simple string containing a SPDX expression for "
+            "`project.license`. You can also use `project.license-files`. "
+            "(Both options available on setuptools>=77.0.0).",
+            see_url=f"https://packaging.python.org/en/latest/{pypa_guides}",
+            due_date=(2026, 2, 18),  # Introduced on 2025-02-18
+        )
+        if "file" in val:
+            # XXX: Is it completely safe to assume static?
+            value = expand.read_files([val["file"]], root_dir)
+            _set_config(dist, "license", _static.Str(value))
+            dist._referenced_files.add(val["file"])
+        else:
+            _set_config(dist, "license", _static.Str(val["text"]))
+
+
+def _people(dist: Distribution, val: list[dict], _root_dir: StrPath | None, kind: str):
+    field = []
+    email_field = []
+    for person in val:
+        if "name" not in person:
+            email_field.append(person["email"])
+        elif "email" not in person:
+            field.append(person["name"])
+        else:
+            addr = Address(display_name=person["name"], addr_spec=person["email"])
+            email_field.append(str(addr))
+
+    if field:
+        _set_config(dist, kind, _static.Str(", ".join(field)))
+    if email_field:
+        _set_config(dist, f"{kind}_email", _static.Str(", ".join(email_field)))
+
+
+def _project_urls(dist: Distribution, val: dict, _root_dir: StrPath | None):
+    _set_config(dist, "project_urls", val)
+
+
+def _python_requires(dist: Distribution, val: str, _root_dir: StrPath | None):
+    _set_config(dist, "python_requires", _static.SpecifierSet(val))
+
+
+def _dependencies(dist: Distribution, val: list, _root_dir: StrPath | None):
+    if getattr(dist, "install_requires", []):
+        msg = "`install_requires` overwritten in `pyproject.toml` (dependencies)"
+        SetuptoolsWarning.emit(msg)
+    dist.install_requires = val
+
+
+def _optional_dependencies(dist: Distribution, val: dict, _root_dir: StrPath | None):
+    if getattr(dist, "extras_require", None):
+        msg = "`extras_require` overwritten in `pyproject.toml` (optional-dependencies)"
+        SetuptoolsWarning.emit(msg)
+    dist.extras_require = val
+
+
+def _ext_modules(dist: Distribution, val: list[dict]) -> list[Extension]:
+    existing = dist.ext_modules or []
+    args = ({k.replace("-", "_"): v for k, v in x.items()} for x in val)
+    new = [Extension(**kw) for kw in args]
+    return [*existing, *new]
+
+
+def _noop(_dist: Distribution, val: _T) -> _T:
+    return val
+
+
+def _identity(val: _T) -> _T:
+    return val
+
+
+def _unify_entry_points(project_table: dict):
+    project = project_table
+    given = project.pop("entry-points", project.pop("entry_points", {}))
+    entry_points = dict(given)  # Avoid problems with static
+    renaming = {"scripts": "console_scripts", "gui_scripts": "gui_scripts"}
+    for key, value in list(project.items()):  # eager to allow modifications
+        norm_key = json_compatible_key(key)
+        if norm_key in renaming:
+            # Don't skip even if value is empty (reason: reset missing `dynamic`)
+            entry_points[renaming[norm_key]] = project.pop(key)
+
+    if entry_points:
+        project["entry-points"] = {
+            name: [f"{k} = {v}" for k, v in group.items()]
+            for name, group in entry_points.items()
+            if group  # now we can skip empty groups
+        }
+        # Sometimes this will set `project["entry-points"] = {}`, and that is
+        # intentional (for resetting configurations that are missing `dynamic`).
+
+
+def _copy_command_options(pyproject: dict, dist: Distribution, filename: StrPath):
+    tool_table = pyproject.get("tool", {})
+    cmdclass = tool_table.get("setuptools", {}).get("cmdclass", {})
+    valid_options = _valid_command_options(cmdclass)
+
+    cmd_opts = dist.command_options
+    for cmd, config in pyproject.get("tool", {}).get("distutils", {}).items():
+        cmd = json_compatible_key(cmd)
+        valid = valid_options.get(cmd, set())
+        cmd_opts.setdefault(cmd, {})
+        for key, value in config.items():
+            key = json_compatible_key(key)
+            cmd_opts[cmd][key] = (str(filename), value)
+            if key not in valid:
+                # To avoid removing options that are specified dynamically we
+                # just log a warn...
+                _logger.warning(f"Command option {cmd}.{key} is not defined")
+
+
+def _valid_command_options(cmdclass: Mapping = EMPTY) -> dict[str, set[str]]:
+    from setuptools.dist import Distribution
+
+    from .._importlib import metadata
+
+    valid_options = {"global": _normalise_cmd_options(Distribution.global_options)}
+
+    unloaded_entry_points = metadata.entry_points(group='distutils.commands')
+    loaded_entry_points = (_load_ep(ep) for ep in unloaded_entry_points)
+    entry_points = (ep for ep in loaded_entry_points if ep)
+    for cmd, cmd_class in chain(entry_points, cmdclass.items()):
+        opts = valid_options.get(cmd, set())
+        opts = opts | _normalise_cmd_options(getattr(cmd_class, "user_options", []))
+        valid_options[cmd] = opts
+
+    return valid_options
+
+
+def _load_ep(ep: metadata.EntryPoint) -> tuple[str, type] | None:
+    if ep.value.startswith("wheel.bdist_wheel"):
+        # Ignore deprecated entrypoint from wheel and avoid warning pypa/wheel#631
+        # TODO: remove check when `bdist_wheel` has been fully removed from pypa/wheel
+        return None
+
+    # Ignore all the errors
+    try:
+        return (ep.name, ep.load())
+    except Exception as ex:
+        msg = f"{ex.__class__.__name__} while trying to load entry-point {ep.name}"
+        _logger.warning(f"{msg}: {ex}")
+        return None
+
+
+def _normalise_cmd_option_key(name: str) -> str:
+    return json_compatible_key(name).strip("_=")
+
+
+def _normalise_cmd_options(desc: _OptionsList) -> set[str]:
+    return {_normalise_cmd_option_key(fancy_option[0]) for fancy_option in desc}
+
+
+def _get_previous_entrypoints(dist: Distribution) -> dict[str, list]:
+    ignore = ("console_scripts", "gui_scripts")
+    value = getattr(dist, "entry_points", None) or {}
+    return {k: v for k, v in value.items() if k not in ignore}
+
+
+def _get_previous_scripts(dist: Distribution) -> list | None:
+    value = getattr(dist, "entry_points", None) or {}
+    return value.get("console_scripts")
+
+
+def _get_previous_gui_scripts(dist: Distribution) -> list | None:
+    value = getattr(dist, "entry_points", None) or {}
+    return value.get("gui_scripts")
+
+
+def _set_static_list_metadata(attr: str, dist: Distribution, val: list) -> None:
+    """Apply distutils metadata validation but preserve "static" behaviour"""
+    meta = dist.metadata
+    setter, getter = getattr(meta, f"set_{attr}"), getattr(meta, f"get_{attr}")
+    setter(val)
+    setattr(meta, attr, _static.List(getter()))
+
+
+def _attrgetter(attr):
+    """
+    Similar to ``operator.attrgetter`` but returns None if ``attr`` is not found
+    >>> from types import SimpleNamespace
+    >>> obj = SimpleNamespace(a=42, b=SimpleNamespace(c=13))
+    >>> _attrgetter("a")(obj)
+    42
+    >>> _attrgetter("b.c")(obj)
+    13
+    >>> _attrgetter("d")(obj) is None
+    True
+    """
+    return partial(reduce, lambda acc, x: getattr(acc, x, None), attr.split("."))
+
+
+def _some_attrgetter(*items):
+    """
+    Return the first "truth-y" attribute or None
+    >>> from types import SimpleNamespace
+    >>> obj = SimpleNamespace(a=42, b=SimpleNamespace(c=13))
+    >>> _some_attrgetter("d", "a", "b.c")(obj)
+    42
+    >>> _some_attrgetter("d", "e", "b.c", "a")(obj)
+    13
+    >>> _some_attrgetter("d", "e", "f")(obj) is None
+    True
+    """
+
+    def _acessor(obj):
+        values = (_attrgetter(i)(obj) for i in items)
+        return next((i for i in values if i is not None), None)
+
+    return _acessor
+
+
+PYPROJECT_CORRESPONDENCE: dict[str, _Correspondence] = {
+    "readme": _long_description,
+    "license": _license,
+    "authors": partial(_people, kind="author"),
+    "maintainers": partial(_people, kind="maintainer"),
+    "urls": _project_urls,
+    "dependencies": _dependencies,
+    "optional_dependencies": _optional_dependencies,
+    "requires_python": _python_requires,
+}
+
+TOOL_TABLE_RENAMES = {"script_files": "scripts"}
+TOOL_TABLE_REMOVALS = {
+    "namespace_packages": """
+        Please migrate to implicit native namespaces instead.
+        See https://packaging.python.org/en/latest/guides/packaging-namespace-packages/.
+        """,
+}
+TOOL_TABLE_CORRESPONDENCE = {
+    # Fields with corresponding core metadata need to be marked as static:
+    "obsoletes": partial(_set_static_list_metadata, "obsoletes"),
+    "provides": partial(_set_static_list_metadata, "provides"),
+    "platforms": partial(_set_static_list_metadata, "platforms"),
+}
+
+SETUPTOOLS_PATCHES = {
+    "long_description_content_type",
+    "project_urls",
+    "provides_extras",
+    "license_file",
+    "license_files",
+    "license_expression",
+}
+
+_PREPROCESS = {
+    "ext_modules": _ext_modules,
+}
+
+_PREVIOUSLY_DEFINED = {
+    "name": _attrgetter("metadata.name"),
+    "version": _attrgetter("metadata.version"),
+    "description": _attrgetter("metadata.description"),
+    "readme": _attrgetter("metadata.long_description"),
+    "requires-python": _some_attrgetter("python_requires", "metadata.python_requires"),
+    "license": _some_attrgetter("metadata.license_expression", "metadata.license"),
+    # XXX: `license-file` is currently not considered in the context of `dynamic`.
+    #      See TestPresetField.test_license_files_exempt_from_dynamic
+    "authors": _some_attrgetter("metadata.author", "metadata.author_email"),
+    "maintainers": _some_attrgetter("metadata.maintainer", "metadata.maintainer_email"),
+    "keywords": _attrgetter("metadata.keywords"),
+    "classifiers": _attrgetter("metadata.classifiers"),
+    "urls": _attrgetter("metadata.project_urls"),
+    "entry-points": _get_previous_entrypoints,
+    "scripts": _get_previous_scripts,
+    "gui-scripts": _get_previous_gui_scripts,
+    "dependencies": _attrgetter("install_requires"),
+    "optional-dependencies": _attrgetter("extras_require"),
+}
+
+
+_RESET_PREVIOUSLY_DEFINED: dict = {
+    # Fix improper setting: given in `setup.py`, but not listed in `dynamic`
+    # Use "immutable" data structures to avoid in-place modification.
+    # dict: pyproject name => value to which reset
+    "license": "",
+    # XXX: `license-file` is currently not considered in the context of `dynamic`.
+    #      See TestPresetField.test_license_files_exempt_from_dynamic
+    "authors": _static.EMPTY_LIST,
+    "maintainers": _static.EMPTY_LIST,
+    "keywords": _static.EMPTY_LIST,
+    "classifiers": _static.EMPTY_LIST,
+    "urls": _static.EMPTY_DICT,
+    "entry-points": _static.EMPTY_DICT,
+    "scripts": _static.EMPTY_DICT,
+    "gui-scripts": _static.EMPTY_DICT,
+    "dependencies": _static.EMPTY_LIST,
+    "optional-dependencies": _static.EMPTY_DICT,
+}
+
+
+class _MissingDynamic(SetuptoolsWarning):
+    _SUMMARY = "`{field}` defined outside of `pyproject.toml` is ignored."
+
+    _DETAILS = """
+    The following seems to be defined outside of `pyproject.toml`:
+
+    `{field} = {value!r}`
+
+    According to the spec (see the link below), however, setuptools CANNOT
+    consider this value unless `{field}` is listed as `dynamic`.
+
+    https://packaging.python.org/en/latest/specifications/pyproject-toml/#declaring-project-metadata-the-project-table
+
+    To prevent this problem, you can list `{field}` under `dynamic` or alternatively
+    remove the `[project]` table from your file and rely entirely on other means of
+    configuration.
+    """
+    # TODO: Consider removing this check in the future?
+    #       There is a trade-off here between improving "debug-ability" and the cost
+    #       of running/testing/maintaining these unnecessary checks...
+
+    @classmethod
+    def details(cls, field: str, value: Any) -> str:
+        return cls._DETAILS.format(field=field, value=value)
diff --git a/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/NOTICE b/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/NOTICE
new file mode 100644
index 0000000000000000000000000000000000000000..ac5464d88c6f071c18d8eceb1e81d2550573599b
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/NOTICE
@@ -0,0 +1,438 @@
+The code contained in this directory was automatically generated using the
+following command:
+
+    python -m validate_pyproject.pre_compile --output-dir=setuptools/config/_validate_pyproject --enable-plugins setuptools distutils --very-verbose -t setuptools=setuptools/config/setuptools.schema.json -t distutils=setuptools/config/distutils.schema.json
+
+Please avoid changing it manually.
+
+
+You can report issues or suggest changes directly to `validate-pyproject`
+(or to the relevant plugin repository)
+
+- https://github.com/abravalheri/validate-pyproject/issues
+
+
+***
+
+The following files include code from opensource projects
+(either as direct copies or modified versions):
+
+- `fastjsonschema_exceptions.py`:
+    - project: `fastjsonschema` - licensed under BSD-3-Clause
+      (https://github.com/horejsek/python-fastjsonschema)
+- `extra_validations.py` and `format.py`, `error_reporting.py`:
+    - project: `validate-pyproject` - licensed under MPL-2.0
+      (https://github.com/abravalheri/validate-pyproject)
+
+
+Additionally the following files are automatically generated by tools provided
+by the same projects:
+
+- `__init__.py`
+- `fastjsonschema_validations.py`
+
+The relevant copyright notes and licenses are included below.
+
+
+***
+
+`fastjsonschema`
+================
+
+Copyright (c) 2018, Michal Horejsek
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+  Redistributions of source code must retain the above copyright notice, this
+  list of conditions and the following disclaimer.
+
+  Redistributions in binary form must reproduce the above copyright notice, this
+  list of conditions and the following disclaimer in the documentation and/or
+  other materials provided with the distribution.
+
+  Neither the name of the {organization} 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.
+
+
+
+***
+
+`validate-pyproject`
+====================
+
+Mozilla Public License, version 2.0
+
+1. Definitions
+
+1.1. "Contributor"
+
+     means each individual or legal entity that creates, contributes to the
+     creation of, or owns Covered Software.
+
+1.2. "Contributor Version"
+
+     means the combination of the Contributions of others (if any) used by a
+     Contributor and that particular Contributor's Contribution.
+
+1.3. "Contribution"
+
+     means Covered Software of a particular Contributor.
+
+1.4. "Covered Software"
+
+     means Source Code Form to which the initial Contributor has attached the
+     notice in Exhibit A, the Executable Form of such Source Code Form, and
+     Modifications of such Source Code Form, in each case including portions
+     thereof.
+
+1.5. "Incompatible With Secondary Licenses"
+     means
+
+     a. that the initial Contributor has attached the notice described in
+        Exhibit B to the Covered Software; or
+
+     b. that the Covered Software was made available under the terms of
+        version 1.1 or earlier of the License, but not also under the terms of
+        a Secondary License.
+
+1.6. "Executable Form"
+
+     means any form of the work other than Source Code Form.
+
+1.7. "Larger Work"
+
+     means a work that combines Covered Software with other material, in a
+     separate file or files, that is not Covered Software.
+
+1.8. "License"
+
+     means this document.
+
+1.9. "Licensable"
+
+     means having the right to grant, to the maximum extent possible, whether
+     at the time of the initial grant or subsequently, any and all of the
+     rights conveyed by this License.
+
+1.10. "Modifications"
+
+     means any of the following:
+
+     a. any file in Source Code Form that results from an addition to,
+        deletion from, or modification of the contents of Covered Software; or
+
+     b. any new file in Source Code Form that contains any Covered Software.
+
+1.11. "Patent Claims" of a Contributor
+
+      means any patent claim(s), including without limitation, method,
+      process, and apparatus claims, in any patent Licensable by such
+      Contributor that would be infringed, but for the grant of the License,
+      by the making, using, selling, offering for sale, having made, import,
+      or transfer of either its Contributions or its Contributor Version.
+
+1.12. "Secondary License"
+
+      means either the GNU General Public License, Version 2.0, the GNU Lesser
+      General Public License, Version 2.1, the GNU Affero General Public
+      License, Version 3.0, or any later versions of those licenses.
+
+1.13. "Source Code Form"
+
+      means the form of the work preferred for making modifications.
+
+1.14. "You" (or "Your")
+
+      means an individual or a legal entity exercising rights under this
+      License. For legal entities, "You" includes any entity that controls, is
+      controlled by, or is under common control with You. For purposes of this
+      definition, "control" means (a) the power, direct or indirect, to cause
+      the direction or management of such entity, whether by contract or
+      otherwise, or (b) ownership of more than fifty percent (50%) of the
+      outstanding shares or beneficial ownership of such entity.
+
+
+2. License Grants and Conditions
+
+2.1. Grants
+
+     Each Contributor hereby grants You a world-wide, royalty-free,
+     non-exclusive license:
+
+     a. under intellectual property rights (other than patent or trademark)
+        Licensable by such Contributor to use, reproduce, make available,
+        modify, display, perform, distribute, and otherwise exploit its
+        Contributions, either on an unmodified basis, with Modifications, or
+        as part of a Larger Work; and
+
+     b. under Patent Claims of such Contributor to make, use, sell, offer for
+        sale, have made, import, and otherwise transfer either its
+        Contributions or its Contributor Version.
+
+2.2. Effective Date
+
+     The licenses granted in Section 2.1 with respect to any Contribution
+     become effective for each Contribution on the date the Contributor first
+     distributes such Contribution.
+
+2.3. Limitations on Grant Scope
+
+     The licenses granted in this Section 2 are the only rights granted under
+     this License. No additional rights or licenses will be implied from the
+     distribution or licensing of Covered Software under this License.
+     Notwithstanding Section 2.1(b) above, no patent license is granted by a
+     Contributor:
+
+     a. for any code that a Contributor has removed from Covered Software; or
+
+     b. for infringements caused by: (i) Your and any other third party's
+        modifications of Covered Software, or (ii) the combination of its
+        Contributions with other software (except as part of its Contributor
+        Version); or
+
+     c. under Patent Claims infringed by Covered Software in the absence of
+        its Contributions.
+
+     This License does not grant any rights in the trademarks, service marks,
+     or logos of any Contributor (except as may be necessary to comply with
+     the notice requirements in Section 3.4).
+
+2.4. Subsequent Licenses
+
+     No Contributor makes additional grants as a result of Your choice to
+     distribute the Covered Software under a subsequent version of this
+     License (see Section 10.2) or under the terms of a Secondary License (if
+     permitted under the terms of Section 3.3).
+
+2.5. Representation
+
+     Each Contributor represents that the Contributor believes its
+     Contributions are its original creation(s) or it has sufficient rights to
+     grant the rights to its Contributions conveyed by this License.
+
+2.6. Fair Use
+
+     This License is not intended to limit any rights You have under
+     applicable copyright doctrines of fair use, fair dealing, or other
+     equivalents.
+
+2.7. Conditions
+
+     Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
+     Section 2.1.
+
+
+3. Responsibilities
+
+3.1. Distribution of Source Form
+
+     All distribution of Covered Software in Source Code Form, including any
+     Modifications that You create or to which You contribute, must be under
+     the terms of this License. You must inform recipients that the Source
+     Code Form of the Covered Software is governed by the terms of this
+     License, and how they can obtain a copy of this License. You may not
+     attempt to alter or restrict the recipients' rights in the Source Code
+     Form.
+
+3.2. Distribution of Executable Form
+
+     If You distribute Covered Software in Executable Form then:
+
+     a. such Covered Software must also be made available in Source Code Form,
+        as described in Section 3.1, and You must inform recipients of the
+        Executable Form how they can obtain a copy of such Source Code Form by
+        reasonable means in a timely manner, at a charge no more than the cost
+        of distribution to the recipient; and
+
+     b. You may distribute such Executable Form under the terms of this
+        License, or sublicense it under different terms, provided that the
+        license for the Executable Form does not attempt to limit or alter the
+        recipients' rights in the Source Code Form under this License.
+
+3.3. Distribution of a Larger Work
+
+     You may create and distribute a Larger Work under terms of Your choice,
+     provided that You also comply with the requirements of this License for
+     the Covered Software. If the Larger Work is a combination of Covered
+     Software with a work governed by one or more Secondary Licenses, and the
+     Covered Software is not Incompatible With Secondary Licenses, this
+     License permits You to additionally distribute such Covered Software
+     under the terms of such Secondary License(s), so that the recipient of
+     the Larger Work may, at their option, further distribute the Covered
+     Software under the terms of either this License or such Secondary
+     License(s).
+
+3.4. Notices
+
+     You may not remove or alter the substance of any license notices
+     (including copyright notices, patent notices, disclaimers of warranty, or
+     limitations of liability) contained within the Source Code Form of the
+     Covered Software, except that You may alter any license notices to the
+     extent required to remedy known factual inaccuracies.
+
+3.5. Application of Additional Terms
+
+     You may choose to offer, and to charge a fee for, warranty, support,
+     indemnity or liability obligations to one or more recipients of Covered
+     Software. However, You may do so only on Your own behalf, and not on
+     behalf of any Contributor. You must make it absolutely clear that any
+     such warranty, support, indemnity, or liability obligation is offered by
+     You alone, and You hereby agree to indemnify every Contributor for any
+     liability incurred by such Contributor as a result of warranty, support,
+     indemnity or liability terms You offer. You may include additional
+     disclaimers of warranty and limitations of liability specific to any
+     jurisdiction.
+
+4. Inability to Comply Due to Statute or Regulation
+
+   If it is impossible for You to comply with any of the terms of this License
+   with respect to some or all of the Covered Software due to statute,
+   judicial order, or regulation then You must: (a) comply with the terms of
+   this License to the maximum extent possible; and (b) describe the
+   limitations and the code they affect. Such description must be placed in a
+   text file included with all distributions of the Covered Software under
+   this License. Except to the extent prohibited by statute or regulation,
+   such description must be sufficiently detailed for a recipient of ordinary
+   skill to be able to understand it.
+
+5. Termination
+
+5.1. The rights granted under this License will terminate automatically if You
+     fail to comply with any of its terms. However, if You become compliant,
+     then the rights granted under this License from a particular Contributor
+     are reinstated (a) provisionally, unless and until such Contributor
+     explicitly and finally terminates Your grants, and (b) on an ongoing
+     basis, if such Contributor fails to notify You of the non-compliance by
+     some reasonable means prior to 60 days after You have come back into
+     compliance. Moreover, Your grants from a particular Contributor are
+     reinstated on an ongoing basis if such Contributor notifies You of the
+     non-compliance by some reasonable means, this is the first time You have
+     received notice of non-compliance with this License from such
+     Contributor, and You become compliant prior to 30 days after Your receipt
+     of the notice.
+
+5.2. If You initiate litigation against any entity by asserting a patent
+     infringement claim (excluding declaratory judgment actions,
+     counter-claims, and cross-claims) alleging that a Contributor Version
+     directly or indirectly infringes any patent, then the rights granted to
+     You by any and all Contributors for the Covered Software under Section
+     2.1 of this License shall terminate.
+
+5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user
+     license agreements (excluding distributors and resellers) which have been
+     validly granted by You or Your distributors under this License prior to
+     termination shall survive termination.
+
+6. Disclaimer of Warranty
+
+   Covered Software is provided under this License on an "as is" basis,
+   without warranty of any kind, either expressed, implied, or statutory,
+   including, without limitation, warranties that the Covered Software is free
+   of defects, merchantable, fit for a particular purpose or non-infringing.
+   The entire risk as to the quality and performance of the Covered Software
+   is with You. Should any Covered Software prove defective in any respect,
+   You (not any Contributor) assume the cost of any necessary servicing,
+   repair, or correction. This disclaimer of warranty constitutes an essential
+   part of this License. No use of  any Covered Software is authorized under
+   this License except under this disclaimer.
+
+7. Limitation of Liability
+
+   Under no circumstances and under no legal theory, whether tort (including
+   negligence), contract, or otherwise, shall any Contributor, or anyone who
+   distributes Covered Software as permitted above, be liable to You for any
+   direct, indirect, special, incidental, or consequential damages of any
+   character including, without limitation, damages for lost profits, loss of
+   goodwill, work stoppage, computer failure or malfunction, or any and all
+   other commercial damages or losses, even if such party shall have been
+   informed of the possibility of such damages. This limitation of liability
+   shall not apply to liability for death or personal injury resulting from
+   such party's negligence to the extent applicable law prohibits such
+   limitation. Some jurisdictions do not allow the exclusion or limitation of
+   incidental or consequential damages, so this exclusion and limitation may
+   not apply to You.
+
+8. Litigation
+
+   Any litigation relating to this License may be brought only in the courts
+   of a jurisdiction where the defendant maintains its principal place of
+   business and such litigation shall be governed by laws of that
+   jurisdiction, without reference to its conflict-of-law provisions. Nothing
+   in this Section shall prevent a party's ability to bring cross-claims or
+   counter-claims.
+
+9. Miscellaneous
+
+   This License represents the complete agreement concerning the subject
+   matter hereof. If any provision of this License is held to be
+   unenforceable, such provision shall be reformed only to the extent
+   necessary to make it enforceable. Any law or regulation which provides that
+   the language of a contract shall be construed against the drafter shall not
+   be used to construe this License against a Contributor.
+
+
+10. Versions of the License
+
+10.1. New Versions
+
+      Mozilla Foundation is the license steward. Except as provided in Section
+      10.3, no one other than the license steward has the right to modify or
+      publish new versions of this License. Each version will be given a
+      distinguishing version number.
+
+10.2. Effect of New Versions
+
+      You may distribute the Covered Software under the terms of the version
+      of the License under which You originally received the Covered Software,
+      or under the terms of any subsequent version published by the license
+      steward.
+
+10.3. Modified Versions
+
+      If you create software not governed by this License, and you want to
+      create a new license for such software, you may create and use a
+      modified version of this License if you rename the license and remove
+      any references to the name of the license steward (except to note that
+      such modified license differs from this License).
+
+10.4. Distributing Source Code Form that is Incompatible With Secondary
+      Licenses If You choose to distribute Source Code Form that is
+      Incompatible With Secondary Licenses under the terms of this version of
+      the License, the notice described in Exhibit B of this License must be
+      attached.
+
+Exhibit A - Source Code Form License Notice
+
+      This Source Code Form is subject to the
+      terms of the Mozilla Public License, v.
+      2.0. If a copy of the MPL was not
+      distributed with this file, You can
+      obtain one at
+      https://mozilla.org/MPL/2.0/.
+
+If it is not possible or desirable to put the notice in a particular file,
+then You may include the notice in a location (such as a LICENSE file in a
+relevant directory) where a recipient would be likely to look for such a
+notice.
+
+You may add additional accurate notices of copyright ownership.
+
+Exhibit B - "Incompatible With Secondary Licenses" Notice
+
+      This Source Code Form is "Incompatible
+      With Secondary Licenses", as defined by
+      the Mozilla Public License, v. 2.0.
diff --git a/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/__init__.py b/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4f612bd51c4ac1d272318ed6fb96e4aeb57e3e27
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/__init__.py
@@ -0,0 +1,34 @@
+from functools import reduce
+from typing import Any, Callable, Dict
+
+from . import formats
+from .error_reporting import detailed_errors, ValidationError
+from .extra_validations import EXTRA_VALIDATIONS
+from .fastjsonschema_exceptions import JsonSchemaException, JsonSchemaValueException
+from .fastjsonschema_validations import validate as _validate
+
+__all__ = [
+    "validate",
+    "FORMAT_FUNCTIONS",
+    "EXTRA_VALIDATIONS",
+    "ValidationError",
+    "JsonSchemaException",
+    "JsonSchemaValueException",
+]
+
+
+FORMAT_FUNCTIONS: Dict[str, Callable[[str], bool]] = {
+    fn.__name__.replace("_", "-"): fn
+    for fn in formats.__dict__.values()
+    if callable(fn) and not fn.__name__.startswith("_")
+}
+
+
+def validate(data: Any) -> bool:
+    """Validate the given ``data`` object using JSON Schema
+    This function raises ``ValidationError`` if ``data`` is invalid.
+    """
+    with detailed_errors():
+        _validate(data, custom_formats=FORMAT_FUNCTIONS)
+        reduce(lambda acc, fn: fn(acc), EXTRA_VALIDATIONS, data)
+    return True
diff --git a/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..779e5cb33880620bfe1bd0d3f8893e8e2f9449d1
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/__pycache__/error_reporting.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/__pycache__/error_reporting.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f66bf2f7f49575f905beffaf12f7b67cb5911743
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/__pycache__/error_reporting.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/__pycache__/extra_validations.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/__pycache__/extra_validations.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7e4317bb8ab0876c637120575df2dd605857093f
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/__pycache__/extra_validations.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/__pycache__/fastjsonschema_exceptions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/__pycache__/fastjsonschema_exceptions.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2ca270a4f091a4d85365207a106bf62a6405ea4d
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/__pycache__/fastjsonschema_exceptions.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/__pycache__/fastjsonschema_validations.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/__pycache__/fastjsonschema_validations.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b740eaabf15602a8780676e9e9759321144c5893
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/__pycache__/fastjsonschema_validations.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:e9fa30f2e8dc28794119de603c6d204647a967a49635997163f5b248c3c18dfe
+size 233678
diff --git a/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/__pycache__/formats.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/__pycache__/formats.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6c28e0ece57f353cd0f9094359af9226c10abd92
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/__pycache__/formats.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/error_reporting.py b/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/error_reporting.py
new file mode 100644
index 0000000000000000000000000000000000000000..3591231c09f56494eb46119f9794053439b3fe8c
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/error_reporting.py
@@ -0,0 +1,336 @@
+import io
+import json
+import logging
+import os
+import re
+import typing
+from contextlib import contextmanager
+from textwrap import indent, wrap
+from typing import Any, Dict, Generator, Iterator, List, Optional, Sequence, Union
+
+from .fastjsonschema_exceptions import JsonSchemaValueException
+
+if typing.TYPE_CHECKING:
+    import sys
+
+    if sys.version_info < (3, 11):
+        from typing_extensions import Self
+    else:
+        from typing import Self
+
+_logger = logging.getLogger(__name__)
+
+_MESSAGE_REPLACEMENTS = {
+    "must be named by propertyName definition": "keys must be named by",
+    "one of contains definition": "at least one item that matches",
+    " same as const definition:": "",
+    "only specified items": "only items matching the definition",
+}
+
+_SKIP_DETAILS = (
+    "must not be empty",
+    "is always invalid",
+    "must not be there",
+)
+
+_NEED_DETAILS = {"anyOf", "oneOf", "allOf", "contains", "propertyNames", "not", "items"}
+
+_CAMEL_CASE_SPLITTER = re.compile(r"\W+|([A-Z][^A-Z\W]*)")
+_IDENTIFIER = re.compile(r"^[\w_]+$", re.I)
+
+_TOML_JARGON = {
+    "object": "table",
+    "property": "key",
+    "properties": "keys",
+    "property names": "keys",
+}
+
+_FORMATS_HELP = """
+For more details about `format` see
+https://validate-pyproject.readthedocs.io/en/latest/api/validate_pyproject.formats.html
+"""
+
+
+class ValidationError(JsonSchemaValueException):
+    """Report violations of a given JSON schema.
+
+    This class extends :exc:`~fastjsonschema.JsonSchemaValueException`
+    by adding the following properties:
+
+    - ``summary``: an improved version of the ``JsonSchemaValueException`` error message
+      with only the necessary information)
+
+    - ``details``: more contextual information about the error like the failing schema
+      itself and the value that violates the schema.
+
+    Depending on the level of the verbosity of the ``logging`` configuration
+    the exception message will be only ``summary`` (default) or a combination of
+    ``summary`` and ``details`` (when the logging level is set to :obj:`logging.DEBUG`).
+    """
+
+    summary = ""
+    details = ""
+    _original_message = ""
+
+    @classmethod
+    def _from_jsonschema(cls, ex: JsonSchemaValueException) -> "Self":
+        formatter = _ErrorFormatting(ex)
+        obj = cls(str(formatter), ex.value, formatter.name, ex.definition, ex.rule)
+        debug_code = os.getenv("JSONSCHEMA_DEBUG_CODE_GENERATION", "false").lower()
+        if debug_code != "false":  # pragma: no cover
+            obj.__cause__, obj.__traceback__ = ex.__cause__, ex.__traceback__
+        obj._original_message = ex.message
+        obj.summary = formatter.summary
+        obj.details = formatter.details
+        return obj
+
+
+@contextmanager
+def detailed_errors() -> Generator[None, None, None]:
+    try:
+        yield
+    except JsonSchemaValueException as ex:
+        raise ValidationError._from_jsonschema(ex) from None
+
+
+class _ErrorFormatting:
+    def __init__(self, ex: JsonSchemaValueException):
+        self.ex = ex
+        self.name = f"`{self._simplify_name(ex.name)}`"
+        self._original_message: str = self.ex.message.replace(ex.name, self.name)
+        self._summary = ""
+        self._details = ""
+
+    def __str__(self) -> str:
+        if _logger.getEffectiveLevel() <= logging.DEBUG and self.details:
+            return f"{self.summary}\n\n{self.details}"
+
+        return self.summary
+
+    @property
+    def summary(self) -> str:
+        if not self._summary:
+            self._summary = self._expand_summary()
+
+        return self._summary
+
+    @property
+    def details(self) -> str:
+        if not self._details:
+            self._details = self._expand_details()
+
+        return self._details
+
+    @staticmethod
+    def _simplify_name(name: str) -> str:
+        x = len("data.")
+        return name[x:] if name.startswith("data.") else name
+
+    def _expand_summary(self) -> str:
+        msg = self._original_message
+
+        for bad, repl in _MESSAGE_REPLACEMENTS.items():
+            msg = msg.replace(bad, repl)
+
+        if any(substring in msg for substring in _SKIP_DETAILS):
+            return msg
+
+        schema = self.ex.rule_definition
+        if self.ex.rule in _NEED_DETAILS and schema:
+            summary = _SummaryWriter(_TOML_JARGON)
+            return f"{msg}:\n\n{indent(summary(schema), '    ')}"
+
+        return msg
+
+    def _expand_details(self) -> str:
+        optional = []
+        definition = self.ex.definition or {}
+        desc_lines = definition.pop("$$description", [])
+        desc = definition.pop("description", None) or " ".join(desc_lines)
+        if desc:
+            description = "\n".join(
+                wrap(
+                    desc,
+                    width=80,
+                    initial_indent="    ",
+                    subsequent_indent="    ",
+                    break_long_words=False,
+                )
+            )
+            optional.append(f"DESCRIPTION:\n{description}")
+        schema = json.dumps(definition, indent=4)
+        value = json.dumps(self.ex.value, indent=4)
+        defaults = [
+            f"GIVEN VALUE:\n{indent(value, '    ')}",
+            f"OFFENDING RULE: {self.ex.rule!r}",
+            f"DEFINITION:\n{indent(schema, '    ')}",
+        ]
+        msg = "\n\n".join(optional + defaults)
+        epilog = f"\n{_FORMATS_HELP}" if "format" in msg.lower() else ""
+        return msg + epilog
+
+
+class _SummaryWriter:
+    _IGNORE = frozenset(("description", "default", "title", "examples"))
+
+    def __init__(self, jargon: Optional[Dict[str, str]] = None):
+        self.jargon: Dict[str, str] = jargon or {}
+        # Clarify confusing terms
+        self._terms = {
+            "anyOf": "at least one of the following",
+            "oneOf": "exactly one of the following",
+            "allOf": "all of the following",
+            "not": "(*NOT* the following)",
+            "prefixItems": f"{self._jargon('items')} (in order)",
+            "items": "items",
+            "contains": "contains at least one of",
+            "propertyNames": (
+                f"non-predefined acceptable {self._jargon('property names')}"
+            ),
+            "patternProperties": f"{self._jargon('properties')} named via pattern",
+            "const": "predefined value",
+            "enum": "one of",
+        }
+        # Attributes that indicate that the definition is easy and can be done
+        # inline (e.g. string and number)
+        self._guess_inline_defs = [
+            "enum",
+            "const",
+            "maxLength",
+            "minLength",
+            "pattern",
+            "format",
+            "minimum",
+            "maximum",
+            "exclusiveMinimum",
+            "exclusiveMaximum",
+            "multipleOf",
+        ]
+
+    def _jargon(self, term: Union[str, List[str]]) -> Union[str, List[str]]:
+        if isinstance(term, list):
+            return [self.jargon.get(t, t) for t in term]
+        return self.jargon.get(term, term)
+
+    def __call__(
+        self,
+        schema: Union[dict, List[dict]],
+        prefix: str = "",
+        *,
+        _path: Sequence[str] = (),
+    ) -> str:
+        if isinstance(schema, list):
+            return self._handle_list(schema, prefix, _path)
+
+        filtered = self._filter_unecessary(schema, _path)
+        simple = self._handle_simple_dict(filtered, _path)
+        if simple:
+            return f"{prefix}{simple}"
+
+        child_prefix = self._child_prefix(prefix, "  ")
+        item_prefix = self._child_prefix(prefix, "- ")
+        indent = len(prefix) * " "
+        with io.StringIO() as buffer:
+            for i, (key, value) in enumerate(filtered.items()):
+                child_path = [*_path, key]
+                line_prefix = prefix if i == 0 else indent
+                buffer.write(f"{line_prefix}{self._label(child_path)}:")
+                # ^  just the first item should receive the complete prefix
+                if isinstance(value, dict):
+                    filtered = self._filter_unecessary(value, child_path)
+                    simple = self._handle_simple_dict(filtered, child_path)
+                    buffer.write(
+                        f" {simple}"
+                        if simple
+                        else f"\n{self(value, child_prefix, _path=child_path)}"
+                    )
+                elif isinstance(value, list) and (
+                    key != "type" or self._is_property(child_path)
+                ):
+                    children = self._handle_list(value, item_prefix, child_path)
+                    sep = " " if children.startswith("[") else "\n"
+                    buffer.write(f"{sep}{children}")
+                else:
+                    buffer.write(f" {self._value(value, child_path)}\n")
+            return buffer.getvalue()
+
+    def _is_unecessary(self, path: Sequence[str]) -> bool:
+        if self._is_property(path) or not path:  # empty path => instruction @ root
+            return False
+        key = path[-1]
+        return any(key.startswith(k) for k in "$_") or key in self._IGNORE
+
+    def _filter_unecessary(
+        self, schema: Dict[str, Any], path: Sequence[str]
+    ) -> Dict[str, Any]:
+        return {
+            key: value
+            for key, value in schema.items()
+            if not self._is_unecessary([*path, key])
+        }
+
+    def _handle_simple_dict(self, value: dict, path: Sequence[str]) -> Optional[str]:
+        inline = any(p in value for p in self._guess_inline_defs)
+        simple = not any(isinstance(v, (list, dict)) for v in value.values())
+        if inline or simple:
+            return f"{{{', '.join(self._inline_attrs(value, path))}}}\n"
+        return None
+
+    def _handle_list(
+        self, schemas: list, prefix: str = "", path: Sequence[str] = ()
+    ) -> str:
+        if self._is_unecessary(path):
+            return ""
+
+        repr_ = repr(schemas)
+        if all(not isinstance(e, (dict, list)) for e in schemas) and len(repr_) < 60:
+            return f"{repr_}\n"
+
+        item_prefix = self._child_prefix(prefix, "- ")
+        return "".join(
+            self(v, item_prefix, _path=[*path, f"[{i}]"]) for i, v in enumerate(schemas)
+        )
+
+    def _is_property(self, path: Sequence[str]) -> bool:
+        """Check if the given path can correspond to an arbitrarily named property"""
+        counter = 0
+        for key in path[-2::-1]:
+            if key not in {"properties", "patternProperties"}:
+                break
+            counter += 1
+
+        # If the counter if even, the path correspond to a JSON Schema keyword
+        # otherwise it can be any arbitrary string naming a property
+        return counter % 2 == 1
+
+    def _label(self, path: Sequence[str]) -> str:
+        *parents, key = path
+        if not self._is_property(path):
+            norm_key = _separate_terms(key)
+            return self._terms.get(key) or " ".join(self._jargon(norm_key))
+
+        if parents[-1] == "patternProperties":
+            return f"(regex {key!r})"
+        return repr(key)  # property name
+
+    def _value(self, value: Any, path: Sequence[str]) -> str:
+        if path[-1] == "type" and not self._is_property(path):
+            type_ = self._jargon(value)
+            return f"[{', '.join(type_)}]" if isinstance(type_, list) else type_
+        return repr(value)
+
+    def _inline_attrs(self, schema: dict, path: Sequence[str]) -> Iterator[str]:
+        for key, value in schema.items():
+            child_path = [*path, key]
+            yield f"{self._label(child_path)}: {self._value(value, child_path)}"
+
+    def _child_prefix(self, parent_prefix: str, child_prefix: str) -> str:
+        return len(parent_prefix) * " " + child_prefix
+
+
+def _separate_terms(word: str) -> List[str]:
+    """
+    >>> _separate_terms("FooBar-foo")
+    ['foo', 'bar', 'foo']
+    """
+    return [w.lower() for w in _CAMEL_CASE_SPLITTER.split(word) if w]
diff --git a/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/extra_validations.py b/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/extra_validations.py
new file mode 100644
index 0000000000000000000000000000000000000000..789411d0ff397041f87a834e634bac8488024326
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/extra_validations.py
@@ -0,0 +1,82 @@
+"""The purpose of this module is implement PEP 621 validations that are
+difficult to express as a JSON Schema (or that are not supported by the current
+JSON Schema library).
+"""
+
+from inspect import cleandoc
+from typing import Mapping, TypeVar
+
+from .error_reporting import ValidationError
+
+T = TypeVar("T", bound=Mapping)
+
+
+class RedefiningStaticFieldAsDynamic(ValidationError):
+    _DESC = """According to PEP 621:
+
+    Build back-ends MUST raise an error if the metadata specifies a field
+    statically as well as being listed in dynamic.
+    """
+    __doc__ = _DESC
+    _URL = (
+        "https://packaging.python.org/en/latest/specifications/"
+        "pyproject-toml/#dynamic"
+    )
+
+
+class IncludedDependencyGroupMustExist(ValidationError):
+    _DESC = """An included dependency group must exist and must not be cyclic.
+    """
+    __doc__ = _DESC
+    _URL = "https://peps.python.org/pep-0735/"
+
+
+def validate_project_dynamic(pyproject: T) -> T:
+    project_table = pyproject.get("project", {})
+    dynamic = project_table.get("dynamic", [])
+
+    for field in dynamic:
+        if field in project_table:
+            raise RedefiningStaticFieldAsDynamic(
+                message=f"You cannot provide a value for `project.{field}` and "
+                "list it under `project.dynamic` at the same time",
+                value={
+                    field: project_table[field],
+                    "...": " # ...",
+                    "dynamic": dynamic,
+                },
+                name=f"data.project.{field}",
+                definition={
+                    "description": cleandoc(RedefiningStaticFieldAsDynamic._DESC),
+                    "see": RedefiningStaticFieldAsDynamic._URL,
+                },
+                rule="PEP 621",
+            )
+
+    return pyproject
+
+
+def validate_include_depenency(pyproject: T) -> T:
+    dependency_groups = pyproject.get("dependency-groups", {})
+    for key, value in dependency_groups.items():
+        for each in value:
+            if (
+                isinstance(each, dict)
+                and (include_group := each.get("include-group"))
+                and include_group not in dependency_groups
+            ):
+                raise IncludedDependencyGroupMustExist(
+                    message=f"The included dependency group {include_group} doesn't exist",
+                    value=each,
+                    name=f"data.dependency_groups.{key}",
+                    definition={
+                        "description": cleandoc(IncludedDependencyGroupMustExist._DESC),
+                        "see": IncludedDependencyGroupMustExist._URL,
+                    },
+                    rule="PEP 735",
+                )
+    # TODO: check for `include-group` cycles (can be conditional to graphlib)
+    return pyproject
+
+
+EXTRA_VALIDATIONS = (validate_project_dynamic, validate_include_depenency)
diff --git a/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/fastjsonschema_exceptions.py b/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/fastjsonschema_exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..d2dddd6a106f021a4723c1e8f5953ccc09e55e1f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/fastjsonschema_exceptions.py
@@ -0,0 +1,51 @@
+import re
+
+
+SPLIT_RE = re.compile(r'[\.\[\]]+')
+
+
+class JsonSchemaException(ValueError):
+    """
+    Base exception of ``fastjsonschema`` library.
+    """
+
+
+class JsonSchemaValueException(JsonSchemaException):
+    """
+    Exception raised by validation function. Available properties:
+
+     * ``message`` containing human-readable information what is wrong (e.g. ``data.property[index] must be smaller than or equal to 42``),
+     * invalid ``value`` (e.g. ``60``),
+     * ``name`` of a path in the data structure (e.g. ``data.property[index]``),
+     * ``path`` as an array in the data structure (e.g. ``['data', 'property', 'index']``),
+     * the whole ``definition`` which the ``value`` has to fulfil (e.g. ``{'type': 'number', 'maximum': 42}``),
+     * ``rule`` which the ``value`` is breaking (e.g. ``maximum``)
+     * and ``rule_definition`` (e.g. ``42``).
+
+    .. versionchanged:: 2.14.0
+        Added all extra properties.
+    """
+
+    def __init__(self, message, value=None, name=None, definition=None, rule=None):
+        super().__init__(message)
+        self.message = message
+        self.value = value
+        self.name = name
+        self.definition = definition
+        self.rule = rule
+
+    @property
+    def path(self):
+        return [item for item in SPLIT_RE.split(self.name) if item != '']
+
+    @property
+    def rule_definition(self):
+        if not self.rule or not self.definition:
+            return None
+        return self.definition.get(self.rule)
+
+
+class JsonSchemaDefinitionException(JsonSchemaException):
+    """
+    Exception raised by generator of validation function.
+    """
diff --git a/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/fastjsonschema_validations.py b/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/fastjsonschema_validations.py
new file mode 100644
index 0000000000000000000000000000000000000000..c69368a83ff1bdb89cf4853e00429f0125ca3dce
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/fastjsonschema_validations.py
@@ -0,0 +1,1412 @@
+# noqa
+# ruff: noqa
+# flake8: noqa
+# pylint: skip-file
+# mypy: ignore-errors
+# yapf: disable
+# pylama:skip=1
+
+
+# *** PLEASE DO NOT MODIFY DIRECTLY: Automatically generated code *** 
+
+
+VERSION = "2.20.0"
+from decimal import Decimal
+import re
+from .fastjsonschema_exceptions import JsonSchemaValueException
+
+
+REGEX_PATTERNS = {
+    '^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$': re.compile('^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])\\Z'),
+    '^.*$': re.compile('^.*$'),
+    '.+': re.compile('.+'),
+    '^.+$': re.compile('^.+$'),
+    'idn-email_re_pattern': re.compile('^[^@]+@[^@]+\\.[^@]+\\Z')
+}
+
+NoneType = type(None)
+
+def validate(data, custom_formats={}, name_prefix=None):
+    validate_https___packaging_python_org_en_latest_specifications_declaring_build_dependencies(data, custom_formats, (name_prefix or "data") + "")
+    return data
+
+def validate_https___packaging_python_org_en_latest_specifications_declaring_build_dependencies(data, custom_formats={}, name_prefix=None):
+    if not isinstance(data, (dict)):
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be object", value=data, name="" + (name_prefix or "data") + "", definition={'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://packaging.python.org/en/latest/specifications/declaring-build-dependencies/', 'title': 'Data structure for ``pyproject.toml`` files', '$$description': ['File format containing build-time configurations for the Python ecosystem. ', ':pep:`517` initially defined a build-system independent format for source trees', 'which was complemented by :pep:`518` to provide a way of specifying dependencies ', 'for building Python projects.', 'Please notice the ``project`` table (as initially defined in  :pep:`621`) is not included', 'in this schema and should be considered separately.'], 'type': 'object', 'additionalProperties': False, 'properties': {'build-system': {'type': 'object', 'description': 'Table used to store build-related data', 'additionalProperties': False, 'properties': {'requires': {'type': 'array', '$$description': ['List of dependencies in the :pep:`508` format required to execute the build', 'system. Please notice that the resulting dependency graph', '**MUST NOT contain cycles**'], 'items': {'type': 'string'}}, 'build-backend': {'type': 'string', 'description': 'Python object that will be used to perform the build according to :pep:`517`', 'format': 'pep517-backend-reference'}, 'backend-path': {'type': 'array', '$$description': ['List of directories to be prepended to ``sys.path`` when loading the', 'back-end, and running its hooks'], 'items': {'type': 'string', '$comment': 'Should be a path (TODO: enforce it with format?)'}}}, 'required': ['requires']}, 'project': {'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://packaging.python.org/en/latest/specifications/pyproject-toml/', 'title': 'Package metadata stored in the ``project`` table', '$$description': ['Data structure for the **project** table inside ``pyproject.toml``', '(as initially defined in :pep:`621`)'], 'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, 'version': {'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, 'description': {'type': 'string', '$$description': ['The `summary description of the project', '`_']}, 'readme': {'$$description': ['`Full/detailed description of the project in the form of a README', '`_', "with meaning similar to the one defined in `core metadata's Description", '`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, 'requires-python': {'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '`_.']}, 'license': {'description': '`Project license `_.', 'oneOf': [{'type': 'string', 'description': 'An SPDX license identifier', 'format': 'SPDX'}, {'type': 'object', 'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'type': 'object', 'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}]}, 'license-files': {'description': 'Paths or globs to paths of license files', 'type': 'array', 'items': {'type': 'string'}}, 'authors': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': ["The people or organizations considered to be the 'authors' of the project.", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, 'maintainers': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': ["The people or organizations considered to be the 'maintainers' of the project.", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, 'keywords': {'type': 'array', 'items': {'type': 'string'}, 'description': 'List of keywords to assist searching for the distribution in a larger catalog.'}, 'classifiers': {'type': 'array', 'items': {'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier `_.'}, '$$description': ['`Trove classifiers `_', 'which apply to the project.']}, 'urls': {'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, 'scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create command-line wrappers for the given', '`entry points `_.']}, 'gui-scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create GUI wrappers for the given', '`entry points `_.', 'The difference between ``scripts`` and ``gui-scripts`` is only relevant in', 'Windows.']}, 'entry-points': {'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$ref': '#/definitions/entry-point-group'}}}, 'dependencies': {'type': 'array', 'description': 'Project (mandatory) dependencies.', 'items': {'$ref': '#/definitions/dependency'}}, 'optional-dependencies': {'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$ref': '#/definitions/dependency'}}}}, 'dynamic': {'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'license-files', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']}}}, 'required': ['name'], 'additionalProperties': False, 'allOf': [{'if': {'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as "Required", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, 'then': {'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}}, {'if': {'required': ['license-files']}, 'then': {'properties': {'license': {'type': 'string'}}}}], 'definitions': {'author': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, 'entry-point-group': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'dependency': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}, 'tool': {'type': 'object', 'properties': {'distutils': {'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://setuptools.pypa.io/en/latest/deprecated/distutils/configfile.html', 'title': '``tool.distutils`` table', '$$description': ['**EXPERIMENTAL** (NOT OFFICIALLY SUPPORTED): Use ``tool.distutils``', 'subtables to configure arguments for ``distutils`` commands.', 'Originally, ``distutils`` allowed developers to configure arguments for', '``setup.py`` commands via `distutils configuration files', '`_.', 'See also `the old Python docs _`.'], 'type': 'object', 'properties': {'global': {'type': 'object', 'description': 'Global options applied to all ``distutils`` commands'}}, 'patternProperties': {'.+': {'type': 'object'}}, '$comment': 'TODO: Is there a practical way of making this schema more specific?'}, 'setuptools': {'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://setuptools.pypa.io/en/latest/userguide/pyproject_config.html', 'title': '``tool.setuptools`` table', '$$description': ['``setuptools``-specific configurations that can be set by users that require', 'customization.', 'These configurations are completely optional and probably can be skipped when', 'creating simple packages. They are equivalent to some of the `Keywords', '`_', 'used by the ``setup.py`` file, and can be set via the ``tool.setuptools`` table.', 'It considers only ``setuptools`` `parameters', '`_', 'that are not covered by :pep:`621`; and intentionally excludes ``dependency_links``', 'and ``setup_requires`` (incompatible with modern workflows/standards).'], 'type': 'object', 'additionalProperties': False, 'properties': {'platforms': {'type': 'array', 'items': {'type': 'string'}}, 'provides': {'$$description': ['Package and virtual package names contained within this package', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'obsoletes': {'$$description': ['Packages which this package renders obsolete', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'zip-safe': {'$$description': ['Whether the project can be safely installed and run from a zip file.', '**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and', '``setup.py install`` in the context of ``eggs`` (**DEPRECATED**).'], 'type': 'boolean'}, 'script-files': {'$$description': ['Legacy way of defining scripts (entry-points are preferred).', 'Equivalent to the ``script`` keyword in ``setup.py``', '(it was renamed to avoid confusion with entry-point based ``project.scripts``', 'defined in :pep:`621`).', '**DISCOURAGED**: generic script wrappers are tricky and may not work properly.', 'Whenever possible, please use ``project.scripts`` instead.'], 'type': 'array', 'items': {'type': 'string'}, '$comment': 'TODO: is this field deprecated/should be removed?'}, 'eager-resources': {'$$description': ['Resources that should be extracted together, if any of them is needed,', 'or if any C extensions included in the project are imported.', '**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and', '``setup.py install`` in the context of ``eggs`` (**DEPRECATED**).'], 'type': 'array', 'items': {'type': 'string'}}, 'packages': {'$$description': ['Packages that should be included in the distribution.', 'It can be given either as a list of package identifiers', 'or as a ``dict``-like structure with a single key ``find``', 'which corresponds to a dynamic call to', '``setuptools.config.expand.find_packages`` function.', 'The ``find`` key is associated with a nested ``dict``-like structure that can', 'contain ``where``, ``include``, ``exclude`` and ``namespaces`` keys,', 'mimicking the keyword arguments of the associated function.'], 'oneOf': [{'title': 'Array of Python package identifiers', 'type': 'array', 'items': {'$ref': '#/definitions/package-name'}}, {'$ref': '#/definitions/find-directive'}]}, 'package-dir': {'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'const': ''}, {'$ref': '#/definitions/package-name'}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, 'package-data': {'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'type': 'string', 'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'include-package-data': {'$$description': ['Automatically include any data files inside the package directories', 'that are specified by ``MANIFEST.in``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'boolean'}, 'exclude-package-data': {'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'type': 'string', 'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'namespace-packages': {'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name-relaxed'}, '$comment': 'https://setuptools.pypa.io/en/latest/userguide/package_discovery.html', 'description': '**DEPRECATED**: use implicit namespaces instead (:pep:`420`).'}, 'py-modules': {'description': 'Modules that setuptools will manipulate', 'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name-relaxed'}, '$comment': 'TODO: clarify the relationship with ``packages``'}, 'ext-modules': {'description': 'Extension modules to be compiled by setuptools', 'type': 'array', 'items': {'$ref': '#/definitions/ext-module'}}, 'data-files': {'$$description': ['``dict``-like structure where each key represents a directory and', 'the value is a list of glob patterns that should be installed in them.', '**DISCOURAGED**: please notice this might not work as expected with wheels.', 'Whenever possible, consider using data files inside the package directories', '(or create a new namespace package that only contains data files).', 'See `data files support', '`_.'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'cmdclass': {'$$description': ['Mapping of distutils-style command names to ``setuptools.Command`` subclasses', 'which in turn should be represented by strings with a qualified class name', '(i.e., "dotted" form with module), e.g.::\n\n', '    cmdclass = {mycmd = "pkg.subpkg.module.CommandClass"}\n\n', 'The command class should be a directly defined at the top-level of the', 'containing module (no class nesting).'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'string', 'format': 'python-qualified-identifier'}}}, 'license-files': {'type': 'array', 'items': {'type': 'string'}, '$$description': ['**PROVISIONAL**: list of glob patterns for all license files being distributed.', '(likely to become standard with :pep:`639`).', "By default: ``['LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*']``"], '$comment': 'TODO: revise if PEP 639 is accepted. Probably ``project.license-files``?'}, 'dynamic': {'type': 'object', 'description': 'Instructions for loading :pep:`621`-related metadata dynamically', 'additionalProperties': False, 'properties': {'version': {'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.', 'Also ensure to set ``project.dynamic`` accordingly.'], 'oneOf': [{'$ref': '#/definitions/attr-directive'}, {'$ref': '#/definitions/file-directive'}]}, 'classifiers': {'$ref': '#/definitions/file-directive'}, 'description': {'$ref': '#/definitions/file-directive'}, 'entry-points': {'$ref': '#/definitions/file-directive'}, 'dependencies': {'$ref': '#/definitions/file-directive-for-dependencies'}, 'optional-dependencies': {'type': 'object', 'propertyNames': {'type': 'string', 'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'$ref': '#/definitions/file-directive-for-dependencies'}}}, 'readme': {'type': 'object', 'anyOf': [{'$ref': '#/definitions/file-directive'}, {'type': 'object', 'properties': {'content-type': {'type': 'string'}, 'file': {'$ref': '#/definitions/file-directive/properties/file'}}, 'additionalProperties': False}], 'required': ['file']}}}}, 'definitions': {'package-name': {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}, 'ext-module': {'$id': '#/definitions/ext-module', 'title': 'Extension module', 'description': 'Parameters to construct a :class:`setuptools.Extension` object', 'type': 'object', 'required': ['name', 'sources'], 'additionalProperties': False, 'properties': {'name': {'type': 'string', 'format': 'python-module-name-relaxed'}, 'sources': {'type': 'array', 'items': {'type': 'string'}}, 'include-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'define-macros': {'type': 'array', 'items': {'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}}, 'undef-macros': {'type': 'array', 'items': {'type': 'string'}}, 'library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'libraries': {'type': 'array', 'items': {'type': 'string'}}, 'runtime-library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'extra-objects': {'type': 'array', 'items': {'type': 'string'}}, 'extra-compile-args': {'type': 'array', 'items': {'type': 'string'}}, 'extra-link-args': {'type': 'array', 'items': {'type': 'string'}}, 'export-symbols': {'type': 'array', 'items': {'type': 'string'}}, 'swig-opts': {'type': 'array', 'items': {'type': 'string'}}, 'depends': {'type': 'array', 'items': {'type': 'string'}}, 'language': {'type': 'string'}, 'optional': {'type': 'boolean'}, 'py-limited-api': {'type': 'boolean'}}}, 'file-directive': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'file-directive-for-dependencies': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}, 'attr-directive': {'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, 'find-directive': {'$id': '#/definitions/find-directive', 'title': "'find:' directive", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}}}}}, 'dependency-groups': {'type': 'object', 'description': 'Dependency groups following PEP 735', 'additionalProperties': False, 'patternProperties': {'^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$': {'type': 'array', 'items': {'oneOf': [{'type': 'string', 'description': 'Python package specifiers following PEP 508', 'format': 'pep508'}, {'type': 'object', 'additionalProperties': False, 'properties': {'include-group': {'description': 'Another dependency group to include in this one', 'type': 'string', 'pattern': '^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$'}}}]}}}}}, 'project': {'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://packaging.python.org/en/latest/specifications/pyproject-toml/', 'title': 'Package metadata stored in the ``project`` table', '$$description': ['Data structure for the **project** table inside ``pyproject.toml``', '(as initially defined in :pep:`621`)'], 'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, 'version': {'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, 'description': {'type': 'string', '$$description': ['The `summary description of the project', '`_']}, 'readme': {'$$description': ['`Full/detailed description of the project in the form of a README', '`_', "with meaning similar to the one defined in `core metadata's Description", '`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, 'requires-python': {'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '`_.']}, 'license': {'description': '`Project license `_.', 'oneOf': [{'type': 'string', 'description': 'An SPDX license identifier', 'format': 'SPDX'}, {'type': 'object', 'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'type': 'object', 'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}]}, 'license-files': {'description': 'Paths or globs to paths of license files', 'type': 'array', 'items': {'type': 'string'}}, 'authors': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': ["The people or organizations considered to be the 'authors' of the project.", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, 'maintainers': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': ["The people or organizations considered to be the 'maintainers' of the project.", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, 'keywords': {'type': 'array', 'items': {'type': 'string'}, 'description': 'List of keywords to assist searching for the distribution in a larger catalog.'}, 'classifiers': {'type': 'array', 'items': {'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier `_.'}, '$$description': ['`Trove classifiers `_', 'which apply to the project.']}, 'urls': {'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, 'scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create command-line wrappers for the given', '`entry points `_.']}, 'gui-scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create GUI wrappers for the given', '`entry points `_.', 'The difference between ``scripts`` and ``gui-scripts`` is only relevant in', 'Windows.']}, 'entry-points': {'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$ref': '#/definitions/entry-point-group'}}}, 'dependencies': {'type': 'array', 'description': 'Project (mandatory) dependencies.', 'items': {'$ref': '#/definitions/dependency'}}, 'optional-dependencies': {'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$ref': '#/definitions/dependency'}}}}, 'dynamic': {'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'license-files', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']}}}, 'required': ['name'], 'additionalProperties': False, 'allOf': [{'if': {'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as "Required", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, 'then': {'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}}, {'if': {'required': ['license-files']}, 'then': {'properties': {'license': {'type': 'string'}}}}], 'definitions': {'author': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, 'entry-point-group': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'dependency': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}}, rule='type')
+    data_is_dict = isinstance(data, dict)
+    if data_is_dict:
+        data_keys = set(data.keys())
+        if "build-system" in data_keys:
+            data_keys.remove("build-system")
+            data__buildsystem = data["build-system"]
+            if not isinstance(data__buildsystem, (dict)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".build-system must be object", value=data__buildsystem, name="" + (name_prefix or "data") + ".build-system", definition={'type': 'object', 'description': 'Table used to store build-related data', 'additionalProperties': False, 'properties': {'requires': {'type': 'array', '$$description': ['List of dependencies in the :pep:`508` format required to execute the build', 'system. Please notice that the resulting dependency graph', '**MUST NOT contain cycles**'], 'items': {'type': 'string'}}, 'build-backend': {'type': 'string', 'description': 'Python object that will be used to perform the build according to :pep:`517`', 'format': 'pep517-backend-reference'}, 'backend-path': {'type': 'array', '$$description': ['List of directories to be prepended to ``sys.path`` when loading the', 'back-end, and running its hooks'], 'items': {'type': 'string', '$comment': 'Should be a path (TODO: enforce it with format?)'}}}, 'required': ['requires']}, rule='type')
+            data__buildsystem_is_dict = isinstance(data__buildsystem, dict)
+            if data__buildsystem_is_dict:
+                data__buildsystem__missing_keys = set(['requires']) - data__buildsystem.keys()
+                if data__buildsystem__missing_keys:
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".build-system must contain " + (str(sorted(data__buildsystem__missing_keys)) + " properties"), value=data__buildsystem, name="" + (name_prefix or "data") + ".build-system", definition={'type': 'object', 'description': 'Table used to store build-related data', 'additionalProperties': False, 'properties': {'requires': {'type': 'array', '$$description': ['List of dependencies in the :pep:`508` format required to execute the build', 'system. Please notice that the resulting dependency graph', '**MUST NOT contain cycles**'], 'items': {'type': 'string'}}, 'build-backend': {'type': 'string', 'description': 'Python object that will be used to perform the build according to :pep:`517`', 'format': 'pep517-backend-reference'}, 'backend-path': {'type': 'array', '$$description': ['List of directories to be prepended to ``sys.path`` when loading the', 'back-end, and running its hooks'], 'items': {'type': 'string', '$comment': 'Should be a path (TODO: enforce it with format?)'}}}, 'required': ['requires']}, rule='required')
+                data__buildsystem_keys = set(data__buildsystem.keys())
+                if "requires" in data__buildsystem_keys:
+                    data__buildsystem_keys.remove("requires")
+                    data__buildsystem__requires = data__buildsystem["requires"]
+                    if not isinstance(data__buildsystem__requires, (list, tuple)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".build-system.requires must be array", value=data__buildsystem__requires, name="" + (name_prefix or "data") + ".build-system.requires", definition={'type': 'array', '$$description': ['List of dependencies in the :pep:`508` format required to execute the build', 'system. Please notice that the resulting dependency graph', '**MUST NOT contain cycles**'], 'items': {'type': 'string'}}, rule='type')
+                    data__buildsystem__requires_is_list = isinstance(data__buildsystem__requires, (list, tuple))
+                    if data__buildsystem__requires_is_list:
+                        data__buildsystem__requires_len = len(data__buildsystem__requires)
+                        for data__buildsystem__requires_x, data__buildsystem__requires_item in enumerate(data__buildsystem__requires):
+                            if not isinstance(data__buildsystem__requires_item, (str)):
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".build-system.requires[{data__buildsystem__requires_x}]".format(**locals()) + " must be string", value=data__buildsystem__requires_item, name="" + (name_prefix or "data") + ".build-system.requires[{data__buildsystem__requires_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+                if "build-backend" in data__buildsystem_keys:
+                    data__buildsystem_keys.remove("build-backend")
+                    data__buildsystem__buildbackend = data__buildsystem["build-backend"]
+                    if not isinstance(data__buildsystem__buildbackend, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".build-system.build-backend must be string", value=data__buildsystem__buildbackend, name="" + (name_prefix or "data") + ".build-system.build-backend", definition={'type': 'string', 'description': 'Python object that will be used to perform the build according to :pep:`517`', 'format': 'pep517-backend-reference'}, rule='type')
+                    if isinstance(data__buildsystem__buildbackend, str):
+                        if not custom_formats["pep517-backend-reference"](data__buildsystem__buildbackend):
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".build-system.build-backend must be pep517-backend-reference", value=data__buildsystem__buildbackend, name="" + (name_prefix or "data") + ".build-system.build-backend", definition={'type': 'string', 'description': 'Python object that will be used to perform the build according to :pep:`517`', 'format': 'pep517-backend-reference'}, rule='format')
+                if "backend-path" in data__buildsystem_keys:
+                    data__buildsystem_keys.remove("backend-path")
+                    data__buildsystem__backendpath = data__buildsystem["backend-path"]
+                    if not isinstance(data__buildsystem__backendpath, (list, tuple)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".build-system.backend-path must be array", value=data__buildsystem__backendpath, name="" + (name_prefix or "data") + ".build-system.backend-path", definition={'type': 'array', '$$description': ['List of directories to be prepended to ``sys.path`` when loading the', 'back-end, and running its hooks'], 'items': {'type': 'string', '$comment': 'Should be a path (TODO: enforce it with format?)'}}, rule='type')
+                    data__buildsystem__backendpath_is_list = isinstance(data__buildsystem__backendpath, (list, tuple))
+                    if data__buildsystem__backendpath_is_list:
+                        data__buildsystem__backendpath_len = len(data__buildsystem__backendpath)
+                        for data__buildsystem__backendpath_x, data__buildsystem__backendpath_item in enumerate(data__buildsystem__backendpath):
+                            if not isinstance(data__buildsystem__backendpath_item, (str)):
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".build-system.backend-path[{data__buildsystem__backendpath_x}]".format(**locals()) + " must be string", value=data__buildsystem__backendpath_item, name="" + (name_prefix or "data") + ".build-system.backend-path[{data__buildsystem__backendpath_x}]".format(**locals()) + "", definition={'type': 'string', '$comment': 'Should be a path (TODO: enforce it with format?)'}, rule='type')
+                if data__buildsystem_keys:
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".build-system must not contain "+str(data__buildsystem_keys)+" properties", value=data__buildsystem, name="" + (name_prefix or "data") + ".build-system", definition={'type': 'object', 'description': 'Table used to store build-related data', 'additionalProperties': False, 'properties': {'requires': {'type': 'array', '$$description': ['List of dependencies in the :pep:`508` format required to execute the build', 'system. Please notice that the resulting dependency graph', '**MUST NOT contain cycles**'], 'items': {'type': 'string'}}, 'build-backend': {'type': 'string', 'description': 'Python object that will be used to perform the build according to :pep:`517`', 'format': 'pep517-backend-reference'}, 'backend-path': {'type': 'array', '$$description': ['List of directories to be prepended to ``sys.path`` when loading the', 'back-end, and running its hooks'], 'items': {'type': 'string', '$comment': 'Should be a path (TODO: enforce it with format?)'}}}, 'required': ['requires']}, rule='additionalProperties')
+        if "project" in data_keys:
+            data_keys.remove("project")
+            data__project = data["project"]
+            validate_https___packaging_python_org_en_latest_specifications_pyproject_toml(data__project, custom_formats, (name_prefix or "data") + ".project")
+        if "tool" in data_keys:
+            data_keys.remove("tool")
+            data__tool = data["tool"]
+            if not isinstance(data__tool, (dict)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".tool must be object", value=data__tool, name="" + (name_prefix or "data") + ".tool", definition={'type': 'object', 'properties': {'distutils': {'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://setuptools.pypa.io/en/latest/deprecated/distutils/configfile.html', 'title': '``tool.distutils`` table', '$$description': ['**EXPERIMENTAL** (NOT OFFICIALLY SUPPORTED): Use ``tool.distutils``', 'subtables to configure arguments for ``distutils`` commands.', 'Originally, ``distutils`` allowed developers to configure arguments for', '``setup.py`` commands via `distutils configuration files', '`_.', 'See also `the old Python docs _`.'], 'type': 'object', 'properties': {'global': {'type': 'object', 'description': 'Global options applied to all ``distutils`` commands'}}, 'patternProperties': {'.+': {'type': 'object'}}, '$comment': 'TODO: Is there a practical way of making this schema more specific?'}, 'setuptools': {'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://setuptools.pypa.io/en/latest/userguide/pyproject_config.html', 'title': '``tool.setuptools`` table', '$$description': ['``setuptools``-specific configurations that can be set by users that require', 'customization.', 'These configurations are completely optional and probably can be skipped when', 'creating simple packages. They are equivalent to some of the `Keywords', '`_', 'used by the ``setup.py`` file, and can be set via the ``tool.setuptools`` table.', 'It considers only ``setuptools`` `parameters', '`_', 'that are not covered by :pep:`621`; and intentionally excludes ``dependency_links``', 'and ``setup_requires`` (incompatible with modern workflows/standards).'], 'type': 'object', 'additionalProperties': False, 'properties': {'platforms': {'type': 'array', 'items': {'type': 'string'}}, 'provides': {'$$description': ['Package and virtual package names contained within this package', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'obsoletes': {'$$description': ['Packages which this package renders obsolete', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'zip-safe': {'$$description': ['Whether the project can be safely installed and run from a zip file.', '**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and', '``setup.py install`` in the context of ``eggs`` (**DEPRECATED**).'], 'type': 'boolean'}, 'script-files': {'$$description': ['Legacy way of defining scripts (entry-points are preferred).', 'Equivalent to the ``script`` keyword in ``setup.py``', '(it was renamed to avoid confusion with entry-point based ``project.scripts``', 'defined in :pep:`621`).', '**DISCOURAGED**: generic script wrappers are tricky and may not work properly.', 'Whenever possible, please use ``project.scripts`` instead.'], 'type': 'array', 'items': {'type': 'string'}, '$comment': 'TODO: is this field deprecated/should be removed?'}, 'eager-resources': {'$$description': ['Resources that should be extracted together, if any of them is needed,', 'or if any C extensions included in the project are imported.', '**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and', '``setup.py install`` in the context of ``eggs`` (**DEPRECATED**).'], 'type': 'array', 'items': {'type': 'string'}}, 'packages': {'$$description': ['Packages that should be included in the distribution.', 'It can be given either as a list of package identifiers', 'or as a ``dict``-like structure with a single key ``find``', 'which corresponds to a dynamic call to', '``setuptools.config.expand.find_packages`` function.', 'The ``find`` key is associated with a nested ``dict``-like structure that can', 'contain ``where``, ``include``, ``exclude`` and ``namespaces`` keys,', 'mimicking the keyword arguments of the associated function.'], 'oneOf': [{'title': 'Array of Python package identifiers', 'type': 'array', 'items': {'$ref': '#/definitions/package-name'}}, {'$ref': '#/definitions/find-directive'}]}, 'package-dir': {'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'const': ''}, {'$ref': '#/definitions/package-name'}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, 'package-data': {'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'type': 'string', 'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'include-package-data': {'$$description': ['Automatically include any data files inside the package directories', 'that are specified by ``MANIFEST.in``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'boolean'}, 'exclude-package-data': {'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'type': 'string', 'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'namespace-packages': {'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name-relaxed'}, '$comment': 'https://setuptools.pypa.io/en/latest/userguide/package_discovery.html', 'description': '**DEPRECATED**: use implicit namespaces instead (:pep:`420`).'}, 'py-modules': {'description': 'Modules that setuptools will manipulate', 'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name-relaxed'}, '$comment': 'TODO: clarify the relationship with ``packages``'}, 'ext-modules': {'description': 'Extension modules to be compiled by setuptools', 'type': 'array', 'items': {'$ref': '#/definitions/ext-module'}}, 'data-files': {'$$description': ['``dict``-like structure where each key represents a directory and', 'the value is a list of glob patterns that should be installed in them.', '**DISCOURAGED**: please notice this might not work as expected with wheels.', 'Whenever possible, consider using data files inside the package directories', '(or create a new namespace package that only contains data files).', 'See `data files support', '`_.'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'cmdclass': {'$$description': ['Mapping of distutils-style command names to ``setuptools.Command`` subclasses', 'which in turn should be represented by strings with a qualified class name', '(i.e., "dotted" form with module), e.g.::\n\n', '    cmdclass = {mycmd = "pkg.subpkg.module.CommandClass"}\n\n', 'The command class should be a directly defined at the top-level of the', 'containing module (no class nesting).'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'string', 'format': 'python-qualified-identifier'}}}, 'license-files': {'type': 'array', 'items': {'type': 'string'}, '$$description': ['**PROVISIONAL**: list of glob patterns for all license files being distributed.', '(likely to become standard with :pep:`639`).', "By default: ``['LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*']``"], '$comment': 'TODO: revise if PEP 639 is accepted. Probably ``project.license-files``?'}, 'dynamic': {'type': 'object', 'description': 'Instructions for loading :pep:`621`-related metadata dynamically', 'additionalProperties': False, 'properties': {'version': {'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.', 'Also ensure to set ``project.dynamic`` accordingly.'], 'oneOf': [{'$ref': '#/definitions/attr-directive'}, {'$ref': '#/definitions/file-directive'}]}, 'classifiers': {'$ref': '#/definitions/file-directive'}, 'description': {'$ref': '#/definitions/file-directive'}, 'entry-points': {'$ref': '#/definitions/file-directive'}, 'dependencies': {'$ref': '#/definitions/file-directive-for-dependencies'}, 'optional-dependencies': {'type': 'object', 'propertyNames': {'type': 'string', 'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'$ref': '#/definitions/file-directive-for-dependencies'}}}, 'readme': {'type': 'object', 'anyOf': [{'$ref': '#/definitions/file-directive'}, {'type': 'object', 'properties': {'content-type': {'type': 'string'}, 'file': {'$ref': '#/definitions/file-directive/properties/file'}}, 'additionalProperties': False}], 'required': ['file']}}}}, 'definitions': {'package-name': {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}, 'ext-module': {'$id': '#/definitions/ext-module', 'title': 'Extension module', 'description': 'Parameters to construct a :class:`setuptools.Extension` object', 'type': 'object', 'required': ['name', 'sources'], 'additionalProperties': False, 'properties': {'name': {'type': 'string', 'format': 'python-module-name-relaxed'}, 'sources': {'type': 'array', 'items': {'type': 'string'}}, 'include-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'define-macros': {'type': 'array', 'items': {'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}}, 'undef-macros': {'type': 'array', 'items': {'type': 'string'}}, 'library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'libraries': {'type': 'array', 'items': {'type': 'string'}}, 'runtime-library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'extra-objects': {'type': 'array', 'items': {'type': 'string'}}, 'extra-compile-args': {'type': 'array', 'items': {'type': 'string'}}, 'extra-link-args': {'type': 'array', 'items': {'type': 'string'}}, 'export-symbols': {'type': 'array', 'items': {'type': 'string'}}, 'swig-opts': {'type': 'array', 'items': {'type': 'string'}}, 'depends': {'type': 'array', 'items': {'type': 'string'}}, 'language': {'type': 'string'}, 'optional': {'type': 'boolean'}, 'py-limited-api': {'type': 'boolean'}}}, 'file-directive': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'file-directive-for-dependencies': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}, 'attr-directive': {'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, 'find-directive': {'$id': '#/definitions/find-directive', 'title': "'find:' directive", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}}}}}, rule='type')
+            data__tool_is_dict = isinstance(data__tool, dict)
+            if data__tool_is_dict:
+                data__tool_keys = set(data__tool.keys())
+                if "distutils" in data__tool_keys:
+                    data__tool_keys.remove("distutils")
+                    data__tool__distutils = data__tool["distutils"]
+                    validate_https___setuptools_pypa_io_en_latest_deprecated_distutils_configfile_html(data__tool__distutils, custom_formats, (name_prefix or "data") + ".tool.distutils")
+                if "setuptools" in data__tool_keys:
+                    data__tool_keys.remove("setuptools")
+                    data__tool__setuptools = data__tool["setuptools"]
+                    validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html(data__tool__setuptools, custom_formats, (name_prefix or "data") + ".tool.setuptools")
+        if "dependency-groups" in data_keys:
+            data_keys.remove("dependency-groups")
+            data__dependencygroups = data["dependency-groups"]
+            if not isinstance(data__dependencygroups, (dict)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".dependency-groups must be object", value=data__dependencygroups, name="" + (name_prefix or "data") + ".dependency-groups", definition={'type': 'object', 'description': 'Dependency groups following PEP 735', 'additionalProperties': False, 'patternProperties': {'^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$': {'type': 'array', 'items': {'oneOf': [{'type': 'string', 'description': 'Python package specifiers following PEP 508', 'format': 'pep508'}, {'type': 'object', 'additionalProperties': False, 'properties': {'include-group': {'description': 'Another dependency group to include in this one', 'type': 'string', 'pattern': '^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$'}}}]}}}}, rule='type')
+            data__dependencygroups_is_dict = isinstance(data__dependencygroups, dict)
+            if data__dependencygroups_is_dict:
+                data__dependencygroups_keys = set(data__dependencygroups.keys())
+                for data__dependencygroups_key, data__dependencygroups_val in data__dependencygroups.items():
+                    if REGEX_PATTERNS['^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$'].search(data__dependencygroups_key):
+                        if data__dependencygroups_key in data__dependencygroups_keys:
+                            data__dependencygroups_keys.remove(data__dependencygroups_key)
+                        if not isinstance(data__dependencygroups_val, (list, tuple)):
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}".format(**locals()) + " must be array", value=data__dependencygroups_val, name="" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}".format(**locals()) + "", definition={'type': 'array', 'items': {'oneOf': [{'type': 'string', 'description': 'Python package specifiers following PEP 508', 'format': 'pep508'}, {'type': 'object', 'additionalProperties': False, 'properties': {'include-group': {'description': 'Another dependency group to include in this one', 'type': 'string', 'pattern': '^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$'}}}]}}, rule='type')
+                        data__dependencygroups_val_is_list = isinstance(data__dependencygroups_val, (list, tuple))
+                        if data__dependencygroups_val_is_list:
+                            data__dependencygroups_val_len = len(data__dependencygroups_val)
+                            for data__dependencygroups_val_x, data__dependencygroups_val_item in enumerate(data__dependencygroups_val):
+                                data__dependencygroups_val_item_one_of_count1 = 0
+                                if data__dependencygroups_val_item_one_of_count1 < 2:
+                                    try:
+                                        if not isinstance(data__dependencygroups_val_item, (str)):
+                                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}]".format(**locals()) + " must be string", value=data__dependencygroups_val_item, name="" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}]".format(**locals()) + "", definition={'type': 'string', 'description': 'Python package specifiers following PEP 508', 'format': 'pep508'}, rule='type')
+                                        if isinstance(data__dependencygroups_val_item, str):
+                                            if not custom_formats["pep508"](data__dependencygroups_val_item):
+                                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}]".format(**locals()) + " must be pep508", value=data__dependencygroups_val_item, name="" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}]".format(**locals()) + "", definition={'type': 'string', 'description': 'Python package specifiers following PEP 508', 'format': 'pep508'}, rule='format')
+                                        data__dependencygroups_val_item_one_of_count1 += 1
+                                    except JsonSchemaValueException: pass
+                                if data__dependencygroups_val_item_one_of_count1 < 2:
+                                    try:
+                                        if not isinstance(data__dependencygroups_val_item, (dict)):
+                                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}]".format(**locals()) + " must be object", value=data__dependencygroups_val_item, name="" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}]".format(**locals()) + "", definition={'type': 'object', 'additionalProperties': False, 'properties': {'include-group': {'description': 'Another dependency group to include in this one', 'type': 'string', 'pattern': '^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$'}}}, rule='type')
+                                        data__dependencygroups_val_item_is_dict = isinstance(data__dependencygroups_val_item, dict)
+                                        if data__dependencygroups_val_item_is_dict:
+                                            data__dependencygroups_val_item_keys = set(data__dependencygroups_val_item.keys())
+                                            if "include-group" in data__dependencygroups_val_item_keys:
+                                                data__dependencygroups_val_item_keys.remove("include-group")
+                                                data__dependencygroups_val_item__includegroup = data__dependencygroups_val_item["include-group"]
+                                                if not isinstance(data__dependencygroups_val_item__includegroup, (str)):
+                                                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}].include-group".format(**locals()) + " must be string", value=data__dependencygroups_val_item__includegroup, name="" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}].include-group".format(**locals()) + "", definition={'description': 'Another dependency group to include in this one', 'type': 'string', 'pattern': '^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$'}, rule='type')
+                                                if isinstance(data__dependencygroups_val_item__includegroup, str):
+                                                    if not REGEX_PATTERNS['^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$'].search(data__dependencygroups_val_item__includegroup):
+                                                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}].include-group".format(**locals()) + " must match pattern ^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$", value=data__dependencygroups_val_item__includegroup, name="" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}].include-group".format(**locals()) + "", definition={'description': 'Another dependency group to include in this one', 'type': 'string', 'pattern': '^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$'}, rule='pattern')
+                                            if data__dependencygroups_val_item_keys:
+                                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}]".format(**locals()) + " must not contain "+str(data__dependencygroups_val_item_keys)+" properties", value=data__dependencygroups_val_item, name="" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}]".format(**locals()) + "", definition={'type': 'object', 'additionalProperties': False, 'properties': {'include-group': {'description': 'Another dependency group to include in this one', 'type': 'string', 'pattern': '^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$'}}}, rule='additionalProperties')
+                                        data__dependencygroups_val_item_one_of_count1 += 1
+                                    except JsonSchemaValueException: pass
+                                if data__dependencygroups_val_item_one_of_count1 != 1:
+                                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}]".format(**locals()) + " must be valid exactly by one definition" + (" (" + str(data__dependencygroups_val_item_one_of_count1) + " matches found)"), value=data__dependencygroups_val_item, name="" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}]".format(**locals()) + "", definition={'oneOf': [{'type': 'string', 'description': 'Python package specifiers following PEP 508', 'format': 'pep508'}, {'type': 'object', 'additionalProperties': False, 'properties': {'include-group': {'description': 'Another dependency group to include in this one', 'type': 'string', 'pattern': '^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$'}}}]}, rule='oneOf')
+                if data__dependencygroups_keys:
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".dependency-groups must not contain "+str(data__dependencygroups_keys)+" properties", value=data__dependencygroups, name="" + (name_prefix or "data") + ".dependency-groups", definition={'type': 'object', 'description': 'Dependency groups following PEP 735', 'additionalProperties': False, 'patternProperties': {'^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$': {'type': 'array', 'items': {'oneOf': [{'type': 'string', 'description': 'Python package specifiers following PEP 508', 'format': 'pep508'}, {'type': 'object', 'additionalProperties': False, 'properties': {'include-group': {'description': 'Another dependency group to include in this one', 'type': 'string', 'pattern': '^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$'}}}]}}}}, rule='additionalProperties')
+        if data_keys:
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must not contain "+str(data_keys)+" properties", value=data, name="" + (name_prefix or "data") + "", definition={'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://packaging.python.org/en/latest/specifications/declaring-build-dependencies/', 'title': 'Data structure for ``pyproject.toml`` files', '$$description': ['File format containing build-time configurations for the Python ecosystem. ', ':pep:`517` initially defined a build-system independent format for source trees', 'which was complemented by :pep:`518` to provide a way of specifying dependencies ', 'for building Python projects.', 'Please notice the ``project`` table (as initially defined in  :pep:`621`) is not included', 'in this schema and should be considered separately.'], 'type': 'object', 'additionalProperties': False, 'properties': {'build-system': {'type': 'object', 'description': 'Table used to store build-related data', 'additionalProperties': False, 'properties': {'requires': {'type': 'array', '$$description': ['List of dependencies in the :pep:`508` format required to execute the build', 'system. Please notice that the resulting dependency graph', '**MUST NOT contain cycles**'], 'items': {'type': 'string'}}, 'build-backend': {'type': 'string', 'description': 'Python object that will be used to perform the build according to :pep:`517`', 'format': 'pep517-backend-reference'}, 'backend-path': {'type': 'array', '$$description': ['List of directories to be prepended to ``sys.path`` when loading the', 'back-end, and running its hooks'], 'items': {'type': 'string', '$comment': 'Should be a path (TODO: enforce it with format?)'}}}, 'required': ['requires']}, 'project': {'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://packaging.python.org/en/latest/specifications/pyproject-toml/', 'title': 'Package metadata stored in the ``project`` table', '$$description': ['Data structure for the **project** table inside ``pyproject.toml``', '(as initially defined in :pep:`621`)'], 'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, 'version': {'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, 'description': {'type': 'string', '$$description': ['The `summary description of the project', '`_']}, 'readme': {'$$description': ['`Full/detailed description of the project in the form of a README', '`_', "with meaning similar to the one defined in `core metadata's Description", '`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, 'requires-python': {'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '`_.']}, 'license': {'description': '`Project license `_.', 'oneOf': [{'type': 'string', 'description': 'An SPDX license identifier', 'format': 'SPDX'}, {'type': 'object', 'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'type': 'object', 'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}]}, 'license-files': {'description': 'Paths or globs to paths of license files', 'type': 'array', 'items': {'type': 'string'}}, 'authors': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': ["The people or organizations considered to be the 'authors' of the project.", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, 'maintainers': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': ["The people or organizations considered to be the 'maintainers' of the project.", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, 'keywords': {'type': 'array', 'items': {'type': 'string'}, 'description': 'List of keywords to assist searching for the distribution in a larger catalog.'}, 'classifiers': {'type': 'array', 'items': {'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier `_.'}, '$$description': ['`Trove classifiers `_', 'which apply to the project.']}, 'urls': {'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, 'scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create command-line wrappers for the given', '`entry points `_.']}, 'gui-scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create GUI wrappers for the given', '`entry points `_.', 'The difference between ``scripts`` and ``gui-scripts`` is only relevant in', 'Windows.']}, 'entry-points': {'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$ref': '#/definitions/entry-point-group'}}}, 'dependencies': {'type': 'array', 'description': 'Project (mandatory) dependencies.', 'items': {'$ref': '#/definitions/dependency'}}, 'optional-dependencies': {'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$ref': '#/definitions/dependency'}}}}, 'dynamic': {'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'license-files', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']}}}, 'required': ['name'], 'additionalProperties': False, 'allOf': [{'if': {'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as "Required", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, 'then': {'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}}, {'if': {'required': ['license-files']}, 'then': {'properties': {'license': {'type': 'string'}}}}], 'definitions': {'author': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, 'entry-point-group': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'dependency': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}, 'tool': {'type': 'object', 'properties': {'distutils': {'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://setuptools.pypa.io/en/latest/deprecated/distutils/configfile.html', 'title': '``tool.distutils`` table', '$$description': ['**EXPERIMENTAL** (NOT OFFICIALLY SUPPORTED): Use ``tool.distutils``', 'subtables to configure arguments for ``distutils`` commands.', 'Originally, ``distutils`` allowed developers to configure arguments for', '``setup.py`` commands via `distutils configuration files', '`_.', 'See also `the old Python docs _`.'], 'type': 'object', 'properties': {'global': {'type': 'object', 'description': 'Global options applied to all ``distutils`` commands'}}, 'patternProperties': {'.+': {'type': 'object'}}, '$comment': 'TODO: Is there a practical way of making this schema more specific?'}, 'setuptools': {'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://setuptools.pypa.io/en/latest/userguide/pyproject_config.html', 'title': '``tool.setuptools`` table', '$$description': ['``setuptools``-specific configurations that can be set by users that require', 'customization.', 'These configurations are completely optional and probably can be skipped when', 'creating simple packages. They are equivalent to some of the `Keywords', '`_', 'used by the ``setup.py`` file, and can be set via the ``tool.setuptools`` table.', 'It considers only ``setuptools`` `parameters', '`_', 'that are not covered by :pep:`621`; and intentionally excludes ``dependency_links``', 'and ``setup_requires`` (incompatible with modern workflows/standards).'], 'type': 'object', 'additionalProperties': False, 'properties': {'platforms': {'type': 'array', 'items': {'type': 'string'}}, 'provides': {'$$description': ['Package and virtual package names contained within this package', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'obsoletes': {'$$description': ['Packages which this package renders obsolete', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'zip-safe': {'$$description': ['Whether the project can be safely installed and run from a zip file.', '**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and', '``setup.py install`` in the context of ``eggs`` (**DEPRECATED**).'], 'type': 'boolean'}, 'script-files': {'$$description': ['Legacy way of defining scripts (entry-points are preferred).', 'Equivalent to the ``script`` keyword in ``setup.py``', '(it was renamed to avoid confusion with entry-point based ``project.scripts``', 'defined in :pep:`621`).', '**DISCOURAGED**: generic script wrappers are tricky and may not work properly.', 'Whenever possible, please use ``project.scripts`` instead.'], 'type': 'array', 'items': {'type': 'string'}, '$comment': 'TODO: is this field deprecated/should be removed?'}, 'eager-resources': {'$$description': ['Resources that should be extracted together, if any of them is needed,', 'or if any C extensions included in the project are imported.', '**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and', '``setup.py install`` in the context of ``eggs`` (**DEPRECATED**).'], 'type': 'array', 'items': {'type': 'string'}}, 'packages': {'$$description': ['Packages that should be included in the distribution.', 'It can be given either as a list of package identifiers', 'or as a ``dict``-like structure with a single key ``find``', 'which corresponds to a dynamic call to', '``setuptools.config.expand.find_packages`` function.', 'The ``find`` key is associated with a nested ``dict``-like structure that can', 'contain ``where``, ``include``, ``exclude`` and ``namespaces`` keys,', 'mimicking the keyword arguments of the associated function.'], 'oneOf': [{'title': 'Array of Python package identifiers', 'type': 'array', 'items': {'$ref': '#/definitions/package-name'}}, {'$ref': '#/definitions/find-directive'}]}, 'package-dir': {'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'const': ''}, {'$ref': '#/definitions/package-name'}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, 'package-data': {'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'type': 'string', 'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'include-package-data': {'$$description': ['Automatically include any data files inside the package directories', 'that are specified by ``MANIFEST.in``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'boolean'}, 'exclude-package-data': {'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'type': 'string', 'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'namespace-packages': {'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name-relaxed'}, '$comment': 'https://setuptools.pypa.io/en/latest/userguide/package_discovery.html', 'description': '**DEPRECATED**: use implicit namespaces instead (:pep:`420`).'}, 'py-modules': {'description': 'Modules that setuptools will manipulate', 'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name-relaxed'}, '$comment': 'TODO: clarify the relationship with ``packages``'}, 'ext-modules': {'description': 'Extension modules to be compiled by setuptools', 'type': 'array', 'items': {'$ref': '#/definitions/ext-module'}}, 'data-files': {'$$description': ['``dict``-like structure where each key represents a directory and', 'the value is a list of glob patterns that should be installed in them.', '**DISCOURAGED**: please notice this might not work as expected with wheels.', 'Whenever possible, consider using data files inside the package directories', '(or create a new namespace package that only contains data files).', 'See `data files support', '`_.'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'cmdclass': {'$$description': ['Mapping of distutils-style command names to ``setuptools.Command`` subclasses', 'which in turn should be represented by strings with a qualified class name', '(i.e., "dotted" form with module), e.g.::\n\n', '    cmdclass = {mycmd = "pkg.subpkg.module.CommandClass"}\n\n', 'The command class should be a directly defined at the top-level of the', 'containing module (no class nesting).'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'string', 'format': 'python-qualified-identifier'}}}, 'license-files': {'type': 'array', 'items': {'type': 'string'}, '$$description': ['**PROVISIONAL**: list of glob patterns for all license files being distributed.', '(likely to become standard with :pep:`639`).', "By default: ``['LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*']``"], '$comment': 'TODO: revise if PEP 639 is accepted. Probably ``project.license-files``?'}, 'dynamic': {'type': 'object', 'description': 'Instructions for loading :pep:`621`-related metadata dynamically', 'additionalProperties': False, 'properties': {'version': {'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.', 'Also ensure to set ``project.dynamic`` accordingly.'], 'oneOf': [{'$ref': '#/definitions/attr-directive'}, {'$ref': '#/definitions/file-directive'}]}, 'classifiers': {'$ref': '#/definitions/file-directive'}, 'description': {'$ref': '#/definitions/file-directive'}, 'entry-points': {'$ref': '#/definitions/file-directive'}, 'dependencies': {'$ref': '#/definitions/file-directive-for-dependencies'}, 'optional-dependencies': {'type': 'object', 'propertyNames': {'type': 'string', 'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'$ref': '#/definitions/file-directive-for-dependencies'}}}, 'readme': {'type': 'object', 'anyOf': [{'$ref': '#/definitions/file-directive'}, {'type': 'object', 'properties': {'content-type': {'type': 'string'}, 'file': {'$ref': '#/definitions/file-directive/properties/file'}}, 'additionalProperties': False}], 'required': ['file']}}}}, 'definitions': {'package-name': {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}, 'ext-module': {'$id': '#/definitions/ext-module', 'title': 'Extension module', 'description': 'Parameters to construct a :class:`setuptools.Extension` object', 'type': 'object', 'required': ['name', 'sources'], 'additionalProperties': False, 'properties': {'name': {'type': 'string', 'format': 'python-module-name-relaxed'}, 'sources': {'type': 'array', 'items': {'type': 'string'}}, 'include-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'define-macros': {'type': 'array', 'items': {'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}}, 'undef-macros': {'type': 'array', 'items': {'type': 'string'}}, 'library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'libraries': {'type': 'array', 'items': {'type': 'string'}}, 'runtime-library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'extra-objects': {'type': 'array', 'items': {'type': 'string'}}, 'extra-compile-args': {'type': 'array', 'items': {'type': 'string'}}, 'extra-link-args': {'type': 'array', 'items': {'type': 'string'}}, 'export-symbols': {'type': 'array', 'items': {'type': 'string'}}, 'swig-opts': {'type': 'array', 'items': {'type': 'string'}}, 'depends': {'type': 'array', 'items': {'type': 'string'}}, 'language': {'type': 'string'}, 'optional': {'type': 'boolean'}, 'py-limited-api': {'type': 'boolean'}}}, 'file-directive': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'file-directive-for-dependencies': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}, 'attr-directive': {'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, 'find-directive': {'$id': '#/definitions/find-directive', 'title': "'find:' directive", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}}}}}, 'dependency-groups': {'type': 'object', 'description': 'Dependency groups following PEP 735', 'additionalProperties': False, 'patternProperties': {'^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$': {'type': 'array', 'items': {'oneOf': [{'type': 'string', 'description': 'Python package specifiers following PEP 508', 'format': 'pep508'}, {'type': 'object', 'additionalProperties': False, 'properties': {'include-group': {'description': 'Another dependency group to include in this one', 'type': 'string', 'pattern': '^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$'}}}]}}}}}, 'project': {'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://packaging.python.org/en/latest/specifications/pyproject-toml/', 'title': 'Package metadata stored in the ``project`` table', '$$description': ['Data structure for the **project** table inside ``pyproject.toml``', '(as initially defined in :pep:`621`)'], 'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, 'version': {'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, 'description': {'type': 'string', '$$description': ['The `summary description of the project', '`_']}, 'readme': {'$$description': ['`Full/detailed description of the project in the form of a README', '`_', "with meaning similar to the one defined in `core metadata's Description", '`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, 'requires-python': {'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '`_.']}, 'license': {'description': '`Project license `_.', 'oneOf': [{'type': 'string', 'description': 'An SPDX license identifier', 'format': 'SPDX'}, {'type': 'object', 'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'type': 'object', 'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}]}, 'license-files': {'description': 'Paths or globs to paths of license files', 'type': 'array', 'items': {'type': 'string'}}, 'authors': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': ["The people or organizations considered to be the 'authors' of the project.", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, 'maintainers': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': ["The people or organizations considered to be the 'maintainers' of the project.", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, 'keywords': {'type': 'array', 'items': {'type': 'string'}, 'description': 'List of keywords to assist searching for the distribution in a larger catalog.'}, 'classifiers': {'type': 'array', 'items': {'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier `_.'}, '$$description': ['`Trove classifiers `_', 'which apply to the project.']}, 'urls': {'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, 'scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create command-line wrappers for the given', '`entry points `_.']}, 'gui-scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create GUI wrappers for the given', '`entry points `_.', 'The difference between ``scripts`` and ``gui-scripts`` is only relevant in', 'Windows.']}, 'entry-points': {'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$ref': '#/definitions/entry-point-group'}}}, 'dependencies': {'type': 'array', 'description': 'Project (mandatory) dependencies.', 'items': {'$ref': '#/definitions/dependency'}}, 'optional-dependencies': {'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$ref': '#/definitions/dependency'}}}}, 'dynamic': {'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'license-files', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']}}}, 'required': ['name'], 'additionalProperties': False, 'allOf': [{'if': {'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as "Required", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, 'then': {'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}}, {'if': {'required': ['license-files']}, 'then': {'properties': {'license': {'type': 'string'}}}}], 'definitions': {'author': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, 'entry-point-group': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'dependency': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}}, rule='additionalProperties')
+    return data
+
+def validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html(data, custom_formats={}, name_prefix=None):
+    if not isinstance(data, (dict)):
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be object", value=data, name="" + (name_prefix or "data") + "", definition={'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://setuptools.pypa.io/en/latest/userguide/pyproject_config.html', 'title': '``tool.setuptools`` table', '$$description': ['``setuptools``-specific configurations that can be set by users that require', 'customization.', 'These configurations are completely optional and probably can be skipped when', 'creating simple packages. They are equivalent to some of the `Keywords', '`_', 'used by the ``setup.py`` file, and can be set via the ``tool.setuptools`` table.', 'It considers only ``setuptools`` `parameters', '`_', 'that are not covered by :pep:`621`; and intentionally excludes ``dependency_links``', 'and ``setup_requires`` (incompatible with modern workflows/standards).'], 'type': 'object', 'additionalProperties': False, 'properties': {'platforms': {'type': 'array', 'items': {'type': 'string'}}, 'provides': {'$$description': ['Package and virtual package names contained within this package', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'obsoletes': {'$$description': ['Packages which this package renders obsolete', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'zip-safe': {'$$description': ['Whether the project can be safely installed and run from a zip file.', '**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and', '``setup.py install`` in the context of ``eggs`` (**DEPRECATED**).'], 'type': 'boolean'}, 'script-files': {'$$description': ['Legacy way of defining scripts (entry-points are preferred).', 'Equivalent to the ``script`` keyword in ``setup.py``', '(it was renamed to avoid confusion with entry-point based ``project.scripts``', 'defined in :pep:`621`).', '**DISCOURAGED**: generic script wrappers are tricky and may not work properly.', 'Whenever possible, please use ``project.scripts`` instead.'], 'type': 'array', 'items': {'type': 'string'}, '$comment': 'TODO: is this field deprecated/should be removed?'}, 'eager-resources': {'$$description': ['Resources that should be extracted together, if any of them is needed,', 'or if any C extensions included in the project are imported.', '**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and', '``setup.py install`` in the context of ``eggs`` (**DEPRECATED**).'], 'type': 'array', 'items': {'type': 'string'}}, 'packages': {'$$description': ['Packages that should be included in the distribution.', 'It can be given either as a list of package identifiers', 'or as a ``dict``-like structure with a single key ``find``', 'which corresponds to a dynamic call to', '``setuptools.config.expand.find_packages`` function.', 'The ``find`` key is associated with a nested ``dict``-like structure that can', 'contain ``where``, ``include``, ``exclude`` and ``namespaces`` keys,', 'mimicking the keyword arguments of the associated function.'], 'oneOf': [{'title': 'Array of Python package identifiers', 'type': 'array', 'items': {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}}, {'$id': '#/definitions/find-directive', 'title': "'find:' directive", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}]}, 'package-dir': {'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'const': ''}, {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, 'package-data': {'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'type': 'string', 'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'include-package-data': {'$$description': ['Automatically include any data files inside the package directories', 'that are specified by ``MANIFEST.in``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'boolean'}, 'exclude-package-data': {'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'type': 'string', 'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'namespace-packages': {'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name-relaxed'}, '$comment': 'https://setuptools.pypa.io/en/latest/userguide/package_discovery.html', 'description': '**DEPRECATED**: use implicit namespaces instead (:pep:`420`).'}, 'py-modules': {'description': 'Modules that setuptools will manipulate', 'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name-relaxed'}, '$comment': 'TODO: clarify the relationship with ``packages``'}, 'ext-modules': {'description': 'Extension modules to be compiled by setuptools', 'type': 'array', 'items': {'$id': '#/definitions/ext-module', 'title': 'Extension module', 'description': 'Parameters to construct a :class:`setuptools.Extension` object', 'type': 'object', 'required': ['name', 'sources'], 'additionalProperties': False, 'properties': {'name': {'type': 'string', 'format': 'python-module-name-relaxed'}, 'sources': {'type': 'array', 'items': {'type': 'string'}}, 'include-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'define-macros': {'type': 'array', 'items': {'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}}, 'undef-macros': {'type': 'array', 'items': {'type': 'string'}}, 'library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'libraries': {'type': 'array', 'items': {'type': 'string'}}, 'runtime-library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'extra-objects': {'type': 'array', 'items': {'type': 'string'}}, 'extra-compile-args': {'type': 'array', 'items': {'type': 'string'}}, 'extra-link-args': {'type': 'array', 'items': {'type': 'string'}}, 'export-symbols': {'type': 'array', 'items': {'type': 'string'}}, 'swig-opts': {'type': 'array', 'items': {'type': 'string'}}, 'depends': {'type': 'array', 'items': {'type': 'string'}}, 'language': {'type': 'string'}, 'optional': {'type': 'boolean'}, 'py-limited-api': {'type': 'boolean'}}}}, 'data-files': {'$$description': ['``dict``-like structure where each key represents a directory and', 'the value is a list of glob patterns that should be installed in them.', '**DISCOURAGED**: please notice this might not work as expected with wheels.', 'Whenever possible, consider using data files inside the package directories', '(or create a new namespace package that only contains data files).', 'See `data files support', '`_.'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'cmdclass': {'$$description': ['Mapping of distutils-style command names to ``setuptools.Command`` subclasses', 'which in turn should be represented by strings with a qualified class name', '(i.e., "dotted" form with module), e.g.::\n\n', '    cmdclass = {mycmd = "pkg.subpkg.module.CommandClass"}\n\n', 'The command class should be a directly defined at the top-level of the', 'containing module (no class nesting).'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'string', 'format': 'python-qualified-identifier'}}}, 'license-files': {'type': 'array', 'items': {'type': 'string'}, '$$description': ['**PROVISIONAL**: list of glob patterns for all license files being distributed.', '(likely to become standard with :pep:`639`).', "By default: ``['LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*']``"], '$comment': 'TODO: revise if PEP 639 is accepted. Probably ``project.license-files``?'}, 'dynamic': {'type': 'object', 'description': 'Instructions for loading :pep:`621`-related metadata dynamically', 'additionalProperties': False, 'properties': {'version': {'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.', 'Also ensure to set ``project.dynamic`` accordingly.'], 'oneOf': [{'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}]}, 'classifiers': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'description': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'entry-points': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'dependencies': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}, 'optional-dependencies': {'type': 'object', 'propertyNames': {'type': 'string', 'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}}}, 'readme': {'type': 'object', 'anyOf': [{'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, {'type': 'object', 'properties': {'content-type': {'type': 'string'}, 'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'additionalProperties': False}], 'required': ['file']}}}}, 'definitions': {'package-name': {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}, 'ext-module': {'$id': '#/definitions/ext-module', 'title': 'Extension module', 'description': 'Parameters to construct a :class:`setuptools.Extension` object', 'type': 'object', 'required': ['name', 'sources'], 'additionalProperties': False, 'properties': {'name': {'type': 'string', 'format': 'python-module-name-relaxed'}, 'sources': {'type': 'array', 'items': {'type': 'string'}}, 'include-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'define-macros': {'type': 'array', 'items': {'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}}, 'undef-macros': {'type': 'array', 'items': {'type': 'string'}}, 'library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'libraries': {'type': 'array', 'items': {'type': 'string'}}, 'runtime-library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'extra-objects': {'type': 'array', 'items': {'type': 'string'}}, 'extra-compile-args': {'type': 'array', 'items': {'type': 'string'}}, 'extra-link-args': {'type': 'array', 'items': {'type': 'string'}}, 'export-symbols': {'type': 'array', 'items': {'type': 'string'}}, 'swig-opts': {'type': 'array', 'items': {'type': 'string'}}, 'depends': {'type': 'array', 'items': {'type': 'string'}}, 'language': {'type': 'string'}, 'optional': {'type': 'boolean'}, 'py-limited-api': {'type': 'boolean'}}}, 'file-directive': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'file-directive-for-dependencies': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}]}, 'attr-directive': {'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, 'find-directive': {'$id': '#/definitions/find-directive', 'title': "'find:' directive", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}}}, rule='type')
+    data_is_dict = isinstance(data, dict)
+    if data_is_dict:
+        data_keys = set(data.keys())
+        if "platforms" in data_keys:
+            data_keys.remove("platforms")
+            data__platforms = data["platforms"]
+            if not isinstance(data__platforms, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".platforms must be array", value=data__platforms, name="" + (name_prefix or "data") + ".platforms", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__platforms_is_list = isinstance(data__platforms, (list, tuple))
+            if data__platforms_is_list:
+                data__platforms_len = len(data__platforms)
+                for data__platforms_x, data__platforms_item in enumerate(data__platforms):
+                    if not isinstance(data__platforms_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".platforms[{data__platforms_x}]".format(**locals()) + " must be string", value=data__platforms_item, name="" + (name_prefix or "data") + ".platforms[{data__platforms_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "provides" in data_keys:
+            data_keys.remove("provides")
+            data__provides = data["provides"]
+            if not isinstance(data__provides, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".provides must be array", value=data__provides, name="" + (name_prefix or "data") + ".provides", definition={'$$description': ['Package and virtual package names contained within this package', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, rule='type')
+            data__provides_is_list = isinstance(data__provides, (list, tuple))
+            if data__provides_is_list:
+                data__provides_len = len(data__provides)
+                for data__provides_x, data__provides_item in enumerate(data__provides):
+                    if not isinstance(data__provides_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".provides[{data__provides_x}]".format(**locals()) + " must be string", value=data__provides_item, name="" + (name_prefix or "data") + ".provides[{data__provides_x}]".format(**locals()) + "", definition={'type': 'string', 'format': 'pep508-identifier'}, rule='type')
+                    if isinstance(data__provides_item, str):
+                        if not custom_formats["pep508-identifier"](data__provides_item):
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".provides[{data__provides_x}]".format(**locals()) + " must be pep508-identifier", value=data__provides_item, name="" + (name_prefix or "data") + ".provides[{data__provides_x}]".format(**locals()) + "", definition={'type': 'string', 'format': 'pep508-identifier'}, rule='format')
+        if "obsoletes" in data_keys:
+            data_keys.remove("obsoletes")
+            data__obsoletes = data["obsoletes"]
+            if not isinstance(data__obsoletes, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".obsoletes must be array", value=data__obsoletes, name="" + (name_prefix or "data") + ".obsoletes", definition={'$$description': ['Packages which this package renders obsolete', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, rule='type')
+            data__obsoletes_is_list = isinstance(data__obsoletes, (list, tuple))
+            if data__obsoletes_is_list:
+                data__obsoletes_len = len(data__obsoletes)
+                for data__obsoletes_x, data__obsoletes_item in enumerate(data__obsoletes):
+                    if not isinstance(data__obsoletes_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".obsoletes[{data__obsoletes_x}]".format(**locals()) + " must be string", value=data__obsoletes_item, name="" + (name_prefix or "data") + ".obsoletes[{data__obsoletes_x}]".format(**locals()) + "", definition={'type': 'string', 'format': 'pep508-identifier'}, rule='type')
+                    if isinstance(data__obsoletes_item, str):
+                        if not custom_formats["pep508-identifier"](data__obsoletes_item):
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".obsoletes[{data__obsoletes_x}]".format(**locals()) + " must be pep508-identifier", value=data__obsoletes_item, name="" + (name_prefix or "data") + ".obsoletes[{data__obsoletes_x}]".format(**locals()) + "", definition={'type': 'string', 'format': 'pep508-identifier'}, rule='format')
+        if "zip-safe" in data_keys:
+            data_keys.remove("zip-safe")
+            data__zipsafe = data["zip-safe"]
+            if not isinstance(data__zipsafe, (bool)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".zip-safe must be boolean", value=data__zipsafe, name="" + (name_prefix or "data") + ".zip-safe", definition={'$$description': ['Whether the project can be safely installed and run from a zip file.', '**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and', '``setup.py install`` in the context of ``eggs`` (**DEPRECATED**).'], 'type': 'boolean'}, rule='type')
+        if "script-files" in data_keys:
+            data_keys.remove("script-files")
+            data__scriptfiles = data["script-files"]
+            if not isinstance(data__scriptfiles, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".script-files must be array", value=data__scriptfiles, name="" + (name_prefix or "data") + ".script-files", definition={'$$description': ['Legacy way of defining scripts (entry-points are preferred).', 'Equivalent to the ``script`` keyword in ``setup.py``', '(it was renamed to avoid confusion with entry-point based ``project.scripts``', 'defined in :pep:`621`).', '**DISCOURAGED**: generic script wrappers are tricky and may not work properly.', 'Whenever possible, please use ``project.scripts`` instead.'], 'type': 'array', 'items': {'type': 'string'}, '$comment': 'TODO: is this field deprecated/should be removed?'}, rule='type')
+            data__scriptfiles_is_list = isinstance(data__scriptfiles, (list, tuple))
+            if data__scriptfiles_is_list:
+                data__scriptfiles_len = len(data__scriptfiles)
+                for data__scriptfiles_x, data__scriptfiles_item in enumerate(data__scriptfiles):
+                    if not isinstance(data__scriptfiles_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".script-files[{data__scriptfiles_x}]".format(**locals()) + " must be string", value=data__scriptfiles_item, name="" + (name_prefix or "data") + ".script-files[{data__scriptfiles_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "eager-resources" in data_keys:
+            data_keys.remove("eager-resources")
+            data__eagerresources = data["eager-resources"]
+            if not isinstance(data__eagerresources, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".eager-resources must be array", value=data__eagerresources, name="" + (name_prefix or "data") + ".eager-resources", definition={'$$description': ['Resources that should be extracted together, if any of them is needed,', 'or if any C extensions included in the project are imported.', '**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and', '``setup.py install`` in the context of ``eggs`` (**DEPRECATED**).'], 'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__eagerresources_is_list = isinstance(data__eagerresources, (list, tuple))
+            if data__eagerresources_is_list:
+                data__eagerresources_len = len(data__eagerresources)
+                for data__eagerresources_x, data__eagerresources_item in enumerate(data__eagerresources):
+                    if not isinstance(data__eagerresources_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".eager-resources[{data__eagerresources_x}]".format(**locals()) + " must be string", value=data__eagerresources_item, name="" + (name_prefix or "data") + ".eager-resources[{data__eagerresources_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "packages" in data_keys:
+            data_keys.remove("packages")
+            data__packages = data["packages"]
+            data__packages_one_of_count2 = 0
+            if data__packages_one_of_count2 < 2:
+                try:
+                    if not isinstance(data__packages, (list, tuple)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".packages must be array", value=data__packages, name="" + (name_prefix or "data") + ".packages", definition={'title': 'Array of Python package identifiers', 'type': 'array', 'items': {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}}, rule='type')
+                    data__packages_is_list = isinstance(data__packages, (list, tuple))
+                    if data__packages_is_list:
+                        data__packages_len = len(data__packages)
+                        for data__packages_x, data__packages_item in enumerate(data__packages):
+                            validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_package_name(data__packages_item, custom_formats, (name_prefix or "data") + ".packages[{data__packages_x}]".format(**locals()))
+                    data__packages_one_of_count2 += 1
+                except JsonSchemaValueException: pass
+            if data__packages_one_of_count2 < 2:
+                try:
+                    validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_find_directive(data__packages, custom_formats, (name_prefix or "data") + ".packages")
+                    data__packages_one_of_count2 += 1
+                except JsonSchemaValueException: pass
+            if data__packages_one_of_count2 != 1:
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".packages must be valid exactly by one definition" + (" (" + str(data__packages_one_of_count2) + " matches found)"), value=data__packages, name="" + (name_prefix or "data") + ".packages", definition={'$$description': ['Packages that should be included in the distribution.', 'It can be given either as a list of package identifiers', 'or as a ``dict``-like structure with a single key ``find``', 'which corresponds to a dynamic call to', '``setuptools.config.expand.find_packages`` function.', 'The ``find`` key is associated with a nested ``dict``-like structure that can', 'contain ``where``, ``include``, ``exclude`` and ``namespaces`` keys,', 'mimicking the keyword arguments of the associated function.'], 'oneOf': [{'title': 'Array of Python package identifiers', 'type': 'array', 'items': {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}}, {'$id': '#/definitions/find-directive', 'title': "'find:' directive", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}]}, rule='oneOf')
+        if "package-dir" in data_keys:
+            data_keys.remove("package-dir")
+            data__packagedir = data["package-dir"]
+            if not isinstance(data__packagedir, (dict)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-dir must be object", value=data__packagedir, name="" + (name_prefix or "data") + ".package-dir", definition={'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'const': ''}, {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, rule='type')
+            data__packagedir_is_dict = isinstance(data__packagedir, dict)
+            if data__packagedir_is_dict:
+                data__packagedir_keys = set(data__packagedir.keys())
+                for data__packagedir_key, data__packagedir_val in data__packagedir.items():
+                    if REGEX_PATTERNS['^.*$'].search(data__packagedir_key):
+                        if data__packagedir_key in data__packagedir_keys:
+                            data__packagedir_keys.remove(data__packagedir_key)
+                        if not isinstance(data__packagedir_val, (str)):
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-dir.{data__packagedir_key}".format(**locals()) + " must be string", value=data__packagedir_val, name="" + (name_prefix or "data") + ".package-dir.{data__packagedir_key}".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+                if data__packagedir_keys:
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-dir must not contain "+str(data__packagedir_keys)+" properties", value=data__packagedir, name="" + (name_prefix or "data") + ".package-dir", definition={'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'const': ''}, {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, rule='additionalProperties')
+                data__packagedir_len = len(data__packagedir)
+                if data__packagedir_len != 0:
+                    data__packagedir_property_names = True
+                    for data__packagedir_key in data__packagedir:
+                        try:
+                            data__packagedir_key_any_of_count3 = 0
+                            if not data__packagedir_key_any_of_count3:
+                                try:
+                                    if data__packagedir_key != "":
+                                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-dir must be same as const definition: ", value=data__packagedir_key, name="" + (name_prefix or "data") + ".package-dir", definition={'const': ''}, rule='const')
+                                    data__packagedir_key_any_of_count3 += 1
+                                except JsonSchemaValueException: pass
+                            if not data__packagedir_key_any_of_count3:
+                                try:
+                                    validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_package_name(data__packagedir_key, custom_formats, (name_prefix or "data") + ".package-dir")
+                                    data__packagedir_key_any_of_count3 += 1
+                                except JsonSchemaValueException: pass
+                            if not data__packagedir_key_any_of_count3:
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-dir cannot be validated by any definition", value=data__packagedir_key, name="" + (name_prefix or "data") + ".package-dir", definition={'anyOf': [{'const': ''}, {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}]}, rule='anyOf')
+                        except JsonSchemaValueException:
+                            data__packagedir_property_names = False
+                    if not data__packagedir_property_names:
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-dir must be named by propertyName definition", value=data__packagedir, name="" + (name_prefix or "data") + ".package-dir", definition={'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'const': ''}, {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, rule='propertyNames')
+        if "package-data" in data_keys:
+            data_keys.remove("package-data")
+            data__packagedata = data["package-data"]
+            if not isinstance(data__packagedata, (dict)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-data must be object", value=data__packagedata, name="" + (name_prefix or "data") + ".package-data", definition={'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'type': 'string', 'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, rule='type')
+            data__packagedata_is_dict = isinstance(data__packagedata, dict)
+            if data__packagedata_is_dict:
+                data__packagedata_keys = set(data__packagedata.keys())
+                for data__packagedata_key, data__packagedata_val in data__packagedata.items():
+                    if REGEX_PATTERNS['^.*$'].search(data__packagedata_key):
+                        if data__packagedata_key in data__packagedata_keys:
+                            data__packagedata_keys.remove(data__packagedata_key)
+                        if not isinstance(data__packagedata_val, (list, tuple)):
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-data.{data__packagedata_key}".format(**locals()) + " must be array", value=data__packagedata_val, name="" + (name_prefix or "data") + ".package-data.{data__packagedata_key}".format(**locals()) + "", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+                        data__packagedata_val_is_list = isinstance(data__packagedata_val, (list, tuple))
+                        if data__packagedata_val_is_list:
+                            data__packagedata_val_len = len(data__packagedata_val)
+                            for data__packagedata_val_x, data__packagedata_val_item in enumerate(data__packagedata_val):
+                                if not isinstance(data__packagedata_val_item, (str)):
+                                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-data.{data__packagedata_key}[{data__packagedata_val_x}]".format(**locals()) + " must be string", value=data__packagedata_val_item, name="" + (name_prefix or "data") + ".package-data.{data__packagedata_key}[{data__packagedata_val_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+                if data__packagedata_keys:
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-data must not contain "+str(data__packagedata_keys)+" properties", value=data__packagedata, name="" + (name_prefix or "data") + ".package-data", definition={'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'type': 'string', 'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, rule='additionalProperties')
+                data__packagedata_len = len(data__packagedata)
+                if data__packagedata_len != 0:
+                    data__packagedata_property_names = True
+                    for data__packagedata_key in data__packagedata:
+                        try:
+                            data__packagedata_key_any_of_count4 = 0
+                            if not data__packagedata_key_any_of_count4:
+                                try:
+                                    if not isinstance(data__packagedata_key, (str)):
+                                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-data must be string", value=data__packagedata_key, name="" + (name_prefix or "data") + ".package-data", definition={'type': 'string', 'format': 'python-module-name'}, rule='type')
+                                    if isinstance(data__packagedata_key, str):
+                                        if not custom_formats["python-module-name"](data__packagedata_key):
+                                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-data must be python-module-name", value=data__packagedata_key, name="" + (name_prefix or "data") + ".package-data", definition={'type': 'string', 'format': 'python-module-name'}, rule='format')
+                                    data__packagedata_key_any_of_count4 += 1
+                                except JsonSchemaValueException: pass
+                            if not data__packagedata_key_any_of_count4:
+                                try:
+                                    if data__packagedata_key != "*":
+                                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-data must be same as const definition: *", value=data__packagedata_key, name="" + (name_prefix or "data") + ".package-data", definition={'const': '*'}, rule='const')
+                                    data__packagedata_key_any_of_count4 += 1
+                                except JsonSchemaValueException: pass
+                            if not data__packagedata_key_any_of_count4:
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-data cannot be validated by any definition", value=data__packagedata_key, name="" + (name_prefix or "data") + ".package-data", definition={'anyOf': [{'type': 'string', 'format': 'python-module-name'}, {'const': '*'}]}, rule='anyOf')
+                        except JsonSchemaValueException:
+                            data__packagedata_property_names = False
+                    if not data__packagedata_property_names:
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-data must be named by propertyName definition", value=data__packagedata, name="" + (name_prefix or "data") + ".package-data", definition={'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'type': 'string', 'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, rule='propertyNames')
+        if "include-package-data" in data_keys:
+            data_keys.remove("include-package-data")
+            data__includepackagedata = data["include-package-data"]
+            if not isinstance(data__includepackagedata, (bool)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".include-package-data must be boolean", value=data__includepackagedata, name="" + (name_prefix or "data") + ".include-package-data", definition={'$$description': ['Automatically include any data files inside the package directories', 'that are specified by ``MANIFEST.in``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'boolean'}, rule='type')
+        if "exclude-package-data" in data_keys:
+            data_keys.remove("exclude-package-data")
+            data__excludepackagedata = data["exclude-package-data"]
+            if not isinstance(data__excludepackagedata, (dict)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".exclude-package-data must be object", value=data__excludepackagedata, name="" + (name_prefix or "data") + ".exclude-package-data", definition={'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'type': 'string', 'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, rule='type')
+            data__excludepackagedata_is_dict = isinstance(data__excludepackagedata, dict)
+            if data__excludepackagedata_is_dict:
+                data__excludepackagedata_keys = set(data__excludepackagedata.keys())
+                for data__excludepackagedata_key, data__excludepackagedata_val in data__excludepackagedata.items():
+                    if REGEX_PATTERNS['^.*$'].search(data__excludepackagedata_key):
+                        if data__excludepackagedata_key in data__excludepackagedata_keys:
+                            data__excludepackagedata_keys.remove(data__excludepackagedata_key)
+                        if not isinstance(data__excludepackagedata_val, (list, tuple)):
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".exclude-package-data.{data__excludepackagedata_key}".format(**locals()) + " must be array", value=data__excludepackagedata_val, name="" + (name_prefix or "data") + ".exclude-package-data.{data__excludepackagedata_key}".format(**locals()) + "", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+                        data__excludepackagedata_val_is_list = isinstance(data__excludepackagedata_val, (list, tuple))
+                        if data__excludepackagedata_val_is_list:
+                            data__excludepackagedata_val_len = len(data__excludepackagedata_val)
+                            for data__excludepackagedata_val_x, data__excludepackagedata_val_item in enumerate(data__excludepackagedata_val):
+                                if not isinstance(data__excludepackagedata_val_item, (str)):
+                                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".exclude-package-data.{data__excludepackagedata_key}[{data__excludepackagedata_val_x}]".format(**locals()) + " must be string", value=data__excludepackagedata_val_item, name="" + (name_prefix or "data") + ".exclude-package-data.{data__excludepackagedata_key}[{data__excludepackagedata_val_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+                if data__excludepackagedata_keys:
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".exclude-package-data must not contain "+str(data__excludepackagedata_keys)+" properties", value=data__excludepackagedata, name="" + (name_prefix or "data") + ".exclude-package-data", definition={'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'type': 'string', 'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, rule='additionalProperties')
+                data__excludepackagedata_len = len(data__excludepackagedata)
+                if data__excludepackagedata_len != 0:
+                    data__excludepackagedata_property_names = True
+                    for data__excludepackagedata_key in data__excludepackagedata:
+                        try:
+                            data__excludepackagedata_key_any_of_count5 = 0
+                            if not data__excludepackagedata_key_any_of_count5:
+                                try:
+                                    if not isinstance(data__excludepackagedata_key, (str)):
+                                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".exclude-package-data must be string", value=data__excludepackagedata_key, name="" + (name_prefix or "data") + ".exclude-package-data", definition={'type': 'string', 'format': 'python-module-name'}, rule='type')
+                                    if isinstance(data__excludepackagedata_key, str):
+                                        if not custom_formats["python-module-name"](data__excludepackagedata_key):
+                                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".exclude-package-data must be python-module-name", value=data__excludepackagedata_key, name="" + (name_prefix or "data") + ".exclude-package-data", definition={'type': 'string', 'format': 'python-module-name'}, rule='format')
+                                    data__excludepackagedata_key_any_of_count5 += 1
+                                except JsonSchemaValueException: pass
+                            if not data__excludepackagedata_key_any_of_count5:
+                                try:
+                                    if data__excludepackagedata_key != "*":
+                                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".exclude-package-data must be same as const definition: *", value=data__excludepackagedata_key, name="" + (name_prefix or "data") + ".exclude-package-data", definition={'const': '*'}, rule='const')
+                                    data__excludepackagedata_key_any_of_count5 += 1
+                                except JsonSchemaValueException: pass
+                            if not data__excludepackagedata_key_any_of_count5:
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".exclude-package-data cannot be validated by any definition", value=data__excludepackagedata_key, name="" + (name_prefix or "data") + ".exclude-package-data", definition={'anyOf': [{'type': 'string', 'format': 'python-module-name'}, {'const': '*'}]}, rule='anyOf')
+                        except JsonSchemaValueException:
+                            data__excludepackagedata_property_names = False
+                    if not data__excludepackagedata_property_names:
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".exclude-package-data must be named by propertyName definition", value=data__excludepackagedata, name="" + (name_prefix or "data") + ".exclude-package-data", definition={'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'type': 'string', 'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, rule='propertyNames')
+        if "namespace-packages" in data_keys:
+            data_keys.remove("namespace-packages")
+            data__namespacepackages = data["namespace-packages"]
+            if not isinstance(data__namespacepackages, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".namespace-packages must be array", value=data__namespacepackages, name="" + (name_prefix or "data") + ".namespace-packages", definition={'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name-relaxed'}, '$comment': 'https://setuptools.pypa.io/en/latest/userguide/package_discovery.html', 'description': '**DEPRECATED**: use implicit namespaces instead (:pep:`420`).'}, rule='type')
+            data__namespacepackages_is_list = isinstance(data__namespacepackages, (list, tuple))
+            if data__namespacepackages_is_list:
+                data__namespacepackages_len = len(data__namespacepackages)
+                for data__namespacepackages_x, data__namespacepackages_item in enumerate(data__namespacepackages):
+                    if not isinstance(data__namespacepackages_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".namespace-packages[{data__namespacepackages_x}]".format(**locals()) + " must be string", value=data__namespacepackages_item, name="" + (name_prefix or "data") + ".namespace-packages[{data__namespacepackages_x}]".format(**locals()) + "", definition={'type': 'string', 'format': 'python-module-name-relaxed'}, rule='type')
+                    if isinstance(data__namespacepackages_item, str):
+                        if not custom_formats["python-module-name-relaxed"](data__namespacepackages_item):
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".namespace-packages[{data__namespacepackages_x}]".format(**locals()) + " must be python-module-name-relaxed", value=data__namespacepackages_item, name="" + (name_prefix or "data") + ".namespace-packages[{data__namespacepackages_x}]".format(**locals()) + "", definition={'type': 'string', 'format': 'python-module-name-relaxed'}, rule='format')
+        if "py-modules" in data_keys:
+            data_keys.remove("py-modules")
+            data__pymodules = data["py-modules"]
+            if not isinstance(data__pymodules, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".py-modules must be array", value=data__pymodules, name="" + (name_prefix or "data") + ".py-modules", definition={'description': 'Modules that setuptools will manipulate', 'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name-relaxed'}, '$comment': 'TODO: clarify the relationship with ``packages``'}, rule='type')
+            data__pymodules_is_list = isinstance(data__pymodules, (list, tuple))
+            if data__pymodules_is_list:
+                data__pymodules_len = len(data__pymodules)
+                for data__pymodules_x, data__pymodules_item in enumerate(data__pymodules):
+                    if not isinstance(data__pymodules_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".py-modules[{data__pymodules_x}]".format(**locals()) + " must be string", value=data__pymodules_item, name="" + (name_prefix or "data") + ".py-modules[{data__pymodules_x}]".format(**locals()) + "", definition={'type': 'string', 'format': 'python-module-name-relaxed'}, rule='type')
+                    if isinstance(data__pymodules_item, str):
+                        if not custom_formats["python-module-name-relaxed"](data__pymodules_item):
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".py-modules[{data__pymodules_x}]".format(**locals()) + " must be python-module-name-relaxed", value=data__pymodules_item, name="" + (name_prefix or "data") + ".py-modules[{data__pymodules_x}]".format(**locals()) + "", definition={'type': 'string', 'format': 'python-module-name-relaxed'}, rule='format')
+        if "ext-modules" in data_keys:
+            data_keys.remove("ext-modules")
+            data__extmodules = data["ext-modules"]
+            if not isinstance(data__extmodules, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".ext-modules must be array", value=data__extmodules, name="" + (name_prefix or "data") + ".ext-modules", definition={'description': 'Extension modules to be compiled by setuptools', 'type': 'array', 'items': {'$id': '#/definitions/ext-module', 'title': 'Extension module', 'description': 'Parameters to construct a :class:`setuptools.Extension` object', 'type': 'object', 'required': ['name', 'sources'], 'additionalProperties': False, 'properties': {'name': {'type': 'string', 'format': 'python-module-name-relaxed'}, 'sources': {'type': 'array', 'items': {'type': 'string'}}, 'include-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'define-macros': {'type': 'array', 'items': {'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}}, 'undef-macros': {'type': 'array', 'items': {'type': 'string'}}, 'library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'libraries': {'type': 'array', 'items': {'type': 'string'}}, 'runtime-library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'extra-objects': {'type': 'array', 'items': {'type': 'string'}}, 'extra-compile-args': {'type': 'array', 'items': {'type': 'string'}}, 'extra-link-args': {'type': 'array', 'items': {'type': 'string'}}, 'export-symbols': {'type': 'array', 'items': {'type': 'string'}}, 'swig-opts': {'type': 'array', 'items': {'type': 'string'}}, 'depends': {'type': 'array', 'items': {'type': 'string'}}, 'language': {'type': 'string'}, 'optional': {'type': 'boolean'}, 'py-limited-api': {'type': 'boolean'}}}}, rule='type')
+            data__extmodules_is_list = isinstance(data__extmodules, (list, tuple))
+            if data__extmodules_is_list:
+                data__extmodules_len = len(data__extmodules)
+                for data__extmodules_x, data__extmodules_item in enumerate(data__extmodules):
+                    validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_ext_module(data__extmodules_item, custom_formats, (name_prefix or "data") + ".ext-modules[{data__extmodules_x}]".format(**locals()))
+        if "data-files" in data_keys:
+            data_keys.remove("data-files")
+            data__datafiles = data["data-files"]
+            if not isinstance(data__datafiles, (dict)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".data-files must be object", value=data__datafiles, name="" + (name_prefix or "data") + ".data-files", definition={'$$description': ['``dict``-like structure where each key represents a directory and', 'the value is a list of glob patterns that should be installed in them.', '**DISCOURAGED**: please notice this might not work as expected with wheels.', 'Whenever possible, consider using data files inside the package directories', '(or create a new namespace package that only contains data files).', 'See `data files support', '`_.'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, rule='type')
+            data__datafiles_is_dict = isinstance(data__datafiles, dict)
+            if data__datafiles_is_dict:
+                data__datafiles_keys = set(data__datafiles.keys())
+                for data__datafiles_key, data__datafiles_val in data__datafiles.items():
+                    if REGEX_PATTERNS['^.*$'].search(data__datafiles_key):
+                        if data__datafiles_key in data__datafiles_keys:
+                            data__datafiles_keys.remove(data__datafiles_key)
+                        if not isinstance(data__datafiles_val, (list, tuple)):
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".data-files.{data__datafiles_key}".format(**locals()) + " must be array", value=data__datafiles_val, name="" + (name_prefix or "data") + ".data-files.{data__datafiles_key}".format(**locals()) + "", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+                        data__datafiles_val_is_list = isinstance(data__datafiles_val, (list, tuple))
+                        if data__datafiles_val_is_list:
+                            data__datafiles_val_len = len(data__datafiles_val)
+                            for data__datafiles_val_x, data__datafiles_val_item in enumerate(data__datafiles_val):
+                                if not isinstance(data__datafiles_val_item, (str)):
+                                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".data-files.{data__datafiles_key}[{data__datafiles_val_x}]".format(**locals()) + " must be string", value=data__datafiles_val_item, name="" + (name_prefix or "data") + ".data-files.{data__datafiles_key}[{data__datafiles_val_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "cmdclass" in data_keys:
+            data_keys.remove("cmdclass")
+            data__cmdclass = data["cmdclass"]
+            if not isinstance(data__cmdclass, (dict)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".cmdclass must be object", value=data__cmdclass, name="" + (name_prefix or "data") + ".cmdclass", definition={'$$description': ['Mapping of distutils-style command names to ``setuptools.Command`` subclasses', 'which in turn should be represented by strings with a qualified class name', '(i.e., "dotted" form with module), e.g.::\n\n', '    cmdclass = {mycmd = "pkg.subpkg.module.CommandClass"}\n\n', 'The command class should be a directly defined at the top-level of the', 'containing module (no class nesting).'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'string', 'format': 'python-qualified-identifier'}}}, rule='type')
+            data__cmdclass_is_dict = isinstance(data__cmdclass, dict)
+            if data__cmdclass_is_dict:
+                data__cmdclass_keys = set(data__cmdclass.keys())
+                for data__cmdclass_key, data__cmdclass_val in data__cmdclass.items():
+                    if REGEX_PATTERNS['^.*$'].search(data__cmdclass_key):
+                        if data__cmdclass_key in data__cmdclass_keys:
+                            data__cmdclass_keys.remove(data__cmdclass_key)
+                        if not isinstance(data__cmdclass_val, (str)):
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".cmdclass.{data__cmdclass_key}".format(**locals()) + " must be string", value=data__cmdclass_val, name="" + (name_prefix or "data") + ".cmdclass.{data__cmdclass_key}".format(**locals()) + "", definition={'type': 'string', 'format': 'python-qualified-identifier'}, rule='type')
+                        if isinstance(data__cmdclass_val, str):
+                            if not custom_formats["python-qualified-identifier"](data__cmdclass_val):
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".cmdclass.{data__cmdclass_key}".format(**locals()) + " must be python-qualified-identifier", value=data__cmdclass_val, name="" + (name_prefix or "data") + ".cmdclass.{data__cmdclass_key}".format(**locals()) + "", definition={'type': 'string', 'format': 'python-qualified-identifier'}, rule='format')
+        if "license-files" in data_keys:
+            data_keys.remove("license-files")
+            data__licensefiles = data["license-files"]
+            if not isinstance(data__licensefiles, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".license-files must be array", value=data__licensefiles, name="" + (name_prefix or "data") + ".license-files", definition={'type': 'array', 'items': {'type': 'string'}, '$$description': ['**PROVISIONAL**: list of glob patterns for all license files being distributed.', '(likely to become standard with :pep:`639`).', "By default: ``['LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*']``"], '$comment': 'TODO: revise if PEP 639 is accepted. Probably ``project.license-files``?'}, rule='type')
+            data__licensefiles_is_list = isinstance(data__licensefiles, (list, tuple))
+            if data__licensefiles_is_list:
+                data__licensefiles_len = len(data__licensefiles)
+                for data__licensefiles_x, data__licensefiles_item in enumerate(data__licensefiles):
+                    if not isinstance(data__licensefiles_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".license-files[{data__licensefiles_x}]".format(**locals()) + " must be string", value=data__licensefiles_item, name="" + (name_prefix or "data") + ".license-files[{data__licensefiles_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "dynamic" in data_keys:
+            data_keys.remove("dynamic")
+            data__dynamic = data["dynamic"]
+            if not isinstance(data__dynamic, (dict)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic must be object", value=data__dynamic, name="" + (name_prefix or "data") + ".dynamic", definition={'type': 'object', 'description': 'Instructions for loading :pep:`621`-related metadata dynamically', 'additionalProperties': False, 'properties': {'version': {'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.', 'Also ensure to set ``project.dynamic`` accordingly.'], 'oneOf': [{'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}]}, 'classifiers': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'description': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'entry-points': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'dependencies': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}, 'optional-dependencies': {'type': 'object', 'propertyNames': {'type': 'string', 'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}}}, 'readme': {'type': 'object', 'anyOf': [{'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, {'type': 'object', 'properties': {'content-type': {'type': 'string'}, 'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'additionalProperties': False}], 'required': ['file']}}}, rule='type')
+            data__dynamic_is_dict = isinstance(data__dynamic, dict)
+            if data__dynamic_is_dict:
+                data__dynamic_keys = set(data__dynamic.keys())
+                if "version" in data__dynamic_keys:
+                    data__dynamic_keys.remove("version")
+                    data__dynamic__version = data__dynamic["version"]
+                    data__dynamic__version_one_of_count6 = 0
+                    if data__dynamic__version_one_of_count6 < 2:
+                        try:
+                            validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_attr_directive(data__dynamic__version, custom_formats, (name_prefix or "data") + ".dynamic.version")
+                            data__dynamic__version_one_of_count6 += 1
+                        except JsonSchemaValueException: pass
+                    if data__dynamic__version_one_of_count6 < 2:
+                        try:
+                            validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_file_directive(data__dynamic__version, custom_formats, (name_prefix or "data") + ".dynamic.version")
+                            data__dynamic__version_one_of_count6 += 1
+                        except JsonSchemaValueException: pass
+                    if data__dynamic__version_one_of_count6 != 1:
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.version must be valid exactly by one definition" + (" (" + str(data__dynamic__version_one_of_count6) + " matches found)"), value=data__dynamic__version, name="" + (name_prefix or "data") + ".dynamic.version", definition={'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.', 'Also ensure to set ``project.dynamic`` accordingly.'], 'oneOf': [{'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}]}, rule='oneOf')
+                if "classifiers" in data__dynamic_keys:
+                    data__dynamic_keys.remove("classifiers")
+                    data__dynamic__classifiers = data__dynamic["classifiers"]
+                    validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_file_directive(data__dynamic__classifiers, custom_formats, (name_prefix or "data") + ".dynamic.classifiers")
+                if "description" in data__dynamic_keys:
+                    data__dynamic_keys.remove("description")
+                    data__dynamic__description = data__dynamic["description"]
+                    validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_file_directive(data__dynamic__description, custom_formats, (name_prefix or "data") + ".dynamic.description")
+                if "entry-points" in data__dynamic_keys:
+                    data__dynamic_keys.remove("entry-points")
+                    data__dynamic__entrypoints = data__dynamic["entry-points"]
+                    validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_file_directive(data__dynamic__entrypoints, custom_formats, (name_prefix or "data") + ".dynamic.entry-points")
+                if "dependencies" in data__dynamic_keys:
+                    data__dynamic_keys.remove("dependencies")
+                    data__dynamic__dependencies = data__dynamic["dependencies"]
+                    validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_file_directive_for_dependencies(data__dynamic__dependencies, custom_formats, (name_prefix or "data") + ".dynamic.dependencies")
+                if "optional-dependencies" in data__dynamic_keys:
+                    data__dynamic_keys.remove("optional-dependencies")
+                    data__dynamic__optionaldependencies = data__dynamic["optional-dependencies"]
+                    if not isinstance(data__dynamic__optionaldependencies, (dict)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.optional-dependencies must be object", value=data__dynamic__optionaldependencies, name="" + (name_prefix or "data") + ".dynamic.optional-dependencies", definition={'type': 'object', 'propertyNames': {'type': 'string', 'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}}}, rule='type')
+                    data__dynamic__optionaldependencies_is_dict = isinstance(data__dynamic__optionaldependencies, dict)
+                    if data__dynamic__optionaldependencies_is_dict:
+                        data__dynamic__optionaldependencies_keys = set(data__dynamic__optionaldependencies.keys())
+                        for data__dynamic__optionaldependencies_key, data__dynamic__optionaldependencies_val in data__dynamic__optionaldependencies.items():
+                            if REGEX_PATTERNS['.+'].search(data__dynamic__optionaldependencies_key):
+                                if data__dynamic__optionaldependencies_key in data__dynamic__optionaldependencies_keys:
+                                    data__dynamic__optionaldependencies_keys.remove(data__dynamic__optionaldependencies_key)
+                                validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_file_directive_for_dependencies(data__dynamic__optionaldependencies_val, custom_formats, (name_prefix or "data") + ".dynamic.optional-dependencies.{data__dynamic__optionaldependencies_key}".format(**locals()))
+                        if data__dynamic__optionaldependencies_keys:
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.optional-dependencies must not contain "+str(data__dynamic__optionaldependencies_keys)+" properties", value=data__dynamic__optionaldependencies, name="" + (name_prefix or "data") + ".dynamic.optional-dependencies", definition={'type': 'object', 'propertyNames': {'type': 'string', 'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}}}, rule='additionalProperties')
+                        data__dynamic__optionaldependencies_len = len(data__dynamic__optionaldependencies)
+                        if data__dynamic__optionaldependencies_len != 0:
+                            data__dynamic__optionaldependencies_property_names = True
+                            for data__dynamic__optionaldependencies_key in data__dynamic__optionaldependencies:
+                                try:
+                                    if not isinstance(data__dynamic__optionaldependencies_key, (str)):
+                                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.optional-dependencies must be string", value=data__dynamic__optionaldependencies_key, name="" + (name_prefix or "data") + ".dynamic.optional-dependencies", definition={'type': 'string', 'format': 'pep508-identifier'}, rule='type')
+                                    if isinstance(data__dynamic__optionaldependencies_key, str):
+                                        if not custom_formats["pep508-identifier"](data__dynamic__optionaldependencies_key):
+                                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.optional-dependencies must be pep508-identifier", value=data__dynamic__optionaldependencies_key, name="" + (name_prefix or "data") + ".dynamic.optional-dependencies", definition={'type': 'string', 'format': 'pep508-identifier'}, rule='format')
+                                except JsonSchemaValueException:
+                                    data__dynamic__optionaldependencies_property_names = False
+                            if not data__dynamic__optionaldependencies_property_names:
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.optional-dependencies must be named by propertyName definition", value=data__dynamic__optionaldependencies, name="" + (name_prefix or "data") + ".dynamic.optional-dependencies", definition={'type': 'object', 'propertyNames': {'type': 'string', 'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}}}, rule='propertyNames')
+                if "readme" in data__dynamic_keys:
+                    data__dynamic_keys.remove("readme")
+                    data__dynamic__readme = data__dynamic["readme"]
+                    if not isinstance(data__dynamic__readme, (dict)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.readme must be object", value=data__dynamic__readme, name="" + (name_prefix or "data") + ".dynamic.readme", definition={'type': 'object', 'anyOf': [{'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, {'type': 'object', 'properties': {'content-type': {'type': 'string'}, 'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'additionalProperties': False}], 'required': ['file']}, rule='type')
+                    data__dynamic__readme_any_of_count7 = 0
+                    if not data__dynamic__readme_any_of_count7:
+                        try:
+                            validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_file_directive(data__dynamic__readme, custom_formats, (name_prefix or "data") + ".dynamic.readme")
+                            data__dynamic__readme_any_of_count7 += 1
+                        except JsonSchemaValueException: pass
+                    if not data__dynamic__readme_any_of_count7:
+                        try:
+                            if not isinstance(data__dynamic__readme, (dict)):
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.readme must be object", value=data__dynamic__readme, name="" + (name_prefix or "data") + ".dynamic.readme", definition={'type': 'object', 'properties': {'content-type': {'type': 'string'}, 'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'additionalProperties': False}, rule='type')
+                            data__dynamic__readme_is_dict = isinstance(data__dynamic__readme, dict)
+                            if data__dynamic__readme_is_dict:
+                                data__dynamic__readme_keys = set(data__dynamic__readme.keys())
+                                if "content-type" in data__dynamic__readme_keys:
+                                    data__dynamic__readme_keys.remove("content-type")
+                                    data__dynamic__readme__contenttype = data__dynamic__readme["content-type"]
+                                    if not isinstance(data__dynamic__readme__contenttype, (str)):
+                                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.readme.content-type must be string", value=data__dynamic__readme__contenttype, name="" + (name_prefix or "data") + ".dynamic.readme.content-type", definition={'type': 'string'}, rule='type')
+                                if "file" in data__dynamic__readme_keys:
+                                    data__dynamic__readme_keys.remove("file")
+                                    data__dynamic__readme__file = data__dynamic__readme["file"]
+                                    validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_file_directive_properties_file(data__dynamic__readme__file, custom_formats, (name_prefix or "data") + ".dynamic.readme.file")
+                                if data__dynamic__readme_keys:
+                                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.readme must not contain "+str(data__dynamic__readme_keys)+" properties", value=data__dynamic__readme, name="" + (name_prefix or "data") + ".dynamic.readme", definition={'type': 'object', 'properties': {'content-type': {'type': 'string'}, 'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'additionalProperties': False}, rule='additionalProperties')
+                            data__dynamic__readme_any_of_count7 += 1
+                        except JsonSchemaValueException: pass
+                    if not data__dynamic__readme_any_of_count7:
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.readme cannot be validated by any definition", value=data__dynamic__readme, name="" + (name_prefix or "data") + ".dynamic.readme", definition={'type': 'object', 'anyOf': [{'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, {'type': 'object', 'properties': {'content-type': {'type': 'string'}, 'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'additionalProperties': False}], 'required': ['file']}, rule='anyOf')
+                    data__dynamic__readme_is_dict = isinstance(data__dynamic__readme, dict)
+                    if data__dynamic__readme_is_dict:
+                        data__dynamic__readme__missing_keys = set(['file']) - data__dynamic__readme.keys()
+                        if data__dynamic__readme__missing_keys:
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.readme must contain " + (str(sorted(data__dynamic__readme__missing_keys)) + " properties"), value=data__dynamic__readme, name="" + (name_prefix or "data") + ".dynamic.readme", definition={'type': 'object', 'anyOf': [{'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, {'type': 'object', 'properties': {'content-type': {'type': 'string'}, 'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'additionalProperties': False}], 'required': ['file']}, rule='required')
+                if data__dynamic_keys:
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic must not contain "+str(data__dynamic_keys)+" properties", value=data__dynamic, name="" + (name_prefix or "data") + ".dynamic", definition={'type': 'object', 'description': 'Instructions for loading :pep:`621`-related metadata dynamically', 'additionalProperties': False, 'properties': {'version': {'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.', 'Also ensure to set ``project.dynamic`` accordingly.'], 'oneOf': [{'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}]}, 'classifiers': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'description': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'entry-points': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'dependencies': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}, 'optional-dependencies': {'type': 'object', 'propertyNames': {'type': 'string', 'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}}}, 'readme': {'type': 'object', 'anyOf': [{'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, {'type': 'object', 'properties': {'content-type': {'type': 'string'}, 'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'additionalProperties': False}], 'required': ['file']}}}, rule='additionalProperties')
+        if data_keys:
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must not contain "+str(data_keys)+" properties", value=data, name="" + (name_prefix or "data") + "", definition={'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://setuptools.pypa.io/en/latest/userguide/pyproject_config.html', 'title': '``tool.setuptools`` table', '$$description': ['``setuptools``-specific configurations that can be set by users that require', 'customization.', 'These configurations are completely optional and probably can be skipped when', 'creating simple packages. They are equivalent to some of the `Keywords', '`_', 'used by the ``setup.py`` file, and can be set via the ``tool.setuptools`` table.', 'It considers only ``setuptools`` `parameters', '`_', 'that are not covered by :pep:`621`; and intentionally excludes ``dependency_links``', 'and ``setup_requires`` (incompatible with modern workflows/standards).'], 'type': 'object', 'additionalProperties': False, 'properties': {'platforms': {'type': 'array', 'items': {'type': 'string'}}, 'provides': {'$$description': ['Package and virtual package names contained within this package', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'obsoletes': {'$$description': ['Packages which this package renders obsolete', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'zip-safe': {'$$description': ['Whether the project can be safely installed and run from a zip file.', '**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and', '``setup.py install`` in the context of ``eggs`` (**DEPRECATED**).'], 'type': 'boolean'}, 'script-files': {'$$description': ['Legacy way of defining scripts (entry-points are preferred).', 'Equivalent to the ``script`` keyword in ``setup.py``', '(it was renamed to avoid confusion with entry-point based ``project.scripts``', 'defined in :pep:`621`).', '**DISCOURAGED**: generic script wrappers are tricky and may not work properly.', 'Whenever possible, please use ``project.scripts`` instead.'], 'type': 'array', 'items': {'type': 'string'}, '$comment': 'TODO: is this field deprecated/should be removed?'}, 'eager-resources': {'$$description': ['Resources that should be extracted together, if any of them is needed,', 'or if any C extensions included in the project are imported.', '**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and', '``setup.py install`` in the context of ``eggs`` (**DEPRECATED**).'], 'type': 'array', 'items': {'type': 'string'}}, 'packages': {'$$description': ['Packages that should be included in the distribution.', 'It can be given either as a list of package identifiers', 'or as a ``dict``-like structure with a single key ``find``', 'which corresponds to a dynamic call to', '``setuptools.config.expand.find_packages`` function.', 'The ``find`` key is associated with a nested ``dict``-like structure that can', 'contain ``where``, ``include``, ``exclude`` and ``namespaces`` keys,', 'mimicking the keyword arguments of the associated function.'], 'oneOf': [{'title': 'Array of Python package identifiers', 'type': 'array', 'items': {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}}, {'$id': '#/definitions/find-directive', 'title': "'find:' directive", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}]}, 'package-dir': {'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'const': ''}, {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, 'package-data': {'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'type': 'string', 'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'include-package-data': {'$$description': ['Automatically include any data files inside the package directories', 'that are specified by ``MANIFEST.in``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'boolean'}, 'exclude-package-data': {'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'type': 'string', 'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'namespace-packages': {'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name-relaxed'}, '$comment': 'https://setuptools.pypa.io/en/latest/userguide/package_discovery.html', 'description': '**DEPRECATED**: use implicit namespaces instead (:pep:`420`).'}, 'py-modules': {'description': 'Modules that setuptools will manipulate', 'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name-relaxed'}, '$comment': 'TODO: clarify the relationship with ``packages``'}, 'ext-modules': {'description': 'Extension modules to be compiled by setuptools', 'type': 'array', 'items': {'$id': '#/definitions/ext-module', 'title': 'Extension module', 'description': 'Parameters to construct a :class:`setuptools.Extension` object', 'type': 'object', 'required': ['name', 'sources'], 'additionalProperties': False, 'properties': {'name': {'type': 'string', 'format': 'python-module-name-relaxed'}, 'sources': {'type': 'array', 'items': {'type': 'string'}}, 'include-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'define-macros': {'type': 'array', 'items': {'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}}, 'undef-macros': {'type': 'array', 'items': {'type': 'string'}}, 'library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'libraries': {'type': 'array', 'items': {'type': 'string'}}, 'runtime-library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'extra-objects': {'type': 'array', 'items': {'type': 'string'}}, 'extra-compile-args': {'type': 'array', 'items': {'type': 'string'}}, 'extra-link-args': {'type': 'array', 'items': {'type': 'string'}}, 'export-symbols': {'type': 'array', 'items': {'type': 'string'}}, 'swig-opts': {'type': 'array', 'items': {'type': 'string'}}, 'depends': {'type': 'array', 'items': {'type': 'string'}}, 'language': {'type': 'string'}, 'optional': {'type': 'boolean'}, 'py-limited-api': {'type': 'boolean'}}}}, 'data-files': {'$$description': ['``dict``-like structure where each key represents a directory and', 'the value is a list of glob patterns that should be installed in them.', '**DISCOURAGED**: please notice this might not work as expected with wheels.', 'Whenever possible, consider using data files inside the package directories', '(or create a new namespace package that only contains data files).', 'See `data files support', '`_.'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'cmdclass': {'$$description': ['Mapping of distutils-style command names to ``setuptools.Command`` subclasses', 'which in turn should be represented by strings with a qualified class name', '(i.e., "dotted" form with module), e.g.::\n\n', '    cmdclass = {mycmd = "pkg.subpkg.module.CommandClass"}\n\n', 'The command class should be a directly defined at the top-level of the', 'containing module (no class nesting).'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'string', 'format': 'python-qualified-identifier'}}}, 'license-files': {'type': 'array', 'items': {'type': 'string'}, '$$description': ['**PROVISIONAL**: list of glob patterns for all license files being distributed.', '(likely to become standard with :pep:`639`).', "By default: ``['LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*']``"], '$comment': 'TODO: revise if PEP 639 is accepted. Probably ``project.license-files``?'}, 'dynamic': {'type': 'object', 'description': 'Instructions for loading :pep:`621`-related metadata dynamically', 'additionalProperties': False, 'properties': {'version': {'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.', 'Also ensure to set ``project.dynamic`` accordingly.'], 'oneOf': [{'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}]}, 'classifiers': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'description': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'entry-points': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'dependencies': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}, 'optional-dependencies': {'type': 'object', 'propertyNames': {'type': 'string', 'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}}}, 'readme': {'type': 'object', 'anyOf': [{'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, {'type': 'object', 'properties': {'content-type': {'type': 'string'}, 'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'additionalProperties': False}], 'required': ['file']}}}}, 'definitions': {'package-name': {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}, 'ext-module': {'$id': '#/definitions/ext-module', 'title': 'Extension module', 'description': 'Parameters to construct a :class:`setuptools.Extension` object', 'type': 'object', 'required': ['name', 'sources'], 'additionalProperties': False, 'properties': {'name': {'type': 'string', 'format': 'python-module-name-relaxed'}, 'sources': {'type': 'array', 'items': {'type': 'string'}}, 'include-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'define-macros': {'type': 'array', 'items': {'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}}, 'undef-macros': {'type': 'array', 'items': {'type': 'string'}}, 'library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'libraries': {'type': 'array', 'items': {'type': 'string'}}, 'runtime-library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'extra-objects': {'type': 'array', 'items': {'type': 'string'}}, 'extra-compile-args': {'type': 'array', 'items': {'type': 'string'}}, 'extra-link-args': {'type': 'array', 'items': {'type': 'string'}}, 'export-symbols': {'type': 'array', 'items': {'type': 'string'}}, 'swig-opts': {'type': 'array', 'items': {'type': 'string'}}, 'depends': {'type': 'array', 'items': {'type': 'string'}}, 'language': {'type': 'string'}, 'optional': {'type': 'boolean'}, 'py-limited-api': {'type': 'boolean'}}}, 'file-directive': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'file-directive-for-dependencies': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}]}, 'attr-directive': {'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, 'find-directive': {'$id': '#/definitions/find-directive', 'title': "'find:' directive", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}}}, rule='additionalProperties')
+    return data
+
+def validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_file_directive_properties_file(data, custom_formats={}, name_prefix=None):
+    data_one_of_count8 = 0
+    if data_one_of_count8 < 2:
+        try:
+            if not isinstance(data, (str)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + " must be string", value=data, name="" + (name_prefix or "data") + "", definition={'type': 'string'}, rule='type')
+            data_one_of_count8 += 1
+        except JsonSchemaValueException: pass
+    if data_one_of_count8 < 2:
+        try:
+            if not isinstance(data, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + " must be array", value=data, name="" + (name_prefix or "data") + "", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data_is_list = isinstance(data, (list, tuple))
+            if data_is_list:
+                data_len = len(data)
+                for data_x, data_item in enumerate(data):
+                    if not isinstance(data_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + "[{data_x}]".format(**locals()) + " must be string", value=data_item, name="" + (name_prefix or "data") + "[{data_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+            data_one_of_count8 += 1
+        except JsonSchemaValueException: pass
+    if data_one_of_count8 != 1:
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be valid exactly by one definition" + (" (" + str(data_one_of_count8) + " matches found)"), value=data, name="" + (name_prefix or "data") + "", definition={'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}, rule='oneOf')
+    return data
+
+def validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_file_directive_for_dependencies(data, custom_formats={}, name_prefix=None):
+    validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_file_directive(data, custom_formats, (name_prefix or "data") + "")
+    return data
+
+def validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_file_directive(data, custom_formats={}, name_prefix=None):
+    if not isinstance(data, (dict)):
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be object", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, rule='type')
+    data_is_dict = isinstance(data, dict)
+    if data_is_dict:
+        data__missing_keys = set(['file']) - data.keys()
+        if data__missing_keys:
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must contain " + (str(sorted(data__missing_keys)) + " properties"), value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, rule='required')
+        data_keys = set(data.keys())
+        if "file" in data_keys:
+            data_keys.remove("file")
+            data__file = data["file"]
+            data__file_one_of_count9 = 0
+            if data__file_one_of_count9 < 2:
+                try:
+                    if not isinstance(data__file, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".file must be string", value=data__file, name="" + (name_prefix or "data") + ".file", definition={'type': 'string'}, rule='type')
+                    data__file_one_of_count9 += 1
+                except JsonSchemaValueException: pass
+            if data__file_one_of_count9 < 2:
+                try:
+                    if not isinstance(data__file, (list, tuple)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".file must be array", value=data__file, name="" + (name_prefix or "data") + ".file", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+                    data__file_is_list = isinstance(data__file, (list, tuple))
+                    if data__file_is_list:
+                        data__file_len = len(data__file)
+                        for data__file_x, data__file_item in enumerate(data__file):
+                            if not isinstance(data__file_item, (str)):
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".file[{data__file_x}]".format(**locals()) + " must be string", value=data__file_item, name="" + (name_prefix or "data") + ".file[{data__file_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+                    data__file_one_of_count9 += 1
+                except JsonSchemaValueException: pass
+            if data__file_one_of_count9 != 1:
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".file must be valid exactly by one definition" + (" (" + str(data__file_one_of_count9) + " matches found)"), value=data__file, name="" + (name_prefix or "data") + ".file", definition={'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}, rule='oneOf')
+        if data_keys:
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must not contain "+str(data_keys)+" properties", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, rule='additionalProperties')
+    return data
+
+def validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_attr_directive(data, custom_formats={}, name_prefix=None):
+    if not isinstance(data, (dict)):
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be object", value=data, name="" + (name_prefix or "data") + "", definition={'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, rule='type')
+    data_is_dict = isinstance(data, dict)
+    if data_is_dict:
+        data__missing_keys = set(['attr']) - data.keys()
+        if data__missing_keys:
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must contain " + (str(sorted(data__missing_keys)) + " properties"), value=data, name="" + (name_prefix or "data") + "", definition={'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, rule='required')
+        data_keys = set(data.keys())
+        if "attr" in data_keys:
+            data_keys.remove("attr")
+            data__attr = data["attr"]
+            if not isinstance(data__attr, (str)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".attr must be string", value=data__attr, name="" + (name_prefix or "data") + ".attr", definition={'type': 'string', 'format': 'python-qualified-identifier'}, rule='type')
+            if isinstance(data__attr, str):
+                if not custom_formats["python-qualified-identifier"](data__attr):
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".attr must be python-qualified-identifier", value=data__attr, name="" + (name_prefix or "data") + ".attr", definition={'type': 'string', 'format': 'python-qualified-identifier'}, rule='format')
+        if data_keys:
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must not contain "+str(data_keys)+" properties", value=data, name="" + (name_prefix or "data") + "", definition={'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, rule='additionalProperties')
+    return data
+
+def validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_ext_module(data, custom_formats={}, name_prefix=None):
+    if not isinstance(data, (dict)):
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be object", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/ext-module', 'title': 'Extension module', 'description': 'Parameters to construct a :class:`setuptools.Extension` object', 'type': 'object', 'required': ['name', 'sources'], 'additionalProperties': False, 'properties': {'name': {'type': 'string', 'format': 'python-module-name-relaxed'}, 'sources': {'type': 'array', 'items': {'type': 'string'}}, 'include-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'define-macros': {'type': 'array', 'items': {'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}}, 'undef-macros': {'type': 'array', 'items': {'type': 'string'}}, 'library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'libraries': {'type': 'array', 'items': {'type': 'string'}}, 'runtime-library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'extra-objects': {'type': 'array', 'items': {'type': 'string'}}, 'extra-compile-args': {'type': 'array', 'items': {'type': 'string'}}, 'extra-link-args': {'type': 'array', 'items': {'type': 'string'}}, 'export-symbols': {'type': 'array', 'items': {'type': 'string'}}, 'swig-opts': {'type': 'array', 'items': {'type': 'string'}}, 'depends': {'type': 'array', 'items': {'type': 'string'}}, 'language': {'type': 'string'}, 'optional': {'type': 'boolean'}, 'py-limited-api': {'type': 'boolean'}}}, rule='type')
+    data_is_dict = isinstance(data, dict)
+    if data_is_dict:
+        data__missing_keys = set(['name', 'sources']) - data.keys()
+        if data__missing_keys:
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must contain " + (str(sorted(data__missing_keys)) + " properties"), value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/ext-module', 'title': 'Extension module', 'description': 'Parameters to construct a :class:`setuptools.Extension` object', 'type': 'object', 'required': ['name', 'sources'], 'additionalProperties': False, 'properties': {'name': {'type': 'string', 'format': 'python-module-name-relaxed'}, 'sources': {'type': 'array', 'items': {'type': 'string'}}, 'include-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'define-macros': {'type': 'array', 'items': {'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}}, 'undef-macros': {'type': 'array', 'items': {'type': 'string'}}, 'library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'libraries': {'type': 'array', 'items': {'type': 'string'}}, 'runtime-library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'extra-objects': {'type': 'array', 'items': {'type': 'string'}}, 'extra-compile-args': {'type': 'array', 'items': {'type': 'string'}}, 'extra-link-args': {'type': 'array', 'items': {'type': 'string'}}, 'export-symbols': {'type': 'array', 'items': {'type': 'string'}}, 'swig-opts': {'type': 'array', 'items': {'type': 'string'}}, 'depends': {'type': 'array', 'items': {'type': 'string'}}, 'language': {'type': 'string'}, 'optional': {'type': 'boolean'}, 'py-limited-api': {'type': 'boolean'}}}, rule='required')
+        data_keys = set(data.keys())
+        if "name" in data_keys:
+            data_keys.remove("name")
+            data__name = data["name"]
+            if not isinstance(data__name, (str)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".name must be string", value=data__name, name="" + (name_prefix or "data") + ".name", definition={'type': 'string', 'format': 'python-module-name-relaxed'}, rule='type')
+            if isinstance(data__name, str):
+                if not custom_formats["python-module-name-relaxed"](data__name):
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".name must be python-module-name-relaxed", value=data__name, name="" + (name_prefix or "data") + ".name", definition={'type': 'string', 'format': 'python-module-name-relaxed'}, rule='format')
+        if "sources" in data_keys:
+            data_keys.remove("sources")
+            data__sources = data["sources"]
+            if not isinstance(data__sources, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".sources must be array", value=data__sources, name="" + (name_prefix or "data") + ".sources", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__sources_is_list = isinstance(data__sources, (list, tuple))
+            if data__sources_is_list:
+                data__sources_len = len(data__sources)
+                for data__sources_x, data__sources_item in enumerate(data__sources):
+                    if not isinstance(data__sources_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".sources[{data__sources_x}]".format(**locals()) + " must be string", value=data__sources_item, name="" + (name_prefix or "data") + ".sources[{data__sources_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "include-dirs" in data_keys:
+            data_keys.remove("include-dirs")
+            data__includedirs = data["include-dirs"]
+            if not isinstance(data__includedirs, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".include-dirs must be array", value=data__includedirs, name="" + (name_prefix or "data") + ".include-dirs", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__includedirs_is_list = isinstance(data__includedirs, (list, tuple))
+            if data__includedirs_is_list:
+                data__includedirs_len = len(data__includedirs)
+                for data__includedirs_x, data__includedirs_item in enumerate(data__includedirs):
+                    if not isinstance(data__includedirs_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".include-dirs[{data__includedirs_x}]".format(**locals()) + " must be string", value=data__includedirs_item, name="" + (name_prefix or "data") + ".include-dirs[{data__includedirs_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "define-macros" in data_keys:
+            data_keys.remove("define-macros")
+            data__definemacros = data["define-macros"]
+            if not isinstance(data__definemacros, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".define-macros must be array", value=data__definemacros, name="" + (name_prefix or "data") + ".define-macros", definition={'type': 'array', 'items': {'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}}, rule='type')
+            data__definemacros_is_list = isinstance(data__definemacros, (list, tuple))
+            if data__definemacros_is_list:
+                data__definemacros_len = len(data__definemacros)
+                for data__definemacros_x, data__definemacros_item in enumerate(data__definemacros):
+                    if not isinstance(data__definemacros_item, (list, tuple)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".define-macros[{data__definemacros_x}]".format(**locals()) + " must be array", value=data__definemacros_item, name="" + (name_prefix or "data") + ".define-macros[{data__definemacros_x}]".format(**locals()) + "", definition={'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}, rule='type')
+                    data__definemacros_item_is_list = isinstance(data__definemacros_item, (list, tuple))
+                    if data__definemacros_item_is_list:
+                        data__definemacros_item_len = len(data__definemacros_item)
+                        if data__definemacros_item_len > 0:
+                            data__definemacros_item__0 = data__definemacros_item[0]
+                            if not isinstance(data__definemacros_item__0, (str)):
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".define-macros[{data__definemacros_x}][0]".format(**locals()) + " must be string", value=data__definemacros_item__0, name="" + (name_prefix or "data") + ".define-macros[{data__definemacros_x}][0]".format(**locals()) + "", definition={'description': 'macro name', 'type': 'string'}, rule='type')
+                        if data__definemacros_item_len > 1:
+                            data__definemacros_item__1 = data__definemacros_item[1]
+                            data__definemacros_item__1_one_of_count10 = 0
+                            if data__definemacros_item__1_one_of_count10 < 2:
+                                try:
+                                    if not isinstance(data__definemacros_item__1, (str)):
+                                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".define-macros[{data__definemacros_x}][1]".format(**locals()) + " must be string", value=data__definemacros_item__1, name="" + (name_prefix or "data") + ".define-macros[{data__definemacros_x}][1]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+                                    data__definemacros_item__1_one_of_count10 += 1
+                                except JsonSchemaValueException: pass
+                            if data__definemacros_item__1_one_of_count10 < 2:
+                                try:
+                                    if not isinstance(data__definemacros_item__1, (NoneType)):
+                                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".define-macros[{data__definemacros_x}][1]".format(**locals()) + " must be null", value=data__definemacros_item__1, name="" + (name_prefix or "data") + ".define-macros[{data__definemacros_x}][1]".format(**locals()) + "", definition={'type': 'null'}, rule='type')
+                                    data__definemacros_item__1_one_of_count10 += 1
+                                except JsonSchemaValueException: pass
+                            if data__definemacros_item__1_one_of_count10 != 1:
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".define-macros[{data__definemacros_x}][1]".format(**locals()) + " must be valid exactly by one definition" + (" (" + str(data__definemacros_item__1_one_of_count10) + " matches found)"), value=data__definemacros_item__1, name="" + (name_prefix or "data") + ".define-macros[{data__definemacros_x}][1]".format(**locals()) + "", definition={'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}, rule='oneOf')
+                        if data__definemacros_item_len > 2:
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".define-macros[{data__definemacros_x}]".format(**locals()) + " must contain only specified items", value=data__definemacros_item, name="" + (name_prefix or "data") + ".define-macros[{data__definemacros_x}]".format(**locals()) + "", definition={'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}, rule='items')
+        if "undef-macros" in data_keys:
+            data_keys.remove("undef-macros")
+            data__undefmacros = data["undef-macros"]
+            if not isinstance(data__undefmacros, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".undef-macros must be array", value=data__undefmacros, name="" + (name_prefix or "data") + ".undef-macros", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__undefmacros_is_list = isinstance(data__undefmacros, (list, tuple))
+            if data__undefmacros_is_list:
+                data__undefmacros_len = len(data__undefmacros)
+                for data__undefmacros_x, data__undefmacros_item in enumerate(data__undefmacros):
+                    if not isinstance(data__undefmacros_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".undef-macros[{data__undefmacros_x}]".format(**locals()) + " must be string", value=data__undefmacros_item, name="" + (name_prefix or "data") + ".undef-macros[{data__undefmacros_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "library-dirs" in data_keys:
+            data_keys.remove("library-dirs")
+            data__librarydirs = data["library-dirs"]
+            if not isinstance(data__librarydirs, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".library-dirs must be array", value=data__librarydirs, name="" + (name_prefix or "data") + ".library-dirs", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__librarydirs_is_list = isinstance(data__librarydirs, (list, tuple))
+            if data__librarydirs_is_list:
+                data__librarydirs_len = len(data__librarydirs)
+                for data__librarydirs_x, data__librarydirs_item in enumerate(data__librarydirs):
+                    if not isinstance(data__librarydirs_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".library-dirs[{data__librarydirs_x}]".format(**locals()) + " must be string", value=data__librarydirs_item, name="" + (name_prefix or "data") + ".library-dirs[{data__librarydirs_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "libraries" in data_keys:
+            data_keys.remove("libraries")
+            data__libraries = data["libraries"]
+            if not isinstance(data__libraries, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".libraries must be array", value=data__libraries, name="" + (name_prefix or "data") + ".libraries", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__libraries_is_list = isinstance(data__libraries, (list, tuple))
+            if data__libraries_is_list:
+                data__libraries_len = len(data__libraries)
+                for data__libraries_x, data__libraries_item in enumerate(data__libraries):
+                    if not isinstance(data__libraries_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".libraries[{data__libraries_x}]".format(**locals()) + " must be string", value=data__libraries_item, name="" + (name_prefix or "data") + ".libraries[{data__libraries_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "runtime-library-dirs" in data_keys:
+            data_keys.remove("runtime-library-dirs")
+            data__runtimelibrarydirs = data["runtime-library-dirs"]
+            if not isinstance(data__runtimelibrarydirs, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".runtime-library-dirs must be array", value=data__runtimelibrarydirs, name="" + (name_prefix or "data") + ".runtime-library-dirs", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__runtimelibrarydirs_is_list = isinstance(data__runtimelibrarydirs, (list, tuple))
+            if data__runtimelibrarydirs_is_list:
+                data__runtimelibrarydirs_len = len(data__runtimelibrarydirs)
+                for data__runtimelibrarydirs_x, data__runtimelibrarydirs_item in enumerate(data__runtimelibrarydirs):
+                    if not isinstance(data__runtimelibrarydirs_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".runtime-library-dirs[{data__runtimelibrarydirs_x}]".format(**locals()) + " must be string", value=data__runtimelibrarydirs_item, name="" + (name_prefix or "data") + ".runtime-library-dirs[{data__runtimelibrarydirs_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "extra-objects" in data_keys:
+            data_keys.remove("extra-objects")
+            data__extraobjects = data["extra-objects"]
+            if not isinstance(data__extraobjects, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".extra-objects must be array", value=data__extraobjects, name="" + (name_prefix or "data") + ".extra-objects", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__extraobjects_is_list = isinstance(data__extraobjects, (list, tuple))
+            if data__extraobjects_is_list:
+                data__extraobjects_len = len(data__extraobjects)
+                for data__extraobjects_x, data__extraobjects_item in enumerate(data__extraobjects):
+                    if not isinstance(data__extraobjects_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".extra-objects[{data__extraobjects_x}]".format(**locals()) + " must be string", value=data__extraobjects_item, name="" + (name_prefix or "data") + ".extra-objects[{data__extraobjects_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "extra-compile-args" in data_keys:
+            data_keys.remove("extra-compile-args")
+            data__extracompileargs = data["extra-compile-args"]
+            if not isinstance(data__extracompileargs, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".extra-compile-args must be array", value=data__extracompileargs, name="" + (name_prefix or "data") + ".extra-compile-args", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__extracompileargs_is_list = isinstance(data__extracompileargs, (list, tuple))
+            if data__extracompileargs_is_list:
+                data__extracompileargs_len = len(data__extracompileargs)
+                for data__extracompileargs_x, data__extracompileargs_item in enumerate(data__extracompileargs):
+                    if not isinstance(data__extracompileargs_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".extra-compile-args[{data__extracompileargs_x}]".format(**locals()) + " must be string", value=data__extracompileargs_item, name="" + (name_prefix or "data") + ".extra-compile-args[{data__extracompileargs_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "extra-link-args" in data_keys:
+            data_keys.remove("extra-link-args")
+            data__extralinkargs = data["extra-link-args"]
+            if not isinstance(data__extralinkargs, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".extra-link-args must be array", value=data__extralinkargs, name="" + (name_prefix or "data") + ".extra-link-args", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__extralinkargs_is_list = isinstance(data__extralinkargs, (list, tuple))
+            if data__extralinkargs_is_list:
+                data__extralinkargs_len = len(data__extralinkargs)
+                for data__extralinkargs_x, data__extralinkargs_item in enumerate(data__extralinkargs):
+                    if not isinstance(data__extralinkargs_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".extra-link-args[{data__extralinkargs_x}]".format(**locals()) + " must be string", value=data__extralinkargs_item, name="" + (name_prefix or "data") + ".extra-link-args[{data__extralinkargs_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "export-symbols" in data_keys:
+            data_keys.remove("export-symbols")
+            data__exportsymbols = data["export-symbols"]
+            if not isinstance(data__exportsymbols, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".export-symbols must be array", value=data__exportsymbols, name="" + (name_prefix or "data") + ".export-symbols", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__exportsymbols_is_list = isinstance(data__exportsymbols, (list, tuple))
+            if data__exportsymbols_is_list:
+                data__exportsymbols_len = len(data__exportsymbols)
+                for data__exportsymbols_x, data__exportsymbols_item in enumerate(data__exportsymbols):
+                    if not isinstance(data__exportsymbols_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".export-symbols[{data__exportsymbols_x}]".format(**locals()) + " must be string", value=data__exportsymbols_item, name="" + (name_prefix or "data") + ".export-symbols[{data__exportsymbols_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "swig-opts" in data_keys:
+            data_keys.remove("swig-opts")
+            data__swigopts = data["swig-opts"]
+            if not isinstance(data__swigopts, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".swig-opts must be array", value=data__swigopts, name="" + (name_prefix or "data") + ".swig-opts", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__swigopts_is_list = isinstance(data__swigopts, (list, tuple))
+            if data__swigopts_is_list:
+                data__swigopts_len = len(data__swigopts)
+                for data__swigopts_x, data__swigopts_item in enumerate(data__swigopts):
+                    if not isinstance(data__swigopts_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".swig-opts[{data__swigopts_x}]".format(**locals()) + " must be string", value=data__swigopts_item, name="" + (name_prefix or "data") + ".swig-opts[{data__swigopts_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "depends" in data_keys:
+            data_keys.remove("depends")
+            data__depends = data["depends"]
+            if not isinstance(data__depends, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".depends must be array", value=data__depends, name="" + (name_prefix or "data") + ".depends", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__depends_is_list = isinstance(data__depends, (list, tuple))
+            if data__depends_is_list:
+                data__depends_len = len(data__depends)
+                for data__depends_x, data__depends_item in enumerate(data__depends):
+                    if not isinstance(data__depends_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".depends[{data__depends_x}]".format(**locals()) + " must be string", value=data__depends_item, name="" + (name_prefix or "data") + ".depends[{data__depends_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "language" in data_keys:
+            data_keys.remove("language")
+            data__language = data["language"]
+            if not isinstance(data__language, (str)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".language must be string", value=data__language, name="" + (name_prefix or "data") + ".language", definition={'type': 'string'}, rule='type')
+        if "optional" in data_keys:
+            data_keys.remove("optional")
+            data__optional = data["optional"]
+            if not isinstance(data__optional, (bool)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".optional must be boolean", value=data__optional, name="" + (name_prefix or "data") + ".optional", definition={'type': 'boolean'}, rule='type')
+        if "py-limited-api" in data_keys:
+            data_keys.remove("py-limited-api")
+            data__pylimitedapi = data["py-limited-api"]
+            if not isinstance(data__pylimitedapi, (bool)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".py-limited-api must be boolean", value=data__pylimitedapi, name="" + (name_prefix or "data") + ".py-limited-api", definition={'type': 'boolean'}, rule='type')
+        if data_keys:
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must not contain "+str(data_keys)+" properties", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/ext-module', 'title': 'Extension module', 'description': 'Parameters to construct a :class:`setuptools.Extension` object', 'type': 'object', 'required': ['name', 'sources'], 'additionalProperties': False, 'properties': {'name': {'type': 'string', 'format': 'python-module-name-relaxed'}, 'sources': {'type': 'array', 'items': {'type': 'string'}}, 'include-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'define-macros': {'type': 'array', 'items': {'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}}, 'undef-macros': {'type': 'array', 'items': {'type': 'string'}}, 'library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'libraries': {'type': 'array', 'items': {'type': 'string'}}, 'runtime-library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'extra-objects': {'type': 'array', 'items': {'type': 'string'}}, 'extra-compile-args': {'type': 'array', 'items': {'type': 'string'}}, 'extra-link-args': {'type': 'array', 'items': {'type': 'string'}}, 'export-symbols': {'type': 'array', 'items': {'type': 'string'}}, 'swig-opts': {'type': 'array', 'items': {'type': 'string'}}, 'depends': {'type': 'array', 'items': {'type': 'string'}}, 'language': {'type': 'string'}, 'optional': {'type': 'boolean'}, 'py-limited-api': {'type': 'boolean'}}}, rule='additionalProperties')
+    return data
+
+def validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_find_directive(data, custom_formats={}, name_prefix=None):
+    if not isinstance(data, (dict)):
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be object", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/find-directive', 'title': "'find:' directive", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}, rule='type')
+    data_is_dict = isinstance(data, dict)
+    if data_is_dict:
+        data_keys = set(data.keys())
+        if "find" in data_keys:
+            data_keys.remove("find")
+            data__find = data["find"]
+            if not isinstance(data__find, (dict)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".find must be object", value=data__find, name="" + (name_prefix or "data") + ".find", definition={'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}, rule='type')
+            data__find_is_dict = isinstance(data__find, dict)
+            if data__find_is_dict:
+                data__find_keys = set(data__find.keys())
+                if "where" in data__find_keys:
+                    data__find_keys.remove("where")
+                    data__find__where = data__find["where"]
+                    if not isinstance(data__find__where, (list, tuple)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".find.where must be array", value=data__find__where, name="" + (name_prefix or "data") + ".find.where", definition={'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, rule='type')
+                    data__find__where_is_list = isinstance(data__find__where, (list, tuple))
+                    if data__find__where_is_list:
+                        data__find__where_len = len(data__find__where)
+                        for data__find__where_x, data__find__where_item in enumerate(data__find__where):
+                            if not isinstance(data__find__where_item, (str)):
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".find.where[{data__find__where_x}]".format(**locals()) + " must be string", value=data__find__where_item, name="" + (name_prefix or "data") + ".find.where[{data__find__where_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+                if "exclude" in data__find_keys:
+                    data__find_keys.remove("exclude")
+                    data__find__exclude = data__find["exclude"]
+                    if not isinstance(data__find__exclude, (list, tuple)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".find.exclude must be array", value=data__find__exclude, name="" + (name_prefix or "data") + ".find.exclude", definition={'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, rule='type')
+                    data__find__exclude_is_list = isinstance(data__find__exclude, (list, tuple))
+                    if data__find__exclude_is_list:
+                        data__find__exclude_len = len(data__find__exclude)
+                        for data__find__exclude_x, data__find__exclude_item in enumerate(data__find__exclude):
+                            if not isinstance(data__find__exclude_item, (str)):
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".find.exclude[{data__find__exclude_x}]".format(**locals()) + " must be string", value=data__find__exclude_item, name="" + (name_prefix or "data") + ".find.exclude[{data__find__exclude_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+                if "include" in data__find_keys:
+                    data__find_keys.remove("include")
+                    data__find__include = data__find["include"]
+                    if not isinstance(data__find__include, (list, tuple)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".find.include must be array", value=data__find__include, name="" + (name_prefix or "data") + ".find.include", definition={'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, rule='type')
+                    data__find__include_is_list = isinstance(data__find__include, (list, tuple))
+                    if data__find__include_is_list:
+                        data__find__include_len = len(data__find__include)
+                        for data__find__include_x, data__find__include_item in enumerate(data__find__include):
+                            if not isinstance(data__find__include_item, (str)):
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".find.include[{data__find__include_x}]".format(**locals()) + " must be string", value=data__find__include_item, name="" + (name_prefix or "data") + ".find.include[{data__find__include_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+                if "namespaces" in data__find_keys:
+                    data__find_keys.remove("namespaces")
+                    data__find__namespaces = data__find["namespaces"]
+                    if not isinstance(data__find__namespaces, (bool)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".find.namespaces must be boolean", value=data__find__namespaces, name="" + (name_prefix or "data") + ".find.namespaces", definition={'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}, rule='type')
+                if data__find_keys:
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".find must not contain "+str(data__find_keys)+" properties", value=data__find, name="" + (name_prefix or "data") + ".find", definition={'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}, rule='additionalProperties')
+        if data_keys:
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must not contain "+str(data_keys)+" properties", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/find-directive', 'title': "'find:' directive", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}, rule='additionalProperties')
+    return data
+
+def validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_package_name(data, custom_formats={}, name_prefix=None):
+    if not isinstance(data, (str)):
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be string", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}, rule='type')
+    data_any_of_count11 = 0
+    if not data_any_of_count11:
+        try:
+            if not isinstance(data, (str)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + " must be string", value=data, name="" + (name_prefix or "data") + "", definition={'type': 'string', 'format': 'python-module-name-relaxed'}, rule='type')
+            if isinstance(data, str):
+                if not custom_formats["python-module-name-relaxed"](data):
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + " must be python-module-name-relaxed", value=data, name="" + (name_prefix or "data") + "", definition={'type': 'string', 'format': 'python-module-name-relaxed'}, rule='format')
+            data_any_of_count11 += 1
+        except JsonSchemaValueException: pass
+    if not data_any_of_count11:
+        try:
+            if not isinstance(data, (str)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + " must be string", value=data, name="" + (name_prefix or "data") + "", definition={'type': 'string', 'format': 'pep561-stub-name'}, rule='type')
+            if isinstance(data, str):
+                if not custom_formats["pep561-stub-name"](data):
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + " must be pep561-stub-name", value=data, name="" + (name_prefix or "data") + "", definition={'type': 'string', 'format': 'pep561-stub-name'}, rule='format')
+            data_any_of_count11 += 1
+        except JsonSchemaValueException: pass
+    if not data_any_of_count11:
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " cannot be validated by any definition", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}, rule='anyOf')
+    return data
+
+def validate_https___setuptools_pypa_io_en_latest_deprecated_distutils_configfile_html(data, custom_formats={}, name_prefix=None):
+    if not isinstance(data, (dict)):
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be object", value=data, name="" + (name_prefix or "data") + "", definition={'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://setuptools.pypa.io/en/latest/deprecated/distutils/configfile.html', 'title': '``tool.distutils`` table', '$$description': ['**EXPERIMENTAL** (NOT OFFICIALLY SUPPORTED): Use ``tool.distutils``', 'subtables to configure arguments for ``distutils`` commands.', 'Originally, ``distutils`` allowed developers to configure arguments for', '``setup.py`` commands via `distutils configuration files', '`_.', 'See also `the old Python docs _`.'], 'type': 'object', 'properties': {'global': {'type': 'object', 'description': 'Global options applied to all ``distutils`` commands'}}, 'patternProperties': {'.+': {'type': 'object'}}, '$comment': 'TODO: Is there a practical way of making this schema more specific?'}, rule='type')
+    data_is_dict = isinstance(data, dict)
+    if data_is_dict:
+        data_keys = set(data.keys())
+        if "global" in data_keys:
+            data_keys.remove("global")
+            data__global = data["global"]
+            if not isinstance(data__global, (dict)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".global must be object", value=data__global, name="" + (name_prefix or "data") + ".global", definition={'type': 'object', 'description': 'Global options applied to all ``distutils`` commands'}, rule='type')
+        for data_key, data_val in data.items():
+            if REGEX_PATTERNS['.+'].search(data_key):
+                if data_key in data_keys:
+                    data_keys.remove(data_key)
+                if not isinstance(data_val, (dict)):
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".{data_key}".format(**locals()) + " must be object", value=data_val, name="" + (name_prefix or "data") + ".{data_key}".format(**locals()) + "", definition={'type': 'object'}, rule='type')
+    return data
+
+def validate_https___packaging_python_org_en_latest_specifications_pyproject_toml(data, custom_formats={}, name_prefix=None):
+    if not isinstance(data, (dict)):
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be object", value=data, name="" + (name_prefix or "data") + "", definition={'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://packaging.python.org/en/latest/specifications/pyproject-toml/', 'title': 'Package metadata stored in the ``project`` table', '$$description': ['Data structure for the **project** table inside ``pyproject.toml``', '(as initially defined in :pep:`621`)'], 'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, 'version': {'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, 'description': {'type': 'string', '$$description': ['The `summary description of the project', '`_']}, 'readme': {'$$description': ['`Full/detailed description of the project in the form of a README', '`_', "with meaning similar to the one defined in `core metadata's Description", '`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, 'requires-python': {'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '`_.']}, 'license': {'description': '`Project license `_.', 'oneOf': [{'type': 'string', 'description': 'An SPDX license identifier', 'format': 'SPDX'}, {'type': 'object', 'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'type': 'object', 'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}]}, 'license-files': {'description': 'Paths or globs to paths of license files', 'type': 'array', 'items': {'type': 'string'}}, 'authors': {'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, '$$description': ["The people or organizations considered to be the 'authors' of the project.", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, 'maintainers': {'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, '$$description': ["The people or organizations considered to be the 'maintainers' of the project.", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, 'keywords': {'type': 'array', 'items': {'type': 'string'}, 'description': 'List of keywords to assist searching for the distribution in a larger catalog.'}, 'classifiers': {'type': 'array', 'items': {'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier `_.'}, '$$description': ['`Trove classifiers `_', 'which apply to the project.']}, 'urls': {'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, 'scripts': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'gui-scripts': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'entry-points': {'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}}}, 'dependencies': {'type': 'array', 'description': 'Project (mandatory) dependencies.', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}, 'optional-dependencies': {'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}}, 'dynamic': {'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'license-files', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']}}}, 'required': ['name'], 'additionalProperties': False, 'allOf': [{'if': {'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as "Required", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, 'then': {'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}}, {'if': {'required': ['license-files']}, 'then': {'properties': {'license': {'type': 'string'}}}}], 'definitions': {'author': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, 'entry-point-group': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'dependency': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}, rule='type')
+    try:
+        try:
+            data_is_dict = isinstance(data, dict)
+            if data_is_dict:
+                data__missing_keys = set(['dynamic']) - data.keys()
+                if data__missing_keys:
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + " must contain " + (str(sorted(data__missing_keys)) + " properties"), value=data, name="" + (name_prefix or "data") + "", definition={'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, rule='required')
+                data_keys = set(data.keys())
+                if "dynamic" in data_keys:
+                    data_keys.remove("dynamic")
+                    data__dynamic = data["dynamic"]
+                    data__dynamic_is_list = isinstance(data__dynamic, (list, tuple))
+                    if data__dynamic_is_list:
+                        data__dynamic_contains = False
+                        for data__dynamic_key in data__dynamic:
+                            try:
+                                if data__dynamic_key != "version":
+                                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic must be same as const definition: version", value=data__dynamic_key, name="" + (name_prefix or "data") + ".dynamic", definition={'const': 'version'}, rule='const')
+                                data__dynamic_contains = True
+                                break
+                            except JsonSchemaValueException: pass
+                        if not data__dynamic_contains:
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic must contain one of contains definition", value=data__dynamic, name="" + (name_prefix or "data") + ".dynamic", definition={'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}, rule='contains')
+        except JsonSchemaValueException: pass
+        else:
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must NOT match a disallowed definition", value=data, name="" + (name_prefix or "data") + "", definition={'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as "Required", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, rule='not')
+    except JsonSchemaValueException:
+        pass
+    else:
+        data_is_dict = isinstance(data, dict)
+        if data_is_dict:
+            data__missing_keys = set(['version']) - data.keys()
+            if data__missing_keys:
+                raise JsonSchemaValueException("" + (name_prefix or "data") + " must contain " + (str(sorted(data__missing_keys)) + " properties"), value=data, name="" + (name_prefix or "data") + "", definition={'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}, rule='required')
+    try:
+        data_is_dict = isinstance(data, dict)
+        if data_is_dict:
+            data__missing_keys = set(['license-files']) - data.keys()
+            if data__missing_keys:
+                raise JsonSchemaValueException("" + (name_prefix or "data") + " must contain " + (str(sorted(data__missing_keys)) + " properties"), value=data, name="" + (name_prefix or "data") + "", definition={'required': ['license-files']}, rule='required')
+    except JsonSchemaValueException:
+        pass
+    else:
+        data_is_dict = isinstance(data, dict)
+        if data_is_dict:
+            data_keys = set(data.keys())
+            if "license" in data_keys:
+                data_keys.remove("license")
+                data__license = data["license"]
+                if not isinstance(data__license, (str)):
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".license must be string", value=data__license, name="" + (name_prefix or "data") + ".license", definition={'type': 'string'}, rule='type')
+    data_is_dict = isinstance(data, dict)
+    if data_is_dict:
+        data__missing_keys = set(['name']) - data.keys()
+        if data__missing_keys:
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must contain " + (str(sorted(data__missing_keys)) + " properties"), value=data, name="" + (name_prefix or "data") + "", definition={'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://packaging.python.org/en/latest/specifications/pyproject-toml/', 'title': 'Package metadata stored in the ``project`` table', '$$description': ['Data structure for the **project** table inside ``pyproject.toml``', '(as initially defined in :pep:`621`)'], 'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, 'version': {'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, 'description': {'type': 'string', '$$description': ['The `summary description of the project', '`_']}, 'readme': {'$$description': ['`Full/detailed description of the project in the form of a README', '`_', "with meaning similar to the one defined in `core metadata's Description", '`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, 'requires-python': {'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '`_.']}, 'license': {'description': '`Project license `_.', 'oneOf': [{'type': 'string', 'description': 'An SPDX license identifier', 'format': 'SPDX'}, {'type': 'object', 'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'type': 'object', 'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}]}, 'license-files': {'description': 'Paths or globs to paths of license files', 'type': 'array', 'items': {'type': 'string'}}, 'authors': {'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, '$$description': ["The people or organizations considered to be the 'authors' of the project.", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, 'maintainers': {'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, '$$description': ["The people or organizations considered to be the 'maintainers' of the project.", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, 'keywords': {'type': 'array', 'items': {'type': 'string'}, 'description': 'List of keywords to assist searching for the distribution in a larger catalog.'}, 'classifiers': {'type': 'array', 'items': {'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier `_.'}, '$$description': ['`Trove classifiers `_', 'which apply to the project.']}, 'urls': {'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, 'scripts': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'gui-scripts': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'entry-points': {'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}}}, 'dependencies': {'type': 'array', 'description': 'Project (mandatory) dependencies.', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}, 'optional-dependencies': {'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}}, 'dynamic': {'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'license-files', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']}}}, 'required': ['name'], 'additionalProperties': False, 'allOf': [{'if': {'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as "Required", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, 'then': {'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}}, {'if': {'required': ['license-files']}, 'then': {'properties': {'license': {'type': 'string'}}}}], 'definitions': {'author': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, 'entry-point-group': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'dependency': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}, rule='required')
+        data_keys = set(data.keys())
+        if "name" in data_keys:
+            data_keys.remove("name")
+            data__name = data["name"]
+            if not isinstance(data__name, (str)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".name must be string", value=data__name, name="" + (name_prefix or "data") + ".name", definition={'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, rule='type')
+            if isinstance(data__name, str):
+                if not custom_formats["pep508-identifier"](data__name):
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".name must be pep508-identifier", value=data__name, name="" + (name_prefix or "data") + ".name", definition={'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, rule='format')
+        if "version" in data_keys:
+            data_keys.remove("version")
+            data__version = data["version"]
+            if not isinstance(data__version, (str)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".version must be string", value=data__version, name="" + (name_prefix or "data") + ".version", definition={'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, rule='type')
+            if isinstance(data__version, str):
+                if not custom_formats["pep440"](data__version):
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".version must be pep440", value=data__version, name="" + (name_prefix or "data") + ".version", definition={'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, rule='format')
+        if "description" in data_keys:
+            data_keys.remove("description")
+            data__description = data["description"]
+            if not isinstance(data__description, (str)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".description must be string", value=data__description, name="" + (name_prefix or "data") + ".description", definition={'type': 'string', '$$description': ['The `summary description of the project', '`_']}, rule='type')
+        if "readme" in data_keys:
+            data_keys.remove("readme")
+            data__readme = data["readme"]
+            data__readme_one_of_count12 = 0
+            if data__readme_one_of_count12 < 2:
+                try:
+                    if not isinstance(data__readme, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".readme must be string", value=data__readme, name="" + (name_prefix or "data") + ".readme", definition={'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, rule='type')
+                    data__readme_one_of_count12 += 1
+                except JsonSchemaValueException: pass
+            if data__readme_one_of_count12 < 2:
+                try:
+                    if not isinstance(data__readme, (dict)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".readme must be object", value=data__readme, name="" + (name_prefix or "data") + ".readme", definition={'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}, rule='type')
+                    data__readme_any_of_count13 = 0
+                    if not data__readme_any_of_count13:
+                        try:
+                            data__readme_is_dict = isinstance(data__readme, dict)
+                            if data__readme_is_dict:
+                                data__readme__missing_keys = set(['file']) - data__readme.keys()
+                                if data__readme__missing_keys:
+                                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".readme must contain " + (str(sorted(data__readme__missing_keys)) + " properties"), value=data__readme, name="" + (name_prefix or "data") + ".readme", definition={'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, rule='required')
+                                data__readme_keys = set(data__readme.keys())
+                                if "file" in data__readme_keys:
+                                    data__readme_keys.remove("file")
+                                    data__readme__file = data__readme["file"]
+                                    if not isinstance(data__readme__file, (str)):
+                                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".readme.file must be string", value=data__readme__file, name="" + (name_prefix or "data") + ".readme.file", definition={'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}, rule='type')
+                            data__readme_any_of_count13 += 1
+                        except JsonSchemaValueException: pass
+                    if not data__readme_any_of_count13:
+                        try:
+                            data__readme_is_dict = isinstance(data__readme, dict)
+                            if data__readme_is_dict:
+                                data__readme__missing_keys = set(['text']) - data__readme.keys()
+                                if data__readme__missing_keys:
+                                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".readme must contain " + (str(sorted(data__readme__missing_keys)) + " properties"), value=data__readme, name="" + (name_prefix or "data") + ".readme", definition={'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}, rule='required')
+                                data__readme_keys = set(data__readme.keys())
+                                if "text" in data__readme_keys:
+                                    data__readme_keys.remove("text")
+                                    data__readme__text = data__readme["text"]
+                                    if not isinstance(data__readme__text, (str)):
+                                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".readme.text must be string", value=data__readme__text, name="" + (name_prefix or "data") + ".readme.text", definition={'type': 'string', 'description': 'Full text describing the project.'}, rule='type')
+                            data__readme_any_of_count13 += 1
+                        except JsonSchemaValueException: pass
+                    if not data__readme_any_of_count13:
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".readme cannot be validated by any definition", value=data__readme, name="" + (name_prefix or "data") + ".readme", definition={'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, rule='anyOf')
+                    data__readme_is_dict = isinstance(data__readme, dict)
+                    if data__readme_is_dict:
+                        data__readme__missing_keys = set(['content-type']) - data__readme.keys()
+                        if data__readme__missing_keys:
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".readme must contain " + (str(sorted(data__readme__missing_keys)) + " properties"), value=data__readme, name="" + (name_prefix or "data") + ".readme", definition={'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}, rule='required')
+                        data__readme_keys = set(data__readme.keys())
+                        if "content-type" in data__readme_keys:
+                            data__readme_keys.remove("content-type")
+                            data__readme__contenttype = data__readme["content-type"]
+                            if not isinstance(data__readme__contenttype, (str)):
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".readme.content-type must be string", value=data__readme__contenttype, name="" + (name_prefix or "data") + ".readme.content-type", definition={'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}, rule='type')
+                    data__readme_one_of_count12 += 1
+                except JsonSchemaValueException: pass
+            if data__readme_one_of_count12 != 1:
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".readme must be valid exactly by one definition" + (" (" + str(data__readme_one_of_count12) + " matches found)"), value=data__readme, name="" + (name_prefix or "data") + ".readme", definition={'$$description': ['`Full/detailed description of the project in the form of a README', '`_', "with meaning similar to the one defined in `core metadata's Description", '`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, rule='oneOf')
+        if "requires-python" in data_keys:
+            data_keys.remove("requires-python")
+            data__requirespython = data["requires-python"]
+            if not isinstance(data__requirespython, (str)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".requires-python must be string", value=data__requirespython, name="" + (name_prefix or "data") + ".requires-python", definition={'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '`_.']}, rule='type')
+            if isinstance(data__requirespython, str):
+                if not custom_formats["pep508-versionspec"](data__requirespython):
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".requires-python must be pep508-versionspec", value=data__requirespython, name="" + (name_prefix or "data") + ".requires-python", definition={'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '`_.']}, rule='format')
+        if "license" in data_keys:
+            data_keys.remove("license")
+            data__license = data["license"]
+            data__license_one_of_count14 = 0
+            if data__license_one_of_count14 < 2:
+                try:
+                    if not isinstance(data__license, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".license must be string", value=data__license, name="" + (name_prefix or "data") + ".license", definition={'type': 'string', 'description': 'An SPDX license identifier', 'format': 'SPDX'}, rule='type')
+                    if isinstance(data__license, str):
+                        if not custom_formats["SPDX"](data__license):
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".license must be SPDX", value=data__license, name="" + (name_prefix or "data") + ".license", definition={'type': 'string', 'description': 'An SPDX license identifier', 'format': 'SPDX'}, rule='format')
+                    data__license_one_of_count14 += 1
+                except JsonSchemaValueException: pass
+            if data__license_one_of_count14 < 2:
+                try:
+                    if not isinstance(data__license, (dict)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".license must be object", value=data__license, name="" + (name_prefix or "data") + ".license", definition={'type': 'object', 'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, rule='type')
+                    data__license_is_dict = isinstance(data__license, dict)
+                    if data__license_is_dict:
+                        data__license__missing_keys = set(['file']) - data__license.keys()
+                        if data__license__missing_keys:
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".license must contain " + (str(sorted(data__license__missing_keys)) + " properties"), value=data__license, name="" + (name_prefix or "data") + ".license", definition={'type': 'object', 'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, rule='required')
+                        data__license_keys = set(data__license.keys())
+                        if "file" in data__license_keys:
+                            data__license_keys.remove("file")
+                            data__license__file = data__license["file"]
+                            if not isinstance(data__license__file, (str)):
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".license.file must be string", value=data__license__file, name="" + (name_prefix or "data") + ".license.file", definition={'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}, rule='type')
+                    data__license_one_of_count14 += 1
+                except JsonSchemaValueException: pass
+            if data__license_one_of_count14 < 2:
+                try:
+                    if not isinstance(data__license, (dict)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".license must be object", value=data__license, name="" + (name_prefix or "data") + ".license", definition={'type': 'object', 'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}, rule='type')
+                    data__license_is_dict = isinstance(data__license, dict)
+                    if data__license_is_dict:
+                        data__license__missing_keys = set(['text']) - data__license.keys()
+                        if data__license__missing_keys:
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".license must contain " + (str(sorted(data__license__missing_keys)) + " properties"), value=data__license, name="" + (name_prefix or "data") + ".license", definition={'type': 'object', 'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}, rule='required')
+                        data__license_keys = set(data__license.keys())
+                        if "text" in data__license_keys:
+                            data__license_keys.remove("text")
+                            data__license__text = data__license["text"]
+                            if not isinstance(data__license__text, (str)):
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".license.text must be string", value=data__license__text, name="" + (name_prefix or "data") + ".license.text", definition={'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}, rule='type')
+                    data__license_one_of_count14 += 1
+                except JsonSchemaValueException: pass
+            if data__license_one_of_count14 != 1:
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".license must be valid exactly by one definition" + (" (" + str(data__license_one_of_count14) + " matches found)"), value=data__license, name="" + (name_prefix or "data") + ".license", definition={'description': '`Project license `_.', 'oneOf': [{'type': 'string', 'description': 'An SPDX license identifier', 'format': 'SPDX'}, {'type': 'object', 'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'type': 'object', 'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}]}, rule='oneOf')
+        if "license-files" in data_keys:
+            data_keys.remove("license-files")
+            data__licensefiles = data["license-files"]
+            if not isinstance(data__licensefiles, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".license-files must be array", value=data__licensefiles, name="" + (name_prefix or "data") + ".license-files", definition={'description': 'Paths or globs to paths of license files', 'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__licensefiles_is_list = isinstance(data__licensefiles, (list, tuple))
+            if data__licensefiles_is_list:
+                data__licensefiles_len = len(data__licensefiles)
+                for data__licensefiles_x, data__licensefiles_item in enumerate(data__licensefiles):
+                    if not isinstance(data__licensefiles_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".license-files[{data__licensefiles_x}]".format(**locals()) + " must be string", value=data__licensefiles_item, name="" + (name_prefix or "data") + ".license-files[{data__licensefiles_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "authors" in data_keys:
+            data_keys.remove("authors")
+            data__authors = data["authors"]
+            if not isinstance(data__authors, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".authors must be array", value=data__authors, name="" + (name_prefix or "data") + ".authors", definition={'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, '$$description': ["The people or organizations considered to be the 'authors' of the project.", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, rule='type')
+            data__authors_is_list = isinstance(data__authors, (list, tuple))
+            if data__authors_is_list:
+                data__authors_len = len(data__authors)
+                for data__authors_x, data__authors_item in enumerate(data__authors):
+                    validate_https___packaging_python_org_en_latest_specifications_pyproject_toml___definitions_author(data__authors_item, custom_formats, (name_prefix or "data") + ".authors[{data__authors_x}]".format(**locals()))
+        if "maintainers" in data_keys:
+            data_keys.remove("maintainers")
+            data__maintainers = data["maintainers"]
+            if not isinstance(data__maintainers, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".maintainers must be array", value=data__maintainers, name="" + (name_prefix or "data") + ".maintainers", definition={'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, '$$description': ["The people or organizations considered to be the 'maintainers' of the project.", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, rule='type')
+            data__maintainers_is_list = isinstance(data__maintainers, (list, tuple))
+            if data__maintainers_is_list:
+                data__maintainers_len = len(data__maintainers)
+                for data__maintainers_x, data__maintainers_item in enumerate(data__maintainers):
+                    validate_https___packaging_python_org_en_latest_specifications_pyproject_toml___definitions_author(data__maintainers_item, custom_formats, (name_prefix or "data") + ".maintainers[{data__maintainers_x}]".format(**locals()))
+        if "keywords" in data_keys:
+            data_keys.remove("keywords")
+            data__keywords = data["keywords"]
+            if not isinstance(data__keywords, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".keywords must be array", value=data__keywords, name="" + (name_prefix or "data") + ".keywords", definition={'type': 'array', 'items': {'type': 'string'}, 'description': 'List of keywords to assist searching for the distribution in a larger catalog.'}, rule='type')
+            data__keywords_is_list = isinstance(data__keywords, (list, tuple))
+            if data__keywords_is_list:
+                data__keywords_len = len(data__keywords)
+                for data__keywords_x, data__keywords_item in enumerate(data__keywords):
+                    if not isinstance(data__keywords_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".keywords[{data__keywords_x}]".format(**locals()) + " must be string", value=data__keywords_item, name="" + (name_prefix or "data") + ".keywords[{data__keywords_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "classifiers" in data_keys:
+            data_keys.remove("classifiers")
+            data__classifiers = data["classifiers"]
+            if not isinstance(data__classifiers, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".classifiers must be array", value=data__classifiers, name="" + (name_prefix or "data") + ".classifiers", definition={'type': 'array', 'items': {'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier `_.'}, '$$description': ['`Trove classifiers `_', 'which apply to the project.']}, rule='type')
+            data__classifiers_is_list = isinstance(data__classifiers, (list, tuple))
+            if data__classifiers_is_list:
+                data__classifiers_len = len(data__classifiers)
+                for data__classifiers_x, data__classifiers_item in enumerate(data__classifiers):
+                    if not isinstance(data__classifiers_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".classifiers[{data__classifiers_x}]".format(**locals()) + " must be string", value=data__classifiers_item, name="" + (name_prefix or "data") + ".classifiers[{data__classifiers_x}]".format(**locals()) + "", definition={'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier `_.'}, rule='type')
+                    if isinstance(data__classifiers_item, str):
+                        if not custom_formats["trove-classifier"](data__classifiers_item):
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".classifiers[{data__classifiers_x}]".format(**locals()) + " must be trove-classifier", value=data__classifiers_item, name="" + (name_prefix or "data") + ".classifiers[{data__classifiers_x}]".format(**locals()) + "", definition={'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier `_.'}, rule='format')
+        if "urls" in data_keys:
+            data_keys.remove("urls")
+            data__urls = data["urls"]
+            if not isinstance(data__urls, (dict)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".urls must be object", value=data__urls, name="" + (name_prefix or "data") + ".urls", definition={'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, rule='type')
+            data__urls_is_dict = isinstance(data__urls, dict)
+            if data__urls_is_dict:
+                data__urls_keys = set(data__urls.keys())
+                for data__urls_key, data__urls_val in data__urls.items():
+                    if REGEX_PATTERNS['^.+$'].search(data__urls_key):
+                        if data__urls_key in data__urls_keys:
+                            data__urls_keys.remove(data__urls_key)
+                        if not isinstance(data__urls_val, (str)):
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".urls.{data__urls_key}".format(**locals()) + " must be string", value=data__urls_val, name="" + (name_prefix or "data") + ".urls.{data__urls_key}".format(**locals()) + "", definition={'type': 'string', 'format': 'url'}, rule='type')
+                        if isinstance(data__urls_val, str):
+                            if not custom_formats["url"](data__urls_val):
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".urls.{data__urls_key}".format(**locals()) + " must be url", value=data__urls_val, name="" + (name_prefix or "data") + ".urls.{data__urls_key}".format(**locals()) + "", definition={'type': 'string', 'format': 'url'}, rule='format')
+                if data__urls_keys:
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".urls must not contain "+str(data__urls_keys)+" properties", value=data__urls, name="" + (name_prefix or "data") + ".urls", definition={'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, rule='additionalProperties')
+        if "scripts" in data_keys:
+            data_keys.remove("scripts")
+            data__scripts = data["scripts"]
+            validate_https___packaging_python_org_en_latest_specifications_pyproject_toml___definitions_entry_point_group(data__scripts, custom_formats, (name_prefix or "data") + ".scripts")
+        if "gui-scripts" in data_keys:
+            data_keys.remove("gui-scripts")
+            data__guiscripts = data["gui-scripts"]
+            validate_https___packaging_python_org_en_latest_specifications_pyproject_toml___definitions_entry_point_group(data__guiscripts, custom_formats, (name_prefix or "data") + ".gui-scripts")
+        if "entry-points" in data_keys:
+            data_keys.remove("entry-points")
+            data__entrypoints = data["entry-points"]
+            data__entrypoints_is_dict = isinstance(data__entrypoints, dict)
+            if data__entrypoints_is_dict:
+                data__entrypoints_keys = set(data__entrypoints.keys())
+                for data__entrypoints_key, data__entrypoints_val in data__entrypoints.items():
+                    if REGEX_PATTERNS['^.+$'].search(data__entrypoints_key):
+                        if data__entrypoints_key in data__entrypoints_keys:
+                            data__entrypoints_keys.remove(data__entrypoints_key)
+                        validate_https___packaging_python_org_en_latest_specifications_pyproject_toml___definitions_entry_point_group(data__entrypoints_val, custom_formats, (name_prefix or "data") + ".entry-points.{data__entrypoints_key}".format(**locals()))
+                if data__entrypoints_keys:
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".entry-points must not contain "+str(data__entrypoints_keys)+" properties", value=data__entrypoints, name="" + (name_prefix or "data") + ".entry-points", definition={'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}}}, rule='additionalProperties')
+                data__entrypoints_len = len(data__entrypoints)
+                if data__entrypoints_len != 0:
+                    data__entrypoints_property_names = True
+                    for data__entrypoints_key in data__entrypoints:
+                        try:
+                            if isinstance(data__entrypoints_key, str):
+                                if not custom_formats["python-entrypoint-group"](data__entrypoints_key):
+                                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".entry-points must be python-entrypoint-group", value=data__entrypoints_key, name="" + (name_prefix or "data") + ".entry-points", definition={'format': 'python-entrypoint-group'}, rule='format')
+                        except JsonSchemaValueException:
+                            data__entrypoints_property_names = False
+                    if not data__entrypoints_property_names:
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".entry-points must be named by propertyName definition", value=data__entrypoints, name="" + (name_prefix or "data") + ".entry-points", definition={'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}}}, rule='propertyNames')
+        if "dependencies" in data_keys:
+            data_keys.remove("dependencies")
+            data__dependencies = data["dependencies"]
+            if not isinstance(data__dependencies, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".dependencies must be array", value=data__dependencies, name="" + (name_prefix or "data") + ".dependencies", definition={'type': 'array', 'description': 'Project (mandatory) dependencies.', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}, rule='type')
+            data__dependencies_is_list = isinstance(data__dependencies, (list, tuple))
+            if data__dependencies_is_list:
+                data__dependencies_len = len(data__dependencies)
+                for data__dependencies_x, data__dependencies_item in enumerate(data__dependencies):
+                    validate_https___packaging_python_org_en_latest_specifications_pyproject_toml___definitions_dependency(data__dependencies_item, custom_formats, (name_prefix or "data") + ".dependencies[{data__dependencies_x}]".format(**locals()))
+        if "optional-dependencies" in data_keys:
+            data_keys.remove("optional-dependencies")
+            data__optionaldependencies = data["optional-dependencies"]
+            if not isinstance(data__optionaldependencies, (dict)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".optional-dependencies must be object", value=data__optionaldependencies, name="" + (name_prefix or "data") + ".optional-dependencies", definition={'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}}, rule='type')
+            data__optionaldependencies_is_dict = isinstance(data__optionaldependencies, dict)
+            if data__optionaldependencies_is_dict:
+                data__optionaldependencies_keys = set(data__optionaldependencies.keys())
+                for data__optionaldependencies_key, data__optionaldependencies_val in data__optionaldependencies.items():
+                    if REGEX_PATTERNS['^.+$'].search(data__optionaldependencies_key):
+                        if data__optionaldependencies_key in data__optionaldependencies_keys:
+                            data__optionaldependencies_keys.remove(data__optionaldependencies_key)
+                        if not isinstance(data__optionaldependencies_val, (list, tuple)):
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".optional-dependencies.{data__optionaldependencies_key}".format(**locals()) + " must be array", value=data__optionaldependencies_val, name="" + (name_prefix or "data") + ".optional-dependencies.{data__optionaldependencies_key}".format(**locals()) + "", definition={'type': 'array', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}, rule='type')
+                        data__optionaldependencies_val_is_list = isinstance(data__optionaldependencies_val, (list, tuple))
+                        if data__optionaldependencies_val_is_list:
+                            data__optionaldependencies_val_len = len(data__optionaldependencies_val)
+                            for data__optionaldependencies_val_x, data__optionaldependencies_val_item in enumerate(data__optionaldependencies_val):
+                                validate_https___packaging_python_org_en_latest_specifications_pyproject_toml___definitions_dependency(data__optionaldependencies_val_item, custom_formats, (name_prefix or "data") + ".optional-dependencies.{data__optionaldependencies_key}[{data__optionaldependencies_val_x}]".format(**locals()))
+                if data__optionaldependencies_keys:
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".optional-dependencies must not contain "+str(data__optionaldependencies_keys)+" properties", value=data__optionaldependencies, name="" + (name_prefix or "data") + ".optional-dependencies", definition={'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}}, rule='additionalProperties')
+                data__optionaldependencies_len = len(data__optionaldependencies)
+                if data__optionaldependencies_len != 0:
+                    data__optionaldependencies_property_names = True
+                    for data__optionaldependencies_key in data__optionaldependencies:
+                        try:
+                            if isinstance(data__optionaldependencies_key, str):
+                                if not custom_formats["pep508-identifier"](data__optionaldependencies_key):
+                                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".optional-dependencies must be pep508-identifier", value=data__optionaldependencies_key, name="" + (name_prefix or "data") + ".optional-dependencies", definition={'format': 'pep508-identifier'}, rule='format')
+                        except JsonSchemaValueException:
+                            data__optionaldependencies_property_names = False
+                    if not data__optionaldependencies_property_names:
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".optional-dependencies must be named by propertyName definition", value=data__optionaldependencies, name="" + (name_prefix or "data") + ".optional-dependencies", definition={'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}}, rule='propertyNames')
+        if "dynamic" in data_keys:
+            data_keys.remove("dynamic")
+            data__dynamic = data["dynamic"]
+            if not isinstance(data__dynamic, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic must be array", value=data__dynamic, name="" + (name_prefix or "data") + ".dynamic", definition={'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'license-files', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']}}, rule='type')
+            data__dynamic_is_list = isinstance(data__dynamic, (list, tuple))
+            if data__dynamic_is_list:
+                data__dynamic_len = len(data__dynamic)
+                for data__dynamic_x, data__dynamic_item in enumerate(data__dynamic):
+                    if data__dynamic_item not in ['version', 'description', 'readme', 'requires-python', 'license', 'license-files', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']:
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic[{data__dynamic_x}]".format(**locals()) + " must be one of ['version', 'description', 'readme', 'requires-python', 'license', 'license-files', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']", value=data__dynamic_item, name="" + (name_prefix or "data") + ".dynamic[{data__dynamic_x}]".format(**locals()) + "", definition={'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'license-files', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']}, rule='enum')
+        if data_keys:
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must not contain "+str(data_keys)+" properties", value=data, name="" + (name_prefix or "data") + "", definition={'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://packaging.python.org/en/latest/specifications/pyproject-toml/', 'title': 'Package metadata stored in the ``project`` table', '$$description': ['Data structure for the **project** table inside ``pyproject.toml``', '(as initially defined in :pep:`621`)'], 'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, 'version': {'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, 'description': {'type': 'string', '$$description': ['The `summary description of the project', '`_']}, 'readme': {'$$description': ['`Full/detailed description of the project in the form of a README', '`_', "with meaning similar to the one defined in `core metadata's Description", '`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, 'requires-python': {'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '`_.']}, 'license': {'description': '`Project license `_.', 'oneOf': [{'type': 'string', 'description': 'An SPDX license identifier', 'format': 'SPDX'}, {'type': 'object', 'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'type': 'object', 'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}]}, 'license-files': {'description': 'Paths or globs to paths of license files', 'type': 'array', 'items': {'type': 'string'}}, 'authors': {'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, '$$description': ["The people or organizations considered to be the 'authors' of the project.", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, 'maintainers': {'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, '$$description': ["The people or organizations considered to be the 'maintainers' of the project.", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, 'keywords': {'type': 'array', 'items': {'type': 'string'}, 'description': 'List of keywords to assist searching for the distribution in a larger catalog.'}, 'classifiers': {'type': 'array', 'items': {'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier `_.'}, '$$description': ['`Trove classifiers `_', 'which apply to the project.']}, 'urls': {'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, 'scripts': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'gui-scripts': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'entry-points': {'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}}}, 'dependencies': {'type': 'array', 'description': 'Project (mandatory) dependencies.', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}, 'optional-dependencies': {'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}}, 'dynamic': {'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'license-files', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']}}}, 'required': ['name'], 'additionalProperties': False, 'allOf': [{'if': {'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as "Required", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, 'then': {'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}}, {'if': {'required': ['license-files']}, 'then': {'properties': {'license': {'type': 'string'}}}}], 'definitions': {'author': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, 'entry-point-group': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'dependency': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}, rule='additionalProperties')
+    return data
+
+def validate_https___packaging_python_org_en_latest_specifications_pyproject_toml___definitions_dependency(data, custom_formats={}, name_prefix=None):
+    if not isinstance(data, (str)):
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be string", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}, rule='type')
+    if isinstance(data, str):
+        if not custom_formats["pep508"](data):
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must be pep508", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}, rule='format')
+    return data
+
+def validate_https___packaging_python_org_en_latest_specifications_pyproject_toml___definitions_entry_point_group(data, custom_formats={}, name_prefix=None):
+    if not isinstance(data, (dict)):
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be object", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, rule='type')
+    data_is_dict = isinstance(data, dict)
+    if data_is_dict:
+        data_keys = set(data.keys())
+        for data_key, data_val in data.items():
+            if REGEX_PATTERNS['^.+$'].search(data_key):
+                if data_key in data_keys:
+                    data_keys.remove(data_key)
+                if not isinstance(data_val, (str)):
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".{data_key}".format(**locals()) + " must be string", value=data_val, name="" + (name_prefix or "data") + ".{data_key}".format(**locals()) + "", definition={'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}, rule='type')
+                if isinstance(data_val, str):
+                    if not custom_formats["python-entrypoint-reference"](data_val):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".{data_key}".format(**locals()) + " must be python-entrypoint-reference", value=data_val, name="" + (name_prefix or "data") + ".{data_key}".format(**locals()) + "", definition={'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}, rule='format')
+        if data_keys:
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must not contain "+str(data_keys)+" properties", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, rule='additionalProperties')
+        data_len = len(data)
+        if data_len != 0:
+            data_property_names = True
+            for data_key in data:
+                try:
+                    if isinstance(data_key, str):
+                        if not custom_formats["python-entrypoint-name"](data_key):
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + " must be python-entrypoint-name", value=data_key, name="" + (name_prefix or "data") + "", definition={'format': 'python-entrypoint-name'}, rule='format')
+                except JsonSchemaValueException:
+                    data_property_names = False
+            if not data_property_names:
+                raise JsonSchemaValueException("" + (name_prefix or "data") + " must be named by propertyName definition", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, rule='propertyNames')
+    return data
+
+def validate_https___packaging_python_org_en_latest_specifications_pyproject_toml___definitions_author(data, custom_formats={}, name_prefix=None):
+    if not isinstance(data, (dict)):
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be object", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, rule='type')
+    data_is_dict = isinstance(data, dict)
+    if data_is_dict:
+        data_keys = set(data.keys())
+        if "name" in data_keys:
+            data_keys.remove("name")
+            data__name = data["name"]
+            if not isinstance(data__name, (str)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".name must be string", value=data__name, name="" + (name_prefix or "data") + ".name", definition={'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, rule='type')
+        if "email" in data_keys:
+            data_keys.remove("email")
+            data__email = data["email"]
+            if not isinstance(data__email, (str)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".email must be string", value=data__email, name="" + (name_prefix or "data") + ".email", definition={'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}, rule='type')
+            if isinstance(data__email, str):
+                if not REGEX_PATTERNS["idn-email_re_pattern"].match(data__email):
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".email must be idn-email", value=data__email, name="" + (name_prefix or "data") + ".email", definition={'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}, rule='format')
+        if data_keys:
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must not contain "+str(data_keys)+" properties", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, rule='additionalProperties')
+    return data
diff --git a/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/formats.py b/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/formats.py
new file mode 100644
index 0000000000000000000000000000000000000000..1cf4a465ef0156deef5bd4d1fc02350e40ff2fe5
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/formats.py
@@ -0,0 +1,402 @@
+"""
+The functions in this module are used to validate schemas with the
+`format JSON Schema keyword
+`_.
+
+The correspondence is given by replacing the ``_`` character in the name of the
+function with a ``-`` to obtain the format name and vice versa.
+"""
+
+import builtins
+import logging
+import os
+import re
+import string
+import typing
+from itertools import chain as _chain
+
+if typing.TYPE_CHECKING:
+    from typing_extensions import Literal
+
+_logger = logging.getLogger(__name__)
+
+# -------------------------------------------------------------------------------------
+# PEP 440
+
+VERSION_PATTERN = r"""
+    v?
+    (?:
+        (?:(?P[0-9]+)!)?                           # epoch
+        (?P[0-9]+(?:\.[0-9]+)*)                  # release segment
+        (?P
                                          # pre-release
+            [-_\.]?
+            (?Palpha|a|beta|b|preview|pre|c|rc)
+            [-_\.]?
+            (?P[0-9]+)?
+        )?
+        (?P                                         # post release
+            (?:-(?P[0-9]+))
+            |
+            (?:
+                [-_\.]?
+                (?Ppost|rev|r)
+                [-_\.]?
+                (?P[0-9]+)?
+            )
+        )?
+        (?P                                          # dev release
+            [-_\.]?
+            (?Pdev)
+            [-_\.]?
+            (?P[0-9]+)?
+        )?
+    )
+    (?:\+(?P[a-z0-9]+(?:[-_\.][a-z0-9]+)*))?       # local version
+"""
+
+VERSION_REGEX = re.compile(r"^\s*" + VERSION_PATTERN + r"\s*$", re.X | re.I)
+
+
+def pep440(version: str) -> bool:
+    """See :ref:`PyPA's version specification `
+    (initially introduced in :pep:`440`).
+    """
+    return VERSION_REGEX.match(version) is not None
+
+
+# -------------------------------------------------------------------------------------
+# PEP 508
+
+PEP508_IDENTIFIER_PATTERN = r"([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])"
+PEP508_IDENTIFIER_REGEX = re.compile(f"^{PEP508_IDENTIFIER_PATTERN}$", re.I)
+
+
+def pep508_identifier(name: str) -> bool:
+    """See :ref:`PyPA's name specification `
+    (initially introduced in :pep:`508#names`).
+    """
+    return PEP508_IDENTIFIER_REGEX.match(name) is not None
+
+
+try:
+    try:
+        from packaging import requirements as _req
+    except ImportError:  # pragma: no cover
+        # let's try setuptools vendored version
+        from setuptools._vendor.packaging import (  # type: ignore[no-redef]
+            requirements as _req,
+        )
+
+    def pep508(value: str) -> bool:
+        """See :ref:`PyPA's dependency specifiers `
+        (initially introduced in :pep:`508`).
+        """
+        try:
+            _req.Requirement(value)
+            return True
+        except _req.InvalidRequirement:
+            return False
+
+except ImportError:  # pragma: no cover
+    _logger.warning(
+        "Could not find an installation of `packaging`. Requirements, dependencies and "
+        "versions might not be validated. "
+        "To enforce validation, please install `packaging`."
+    )
+
+    def pep508(value: str) -> bool:
+        return True
+
+
+def pep508_versionspec(value: str) -> bool:
+    """Expression that can be used to specify/lock versions (including ranges)
+    See ``versionspec`` in :ref:`PyPA's dependency specifiers
+    ` (initially introduced in :pep:`508`).
+    """
+    if any(c in value for c in (";", "]", "@")):
+        # In PEP 508:
+        # conditional markers, extras and URL specs are not included in the
+        # versionspec
+        return False
+    # Let's pretend we have a dependency called `requirement` with the given
+    # version spec, then we can reuse the pep508 function for validation:
+    return pep508(f"requirement{value}")
+
+
+# -------------------------------------------------------------------------------------
+# PEP 517
+
+
+def pep517_backend_reference(value: str) -> bool:
+    """See PyPA's specification for defining build-backend references
+    introduced in :pep:`517#source-trees`.
+
+    This is similar to an entry-point reference (e.g., ``package.module:object``).
+    """
+    module, _, obj = value.partition(":")
+    identifiers = (i.strip() for i in _chain(module.split("."), obj.split(".")))
+    return all(python_identifier(i) for i in identifiers if i)
+
+
+# -------------------------------------------------------------------------------------
+# Classifiers - PEP 301
+
+
+def _download_classifiers() -> str:
+    import ssl
+    from email.message import Message
+    from urllib.request import urlopen
+
+    url = "https://pypi.org/pypi?:action=list_classifiers"
+    context = ssl.create_default_context()
+    with urlopen(url, context=context) as response:  # noqa: S310 (audit URLs)
+        headers = Message()
+        headers["content_type"] = response.getheader("content-type", "text/plain")
+        return response.read().decode(headers.get_param("charset", "utf-8"))  # type: ignore[no-any-return]
+
+
+class _TroveClassifier:
+    """The ``trove_classifiers`` package is the official way of validating classifiers,
+    however this package might not be always available.
+    As a workaround we can still download a list from PyPI.
+    We also don't want to be over strict about it, so simply skipping silently is an
+    option (classifiers will be validated anyway during the upload to PyPI).
+    """
+
+    downloaded: typing.Union[None, "Literal[False]", typing.Set[str]]
+    """
+    None => not cached yet
+    False => unavailable
+    set => cached values
+    """
+
+    def __init__(self) -> None:
+        self.downloaded = None
+        self._skip_download = False
+        self.__name__ = "trove_classifier"  # Emulate a public function
+
+    def _disable_download(self) -> None:
+        # This is a private API. Only setuptools has the consent of using it.
+        self._skip_download = True
+
+    def __call__(self, value: str) -> bool:
+        if self.downloaded is False or self._skip_download is True:
+            return True
+
+        if os.getenv("NO_NETWORK") or os.getenv("VALIDATE_PYPROJECT_NO_NETWORK"):
+            self.downloaded = False
+            msg = (
+                "Install ``trove-classifiers`` to ensure proper validation. "
+                "Skipping download of classifiers list from PyPI (NO_NETWORK)."
+            )
+            _logger.debug(msg)
+            return True
+
+        if self.downloaded is None:
+            msg = (
+                "Install ``trove-classifiers`` to ensure proper validation. "
+                "Meanwhile a list of classifiers will be downloaded from PyPI."
+            )
+            _logger.debug(msg)
+            try:
+                self.downloaded = set(_download_classifiers().splitlines())
+            except Exception:
+                self.downloaded = False
+                _logger.debug("Problem with download, skipping validation")
+                return True
+
+        return value in self.downloaded or value.lower().startswith("private ::")
+
+
+try:
+    from trove_classifiers import classifiers as _trove_classifiers
+
+    def trove_classifier(value: str) -> bool:
+        """See https://pypi.org/classifiers/"""
+        return value in _trove_classifiers or value.lower().startswith("private ::")
+
+except ImportError:  # pragma: no cover
+    trove_classifier = _TroveClassifier()
+
+
+# -------------------------------------------------------------------------------------
+# Stub packages - PEP 561
+
+
+def pep561_stub_name(value: str) -> bool:
+    """Name of a directory containing type stubs.
+    It must follow the name scheme ``-stubs`` as defined in
+    :pep:`561#stub-only-packages`.
+    """
+    top, *children = value.split(".")
+    if not top.endswith("-stubs"):
+        return False
+    return python_module_name(".".join([top[: -len("-stubs")], *children]))
+
+
+# -------------------------------------------------------------------------------------
+# Non-PEP related
+
+
+def url(value: str) -> bool:
+    """Valid URL (validation uses :obj:`urllib.parse`).
+    For maximum compatibility please make sure to include a ``scheme`` prefix
+    in your URL (e.g. ``http://``).
+    """
+    from urllib.parse import urlparse
+
+    try:
+        parts = urlparse(value)
+        if not parts.scheme:
+            _logger.warning(
+                "For maximum compatibility please make sure to include a "
+                "`scheme` prefix in your URL (e.g. 'http://'). "
+                f"Given value: {value}"
+            )
+            if not (value.startswith("/") or value.startswith("\\") or "@" in value):
+                parts = urlparse(f"http://{value}")
+
+        return bool(parts.scheme and parts.netloc)
+    except Exception:
+        return False
+
+
+# https://packaging.python.org/specifications/entry-points/
+ENTRYPOINT_PATTERN = r"[^\[\s=]([^=]*[^\s=])?"
+ENTRYPOINT_REGEX = re.compile(f"^{ENTRYPOINT_PATTERN}$", re.I)
+RECOMMEDED_ENTRYPOINT_PATTERN = r"[\w.-]+"
+RECOMMEDED_ENTRYPOINT_REGEX = re.compile(f"^{RECOMMEDED_ENTRYPOINT_PATTERN}$", re.I)
+ENTRYPOINT_GROUP_PATTERN = r"\w+(\.\w+)*"
+ENTRYPOINT_GROUP_REGEX = re.compile(f"^{ENTRYPOINT_GROUP_PATTERN}$", re.I)
+
+
+def python_identifier(value: str) -> bool:
+    """Can be used as identifier in Python.
+    (Validation uses :obj:`str.isidentifier`).
+    """
+    return value.isidentifier()
+
+
+def python_qualified_identifier(value: str) -> bool:
+    """
+    Python "dotted identifier", i.e. a sequence of :obj:`python_identifier`
+    concatenated with ``"."`` (e.g.: ``package.module.submodule``).
+    """
+    if value.startswith(".") or value.endswith("."):
+        return False
+    return all(python_identifier(m) for m in value.split("."))
+
+
+def python_module_name(value: str) -> bool:
+    """Module name that can be used in an ``import``-statement in Python.
+    See :obj:`python_qualified_identifier`.
+    """
+    return python_qualified_identifier(value)
+
+
+def python_module_name_relaxed(value: str) -> bool:
+    """Similar to :obj:`python_module_name`, but relaxed to also accept
+    dash characters (``-``) and cover special cases like ``pip-run``.
+
+    It is recommended, however, that beginners avoid dash characters,
+    as they require advanced knowledge about Python internals.
+
+    The following are disallowed:
+
+    * names starting/ending in dashes,
+    * names ending in ``-stubs`` (potentially collide with :obj:`pep561_stub_name`).
+    """
+    if value.startswith("-") or value.endswith("-"):
+        return False
+    if value.endswith("-stubs"):
+        return False  # Avoid collision with PEP 561
+    return python_module_name(value.replace("-", "_"))
+
+
+def python_entrypoint_group(value: str) -> bool:
+    """See ``Data model > group`` in the :ref:`PyPA's entry-points specification
+    `.
+    """
+    return ENTRYPOINT_GROUP_REGEX.match(value) is not None
+
+
+def python_entrypoint_name(value: str) -> bool:
+    """See ``Data model > name`` in the :ref:`PyPA's entry-points specification
+    `.
+    """
+    if not ENTRYPOINT_REGEX.match(value):
+        return False
+    if not RECOMMEDED_ENTRYPOINT_REGEX.match(value):
+        msg = f"Entry point `{value}` does not follow recommended pattern: "
+        msg += RECOMMEDED_ENTRYPOINT_PATTERN
+        _logger.warning(msg)
+    return True
+
+
+def python_entrypoint_reference(value: str) -> bool:
+    """Reference to a Python object using in the format::
+
+        importable.module:object.attr
+
+    See ``Data model >object reference`` in the :ref:`PyPA's entry-points specification
+    `.
+    """
+    module, _, rest = value.partition(":")
+    if "[" in rest:
+        obj, _, extras_ = rest.partition("[")
+        if extras_.strip()[-1] != "]":
+            return False
+        extras = (x.strip() for x in extras_.strip(string.whitespace + "[]").split(","))
+        if not all(pep508_identifier(e) for e in extras):
+            return False
+        _logger.warning(f"`{value}` - using extras for entry points is not recommended")
+    else:
+        obj = rest
+
+    module_parts = module.split(".")
+    identifiers = _chain(module_parts, obj.split(".")) if rest else iter(module_parts)
+    return all(python_identifier(i.strip()) for i in identifiers)
+
+
+def uint8(value: builtins.int) -> bool:
+    r"""Unsigned 8-bit integer (:math:`0 \leq x < 2^8`)"""
+    return 0 <= value < 2**8
+
+
+def uint16(value: builtins.int) -> bool:
+    r"""Unsigned 16-bit integer (:math:`0 \leq x < 2^{16}`)"""
+    return 0 <= value < 2**16
+
+
+def uint(value: builtins.int) -> bool:
+    r"""Unsigned 64-bit integer (:math:`0 \leq x < 2^{64}`)"""
+    return 0 <= value < 2**64
+
+
+def int(value: builtins.int) -> bool:
+    r"""Signed 64-bit integer (:math:`-2^{63} \leq x < 2^{63}`)"""
+    return -(2**63) <= value < 2**63
+
+
+try:
+    from packaging import licenses as _licenses
+
+    def SPDX(value: str) -> bool:
+        """See :ref:`PyPA's License-Expression specification
+        ` (added in :pep:`639`).
+        """
+        try:
+            _licenses.canonicalize_license_expression(value)
+            return True
+        except _licenses.InvalidLicenseExpression:
+            return False
+
+except ImportError:  # pragma: no cover
+    _logger.warning(
+        "Could not find an up-to-date installation of `packaging`. "
+        "License expressions might not be validated. "
+        "To enforce validation, please install `packaging>=24.2`."
+    )
+
+    def SPDX(value: str) -> bool:
+        return True
diff --git a/.venv/lib/python3.12/site-packages/setuptools/config/distutils.schema.json b/.venv/lib/python3.12/site-packages/setuptools/config/distutils.schema.json
new file mode 100644
index 0000000000000000000000000000000000000000..93cd2e868acdaf41bf8b1f77026e84c02a5af3f8
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/config/distutils.schema.json
@@ -0,0 +1,26 @@
+{
+  "$schema": "http://json-schema.org/draft-07/schema#",
+
+  "$id": "https://setuptools.pypa.io/en/latest/deprecated/distutils/configfile.html",
+  "title": "``tool.distutils`` table",
+  "$$description": [
+    "**EXPERIMENTAL** (NOT OFFICIALLY SUPPORTED): Use ``tool.distutils``",
+    "subtables to configure arguments for ``distutils`` commands.",
+    "Originally, ``distutils`` allowed developers to configure arguments for",
+    "``setup.py`` commands via `distutils configuration files",
+    "`_.",
+    "See also `the old Python docs _`."
+  ],
+
+  "type": "object",
+  "properties": {
+    "global": {
+      "type": "object",
+      "description": "Global options applied to all ``distutils`` commands"
+    }
+  },
+  "patternProperties": {
+    ".+": {"type": "object"}
+  },
+  "$comment": "TODO: Is there a practical way of making this schema more specific?"
+}
diff --git a/.venv/lib/python3.12/site-packages/setuptools/config/expand.py b/.venv/lib/python3.12/site-packages/setuptools/config/expand.py
new file mode 100644
index 0000000000000000000000000000000000000000..531f965013031a8c5159c8b8505c38cfb0a4302f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/config/expand.py
@@ -0,0 +1,452 @@
+"""Utility functions to expand configuration directives or special values
+(such glob patterns).
+
+We can split the process of interpreting configuration files into 2 steps:
+
+1. The parsing the file contents from strings to value objects
+   that can be understand by Python (for example a string with a comma
+   separated list of keywords into an actual Python list of strings).
+
+2. The expansion (or post-processing) of these values according to the
+   semantics ``setuptools`` assign to them (for example a configuration field
+   with the ``file:`` directive should be expanded from a list of file paths to
+   a single string with the contents of those files concatenated)
+
+This module focus on the second step, and therefore allow sharing the expansion
+functions among several configuration file formats.
+
+**PRIVATE MODULE**: API reserved for setuptools internal usage only.
+"""
+
+from __future__ import annotations
+
+import ast
+import importlib
+import os
+import pathlib
+import sys
+from collections.abc import Iterable, Iterator, Mapping
+from configparser import ConfigParser
+from glob import iglob
+from importlib.machinery import ModuleSpec, all_suffixes
+from itertools import chain
+from pathlib import Path
+from types import ModuleType, TracebackType
+from typing import TYPE_CHECKING, Any, Callable, TypeVar
+
+from .. import _static
+from .._path import StrPath, same_path as _same_path
+from ..discovery import find_package_path
+from ..warnings import SetuptoolsWarning
+
+from distutils.errors import DistutilsOptionError
+
+if TYPE_CHECKING:
+    from typing_extensions import Self
+
+    from setuptools.dist import Distribution
+
+_K = TypeVar("_K")
+_V_co = TypeVar("_V_co", covariant=True)
+
+
+class StaticModule:
+    """Proxy to a module object that avoids executing arbitrary code."""
+
+    def __init__(self, name: str, spec: ModuleSpec) -> None:
+        module = ast.parse(pathlib.Path(spec.origin).read_bytes())  # type: ignore[arg-type] # Let it raise an error on None
+        vars(self).update(locals())
+        del self.self
+
+    def _find_assignments(self) -> Iterator[tuple[ast.AST, ast.AST]]:
+        for statement in self.module.body:
+            if isinstance(statement, ast.Assign):
+                yield from ((target, statement.value) for target in statement.targets)
+            elif isinstance(statement, ast.AnnAssign) and statement.value:
+                yield (statement.target, statement.value)
+
+    def __getattr__(self, attr: str):
+        """Attempt to load an attribute "statically", via :func:`ast.literal_eval`."""
+        try:
+            return next(
+                ast.literal_eval(value)
+                for target, value in self._find_assignments()
+                if isinstance(target, ast.Name) and target.id == attr
+            )
+        except Exception as e:
+            raise AttributeError(f"{self.name} has no attribute {attr}") from e
+
+
+def glob_relative(
+    patterns: Iterable[str], root_dir: StrPath | None = None
+) -> list[str]:
+    """Expand the list of glob patterns, but preserving relative paths.
+
+    :param list[str] patterns: List of glob patterns
+    :param str root_dir: Path to which globs should be relative
+                         (current directory by default)
+    :rtype: list
+    """
+    glob_characters = {'*', '?', '[', ']', '{', '}'}
+    expanded_values = []
+    root_dir = root_dir or os.getcwd()
+    for value in patterns:
+        # Has globby characters?
+        if any(char in value for char in glob_characters):
+            # then expand the glob pattern while keeping paths *relative*:
+            glob_path = os.path.abspath(os.path.join(root_dir, value))
+            expanded_values.extend(
+                sorted(
+                    os.path.relpath(path, root_dir).replace(os.sep, "/")
+                    for path in iglob(glob_path, recursive=True)
+                )
+            )
+
+        else:
+            # take the value as-is
+            path = os.path.relpath(value, root_dir).replace(os.sep, "/")
+            expanded_values.append(path)
+
+    return expanded_values
+
+
+def read_files(
+    filepaths: StrPath | Iterable[StrPath], root_dir: StrPath | None = None
+) -> str:
+    """Return the content of the files concatenated using ``\n`` as str
+
+    This function is sandboxed and won't reach anything outside ``root_dir``
+
+    (By default ``root_dir`` is the current directory).
+    """
+    from more_itertools import always_iterable
+
+    root_dir = os.path.abspath(root_dir or os.getcwd())
+    _filepaths = (os.path.join(root_dir, path) for path in always_iterable(filepaths))
+    return '\n'.join(
+        _read_file(path)
+        for path in _filter_existing_files(_filepaths)
+        if _assert_local(path, root_dir)
+    )
+
+
+def _filter_existing_files(filepaths: Iterable[StrPath]) -> Iterator[StrPath]:
+    for path in filepaths:
+        if os.path.isfile(path):
+            yield path
+        else:
+            SetuptoolsWarning.emit(f"File {path!r} cannot be found")
+
+
+def _read_file(filepath: bytes | StrPath) -> str:
+    with open(filepath, encoding='utf-8') as f:
+        return f.read()
+
+
+def _assert_local(filepath: StrPath, root_dir: str):
+    if Path(os.path.abspath(root_dir)) not in Path(os.path.abspath(filepath)).parents:
+        msg = f"Cannot access {filepath!r} (or anything outside {root_dir!r})"
+        raise DistutilsOptionError(msg)
+
+    return True
+
+
+def read_attr(
+    attr_desc: str,
+    package_dir: Mapping[str, str] | None = None,
+    root_dir: StrPath | None = None,
+) -> Any:
+    """Reads the value of an attribute from a module.
+
+    This function will try to read the attributed statically first
+    (via :func:`ast.literal_eval`), and only evaluate the module if it fails.
+
+    Examples:
+        read_attr("package.attr")
+        read_attr("package.module.attr")
+
+    :param str attr_desc: Dot-separated string describing how to reach the
+        attribute (see examples above)
+    :param dict[str, str] package_dir: Mapping of package names to their
+        location in disk (represented by paths relative to ``root_dir``).
+    :param str root_dir: Path to directory containing all the packages in
+        ``package_dir`` (current directory by default).
+    :rtype: str
+    """
+    root_dir = root_dir or os.getcwd()
+    attrs_path = attr_desc.strip().split('.')
+    attr_name = attrs_path.pop()
+    module_name = '.'.join(attrs_path)
+    module_name = module_name or '__init__'
+    path = _find_module(module_name, package_dir, root_dir)
+    spec = _find_spec(module_name, path)
+
+    try:
+        value = getattr(StaticModule(module_name, spec), attr_name)
+        # XXX: Is marking as static contents coming from modules too optimistic?
+        return _static.attempt_conversion(value)
+    except Exception:
+        # fallback to evaluate module
+        module = _load_spec(spec, module_name)
+        return getattr(module, attr_name)
+
+
+def _find_spec(module_name: str, module_path: StrPath | None) -> ModuleSpec:
+    spec = importlib.util.spec_from_file_location(module_name, module_path)
+    spec = spec or importlib.util.find_spec(module_name)
+
+    if spec is None:
+        raise ModuleNotFoundError(module_name)
+
+    return spec
+
+
+def _load_spec(spec: ModuleSpec, module_name: str) -> ModuleType:
+    name = getattr(spec, "__name__", module_name)
+    if name in sys.modules:
+        return sys.modules[name]
+    module = importlib.util.module_from_spec(spec)
+    sys.modules[name] = module  # cache (it also ensures `==` works on loaded items)
+    assert spec.loader is not None
+    spec.loader.exec_module(module)
+    return module
+
+
+def _find_module(
+    module_name: str, package_dir: Mapping[str, str] | None, root_dir: StrPath
+) -> str | None:
+    """Find the path to the module named ``module_name``,
+    considering the ``package_dir`` in the build configuration and ``root_dir``.
+
+    >>> tmp = getfixture('tmpdir')
+    >>> _ = tmp.ensure("a/b/c.py")
+    >>> _ = tmp.ensure("a/b/d/__init__.py")
+    >>> r = lambda x: x.replace(str(tmp), "tmp").replace(os.sep, "/")
+    >>> r(_find_module("a.b.c", None, tmp))
+    'tmp/a/b/c.py'
+    >>> r(_find_module("f.g.h", {"": "1", "f": "2", "f.g": "3", "f.g.h": "a/b/d"}, tmp))
+    'tmp/a/b/d/__init__.py'
+    """
+    path_start = find_package_path(module_name, package_dir or {}, root_dir)
+    candidates = chain.from_iterable(
+        (f"{path_start}{ext}", os.path.join(path_start, f"__init__{ext}"))
+        for ext in all_suffixes()
+    )
+    return next((x for x in candidates if os.path.isfile(x)), None)
+
+
+def resolve_class(
+    qualified_class_name: str,
+    package_dir: Mapping[str, str] | None = None,
+    root_dir: StrPath | None = None,
+) -> Callable:
+    """Given a qualified class name, return the associated class object"""
+    root_dir = root_dir or os.getcwd()
+    idx = qualified_class_name.rfind('.')
+    class_name = qualified_class_name[idx + 1 :]
+    pkg_name = qualified_class_name[:idx]
+
+    path = _find_module(pkg_name, package_dir, root_dir)
+    module = _load_spec(_find_spec(pkg_name, path), pkg_name)
+    return getattr(module, class_name)
+
+
+def cmdclass(
+    values: dict[str, str],
+    package_dir: Mapping[str, str] | None = None,
+    root_dir: StrPath | None = None,
+) -> dict[str, Callable]:
+    """Given a dictionary mapping command names to strings for qualified class
+    names, apply :func:`resolve_class` to the dict values.
+    """
+    return {k: resolve_class(v, package_dir, root_dir) for k, v in values.items()}
+
+
+def find_packages(
+    *,
+    namespaces=True,
+    fill_package_dir: dict[str, str] | None = None,
+    root_dir: StrPath | None = None,
+    **kwargs,
+) -> list[str]:
+    """Works similarly to :func:`setuptools.find_packages`, but with all
+    arguments given as keyword arguments. Moreover, ``where`` can be given
+    as a list (the results will be simply concatenated).
+
+    When the additional keyword argument ``namespaces`` is ``True``, it will
+    behave like :func:`setuptools.find_namespace_packages`` (i.e. include
+    implicit namespaces as per :pep:`420`).
+
+    The ``where`` argument will be considered relative to ``root_dir`` (or the current
+    working directory when ``root_dir`` is not given).
+
+    If the ``fill_package_dir`` argument is passed, this function will consider it as a
+    similar data structure to the ``package_dir`` configuration parameter add fill-in
+    any missing package location.
+
+    :rtype: list
+    """
+    from more_itertools import always_iterable, unique_everseen
+
+    from setuptools.discovery import construct_package_dir
+
+    # check "not namespaces" first due to python/mypy#6232
+    if not namespaces:
+        from setuptools.discovery import PackageFinder
+    else:
+        from setuptools.discovery import PEP420PackageFinder as PackageFinder
+
+    root_dir = root_dir or os.curdir
+    where = kwargs.pop('where', ['.'])
+    packages: list[str] = []
+    fill_package_dir = {} if fill_package_dir is None else fill_package_dir
+    search = list(unique_everseen(always_iterable(where)))
+
+    if len(search) == 1 and all(not _same_path(search[0], x) for x in (".", root_dir)):
+        fill_package_dir.setdefault("", search[0])
+
+    for path in search:
+        package_path = _nest_path(root_dir, path)
+        pkgs = PackageFinder.find(package_path, **kwargs)
+        packages.extend(pkgs)
+        if pkgs and not (
+            fill_package_dir.get("") == path or os.path.samefile(package_path, root_dir)
+        ):
+            fill_package_dir.update(construct_package_dir(pkgs, path))
+
+    return packages
+
+
+def _nest_path(parent: StrPath, path: StrPath) -> str:
+    path = parent if path in {".", ""} else os.path.join(parent, path)
+    return os.path.normpath(path)
+
+
+def version(value: Callable | Iterable[str | int] | str) -> str:
+    """When getting the version directly from an attribute,
+    it should be normalised to string.
+    """
+    _value = value() if callable(value) else value
+
+    if isinstance(_value, str):
+        return _value
+    if hasattr(_value, '__iter__'):
+        return '.'.join(map(str, _value))
+    return f'{_value}'
+
+
+def canonic_package_data(package_data: dict) -> dict:
+    if "*" in package_data:
+        package_data[""] = package_data.pop("*")
+    return package_data
+
+
+def canonic_data_files(
+    data_files: list | dict, root_dir: StrPath | None = None
+) -> list[tuple[str, list[str]]]:
+    """For compatibility with ``setup.py``, ``data_files`` should be a list
+    of pairs instead of a dict.
+
+    This function also expands glob patterns.
+    """
+    if isinstance(data_files, list):
+        return data_files
+
+    return [
+        (dest, glob_relative(patterns, root_dir))
+        for dest, patterns in data_files.items()
+    ]
+
+
+def entry_points(
+    text: str, text_source: str = "entry-points"
+) -> dict[str, dict[str, str]]:
+    """Given the contents of entry-points file,
+    process it into a 2-level dictionary (``dict[str, dict[str, str]]``).
+    The first level keys are entry-point groups, the second level keys are
+    entry-point names, and the second level values are references to objects
+    (that correspond to the entry-point value).
+    """
+    # Using undocumented behaviour, see python/typeshed#12700
+    parser = ConfigParser(default_section=None, delimiters=("=",))  # type: ignore[call-overload]
+    parser.optionxform = str  # case sensitive
+    parser.read_string(text, text_source)
+    groups = {k: dict(v.items()) for k, v in parser.items()}
+    groups.pop(parser.default_section, None)
+    return groups
+
+
+class EnsurePackagesDiscovered:
+    """Some expand functions require all the packages to already be discovered before
+    they run, e.g. :func:`read_attr`, :func:`resolve_class`, :func:`cmdclass`.
+
+    Therefore in some cases we will need to run autodiscovery during the evaluation of
+    the configuration. However, it is better to postpone calling package discovery as
+    much as possible, because some parameters can influence it (e.g. ``package_dir``),
+    and those might not have been processed yet.
+    """
+
+    def __init__(self, distribution: Distribution) -> None:
+        self._dist = distribution
+        self._called = False
+
+    def __call__(self):
+        """Trigger the automatic package discovery, if it is still necessary."""
+        if not self._called:
+            self._called = True
+            self._dist.set_defaults(name=False)  # Skip name, we can still be parsing
+
+    def __enter__(self) -> Self:
+        return self
+
+    def __exit__(
+        self,
+        exc_type: type[BaseException] | None,
+        exc_value: BaseException | None,
+        traceback: TracebackType | None,
+    ):
+        if self._called:
+            self._dist.set_defaults.analyse_name()  # Now we can set a default name
+
+    def _get_package_dir(self) -> Mapping[str, str]:
+        self()
+        pkg_dir = self._dist.package_dir
+        return {} if pkg_dir is None else pkg_dir
+
+    @property
+    def package_dir(self) -> Mapping[str, str]:
+        """Proxy to ``package_dir`` that may trigger auto-discovery when used."""
+        return LazyMappingProxy(self._get_package_dir)
+
+
+class LazyMappingProxy(Mapping[_K, _V_co]):
+    """Mapping proxy that delays resolving the target object, until really needed.
+
+    >>> def obtain_mapping():
+    ...     print("Running expensive function!")
+    ...     return {"key": "value", "other key": "other value"}
+    >>> mapping = LazyMappingProxy(obtain_mapping)
+    >>> mapping["key"]
+    Running expensive function!
+    'value'
+    >>> mapping["other key"]
+    'other value'
+    """
+
+    def __init__(self, obtain_mapping_value: Callable[[], Mapping[_K, _V_co]]) -> None:
+        self._obtain = obtain_mapping_value
+        self._value: Mapping[_K, _V_co] | None = None
+
+    def _target(self) -> Mapping[_K, _V_co]:
+        if self._value is None:
+            self._value = self._obtain()
+        return self._value
+
+    def __getitem__(self, key: _K) -> _V_co:
+        return self._target()[key]
+
+    def __len__(self) -> int:
+        return len(self._target())
+
+    def __iter__(self) -> Iterator[_K]:
+        return iter(self._target())
diff --git a/.venv/lib/python3.12/site-packages/setuptools/config/pyprojecttoml.py b/.venv/lib/python3.12/site-packages/setuptools/config/pyprojecttoml.py
new file mode 100644
index 0000000000000000000000000000000000000000..fd6c5968c820435a0a8a82ecfacbe94abd7e8d3d
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/config/pyprojecttoml.py
@@ -0,0 +1,468 @@
+"""
+Load setuptools configuration from ``pyproject.toml`` files.
+
+**PRIVATE MODULE**: API reserved for setuptools internal usage only.
+
+To read project metadata, consider using
+``build.util.project_wheel_metadata`` (https://pypi.org/project/build/).
+For simple scenarios, you can also try parsing the file directly
+with the help of ``tomllib`` or ``tomli``.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+from collections.abc import Mapping
+from contextlib import contextmanager
+from functools import partial
+from types import TracebackType
+from typing import TYPE_CHECKING, Any, Callable
+
+from .._path import StrPath
+from ..errors import FileError, InvalidConfigError
+from ..warnings import SetuptoolsWarning
+from . import expand as _expand
+from ._apply_pyprojecttoml import _PREVIOUSLY_DEFINED, _MissingDynamic, apply as _apply
+
+if TYPE_CHECKING:
+    from typing_extensions import Self
+
+    from setuptools.dist import Distribution
+
+_logger = logging.getLogger(__name__)
+
+
+def load_file(filepath: StrPath) -> dict:
+    from ..compat.py310 import tomllib
+
+    with open(filepath, "rb") as file:
+        return tomllib.load(file)
+
+
+def validate(config: dict, filepath: StrPath) -> bool:
+    from . import _validate_pyproject as validator
+
+    trove_classifier = validator.FORMAT_FUNCTIONS.get("trove-classifier")
+    if hasattr(trove_classifier, "_disable_download"):
+        # Improve reproducibility by default. See abravalheri/validate-pyproject#31
+        trove_classifier._disable_download()  # type: ignore[union-attr]
+
+    try:
+        return validator.validate(config)
+    except validator.ValidationError as ex:
+        summary = f"configuration error: {ex.summary}"
+        if ex.name.strip("`") != "project":
+            # Probably it is just a field missing/misnamed, not worthy the verbosity...
+            _logger.debug(summary)
+            _logger.debug(ex.details)
+
+        error = f"invalid pyproject.toml config: {ex.name}."
+        raise ValueError(f"{error}\n{summary}") from None
+
+
+def apply_configuration(
+    dist: Distribution,
+    filepath: StrPath,
+    ignore_option_errors: bool = False,
+) -> Distribution:
+    """Apply the configuration from a ``pyproject.toml`` file into an existing
+    distribution object.
+    """
+    config = read_configuration(filepath, True, ignore_option_errors, dist)
+    return _apply(dist, config, filepath)
+
+
+def read_configuration(
+    filepath: StrPath,
+    expand: bool = True,
+    ignore_option_errors: bool = False,
+    dist: Distribution | None = None,
+) -> dict[str, Any]:
+    """Read given configuration file and returns options from it as a dict.
+
+    :param str|unicode filepath: Path to configuration file in the ``pyproject.toml``
+        format.
+
+    :param bool expand: Whether to expand directives and other computed values
+        (i.e. post-process the given configuration)
+
+    :param bool ignore_option_errors: Whether to silently ignore
+        options, values of which could not be resolved (e.g. due to exceptions
+        in directives such as file:, attr:, etc.).
+        If False exceptions are propagated as expected.
+
+    :param Distribution|None: Distribution object to which the configuration refers.
+        If not given a dummy object will be created and discarded after the
+        configuration is read. This is used for auto-discovery of packages and in the
+        case a dynamic configuration (e.g. ``attr`` or ``cmdclass``) is expanded.
+        When ``expand=False`` this object is simply ignored.
+
+    :rtype: dict
+    """
+    filepath = os.path.abspath(filepath)
+
+    if not os.path.isfile(filepath):
+        raise FileError(f"Configuration file {filepath!r} does not exist.")
+
+    asdict = load_file(filepath) or {}
+    project_table = asdict.get("project", {})
+    tool_table = asdict.get("tool", {})
+    setuptools_table = tool_table.get("setuptools", {})
+    if not asdict or not (project_table or setuptools_table):
+        return {}  # User is not using pyproject to configure setuptools
+
+    if "setuptools" in asdict.get("tools", {}):
+        # let the user know they probably have a typo in their metadata
+        _ToolsTypoInMetadata.emit()
+
+    if "distutils" in tool_table:
+        _ExperimentalConfiguration.emit(subject="[tool.distutils]")
+
+    # There is an overall sense in the community that making include_package_data=True
+    # the default would be an improvement.
+    # `ini2toml` backfills include_package_data=False when nothing is explicitly given,
+    # therefore setting a default here is backwards compatible.
+    if dist and dist.include_package_data is not None:
+        setuptools_table.setdefault("include-package-data", dist.include_package_data)
+    else:
+        setuptools_table.setdefault("include-package-data", True)
+    # Persist changes:
+    asdict["tool"] = tool_table
+    tool_table["setuptools"] = setuptools_table
+
+    if "ext-modules" in setuptools_table:
+        _ExperimentalConfiguration.emit(subject="[tool.setuptools.ext-modules]")
+
+    with _ignore_errors(ignore_option_errors):
+        # Don't complain about unrelated errors (e.g. tools not using the "tool" table)
+        subset = {"project": project_table, "tool": {"setuptools": setuptools_table}}
+        validate(subset, filepath)
+
+    if expand:
+        root_dir = os.path.dirname(filepath)
+        return expand_configuration(asdict, root_dir, ignore_option_errors, dist)
+
+    return asdict
+
+
+def expand_configuration(
+    config: dict,
+    root_dir: StrPath | None = None,
+    ignore_option_errors: bool = False,
+    dist: Distribution | None = None,
+) -> dict:
+    """Given a configuration with unresolved fields (e.g. dynamic, cmdclass, ...)
+    find their final values.
+
+    :param dict config: Dict containing the configuration for the distribution
+    :param str root_dir: Top-level directory for the distribution/project
+        (the same directory where ``pyproject.toml`` is place)
+    :param bool ignore_option_errors: see :func:`read_configuration`
+    :param Distribution|None: Distribution object to which the configuration refers.
+        If not given a dummy object will be created and discarded after the
+        configuration is read. Used in the case a dynamic configuration
+        (e.g. ``attr`` or ``cmdclass``).
+
+    :rtype: dict
+    """
+    return _ConfigExpander(config, root_dir, ignore_option_errors, dist).expand()
+
+
+class _ConfigExpander:
+    def __init__(
+        self,
+        config: dict,
+        root_dir: StrPath | None = None,
+        ignore_option_errors: bool = False,
+        dist: Distribution | None = None,
+    ) -> None:
+        self.config = config
+        self.root_dir = root_dir or os.getcwd()
+        self.project_cfg = config.get("project", {})
+        self.dynamic = self.project_cfg.get("dynamic", [])
+        self.setuptools_cfg = config.get("tool", {}).get("setuptools", {})
+        self.dynamic_cfg = self.setuptools_cfg.get("dynamic", {})
+        self.ignore_option_errors = ignore_option_errors
+        self._dist = dist
+        self._referenced_files = set[str]()
+
+    def _ensure_dist(self) -> Distribution:
+        from setuptools.dist import Distribution
+
+        attrs = {"src_root": self.root_dir, "name": self.project_cfg.get("name", None)}
+        return self._dist or Distribution(attrs)
+
+    def _process_field(self, container: dict, field: str, fn: Callable):
+        if field in container:
+            with _ignore_errors(self.ignore_option_errors):
+                container[field] = fn(container[field])
+
+    def _canonic_package_data(self, field="package-data"):
+        package_data = self.setuptools_cfg.get(field, {})
+        return _expand.canonic_package_data(package_data)
+
+    def expand(self):
+        self._expand_packages()
+        self._canonic_package_data()
+        self._canonic_package_data("exclude-package-data")
+
+        # A distribution object is required for discovering the correct package_dir
+        dist = self._ensure_dist()
+        ctx = _EnsurePackagesDiscovered(dist, self.project_cfg, self.setuptools_cfg)
+        with ctx as ensure_discovered:
+            package_dir = ensure_discovered.package_dir
+            self._expand_data_files()
+            self._expand_cmdclass(package_dir)
+            self._expand_all_dynamic(dist, package_dir)
+
+        dist._referenced_files.update(self._referenced_files)
+        return self.config
+
+    def _expand_packages(self):
+        packages = self.setuptools_cfg.get("packages")
+        if packages is None or isinstance(packages, (list, tuple)):
+            return
+
+        find = packages.get("find")
+        if isinstance(find, dict):
+            find["root_dir"] = self.root_dir
+            find["fill_package_dir"] = self.setuptools_cfg.setdefault("package-dir", {})
+            with _ignore_errors(self.ignore_option_errors):
+                self.setuptools_cfg["packages"] = _expand.find_packages(**find)
+
+    def _expand_data_files(self):
+        data_files = partial(_expand.canonic_data_files, root_dir=self.root_dir)
+        self._process_field(self.setuptools_cfg, "data-files", data_files)
+
+    def _expand_cmdclass(self, package_dir: Mapping[str, str]):
+        root_dir = self.root_dir
+        cmdclass = partial(_expand.cmdclass, package_dir=package_dir, root_dir=root_dir)
+        self._process_field(self.setuptools_cfg, "cmdclass", cmdclass)
+
+    def _expand_all_dynamic(self, dist: Distribution, package_dir: Mapping[str, str]):
+        special = (  # need special handling
+            "version",
+            "readme",
+            "entry-points",
+            "scripts",
+            "gui-scripts",
+            "classifiers",
+            "dependencies",
+            "optional-dependencies",
+        )
+        # `_obtain` functions are assumed to raise appropriate exceptions/warnings.
+        obtained_dynamic = {
+            field: self._obtain(dist, field, package_dir)
+            for field in self.dynamic
+            if field not in special
+        }
+        obtained_dynamic.update(
+            self._obtain_entry_points(dist, package_dir) or {},
+            version=self._obtain_version(dist, package_dir),
+            readme=self._obtain_readme(dist),
+            classifiers=self._obtain_classifiers(dist),
+            dependencies=self._obtain_dependencies(dist),
+            optional_dependencies=self._obtain_optional_dependencies(dist),
+        )
+        # `None` indicates there is nothing in `tool.setuptools.dynamic` but the value
+        # might have already been set by setup.py/extensions, so avoid overwriting.
+        updates = {k: v for k, v in obtained_dynamic.items() if v is not None}
+        self.project_cfg.update(updates)
+
+    def _ensure_previously_set(self, dist: Distribution, field: str):
+        previous = _PREVIOUSLY_DEFINED[field](dist)
+        if previous is None and not self.ignore_option_errors:
+            msg = (
+                f"No configuration found for dynamic {field!r}.\n"
+                "Some dynamic fields need to be specified via `tool.setuptools.dynamic`"
+                "\nothers must be specified via the equivalent attribute in `setup.py`."
+            )
+            raise InvalidConfigError(msg)
+
+    def _expand_directive(
+        self, specifier: str, directive, package_dir: Mapping[str, str]
+    ):
+        from more_itertools import always_iterable
+
+        with _ignore_errors(self.ignore_option_errors):
+            root_dir = self.root_dir
+            if "file" in directive:
+                self._referenced_files.update(always_iterable(directive["file"]))
+                return _expand.read_files(directive["file"], root_dir)
+            if "attr" in directive:
+                return _expand.read_attr(directive["attr"], package_dir, root_dir)
+            raise ValueError(f"invalid `{specifier}`: {directive!r}")
+        return None
+
+    def _obtain(self, dist: Distribution, field: str, package_dir: Mapping[str, str]):
+        if field in self.dynamic_cfg:
+            return self._expand_directive(
+                f"tool.setuptools.dynamic.{field}",
+                self.dynamic_cfg[field],
+                package_dir,
+            )
+        self._ensure_previously_set(dist, field)
+        return None
+
+    def _obtain_version(self, dist: Distribution, package_dir: Mapping[str, str]):
+        # Since plugins can set version, let's silently skip if it cannot be obtained
+        if "version" in self.dynamic and "version" in self.dynamic_cfg:
+            return _expand.version(
+                # We already do an early check for the presence of "version"
+                self._obtain(dist, "version", package_dir)  # pyright: ignore[reportArgumentType]
+            )
+        return None
+
+    def _obtain_readme(self, dist: Distribution) -> dict[str, str] | None:
+        if "readme" not in self.dynamic:
+            return None
+
+        dynamic_cfg = self.dynamic_cfg
+        if "readme" in dynamic_cfg:
+            return {
+                # We already do an early check for the presence of "readme"
+                "text": self._obtain(dist, "readme", {}),
+                "content-type": dynamic_cfg["readme"].get("content-type", "text/x-rst"),
+            }  # pyright: ignore[reportReturnType]
+
+        self._ensure_previously_set(dist, "readme")
+        return None
+
+    def _obtain_entry_points(
+        self, dist: Distribution, package_dir: Mapping[str, str]
+    ) -> dict[str, dict[str, Any]] | None:
+        fields = ("entry-points", "scripts", "gui-scripts")
+        if not any(field in self.dynamic for field in fields):
+            return None
+
+        text = self._obtain(dist, "entry-points", package_dir)
+        if text is None:
+            return None
+
+        groups = _expand.entry_points(text)
+        # Any is str | dict[str, str], but causes variance issues
+        expanded: dict[str, dict[str, Any]] = {"entry-points": groups}
+
+        def _set_scripts(field: str, group: str):
+            if group in groups:
+                value = groups.pop(group)
+                if field not in self.dynamic:
+                    raise InvalidConfigError(_MissingDynamic.details(field, value))
+                expanded[field] = value
+
+        _set_scripts("scripts", "console_scripts")
+        _set_scripts("gui-scripts", "gui_scripts")
+
+        return expanded
+
+    def _obtain_classifiers(self, dist: Distribution):
+        if "classifiers" in self.dynamic:
+            value = self._obtain(dist, "classifiers", {})
+            if value:
+                return value.splitlines()
+        return None
+
+    def _obtain_dependencies(self, dist: Distribution):
+        if "dependencies" in self.dynamic:
+            value = self._obtain(dist, "dependencies", {})
+            if value:
+                return _parse_requirements_list(value)
+        return None
+
+    def _obtain_optional_dependencies(self, dist: Distribution):
+        if "optional-dependencies" not in self.dynamic:
+            return None
+        if "optional-dependencies" in self.dynamic_cfg:
+            optional_dependencies_map = self.dynamic_cfg["optional-dependencies"]
+            assert isinstance(optional_dependencies_map, dict)
+            return {
+                group: _parse_requirements_list(
+                    self._expand_directive(
+                        f"tool.setuptools.dynamic.optional-dependencies.{group}",
+                        directive,
+                        {},
+                    )
+                )
+                for group, directive in optional_dependencies_map.items()
+            }
+        self._ensure_previously_set(dist, "optional-dependencies")
+        return None
+
+
+def _parse_requirements_list(value):
+    return [
+        line
+        for line in value.splitlines()
+        if line.strip() and not line.strip().startswith("#")
+    ]
+
+
+@contextmanager
+def _ignore_errors(ignore_option_errors: bool):
+    if not ignore_option_errors:
+        yield
+        return
+
+    try:
+        yield
+    except Exception as ex:
+        _logger.debug(f"ignored error: {ex.__class__.__name__} - {ex}")
+
+
+class _EnsurePackagesDiscovered(_expand.EnsurePackagesDiscovered):
+    def __init__(
+        self, distribution: Distribution, project_cfg: dict, setuptools_cfg: dict
+    ) -> None:
+        super().__init__(distribution)
+        self._project_cfg = project_cfg
+        self._setuptools_cfg = setuptools_cfg
+
+    def __enter__(self) -> Self:
+        """When entering the context, the values of ``packages``, ``py_modules`` and
+        ``package_dir`` that are missing in ``dist`` are copied from ``setuptools_cfg``.
+        """
+        dist, cfg = self._dist, self._setuptools_cfg
+        package_dir: dict[str, str] = cfg.setdefault("package-dir", {})
+        package_dir.update(dist.package_dir or {})
+        dist.package_dir = package_dir  # needs to be the same object
+
+        dist.set_defaults._ignore_ext_modules()  # pyproject.toml-specific behaviour
+
+        # Set `name`, `py_modules` and `packages` in dist to short-circuit
+        # auto-discovery, but avoid overwriting empty lists purposefully set by users.
+        if dist.metadata.name is None:
+            dist.metadata.name = self._project_cfg.get("name")
+        if dist.py_modules is None:
+            dist.py_modules = cfg.get("py-modules")
+        if dist.packages is None:
+            dist.packages = cfg.get("packages")
+
+        return super().__enter__()
+
+    def __exit__(
+        self,
+        exc_type: type[BaseException] | None,
+        exc_value: BaseException | None,
+        traceback: TracebackType | None,
+    ) -> None:
+        """When exiting the context, if values of ``packages``, ``py_modules`` and
+        ``package_dir`` are missing in ``setuptools_cfg``, copy from ``dist``.
+        """
+        # If anything was discovered set them back, so they count in the final config.
+        self._setuptools_cfg.setdefault("packages", self._dist.packages)
+        self._setuptools_cfg.setdefault("py-modules", self._dist.py_modules)
+        return super().__exit__(exc_type, exc_value, traceback)
+
+
+class _ExperimentalConfiguration(SetuptoolsWarning):
+    _SUMMARY = (
+        "`{subject}` in `pyproject.toml` is still *experimental* "
+        "and likely to change in future releases."
+    )
+
+
+class _ToolsTypoInMetadata(SetuptoolsWarning):
+    _SUMMARY = (
+        "Ignoring [tools.setuptools] in pyproject.toml, did you mean [tool.setuptools]?"
+    )
diff --git a/.venv/lib/python3.12/site-packages/setuptools/config/setupcfg.py b/.venv/lib/python3.12/site-packages/setuptools/config/setupcfg.py
new file mode 100644
index 0000000000000000000000000000000000000000..633aa9d45d086dd0290a2c38bee632ed7f9a63a4
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/config/setupcfg.py
@@ -0,0 +1,780 @@
+"""
+Load setuptools configuration from ``setup.cfg`` files.
+
+**API will be made private in the future**
+
+To read project metadata, consider using
+``build.util.project_wheel_metadata`` (https://pypi.org/project/build/).
+For simple scenarios, you can also try parsing the file directly
+with the help of ``configparser``.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import functools
+import os
+from collections import defaultdict
+from collections.abc import Iterable, Iterator
+from functools import partial, wraps
+from typing import TYPE_CHECKING, Any, Callable, ClassVar, Generic, TypeVar, cast
+
+from packaging.markers import default_environment as marker_env
+from packaging.requirements import InvalidRequirement, Requirement
+from packaging.version import InvalidVersion, Version
+
+from .. import _static
+from .._path import StrPath
+from ..errors import FileError, OptionError
+from ..warnings import SetuptoolsDeprecationWarning
+from . import expand
+
+if TYPE_CHECKING:
+    from typing_extensions import TypeAlias
+
+    from setuptools.dist import Distribution
+
+    from distutils.dist import DistributionMetadata
+
+SingleCommandOptions: TypeAlias = dict[str, tuple[str, Any]]
+"""Dict that associate the name of the options of a particular command to a
+tuple. The first element of the tuple indicates the origin of the option value
+(e.g. the name of the configuration file where it was read from),
+while the second element of the tuple is the option value itself
+"""
+AllCommandOptions: TypeAlias = dict[str, SingleCommandOptions]
+"""cmd name => its options"""
+Target = TypeVar("Target", "Distribution", "DistributionMetadata")
+
+
+def read_configuration(
+    filepath: StrPath, find_others: bool = False, ignore_option_errors: bool = False
+) -> dict:
+    """Read given configuration file and returns options from it as a dict.
+
+    :param str|unicode filepath: Path to configuration file
+        to get options from.
+
+    :param bool find_others: Whether to search for other configuration files
+        which could be on in various places.
+
+    :param bool ignore_option_errors: Whether to silently ignore
+        options, values of which could not be resolved (e.g. due to exceptions
+        in directives such as file:, attr:, etc.).
+        If False exceptions are propagated as expected.
+
+    :rtype: dict
+    """
+    from setuptools.dist import Distribution
+
+    dist = Distribution()
+    filenames = dist.find_config_files() if find_others else []
+    handlers = _apply(dist, filepath, filenames, ignore_option_errors)
+    return configuration_to_dict(handlers)
+
+
+def apply_configuration(dist: Distribution, filepath: StrPath) -> Distribution:
+    """Apply the configuration from a ``setup.cfg`` file into an existing
+    distribution object.
+    """
+    _apply(dist, filepath)
+    dist._finalize_requires()
+    return dist
+
+
+def _apply(
+    dist: Distribution,
+    filepath: StrPath,
+    other_files: Iterable[StrPath] = (),
+    ignore_option_errors: bool = False,
+) -> tuple[ConfigMetadataHandler, ConfigOptionsHandler]:
+    """Read configuration from ``filepath`` and applies to the ``dist`` object."""
+    from setuptools.dist import _Distribution
+
+    filepath = os.path.abspath(filepath)
+
+    if not os.path.isfile(filepath):
+        raise FileError(f'Configuration file {filepath} does not exist.')
+
+    current_directory = os.getcwd()
+    os.chdir(os.path.dirname(filepath))
+    filenames = [*other_files, filepath]
+
+    try:
+        # TODO: Temporary cast until mypy 1.12 is released with upstream fixes from typeshed
+        _Distribution.parse_config_files(dist, filenames=cast(list[str], filenames))
+        handlers = parse_configuration(
+            dist, dist.command_options, ignore_option_errors=ignore_option_errors
+        )
+        dist._finalize_license_files()
+    finally:
+        os.chdir(current_directory)
+
+    return handlers
+
+
+def _get_option(target_obj: Distribution | DistributionMetadata, key: str):
+    """
+    Given a target object and option key, get that option from
+    the target object, either through a get_{key} method or
+    from an attribute directly.
+    """
+    getter_name = f'get_{key}'
+    by_attribute = functools.partial(getattr, target_obj, key)
+    getter = getattr(target_obj, getter_name, by_attribute)
+    return getter()
+
+
+def configuration_to_dict(
+    handlers: Iterable[
+        ConfigHandler[Distribution] | ConfigHandler[DistributionMetadata]
+    ],
+) -> dict:
+    """Returns configuration data gathered by given handlers as a dict.
+
+    :param Iterable[ConfigHandler] handlers: Handlers list,
+        usually from parse_configuration()
+
+    :rtype: dict
+    """
+    config_dict: dict = defaultdict(dict)
+
+    for handler in handlers:
+        for option in handler.set_options:
+            value = _get_option(handler.target_obj, option)
+            config_dict[handler.section_prefix][option] = value
+
+    return config_dict
+
+
+def parse_configuration(
+    distribution: Distribution,
+    command_options: AllCommandOptions,
+    ignore_option_errors: bool = False,
+) -> tuple[ConfigMetadataHandler, ConfigOptionsHandler]:
+    """Performs additional parsing of configuration options
+    for a distribution.
+
+    Returns a list of used option handlers.
+
+    :param Distribution distribution:
+    :param dict command_options:
+    :param bool ignore_option_errors: Whether to silently ignore
+        options, values of which could not be resolved (e.g. due to exceptions
+        in directives such as file:, attr:, etc.).
+        If False exceptions are propagated as expected.
+    :rtype: list
+    """
+    with expand.EnsurePackagesDiscovered(distribution) as ensure_discovered:
+        options = ConfigOptionsHandler(
+            distribution,
+            command_options,
+            ignore_option_errors,
+            ensure_discovered,
+        )
+
+        options.parse()
+        if not distribution.package_dir:
+            distribution.package_dir = options.package_dir  # Filled by `find_packages`
+
+        meta = ConfigMetadataHandler(
+            distribution.metadata,
+            command_options,
+            ignore_option_errors,
+            ensure_discovered,
+            distribution.package_dir,
+            distribution.src_root,
+        )
+        meta.parse()
+        distribution._referenced_files.update(
+            options._referenced_files, meta._referenced_files
+        )
+
+    return meta, options
+
+
+def _warn_accidental_env_marker_misconfig(label: str, orig_value: str, parsed: list):
+    """Because users sometimes misinterpret this configuration:
+
+    [options.extras_require]
+    foo = bar;python_version<"4"
+
+    It looks like one requirement with an environment marker
+    but because there is no newline, it's parsed as two requirements
+    with a semicolon as separator.
+
+    Therefore, if:
+        * input string does not contain a newline AND
+        * parsed result contains two requirements AND
+        * parsing of the two parts from the result (";")
+        leads in a valid Requirement with a valid marker
+    a UserWarning is shown to inform the user about the possible problem.
+    """
+    if "\n" in orig_value or len(parsed) != 2:
+        return
+
+    markers = marker_env().keys()
+
+    try:
+        req = Requirement(parsed[1])
+        if req.name in markers:
+            _AmbiguousMarker.emit(field=label, req=parsed[1])
+    except InvalidRequirement as ex:
+        if any(parsed[1].startswith(marker) for marker in markers):
+            msg = _AmbiguousMarker.message(field=label, req=parsed[1])
+            raise InvalidRequirement(msg) from ex
+
+
+class ConfigHandler(Generic[Target]):
+    """Handles metadata supplied in configuration files."""
+
+    section_prefix: str
+    """Prefix for config sections handled by this handler.
+    Must be provided by class heirs.
+
+    """
+
+    aliases: ClassVar[dict[str, str]] = {}
+    """Options aliases.
+    For compatibility with various packages. E.g.: d2to1 and pbr.
+    Note: `-` in keys is replaced with `_` by config parser.
+
+    """
+
+    def __init__(
+        self,
+        target_obj: Target,
+        options: AllCommandOptions,
+        ignore_option_errors,
+        ensure_discovered: expand.EnsurePackagesDiscovered,
+    ) -> None:
+        self.ignore_option_errors = ignore_option_errors
+        self.target_obj: Target = target_obj
+        self.sections = dict(self._section_options(options))
+        self.set_options: list[str] = []
+        self.ensure_discovered = ensure_discovered
+        self._referenced_files = set[str]()
+        """After parsing configurations, this property will enumerate
+        all files referenced by the "file:" directive. Private API for setuptools only.
+        """
+
+    @classmethod
+    def _section_options(
+        cls, options: AllCommandOptions
+    ) -> Iterator[tuple[str, SingleCommandOptions]]:
+        for full_name, value in options.items():
+            pre, _sep, name = full_name.partition(cls.section_prefix)
+            if pre:
+                continue
+            yield name.lstrip('.'), value
+
+    @property
+    def parsers(self):
+        """Metadata item name to parser function mapping."""
+        raise NotImplementedError(
+            f'{self.__class__.__name__} must provide .parsers property'
+        )
+
+    def __setitem__(self, option_name, value) -> None:
+        target_obj = self.target_obj
+
+        # Translate alias into real name.
+        option_name = self.aliases.get(option_name, option_name)
+
+        try:
+            current_value = getattr(target_obj, option_name)
+        except AttributeError as e:
+            raise KeyError(option_name) from e
+
+        if current_value:
+            # Already inhabited. Skipping.
+            return
+
+        try:
+            parsed = self.parsers.get(option_name, lambda x: x)(value)
+        except (Exception,) * self.ignore_option_errors:
+            return
+
+        simple_setter = functools.partial(target_obj.__setattr__, option_name)
+        setter = getattr(target_obj, f"set_{option_name}", simple_setter)
+        setter(parsed)
+
+        self.set_options.append(option_name)
+
+    @classmethod
+    def _parse_list(cls, value, separator=','):
+        """Represents value as a list.
+
+        Value is split either by separator (defaults to comma) or by lines.
+
+        :param value:
+        :param separator: List items separator character.
+        :rtype: list
+        """
+        if isinstance(value, list):  # _get_parser_compound case
+            return value
+
+        if '\n' in value:
+            value = value.splitlines()
+        else:
+            value = value.split(separator)
+
+        return [chunk.strip() for chunk in value if chunk.strip()]
+
+    @classmethod
+    def _parse_dict(cls, value):
+        """Represents value as a dict.
+
+        :param value:
+        :rtype: dict
+        """
+        separator = '='
+        result = {}
+        for line in cls._parse_list(value):
+            key, sep, val = line.partition(separator)
+            if sep != separator:
+                raise OptionError(f"Unable to parse option value to dict: {value}")
+            result[key.strip()] = val.strip()
+
+        return result
+
+    @classmethod
+    def _parse_bool(cls, value):
+        """Represents value as boolean.
+
+        :param value:
+        :rtype: bool
+        """
+        value = value.lower()
+        return value in ('1', 'true', 'yes')
+
+    @classmethod
+    def _exclude_files_parser(cls, key):
+        """Returns a parser function to make sure field inputs
+        are not files.
+
+        Parses a value after getting the key so error messages are
+        more informative.
+
+        :param key:
+        :rtype: callable
+        """
+
+        def parser(value):
+            exclude_directive = 'file:'
+            if value.startswith(exclude_directive):
+                raise ValueError(
+                    f'Only strings are accepted for the {key} field, '
+                    'files are not accepted'
+                )
+            return _static.Str(value)
+
+        return parser
+
+    def _parse_file(self, value, root_dir: StrPath | None):
+        """Represents value as a string, allowing including text
+        from nearest files using `file:` directive.
+
+        Directive is sandboxed and won't reach anything outside
+        directory with setup.py.
+
+        Examples:
+            file: README.rst, CHANGELOG.md, src/file.txt
+
+        :param str value:
+        :rtype: str
+        """
+        include_directive = 'file:'
+
+        if not isinstance(value, str):
+            return value
+
+        if not value.startswith(include_directive):
+            return _static.Str(value)
+
+        spec = value[len(include_directive) :]
+        filepaths = [path.strip() for path in spec.split(',')]
+        self._referenced_files.update(filepaths)
+        # XXX: Is marking as static contents coming from files too optimistic?
+        return _static.Str(expand.read_files(filepaths, root_dir))
+
+    def _parse_attr(self, value, package_dir, root_dir: StrPath):
+        """Represents value as a module attribute.
+
+        Examples:
+            attr: package.attr
+            attr: package.module.attr
+
+        :param str value:
+        :rtype: str
+        """
+        attr_directive = 'attr:'
+        if not value.startswith(attr_directive):
+            return _static.Str(value)
+
+        attr_desc = value.replace(attr_directive, '')
+
+        # Make sure package_dir is populated correctly, so `attr:` directives can work
+        package_dir.update(self.ensure_discovered.package_dir)
+        return expand.read_attr(attr_desc, package_dir, root_dir)
+
+    @classmethod
+    def _get_parser_compound(cls, *parse_methods):
+        """Returns parser function to represents value as a list.
+
+        Parses a value applying given methods one after another.
+
+        :param parse_methods:
+        :rtype: callable
+        """
+
+        def parse(value):
+            parsed = value
+
+            for method in parse_methods:
+                parsed = method(parsed)
+
+            return parsed
+
+        return parse
+
+    @classmethod
+    def _parse_section_to_dict_with_key(cls, section_options, values_parser):
+        """Parses section options into a dictionary.
+
+        Applies a given parser to each option in a section.
+
+        :param dict section_options:
+        :param callable values_parser: function with 2 args corresponding to key, value
+        :rtype: dict
+        """
+        value = {}
+        for key, (_, val) in section_options.items():
+            value[key] = values_parser(key, val)
+        return value
+
+    @classmethod
+    def _parse_section_to_dict(cls, section_options, values_parser=None):
+        """Parses section options into a dictionary.
+
+        Optionally applies a given parser to each value.
+
+        :param dict section_options:
+        :param callable values_parser: function with 1 arg corresponding to option value
+        :rtype: dict
+        """
+        parser = (lambda _, v: values_parser(v)) if values_parser else (lambda _, v: v)
+        return cls._parse_section_to_dict_with_key(section_options, parser)
+
+    def parse_section(self, section_options) -> None:
+        """Parses configuration file section.
+
+        :param dict section_options:
+        """
+        for name, (_, value) in section_options.items():
+            with contextlib.suppress(KeyError):
+                # Keep silent for a new option may appear anytime.
+                self[name] = value
+
+    def parse(self) -> None:
+        """Parses configuration file items from one
+        or more related sections.
+
+        """
+        for section_name, section_options in self.sections.items():
+            method_postfix = ''
+            if section_name:  # [section.option] variant
+                method_postfix = f"_{section_name}"
+
+            section_parser_method: Callable | None = getattr(
+                self,
+                # Dots in section names are translated into dunderscores.
+                f'parse_section{method_postfix}'.replace('.', '__'),
+                None,
+            )
+
+            if section_parser_method is None:
+                raise OptionError(
+                    "Unsupported distribution option section: "
+                    f"[{self.section_prefix}.{section_name}]"
+                )
+
+            section_parser_method(section_options)
+
+    def _deprecated_config_handler(self, func, msg, **kw):
+        """this function will wrap around parameters that are deprecated
+
+        :param msg: deprecation message
+        :param func: function to be wrapped around
+        """
+
+        @wraps(func)
+        def config_handler(*args, **kwargs):
+            kw.setdefault("stacklevel", 2)
+            _DeprecatedConfig.emit("Deprecated config in `setup.cfg`", msg, **kw)
+            return func(*args, **kwargs)
+
+        return config_handler
+
+
+class ConfigMetadataHandler(ConfigHandler["DistributionMetadata"]):
+    section_prefix = 'metadata'
+
+    aliases = {
+        'home_page': 'url',
+        'summary': 'description',
+        'classifier': 'classifiers',
+        'platform': 'platforms',
+    }
+
+    strict_mode = False
+    """We need to keep it loose, to be partially compatible with
+    `pbr` and `d2to1` packages which also uses `metadata` section.
+
+    """
+
+    def __init__(
+        self,
+        target_obj: DistributionMetadata,
+        options: AllCommandOptions,
+        ignore_option_errors: bool,
+        ensure_discovered: expand.EnsurePackagesDiscovered,
+        package_dir: dict | None = None,
+        root_dir: StrPath | None = os.curdir,
+    ) -> None:
+        super().__init__(target_obj, options, ignore_option_errors, ensure_discovered)
+        self.package_dir = package_dir
+        self.root_dir = root_dir
+
+    @property
+    def parsers(self):
+        """Metadata item name to parser function mapping."""
+        parse_list_static = self._get_parser_compound(self._parse_list, _static.List)
+        parse_dict_static = self._get_parser_compound(self._parse_dict, _static.Dict)
+        parse_file = partial(self._parse_file, root_dir=self.root_dir)
+        exclude_files_parser = self._exclude_files_parser
+
+        return {
+            'author': _static.Str,
+            'author_email': _static.Str,
+            'maintainer': _static.Str,
+            'maintainer_email': _static.Str,
+            'platforms': parse_list_static,
+            'keywords': parse_list_static,
+            'provides': parse_list_static,
+            'obsoletes': parse_list_static,
+            'classifiers': self._get_parser_compound(parse_file, parse_list_static),
+            'license': exclude_files_parser('license'),
+            'license_files': parse_list_static,
+            'description': parse_file,
+            'long_description': parse_file,
+            'long_description_content_type': _static.Str,
+            'version': self._parse_version,  # Cannot be marked as dynamic
+            'url': _static.Str,
+            'project_urls': parse_dict_static,
+        }
+
+    def _parse_version(self, value):
+        """Parses `version` option value.
+
+        :param value:
+        :rtype: str
+
+        """
+        version = self._parse_file(value, self.root_dir)
+
+        if version != value:
+            version = version.strip()
+            # Be strict about versions loaded from file because it's easy to
+            # accidentally include newlines and other unintended content
+            try:
+                Version(version)
+            except InvalidVersion as e:
+                raise OptionError(
+                    f'Version loaded from {value} does not '
+                    f'comply with PEP 440: {version}'
+                ) from e
+
+            return version
+
+        return expand.version(self._parse_attr(value, self.package_dir, self.root_dir))
+
+
+class ConfigOptionsHandler(ConfigHandler["Distribution"]):
+    section_prefix = 'options'
+
+    def __init__(
+        self,
+        target_obj: Distribution,
+        options: AllCommandOptions,
+        ignore_option_errors: bool,
+        ensure_discovered: expand.EnsurePackagesDiscovered,
+    ) -> None:
+        super().__init__(target_obj, options, ignore_option_errors, ensure_discovered)
+        self.root_dir = target_obj.src_root
+        self.package_dir: dict[str, str] = {}  # To be filled by `find_packages`
+
+    @classmethod
+    def _parse_list_semicolon(cls, value):
+        return cls._parse_list(value, separator=';')
+
+    def _parse_file_in_root(self, value):
+        return self._parse_file(value, root_dir=self.root_dir)
+
+    def _parse_requirements_list(self, label: str, value: str):
+        # Parse a requirements list, either by reading in a `file:`, or a list.
+        parsed = self._parse_list_semicolon(self._parse_file_in_root(value))
+        _warn_accidental_env_marker_misconfig(label, value, parsed)
+        # Filter it to only include lines that are not comments. `parse_list`
+        # will have stripped each line and filtered out empties.
+        return _static.List(line for line in parsed if not line.startswith("#"))
+        # ^-- Use `_static.List` to mark a non-`Dynamic` Core Metadata
+
+    @property
+    def parsers(self):
+        """Metadata item name to parser function mapping."""
+        parse_list = self._parse_list
+        parse_bool = self._parse_bool
+        parse_cmdclass = self._parse_cmdclass
+
+        return {
+            'zip_safe': parse_bool,
+            'include_package_data': parse_bool,
+            'package_dir': self._parse_dict,
+            'scripts': parse_list,
+            'eager_resources': parse_list,
+            'dependency_links': parse_list,
+            'namespace_packages': self._deprecated_config_handler(
+                parse_list,
+                "The namespace_packages parameter is deprecated, "
+                "consider using implicit namespaces instead (PEP 420).",
+                # TODO: define due date, see setuptools.dist:check_nsp.
+            ),
+            'install_requires': partial(  # Core Metadata
+                self._parse_requirements_list, "install_requires"
+            ),
+            'setup_requires': self._parse_list_semicolon,
+            'packages': self._parse_packages,
+            'entry_points': self._parse_file_in_root,
+            'py_modules': parse_list,
+            'python_requires': _static.SpecifierSet,  # Core Metadata
+            'cmdclass': parse_cmdclass,
+        }
+
+    def _parse_cmdclass(self, value):
+        package_dir = self.ensure_discovered.package_dir
+        return expand.cmdclass(self._parse_dict(value), package_dir, self.root_dir)
+
+    def _parse_packages(self, value):
+        """Parses `packages` option value.
+
+        :param value:
+        :rtype: list
+        """
+        find_directives = ['find:', 'find_namespace:']
+        trimmed_value = value.strip()
+
+        if trimmed_value not in find_directives:
+            return self._parse_list(value)
+
+        # Read function arguments from a dedicated section.
+        find_kwargs = self.parse_section_packages__find(
+            self.sections.get('packages.find', {})
+        )
+
+        find_kwargs.update(
+            namespaces=(trimmed_value == find_directives[1]),
+            root_dir=self.root_dir,
+            fill_package_dir=self.package_dir,
+        )
+
+        return expand.find_packages(**find_kwargs)
+
+    def parse_section_packages__find(self, section_options):
+        """Parses `packages.find` configuration file section.
+
+        To be used in conjunction with _parse_packages().
+
+        :param dict section_options:
+        """
+        section_data = self._parse_section_to_dict(section_options, self._parse_list)
+
+        valid_keys = ['where', 'include', 'exclude']
+        find_kwargs = {k: v for k, v in section_data.items() if k in valid_keys and v}
+
+        where = find_kwargs.get('where')
+        if where is not None:
+            find_kwargs['where'] = where[0]  # cast list to single val
+
+        return find_kwargs
+
+    def parse_section_entry_points(self, section_options) -> None:
+        """Parses `entry_points` configuration file section.
+
+        :param dict section_options:
+        """
+        parsed = self._parse_section_to_dict(section_options, self._parse_list)
+        self['entry_points'] = parsed
+
+    def _parse_package_data(self, section_options):
+        package_data = self._parse_section_to_dict(section_options, self._parse_list)
+        return expand.canonic_package_data(package_data)
+
+    def parse_section_package_data(self, section_options) -> None:
+        """Parses `package_data` configuration file section.
+
+        :param dict section_options:
+        """
+        self['package_data'] = self._parse_package_data(section_options)
+
+    def parse_section_exclude_package_data(self, section_options) -> None:
+        """Parses `exclude_package_data` configuration file section.
+
+        :param dict section_options:
+        """
+        self['exclude_package_data'] = self._parse_package_data(section_options)
+
+    def parse_section_extras_require(self, section_options) -> None:  # Core Metadata
+        """Parses `extras_require` configuration file section.
+
+        :param dict section_options:
+        """
+        parsed = self._parse_section_to_dict_with_key(
+            section_options,
+            lambda k, v: self._parse_requirements_list(f"extras_require[{k}]", v),
+        )
+
+        self['extras_require'] = _static.Dict(parsed)
+        # ^-- Use `_static.Dict` to mark a non-`Dynamic` Core Metadata
+
+    def parse_section_data_files(self, section_options) -> None:
+        """Parses `data_files` configuration file section.
+
+        :param dict section_options:
+        """
+        parsed = self._parse_section_to_dict(section_options, self._parse_list)
+        self['data_files'] = expand.canonic_data_files(parsed, self.root_dir)
+
+
+class _AmbiguousMarker(SetuptoolsDeprecationWarning):
+    _SUMMARY = "Ambiguous requirement marker."
+    _DETAILS = """
+    One of the parsed requirements in `{field}` looks like a valid environment marker:
+
+        {req!r}
+
+    Please make sure that the configuration file is correct.
+    You can use dangling lines to avoid this problem.
+    """
+    _SEE_DOCS = "userguide/declarative_config.html#opt-2"
+    # TODO: should we include due_date here? Initially introduced in 6 Aug 2022.
+    # Does this make sense with latest version of packaging?
+
+    @classmethod
+    def message(cls, **kw):
+        docs = f"https://setuptools.pypa.io/en/latest/{cls._SEE_DOCS}"
+        return cls._format(cls._SUMMARY, cls._DETAILS, see_url=docs, format_args=kw)
+
+
+class _DeprecatedConfig(SetuptoolsDeprecationWarning):
+    _SEE_DOCS = "userguide/declarative_config.html"
diff --git a/.venv/lib/python3.12/site-packages/setuptools/config/setuptools.schema.json b/.venv/lib/python3.12/site-packages/setuptools/config/setuptools.schema.json
new file mode 100644
index 0000000000000000000000000000000000000000..ec887b35736e4ede6265e95e3a9e2520b43cc40f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/config/setuptools.schema.json
@@ -0,0 +1,433 @@
+{
+  "$schema": "http://json-schema.org/draft-07/schema#",
+
+  "$id": "https://setuptools.pypa.io/en/latest/userguide/pyproject_config.html",
+  "title": "``tool.setuptools`` table",
+  "$$description": [
+    "``setuptools``-specific configurations that can be set by users that require",
+    "customization.",
+    "These configurations are completely optional and probably can be skipped when",
+    "creating simple packages. They are equivalent to some of the `Keywords",
+    "`_",
+    "used by the ``setup.py`` file, and can be set via the ``tool.setuptools`` table.",
+    "It considers only ``setuptools`` `parameters",
+    "`_",
+    "that are not covered by :pep:`621`; and intentionally excludes ``dependency_links``",
+    "and ``setup_requires`` (incompatible with modern workflows/standards)."
+  ],
+
+  "type": "object",
+  "additionalProperties": false,
+  "properties": {
+    "platforms": {
+      "type": "array",
+      "items": {"type": "string"}
+    },
+    "provides": {
+      "$$description": [
+        "Package and virtual package names contained within this package",
+        "**(not supported by pip)**"
+      ],
+      "type": "array",
+      "items": {"type": "string", "format": "pep508-identifier"}
+    },
+    "obsoletes": {
+      "$$description": [
+        "Packages which this package renders obsolete",
+        "**(not supported by pip)**"
+      ],
+      "type": "array",
+      "items": {"type": "string", "format": "pep508-identifier"}
+    },
+    "zip-safe": {
+      "$$description": [
+        "Whether the project can be safely installed and run from a zip file.",
+        "**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and",
+        "``setup.py install`` in the context of ``eggs`` (**DEPRECATED**)."
+      ],
+      "type": "boolean"
+    },
+    "script-files": {
+      "$$description": [
+        "Legacy way of defining scripts (entry-points are preferred).",
+        "Equivalent to the ``script`` keyword in ``setup.py``",
+        "(it was renamed to avoid confusion with entry-point based ``project.scripts``",
+        "defined in :pep:`621`).",
+        "**DISCOURAGED**: generic script wrappers are tricky and may not work properly.",
+        "Whenever possible, please use ``project.scripts`` instead."
+      ],
+      "type": "array",
+      "items": {"type": "string"},
+      "$comment": "TODO: is this field deprecated/should be removed?"
+    },
+    "eager-resources": {
+      "$$description": [
+        "Resources that should be extracted together, if any of them is needed,",
+        "or if any C extensions included in the project are imported.",
+        "**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and",
+        "``setup.py install`` in the context of ``eggs`` (**DEPRECATED**)."
+      ],
+      "type": "array",
+      "items": {"type": "string"}
+    },
+    "packages": {
+      "$$description": [
+        "Packages that should be included in the distribution.",
+        "It can be given either as a list of package identifiers",
+        "or as a ``dict``-like structure with a single key ``find``",
+        "which corresponds to a dynamic call to",
+        "``setuptools.config.expand.find_packages`` function.",
+        "The ``find`` key is associated with a nested ``dict``-like structure that can",
+        "contain ``where``, ``include``, ``exclude`` and ``namespaces`` keys,",
+        "mimicking the keyword arguments of the associated function."
+      ],
+      "oneOf": [
+        {
+          "title": "Array of Python package identifiers",
+          "type": "array",
+          "items": {"$ref": "#/definitions/package-name"}
+        },
+        {"$ref": "#/definitions/find-directive"}
+      ]
+    },
+    "package-dir": {
+      "$$description": [
+        ":class:`dict`-like structure mapping from package names to directories where their",
+        "code can be found.",
+        "The empty string (as key) means that all packages are contained inside",
+        "the given directory will be included in the distribution."
+      ],
+      "type": "object",
+      "additionalProperties": false,
+      "propertyNames": {
+        "anyOf": [{"const": ""}, {"$ref": "#/definitions/package-name"}]
+      },
+      "patternProperties": {
+        "^.*$": {"type": "string" }
+      }
+    },
+    "package-data": {
+      "$$description": [
+        "Mapping from package names to lists of glob patterns.",
+        "Usually this option is not needed when using ``include-package-data = true``",
+        "For more information on how to include data files, check ``setuptools`` `docs",
+        "`_."
+      ],
+      "type": "object",
+      "additionalProperties": false,
+      "propertyNames": {
+        "anyOf": [{"type": "string", "format": "python-module-name"}, {"const": "*"}]
+      },
+      "patternProperties": {
+        "^.*$": {"type": "array", "items": {"type": "string"}}
+      }
+    },
+    "include-package-data": {
+      "$$description": [
+        "Automatically include any data files inside the package directories",
+        "that are specified by ``MANIFEST.in``",
+        "For more information on how to include data files, check ``setuptools`` `docs",
+        "`_."
+      ],
+      "type": "boolean"
+    },
+    "exclude-package-data": {
+      "$$description": [
+        "Mapping from package names to lists of glob patterns that should be excluded",
+        "For more information on how to include data files, check ``setuptools`` `docs",
+        "`_."
+      ],
+      "type": "object",
+      "additionalProperties": false,
+      "propertyNames": {
+        "anyOf": [{"type": "string", "format": "python-module-name"}, {"const": "*"}]
+      },
+      "patternProperties": {
+          "^.*$": {"type": "array", "items": {"type": "string"}}
+      }
+    },
+    "namespace-packages": {
+      "type": "array",
+      "items": {"type": "string", "format": "python-module-name-relaxed"},
+      "$comment": "https://setuptools.pypa.io/en/latest/userguide/package_discovery.html",
+      "description": "**DEPRECATED**: use implicit namespaces instead (:pep:`420`)."
+    },
+    "py-modules": {
+      "description": "Modules that setuptools will manipulate",
+      "type": "array",
+      "items": {"type": "string", "format": "python-module-name-relaxed"},
+      "$comment": "TODO: clarify the relationship with ``packages``"
+    },
+    "ext-modules": {
+      "description": "Extension modules to be compiled by setuptools",
+      "type": "array",
+      "items": {"$ref": "#/definitions/ext-module"}
+    },
+    "data-files": {
+      "$$description": [
+        "``dict``-like structure where each key represents a directory and",
+        "the value is a list of glob patterns that should be installed in them.",
+        "**DISCOURAGED**: please notice this might not work as expected with wheels.",
+        "Whenever possible, consider using data files inside the package directories",
+        "(or create a new namespace package that only contains data files).",
+        "See `data files support",
+        "`_."
+      ],
+      "type": "object",
+      "patternProperties": {
+          "^.*$": {"type": "array", "items": {"type": "string"}}
+      }
+    },
+    "cmdclass": {
+      "$$description": [
+        "Mapping of distutils-style command names to ``setuptools.Command`` subclasses",
+        "which in turn should be represented by strings with a qualified class name",
+        "(i.e., \"dotted\" form with module), e.g.::\n\n",
+        "    cmdclass = {mycmd = \"pkg.subpkg.module.CommandClass\"}\n\n",
+        "The command class should be a directly defined at the top-level of the",
+        "containing module (no class nesting)."
+      ],
+      "type": "object",
+      "patternProperties": {
+          "^.*$": {"type": "string", "format": "python-qualified-identifier"}
+      }
+    },
+    "license-files": {
+      "type": "array",
+      "items": {"type": "string"},
+      "$$description": [
+        "**PROVISIONAL**: list of glob patterns for all license files being distributed.",
+        "(likely to become standard with :pep:`639`).",
+        "By default: ``['LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*']``"
+      ],
+      "$comment": "TODO: revise if PEP 639 is accepted. Probably ``project.license-files``?"
+    },
+    "dynamic": {
+      "type": "object",
+      "description": "Instructions for loading :pep:`621`-related metadata dynamically",
+      "additionalProperties": false,
+      "properties": {
+        "version": {
+          "$$description": [
+            "A version dynamically loaded via either the ``attr:`` or ``file:``",
+            "directives. Please make sure the given file or attribute respects :pep:`440`.",
+            "Also ensure to set ``project.dynamic`` accordingly."
+          ],
+          "oneOf": [
+            {"$ref": "#/definitions/attr-directive"},
+            {"$ref": "#/definitions/file-directive"}
+          ]
+        },
+        "classifiers": {"$ref": "#/definitions/file-directive"},
+        "description": {"$ref": "#/definitions/file-directive"},
+        "entry-points": {"$ref": "#/definitions/file-directive"},
+        "dependencies": {"$ref": "#/definitions/file-directive-for-dependencies"},
+        "optional-dependencies": {
+          "type": "object",
+          "propertyNames": {"type": "string", "format": "pep508-identifier"},
+          "additionalProperties": false,
+          "patternProperties": {
+            ".+": {"$ref": "#/definitions/file-directive-for-dependencies"}
+          }
+        },
+        "readme": {
+          "type": "object",
+          "anyOf": [
+            {"$ref": "#/definitions/file-directive"},
+            {
+              "type": "object",
+              "properties": {
+                "content-type": {"type": "string"},
+                "file": { "$ref": "#/definitions/file-directive/properties/file" }
+              },
+              "additionalProperties": false}
+          ],
+          "required": ["file"]
+        }
+      }
+    }
+  },
+
+  "definitions": {
+    "package-name": {
+      "$id": "#/definitions/package-name",
+      "title": "Valid package name",
+      "description": "Valid package name (importable or :pep:`561`).",
+      "type": "string",
+      "anyOf": [
+        {"type": "string", "format": "python-module-name-relaxed"},
+        {"type": "string", "format": "pep561-stub-name"}
+      ]
+    },
+    "ext-module": {
+      "$id": "#/definitions/ext-module",
+      "title": "Extension module",
+      "description": "Parameters to construct a :class:`setuptools.Extension` object",
+      "type": "object",
+      "required": ["name", "sources"],
+      "additionalProperties": false,
+      "properties": {
+        "name": {
+          "type": "string",
+          "format": "python-module-name-relaxed"
+        },
+        "sources": {
+          "type": "array",
+          "items": {"type": "string"}
+        },
+        "include-dirs":{
+          "type": "array",
+          "items": {"type": "string"}
+        },
+        "define-macros": {
+          "type": "array",
+          "items": {
+            "type": "array",
+            "items": [
+              {"description": "macro name", "type": "string"},
+              {"description": "macro value", "oneOf": [{"type": "string"}, {"type": "null"}]}
+            ],
+            "additionalItems": false
+          }
+        },
+        "undef-macros": {
+          "type": "array",
+          "items": {"type": "string"}
+        },
+        "library-dirs": {
+          "type": "array",
+          "items": {"type": "string"}
+        },
+        "libraries": {
+          "type": "array",
+          "items": {"type": "string"}
+        },
+        "runtime-library-dirs": {
+          "type": "array",
+          "items": {"type": "string"}
+        },
+        "extra-objects": {
+          "type": "array",
+          "items": {"type": "string"}
+        },
+        "extra-compile-args": {
+          "type": "array",
+          "items": {"type": "string"}
+        },
+        "extra-link-args": {
+          "type": "array",
+          "items": {"type": "string"}
+        },
+        "export-symbols": {
+          "type": "array",
+          "items": {"type": "string"}
+        },
+        "swig-opts": {
+          "type": "array",
+          "items": {"type": "string"}
+        },
+        "depends": {
+          "type": "array",
+          "items": {"type": "string"}
+        },
+        "language": {"type": "string"},
+        "optional": {"type": "boolean"},
+        "py-limited-api": {"type": "boolean"}
+      }
+    },
+    "file-directive": {
+      "$id": "#/definitions/file-directive",
+      "title": "'file:' directive",
+      "description":
+        "Value is read from a file (or list of files and then concatenated)",
+      "type": "object",
+      "additionalProperties": false,
+      "properties": {
+        "file": {
+          "oneOf": [
+            {"type": "string"},
+            {"type": "array", "items": {"type": "string"}}
+          ]
+        }
+      },
+      "required": ["file"]
+    },
+    "file-directive-for-dependencies": {
+      "title": "'file:' directive for dependencies",
+      "allOf": [
+        {
+          "$$description": [
+            "**BETA**: subset of the ``requirements.txt`` format",
+            "without ``pip`` flags and options",
+            "(one :pep:`508`-compliant string per line,",
+            "lines that are blank or start with ``#`` are excluded).",
+            "See `dynamic metadata",
+            "`_."
+          ]
+        },
+        {"$ref": "#/definitions/file-directive"}
+      ]
+    },
+    "attr-directive": {
+      "title": "'attr:' directive",
+      "$id": "#/definitions/attr-directive",
+      "$$description": [
+        "Value is read from a module attribute. Supports callables and iterables;",
+        "unsupported types are cast via ``str()``"
+      ],
+      "type": "object",
+      "additionalProperties": false,
+      "properties": {
+        "attr": {"type": "string", "format": "python-qualified-identifier"}
+      },
+      "required": ["attr"]
+    },
+    "find-directive": {
+      "$id": "#/definitions/find-directive",
+      "title": "'find:' directive",
+      "type": "object",
+      "additionalProperties": false,
+      "properties": {
+        "find": {
+          "type": "object",
+          "$$description": [
+            "Dynamic `package discovery",
+            "`_."
+          ],
+          "additionalProperties": false,
+          "properties": {
+            "where": {
+              "description":
+                "Directories to be searched for packages (Unix-style relative path)",
+              "type": "array",
+              "items": {"type": "string"}
+            },
+            "exclude": {
+              "type": "array",
+              "$$description": [
+                "Exclude packages that match the values listed in this field.",
+                "Can container shell-style wildcards (e.g. ``'pkg.*'``)"
+              ],
+              "items": {"type": "string"}
+            },
+            "include": {
+              "type": "array",
+              "$$description": [
+                "Restrict the found packages to just the ones listed in this field.",
+                "Can container shell-style wildcards (e.g. ``'pkg.*'``)"
+              ],
+              "items": {"type": "string"}
+            },
+            "namespaces": {
+              "type": "boolean",
+              "$$description": [
+                "When ``True``, directories without a ``__init__.py`` file will also",
+                "be scanned for :pep:`420`-style implicit namespaces"
+              ]
+            }
+          }
+        }
+      }
+    }
+  }
+}
diff --git a/.venv/lib/python3.12/site-packages/setuptools/depends.py b/.venv/lib/python3.12/site-packages/setuptools/depends.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5223b79561c36d9b6c45ead78288098e1cb0f1d
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/depends.py
@@ -0,0 +1,185 @@
+from __future__ import annotations
+
+import contextlib
+import dis
+import marshal
+import sys
+from types import CodeType
+from typing import Any, Literal, TypeVar
+
+from packaging.version import Version
+
+from . import _imp
+from ._imp import PY_COMPILED, PY_FROZEN, PY_SOURCE, find_module
+
+_T = TypeVar("_T")
+
+__all__ = ['Require', 'find_module']
+
+
+class Require:
+    """A prerequisite to building or installing a distribution"""
+
+    def __init__(
+        self,
+        name,
+        requested_version,
+        module,
+        homepage: str = '',
+        attribute=None,
+        format=None,
+    ) -> None:
+        if format is None and requested_version is not None:
+            format = Version
+
+        if format is not None:
+            requested_version = format(requested_version)
+            if attribute is None:
+                attribute = '__version__'
+
+        self.__dict__.update(locals())
+        del self.self
+
+    def full_name(self):
+        """Return full package/distribution name, w/version"""
+        if self.requested_version is not None:
+            return f'{self.name}-{self.requested_version}'
+        return self.name
+
+    def version_ok(self, version):
+        """Is 'version' sufficiently up-to-date?"""
+        return (
+            self.attribute is None
+            or self.format is None
+            or str(version) != "unknown"
+            and self.format(version) >= self.requested_version
+        )
+
+    def get_version(
+        self, paths=None, default: _T | Literal["unknown"] = "unknown"
+    ) -> _T | Literal["unknown"] | None | Any:
+        """Get version number of installed module, 'None', or 'default'
+
+        Search 'paths' for module.  If not found, return 'None'.  If found,
+        return the extracted version attribute, or 'default' if no version
+        attribute was specified, or the value cannot be determined without
+        importing the module.  The version is formatted according to the
+        requirement's version format (if any), unless it is 'None' or the
+        supplied 'default'.
+        """
+
+        if self.attribute is None:
+            try:
+                f, _p, _i = find_module(self.module, paths)
+            except ImportError:
+                return None
+            if f:
+                f.close()
+            return default
+
+        v = get_module_constant(self.module, self.attribute, default, paths)
+
+        if v is not None and v is not default and self.format is not None:
+            return self.format(v)
+
+        return v
+
+    def is_present(self, paths=None):
+        """Return true if dependency is present on 'paths'"""
+        return self.get_version(paths) is not None
+
+    def is_current(self, paths=None):
+        """Return true if dependency is present and up-to-date on 'paths'"""
+        version = self.get_version(paths)
+        if version is None:
+            return False
+        return self.version_ok(str(version))
+
+
+def maybe_close(f):
+    @contextlib.contextmanager
+    def empty():
+        yield
+        return
+
+    if not f:
+        return empty()
+
+    return contextlib.closing(f)
+
+
+# Some objects are not available on some platforms.
+# XXX it'd be better to test assertions about bytecode instead.
+if not sys.platform.startswith('java') and sys.platform != 'cli':
+
+    def get_module_constant(
+        module, symbol, default: _T | int = -1, paths=None
+    ) -> _T | int | None | Any:
+        """Find 'module' by searching 'paths', and extract 'symbol'
+
+        Return 'None' if 'module' does not exist on 'paths', or it does not define
+        'symbol'.  If the module defines 'symbol' as a constant, return the
+        constant.  Otherwise, return 'default'."""
+
+        try:
+            f, path, (_suffix, _mode, kind) = info = find_module(module, paths)
+        except ImportError:
+            # Module doesn't exist
+            return None
+
+        with maybe_close(f):
+            if kind == PY_COMPILED:
+                f.read(8)  # skip magic & date
+                code = marshal.load(f)
+            elif kind == PY_FROZEN:
+                code = _imp.get_frozen_object(module, paths)
+            elif kind == PY_SOURCE:
+                code = compile(f.read(), path, 'exec')
+            else:
+                # Not something we can parse; we'll have to import it.  :(
+                imported = _imp.get_module(module, paths, info)
+                return getattr(imported, symbol, None)
+
+        return extract_constant(code, symbol, default)
+
+    def extract_constant(
+        code: CodeType, symbol: str, default: _T | int = -1
+    ) -> _T | int | None | Any:
+        """Extract the constant value of 'symbol' from 'code'
+
+        If the name 'symbol' is bound to a constant value by the Python code
+        object 'code', return that value.  If 'symbol' is bound to an expression,
+        return 'default'.  Otherwise, return 'None'.
+
+        Return value is based on the first assignment to 'symbol'.  'symbol' must
+        be a global, or at least a non-"fast" local in the code block.  That is,
+        only 'STORE_NAME' and 'STORE_GLOBAL' opcodes are checked, and 'symbol'
+        must be present in 'code.co_names'.
+        """
+        if symbol not in code.co_names:
+            # name's not there, can't possibly be an assignment
+            return None
+
+        name_idx = list(code.co_names).index(symbol)
+
+        STORE_NAME = dis.opmap['STORE_NAME']
+        STORE_GLOBAL = dis.opmap['STORE_GLOBAL']
+        LOAD_CONST = dis.opmap['LOAD_CONST']
+
+        const = default
+
+        for byte_code in dis.Bytecode(code):
+            op = byte_code.opcode
+            arg = byte_code.arg
+
+            if op == LOAD_CONST:
+                assert arg is not None
+                const = code.co_consts[arg]
+            elif arg == name_idx and (op == STORE_NAME or op == STORE_GLOBAL):
+                return const
+            else:
+                const = default
+
+        return None
+
+    __all__ += ['get_module_constant', 'extract_constant']
diff --git a/.venv/lib/python3.12/site-packages/setuptools/discovery.py b/.venv/lib/python3.12/site-packages/setuptools/discovery.py
new file mode 100644
index 0000000000000000000000000000000000000000..c88839918562bad12f1a2e72309f1eacfe23349c
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/discovery.py
@@ -0,0 +1,614 @@
+"""Automatic discovery of Python modules and packages (for inclusion in the
+distribution) and other config values.
+
+For the purposes of this module, the following nomenclature is used:
+
+- "src-layout": a directory representing a Python project that contains a "src"
+  folder. Everything under the "src" folder is meant to be included in the
+  distribution when packaging the project. Example::
+
+    .
+    ├── tox.ini
+    ├── pyproject.toml
+    └── src/
+        └── mypkg/
+            ├── __init__.py
+            ├── mymodule.py
+            └── my_data_file.txt
+
+- "flat-layout": a Python project that does not use "src-layout" but instead
+  have a directory under the project root for each package::
+
+    .
+    ├── tox.ini
+    ├── pyproject.toml
+    └── mypkg/
+        ├── __init__.py
+        ├── mymodule.py
+        └── my_data_file.txt
+
+- "single-module": a project that contains a single Python script direct under
+  the project root (no directory used)::
+
+    .
+    ├── tox.ini
+    ├── pyproject.toml
+    └── mymodule.py
+
+"""
+
+from __future__ import annotations
+
+import itertools
+import os
+from collections.abc import Iterable, Iterator, Mapping
+from fnmatch import fnmatchcase
+from glob import glob
+from pathlib import Path
+from typing import TYPE_CHECKING, ClassVar
+
+import _distutils_hack.override  # noqa: F401
+
+from ._path import StrPath
+
+from distutils import log
+from distutils.util import convert_path
+
+if TYPE_CHECKING:
+    from setuptools import Distribution
+
+chain_iter = itertools.chain.from_iterable
+
+
+def _valid_name(path: StrPath) -> bool:
+    # Ignore invalid names that cannot be imported directly
+    return os.path.basename(path).isidentifier()
+
+
+class _Filter:
+    """
+    Given a list of patterns, create a callable that will be true only if
+    the input matches at least one of the patterns.
+    """
+
+    def __init__(self, *patterns: str) -> None:
+        self._patterns = dict.fromkeys(patterns)
+
+    def __call__(self, item: str) -> bool:
+        return any(fnmatchcase(item, pat) for pat in self._patterns)
+
+    def __contains__(self, item: str) -> bool:
+        return item in self._patterns
+
+
+class _Finder:
+    """Base class that exposes functionality for module/package finders"""
+
+    ALWAYS_EXCLUDE: ClassVar[tuple[str, ...]] = ()
+    DEFAULT_EXCLUDE: ClassVar[tuple[str, ...]] = ()
+
+    @classmethod
+    def find(
+        cls,
+        where: StrPath = '.',
+        exclude: Iterable[str] = (),
+        include: Iterable[str] = ('*',),
+    ) -> list[str]:
+        """Return a list of all Python items (packages or modules, depending on
+        the finder implementation) found within directory 'where'.
+
+        'where' is the root directory which will be searched.
+        It should be supplied as a "cross-platform" (i.e. URL-style) path;
+        it will be converted to the appropriate local path syntax.
+
+        'exclude' is a sequence of names to exclude; '*' can be used
+        as a wildcard in the names.
+        When finding packages, 'foo.*' will exclude all subpackages of 'foo'
+        (but not 'foo' itself).
+
+        'include' is a sequence of names to include.
+        If it's specified, only the named items will be included.
+        If it's not specified, all found items will be included.
+        'include' can contain shell style wildcard patterns just like
+        'exclude'.
+        """
+
+        exclude = exclude or cls.DEFAULT_EXCLUDE
+        return list(
+            cls._find_iter(
+                convert_path(str(where)),
+                _Filter(*cls.ALWAYS_EXCLUDE, *exclude),
+                _Filter(*include),
+            )
+        )
+
+    @classmethod
+    def _find_iter(
+        cls, where: StrPath, exclude: _Filter, include: _Filter
+    ) -> Iterator[str]:
+        raise NotImplementedError
+
+
+class PackageFinder(_Finder):
+    """
+    Generate a list of all Python packages found within a directory
+    """
+
+    ALWAYS_EXCLUDE = ("ez_setup", "*__pycache__")
+
+    @classmethod
+    def _find_iter(
+        cls, where: StrPath, exclude: _Filter, include: _Filter
+    ) -> Iterator[str]:
+        """
+        All the packages found in 'where' that pass the 'include' filter, but
+        not the 'exclude' filter.
+        """
+        for root, dirs, files in os.walk(str(where), followlinks=True):
+            # Copy dirs to iterate over it, then empty dirs.
+            all_dirs = dirs[:]
+            dirs[:] = []
+
+            for dir in all_dirs:
+                full_path = os.path.join(root, dir)
+                rel_path = os.path.relpath(full_path, where)
+                package = rel_path.replace(os.path.sep, '.')
+
+                # Skip directory trees that are not valid packages
+                if '.' in dir or not cls._looks_like_package(full_path, package):
+                    continue
+
+                # Should this package be included?
+                if include(package) and not exclude(package):
+                    yield package
+
+                # Early pruning if there is nothing else to be scanned
+                if f"{package}*" in exclude or f"{package}.*" in exclude:
+                    continue
+
+                # Keep searching subdirectories, as there may be more packages
+                # down there, even if the parent was excluded.
+                dirs.append(dir)
+
+    @staticmethod
+    def _looks_like_package(path: StrPath, _package_name: str) -> bool:
+        """Does a directory look like a package?"""
+        return os.path.isfile(os.path.join(path, '__init__.py'))
+
+
+class PEP420PackageFinder(PackageFinder):
+    @staticmethod
+    def _looks_like_package(_path: StrPath, _package_name: str) -> bool:
+        return True
+
+
+class ModuleFinder(_Finder):
+    """Find isolated Python modules.
+    This function will **not** recurse subdirectories.
+    """
+
+    @classmethod
+    def _find_iter(
+        cls, where: StrPath, exclude: _Filter, include: _Filter
+    ) -> Iterator[str]:
+        for file in glob(os.path.join(where, "*.py")):
+            module, _ext = os.path.splitext(os.path.basename(file))
+
+            if not cls._looks_like_module(module):
+                continue
+
+            if include(module) and not exclude(module):
+                yield module
+
+    _looks_like_module = staticmethod(_valid_name)
+
+
+# We have to be extra careful in the case of flat layout to not include files
+# and directories not meant for distribution (e.g. tool-related)
+
+
+class FlatLayoutPackageFinder(PEP420PackageFinder):
+    _EXCLUDE = (
+        "ci",
+        "bin",
+        "debian",
+        "doc",
+        "docs",
+        "documentation",
+        "manpages",
+        "news",
+        "newsfragments",
+        "changelog",
+        "test",
+        "tests",
+        "unit_test",
+        "unit_tests",
+        "example",
+        "examples",
+        "scripts",
+        "tools",
+        "util",
+        "utils",
+        "python",
+        "build",
+        "dist",
+        "venv",
+        "env",
+        "requirements",
+        # ---- Task runners / Build tools ----
+        "tasks",  # invoke
+        "fabfile",  # fabric
+        "site_scons",  # SCons
+        # ---- Other tools ----
+        "benchmark",
+        "benchmarks",
+        "exercise",
+        "exercises",
+        "htmlcov",  # Coverage.py
+        # ---- Hidden directories/Private packages ----
+        "[._]*",
+    )
+
+    DEFAULT_EXCLUDE = tuple(chain_iter((p, f"{p}.*") for p in _EXCLUDE))
+    """Reserved package names"""
+
+    @staticmethod
+    def _looks_like_package(_path: StrPath, package_name: str) -> bool:
+        names = package_name.split('.')
+        # Consider PEP 561
+        root_pkg_is_valid = names[0].isidentifier() or names[0].endswith("-stubs")
+        return root_pkg_is_valid and all(name.isidentifier() for name in names[1:])
+
+
+class FlatLayoutModuleFinder(ModuleFinder):
+    DEFAULT_EXCLUDE = (
+        "setup",
+        "conftest",
+        "test",
+        "tests",
+        "example",
+        "examples",
+        "build",
+        # ---- Task runners ----
+        "toxfile",
+        "noxfile",
+        "pavement",
+        "dodo",
+        "tasks",
+        "fabfile",
+        # ---- Other tools ----
+        "[Ss][Cc]onstruct",  # SCons
+        "conanfile",  # Connan: C/C++ build tool
+        "manage",  # Django
+        "benchmark",
+        "benchmarks",
+        "exercise",
+        "exercises",
+        # ---- Hidden files/Private modules ----
+        "[._]*",
+    )
+    """Reserved top-level module names"""
+
+
+def _find_packages_within(root_pkg: str, pkg_dir: StrPath) -> list[str]:
+    nested = PEP420PackageFinder.find(pkg_dir)
+    return [root_pkg] + [".".join((root_pkg, n)) for n in nested]
+
+
+class ConfigDiscovery:
+    """Fill-in metadata and options that can be automatically derived
+    (from other metadata/options, the file system or conventions)
+    """
+
+    def __init__(self, distribution: Distribution) -> None:
+        self.dist = distribution
+        self._called = False
+        self._disabled = False
+        self._skip_ext_modules = False
+
+    def _disable(self):
+        """Internal API to disable automatic discovery"""
+        self._disabled = True
+
+    def _ignore_ext_modules(self):
+        """Internal API to disregard ext_modules.
+
+        Normally auto-discovery would not be triggered if ``ext_modules`` are set
+        (this is done for backward compatibility with existing packages relying on
+        ``setup.py`` or ``setup.cfg``). However, ``setuptools`` can call this function
+        to ignore given ``ext_modules`` and proceed with the auto-discovery if
+        ``packages`` and ``py_modules`` are not given (e.g. when using pyproject.toml
+        metadata).
+        """
+        self._skip_ext_modules = True
+
+    @property
+    def _root_dir(self) -> StrPath:
+        # The best is to wait until `src_root` is set in dist, before using _root_dir.
+        return self.dist.src_root or os.curdir
+
+    @property
+    def _package_dir(self) -> dict[str, str]:
+        if self.dist.package_dir is None:
+            return {}
+        return self.dist.package_dir
+
+    def __call__(
+        self, force: bool = False, name: bool = True, ignore_ext_modules: bool = False
+    ):
+        """Automatically discover missing configuration fields
+        and modifies the given ``distribution`` object in-place.
+
+        Note that by default this will only have an effect the first time the
+        ``ConfigDiscovery`` object is called.
+
+        To repeatedly invoke automatic discovery (e.g. when the project
+        directory changes), please use ``force=True`` (or create a new
+        ``ConfigDiscovery`` instance).
+        """
+        if force is False and (self._called or self._disabled):
+            # Avoid overhead of multiple calls
+            return
+
+        self._analyse_package_layout(ignore_ext_modules)
+        if name:
+            self.analyse_name()  # depends on ``packages`` and ``py_modules``
+
+        self._called = True
+
+    def _explicitly_specified(self, ignore_ext_modules: bool) -> bool:
+        """``True`` if the user has specified some form of package/module listing"""
+        ignore_ext_modules = ignore_ext_modules or self._skip_ext_modules
+        ext_modules = not (self.dist.ext_modules is None or ignore_ext_modules)
+        return (
+            self.dist.packages is not None
+            or self.dist.py_modules is not None
+            or ext_modules
+            or hasattr(self.dist, "configuration")
+            and self.dist.configuration
+            # ^ Some projects use numpy.distutils.misc_util.Configuration
+        )
+
+    def _analyse_package_layout(self, ignore_ext_modules: bool) -> bool:
+        if self._explicitly_specified(ignore_ext_modules):
+            # For backward compatibility, just try to find modules/packages
+            # when nothing is given
+            return True
+
+        log.debug(
+            "No `packages` or `py_modules` configuration, performing "
+            "automatic discovery."
+        )
+
+        return (
+            self._analyse_explicit_layout()
+            or self._analyse_src_layout()
+            # flat-layout is the trickiest for discovery so it should be last
+            or self._analyse_flat_layout()
+        )
+
+    def _analyse_explicit_layout(self) -> bool:
+        """The user can explicitly give a package layout via ``package_dir``"""
+        package_dir = self._package_dir.copy()  # don't modify directly
+        package_dir.pop("", None)  # This falls under the "src-layout" umbrella
+        root_dir = self._root_dir
+
+        if not package_dir:
+            return False
+
+        log.debug(f"`explicit-layout` detected -- analysing {package_dir}")
+        pkgs = chain_iter(
+            _find_packages_within(pkg, os.path.join(root_dir, parent_dir))
+            for pkg, parent_dir in package_dir.items()
+        )
+        self.dist.packages = list(pkgs)
+        log.debug(f"discovered packages -- {self.dist.packages}")
+        return True
+
+    def _analyse_src_layout(self) -> bool:
+        """Try to find all packages or modules under the ``src`` directory
+        (or anything pointed by ``package_dir[""]``).
+
+        The "src-layout" is relatively safe for automatic discovery.
+        We assume that everything within is meant to be included in the
+        distribution.
+
+        If ``package_dir[""]`` is not given, but the ``src`` directory exists,
+        this function will set ``package_dir[""] = "src"``.
+        """
+        package_dir = self._package_dir
+        src_dir = os.path.join(self._root_dir, package_dir.get("", "src"))
+        if not os.path.isdir(src_dir):
+            return False
+
+        log.debug(f"`src-layout` detected -- analysing {src_dir}")
+        package_dir.setdefault("", os.path.basename(src_dir))
+        self.dist.package_dir = package_dir  # persist eventual modifications
+        self.dist.packages = PEP420PackageFinder.find(src_dir)
+        self.dist.py_modules = ModuleFinder.find(src_dir)
+        log.debug(f"discovered packages -- {self.dist.packages}")
+        log.debug(f"discovered py_modules -- {self.dist.py_modules}")
+        return True
+
+    def _analyse_flat_layout(self) -> bool:
+        """Try to find all packages and modules under the project root.
+
+        Since the ``flat-layout`` is more dangerous in terms of accidentally including
+        extra files/directories, this function is more conservative and will raise an
+        error if multiple packages or modules are found.
+
+        This assumes that multi-package dists are uncommon and refuse to support that
+        use case in order to be able to prevent unintended errors.
+        """
+        log.debug(f"`flat-layout` detected -- analysing {self._root_dir}")
+        return self._analyse_flat_packages() or self._analyse_flat_modules()
+
+    def _analyse_flat_packages(self) -> bool:
+        self.dist.packages = FlatLayoutPackageFinder.find(self._root_dir)
+        top_level = remove_nested_packages(remove_stubs(self.dist.packages))
+        log.debug(f"discovered packages -- {self.dist.packages}")
+        self._ensure_no_accidental_inclusion(top_level, "packages")
+        return bool(top_level)
+
+    def _analyse_flat_modules(self) -> bool:
+        self.dist.py_modules = FlatLayoutModuleFinder.find(self._root_dir)
+        log.debug(f"discovered py_modules -- {self.dist.py_modules}")
+        self._ensure_no_accidental_inclusion(self.dist.py_modules, "modules")
+        return bool(self.dist.py_modules)
+
+    def _ensure_no_accidental_inclusion(self, detected: list[str], kind: str):
+        if len(detected) > 1:
+            from inspect import cleandoc
+
+            from setuptools.errors import PackageDiscoveryError
+
+            msg = f"""Multiple top-level {kind} discovered in a flat-layout: {detected}.
+
+            To avoid accidental inclusion of unwanted files or directories,
+            setuptools will not proceed with this build.
+
+            If you are trying to create a single distribution with multiple {kind}
+            on purpose, you should not rely on automatic discovery.
+            Instead, consider the following options:
+
+            1. set up custom discovery (`find` directive with `include` or `exclude`)
+            2. use a `src-layout`
+            3. explicitly set `py_modules` or `packages` with a list of names
+
+            To find more information, look for "package discovery" on setuptools docs.
+            """
+            raise PackageDiscoveryError(cleandoc(msg))
+
+    def analyse_name(self) -> None:
+        """The packages/modules are the essential contribution of the author.
+        Therefore the name of the distribution can be derived from them.
+        """
+        if self.dist.metadata.name or self.dist.name:
+            # get_name() is not reliable (can return "UNKNOWN")
+            return
+
+        log.debug("No `name` configuration, performing automatic discovery")
+
+        name = (
+            self._find_name_single_package_or_module()
+            or self._find_name_from_packages()
+        )
+        if name:
+            self.dist.metadata.name = name
+
+    def _find_name_single_package_or_module(self) -> str | None:
+        """Exactly one module or package"""
+        for field in ('packages', 'py_modules'):
+            items = getattr(self.dist, field, None) or []
+            if items and len(items) == 1:
+                log.debug(f"Single module/package detected, name: {items[0]}")
+                return items[0]
+
+        return None
+
+    def _find_name_from_packages(self) -> str | None:
+        """Try to find the root package that is not a PEP 420 namespace"""
+        if not self.dist.packages:
+            return None
+
+        packages = remove_stubs(sorted(self.dist.packages, key=len))
+        package_dir = self.dist.package_dir or {}
+
+        parent_pkg = find_parent_package(packages, package_dir, self._root_dir)
+        if parent_pkg:
+            log.debug(f"Common parent package detected, name: {parent_pkg}")
+            return parent_pkg
+
+        log.warn("No parent package detected, impossible to derive `name`")
+        return None
+
+
+def remove_nested_packages(packages: list[str]) -> list[str]:
+    """Remove nested packages from a list of packages.
+
+    >>> remove_nested_packages(["a", "a.b1", "a.b2", "a.b1.c1"])
+    ['a']
+    >>> remove_nested_packages(["a", "b", "c.d", "c.d.e.f", "g.h", "a.a1"])
+    ['a', 'b', 'c.d', 'g.h']
+    """
+    pkgs = sorted(packages, key=len)
+    top_level = pkgs[:]
+    size = len(pkgs)
+    for i, name in enumerate(reversed(pkgs)):
+        if any(name.startswith(f"{other}.") for other in top_level):
+            top_level.pop(size - i - 1)
+
+    return top_level
+
+
+def remove_stubs(packages: list[str]) -> list[str]:
+    """Remove type stubs (:pep:`561`) from a list of packages.
+
+    >>> remove_stubs(["a", "a.b", "a-stubs", "a-stubs.b.c", "b", "c-stubs"])
+    ['a', 'a.b', 'b']
+    """
+    return [pkg for pkg in packages if not pkg.split(".")[0].endswith("-stubs")]
+
+
+def find_parent_package(
+    packages: list[str], package_dir: Mapping[str, str], root_dir: StrPath
+) -> str | None:
+    """Find the parent package that is not a namespace."""
+    packages = sorted(packages, key=len)
+    common_ancestors = []
+    for i, name in enumerate(packages):
+        if not all(n.startswith(f"{name}.") for n in packages[i + 1 :]):
+            # Since packages are sorted by length, this condition is able
+            # to find a list of all common ancestors.
+            # When there is divergence (e.g. multiple root packages)
+            # the list will be empty
+            break
+        common_ancestors.append(name)
+
+    for name in common_ancestors:
+        pkg_path = find_package_path(name, package_dir, root_dir)
+        init = os.path.join(pkg_path, "__init__.py")
+        if os.path.isfile(init):
+            return name
+
+    return None
+
+
+def find_package_path(
+    name: str, package_dir: Mapping[str, str], root_dir: StrPath
+) -> str:
+    """Given a package name, return the path where it should be found on
+    disk, considering the ``package_dir`` option.
+
+    >>> path = find_package_path("my.pkg", {"": "root/is/nested"}, ".")
+    >>> path.replace(os.sep, "/")
+    './root/is/nested/my/pkg'
+
+    >>> path = find_package_path("my.pkg", {"my": "root/is/nested"}, ".")
+    >>> path.replace(os.sep, "/")
+    './root/is/nested/pkg'
+
+    >>> path = find_package_path("my.pkg", {"my.pkg": "root/is/nested"}, ".")
+    >>> path.replace(os.sep, "/")
+    './root/is/nested'
+
+    >>> path = find_package_path("other.pkg", {"my.pkg": "root/is/nested"}, ".")
+    >>> path.replace(os.sep, "/")
+    './other/pkg'
+    """
+    parts = name.split(".")
+    for i in range(len(parts), 0, -1):
+        # Look backwards, the most specific package_dir first
+        partial_name = ".".join(parts[:i])
+        if partial_name in package_dir:
+            parent = package_dir[partial_name]
+            return os.path.join(root_dir, parent, *parts[i:])
+
+    parent = package_dir.get("") or ""
+    return os.path.join(root_dir, *parent.split("/"), *parts)
+
+
+def construct_package_dir(packages: list[str], package_path: StrPath) -> dict[str, str]:
+    parent_pkgs = remove_nested_packages(packages)
+    prefix = Path(package_path).parts
+    return {pkg: "/".join([*prefix, *pkg.split(".")]) for pkg in parent_pkgs}
diff --git a/.venv/lib/python3.12/site-packages/setuptools/dist.py b/.venv/lib/python3.12/site-packages/setuptools/dist.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d972cc49bda84edee28c90be172b17107f00b07
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/dist.py
@@ -0,0 +1,1121 @@
+from __future__ import annotations
+
+import functools
+import io
+import itertools
+import numbers
+import os
+import re
+import sys
+from collections.abc import Iterable, Iterator, MutableMapping, Sequence
+from glob import glob
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, Union
+
+from more_itertools import partition, unique_everseen
+from packaging.markers import InvalidMarker, Marker
+from packaging.specifiers import InvalidSpecifier, SpecifierSet
+from packaging.version import Version
+
+from . import (
+    _entry_points,
+    _reqs,
+    _static,
+    command as _,  # noqa: F401 # imported for side-effects
+)
+from ._importlib import metadata
+from ._normalization import _canonicalize_license_expression
+from ._path import StrPath
+from ._reqs import _StrOrIter
+from .config import pyprojecttoml, setupcfg
+from .discovery import ConfigDiscovery
+from .errors import InvalidConfigError
+from .monkey import get_unpatched
+from .warnings import InformationOnly, SetuptoolsDeprecationWarning
+
+import distutils.cmd
+import distutils.command
+import distutils.core
+import distutils.dist
+import distutils.log
+from distutils.debug import DEBUG
+from distutils.errors import DistutilsOptionError, DistutilsSetupError
+from distutils.fancy_getopt import translate_longopt
+from distutils.util import strtobool
+
+if TYPE_CHECKING:
+    from typing_extensions import TypeAlias
+
+    from pkg_resources import Distribution as _pkg_resources_Distribution
+
+
+__all__ = ['Distribution']
+
+_sequence = tuple, list
+"""
+:meta private:
+
+Supported iterable types that are known to be:
+- ordered (which `set` isn't)
+- not match a str (which `Sequence[str]` does)
+- not imply a nested type (like `dict`)
+for use with `isinstance`.
+"""
+_Sequence: TypeAlias = Union[tuple[str, ...], list[str]]
+# This is how stringifying _Sequence would look in Python 3.10
+_sequence_type_repr = "tuple[str, ...] | list[str]"
+_OrderedStrSequence: TypeAlias = Union[str, dict[str, Any], Sequence[str]]
+"""
+:meta private:
+Avoid single-use iterable. Disallow sets.
+A poor approximation of an OrderedSequence (dict doesn't match a Sequence).
+"""
+
+
+def __getattr__(name: str) -> Any:  # pragma: no cover
+    if name == "sequence":
+        SetuptoolsDeprecationWarning.emit(
+            "`setuptools.dist.sequence` is an internal implementation detail.",
+            "Please define your own `sequence = tuple, list` instead.",
+            due_date=(2025, 8, 28),  # Originally added on 2024-08-27
+        )
+        return _sequence
+    raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
+
+
+def check_importable(dist, attr, value):
+    try:
+        ep = metadata.EntryPoint(value=value, name=None, group=None)
+        assert not ep.extras
+    except (TypeError, ValueError, AttributeError, AssertionError) as e:
+        raise DistutilsSetupError(
+            f"{attr!r} must be importable 'module:attrs' string (got {value!r})"
+        ) from e
+
+
+def assert_string_list(dist, attr: str, value: _Sequence) -> None:
+    """Verify that value is a string list"""
+    try:
+        # verify that value is a list or tuple to exclude unordered
+        # or single-use iterables
+        assert isinstance(value, _sequence)
+        # verify that elements of value are strings
+        assert ''.join(value) != value
+    except (TypeError, ValueError, AttributeError, AssertionError) as e:
+        raise DistutilsSetupError(
+            f"{attr!r} must be of type <{_sequence_type_repr}> (got {value!r})"
+        ) from e
+
+
+def check_nsp(dist, attr, value):
+    """Verify that namespace packages are valid"""
+    ns_packages = value
+    assert_string_list(dist, attr, ns_packages)
+    for nsp in ns_packages:
+        if not dist.has_contents_for(nsp):
+            raise DistutilsSetupError(
+                f"Distribution contains no modules or packages for namespace package {nsp!r}"
+            )
+        parent, _sep, _child = nsp.rpartition('.')
+        if parent and parent not in ns_packages:
+            distutils.log.warn(
+                "WARNING: %r is declared as a package namespace, but %r"
+                " is not: please correct this in setup.py",
+                nsp,
+                parent,
+            )
+        SetuptoolsDeprecationWarning.emit(
+            "The namespace_packages parameter is deprecated.",
+            "Please replace its usage with implicit namespaces (PEP 420).",
+            see_docs="references/keywords.html#keyword-namespace-packages",
+            # TODO: define due_date, it may break old packages that are no longer
+            # maintained (e.g. sphinxcontrib extensions) when installed from source.
+            # Warning officially introduced in May 2022, however the deprecation
+            # was mentioned much earlier in the docs (May 2020, see #2149).
+        )
+
+
+def check_extras(dist, attr, value):
+    """Verify that extras_require mapping is valid"""
+    try:
+        list(itertools.starmap(_check_extra, value.items()))
+    except (TypeError, ValueError, AttributeError) as e:
+        raise DistutilsSetupError(
+            "'extras_require' must be a dictionary whose values are "
+            "strings or lists of strings containing valid project/version "
+            "requirement specifiers."
+        ) from e
+
+
+def _check_extra(extra, reqs):
+    _name, _sep, marker = extra.partition(':')
+    try:
+        _check_marker(marker)
+    except InvalidMarker:
+        msg = f"Invalid environment marker: {marker} ({extra!r})"
+        raise DistutilsSetupError(msg) from None
+    list(_reqs.parse(reqs))
+
+
+def _check_marker(marker):
+    if not marker:
+        return
+    m = Marker(marker)
+    m.evaluate()
+
+
+def assert_bool(dist, attr, value):
+    """Verify that value is True, False, 0, or 1"""
+    if bool(value) != value:
+        raise DistutilsSetupError(f"{attr!r} must be a boolean value (got {value!r})")
+
+
+def invalid_unless_false(dist, attr, value):
+    if not value:
+        DistDeprecationWarning.emit(f"{attr} is ignored.")
+        # TODO: should there be a `due_date` here?
+        return
+    raise DistutilsSetupError(f"{attr} is invalid.")
+
+
+def check_requirements(dist, attr: str, value: _OrderedStrSequence) -> None:
+    """Verify that install_requires is a valid requirements list"""
+    try:
+        list(_reqs.parse(value))
+        if isinstance(value, set):
+            raise TypeError("Unordered types are not allowed")
+    except (TypeError, ValueError) as error:
+        msg = (
+            f"{attr!r} must be a string or iterable of strings "
+            f"containing valid project/version requirement specifiers; {error}"
+        )
+        raise DistutilsSetupError(msg) from error
+
+
+def check_specifier(dist, attr, value):
+    """Verify that value is a valid version specifier"""
+    try:
+        SpecifierSet(value)
+    except (InvalidSpecifier, AttributeError) as error:
+        msg = f"{attr!r} must be a string containing valid version specifiers; {error}"
+        raise DistutilsSetupError(msg) from error
+
+
+def check_entry_points(dist, attr, value):
+    """Verify that entry_points map is parseable"""
+    try:
+        _entry_points.load(value)
+    except Exception as e:
+        raise DistutilsSetupError(e) from e
+
+
+def check_package_data(dist, attr, value):
+    """Verify that value is a dictionary of package names to glob lists"""
+    if not isinstance(value, dict):
+        raise DistutilsSetupError(
+            f"{attr!r} must be a dictionary mapping package names to lists of "
+            "string wildcard patterns"
+        )
+    for k, v in value.items():
+        if not isinstance(k, str):
+            raise DistutilsSetupError(
+                f"keys of {attr!r} dict must be strings (got {k!r})"
+            )
+        assert_string_list(dist, f'values of {attr!r} dict', v)
+
+
+def check_packages(dist, attr, value):
+    for pkgname in value:
+        if not re.match(r'\w+(\.\w+)*', pkgname):
+            distutils.log.warn(
+                "WARNING: %r not a valid package name; please use only "
+                ".-separated package names in setup.py",
+                pkgname,
+            )
+
+
+if TYPE_CHECKING:
+    # Work around a mypy issue where type[T] can't be used as a base: https://github.com/python/mypy/issues/10962
+    from distutils.core import Distribution as _Distribution
+else:
+    _Distribution = get_unpatched(distutils.core.Distribution)
+
+
+class Distribution(_Distribution):
+    """Distribution with support for tests and package data
+
+    This is an enhanced version of 'distutils.dist.Distribution' that
+    effectively adds the following new optional keyword arguments to 'setup()':
+
+     'install_requires' -- a string or sequence of strings specifying project
+        versions that the distribution requires when installed, in the format
+        used by 'pkg_resources.require()'.  They will be installed
+        automatically when the package is installed.  If you wish to use
+        packages that are not available in PyPI, or want to give your users an
+        alternate download location, you can add a 'find_links' option to the
+        '[easy_install]' section of your project's 'setup.cfg' file, and then
+        setuptools will scan the listed web pages for links that satisfy the
+        requirements.
+
+     'extras_require' -- a dictionary mapping names of optional "extras" to the
+        additional requirement(s) that using those extras incurs. For example,
+        this::
+
+            extras_require = dict(reST = ["docutils>=0.3", "reSTedit"])
+
+        indicates that the distribution can optionally provide an extra
+        capability called "reST", but it can only be used if docutils and
+        reSTedit are installed.  If the user installs your package using
+        EasyInstall and requests one of your extras, the corresponding
+        additional requirements will be installed if needed.
+
+     'package_data' -- a dictionary mapping package names to lists of filenames
+        or globs to use to find data files contained in the named packages.
+        If the dictionary has filenames or globs listed under '""' (the empty
+        string), those names will be searched for in every package, in addition
+        to any names for the specific package.  Data files found using these
+        names/globs will be installed along with the package, in the same
+        location as the package.  Note that globs are allowed to reference
+        the contents of non-package subdirectories, as long as you use '/' as
+        a path separator.  (Globs are automatically converted to
+        platform-specific paths at runtime.)
+
+    In addition to these new keywords, this class also has several new methods
+    for manipulating the distribution's contents.  For example, the 'include()'
+    and 'exclude()' methods can be thought of as in-place add and subtract
+    commands that add or remove packages, modules, extensions, and so on from
+    the distribution.
+    """
+
+    _DISTUTILS_UNSUPPORTED_METADATA = {
+        'long_description_content_type': lambda: None,
+        'project_urls': dict,
+        'provides_extras': dict,  # behaves like an ordered set
+        'license_expression': lambda: None,
+        'license_file': lambda: None,
+        'license_files': lambda: None,
+        'install_requires': list,
+        'extras_require': dict,
+    }
+
+    # Used by build_py, editable_wheel and install_lib commands for legacy namespaces
+    namespace_packages: list[str]  #: :meta private: DEPRECATED
+
+    # Any: Dynamic assignment results in Incompatible types in assignment
+    def __init__(self, attrs: MutableMapping[str, Any] | None = None) -> None:
+        have_package_data = hasattr(self, "package_data")
+        if not have_package_data:
+            self.package_data: dict[str, list[str]] = {}
+        attrs = attrs or {}
+        self.dist_files: list[tuple[str, str, str]] = []
+        self.include_package_data: bool | None = None
+        self.exclude_package_data: dict[str, list[str]] | None = None
+        # Filter-out setuptools' specific options.
+        self.src_root: str | None = attrs.pop("src_root", None)
+        self.dependency_links: list[str] = attrs.pop('dependency_links', [])
+        self.setup_requires: list[str] = attrs.pop('setup_requires', [])
+        for ep in metadata.entry_points(group='distutils.setup_keywords'):
+            vars(self).setdefault(ep.name, None)
+
+        metadata_only = set(self._DISTUTILS_UNSUPPORTED_METADATA)
+        metadata_only -= {"install_requires", "extras_require"}
+        dist_attrs = {k: v for k, v in attrs.items() if k not in metadata_only}
+        _Distribution.__init__(self, dist_attrs)
+
+        # Private API (setuptools-use only, not restricted to Distribution)
+        # Stores files that are referenced by the configuration and need to be in the
+        # sdist (e.g. `version = file: VERSION.txt`)
+        self._referenced_files = set[str]()
+
+        self.set_defaults = ConfigDiscovery(self)
+
+        self._set_metadata_defaults(attrs)
+
+        self.metadata.version = self._normalize_version(self.metadata.version)
+        self._finalize_requires()
+
+    def _validate_metadata(self):
+        required = {"name"}
+        provided = {
+            key
+            for key in vars(self.metadata)
+            if getattr(self.metadata, key, None) is not None
+        }
+        missing = required - provided
+
+        if missing:
+            msg = f"Required package metadata is missing: {missing}"
+            raise DistutilsSetupError(msg)
+
+    def _set_metadata_defaults(self, attrs):
+        """
+        Fill-in missing metadata fields not supported by distutils.
+        Some fields may have been set by other tools (e.g. pbr).
+        Those fields (vars(self.metadata)) take precedence to
+        supplied attrs.
+        """
+        for option, default in self._DISTUTILS_UNSUPPORTED_METADATA.items():
+            vars(self.metadata).setdefault(option, attrs.get(option, default()))
+
+    @staticmethod
+    def _normalize_version(version):
+        from . import sic
+
+        if isinstance(version, numbers.Number):
+            # Some people apparently take "version number" too literally :)
+            version = str(version)
+        elif isinstance(version, sic) or version is None:
+            return version
+
+        normalized = str(Version(version))
+        if version != normalized:
+            InformationOnly.emit(f"Normalizing '{version}' to '{normalized}'")
+            return normalized
+        return version
+
+    def _finalize_requires(self):
+        """
+        Set `metadata.python_requires` and fix environment markers
+        in `install_requires` and `extras_require`.
+        """
+        if getattr(self, 'python_requires', None):
+            self.metadata.python_requires = self.python_requires
+
+        self._normalize_requires()
+        self.metadata.install_requires = self.install_requires
+        self.metadata.extras_require = self.extras_require
+
+        if self.extras_require:
+            for extra in self.extras_require.keys():
+                # Setuptools allows a weird ": syntax for extras
+                extra = extra.split(':')[0]
+                if extra:
+                    self.metadata.provides_extras.setdefault(extra)
+
+    def _normalize_requires(self):
+        """Make sure requirement-related attributes exist and are normalized"""
+        install_requires = getattr(self, "install_requires", None) or []
+        extras_require = getattr(self, "extras_require", None) or {}
+
+        # Preserve the "static"-ness of values parsed from config files
+        list_ = _static.List if _static.is_static(install_requires) else list
+        self.install_requires = list_(map(str, _reqs.parse(install_requires)))
+
+        dict_ = _static.Dict if _static.is_static(extras_require) else dict
+        self.extras_require = dict_(
+            (k, list(map(str, _reqs.parse(v or [])))) for k, v in extras_require.items()
+        )
+
+    def _finalize_license_expression(self) -> None:
+        """
+        Normalize license and license_expression.
+        >>> dist = Distribution({"license_expression": _static.Str("mit aNd  gpl-3.0-OR-later")})
+        >>> _static.is_static(dist.metadata.license_expression)
+        True
+        >>> dist._finalize_license_expression()
+        >>> _static.is_static(dist.metadata.license_expression)  # preserve "static-ness"
+        True
+        >>> print(dist.metadata.license_expression)
+        MIT AND GPL-3.0-or-later
+        """
+        classifiers = self.metadata.get_classifiers()
+        license_classifiers = [cl for cl in classifiers if cl.startswith("License :: ")]
+
+        license_expr = self.metadata.license_expression
+        if license_expr:
+            str_ = _static.Str if _static.is_static(license_expr) else str
+            normalized = str_(_canonicalize_license_expression(license_expr))
+            if license_expr != normalized:
+                InformationOnly.emit(f"Normalizing '{license_expr}' to '{normalized}'")
+                self.metadata.license_expression = normalized
+            if license_classifiers:
+                raise InvalidConfigError(
+                    "License classifiers have been superseded by license expressions "
+                    "(see https://peps.python.org/pep-0639/). Please remove:\n\n"
+                    + "\n".join(license_classifiers),
+                )
+        elif license_classifiers:
+            pypa_guides = "guides/writing-pyproject-toml/#license"
+            SetuptoolsDeprecationWarning.emit(
+                "License classifiers are deprecated.",
+                "Please consider removing the following classifiers in favor of a "
+                "SPDX license expression:\n\n" + "\n".join(license_classifiers),
+                see_url=f"https://packaging.python.org/en/latest/{pypa_guides}",
+                # Warning introduced on 2025-02-17
+                # TODO: Should we add a due date? It may affect old/unmaintained
+                #       packages in the ecosystem and cause problems...
+            )
+
+    def _finalize_license_files(self) -> None:
+        """Compute names of all license files which should be included."""
+        license_files: list[str] | None = self.metadata.license_files
+        patterns = license_files or []
+
+        license_file: str | None = self.metadata.license_file
+        if license_file and license_file not in patterns:
+            patterns.append(license_file)
+
+        if license_files is None and license_file is None:
+            # Default patterns match the ones wheel uses
+            # See https://wheel.readthedocs.io/en/stable/user_guide.html
+            # -> 'Including license files in the generated wheel file'
+            patterns = ['LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*']
+            files = self._expand_patterns(patterns, enforce_match=False)
+        else:  # Patterns explicitly given by the user
+            files = self._expand_patterns(patterns, enforce_match=True)
+
+        self.metadata.license_files = list(unique_everseen(files))
+
+    @classmethod
+    def _expand_patterns(
+        cls, patterns: list[str], enforce_match: bool = True
+    ) -> Iterator[str]:
+        """
+        >>> list(Distribution._expand_patterns(['LICENSE']))
+        ['LICENSE']
+        >>> list(Distribution._expand_patterns(['pyproject.toml', 'LIC*']))
+        ['pyproject.toml', 'LICENSE']
+        >>> list(Distribution._expand_patterns(['setuptools/**/pyprojecttoml.py']))
+        ['setuptools/config/pyprojecttoml.py']
+        """
+        return (
+            path.replace(os.sep, "/")
+            for pattern in patterns
+            for path in sorted(cls._find_pattern(pattern, enforce_match))
+            if not path.endswith('~') and os.path.isfile(path)
+        )
+
+    @staticmethod
+    def _find_pattern(pattern: str, enforce_match: bool = True) -> list[str]:
+        r"""
+        >>> Distribution._find_pattern("LICENSE")
+        ['LICENSE']
+        >>> Distribution._find_pattern("/LICENSE.MIT")
+        Traceback (most recent call last):
+        ...
+        setuptools.errors.InvalidConfigError: Pattern '/LICENSE.MIT' should be relative...
+        >>> Distribution._find_pattern("../LICENSE.MIT")
+        Traceback (most recent call last):
+        ...
+        setuptools.warnings.SetuptoolsDeprecationWarning: ...Pattern '../LICENSE.MIT' cannot contain '..'...
+        >>> Distribution._find_pattern("LICEN{CSE*")
+        Traceback (most recent call last):
+        ...
+        setuptools.warnings.SetuptoolsDeprecationWarning: ...Pattern 'LICEN{CSE*' contains invalid characters...
+        """
+        pypa_guides = "specifications/glob-patterns/"
+        if ".." in pattern:
+            SetuptoolsDeprecationWarning.emit(
+                f"Pattern {pattern!r} cannot contain '..'",
+                """
+                Please ensure the files specified are contained by the root
+                of the Python package (normally marked by `pyproject.toml`).
+                """,
+                see_url=f"https://packaging.python.org/en/latest/{pypa_guides}",
+                due_date=(2026, 3, 20),  # Introduced in 2025-03-20
+                # Replace with InvalidConfigError after deprecation
+            )
+        if pattern.startswith((os.sep, "/")) or ":\\" in pattern:
+            raise InvalidConfigError(
+                f"Pattern {pattern!r} should be relative and must not start with '/'"
+            )
+        if re.match(r'^[\w\-\.\/\*\?\[\]]+$', pattern) is None:
+            SetuptoolsDeprecationWarning.emit(
+                "Please provide a valid glob pattern.",
+                "Pattern {pattern!r} contains invalid characters.",
+                pattern=pattern,
+                see_url=f"https://packaging.python.org/en/latest/{pypa_guides}",
+                due_date=(2026, 3, 20),  # Introduced in 2025-02-20
+            )
+
+        found = glob(pattern, recursive=True)
+
+        if enforce_match and not found:
+            SetuptoolsDeprecationWarning.emit(
+                "Cannot find any files for the given pattern.",
+                "Pattern {pattern!r} did not match any files.",
+                pattern=pattern,
+                due_date=(2026, 3, 20),  # Introduced in 2025-02-20
+                # PEP 639 requires us to error, but as a transition period
+                # we will only issue a warning to give people time to prepare.
+                # After the transition, this should raise an InvalidConfigError.
+            )
+        return found
+
+    # FIXME: 'Distribution._parse_config_files' is too complex (14)
+    def _parse_config_files(self, filenames=None):  # noqa: C901
+        """
+        Adapted from distutils.dist.Distribution.parse_config_files,
+        this method provides the same functionality in subtly-improved
+        ways.
+        """
+        from configparser import ConfigParser
+
+        # Ignore install directory options if we have a venv
+        ignore_options = (
+            []
+            if sys.prefix == sys.base_prefix
+            else [
+                'install-base',
+                'install-platbase',
+                'install-lib',
+                'install-platlib',
+                'install-purelib',
+                'install-headers',
+                'install-scripts',
+                'install-data',
+                'prefix',
+                'exec-prefix',
+                'home',
+                'user',
+                'root',
+            ]
+        )
+
+        ignore_options = frozenset(ignore_options)
+
+        if filenames is None:
+            filenames = self.find_config_files()
+
+        if DEBUG:
+            self.announce("Distribution.parse_config_files():")
+
+        parser = ConfigParser()
+        parser.optionxform = str
+        for filename in filenames:
+            with open(filename, encoding='utf-8') as reader:
+                if DEBUG:
+                    self.announce("  reading {filename}".format(**locals()))
+                parser.read_file(reader)
+            for section in parser.sections():
+                options = parser.options(section)
+                opt_dict = self.get_option_dict(section)
+
+                for opt in options:
+                    if opt == '__name__' or opt in ignore_options:
+                        continue
+
+                    val = parser.get(section, opt)
+                    opt = self._enforce_underscore(opt, section)
+                    opt = self._enforce_option_lowercase(opt, section)
+                    opt_dict[opt] = (filename, val)
+
+            # Make the ConfigParser forget everything (so we retain
+            # the original filenames that options come from)
+            parser.__init__()
+
+        if 'global' not in self.command_options:
+            return
+
+        # If there was a "global" section in the config file, use it
+        # to set Distribution options.
+
+        for opt, (src, val) in self.command_options['global'].items():
+            alias = self.negative_opt.get(opt)
+            if alias:
+                val = not strtobool(val)
+            elif opt in ('verbose', 'dry_run'):  # ugh!
+                val = strtobool(val)
+
+            try:
+                setattr(self, alias or opt, val)
+            except ValueError as e:
+                raise DistutilsOptionError(e) from e
+
+    def _enforce_underscore(self, opt: str, section: str) -> str:
+        if "-" not in opt or self._skip_setupcfg_normalization(section):
+            return opt
+
+        underscore_opt = opt.replace('-', '_')
+        affected = f"(Affected: {self.metadata.name})." if self.metadata.name else ""
+        SetuptoolsDeprecationWarning.emit(
+            f"Invalid dash-separated key {opt!r} in {section!r} (setup.cfg), "
+            f"please use the underscore name {underscore_opt!r} instead.",
+            f"""
+            Usage of dash-separated {opt!r} will not be supported in future
+            versions. Please use the underscore name {underscore_opt!r} instead.
+            {affected}
+            """,
+            see_docs="userguide/declarative_config.html",
+            due_date=(2026, 3, 3),
+            # Warning initially introduced in 3 Mar 2021
+        )
+        return underscore_opt
+
+    def _enforce_option_lowercase(self, opt: str, section: str) -> str:
+        if opt.islower() or self._skip_setupcfg_normalization(section):
+            return opt
+
+        lowercase_opt = opt.lower()
+        affected = f"(Affected: {self.metadata.name})." if self.metadata.name else ""
+        SetuptoolsDeprecationWarning.emit(
+            f"Invalid uppercase key {opt!r} in {section!r} (setup.cfg), "
+            f"please use lowercase {lowercase_opt!r} instead.",
+            f"""
+            Usage of uppercase key {opt!r} in {section!r} will not be supported in
+            future versions. Please use lowercase {lowercase_opt!r} instead.
+            {affected}
+            """,
+            see_docs="userguide/declarative_config.html",
+            due_date=(2026, 3, 3),
+            # Warning initially introduced in 6 Mar 2021
+        )
+        return lowercase_opt
+
+    def _skip_setupcfg_normalization(self, section: str) -> bool:
+        skip = (
+            'options.extras_require',
+            'options.data_files',
+            'options.entry_points',
+            'options.package_data',
+            'options.exclude_package_data',
+        )
+        return section in skip or not self._is_setuptools_section(section)
+
+    def _is_setuptools_section(self, section: str) -> bool:
+        return (
+            section == "metadata"
+            or section.startswith("options")
+            or section in _setuptools_commands()
+        )
+
+    # FIXME: 'Distribution._set_command_options' is too complex (14)
+    def _set_command_options(self, command_obj, option_dict=None):  # noqa: C901
+        """
+        Set the options for 'command_obj' from 'option_dict'.  Basically
+        this means copying elements of a dictionary ('option_dict') to
+        attributes of an instance ('command').
+
+        'command_obj' must be a Command instance.  If 'option_dict' is not
+        supplied, uses the standard option dictionary for this command
+        (from 'self.command_options').
+
+        (Adopted from distutils.dist.Distribution._set_command_options)
+        """
+        command_name = command_obj.get_command_name()
+        if option_dict is None:
+            option_dict = self.get_option_dict(command_name)
+
+        if DEBUG:
+            self.announce(f"  setting options for '{command_name}' command:")
+        for option, (source, value) in option_dict.items():
+            if DEBUG:
+                self.announce(f"    {option} = {value} (from {source})")
+            try:
+                bool_opts = [translate_longopt(o) for o in command_obj.boolean_options]
+            except AttributeError:
+                bool_opts = []
+            try:
+                neg_opt = command_obj.negative_opt
+            except AttributeError:
+                neg_opt = {}
+
+            try:
+                is_string = isinstance(value, str)
+                if option in neg_opt and is_string:
+                    setattr(command_obj, neg_opt[option], not strtobool(value))
+                elif option in bool_opts and is_string:
+                    setattr(command_obj, option, strtobool(value))
+                elif hasattr(command_obj, option):
+                    setattr(command_obj, option, value)
+                else:
+                    raise DistutilsOptionError(
+                        f"error in {source}: command '{command_name}' has no such option '{option}'"
+                    )
+            except ValueError as e:
+                raise DistutilsOptionError(e) from e
+
+    def _get_project_config_files(self, filenames: Iterable[StrPath] | None):
+        """Add default file and split between INI and TOML"""
+        tomlfiles = []
+        standard_project_metadata = Path(self.src_root or os.curdir, "pyproject.toml")
+        if filenames is not None:
+            parts = partition(lambda f: Path(f).suffix == ".toml", filenames)
+            filenames = list(parts[0])  # 1st element => predicate is False
+            tomlfiles = list(parts[1])  # 2nd element => predicate is True
+        elif standard_project_metadata.exists():
+            tomlfiles = [standard_project_metadata]
+        return filenames, tomlfiles
+
+    def parse_config_files(
+        self,
+        filenames: Iterable[StrPath] | None = None,
+        ignore_option_errors: bool = False,
+    ) -> None:
+        """Parses configuration files from various levels
+        and loads configuration.
+        """
+        inifiles, tomlfiles = self._get_project_config_files(filenames)
+
+        self._parse_config_files(filenames=inifiles)
+
+        setupcfg.parse_configuration(
+            self, self.command_options, ignore_option_errors=ignore_option_errors
+        )
+        for filename in tomlfiles:
+            pyprojecttoml.apply_configuration(self, filename, ignore_option_errors)
+
+        self._finalize_requires()
+        self._finalize_license_expression()
+        self._finalize_license_files()
+
+    def fetch_build_eggs(
+        self, requires: _StrOrIter
+    ) -> list[_pkg_resources_Distribution]:
+        """Resolve pre-setup requirements"""
+        from .installer import _fetch_build_eggs
+
+        return _fetch_build_eggs(self, requires)
+
+    def finalize_options(self) -> None:
+        """
+        Allow plugins to apply arbitrary operations to the
+        distribution. Each hook may optionally define a 'order'
+        to influence the order of execution. Smaller numbers
+        go first and the default is 0.
+        """
+        group = 'setuptools.finalize_distribution_options'
+
+        def by_order(hook):
+            return getattr(hook, 'order', 0)
+
+        defined = metadata.entry_points(group=group)
+        filtered = itertools.filterfalse(self._removed, defined)
+        loaded = map(lambda e: e.load(), filtered)
+        for ep in sorted(loaded, key=by_order):
+            ep(self)
+
+    @staticmethod
+    def _removed(ep):
+        """
+        When removing an entry point, if metadata is loaded
+        from an older version of Setuptools, that removed
+        entry point will attempt to be loaded and will fail.
+        See #2765 for more details.
+        """
+        removed = {
+            # removed 2021-09-05
+            '2to3_doctests',
+        }
+        return ep.name in removed
+
+    def _finalize_setup_keywords(self):
+        for ep in metadata.entry_points(group='distutils.setup_keywords'):
+            value = getattr(self, ep.name, None)
+            if value is not None:
+                ep.load()(self, ep.name, value)
+
+    def get_egg_cache_dir(self):
+        from . import windows_support
+
+        egg_cache_dir = os.path.join(os.curdir, '.eggs')
+        if not os.path.exists(egg_cache_dir):
+            os.mkdir(egg_cache_dir)
+            windows_support.hide_file(egg_cache_dir)
+            readme_txt_filename = os.path.join(egg_cache_dir, 'README.txt')
+            with open(readme_txt_filename, 'w', encoding="utf-8") as f:
+                f.write(
+                    'This directory contains eggs that were downloaded '
+                    'by setuptools to build, test, and run plug-ins.\n\n'
+                )
+                f.write(
+                    'This directory caches those eggs to prevent '
+                    'repeated downloads.\n\n'
+                )
+                f.write('However, it is safe to delete this directory.\n\n')
+
+        return egg_cache_dir
+
+    def fetch_build_egg(self, req):
+        """Fetch an egg needed for building"""
+        from .installer import fetch_build_egg
+
+        return fetch_build_egg(self, req)
+
+    def get_command_class(self, command: str) -> type[distutils.cmd.Command]:  # type: ignore[override] # Not doing complex overrides yet
+        """Pluggable version of get_command_class()"""
+        if command in self.cmdclass:
+            return self.cmdclass[command]
+
+        # Special case bdist_wheel so it's never loaded from "wheel"
+        if command == 'bdist_wheel':
+            from .command.bdist_wheel import bdist_wheel
+
+            return bdist_wheel
+
+        eps = metadata.entry_points(group='distutils.commands', name=command)
+        for ep in eps:
+            self.cmdclass[command] = cmdclass = ep.load()
+            return cmdclass
+        else:
+            return _Distribution.get_command_class(self, command)
+
+    def print_commands(self):
+        for ep in metadata.entry_points(group='distutils.commands'):
+            if ep.name not in self.cmdclass:
+                cmdclass = ep.load()
+                self.cmdclass[ep.name] = cmdclass
+        return _Distribution.print_commands(self)
+
+    def get_command_list(self):
+        for ep in metadata.entry_points(group='distutils.commands'):
+            if ep.name not in self.cmdclass:
+                cmdclass = ep.load()
+                self.cmdclass[ep.name] = cmdclass
+        return _Distribution.get_command_list(self)
+
+    def include(self, **attrs) -> None:
+        """Add items to distribution that are named in keyword arguments
+
+        For example, 'dist.include(py_modules=["x"])' would add 'x' to
+        the distribution's 'py_modules' attribute, if it was not already
+        there.
+
+        Currently, this method only supports inclusion for attributes that are
+        lists or tuples.  If you need to add support for adding to other
+        attributes in this or a subclass, you can add an '_include_X' method,
+        where 'X' is the name of the attribute.  The method will be called with
+        the value passed to 'include()'.  So, 'dist.include(foo={"bar":"baz"})'
+        will try to call 'dist._include_foo({"bar":"baz"})', which can then
+        handle whatever special inclusion logic is needed.
+        """
+        for k, v in attrs.items():
+            include = getattr(self, '_include_' + k, None)
+            if include:
+                include(v)
+            else:
+                self._include_misc(k, v)
+
+    def exclude_package(self, package: str) -> None:
+        """Remove packages, modules, and extensions in named package"""
+
+        pfx = package + '.'
+        if self.packages:
+            self.packages = [
+                p for p in self.packages if p != package and not p.startswith(pfx)
+            ]
+
+        if self.py_modules:
+            self.py_modules = [
+                p for p in self.py_modules if p != package and not p.startswith(pfx)
+            ]
+
+        if self.ext_modules:
+            self.ext_modules = [
+                p
+                for p in self.ext_modules
+                if p.name != package and not p.name.startswith(pfx)
+            ]
+
+    def has_contents_for(self, package: str) -> bool:
+        """Return true if 'exclude_package(package)' would do something"""
+
+        pfx = package + '.'
+
+        for p in self.iter_distribution_names():
+            if p == package or p.startswith(pfx):
+                return True
+
+        return False
+
+    def _exclude_misc(self, name: str, value: _Sequence) -> None:
+        """Handle 'exclude()' for list/tuple attrs without a special handler"""
+        if not isinstance(value, _sequence):
+            raise DistutilsSetupError(
+                f"{name}: setting must be of type <{_sequence_type_repr}> (got {value!r})"
+            )
+        try:
+            old = getattr(self, name)
+        except AttributeError as e:
+            raise DistutilsSetupError(f"{name}: No such distribution setting") from e
+        if old is not None and not isinstance(old, _sequence):
+            raise DistutilsSetupError(
+                name + ": this setting cannot be changed via include/exclude"
+            )
+        elif old:
+            setattr(self, name, [item for item in old if item not in value])
+
+    def _include_misc(self, name: str, value: _Sequence) -> None:
+        """Handle 'include()' for list/tuple attrs without a special handler"""
+
+        if not isinstance(value, _sequence):
+            raise DistutilsSetupError(
+                f"{name}: setting must be of type <{_sequence_type_repr}> (got {value!r})"
+            )
+        try:
+            old = getattr(self, name)
+        except AttributeError as e:
+            raise DistutilsSetupError(f"{name}: No such distribution setting") from e
+        if old is None:
+            setattr(self, name, value)
+        elif not isinstance(old, _sequence):
+            raise DistutilsSetupError(
+                name + ": this setting cannot be changed via include/exclude"
+            )
+        else:
+            new = [item for item in value if item not in old]
+            setattr(self, name, list(old) + new)
+
+    def exclude(self, **attrs) -> None:
+        """Remove items from distribution that are named in keyword arguments
+
+        For example, 'dist.exclude(py_modules=["x"])' would remove 'x' from
+        the distribution's 'py_modules' attribute.  Excluding packages uses
+        the 'exclude_package()' method, so all of the package's contained
+        packages, modules, and extensions are also excluded.
+
+        Currently, this method only supports exclusion from attributes that are
+        lists or tuples.  If you need to add support for excluding from other
+        attributes in this or a subclass, you can add an '_exclude_X' method,
+        where 'X' is the name of the attribute.  The method will be called with
+        the value passed to 'exclude()'.  So, 'dist.exclude(foo={"bar":"baz"})'
+        will try to call 'dist._exclude_foo({"bar":"baz"})', which can then
+        handle whatever special exclusion logic is needed.
+        """
+        for k, v in attrs.items():
+            exclude = getattr(self, '_exclude_' + k, None)
+            if exclude:
+                exclude(v)
+            else:
+                self._exclude_misc(k, v)
+
+    def _exclude_packages(self, packages: _Sequence) -> None:
+        if not isinstance(packages, _sequence):
+            raise DistutilsSetupError(
+                f"packages: setting must be of type <{_sequence_type_repr}> (got {packages!r})"
+            )
+        list(map(self.exclude_package, packages))
+
+    def _parse_command_opts(self, parser, args):
+        # Remove --with-X/--without-X options when processing command args
+        self.global_options = self.__class__.global_options
+        self.negative_opt = self.__class__.negative_opt
+
+        # First, expand any aliases
+        command = args[0]
+        aliases = self.get_option_dict('aliases')
+        while command in aliases:
+            _src, alias = aliases[command]
+            del aliases[command]  # ensure each alias can expand only once!
+            import shlex
+
+            args[:1] = shlex.split(alias, True)
+            command = args[0]
+
+        nargs = _Distribution._parse_command_opts(self, parser, args)
+
+        # Handle commands that want to consume all remaining arguments
+        cmd_class = self.get_command_class(command)
+        if getattr(cmd_class, 'command_consumes_arguments', None):
+            self.get_option_dict(command)['args'] = ("command line", nargs)
+            if nargs is not None:
+                return []
+
+        return nargs
+
+    def get_cmdline_options(self) -> dict[str, dict[str, str | None]]:
+        """Return a '{cmd: {opt:val}}' map of all command-line options
+
+        Option names are all long, but do not include the leading '--', and
+        contain dashes rather than underscores.  If the option doesn't take
+        an argument (e.g. '--quiet'), the 'val' is 'None'.
+
+        Note that options provided by config files are intentionally excluded.
+        """
+
+        d: dict[str, dict[str, str | None]] = {}
+
+        for cmd, opts in self.command_options.items():
+            val: str | None
+            for opt, (src, val) in opts.items():
+                if src != "command line":
+                    continue
+
+                opt = opt.replace('_', '-')
+
+                if val == 0:
+                    cmdobj = self.get_command_obj(cmd)
+                    neg_opt = self.negative_opt.copy()
+                    neg_opt.update(getattr(cmdobj, 'negative_opt', {}))
+                    for neg, pos in neg_opt.items():
+                        if pos == opt:
+                            opt = neg
+                            val = None
+                            break
+                    else:
+                        raise AssertionError("Shouldn't be able to get here")
+
+                elif val == 1:
+                    val = None
+
+                d.setdefault(cmd, {})[opt] = val
+
+        return d
+
+    def iter_distribution_names(self):
+        """Yield all packages, modules, and extension names in distribution"""
+
+        yield from self.packages or ()
+
+        yield from self.py_modules or ()
+
+        for ext in self.ext_modules or ():
+            if isinstance(ext, tuple):
+                name, _buildinfo = ext
+            else:
+                name = ext.name
+            if name.endswith('module'):
+                name = name[:-6]
+            yield name
+
+    def handle_display_options(self, option_order):
+        """If there were any non-global "display-only" options
+        (--help-commands or the metadata display options) on the command
+        line, display the requested info and return true; else return
+        false.
+        """
+        import sys
+
+        if self.help_commands:
+            return _Distribution.handle_display_options(self, option_order)
+
+        # Stdout may be StringIO (e.g. in tests)
+        if not isinstance(sys.stdout, io.TextIOWrapper):
+            return _Distribution.handle_display_options(self, option_order)
+
+        # Don't wrap stdout if utf-8 is already the encoding. Provides
+        #  workaround for #334.
+        if sys.stdout.encoding.lower() in ('utf-8', 'utf8'):
+            return _Distribution.handle_display_options(self, option_order)
+
+        # Print metadata in UTF-8 no matter the platform
+        encoding = sys.stdout.encoding
+        sys.stdout.reconfigure(encoding='utf-8')
+        try:
+            return _Distribution.handle_display_options(self, option_order)
+        finally:
+            sys.stdout.reconfigure(encoding=encoding)
+
+    def run_command(self, command) -> None:
+        self.set_defaults()
+        # Postpone defaults until all explicit configuration is considered
+        # (setup() args, config files, command line and plugins)
+
+        super().run_command(command)
+
+
+@functools.cache
+def _setuptools_commands() -> set[str]:
+    try:
+        # Use older API for importlib.metadata compatibility
+        entry_points = metadata.distribution('setuptools').entry_points
+        eps: Iterable[str] = (ep.name for ep in entry_points)
+    except metadata.PackageNotFoundError:
+        # during bootstrapping, distribution doesn't exist
+        eps = []
+    return {*distutils.command.__all__, *eps}
+
+
+class DistDeprecationWarning(SetuptoolsDeprecationWarning):
+    """Class for warning about deprecations in dist in
+    setuptools. Not ignored by default, unlike DeprecationWarning."""
diff --git a/.venv/lib/python3.12/site-packages/setuptools/errors.py b/.venv/lib/python3.12/site-packages/setuptools/errors.py
new file mode 100644
index 0000000000000000000000000000000000000000..990ecbf4e2f18eb188addc9e0466152a20193a90
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/errors.py
@@ -0,0 +1,67 @@
+"""setuptools.errors
+
+Provides exceptions used by setuptools modules.
+"""
+
+from __future__ import annotations
+
+from distutils import errors as _distutils_errors
+
+# Re-export errors from distutils to facilitate the migration to PEP632
+
+ByteCompileError = _distutils_errors.DistutilsByteCompileError
+CCompilerError = _distutils_errors.CCompilerError
+ClassError = _distutils_errors.DistutilsClassError
+CompileError = _distutils_errors.CompileError
+ExecError = _distutils_errors.DistutilsExecError
+FileError = _distutils_errors.DistutilsFileError
+InternalError = _distutils_errors.DistutilsInternalError
+LibError = _distutils_errors.LibError
+LinkError = _distutils_errors.LinkError
+ModuleError = _distutils_errors.DistutilsModuleError
+OptionError = _distutils_errors.DistutilsOptionError
+PlatformError = _distutils_errors.DistutilsPlatformError
+PreprocessError = _distutils_errors.PreprocessError
+SetupError = _distutils_errors.DistutilsSetupError
+TemplateError = _distutils_errors.DistutilsTemplateError
+UnknownFileError = _distutils_errors.UnknownFileError
+
+# The root error class in the hierarchy
+BaseError = _distutils_errors.DistutilsError
+
+
+class InvalidConfigError(OptionError):  # type: ignore[valid-type, misc] # distutils imports are `Any` on python 3.12+
+    """Error used for invalid configurations."""
+
+
+class RemovedConfigError(OptionError):  # type: ignore[valid-type, misc] # distutils imports are `Any` on python 3.12+
+    """Error used for configurations that were deprecated and removed."""
+
+
+class RemovedCommandError(BaseError, RuntimeError):  # type: ignore[valid-type, misc] # distutils imports are `Any` on python 3.12+
+    """Error used for commands that have been removed in setuptools.
+
+    Since ``setuptools`` is built on ``distutils``, simply removing a command
+    from ``setuptools`` will make the behavior fall back to ``distutils``; this
+    error is raised if a command exists in ``distutils`` but has been actively
+    removed in ``setuptools``.
+    """
+
+
+class PackageDiscoveryError(BaseError, RuntimeError):  # type: ignore[valid-type, misc] # distutils imports are `Any` on python 3.12+
+    """Impossible to perform automatic discovery of packages and/or modules.
+
+    The current project layout or given discovery options can lead to problems when
+    scanning the project directory.
+
+    Setuptools might also refuse to complete auto-discovery if an error prone condition
+    is detected (e.g. when a project is organised as a flat-layout but contains
+    multiple directories that can be taken as top-level packages inside a single
+    distribution [*]_). In these situations the users are encouraged to be explicit
+    about which packages to include or to make the discovery parameters more specific.
+
+    .. [*] Since multi-package distributions are uncommon it is very likely that the
+       developers did not intend for all the directories to be packaged, and are just
+       leaving auxiliary code in the repository top-level, such as maintenance-related
+       scripts.
+    """
diff --git a/.venv/lib/python3.12/site-packages/setuptools/extension.py b/.venv/lib/python3.12/site-packages/setuptools/extension.py
new file mode 100644
index 0000000000000000000000000000000000000000..76e03d9d6bdcdbd72e443e90c85d34429c22c261
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/extension.py
@@ -0,0 +1,177 @@
+from __future__ import annotations
+
+import functools
+import re
+from typing import TYPE_CHECKING
+
+from setuptools._path import StrPath
+
+from .monkey import get_unpatched
+
+import distutils.core
+import distutils.errors
+import distutils.extension
+
+
+def _have_cython():
+    """
+    Return True if Cython can be imported.
+    """
+    cython_impl = 'Cython.Distutils.build_ext'
+    try:
+        # from (cython_impl) import build_ext
+        __import__(cython_impl, fromlist=['build_ext']).build_ext
+    except Exception:
+        return False
+    return True
+
+
+# for compatibility
+have_pyrex = _have_cython
+if TYPE_CHECKING:
+    # Work around a mypy issue where type[T] can't be used as a base: https://github.com/python/mypy/issues/10962
+    from distutils.core import Extension as _Extension
+else:
+    _Extension = get_unpatched(distutils.core.Extension)
+
+
+class Extension(_Extension):
+    """
+    Describes a single extension module.
+
+    This means that all source files will be compiled into a single binary file
+    ``.`` (with ```` derived from ``name`` and
+    ```` defined by one of the values in
+    ``importlib.machinery.EXTENSION_SUFFIXES``).
+
+    In the case ``.pyx`` files are passed as ``sources and`` ``Cython`` is **not**
+    installed in the build environment, ``setuptools`` may also try to look for the
+    equivalent ``.cpp`` or ``.c`` files.
+
+    :arg str name:
+      the full name of the extension, including any packages -- ie.
+      *not* a filename or pathname, but Python dotted name
+
+    :arg list[str|os.PathLike[str]] sources:
+      list of source filenames, relative to the distribution root
+      (where the setup script lives), in Unix form (slash-separated)
+      for portability.  Source files may be C, C++, SWIG (.i),
+      platform-specific resource files, or whatever else is recognized
+      by the "build_ext" command as source for a Python extension.
+
+    :keyword list[str] include_dirs:
+      list of directories to search for C/C++ header files (in Unix
+      form for portability)
+
+    :keyword list[tuple[str, str|None]] define_macros:
+      list of macros to define; each macro is defined using a 2-tuple:
+      the first item corresponding to the name of the macro and the second
+      item either a string with its value or None to
+      define it without a particular value (equivalent of "#define
+      FOO" in source or -DFOO on Unix C compiler command line)
+
+    :keyword list[str] undef_macros:
+      list of macros to undefine explicitly
+
+    :keyword list[str] library_dirs:
+      list of directories to search for C/C++ libraries at link time
+
+    :keyword list[str] libraries:
+      list of library names (not filenames or paths) to link against
+
+    :keyword list[str] runtime_library_dirs:
+      list of directories to search for C/C++ libraries at run time
+      (for shared extensions, this is when the extension is loaded).
+      Setting this will cause an exception during build on Windows
+      platforms.
+
+    :keyword list[str] extra_objects:
+      list of extra files to link with (eg. object files not implied
+      by 'sources', static library that must be explicitly specified,
+      binary resource files, etc.)
+
+    :keyword list[str] extra_compile_args:
+      any extra platform- and compiler-specific information to use
+      when compiling the source files in 'sources'.  For platforms and
+      compilers where "command line" makes sense, this is typically a
+      list of command-line arguments, but for other platforms it could
+      be anything.
+
+    :keyword list[str] extra_link_args:
+      any extra platform- and compiler-specific information to use
+      when linking object files together to create the extension (or
+      to create a new static Python interpreter).  Similar
+      interpretation as for 'extra_compile_args'.
+
+    :keyword list[str] export_symbols:
+      list of symbols to be exported from a shared extension.  Not
+      used on all platforms, and not generally necessary for Python
+      extensions, which typically export exactly one symbol: "init" +
+      extension_name.
+
+    :keyword list[str] swig_opts:
+      any extra options to pass to SWIG if a source file has the .i
+      extension.
+
+    :keyword list[str] depends:
+      list of files that the extension depends on
+
+    :keyword str language:
+      extension language (i.e. "c", "c++", "objc"). Will be detected
+      from the source extensions if not provided.
+
+    :keyword bool optional:
+      specifies that a build failure in the extension should not abort the
+      build process, but simply not install the failing extension.
+
+    :keyword bool py_limited_api:
+      opt-in flag for the usage of :doc:`Python's limited API `.
+
+    :raises setuptools.errors.PlatformError: if ``runtime_library_dirs`` is
+      specified on Windows. (since v63)
+    """
+
+    # These 4 are set and used in setuptools/command/build_ext.py
+    # The lack of a default value and risk of `AttributeError` is purposeful
+    # to avoid people forgetting to call finalize_options if they modify the extension list.
+    # See example/rationale in https://github.com/pypa/setuptools/issues/4529.
+    _full_name: str  #: Private API, internal use only.
+    _links_to_dynamic: bool  #: Private API, internal use only.
+    _needs_stub: bool  #: Private API, internal use only.
+    _file_name: str  #: Private API, internal use only.
+
+    def __init__(
+        self,
+        name: str,
+        sources: list[StrPath],
+        *args,
+        py_limited_api: bool = False,
+        **kw,
+    ) -> None:
+        # The *args is needed for compatibility as calls may use positional
+        # arguments. py_limited_api may be set only via keyword.
+        self.py_limited_api = py_limited_api
+        super().__init__(
+            name,
+            sources,  # type: ignore[arg-type] # Vendored version of setuptools supports PathLike
+            *args,
+            **kw,
+        )
+
+    def _convert_pyx_sources_to_lang(self):
+        """
+        Replace sources with .pyx extensions to sources with the target
+        language extension. This mechanism allows language authors to supply
+        pre-converted sources but to prefer the .pyx sources.
+        """
+        if _have_cython():
+            # the build has Cython, so allow it to compile the .pyx files
+            return
+        lang = self.language or ''
+        target_ext = '.cpp' if lang.lower() == 'c++' else '.c'
+        sub = functools.partial(re.sub, '.pyx$', target_ext)
+        self.sources = list(map(sub, self.sources))
+
+
+class Library(Extension):
+    """Just like a regular Extension, but built as a library instead"""
diff --git a/.venv/lib/python3.12/site-packages/setuptools/glob.py b/.venv/lib/python3.12/site-packages/setuptools/glob.py
new file mode 100644
index 0000000000000000000000000000000000000000..1dfff2cd50ff87b8cef9d936f1fc9d4a2478b136
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/glob.py
@@ -0,0 +1,185 @@
+"""
+Filename globbing utility. Mostly a copy of `glob` from Python 3.5.
+
+Changes include:
+ * `yield from` and PEP3102 `*` removed.
+ * Hidden files are not ignored.
+"""
+
+from __future__ import annotations
+
+import fnmatch
+import os
+import re
+from collections.abc import Iterable, Iterator
+from typing import TYPE_CHECKING, AnyStr, overload
+
+if TYPE_CHECKING:
+    from _typeshed import BytesPath, StrOrBytesPath, StrPath
+
+__all__ = ["glob", "iglob", "escape"]
+
+
+def glob(pathname: AnyStr, recursive: bool = False) -> list[AnyStr]:
+    """Return a list of paths matching a pathname pattern.
+
+    The pattern may contain simple shell-style wildcards a la
+    fnmatch. However, unlike fnmatch, filenames starting with a
+    dot are special cases that are not matched by '*' and '?'
+    patterns.
+
+    If recursive is true, the pattern '**' will match any files and
+    zero or more directories and subdirectories.
+    """
+    return list(iglob(pathname, recursive=recursive))
+
+
+def iglob(pathname: AnyStr, recursive: bool = False) -> Iterator[AnyStr]:
+    """Return an iterator which yields the paths matching a pathname pattern.
+
+    The pattern may contain simple shell-style wildcards a la
+    fnmatch. However, unlike fnmatch, filenames starting with a
+    dot are special cases that are not matched by '*' and '?'
+    patterns.
+
+    If recursive is true, the pattern '**' will match any files and
+    zero or more directories and subdirectories.
+    """
+    it = _iglob(pathname, recursive)
+    if recursive and _isrecursive(pathname):
+        s = next(it)  # skip empty string
+        assert not s
+    return it
+
+
+def _iglob(pathname: AnyStr, recursive: bool) -> Iterator[AnyStr]:
+    dirname, basename = os.path.split(pathname)
+    glob_in_dir = glob2 if recursive and _isrecursive(basename) else glob1
+
+    if not has_magic(pathname):
+        if basename:
+            if os.path.lexists(pathname):
+                yield pathname
+        else:
+            # Patterns ending with a slash should match only directories
+            if os.path.isdir(dirname):
+                yield pathname
+        return
+
+    if not dirname:
+        yield from glob_in_dir(dirname, basename)
+        return
+    # `os.path.split()` returns the argument itself as a dirname if it is a
+    # drive or UNC path.  Prevent an infinite recursion if a drive or UNC path
+    # contains magic characters (i.e. r'\\?\C:').
+    if dirname != pathname and has_magic(dirname):
+        dirs: Iterable[AnyStr] = _iglob(dirname, recursive)
+    else:
+        dirs = [dirname]
+    if not has_magic(basename):
+        glob_in_dir = glob0
+    for dirname in dirs:
+        for name in glob_in_dir(dirname, basename):
+            yield os.path.join(dirname, name)
+
+
+# These 2 helper functions non-recursively glob inside a literal directory.
+# They return a list of basenames. `glob1` accepts a pattern while `glob0`
+# takes a literal basename (so it only has to check for its existence).
+
+
+@overload
+def glob1(dirname: StrPath, pattern: str) -> list[str]: ...
+@overload
+def glob1(dirname: BytesPath, pattern: bytes) -> list[bytes]: ...
+def glob1(dirname: StrOrBytesPath, pattern: str | bytes) -> list[str] | list[bytes]:
+    if not dirname:
+        if isinstance(pattern, bytes):
+            dirname = os.curdir.encode('ASCII')
+        else:
+            dirname = os.curdir
+    try:
+        names = os.listdir(dirname)
+    except OSError:
+        return []
+    # mypy false-positives: str or bytes type possibility is always kept in sync
+    return fnmatch.filter(names, pattern)  # type: ignore[type-var, return-value]
+
+
+def glob0(dirname, basename):
+    if not basename:
+        # `os.path.split()` returns an empty basename for paths ending with a
+        # directory separator.  'q*x/' should match only directories.
+        if os.path.isdir(dirname):
+            return [basename]
+    else:
+        if os.path.lexists(os.path.join(dirname, basename)):
+            return [basename]
+    return []
+
+
+# This helper function recursively yields relative pathnames inside a literal
+# directory.
+
+
+@overload
+def glob2(dirname: StrPath, pattern: str) -> Iterator[str]: ...
+@overload
+def glob2(dirname: BytesPath, pattern: bytes) -> Iterator[bytes]: ...
+def glob2(dirname: StrOrBytesPath, pattern: str | bytes) -> Iterator[str | bytes]:
+    assert _isrecursive(pattern)
+    yield pattern[:0]
+    yield from _rlistdir(dirname)
+
+
+# Recursively yields relative pathnames inside a literal directory.
+@overload
+def _rlistdir(dirname: StrPath) -> Iterator[str]: ...
+@overload
+def _rlistdir(dirname: BytesPath) -> Iterator[bytes]: ...
+def _rlistdir(dirname: StrOrBytesPath) -> Iterator[str | bytes]:
+    if not dirname:
+        if isinstance(dirname, bytes):
+            dirname = os.curdir.encode('ASCII')
+        else:
+            dirname = os.curdir
+    try:
+        names = os.listdir(dirname)
+    except OSError:
+        return
+    for x in names:
+        yield x
+        # mypy false-positives: str or bytes type possibility is always kept in sync
+        path = os.path.join(dirname, x) if dirname else x  # type: ignore[arg-type]
+        for y in _rlistdir(path):
+            yield os.path.join(x, y)  # type: ignore[arg-type]
+
+
+magic_check = re.compile('([*?[])')
+magic_check_bytes = re.compile(b'([*?[])')
+
+
+def has_magic(s: str | bytes) -> bool:
+    if isinstance(s, bytes):
+        return magic_check_bytes.search(s) is not None
+    else:
+        return magic_check.search(s) is not None
+
+
+def _isrecursive(pattern: str | bytes) -> bool:
+    if isinstance(pattern, bytes):
+        return pattern == b'**'
+    else:
+        return pattern == '**'
+
+
+def escape(pathname):
+    """Escape all special characters."""
+    # Escaping is done by wrapping any of "*?[" between square brackets.
+    # Metacharacters do not work in the drive part and shouldn't be escaped.
+    drive, pathname = os.path.splitdrive(pathname)
+    if isinstance(pathname, bytes):
+        pathname = magic_check_bytes.sub(rb'[\1]', pathname)
+    else:
+        pathname = magic_check.sub(r'[\1]', pathname)
+    return drive + pathname
diff --git a/.venv/lib/python3.12/site-packages/setuptools/gui-32.exe b/.venv/lib/python3.12/site-packages/setuptools/gui-32.exe
new file mode 100644
index 0000000000000000000000000000000000000000..1eb430c6d614a5daea4139badc09c222a4b0e72a
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/gui-32.exe differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/gui-64.exe b/.venv/lib/python3.12/site-packages/setuptools/gui-64.exe
new file mode 100644
index 0000000000000000000000000000000000000000..031cb77c17ba8d8a983448268851d612e05e80d1
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/gui-64.exe differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/gui-arm64.exe b/.venv/lib/python3.12/site-packages/setuptools/gui-arm64.exe
new file mode 100644
index 0000000000000000000000000000000000000000..1e00ffacb182c2af206e5dd9d9fbc41d236da0d1
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/gui-arm64.exe differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/gui.exe b/.venv/lib/python3.12/site-packages/setuptools/gui.exe
new file mode 100644
index 0000000000000000000000000000000000000000..1eb430c6d614a5daea4139badc09c222a4b0e72a
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/gui.exe differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/installer.py b/.venv/lib/python3.12/site-packages/setuptools/installer.py
new file mode 100644
index 0000000000000000000000000000000000000000..64bc2def078bab5e4fb6aba26981e7b73bfc37a5
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/installer.py
@@ -0,0 +1,150 @@
+from __future__ import annotations
+
+import glob
+import os
+import subprocess
+import sys
+import tempfile
+from functools import partial
+
+from pkg_resources import Distribution
+
+from . import _reqs
+from ._reqs import _StrOrIter
+from .warnings import SetuptoolsDeprecationWarning
+from .wheel import Wheel
+
+from distutils import log
+from distutils.errors import DistutilsError
+
+
+def _fixup_find_links(find_links):
+    """Ensure find-links option end-up being a list of strings."""
+    if isinstance(find_links, str):
+        return find_links.split()
+    assert isinstance(find_links, (tuple, list))
+    return find_links
+
+
+def fetch_build_egg(dist, req):
+    """Fetch an egg needed for building.
+
+    Use pip/wheel to fetch/build a wheel."""
+    _DeprecatedInstaller.emit()
+    _warn_wheel_not_available(dist)
+    return _fetch_build_egg_no_warn(dist, req)
+
+
+def _fetch_build_eggs(dist, requires: _StrOrIter) -> list[Distribution]:
+    import pkg_resources  # Delay import to avoid unnecessary side-effects
+
+    _DeprecatedInstaller.emit(stacklevel=3)
+    _warn_wheel_not_available(dist)
+
+    resolved_dists = pkg_resources.working_set.resolve(
+        _reqs.parse(requires, pkg_resources.Requirement),  # required for compatibility
+        installer=partial(_fetch_build_egg_no_warn, dist),  # avoid warning twice
+        replace_conflicting=True,
+    )
+    for dist in resolved_dists:
+        pkg_resources.working_set.add(dist, replace=True)
+    return resolved_dists
+
+
+def _fetch_build_egg_no_warn(dist, req):  # noqa: C901  # is too complex (16)  # FIXME
+    import pkg_resources  # Delay import to avoid unnecessary side-effects
+
+    # Ignore environment markers; if supplied, it is required.
+    req = strip_marker(req)
+    # Take easy_install options into account, but do not override relevant
+    # pip environment variables (like PIP_INDEX_URL or PIP_QUIET); they'll
+    # take precedence.
+    opts = dist.get_option_dict('easy_install')
+    if 'allow_hosts' in opts:
+        raise DistutilsError(
+            'the `allow-hosts` option is not supported '
+            'when using pip to install requirements.'
+        )
+    quiet = 'PIP_QUIET' not in os.environ and 'PIP_VERBOSE' not in os.environ
+    if 'PIP_INDEX_URL' in os.environ:
+        index_url = None
+    elif 'index_url' in opts:
+        index_url = opts['index_url'][1]
+    else:
+        index_url = None
+    find_links = (
+        _fixup_find_links(opts['find_links'][1])[:] if 'find_links' in opts else []
+    )
+    if dist.dependency_links:
+        find_links.extend(dist.dependency_links)
+    eggs_dir = os.path.realpath(dist.get_egg_cache_dir())
+    environment = pkg_resources.Environment()
+    for egg_dist in pkg_resources.find_distributions(eggs_dir):
+        if egg_dist in req and environment.can_add(egg_dist):
+            return egg_dist
+    with tempfile.TemporaryDirectory() as tmpdir:
+        cmd = [
+            sys.executable,
+            '-m',
+            'pip',
+            '--disable-pip-version-check',
+            'wheel',
+            '--no-deps',
+            '-w',
+            tmpdir,
+        ]
+        if quiet:
+            cmd.append('--quiet')
+        if index_url is not None:
+            cmd.extend(('--index-url', index_url))
+        for link in find_links or []:
+            cmd.extend(('--find-links', link))
+        # If requirement is a PEP 508 direct URL, directly pass
+        # the URL to pip, as `req @ url` does not work on the
+        # command line.
+        cmd.append(req.url or str(req))
+        try:
+            subprocess.check_call(cmd)
+        except subprocess.CalledProcessError as e:
+            raise DistutilsError(str(e)) from e
+        wheel = Wheel(glob.glob(os.path.join(tmpdir, '*.whl'))[0])
+        dist_location = os.path.join(eggs_dir, wheel.egg_name())
+        wheel.install_as_egg(dist_location)
+        dist_metadata = pkg_resources.PathMetadata(
+            dist_location, os.path.join(dist_location, 'EGG-INFO')
+        )
+        return pkg_resources.Distribution.from_filename(
+            dist_location, metadata=dist_metadata
+        )
+
+
+def strip_marker(req):
+    """
+    Return a new requirement without the environment marker to avoid
+    calling pip with something like `babel; extra == "i18n"`, which
+    would always be ignored.
+    """
+    import pkg_resources  # Delay import to avoid unnecessary side-effects
+
+    # create a copy to avoid mutating the input
+    req = pkg_resources.Requirement.parse(str(req))
+    req.marker = None
+    return req
+
+
+def _warn_wheel_not_available(dist):
+    import pkg_resources  # Delay import to avoid unnecessary side-effects
+
+    try:
+        pkg_resources.get_distribution('wheel')
+    except pkg_resources.DistributionNotFound:
+        dist.announce('WARNING: The wheel package is not available.', log.WARN)
+
+
+class _DeprecatedInstaller(SetuptoolsDeprecationWarning):
+    _SUMMARY = "setuptools.installer and fetch_build_eggs are deprecated."
+    _DETAILS = """
+    Requirements should be satisfied by a PEP 517 installer.
+    If you are using pip, you can try `pip install --use-pep517`.
+    """
+    # _DUE_DATE not decided yet
diff --git a/.venv/lib/python3.12/site-packages/setuptools/launch.py b/.venv/lib/python3.12/site-packages/setuptools/launch.py
new file mode 100644
index 0000000000000000000000000000000000000000..0d162647d55777d7afa1bf1e44a6c200a3f82419
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/launch.py
@@ -0,0 +1,36 @@
+"""
+Launch the Python script on the command line after
+setuptools is bootstrapped via import.
+"""
+
+# Note that setuptools gets imported implicitly by the
+# invocation of this script using python -m setuptools.launch
+
+import sys
+import tokenize
+
+
+def run() -> None:
+    """
+    Run the script in sys.argv[1] as if it had
+    been invoked naturally.
+    """
+    __builtins__
+    script_name = sys.argv[1]
+    namespace = dict(
+        __file__=script_name,
+        __name__='__main__',
+        __doc__=None,
+    )
+    sys.argv[:] = sys.argv[1:]
+
+    open_ = getattr(tokenize, 'open', open)
+    with open_(script_name) as fid:
+        script = fid.read()
+    norm_script = script.replace('\\r\\n', '\\n')
+    code = compile(norm_script, script_name, 'exec')
+    exec(code, namespace)
+
+
+if __name__ == '__main__':
+    run()
diff --git a/.venv/lib/python3.12/site-packages/setuptools/logging.py b/.venv/lib/python3.12/site-packages/setuptools/logging.py
new file mode 100644
index 0000000000000000000000000000000000000000..532da899f7dc02f9fea9a44c429086b98fe043d8
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/logging.py
@@ -0,0 +1,40 @@
+import inspect
+import logging
+import sys
+
+from . import monkey
+
+import distutils.log
+
+
+def _not_warning(record):
+    return record.levelno < logging.WARNING
+
+
+def configure() -> None:
+    """
+    Configure logging to emit warning and above to stderr
+    and everything else to stdout. This behavior is provided
+    for compatibility with distutils.log but may change in
+    the future.
+    """
+    err_handler = logging.StreamHandler()
+    err_handler.setLevel(logging.WARNING)
+    out_handler = logging.StreamHandler(sys.stdout)
+    out_handler.addFilter(_not_warning)
+    handlers = err_handler, out_handler
+    logging.basicConfig(
+        format="{message}", style='{', handlers=handlers, level=logging.DEBUG
+    )
+    if inspect.ismodule(distutils.dist.log):
+        monkey.patch_func(set_threshold, distutils.log, 'set_threshold')
+        # For some reason `distutils.log` module is getting cached in `distutils.dist`
+        # and then loaded again when patched,
+        # implying: id(distutils.log) != id(distutils.dist.log).
+        # Make sure the same module object is used everywhere:
+        distutils.dist.log = distutils.log
+
+
+def set_threshold(level: int) -> int:
+    logging.root.setLevel(level * 10)
+    return set_threshold.unpatched(level)
diff --git a/.venv/lib/python3.12/site-packages/setuptools/modified.py b/.venv/lib/python3.12/site-packages/setuptools/modified.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ba02fab68734e1e96fd50d7c4b6ffb1442717fb
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/modified.py
@@ -0,0 +1,18 @@
+try:
+    # Ensure a DistutilsError raised by these methods is the same as distutils.errors.DistutilsError
+    from distutils._modified import (
+        newer,
+        newer_group,
+        newer_pairwise,
+        newer_pairwise_group,
+    )
+except ImportError:
+    # fallback for SETUPTOOLS_USE_DISTUTILS=stdlib, because _modified never existed in stdlib
+    from ._distutils._modified import (
+        newer,
+        newer_group,
+        newer_pairwise,
+        newer_pairwise_group,
+    )
+
+__all__ = ['newer', 'newer_pairwise', 'newer_group', 'newer_pairwise_group']
diff --git a/.venv/lib/python3.12/site-packages/setuptools/monkey.py b/.venv/lib/python3.12/site-packages/setuptools/monkey.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ad1abac295c1df613942b8896edf089a103ae1f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/monkey.py
@@ -0,0 +1,126 @@
+"""
+Monkey patching of distutils.
+"""
+
+from __future__ import annotations
+
+import inspect
+import platform
+import sys
+import types
+from typing import TypeVar, cast, overload
+
+import distutils.filelist
+
+_T = TypeVar("_T")
+_UnpatchT = TypeVar("_UnpatchT", type, types.FunctionType)
+
+
+__all__: list[str] = []
+"""
+Everything is private. Contact the project team
+if you think you need this functionality.
+"""
+
+
+def _get_mro(cls):
+    """
+    Returns the bases classes for cls sorted by the MRO.
+
+    Works around an issue on Jython where inspect.getmro will not return all
+    base classes if multiple classes share the same name. Instead, this
+    function will return a tuple containing the class itself, and the contents
+    of cls.__bases__. See https://github.com/pypa/setuptools/issues/1024.
+    """
+    if platform.python_implementation() == "Jython":
+        return (cls,) + cls.__bases__
+    return inspect.getmro(cls)
+
+
+@overload
+def get_unpatched(item: _UnpatchT) -> _UnpatchT: ...
+@overload
+def get_unpatched(item: object) -> None: ...
+def get_unpatched(
+    item: type | types.FunctionType | object,
+) -> type | types.FunctionType | None:
+    if isinstance(item, type):
+        return get_unpatched_class(item)
+    if isinstance(item, types.FunctionType):
+        return get_unpatched_function(item)
+    return None
+
+
+def get_unpatched_class(cls: type[_T]) -> type[_T]:
+    """Protect against re-patching the distutils if reloaded
+
+    Also ensures that no other distutils extension monkeypatched the distutils
+    first.
+    """
+    external_bases = (
+        cast(type[_T], cls)
+        for cls in _get_mro(cls)
+        if not cls.__module__.startswith('setuptools')
+    )
+    base = next(external_bases)
+    if not base.__module__.startswith('distutils'):
+        msg = f"distutils has already been patched by {cls!r}"
+        raise AssertionError(msg)
+    return base
+
+
+def patch_all():
+    import setuptools
+
+    # we can't patch distutils.cmd, alas
+    distutils.core.Command = setuptools.Command  # type: ignore[misc,assignment] # monkeypatching
+
+    _patch_distribution_metadata()
+
+    # Install Distribution throughout the distutils
+    for module in distutils.dist, distutils.core, distutils.cmd:
+        module.Distribution = setuptools.dist.Distribution
+
+    # Install the patched Extension
+    distutils.core.Extension = setuptools.extension.Extension  # type: ignore[misc,assignment] # monkeypatching
+    distutils.extension.Extension = setuptools.extension.Extension  # type: ignore[misc,assignment] # monkeypatching
+    if 'distutils.command.build_ext' in sys.modules:
+        sys.modules[
+            'distutils.command.build_ext'
+        ].Extension = setuptools.extension.Extension
+
+
+def _patch_distribution_metadata():
+    from . import _core_metadata
+
+    """Patch write_pkg_file and read_pkg_file for higher metadata standards"""
+    for attr in (
+        'write_pkg_info',
+        'write_pkg_file',
+        'read_pkg_file',
+        'get_metadata_version',
+        'get_fullname',
+    ):
+        new_val = getattr(_core_metadata, attr)
+        setattr(distutils.dist.DistributionMetadata, attr, new_val)
+
+
+def patch_func(replacement, target_mod, func_name):
+    """
+    Patch func_name in target_mod with replacement
+
+    Important - original must be resolved by name to avoid
+    patching an already patched function.
+    """
+    original = getattr(target_mod, func_name)
+
+    # set the 'unpatched' attribute on the replacement to
+    # point to the original.
+    vars(replacement).setdefault('unpatched', original)
+
+    # replace the function in the original module
+    setattr(target_mod, func_name, replacement)
+
+
+def get_unpatched_function(candidate):
+    return candidate.unpatched
diff --git a/.venv/lib/python3.12/site-packages/setuptools/msvc.py b/.venv/lib/python3.12/site-packages/setuptools/msvc.py
new file mode 100644
index 0000000000000000000000000000000000000000..313a781ae095bbb20874795e5b87396790f0b9c9
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/msvc.py
@@ -0,0 +1,1536 @@
+"""
+Environment info about Microsoft Compilers.
+
+>>> getfixture('windows_only')
+>>> ei = EnvironmentInfo('amd64')
+"""
+
+from __future__ import annotations
+
+import contextlib
+import itertools
+import json
+import os
+import os.path
+import platform
+from typing import TYPE_CHECKING, TypedDict
+
+from more_itertools import unique_everseen
+
+import distutils.errors
+
+if TYPE_CHECKING:
+    from typing_extensions import LiteralString, NotRequired
+
+# https://github.com/python/mypy/issues/8166
+if not TYPE_CHECKING and platform.system() == 'Windows':
+    import winreg
+    from os import environ
+else:
+    # Mock winreg and environ so the module can be imported on this platform.
+
+    class winreg:
+        HKEY_USERS = None
+        HKEY_CURRENT_USER = None
+        HKEY_LOCAL_MACHINE = None
+        HKEY_CLASSES_ROOT = None
+
+    environ: dict[str, str] = dict()
+
+
+class PlatformInfo:
+    """
+    Current and Target Architectures information.
+
+    Parameters
+    ----------
+    arch: str
+        Target architecture.
+    """
+
+    current_cpu = environ.get('processor_architecture', '').lower()
+
+    def __init__(self, arch) -> None:
+        self.arch = arch.lower().replace('x64', 'amd64')
+
+    @property
+    def target_cpu(self):
+        """
+        Return Target CPU architecture.
+
+        Return
+        ------
+        str
+            Target CPU
+        """
+        return self.arch[self.arch.find('_') + 1 :]
+
+    def target_is_x86(self):
+        """
+        Return True if target CPU is x86 32 bits..
+
+        Return
+        ------
+        bool
+            CPU is x86 32 bits
+        """
+        return self.target_cpu == 'x86'
+
+    def current_is_x86(self):
+        """
+        Return True if current CPU is x86 32 bits..
+
+        Return
+        ------
+        bool
+            CPU is x86 32 bits
+        """
+        return self.current_cpu == 'x86'
+
+    def current_dir(self, hidex86=False, x64=False) -> str:
+        """
+        Current platform specific subfolder.
+
+        Parameters
+        ----------
+        hidex86: bool
+            return '' and not '\x86' if architecture is x86.
+        x64: bool
+            return '\x64' and not '\amd64' if architecture is amd64.
+
+        Return
+        ------
+        str
+            subfolder: '\target', or '' (see hidex86 parameter)
+        """
+        return (
+            ''
+            if (self.current_cpu == 'x86' and hidex86)
+            else r'\x64'
+            if (self.current_cpu == 'amd64' and x64)
+            else rf'\{self.current_cpu}'
+        )
+
+    def target_dir(self, hidex86=False, x64=False) -> str:
+        r"""
+        Target platform specific subfolder.
+
+        Parameters
+        ----------
+        hidex86: bool
+            return '' and not '\x86' if architecture is x86.
+        x64: bool
+            return '\x64' and not '\amd64' if architecture is amd64.
+
+        Return
+        ------
+        str
+            subfolder: '\current', or '' (see hidex86 parameter)
+        """
+        return (
+            ''
+            if (self.target_cpu == 'x86' and hidex86)
+            else r'\x64'
+            if (self.target_cpu == 'amd64' and x64)
+            else rf'\{self.target_cpu}'
+        )
+
+    def cross_dir(self, forcex86=False):
+        r"""
+        Cross platform specific subfolder.
+
+        Parameters
+        ----------
+        forcex86: bool
+            Use 'x86' as current architecture even if current architecture is
+            not x86.
+
+        Return
+        ------
+        str
+            subfolder: '' if target architecture is current architecture,
+            '\current_target' if not.
+        """
+        current = 'x86' if forcex86 else self.current_cpu
+        return (
+            ''
+            if self.target_cpu == current
+            else self.target_dir().replace('\\', f'\\{current}_')
+        )
+
+
+class RegistryInfo:
+    """
+    Microsoft Visual Studio related registry information.
+
+    Parameters
+    ----------
+    platform_info: PlatformInfo
+        "PlatformInfo" instance.
+    """
+
+    HKEYS = (
+        winreg.HKEY_USERS,
+        winreg.HKEY_CURRENT_USER,
+        winreg.HKEY_LOCAL_MACHINE,
+        winreg.HKEY_CLASSES_ROOT,
+    )
+
+    def __init__(self, platform_info) -> None:
+        self.pi = platform_info
+
+    @property
+    def visualstudio(self) -> str:
+        """
+        Microsoft Visual Studio root registry key.
+
+        Return
+        ------
+        str
+            Registry key
+        """
+        return 'VisualStudio'
+
+    @property
+    def sxs(self):
+        """
+        Microsoft Visual Studio SxS registry key.
+
+        Return
+        ------
+        str
+            Registry key
+        """
+        return os.path.join(self.visualstudio, 'SxS')
+
+    @property
+    def vc(self):
+        """
+        Microsoft Visual C++ VC7 registry key.
+
+        Return
+        ------
+        str
+            Registry key
+        """
+        return os.path.join(self.sxs, 'VC7')
+
+    @property
+    def vs(self):
+        """
+        Microsoft Visual Studio VS7 registry key.
+
+        Return
+        ------
+        str
+            Registry key
+        """
+        return os.path.join(self.sxs, 'VS7')
+
+    @property
+    def vc_for_python(self) -> str:
+        """
+        Microsoft Visual C++ for Python registry key.
+
+        Return
+        ------
+        str
+            Registry key
+        """
+        return r'DevDiv\VCForPython'
+
+    @property
+    def microsoft_sdk(self) -> str:
+        """
+        Microsoft SDK registry key.
+
+        Return
+        ------
+        str
+            Registry key
+        """
+        return 'Microsoft SDKs'
+
+    @property
+    def windows_sdk(self):
+        """
+        Microsoft Windows/Platform SDK registry key.
+
+        Return
+        ------
+        str
+            Registry key
+        """
+        return os.path.join(self.microsoft_sdk, 'Windows')
+
+    @property
+    def netfx_sdk(self):
+        """
+        Microsoft .NET Framework SDK registry key.
+
+        Return
+        ------
+        str
+            Registry key
+        """
+        return os.path.join(self.microsoft_sdk, 'NETFXSDK')
+
+    @property
+    def windows_kits_roots(self) -> str:
+        """
+        Microsoft Windows Kits Roots registry key.
+
+        Return
+        ------
+        str
+            Registry key
+        """
+        return r'Windows Kits\Installed Roots'
+
+    def microsoft(self, key, x86=False):
+        """
+        Return key in Microsoft software registry.
+
+        Parameters
+        ----------
+        key: str
+            Registry key path where look.
+        x86: str
+            Force x86 software registry.
+
+        Return
+        ------
+        str
+            Registry key
+        """
+        node64 = '' if self.pi.current_is_x86() or x86 else 'Wow6432Node'
+        return os.path.join('Software', node64, 'Microsoft', key)
+
+    def lookup(self, key, name):
+        """
+        Look for values in registry in Microsoft software registry.
+
+        Parameters
+        ----------
+        key: str
+            Registry key path where look.
+        name: str
+            Value name to find.
+
+        Return
+        ------
+        str
+            value
+        """
+        key_read = winreg.KEY_READ
+        openkey = winreg.OpenKey
+        closekey = winreg.CloseKey
+        ms = self.microsoft
+        for hkey in self.HKEYS:
+            bkey = None
+            try:
+                bkey = openkey(hkey, ms(key), 0, key_read)
+            except OSError:
+                if not self.pi.current_is_x86():
+                    try:
+                        bkey = openkey(hkey, ms(key, True), 0, key_read)
+                    except OSError:
+                        continue
+                else:
+                    continue
+            try:
+                return winreg.QueryValueEx(bkey, name)[0]
+            except OSError:
+                pass
+            finally:
+                if bkey:
+                    closekey(bkey)
+        return None
+
+
+class SystemInfo:
+    """
+    Microsoft Windows and Visual Studio related system information.
+
+    Parameters
+    ----------
+    registry_info: RegistryInfo
+        "RegistryInfo" instance.
+    vc_ver: float
+        Required Microsoft Visual C++ version.
+    """
+
+    # Variables and properties in this class use originals CamelCase variables
+    # names from Microsoft source files for more easy comparison.
+    WinDir = environ.get('WinDir', '')
+    ProgramFiles = environ.get('ProgramFiles', '')
+    ProgramFilesx86 = environ.get('ProgramFiles(x86)', ProgramFiles)
+
+    def __init__(self, registry_info, vc_ver=None) -> None:
+        self.ri = registry_info
+        self.pi = self.ri.pi
+
+        self.known_vs_paths = self.find_programdata_vs_vers()
+
+        # Except for VS15+, VC version is aligned with VS version
+        self.vs_ver = self.vc_ver = vc_ver or self._find_latest_available_vs_ver()
+
+    def _find_latest_available_vs_ver(self):
+        """
+        Find the latest VC version
+
+        Return
+        ------
+        float
+            version
+        """
+        reg_vc_vers = self.find_reg_vs_vers()
+
+        if not (reg_vc_vers or self.known_vs_paths):
+            raise distutils.errors.DistutilsPlatformError(
+                'No Microsoft Visual C++ version found'
+            )
+
+        vc_vers = set(reg_vc_vers)
+        vc_vers.update(self.known_vs_paths)
+        return sorted(vc_vers)[-1]
+
+    def find_reg_vs_vers(self):
+        """
+        Find Microsoft Visual Studio versions available in registry.
+
+        Return
+        ------
+        list of float
+            Versions
+        """
+        ms = self.ri.microsoft
+        vckeys = (self.ri.vc, self.ri.vc_for_python, self.ri.vs)
+        vs_vers = []
+        for hkey, key in itertools.product(self.ri.HKEYS, vckeys):
+            try:
+                bkey = winreg.OpenKey(hkey, ms(key), 0, winreg.KEY_READ)
+            except OSError:
+                continue
+            with bkey:
+                subkeys, values, _ = winreg.QueryInfoKey(bkey)
+                for i in range(values):
+                    with contextlib.suppress(ValueError):
+                        ver = float(winreg.EnumValue(bkey, i)[0])
+                        if ver not in vs_vers:
+                            vs_vers.append(ver)
+                for i in range(subkeys):
+                    with contextlib.suppress(ValueError):
+                        ver = float(winreg.EnumKey(bkey, i))
+                        if ver not in vs_vers:
+                            vs_vers.append(ver)
+        return sorted(vs_vers)
+
+    def find_programdata_vs_vers(self) -> dict[float, str]:
+        r"""
+        Find Visual studio 2017+ versions from information in
+        "C:\ProgramData\Microsoft\VisualStudio\Packages\_Instances".
+
+        Return
+        ------
+        dict
+            float version as key, path as value.
+        """
+        vs_versions: dict[float, str] = {}
+        instances_dir = r'C:\ProgramData\Microsoft\VisualStudio\Packages\_Instances'
+
+        try:
+            hashed_names = os.listdir(instances_dir)
+
+        except OSError:
+            # Directory not exists with all Visual Studio versions
+            return vs_versions
+
+        for name in hashed_names:
+            try:
+                # Get VS installation path from "state.json" file
+                state_path = os.path.join(instances_dir, name, 'state.json')
+                with open(state_path, 'rt', encoding='utf-8') as state_file:
+                    state = json.load(state_file)
+                vs_path = state['installationPath']
+
+                # Raises OSError if this VS installation does not contain VC
+                os.listdir(os.path.join(vs_path, r'VC\Tools\MSVC'))
+
+                # Store version and path
+                vs_versions[self._as_float_version(state['installationVersion'])] = (
+                    vs_path
+                )
+
+            except (OSError, KeyError):
+                # Skip if "state.json" file is missing or bad format
+                continue
+
+        return vs_versions
+
+    @staticmethod
+    def _as_float_version(version):
+        """
+        Return a string version as a simplified float version (major.minor)
+
+        Parameters
+        ----------
+        version: str
+            Version.
+
+        Return
+        ------
+        float
+            version
+        """
+        return float('.'.join(version.split('.')[:2]))
+
+    @property
+    def VSInstallDir(self):
+        """
+        Microsoft Visual Studio directory.
+
+        Return
+        ------
+        str
+            path
+        """
+        # Default path
+        default = os.path.join(
+            self.ProgramFilesx86, f'Microsoft Visual Studio {self.vs_ver:0.1f}'
+        )
+
+        # Try to get path from registry, if fail use default path
+        return self.ri.lookup(self.ri.vs, f'{self.vs_ver:0.1f}') or default
+
+    @property
+    def VCInstallDir(self):
+        """
+        Microsoft Visual C++ directory.
+
+        Return
+        ------
+        str
+            path
+        """
+        path = self._guess_vc() or self._guess_vc_legacy()
+
+        if not os.path.isdir(path):
+            msg = 'Microsoft Visual C++ directory not found'
+            raise distutils.errors.DistutilsPlatformError(msg)
+
+        return path
+
+    def _guess_vc(self):
+        """
+        Locate Visual C++ for VS2017+.
+
+        Return
+        ------
+        str
+            path
+        """
+        if self.vs_ver <= 14.0:
+            return ''
+
+        try:
+            # First search in known VS paths
+            vs_dir = self.known_vs_paths[self.vs_ver]
+        except KeyError:
+            # Else, search with path from registry
+            vs_dir = self.VSInstallDir
+
+        guess_vc = os.path.join(vs_dir, r'VC\Tools\MSVC')
+
+        # Subdir with VC exact version as name
+        try:
+            # Update the VC version with real one instead of VS version
+            vc_ver = os.listdir(guess_vc)[-1]
+            self.vc_ver = self._as_float_version(vc_ver)
+            return os.path.join(guess_vc, vc_ver)
+        except (OSError, IndexError):
+            return ''
+
+    def _guess_vc_legacy(self):
+        """
+        Locate Visual C++ for versions prior to 2017.
+
+        Return
+        ------
+        str
+            path
+        """
+        default = os.path.join(
+            self.ProgramFilesx86,
+            rf'Microsoft Visual Studio {self.vs_ver:0.1f}\VC',
+        )
+
+        # Try to get "VC++ for Python" path from registry as default path
+        reg_path = os.path.join(self.ri.vc_for_python, f'{self.vs_ver:0.1f}')
+        python_vc = self.ri.lookup(reg_path, 'installdir')
+        default_vc = os.path.join(python_vc, 'VC') if python_vc else default
+
+        # Try to get path from registry, if fail use default path
+        return self.ri.lookup(self.ri.vc, f'{self.vs_ver:0.1f}') or default_vc
+
+    @property
+    def WindowsSdkVersion(self) -> tuple[LiteralString, ...]:
+        """
+        Microsoft Windows SDK versions for specified MSVC++ version.
+
+        Return
+        ------
+        tuple of str
+            versions
+        """
+        if self.vs_ver <= 9.0:
+            return '7.0', '6.1', '6.0a'
+        elif self.vs_ver == 10.0:
+            return '7.1', '7.0a'
+        elif self.vs_ver == 11.0:
+            return '8.0', '8.0a'
+        elif self.vs_ver == 12.0:
+            return '8.1', '8.1a'
+        elif self.vs_ver >= 14.0:
+            return '10.0', '8.1'
+        return ()
+
+    @property
+    def WindowsSdkLastVersion(self):
+        """
+        Microsoft Windows SDK last version.
+
+        Return
+        ------
+        str
+            version
+        """
+        return self._use_last_dir_name(os.path.join(self.WindowsSdkDir, 'lib'))
+
+    @property
+    def WindowsSdkDir(self) -> str | None:  # noqa: C901  # is too complex (12)  # FIXME
+        """
+        Microsoft Windows SDK directory.
+
+        Return
+        ------
+        str
+            path
+        """
+        sdkdir: str | None = ''
+        for ver in self.WindowsSdkVersion:
+            # Try to get it from registry
+            loc = os.path.join(self.ri.windows_sdk, f'v{ver}')
+            sdkdir = self.ri.lookup(loc, 'installationfolder')
+            if sdkdir:
+                break
+        if not sdkdir or not os.path.isdir(sdkdir):
+            # Try to get "VC++ for Python" version from registry
+            path = os.path.join(self.ri.vc_for_python, f'{self.vc_ver:0.1f}')
+            install_base = self.ri.lookup(path, 'installdir')
+            if install_base:
+                sdkdir = os.path.join(install_base, 'WinSDK')
+        if not sdkdir or not os.path.isdir(sdkdir):
+            # If fail, use default new path
+            for ver in self.WindowsSdkVersion:
+                intver = ver[: ver.rfind('.')]
+                path = rf'Microsoft SDKs\Windows Kits\{intver}'
+                d = os.path.join(self.ProgramFiles, path)
+                if os.path.isdir(d):
+                    sdkdir = d
+        if not sdkdir or not os.path.isdir(sdkdir):
+            # If fail, use default old path
+            for ver in self.WindowsSdkVersion:
+                path = rf'Microsoft SDKs\Windows\v{ver}'
+                d = os.path.join(self.ProgramFiles, path)
+                if os.path.isdir(d):
+                    sdkdir = d
+        if not sdkdir:
+            # If fail, use Platform SDK
+            sdkdir = os.path.join(self.VCInstallDir, 'PlatformSDK')
+        return sdkdir
+
+    @property
+    def WindowsSDKExecutablePath(self):
+        """
+        Microsoft Windows SDK executable directory.
+
+        Return
+        ------
+        str
+            path
+        """
+        # Find WinSDK NetFx Tools registry dir name
+        if self.vs_ver <= 11.0:
+            netfxver = 35
+            arch = ''
+        else:
+            netfxver = 40
+            hidex86 = True if self.vs_ver <= 12.0 else False
+            arch = self.pi.current_dir(x64=True, hidex86=hidex86).replace('\\', '-')
+        fx = f'WinSDK-NetFx{netfxver}Tools{arch}'
+
+        # list all possibles registry paths
+        regpaths = []
+        if self.vs_ver >= 14.0:
+            for ver in self.NetFxSdkVersion:
+                regpaths += [os.path.join(self.ri.netfx_sdk, ver, fx)]
+
+        for ver in self.WindowsSdkVersion:
+            regpaths += [os.path.join(self.ri.windows_sdk, f'v{ver}A', fx)]
+
+        # Return installation folder from the more recent path
+        for path in regpaths:
+            execpath = self.ri.lookup(path, 'installationfolder')
+            if execpath:
+                return execpath
+
+        return None
+
+    @property
+    def FSharpInstallDir(self):
+        """
+        Microsoft Visual F# directory.
+
+        Return
+        ------
+        str
+            path
+        """
+        path = os.path.join(self.ri.visualstudio, rf'{self.vs_ver:0.1f}\Setup\F#')
+        return self.ri.lookup(path, 'productdir') or ''
+
+    @property
+    def UniversalCRTSdkDir(self):
+        """
+        Microsoft Universal CRT SDK directory.
+
+        Return
+        ------
+        str
+            path
+        """
+        # Set Kit Roots versions for specified MSVC++ version
+        vers = ('10', '81') if self.vs_ver >= 14.0 else ()
+
+        # Find path of the more recent Kit
+        for ver in vers:
+            sdkdir = self.ri.lookup(self.ri.windows_kits_roots, f'kitsroot{ver}')
+            if sdkdir:
+                return sdkdir or ''
+
+        return None
+
+    @property
+    def UniversalCRTSdkLastVersion(self):
+        """
+        Microsoft Universal C Runtime SDK last version.
+
+        Return
+        ------
+        str
+            version
+        """
+        return self._use_last_dir_name(os.path.join(self.UniversalCRTSdkDir, 'lib'))
+
+    @property
+    def NetFxSdkVersion(self):
+        """
+        Microsoft .NET Framework SDK versions.
+
+        Return
+        ------
+        tuple of str
+            versions
+        """
+        # Set FxSdk versions for specified VS version
+        return (
+            ('4.7.2', '4.7.1', '4.7', '4.6.2', '4.6.1', '4.6', '4.5.2', '4.5.1', '4.5')
+            if self.vs_ver >= 14.0
+            else ()
+        )
+
+    @property
+    def NetFxSdkDir(self):
+        """
+        Microsoft .NET Framework SDK directory.
+
+        Return
+        ------
+        str
+            path
+        """
+        sdkdir = ''
+        for ver in self.NetFxSdkVersion:
+            loc = os.path.join(self.ri.netfx_sdk, ver)
+            sdkdir = self.ri.lookup(loc, 'kitsinstallationfolder')
+            if sdkdir:
+                break
+        return sdkdir
+
+    @property
+    def FrameworkDir32(self):
+        """
+        Microsoft .NET Framework 32bit directory.
+
+        Return
+        ------
+        str
+            path
+        """
+        # Default path
+        guess_fw = os.path.join(self.WinDir, r'Microsoft.NET\Framework')
+
+        # Try to get path from registry, if fail use default path
+        return self.ri.lookup(self.ri.vc, 'frameworkdir32') or guess_fw
+
+    @property
+    def FrameworkDir64(self):
+        """
+        Microsoft .NET Framework 64bit directory.
+
+        Return
+        ------
+        str
+            path
+        """
+        # Default path
+        guess_fw = os.path.join(self.WinDir, r'Microsoft.NET\Framework64')
+
+        # Try to get path from registry, if fail use default path
+        return self.ri.lookup(self.ri.vc, 'frameworkdir64') or guess_fw
+
+    @property
+    def FrameworkVersion32(self) -> tuple[str, ...]:
+        """
+        Microsoft .NET Framework 32bit versions.
+
+        Return
+        ------
+        tuple of str
+            versions
+        """
+        return self._find_dot_net_versions(32)
+
+    @property
+    def FrameworkVersion64(self) -> tuple[str, ...]:
+        """
+        Microsoft .NET Framework 64bit versions.
+
+        Return
+        ------
+        tuple of str
+            versions
+        """
+        return self._find_dot_net_versions(64)
+
+    def _find_dot_net_versions(self, bits) -> tuple[str, ...]:
+        """
+        Find Microsoft .NET Framework versions.
+
+        Parameters
+        ----------
+        bits: int
+            Platform number of bits: 32 or 64.
+
+        Return
+        ------
+        tuple of str
+            versions
+        """
+        # Find actual .NET version in registry
+        reg_ver = self.ri.lookup(self.ri.vc, f'frameworkver{bits}')
+        dot_net_dir = getattr(self, f'FrameworkDir{bits}')
+        ver = reg_ver or self._use_last_dir_name(dot_net_dir, 'v') or ''
+
+        # Set .NET versions for specified MSVC++ version
+        if self.vs_ver >= 12.0:
+            return ver, 'v4.0'
+        elif self.vs_ver >= 10.0:
+            return 'v4.0.30319' if ver.lower()[:2] != 'v4' else ver, 'v3.5'
+        elif self.vs_ver == 9.0:
+            return 'v3.5', 'v2.0.50727'
+        elif self.vs_ver == 8.0:
+            return 'v3.0', 'v2.0.50727'
+        return ()
+
+    @staticmethod
+    def _use_last_dir_name(path, prefix=''):
+        """
+        Return name of the last dir in path or '' if no dir found.
+
+        Parameters
+        ----------
+        path: str
+            Use dirs in this path
+        prefix: str
+            Use only dirs starting by this prefix
+
+        Return
+        ------
+        str
+            name
+        """
+        matching_dirs = (
+            dir_name
+            for dir_name in reversed(os.listdir(path))
+            if os.path.isdir(os.path.join(path, dir_name))
+            and dir_name.startswith(prefix)
+        )
+        return next(matching_dirs, None) or ''
+
+
+class _EnvironmentDict(TypedDict):
+    include: str
+    lib: str
+    libpath: str
+    path: str
+    py_vcruntime_redist: NotRequired[str | None]
+
+
+class EnvironmentInfo:
+    """
+    Return environment variables for specified Microsoft Visual C++ version
+    and platform : Lib, Include, Path and libpath.
+
+    This function is compatible with Microsoft Visual C++ 9.0 to 14.X.
+
+    Script created by analysing Microsoft environment configuration files like
+    "vcvars[...].bat", "SetEnv.Cmd", "vcbuildtools.bat", ...
+
+    Parameters
+    ----------
+    arch: str
+        Target architecture.
+    vc_ver: float
+        Required Microsoft Visual C++ version. If not set, autodetect the last
+        version.
+    vc_min_ver: float
+        Minimum Microsoft Visual C++ version.
+    """
+
+    # Variables and properties in this class use originals CamelCase variables
+    # names from Microsoft source files for more easy comparison.
+
+    def __init__(self, arch, vc_ver=None, vc_min_ver=0) -> None:
+        self.pi = PlatformInfo(arch)
+        self.ri = RegistryInfo(self.pi)
+        self.si = SystemInfo(self.ri, vc_ver)
+
+        if self.vc_ver < vc_min_ver:
+            err = 'No suitable Microsoft Visual C++ version found'
+            raise distutils.errors.DistutilsPlatformError(err)
+
+    @property
+    def vs_ver(self):
+        """
+        Microsoft Visual Studio.
+
+        Return
+        ------
+        float
+            version
+        """
+        return self.si.vs_ver
+
+    @property
+    def vc_ver(self):
+        """
+        Microsoft Visual C++ version.
+
+        Return
+        ------
+        float
+            version
+        """
+        return self.si.vc_ver
+
+    @property
+    def VSTools(self):
+        """
+        Microsoft Visual Studio Tools.
+
+        Return
+        ------
+        list of str
+            paths
+        """
+        paths = [r'Common7\IDE', r'Common7\Tools']
+
+        if self.vs_ver >= 14.0:
+            arch_subdir = self.pi.current_dir(hidex86=True, x64=True)
+            paths += [r'Common7\IDE\CommonExtensions\Microsoft\TestWindow']
+            paths += [r'Team Tools\Performance Tools']
+            paths += [rf'Team Tools\Performance Tools{arch_subdir}']
+
+        return [os.path.join(self.si.VSInstallDir, path) for path in paths]
+
+    @property
+    def VCIncludes(self):
+        """
+        Microsoft Visual C++ & Microsoft Foundation Class Includes.
+
+        Return
+        ------
+        list of str
+            paths
+        """
+        return [
+            os.path.join(self.si.VCInstallDir, 'Include'),
+            os.path.join(self.si.VCInstallDir, r'ATLMFC\Include'),
+        ]
+
+    @property
+    def VCLibraries(self):
+        """
+        Microsoft Visual C++ & Microsoft Foundation Class Libraries.
+
+        Return
+        ------
+        list of str
+            paths
+        """
+        if self.vs_ver >= 15.0:
+            arch_subdir = self.pi.target_dir(x64=True)
+        else:
+            arch_subdir = self.pi.target_dir(hidex86=True)
+        paths = [f'Lib{arch_subdir}', rf'ATLMFC\Lib{arch_subdir}']
+
+        if self.vs_ver >= 14.0:
+            paths += [rf'Lib\store{arch_subdir}']
+
+        return [os.path.join(self.si.VCInstallDir, path) for path in paths]
+
+    @property
+    def VCStoreRefs(self):
+        """
+        Microsoft Visual C++ store references Libraries.
+
+        Return
+        ------
+        list of str
+            paths
+        """
+        if self.vs_ver < 14.0:
+            return []
+        return [os.path.join(self.si.VCInstallDir, r'Lib\store\references')]
+
+    @property
+    def VCTools(self):
+        """
+        Microsoft Visual C++ Tools.
+
+        Return
+        ------
+        list of str
+            paths
+
+        When host CPU is ARM, the tools should be found for ARM.
+
+        >>> getfixture('windows_only')
+        >>> mp = getfixture('monkeypatch')
+        >>> mp.setattr(PlatformInfo, 'current_cpu', 'arm64')
+        >>> ei = EnvironmentInfo(arch='irrelevant')
+        >>> paths = ei.VCTools
+        >>> any('HostARM64' in path for path in paths)
+        True
+        """
+        si = self.si
+        tools = [os.path.join(si.VCInstallDir, 'VCPackages')]
+
+        forcex86 = True if self.vs_ver <= 10.0 else False
+        arch_subdir = self.pi.cross_dir(forcex86)
+        if arch_subdir:
+            tools += [os.path.join(si.VCInstallDir, f'Bin{arch_subdir}')]
+
+        if self.vs_ver == 14.0:
+            path = f'Bin{self.pi.current_dir(hidex86=True)}'
+            tools += [os.path.join(si.VCInstallDir, path)]
+
+        elif self.vs_ver >= 15.0:
+            host_id = self.pi.current_cpu.replace('amd64', 'x64').upper()
+            host_dir = os.path.join('bin', f'Host{host_id}%s')
+            tools += [
+                os.path.join(si.VCInstallDir, host_dir % self.pi.target_dir(x64=True))
+            ]
+
+            if self.pi.current_cpu != self.pi.target_cpu:
+                tools += [
+                    os.path.join(
+                        si.VCInstallDir, host_dir % self.pi.current_dir(x64=True)
+                    )
+                ]
+
+        else:
+            tools += [os.path.join(si.VCInstallDir, 'Bin')]
+
+        return tools
+
+    @property
+    def OSLibraries(self):
+        """
+        Microsoft Windows SDK Libraries.
+
+        Return
+        ------
+        list of str
+            paths
+        """
+        if self.vs_ver <= 10.0:
+            arch_subdir = self.pi.target_dir(hidex86=True, x64=True)
+            return [os.path.join(self.si.WindowsSdkDir, f'Lib{arch_subdir}')]
+
+        else:
+            arch_subdir = self.pi.target_dir(x64=True)
+            lib = os.path.join(self.si.WindowsSdkDir, 'lib')
+            libver = self._sdk_subdir
+            return [os.path.join(lib, f'{libver}um{arch_subdir}')]
+
+    @property
+    def OSIncludes(self):
+        """
+        Microsoft Windows SDK Include.
+
+        Return
+        ------
+        list of str
+            paths
+        """
+        include = os.path.join(self.si.WindowsSdkDir, 'include')
+
+        if self.vs_ver <= 10.0:
+            return [include, os.path.join(include, 'gl')]
+
+        else:
+            if self.vs_ver >= 14.0:
+                sdkver = self._sdk_subdir
+            else:
+                sdkver = ''
+            return [
+                os.path.join(include, f'{sdkver}shared'),
+                os.path.join(include, f'{sdkver}um'),
+                os.path.join(include, f'{sdkver}winrt'),
+            ]
+
+    @property
+    def OSLibpath(self):
+        """
+        Microsoft Windows SDK Libraries Paths.
+
+        Return
+        ------
+        list of str
+            paths
+        """
+        ref = os.path.join(self.si.WindowsSdkDir, 'References')
+        libpath = []
+
+        if self.vs_ver <= 9.0:
+            libpath += self.OSLibraries
+
+        if self.vs_ver >= 11.0:
+            libpath += [os.path.join(ref, r'CommonConfiguration\Neutral')]
+
+        if self.vs_ver >= 14.0:
+            libpath += [
+                ref,
+                os.path.join(self.si.WindowsSdkDir, 'UnionMetadata'),
+                os.path.join(ref, 'Windows.Foundation.UniversalApiContract', '1.0.0.0'),
+                os.path.join(ref, 'Windows.Foundation.FoundationContract', '1.0.0.0'),
+                os.path.join(
+                    ref, 'Windows.Networking.Connectivity.WwanContract', '1.0.0.0'
+                ),
+                os.path.join(
+                    self.si.WindowsSdkDir,
+                    'ExtensionSDKs',
+                    'Microsoft.VCLibs',
+                    f'{self.vs_ver:0.1f}',
+                    'References',
+                    'CommonConfiguration',
+                    'neutral',
+                ),
+            ]
+        return libpath
+
+    @property
+    def SdkTools(self):
+        """
+        Microsoft Windows SDK Tools.
+
+        Return
+        ------
+        list of str
+            paths
+        """
+        return list(self._sdk_tools())
+
+    def _sdk_tools(self):
+        """
+        Microsoft Windows SDK Tools paths generator.
+
+        Return
+        ------
+        generator of str
+            paths
+        """
+        if self.vs_ver < 15.0:
+            bin_dir = 'Bin' if self.vs_ver <= 11.0 else r'Bin\x86'
+            yield os.path.join(self.si.WindowsSdkDir, bin_dir)
+
+        if not self.pi.current_is_x86():
+            arch_subdir = self.pi.current_dir(x64=True)
+            path = f'Bin{arch_subdir}'
+            yield os.path.join(self.si.WindowsSdkDir, path)
+
+        if self.vs_ver in (10.0, 11.0):
+            if self.pi.target_is_x86():
+                arch_subdir = ''
+            else:
+                arch_subdir = self.pi.current_dir(hidex86=True, x64=True)
+            path = rf'Bin\NETFX 4.0 Tools{arch_subdir}'
+            yield os.path.join(self.si.WindowsSdkDir, path)
+
+        elif self.vs_ver >= 15.0:
+            path = os.path.join(self.si.WindowsSdkDir, 'Bin')
+            arch_subdir = self.pi.current_dir(x64=True)
+            sdkver = self.si.WindowsSdkLastVersion
+            yield os.path.join(path, f'{sdkver}{arch_subdir}')
+
+        if self.si.WindowsSDKExecutablePath:
+            yield self.si.WindowsSDKExecutablePath
+
+    @property
+    def _sdk_subdir(self):
+        """
+        Microsoft Windows SDK version subdir.
+
+        Return
+        ------
+        str
+            subdir
+        """
+        ucrtver = self.si.WindowsSdkLastVersion
+        return (f'{ucrtver}\\') if ucrtver else ''
+
+    @property
+    def SdkSetup(self):
+        """
+        Microsoft Windows SDK Setup.
+
+        Return
+        ------
+        list of str
+            paths
+        """
+        if self.vs_ver > 9.0:
+            return []
+
+        return [os.path.join(self.si.WindowsSdkDir, 'Setup')]
+
+    @property
+    def FxTools(self):
+        """
+        Microsoft .NET Framework Tools.
+
+        Return
+        ------
+        list of str
+            paths
+        """
+        pi = self.pi
+        si = self.si
+
+        if self.vs_ver <= 10.0:
+            include32 = True
+            include64 = not pi.target_is_x86() and not pi.current_is_x86()
+        else:
+            include32 = pi.target_is_x86() or pi.current_is_x86()
+            include64 = pi.current_cpu == 'amd64' or pi.target_cpu == 'amd64'
+
+        tools = []
+        if include32:
+            tools += [
+                os.path.join(si.FrameworkDir32, ver) for ver in si.FrameworkVersion32
+            ]
+        if include64:
+            tools += [
+                os.path.join(si.FrameworkDir64, ver) for ver in si.FrameworkVersion64
+            ]
+        return tools
+
+    @property
+    def NetFxSDKLibraries(self):
+        """
+        Microsoft .Net Framework SDK Libraries.
+
+        Return
+        ------
+        list of str
+            paths
+        """
+        if self.vs_ver < 14.0 or not self.si.NetFxSdkDir:
+            return []
+
+        arch_subdir = self.pi.target_dir(x64=True)
+        return [os.path.join(self.si.NetFxSdkDir, rf'lib\um{arch_subdir}')]
+
+    @property
+    def NetFxSDKIncludes(self):
+        """
+        Microsoft .Net Framework SDK Includes.
+
+        Return
+        ------
+        list of str
+            paths
+        """
+        if self.vs_ver < 14.0 or not self.si.NetFxSdkDir:
+            return []
+
+        return [os.path.join(self.si.NetFxSdkDir, r'include\um')]
+
+    @property
+    def VsTDb(self):
+        """
+        Microsoft Visual Studio Team System Database.
+
+        Return
+        ------
+        list of str
+            paths
+        """
+        return [os.path.join(self.si.VSInstallDir, r'VSTSDB\Deploy')]
+
+    @property
+    def MSBuild(self):
+        """
+        Microsoft Build Engine.
+
+        Return
+        ------
+        list of str
+            paths
+        """
+        if self.vs_ver < 12.0:
+            return []
+        elif self.vs_ver < 15.0:
+            base_path = self.si.ProgramFilesx86
+            arch_subdir = self.pi.current_dir(hidex86=True)
+        else:
+            base_path = self.si.VSInstallDir
+            arch_subdir = ''
+
+        path = rf'MSBuild\{self.vs_ver:0.1f}\bin{arch_subdir}'
+        build = [os.path.join(base_path, path)]
+
+        if self.vs_ver >= 15.0:
+            # Add Roslyn C# & Visual Basic Compiler
+            build += [os.path.join(base_path, path, 'Roslyn')]
+
+        return build
+
+    @property
+    def HTMLHelpWorkshop(self):
+        """
+        Microsoft HTML Help Workshop.
+
+        Return
+        ------
+        list of str
+            paths
+        """
+        if self.vs_ver < 11.0:
+            return []
+
+        return [os.path.join(self.si.ProgramFilesx86, 'HTML Help Workshop')]
+
+    @property
+    def UCRTLibraries(self):
+        """
+        Microsoft Universal C Runtime SDK Libraries.
+
+        Return
+        ------
+        list of str
+            paths
+        """
+        if self.vs_ver < 14.0:
+            return []
+
+        arch_subdir = self.pi.target_dir(x64=True)
+        lib = os.path.join(self.si.UniversalCRTSdkDir, 'lib')
+        ucrtver = self._ucrt_subdir
+        return [os.path.join(lib, f'{ucrtver}ucrt{arch_subdir}')]
+
+    @property
+    def UCRTIncludes(self):
+        """
+        Microsoft Universal C Runtime SDK Include.
+
+        Return
+        ------
+        list of str
+            paths
+        """
+        if self.vs_ver < 14.0:
+            return []
+
+        include = os.path.join(self.si.UniversalCRTSdkDir, 'include')
+        return [os.path.join(include, f'{self._ucrt_subdir}ucrt')]
+
+    @property
+    def _ucrt_subdir(self):
+        """
+        Microsoft Universal C Runtime SDK version subdir.
+
+        Return
+        ------
+        str
+            subdir
+        """
+        ucrtver = self.si.UniversalCRTSdkLastVersion
+        return (f'{ucrtver}\\') if ucrtver else ''
+
+    @property
+    def FSharp(self):
+        """
+        Microsoft Visual F#.
+
+        Return
+        ------
+        list of str
+            paths
+        """
+        if 11.0 > self.vs_ver > 12.0:
+            return []
+
+        return [self.si.FSharpInstallDir]
+
+    @property
+    def VCRuntimeRedist(self) -> str | None:
+        """
+        Microsoft Visual C++ runtime redistributable dll.
+
+        Returns the first suitable path found or None.
+        """
+        vcruntime = f'vcruntime{self.vc_ver}0.dll'
+        arch_subdir = self.pi.target_dir(x64=True).strip('\\')
+
+        # Installation prefixes candidates
+        prefixes = []
+        tools_path = self.si.VCInstallDir
+        redist_path = os.path.dirname(tools_path.replace(r'\Tools', r'\Redist'))
+        if os.path.isdir(redist_path):
+            # Redist version may not be exactly the same as tools
+            redist_path = os.path.join(redist_path, os.listdir(redist_path)[-1])
+            prefixes += [redist_path, os.path.join(redist_path, 'onecore')]
+
+        prefixes += [os.path.join(tools_path, 'redist')]  # VS14 legacy path
+
+        # CRT directory
+        crt_dirs = (
+            f'Microsoft.VC{self.vc_ver * 10}.CRT',
+            # Sometime store in directory with VS version instead of VC
+            f'Microsoft.VC{int(self.vs_ver) * 10}.CRT',
+        )
+
+        # vcruntime path
+        candidate_paths = (
+            os.path.join(prefix, arch_subdir, crt_dir, vcruntime)
+            for (prefix, crt_dir) in itertools.product(prefixes, crt_dirs)
+        )
+        return next(filter(os.path.isfile, candidate_paths), None)  # type: ignore[arg-type] #python/mypy#12682
+
+    def return_env(self, exists: bool = True) -> _EnvironmentDict:
+        """
+        Return environment dict.
+
+        Parameters
+        ----------
+        exists: bool
+            It True, only return existing paths.
+
+        Return
+        ------
+        dict
+            environment
+        """
+        env = _EnvironmentDict(
+            include=self._build_paths(
+                'include',
+                [
+                    self.VCIncludes,
+                    self.OSIncludes,
+                    self.UCRTIncludes,
+                    self.NetFxSDKIncludes,
+                ],
+                exists,
+            ),
+            lib=self._build_paths(
+                'lib',
+                [
+                    self.VCLibraries,
+                    self.OSLibraries,
+                    self.FxTools,
+                    self.UCRTLibraries,
+                    self.NetFxSDKLibraries,
+                ],
+                exists,
+            ),
+            libpath=self._build_paths(
+                'libpath',
+                [self.VCLibraries, self.FxTools, self.VCStoreRefs, self.OSLibpath],
+                exists,
+            ),
+            path=self._build_paths(
+                'path',
+                [
+                    self.VCTools,
+                    self.VSTools,
+                    self.VsTDb,
+                    self.SdkTools,
+                    self.SdkSetup,
+                    self.FxTools,
+                    self.MSBuild,
+                    self.HTMLHelpWorkshop,
+                    self.FSharp,
+                ],
+                exists,
+            ),
+        )
+        if self.vs_ver >= 14 and self.VCRuntimeRedist:
+            env['py_vcruntime_redist'] = self.VCRuntimeRedist
+        return env
+
+    def _build_paths(self, name, spec_path_lists, exists):
+        """
+        Given an environment variable name and specified paths,
+        return a pathsep-separated string of paths containing
+        unique, extant, directories from those paths and from
+        the environment variable. Raise an error if no paths
+        are resolved.
+
+        Parameters
+        ----------
+        name: str
+            Environment variable name
+        spec_path_lists: list of str
+            Paths
+        exists: bool
+            It True, only return existing paths.
+
+        Return
+        ------
+        str
+            Pathsep-separated paths
+        """
+        # flatten spec_path_lists
+        spec_paths = itertools.chain.from_iterable(spec_path_lists)
+        env_paths = environ.get(name, '').split(os.pathsep)
+        paths = itertools.chain(spec_paths, env_paths)
+        extant_paths = list(filter(os.path.isdir, paths)) if exists else paths
+        if not extant_paths:
+            msg = f"{name.upper()} environment variable is empty"
+            raise distutils.errors.DistutilsPlatformError(msg)
+        unique_paths = unique_everseen(extant_paths)
+        return os.pathsep.join(unique_paths)
diff --git a/.venv/lib/python3.12/site-packages/setuptools/namespaces.py b/.venv/lib/python3.12/site-packages/setuptools/namespaces.py
new file mode 100644
index 0000000000000000000000000000000000000000..85ea2ebd654c480b8c19d1715b3772c4bcfd812e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/namespaces.py
@@ -0,0 +1,106 @@
+import itertools
+import os
+
+from .compat import py312
+
+from distutils import log
+
+flatten = itertools.chain.from_iterable
+
+
+class Installer:
+    nspkg_ext = '-nspkg.pth'
+
+    def install_namespaces(self) -> None:
+        nsp = self._get_all_ns_packages()
+        if not nsp:
+            return
+        filename = self._get_nspkg_file()
+        self.outputs.append(filename)
+        log.info("Installing %s", filename)
+        lines = map(self._gen_nspkg_line, nsp)
+
+        if self.dry_run:
+            # always generate the lines, even in dry run
+            list(lines)
+            return
+
+        with open(filename, 'wt', encoding=py312.PTH_ENCODING) as f:
+            # Python<3.13 requires encoding="locale" instead of "utf-8"
+            # See: python/cpython#77102
+            f.writelines(lines)
+
+    def uninstall_namespaces(self) -> None:
+        filename = self._get_nspkg_file()
+        if not os.path.exists(filename):
+            return
+        log.info("Removing %s", filename)
+        os.remove(filename)
+
+    def _get_nspkg_file(self):
+        filename, _ = os.path.splitext(self._get_target())
+        return filename + self.nspkg_ext
+
+    def _get_target(self):
+        return self.target
+
+    _nspkg_tmpl = (
+        "import sys, types, os",
+        "p = os.path.join(%(root)s, *%(pth)r)",
+        "importlib = __import__('importlib.util')",
+        "__import__('importlib.machinery')",
+        (
+            "m = "
+            "sys.modules.setdefault(%(pkg)r, "
+            "importlib.util.module_from_spec("
+            "importlib.machinery.PathFinder.find_spec(%(pkg)r, "
+            "[os.path.dirname(p)])))"
+        ),
+        ("m = m or sys.modules.setdefault(%(pkg)r, types.ModuleType(%(pkg)r))"),
+        "mp = (m or []) and m.__dict__.setdefault('__path__',[])",
+        "(p not in mp) and mp.append(p)",
+    )
+    "lines for the namespace installer"
+
+    _nspkg_tmpl_multi = ('m and setattr(sys.modules[%(parent)r], %(child)r, m)',)
+    "additional line(s) when a parent package is indicated"
+
+    def _get_root(self):
+        return "sys._getframe(1).f_locals['sitedir']"
+
+    def _gen_nspkg_line(self, pkg):
+        pth = tuple(pkg.split('.'))
+        root = self._get_root()
+        tmpl_lines = self._nspkg_tmpl
+        parent, sep, child = pkg.rpartition('.')
+        if parent:
+            tmpl_lines += self._nspkg_tmpl_multi
+        return ';'.join(tmpl_lines) % locals() + '\n'
+
+    def _get_all_ns_packages(self):
+        """Return sorted list of all package namespaces"""
+        pkgs = self.distribution.namespace_packages or []
+        return sorted(set(flatten(map(self._pkg_names, pkgs))))
+
+    @staticmethod
+    def _pkg_names(pkg):
+        """
+        Given a namespace package, yield the components of that
+        package.
+
+        >>> names = Installer._pkg_names('a.b.c')
+        >>> set(names) == set(['a', 'a.b', 'a.b.c'])
+        True
+        """
+        parts = pkg.split('.')
+        while parts:
+            yield '.'.join(parts)
+            parts.pop()
+
+
+class DevelopInstaller(Installer):
+    def _get_root(self):
+        return repr(str(self.egg_path))
+
+    def _get_target(self):
+        return self.egg_link
diff --git a/.venv/lib/python3.12/site-packages/setuptools/package_index.py b/.venv/lib/python3.12/site-packages/setuptools/package_index.py
new file mode 100644
index 0000000000000000000000000000000000000000..1a6abebcda4f62c91e0843a17ed4716f8fd3b1d9
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/package_index.py
@@ -0,0 +1,1137 @@
+"""PyPI and direct package downloading."""
+
+from __future__ import annotations
+
+import base64
+import configparser
+import hashlib
+import html
+import http.client
+import io
+import itertools
+import os
+import re
+import shutil
+import socket
+import subprocess
+import sys
+import urllib.error
+import urllib.parse
+import urllib.request
+from fnmatch import translate
+from functools import wraps
+from typing import NamedTuple
+
+from more_itertools import unique_everseen
+
+import setuptools
+from pkg_resources import (
+    BINARY_DIST,
+    CHECKOUT_DIST,
+    DEVELOP_DIST,
+    EGG_DIST,
+    SOURCE_DIST,
+    Distribution,
+    Environment,
+    Requirement,
+    find_distributions,
+    normalize_path,
+    parse_version,
+    safe_name,
+    safe_version,
+    to_filename,
+)
+from setuptools.wheel import Wheel
+
+from .unicode_utils import _cfg_read_utf8_with_fallback, _read_utf8_with_fallback
+
+from distutils import log
+from distutils.errors import DistutilsError
+
+EGG_FRAGMENT = re.compile(r'^egg=([-A-Za-z0-9_.+!]+)$')
+HREF = re.compile(r"""href\s*=\s*['"]?([^'"> ]+)""", re.I)
+PYPI_MD5 = re.compile(
+    r'([^<]+)\n\s+\(md5\)'
+)
+URL_SCHEME = re.compile('([-+.a-z0-9]{2,}):', re.I).match
+EXTENSIONS = ".tar.gz .tar.bz2 .tar .zip .tgz".split()
+
+__all__ = [
+    'PackageIndex',
+    'distros_for_url',
+    'parse_bdist_wininst',
+    'interpret_distro_name',
+]
+
+_SOCKET_TIMEOUT = 15
+
+user_agent = f"setuptools/{setuptools.__version__} Python-urllib/{sys.version_info.major}.{sys.version_info.minor}"
+
+
+def parse_requirement_arg(spec):
+    try:
+        return Requirement.parse(spec)
+    except ValueError as e:
+        raise DistutilsError(
+            f"Not a URL, existing file, or requirement spec: {spec!r}"
+        ) from e
+
+
+def parse_bdist_wininst(name):
+    """Return (base,pyversion) or (None,None) for possible .exe name"""
+
+    lower = name.lower()
+    base, py_ver, plat = None, None, None
+
+    if lower.endswith('.exe'):
+        if lower.endswith('.win32.exe'):
+            base = name[:-10]
+            plat = 'win32'
+        elif lower.startswith('.win32-py', -16):
+            py_ver = name[-7:-4]
+            base = name[:-16]
+            plat = 'win32'
+        elif lower.endswith('.win-amd64.exe'):
+            base = name[:-14]
+            plat = 'win-amd64'
+        elif lower.startswith('.win-amd64-py', -20):
+            py_ver = name[-7:-4]
+            base = name[:-20]
+            plat = 'win-amd64'
+    return base, py_ver, plat
+
+
+def egg_info_for_url(url):
+    parts = urllib.parse.urlparse(url)
+    _scheme, server, path, _parameters, _query, fragment = parts
+    base = urllib.parse.unquote(path.split('/')[-1])
+    if server == 'sourceforge.net' and base == 'download':  # XXX Yuck
+        base = urllib.parse.unquote(path.split('/')[-2])
+    if '#' in base:
+        base, fragment = base.split('#', 1)
+    return base, fragment
+
+
+def distros_for_url(url, metadata=None):
+    """Yield egg or source distribution objects that might be found at a URL"""
+    base, fragment = egg_info_for_url(url)
+    yield from distros_for_location(url, base, metadata)
+    if fragment:
+        match = EGG_FRAGMENT.match(fragment)
+        if match:
+            yield from interpret_distro_name(
+                url, match.group(1), metadata, precedence=CHECKOUT_DIST
+            )
+
+
+def distros_for_location(location, basename, metadata=None):
+    """Yield egg or source distribution objects based on basename"""
+    if basename.endswith('.egg.zip'):
+        basename = basename[:-4]  # strip the .zip
+    if basename.endswith('.egg') and '-' in basename:
+        # only one, unambiguous interpretation
+        return [Distribution.from_location(location, basename, metadata)]
+    if basename.endswith('.whl') and '-' in basename:
+        wheel = Wheel(basename)
+        if not wheel.is_compatible():
+            return []
+        return [
+            Distribution(
+                location=location,
+                project_name=wheel.project_name,
+                version=wheel.version,
+                # Increase priority over eggs.
+                precedence=EGG_DIST + 1,
+            )
+        ]
+    if basename.endswith('.exe'):
+        win_base, py_ver, platform = parse_bdist_wininst(basename)
+        if win_base is not None:
+            return interpret_distro_name(
+                location, win_base, metadata, py_ver, BINARY_DIST, platform
+            )
+    # Try source distro extensions (.zip, .tgz, etc.)
+    #
+    for ext in EXTENSIONS:
+        if basename.endswith(ext):
+            basename = basename[: -len(ext)]
+            return interpret_distro_name(location, basename, metadata)
+    return []  # no extension matched
+
+
+def distros_for_filename(filename, metadata=None):
+    """Yield possible egg or source distribution objects based on a filename"""
+    return distros_for_location(
+        normalize_path(filename), os.path.basename(filename), metadata
+    )
+
+
+def interpret_distro_name(
+    location, basename, metadata, py_version=None, precedence=SOURCE_DIST, platform=None
+):
+    """Generate the interpretation of a source distro name
+
+    Note: if `location` is a filesystem filename, you should call
+    ``pkg_resources.normalize_path()`` on it before passing it to this
+    routine!
+    """
+
+    parts = basename.split('-')
+    if not py_version and any(re.match(r'py\d\.\d$', p) for p in parts[2:]):
+        # it is a bdist_dumb, not an sdist -- bail out
+        return
+
+    # find the pivot (p) that splits the name from the version.
+    # infer the version as the first item that has a digit.
+    for p in range(len(parts)):
+        if parts[p][:1].isdigit():
+            break
+    else:
+        p = len(parts)
+
+    yield Distribution(
+        location,
+        metadata,
+        '-'.join(parts[:p]),
+        '-'.join(parts[p:]),
+        py_version=py_version,
+        precedence=precedence,
+        platform=platform,
+    )
+
+
+def unique_values(func):
+    """
+    Wrap a function returning an iterable such that the resulting iterable
+    only ever yields unique items.
+    """
+
+    @wraps(func)
+    def wrapper(*args, **kwargs):
+        return unique_everseen(func(*args, **kwargs))
+
+    return wrapper
+
+
+REL = re.compile(r"""<([^>]*\srel\s{0,10}=\s{0,10}['"]?([^'" >]+)[^>]*)>""", re.I)
+"""
+Regex for an HTML tag with 'rel="val"' attributes.
+"""
+
+
+@unique_values
+def find_external_links(url, page):
+    """Find rel="homepage" and rel="download" links in `page`, yielding URLs"""
+
+    for match in REL.finditer(page):
+        tag, rel = match.groups()
+        rels = set(map(str.strip, rel.lower().split(',')))
+        if 'homepage' in rels or 'download' in rels:
+            for match in HREF.finditer(tag):
+                yield urllib.parse.urljoin(url, htmldecode(match.group(1)))
+
+    for tag in ("Home Page", "Download URL"):
+        pos = page.find(tag)
+        if pos != -1:
+            match = HREF.search(page, pos)
+            if match:
+                yield urllib.parse.urljoin(url, htmldecode(match.group(1)))
+
+
+class ContentChecker:
+    """
+    A null content checker that defines the interface for checking content
+    """
+
+    def feed(self, block):
+        """
+        Feed a block of data to the hash.
+        """
+        return
+
+    def is_valid(self):
+        """
+        Check the hash. Return False if validation fails.
+        """
+        return True
+
+    def report(self, reporter, template):
+        """
+        Call reporter with information about the checker (hash name)
+        substituted into the template.
+        """
+        return
+
+
+class HashChecker(ContentChecker):
+    pattern = re.compile(
+        r'(?Psha1|sha224|sha384|sha256|sha512|md5)='
+        r'(?P[a-f0-9]+)'
+    )
+
+    def __init__(self, hash_name, expected) -> None:
+        self.hash_name = hash_name
+        self.hash = hashlib.new(hash_name)
+        self.expected = expected
+
+    @classmethod
+    def from_url(cls, url):
+        "Construct a (possibly null) ContentChecker from a URL"
+        fragment = urllib.parse.urlparse(url)[-1]
+        if not fragment:
+            return ContentChecker()
+        match = cls.pattern.search(fragment)
+        if not match:
+            return ContentChecker()
+        return cls(**match.groupdict())
+
+    def feed(self, block):
+        self.hash.update(block)
+
+    def is_valid(self):
+        return self.hash.hexdigest() == self.expected
+
+    def report(self, reporter, template):
+        msg = template % self.hash_name
+        return reporter(msg)
+
+
+class PackageIndex(Environment):
+    """A distribution index that scans web pages for download URLs"""
+
+    def __init__(
+        self,
+        index_url: str = "https://pypi.org/simple/",
+        hosts=('*',),
+        ca_bundle=None,
+        verify_ssl: bool = True,
+        *args,
+        **kw,
+    ) -> None:
+        super().__init__(*args, **kw)
+        self.index_url = index_url + "/"[: not index_url.endswith('/')]
+        self.scanned_urls: dict = {}
+        self.fetched_urls: dict = {}
+        self.package_pages: dict = {}
+        self.allows = re.compile('|'.join(map(translate, hosts))).match
+        self.to_scan: list = []
+        self.opener = urllib.request.urlopen
+
+    def add(self, dist):
+        # ignore invalid versions
+        try:
+            parse_version(dist.version)
+        except Exception:
+            return None
+        return super().add(dist)
+
+    # FIXME: 'PackageIndex.process_url' is too complex (14)
+    def process_url(self, url, retrieve: bool = False) -> None:  # noqa: C901
+        """Evaluate a URL as a possible download, and maybe retrieve it"""
+        if url in self.scanned_urls and not retrieve:
+            return
+        self.scanned_urls[url] = True
+        if not URL_SCHEME(url):
+            self.process_filename(url)
+            return
+        else:
+            dists = list(distros_for_url(url))
+            if dists:
+                if not self.url_ok(url):
+                    return
+                self.debug("Found link: %s", url)
+
+        if dists or not retrieve or url in self.fetched_urls:
+            list(map(self.add, dists))
+            return  # don't need the actual page
+
+        if not self.url_ok(url):
+            self.fetched_urls[url] = True
+            return
+
+        self.info("Reading %s", url)
+        self.fetched_urls[url] = True  # prevent multiple fetch attempts
+        tmpl = "Download error on %s: %%s -- Some packages may not be found!"
+        f = self.open_url(url, tmpl % url)
+        if f is None:
+            return
+        if isinstance(f, urllib.error.HTTPError) and f.code == 401:
+            self.info(f"Authentication error: {f.msg}")
+        self.fetched_urls[f.url] = True
+        if 'html' not in f.headers.get('content-type', '').lower():
+            f.close()  # not html, we can't process it
+            return
+
+        base = f.url  # handle redirects
+        page = f.read()
+        if not isinstance(page, str):
+            # In Python 3 and got bytes but want str.
+            if isinstance(f, urllib.error.HTTPError):
+                # Errors have no charset, assume latin1:
+                charset = 'latin-1'
+            else:
+                charset = f.headers.get_param('charset') or 'latin-1'
+            page = page.decode(charset, "ignore")
+        f.close()
+        for match in HREF.finditer(page):
+            link = urllib.parse.urljoin(base, htmldecode(match.group(1)))
+            self.process_url(link)
+        if url.startswith(self.index_url) and getattr(f, 'code', None) != 404:
+            page = self.process_index(url, page)
+
+    def process_filename(self, fn, nested: bool = False) -> None:
+        # process filenames or directories
+        if not os.path.exists(fn):
+            self.warn("Not found: %s", fn)
+            return
+
+        if os.path.isdir(fn) and not nested:
+            path = os.path.realpath(fn)
+            for item in os.listdir(path):
+                self.process_filename(os.path.join(path, item), True)
+
+        dists = distros_for_filename(fn)
+        if dists:
+            self.debug("Found: %s", fn)
+            list(map(self.add, dists))
+
+    def url_ok(self, url, fatal: bool = False) -> bool:
+        s = URL_SCHEME(url)
+        is_file = s and s.group(1).lower() == 'file'
+        if is_file or self.allows(urllib.parse.urlparse(url)[1]):
+            return True
+        msg = (
+            "\nNote: Bypassing %s (disallowed host; see "
+            "https://setuptools.pypa.io/en/latest/deprecated/"
+            "easy_install.html#restricting-downloads-with-allow-hosts for details).\n"
+        )
+        if fatal:
+            raise DistutilsError(msg % url)
+        else:
+            self.warn(msg, url)
+            return False
+
+    def scan_egg_links(self, search_path) -> None:
+        dirs = filter(os.path.isdir, search_path)
+        egg_links = (
+            (path, entry)
+            for path in dirs
+            for entry in os.listdir(path)
+            if entry.endswith('.egg-link')
+        )
+        list(itertools.starmap(self.scan_egg_link, egg_links))
+
+    def scan_egg_link(self, path, entry) -> None:
+        content = _read_utf8_with_fallback(os.path.join(path, entry))
+        # filter non-empty lines
+        lines = list(filter(None, map(str.strip, content.splitlines())))
+
+        if len(lines) != 2:
+            # format is not recognized; punt
+            return
+
+        egg_path, _setup_path = lines
+
+        for dist in find_distributions(os.path.join(path, egg_path)):
+            dist.location = os.path.join(path, *lines)
+            dist.precedence = SOURCE_DIST
+            self.add(dist)
+
+    def _scan(self, link):
+        # Process a URL to see if it's for a package page
+        NO_MATCH_SENTINEL = None, None
+        if not link.startswith(self.index_url):
+            return NO_MATCH_SENTINEL
+
+        parts = list(map(urllib.parse.unquote, link[len(self.index_url) :].split('/')))
+        if len(parts) != 2 or '#' in parts[1]:
+            return NO_MATCH_SENTINEL
+
+        # it's a package page, sanitize and index it
+        pkg = safe_name(parts[0])
+        ver = safe_version(parts[1])
+        self.package_pages.setdefault(pkg.lower(), {})[link] = True
+        return to_filename(pkg), to_filename(ver)
+
+    def process_index(self, url, page):
+        """Process the contents of a PyPI page"""
+
+        # process an index page into the package-page index
+        for match in HREF.finditer(page):
+            try:
+                self._scan(urllib.parse.urljoin(url, htmldecode(match.group(1))))
+            except ValueError:
+                pass
+
+        pkg, ver = self._scan(url)  # ensure this page is in the page index
+        if not pkg:
+            return ""  # no sense double-scanning non-package pages
+
+        # process individual package page
+        for new_url in find_external_links(url, page):
+            # Process the found URL
+            base, frag = egg_info_for_url(new_url)
+            if base.endswith('.py') and not frag:
+                if ver:
+                    new_url += f'#egg={pkg}-{ver}'
+                else:
+                    self.need_version_info(url)
+            self.scan_url(new_url)
+
+        return PYPI_MD5.sub(
+            lambda m: '{}'.format(*m.group(1, 3, 2)), page
+        )
+
+    def need_version_info(self, url) -> None:
+        self.scan_all(
+            "Page at %s links to .py file(s) without version info; an index "
+            "scan is required.",
+            url,
+        )
+
+    def scan_all(self, msg=None, *args) -> None:
+        if self.index_url not in self.fetched_urls:
+            if msg:
+                self.warn(msg, *args)
+            self.info("Scanning index of all packages (this may take a while)")
+        self.scan_url(self.index_url)
+
+    def find_packages(self, requirement) -> None:
+        self.scan_url(self.index_url + requirement.unsafe_name + '/')
+
+        if not self.package_pages.get(requirement.key):
+            # Fall back to safe version of the name
+            self.scan_url(self.index_url + requirement.project_name + '/')
+
+        if not self.package_pages.get(requirement.key):
+            # We couldn't find the target package, so search the index page too
+            self.not_found_in_index(requirement)
+
+        for url in list(self.package_pages.get(requirement.key, ())):
+            # scan each page that might be related to the desired package
+            self.scan_url(url)
+
+    def obtain(self, requirement, installer=None):
+        self.prescan()
+        self.find_packages(requirement)
+        for dist in self[requirement.key]:
+            if dist in requirement:
+                return dist
+            self.debug("%s does not match %s", requirement, dist)
+        return super().obtain(requirement, installer)
+
+    def check_hash(self, checker, filename, tfp) -> None:
+        """
+        checker is a ContentChecker
+        """
+        checker.report(self.debug, f"Validating %s checksum for {filename}")
+        if not checker.is_valid():
+            tfp.close()
+            os.unlink(filename)
+            raise DistutilsError(
+                f"{checker.hash.name} validation failed for {os.path.basename(filename)}; "
+                "possible download problem?"
+            )
+
+    def add_find_links(self, urls) -> None:
+        """Add `urls` to the list that will be prescanned for searches"""
+        for url in urls:
+            if (
+                self.to_scan is None  # if we have already "gone online"
+                or not URL_SCHEME(url)  # or it's a local file/directory
+                or url.startswith('file:')
+                or list(distros_for_url(url))  # or a direct package link
+            ):
+                # then go ahead and process it now
+                self.scan_url(url)
+            else:
+                # otherwise, defer retrieval till later
+                self.to_scan.append(url)
+
+    def prescan(self):
+        """Scan urls scheduled for prescanning (e.g. --find-links)"""
+        if self.to_scan:
+            list(map(self.scan_url, self.to_scan))
+        self.to_scan = None  # from now on, go ahead and process immediately
+
+    def not_found_in_index(self, requirement) -> None:
+        if self[requirement.key]:  # we've seen at least one distro
+            meth, msg = self.info, "Couldn't retrieve index page for %r"
+        else:  # no distros seen for this name, might be misspelled
+            meth, msg = self.warn, "Couldn't find index page for %r (maybe misspelled?)"
+        meth(msg, requirement.unsafe_name)
+        self.scan_all()
+
+    def download(self, spec, tmpdir):
+        """Locate and/or download `spec` to `tmpdir`, returning a local path
+
+        `spec` may be a ``Requirement`` object, or a string containing a URL,
+        an existing local filename, or a project/version requirement spec
+        (i.e. the string form of a ``Requirement`` object).  If it is the URL
+        of a .py file with an unambiguous ``#egg=name-version`` tag (i.e., one
+        that escapes ``-`` as ``_`` throughout), a trivial ``setup.py`` is
+        automatically created alongside the downloaded file.
+
+        If `spec` is a ``Requirement`` object or a string containing a
+        project/version requirement spec, this method returns the location of
+        a matching distribution (possibly after downloading it to `tmpdir`).
+        If `spec` is a locally existing file or directory name, it is simply
+        returned unchanged.  If `spec` is a URL, it is downloaded to a subpath
+        of `tmpdir`, and the local filename is returned.  Various errors may be
+        raised if a problem occurs during downloading.
+        """
+        if not isinstance(spec, Requirement):
+            scheme = URL_SCHEME(spec)
+            if scheme:
+                # It's a url, download it to tmpdir
+                found = self._download_url(spec, tmpdir)
+                base, fragment = egg_info_for_url(spec)
+                if base.endswith('.py'):
+                    found = self.gen_setup(found, fragment, tmpdir)
+                return found
+            elif os.path.exists(spec):
+                # Existing file or directory, just return it
+                return spec
+            else:
+                spec = parse_requirement_arg(spec)
+        return getattr(self.fetch_distribution(spec, tmpdir), 'location', None)
+
+    def fetch_distribution(  # noqa: C901  # is too complex (14)  # FIXME
+        self,
+        requirement,
+        tmpdir,
+        force_scan: bool = False,
+        source: bool = False,
+        develop_ok: bool = False,
+        local_index=None,
+    ) -> Distribution | None:
+        """Obtain a distribution suitable for fulfilling `requirement`
+
+        `requirement` must be a ``pkg_resources.Requirement`` instance.
+        If necessary, or if the `force_scan` flag is set, the requirement is
+        searched for in the (online) package index as well as the locally
+        installed packages.  If a distribution matching `requirement` is found,
+        the returned distribution's ``location`` is the value you would have
+        gotten from calling the ``download()`` method with the matching
+        distribution's URL or filename.  If no matching distribution is found,
+        ``None`` is returned.
+
+        If the `source` flag is set, only source distributions and source
+        checkout links will be considered.  Unless the `develop_ok` flag is
+        set, development and system eggs (i.e., those using the ``.egg-info``
+        format) will be ignored.
+        """
+        # process a Requirement
+        self.info("Searching for %s", requirement)
+        skipped = set()
+        dist = None
+
+        def find(req, env: Environment | None = None):
+            if env is None:
+                env = self
+            # Find a matching distribution; may be called more than once
+
+            for dist in env[req.key]:
+                if dist.precedence == DEVELOP_DIST and not develop_ok:
+                    if dist not in skipped:
+                        self.warn(
+                            "Skipping development or system egg: %s",
+                            dist,
+                        )
+                        skipped.add(dist)
+                    continue
+
+                test = dist in req and (dist.precedence <= SOURCE_DIST or not source)
+                if test:
+                    loc = self.download(dist.location, tmpdir)
+                    dist.download_location = loc
+                    if os.path.exists(dist.download_location):
+                        return dist
+
+            return None
+
+        if force_scan:
+            self.prescan()
+            self.find_packages(requirement)
+            dist = find(requirement)
+
+        if not dist and local_index is not None:
+            dist = find(requirement, local_index)
+
+        if dist is None:
+            if self.to_scan is not None:
+                self.prescan()
+            dist = find(requirement)
+
+        if dist is None and not force_scan:
+            self.find_packages(requirement)
+            dist = find(requirement)
+
+        if dist is None:
+            self.warn(
+                "No local packages or working download links found for %s%s",
+                (source and "a source distribution of " or ""),
+                requirement,
+            )
+            return None
+        else:
+            self.info("Best match: %s", dist)
+            return dist.clone(location=dist.download_location)
+
+    def fetch(
+        self, requirement, tmpdir, force_scan: bool = False, source: bool = False
+    ) -> str | None:
+        """Obtain a file suitable for fulfilling `requirement`
+
+        DEPRECATED; use the ``fetch_distribution()`` method now instead.  For
+        backward compatibility, this routine is identical but returns the
+        ``location`` of the downloaded distribution instead of a distribution
+        object.
+        """
+        dist = self.fetch_distribution(requirement, tmpdir, force_scan, source)
+        if dist is not None:
+            return dist.location
+        return None
+
+    def gen_setup(self, filename, fragment, tmpdir):
+        match = EGG_FRAGMENT.match(fragment)
+        dists = (
+            match
+            and [
+                d
+                for d in interpret_distro_name(filename, match.group(1), None)
+                if d.version
+            ]
+            or []
+        )
+
+        if len(dists) == 1:  # unambiguous ``#egg`` fragment
+            basename = os.path.basename(filename)
+
+            # Make sure the file has been downloaded to the temp dir.
+            if os.path.dirname(filename) != tmpdir:
+                dst = os.path.join(tmpdir, basename)
+                if not (os.path.exists(dst) and os.path.samefile(filename, dst)):
+                    shutil.copy2(filename, dst)
+                    filename = dst
+
+            with open(os.path.join(tmpdir, 'setup.py'), 'w', encoding="utf-8") as file:
+                file.write(
+                    "from setuptools import setup\n"
+                    f"setup(name={dists[0].project_name!r}, version={dists[0].version!r}, py_modules=[{os.path.splitext(basename)[0]!r}])\n"
+                )
+            return filename
+
+        elif match:
+            raise DistutilsError(
+                f"Can't unambiguously interpret project/version identifier {fragment!r}; "
+                "any dashes in the name or version should be escaped using "
+                f"underscores. {dists!r}"
+            )
+        else:
+            raise DistutilsError(
+                "Can't process plain .py files without an '#egg=name-version'"
+                " suffix to enable automatic setup script generation."
+            )
+
+    dl_blocksize = 8192
+
+    def _download_to(self, url, filename):
+        self.info("Downloading %s", url)
+        # Download the file
+        fp = None
+        try:
+            checker = HashChecker.from_url(url)
+            fp = self.open_url(url)
+            if isinstance(fp, urllib.error.HTTPError):
+                raise DistutilsError(f"Can't download {url}: {fp.code} {fp.msg}")
+            headers = fp.info()
+            blocknum = 0
+            bs = self.dl_blocksize
+            size = -1
+            if "content-length" in headers:
+                # Some servers return multiple Content-Length headers :(
+                sizes = headers.get_all('Content-Length')
+                size = max(map(int, sizes))
+                self.reporthook(url, filename, blocknum, bs, size)
+            with open(filename, 'wb') as tfp:
+                while True:
+                    block = fp.read(bs)
+                    if block:
+                        checker.feed(block)
+                        tfp.write(block)
+                        blocknum += 1
+                        self.reporthook(url, filename, blocknum, bs, size)
+                    else:
+                        break
+                self.check_hash(checker, filename, tfp)
+            return headers
+        finally:
+            if fp:
+                fp.close()
+
+    def reporthook(self, url, filename, blocknum, blksize, size) -> None:
+        pass  # no-op
+
+    # FIXME:
+    def open_url(self, url, warning=None):  # noqa: C901  # is too complex (12)
+        if url.startswith('file:'):
+            return local_open(url)
+        try:
+            return open_with_auth(url, self.opener)
+        except (ValueError, http.client.InvalidURL) as v:
+            msg = ' '.join([str(arg) for arg in v.args])
+            if warning:
+                self.warn(warning, msg)
+            else:
+                raise DistutilsError(f'{url} {msg}') from v
+        except urllib.error.HTTPError as v:
+            return v
+        except urllib.error.URLError as v:
+            if warning:
+                self.warn(warning, v.reason)
+            else:
+                raise DistutilsError(f"Download error for {url}: {v.reason}") from v
+        except http.client.BadStatusLine as v:
+            if warning:
+                self.warn(warning, v.line)
+            else:
+                raise DistutilsError(
+                    f'{url} returned a bad status line. The server might be '
+                    f'down, {v.line}'
+                ) from v
+        except (http.client.HTTPException, OSError) as v:
+            if warning:
+                self.warn(warning, v)
+            else:
+                raise DistutilsError(f"Download error for {url}: {v}") from v
+
+    def _download_url(self, url, tmpdir):
+        # Determine download filename
+        #
+        name, _fragment = egg_info_for_url(url)
+        if name:
+            while '..' in name:
+                name = name.replace('..', '.').replace('\\', '_')
+        else:
+            name = "__downloaded__"  # default if URL has no path contents
+
+        if name.endswith('.egg.zip'):
+            name = name[:-4]  # strip the extra .zip before download
+
+        filename = os.path.join(tmpdir, name)
+
+        return self._download_vcs(url, filename) or self._download_other(url, filename)
+
+    @staticmethod
+    def _resolve_vcs(url):
+        """
+        >>> rvcs = PackageIndex._resolve_vcs
+        >>> rvcs('git+http://foo/bar')
+        'git'
+        >>> rvcs('hg+https://foo/bar')
+        'hg'
+        >>> rvcs('git:myhost')
+        'git'
+        >>> rvcs('hg:myhost')
+        >>> rvcs('http://foo/bar')
+        """
+        scheme = urllib.parse.urlsplit(url).scheme
+        pre, sep, _post = scheme.partition('+')
+        # svn and git have their own protocol; hg does not
+        allowed = set(['svn', 'git'] + ['hg'] * bool(sep))
+        return next(iter({pre} & allowed), None)
+
+    def _download_vcs(self, url, spec_filename):
+        vcs = self._resolve_vcs(url)
+        if not vcs:
+            return None
+        if vcs == 'svn':
+            raise DistutilsError(
+                f"Invalid config, SVN download is not supported: {url}"
+            )
+
+        filename, _, _ = spec_filename.partition('#')
+        url, rev = self._vcs_split_rev_from_url(url)
+
+        self.info(f"Doing {vcs} clone from {url} to {filename}")
+        subprocess.check_call([vcs, 'clone', '--quiet', url, filename])
+
+        co_commands = dict(
+            git=[vcs, '-C', filename, 'checkout', '--quiet', rev],
+            hg=[vcs, '--cwd', filename, 'up', '-C', '-r', rev, '-q'],
+        )
+        if rev is not None:
+            self.info(f"Checking out {rev}")
+            subprocess.check_call(co_commands[vcs])
+
+        return filename
+
+    def _download_other(self, url, filename):
+        scheme = urllib.parse.urlsplit(url).scheme
+        if scheme == 'file':  # pragma: no cover
+            return urllib.request.url2pathname(urllib.parse.urlparse(url).path)
+        # raise error if not allowed
+        self.url_ok(url, True)
+        return self._attempt_download(url, filename)
+
+    def scan_url(self, url) -> None:
+        self.process_url(url, True)
+
+    def _attempt_download(self, url, filename):
+        headers = self._download_to(url, filename)
+        if 'html' in headers.get('content-type', '').lower():
+            return self._invalid_download_html(url, headers, filename)
+        else:
+            return filename
+
+    def _invalid_download_html(self, url, headers, filename):
+        os.unlink(filename)
+        raise DistutilsError(f"Unexpected HTML page found at {url}")
+
+    @staticmethod
+    def _vcs_split_rev_from_url(url):
+        """
+        Given a possible VCS URL, return a clean URL and resolved revision if any.
+
+        >>> vsrfu = PackageIndex._vcs_split_rev_from_url
+        >>> vsrfu('git+https://github.com/pypa/setuptools@v69.0.0#egg-info=setuptools')
+        ('https://github.com/pypa/setuptools', 'v69.0.0')
+        >>> vsrfu('git+https://github.com/pypa/setuptools#egg-info=setuptools')
+        ('https://github.com/pypa/setuptools', None)
+        >>> vsrfu('http://foo/bar')
+        ('http://foo/bar', None)
+        """
+        parts = urllib.parse.urlsplit(url)
+
+        clean_scheme = parts.scheme.split('+', 1)[-1]
+
+        # Some fragment identification fails
+        no_fragment_path, _, _ = parts.path.partition('#')
+
+        pre, sep, post = no_fragment_path.rpartition('@')
+        clean_path, rev = (pre, post) if sep else (post, None)
+
+        resolved = parts._replace(
+            scheme=clean_scheme,
+            path=clean_path,
+            # discard the fragment
+            fragment='',
+        ).geturl()
+
+        return resolved, rev
+
+    def debug(self, msg, *args) -> None:
+        log.debug(msg, *args)
+
+    def info(self, msg, *args) -> None:
+        log.info(msg, *args)
+
+    def warn(self, msg, *args) -> None:
+        log.warn(msg, *args)
+
+
+# This pattern matches a character entity reference (a decimal numeric
+# references, a hexadecimal numeric reference, or a named reference).
+entity_sub = re.compile(r'&(#(\d+|x[\da-fA-F]+)|[\w.:-]+);?').sub
+
+
+def decode_entity(match):
+    what = match.group(0)
+    return html.unescape(what)
+
+
+def htmldecode(text):
+    """
+    Decode HTML entities in the given text.
+
+    >>> htmldecode(
+    ...     'https://../package_name-0.1.2.tar.gz'
+    ...     '?tokena=A&tokenb=B">package_name-0.1.2.tar.gz')
+    'https://../package_name-0.1.2.tar.gz?tokena=A&tokenb=B">package_name-0.1.2.tar.gz'
+    """
+    return entity_sub(decode_entity, text)
+
+
+def socket_timeout(timeout=15):
+    def _socket_timeout(func):
+        def _socket_timeout(*args, **kwargs):
+            old_timeout = socket.getdefaulttimeout()
+            socket.setdefaulttimeout(timeout)
+            try:
+                return func(*args, **kwargs)
+            finally:
+                socket.setdefaulttimeout(old_timeout)
+
+        return _socket_timeout
+
+    return _socket_timeout
+
+
+def _encode_auth(auth):
+    """
+    Encode auth from a URL suitable for an HTTP header.
+    >>> str(_encode_auth('username%3Apassword'))
+    'dXNlcm5hbWU6cGFzc3dvcmQ='
+
+    Long auth strings should not cause a newline to be inserted.
+    >>> long_auth = 'username:' + 'password'*10
+    >>> chr(10) in str(_encode_auth(long_auth))
+    False
+    """
+    auth_s = urllib.parse.unquote(auth)
+    # convert to bytes
+    auth_bytes = auth_s.encode()
+    encoded_bytes = base64.b64encode(auth_bytes)
+    # convert back to a string
+    encoded = encoded_bytes.decode()
+    # strip the trailing carriage return
+    return encoded.replace('\n', '')
+
+
+class Credential(NamedTuple):
+    """
+    A username/password pair.
+
+    Displayed separated by `:`.
+    >>> str(Credential('username', 'password'))
+    'username:password'
+    """
+
+    username: str
+    password: str
+
+    def __str__(self) -> str:
+        return f'{self.username}:{self.password}'
+
+
+class PyPIConfig(configparser.RawConfigParser):
+    def __init__(self):
+        """
+        Load from ~/.pypirc
+        """
+        defaults = dict.fromkeys(['username', 'password', 'repository'], '')
+        super().__init__(defaults)
+
+        rc = os.path.join(os.path.expanduser('~'), '.pypirc')
+        if os.path.exists(rc):
+            _cfg_read_utf8_with_fallback(self, rc)
+
+    @property
+    def creds_by_repository(self):
+        sections_with_repositories = [
+            section
+            for section in self.sections()
+            if self.get(section, 'repository').strip()
+        ]
+
+        return dict(map(self._get_repo_cred, sections_with_repositories))
+
+    def _get_repo_cred(self, section):
+        repo = self.get(section, 'repository').strip()
+        return repo, Credential(
+            self.get(section, 'username').strip(),
+            self.get(section, 'password').strip(),
+        )
+
+    def find_credential(self, url):
+        """
+        If the URL indicated appears to be a repository defined in this
+        config, return the credential for that repository.
+        """
+        for repository, cred in self.creds_by_repository.items():
+            if url.startswith(repository):
+                return cred
+        return None
+
+
+def open_with_auth(url, opener=urllib.request.urlopen):
+    """Open a urllib2 request, handling HTTP authentication"""
+
+    parsed = urllib.parse.urlparse(url)
+    scheme, netloc, path, params, query, frag = parsed
+
+    # Double scheme does not raise on macOS as revealed by a
+    # failing test. We would expect "nonnumeric port". Refs #20.
+    if netloc.endswith(':'):
+        raise http.client.InvalidURL("nonnumeric port: ''")
+
+    if scheme in ('http', 'https'):
+        auth, address = _splituser(netloc)
+    else:
+        auth, address = (None, None)
+
+    if not auth:
+        cred = PyPIConfig().find_credential(url)
+        if cred:
+            auth = str(cred)
+            info = cred.username, url
+            log.info('Authenticating as %s for %s (from .pypirc)', *info)
+
+    if auth:
+        auth = "Basic " + _encode_auth(auth)
+        parts = scheme, address, path, params, query, frag
+        new_url = urllib.parse.urlunparse(parts)
+        request = urllib.request.Request(new_url)
+        request.add_header("Authorization", auth)
+    else:
+        request = urllib.request.Request(url)
+
+    request.add_header('User-Agent', user_agent)
+    fp = opener(request)
+
+    if auth:
+        # Put authentication info back into request URL if same host,
+        # so that links found on the page will work
+        s2, h2, path2, param2, query2, frag2 = urllib.parse.urlparse(fp.url)
+        if s2 == scheme and h2 == address:
+            parts = s2, netloc, path2, param2, query2, frag2
+            fp.url = urllib.parse.urlunparse(parts)
+
+    return fp
+
+
+# copy of urllib.parse._splituser from Python 3.8
+# See https://github.com/python/cpython/issues/80072.
+def _splituser(host):
+    """splituser('user[:passwd]@host[:port]')
+    --> 'user[:passwd]', 'host[:port]'."""
+    user, delim, host = host.rpartition('@')
+    return (user if delim else None), host
+
+
+# adding a timeout to avoid freezing package_index
+open_with_auth = socket_timeout(_SOCKET_TIMEOUT)(open_with_auth)
+
+
+def fix_sf_url(url):
+    return url  # backward compatibility
+
+
+def local_open(url):
+    """Read a local path, with special support for directories"""
+    _scheme, _server, path, _param, _query, _frag = urllib.parse.urlparse(url)
+    filename = urllib.request.url2pathname(path)
+    if os.path.isfile(filename):
+        return urllib.request.urlopen(url)
+    elif path.endswith('/') and os.path.isdir(filename):
+        files = []
+        for f in os.listdir(filename):
+            filepath = os.path.join(filename, f)
+            if f == 'index.html':
+                body = _read_utf8_with_fallback(filepath)
+                break
+            elif os.path.isdir(filepath):
+                f += '/'
+            files.append(f'{f}')
+        else:
+            tmpl = "{url}{files}"
+            body = tmpl.format(url=url, files='\n'.join(files))
+        status, message = 200, "OK"
+    else:
+        status, message, body = 404, "Path not found", "Not found"
+
+    headers = {'content-type': 'text/html'}
+    body_stream = io.StringIO(body)
+    return urllib.error.HTTPError(url, status, message, headers, body_stream)
diff --git a/.venv/lib/python3.12/site-packages/setuptools/sandbox.py b/.venv/lib/python3.12/site-packages/setuptools/sandbox.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d84242d667c7df6a20aa56eabce6ac34ddc4a7e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/sandbox.py
@@ -0,0 +1,536 @@
+from __future__ import annotations
+
+import builtins
+import contextlib
+import functools
+import itertools
+import operator
+import os
+import pickle
+import re
+import sys
+import tempfile
+import textwrap
+from types import TracebackType
+from typing import TYPE_CHECKING, Any, ClassVar
+
+import pkg_resources
+from pkg_resources import working_set
+
+from distutils.errors import DistutilsError
+
+if TYPE_CHECKING:
+    import os as _os
+elif sys.platform.startswith('java'):
+    import org.python.modules.posix.PosixModule as _os  # pyright: ignore[reportMissingImports]
+else:
+    _os = sys.modules[os.name]
+_open = open
+
+
+if TYPE_CHECKING:
+    from typing_extensions import Self
+
+__all__ = [
+    "AbstractSandbox",
+    "DirectorySandbox",
+    "SandboxViolation",
+    "run_setup",
+]
+
+
+def _execfile(filename, globals, locals=None):
+    """
+    Python 3 implementation of execfile.
+    """
+    mode = 'rb'
+    with open(filename, mode) as stream:
+        script = stream.read()
+    if locals is None:
+        locals = globals
+    code = compile(script, filename, 'exec')
+    exec(code, globals, locals)
+
+
+@contextlib.contextmanager
+def save_argv(repl=None):
+    saved = sys.argv[:]
+    if repl is not None:
+        sys.argv[:] = repl
+    try:
+        yield saved
+    finally:
+        sys.argv[:] = saved
+
+
+@contextlib.contextmanager
+def save_path():
+    saved = sys.path[:]
+    try:
+        yield saved
+    finally:
+        sys.path[:] = saved
+
+
+@contextlib.contextmanager
+def override_temp(replacement):
+    """
+    Monkey-patch tempfile.tempdir with replacement, ensuring it exists
+    """
+    os.makedirs(replacement, exist_ok=True)
+
+    saved = tempfile.tempdir
+
+    tempfile.tempdir = replacement
+
+    try:
+        yield
+    finally:
+        tempfile.tempdir = saved
+
+
+@contextlib.contextmanager
+def pushd(target):
+    saved = os.getcwd()
+    os.chdir(target)
+    try:
+        yield saved
+    finally:
+        os.chdir(saved)
+
+
+class UnpickleableException(Exception):
+    """
+    An exception representing another Exception that could not be pickled.
+    """
+
+    @staticmethod
+    def dump(type, exc):
+        """
+        Always return a dumped (pickled) type and exc. If exc can't be pickled,
+        wrap it in UnpickleableException first.
+        """
+        try:
+            return pickle.dumps(type), pickle.dumps(exc)
+        except Exception:
+            # get UnpickleableException inside the sandbox
+            from setuptools.sandbox import UnpickleableException as cls
+
+            return cls.dump(cls, cls(repr(exc)))
+
+
+class ExceptionSaver:
+    """
+    A Context Manager that will save an exception, serialize, and restore it
+    later.
+    """
+
+    def __enter__(self) -> Self:
+        return self
+
+    def __exit__(
+        self,
+        type: type[BaseException] | None,
+        exc: BaseException | None,
+        tb: TracebackType | None,
+    ) -> bool:
+        if not exc:
+            return False
+
+        # dump the exception
+        self._saved = UnpickleableException.dump(type, exc)
+        self._tb = tb
+
+        # suppress the exception
+        return True
+
+    def resume(self):
+        "restore and re-raise any exception"
+
+        if '_saved' not in vars(self):
+            return
+
+        _type, exc = map(pickle.loads, self._saved)
+        raise exc.with_traceback(self._tb)
+
+
+@contextlib.contextmanager
+def save_modules():
+    """
+    Context in which imported modules are saved.
+
+    Translates exceptions internal to the context into the equivalent exception
+    outside the context.
+    """
+    saved = sys.modules.copy()
+    with ExceptionSaver() as saved_exc:
+        yield saved
+
+    sys.modules.update(saved)
+    # remove any modules imported since
+    del_modules = (
+        mod_name
+        for mod_name in sys.modules
+        if mod_name not in saved
+        # exclude any encodings modules. See #285
+        and not mod_name.startswith('encodings.')
+    )
+    _clear_modules(del_modules)
+
+    saved_exc.resume()
+
+
+def _clear_modules(module_names):
+    for mod_name in list(module_names):
+        del sys.modules[mod_name]
+
+
+@contextlib.contextmanager
+def save_pkg_resources_state():
+    saved = pkg_resources.__getstate__()
+    try:
+        yield saved
+    finally:
+        pkg_resources.__setstate__(saved)
+
+
+@contextlib.contextmanager
+def setup_context(setup_dir):
+    temp_dir = os.path.join(setup_dir, 'temp')
+    with save_pkg_resources_state():
+        with save_modules():
+            with save_path():
+                hide_setuptools()
+                with save_argv():
+                    with override_temp(temp_dir):
+                        with pushd(setup_dir):
+                            # ensure setuptools commands are available
+                            __import__('setuptools')
+                            yield
+
+
+_MODULES_TO_HIDE = {
+    'setuptools',
+    'distutils',
+    'pkg_resources',
+    'Cython',
+    '_distutils_hack',
+}
+
+
+def _needs_hiding(mod_name):
+    """
+    >>> _needs_hiding('setuptools')
+    True
+    >>> _needs_hiding('pkg_resources')
+    True
+    >>> _needs_hiding('setuptools_plugin')
+    False
+    >>> _needs_hiding('setuptools.__init__')
+    True
+    >>> _needs_hiding('distutils')
+    True
+    >>> _needs_hiding('os')
+    False
+    >>> _needs_hiding('Cython')
+    True
+    """
+    base_module = mod_name.split('.', 1)[0]
+    return base_module in _MODULES_TO_HIDE
+
+
+def hide_setuptools():
+    """
+    Remove references to setuptools' modules from sys.modules to allow the
+    invocation to import the most appropriate setuptools. This technique is
+    necessary to avoid issues such as #315 where setuptools upgrading itself
+    would fail to find a function declared in the metadata.
+    """
+    _distutils_hack = sys.modules.get('_distutils_hack', None)
+    if _distutils_hack is not None:
+        _distutils_hack._remove_shim()
+
+    modules = filter(_needs_hiding, sys.modules)
+    _clear_modules(modules)
+
+
+def run_setup(setup_script, args):
+    """Run a distutils setup script, sandboxed in its directory"""
+    setup_dir = os.path.abspath(os.path.dirname(setup_script))
+    with setup_context(setup_dir):
+        try:
+            sys.argv[:] = [setup_script] + list(args)
+            sys.path.insert(0, setup_dir)
+            # reset to include setup dir, w/clean callback list
+            working_set.__init__()
+            working_set.callbacks.append(lambda dist: dist.activate())
+
+            with DirectorySandbox(setup_dir):
+                ns = dict(__file__=setup_script, __name__='__main__')
+                _execfile(setup_script, ns)
+        except SystemExit as v:
+            if v.args and v.args[0]:
+                raise
+            # Normal exit, just return
+
+
+class AbstractSandbox:
+    """Wrap 'os' module and 'open()' builtin for virtualizing setup scripts"""
+
+    _active = False
+
+    def __init__(self) -> None:
+        self._attrs = [
+            name
+            for name in dir(_os)
+            if not name.startswith('_') and hasattr(self, name)
+        ]
+
+    def _copy(self, source):
+        for name in self._attrs:
+            setattr(os, name, getattr(source, name))
+
+    def __enter__(self) -> None:
+        self._copy(self)
+        builtins.open = self._open
+        self._active = True
+
+    def __exit__(
+        self,
+        exc_type: type[BaseException] | None,
+        exc_value: BaseException | None,
+        traceback: TracebackType | None,
+    ):
+        self._active = False
+        builtins.open = _open
+        self._copy(_os)
+
+    def run(self, func):
+        """Run 'func' under os sandboxing"""
+        with self:
+            return func()
+
+    def _mk_dual_path_wrapper(name: str):  # type: ignore[misc] # https://github.com/pypa/setuptools/pull/4099
+        original = getattr(_os, name)
+
+        def wrap(self, src, dst, *args, **kw):
+            if self._active:
+                src, dst = self._remap_pair(name, src, dst, *args, **kw)
+            return original(src, dst, *args, **kw)
+
+        return wrap
+
+    for __name in ["rename", "link", "symlink"]:
+        if hasattr(_os, __name):
+            locals()[__name] = _mk_dual_path_wrapper(__name)
+
+    def _mk_single_path_wrapper(name: str, original=None):  # type: ignore[misc] # https://github.com/pypa/setuptools/pull/4099
+        original = original or getattr(_os, name)
+
+        def wrap(self, path, *args, **kw):
+            if self._active:
+                path = self._remap_input(name, path, *args, **kw)
+            return original(path, *args, **kw)
+
+        return wrap
+
+    _open = _mk_single_path_wrapper('open', _open)
+    for __name in [
+        "stat",
+        "listdir",
+        "chdir",
+        "open",
+        "chmod",
+        "chown",
+        "mkdir",
+        "remove",
+        "unlink",
+        "rmdir",
+        "utime",
+        "lchown",
+        "chroot",
+        "lstat",
+        "startfile",
+        "mkfifo",
+        "mknod",
+        "pathconf",
+        "access",
+    ]:
+        if hasattr(_os, __name):
+            locals()[__name] = _mk_single_path_wrapper(__name)
+
+    def _mk_single_with_return(name: str):  # type: ignore[misc] # https://github.com/pypa/setuptools/pull/4099
+        original = getattr(_os, name)
+
+        def wrap(self, path, *args, **kw):
+            if self._active:
+                path = self._remap_input(name, path, *args, **kw)
+                return self._remap_output(name, original(path, *args, **kw))
+            return original(path, *args, **kw)
+
+        return wrap
+
+    for __name in ['readlink', 'tempnam']:
+        if hasattr(_os, __name):
+            locals()[__name] = _mk_single_with_return(__name)
+
+    def _mk_query(name: str):  # type: ignore[misc] # https://github.com/pypa/setuptools/pull/4099
+        original = getattr(_os, name)
+
+        def wrap(self, *args, **kw):
+            retval = original(*args, **kw)
+            if self._active:
+                return self._remap_output(name, retval)
+            return retval
+
+        return wrap
+
+    for __name in ['getcwd', 'tmpnam']:
+        if hasattr(_os, __name):
+            locals()[__name] = _mk_query(__name)
+
+    def _validate_path(self, path):
+        """Called to remap or validate any path, whether input or output"""
+        return path
+
+    def _remap_input(self, operation, path, *args, **kw):
+        """Called for path inputs"""
+        return self._validate_path(path)
+
+    def _remap_output(self, operation, path):
+        """Called for path outputs"""
+        return self._validate_path(path)
+
+    def _remap_pair(self, operation, src, dst, *args, **kw):
+        """Called for path pairs like rename, link, and symlink operations"""
+        return (
+            self._remap_input(operation + '-from', src, *args, **kw),
+            self._remap_input(operation + '-to', dst, *args, **kw),
+        )
+
+    if TYPE_CHECKING:
+        # This is a catch-all for all the dynamically created attributes.
+        # This isn't public API anyway
+        def __getattribute__(self, name: str) -> Any: ...
+
+
+if hasattr(os, 'devnull'):
+    _EXCEPTIONS = [os.devnull]
+else:
+    _EXCEPTIONS = []
+
+
+class DirectorySandbox(AbstractSandbox):
+    """Restrict operations to a single subdirectory - pseudo-chroot"""
+
+    write_ops: ClassVar[dict[str, None]] = dict.fromkeys([
+        "open",
+        "chmod",
+        "chown",
+        "mkdir",
+        "remove",
+        "unlink",
+        "rmdir",
+        "utime",
+        "lchown",
+        "chroot",
+        "mkfifo",
+        "mknod",
+        "tempnam",
+    ])
+
+    _exception_patterns: list[str | re.Pattern] = []
+    "exempt writing to paths that match the pattern"
+
+    def __init__(self, sandbox, exceptions=_EXCEPTIONS) -> None:
+        self._sandbox = os.path.normcase(os.path.realpath(sandbox))
+        self._prefix = os.path.join(self._sandbox, '')
+        self._exceptions = [
+            os.path.normcase(os.path.realpath(path)) for path in exceptions
+        ]
+        AbstractSandbox.__init__(self)
+
+    def _violation(self, operation, *args, **kw):
+        from setuptools.sandbox import SandboxViolation
+
+        raise SandboxViolation(operation, args, kw)
+
+    def _open(self, path, mode='r', *args, **kw):
+        if mode not in ('r', 'rt', 'rb', 'rU', 'U') and not self._ok(path):
+            self._violation("open", path, mode, *args, **kw)
+        return _open(path, mode, *args, **kw)
+
+    def tmpnam(self) -> None:
+        self._violation("tmpnam")
+
+    def _ok(self, path):
+        active = self._active
+        try:
+            self._active = False
+            realpath = os.path.normcase(os.path.realpath(path))
+            return (
+                self._exempted(realpath)
+                or realpath == self._sandbox
+                or realpath.startswith(self._prefix)
+            )
+        finally:
+            self._active = active
+
+    def _exempted(self, filepath):
+        start_matches = (
+            filepath.startswith(exception) for exception in self._exceptions
+        )
+        pattern_matches = (
+            re.match(pattern, filepath) for pattern in self._exception_patterns
+        )
+        candidates = itertools.chain(start_matches, pattern_matches)
+        return any(candidates)
+
+    def _remap_input(self, operation, path, *args, **kw):
+        """Called for path inputs"""
+        if operation in self.write_ops and not self._ok(path):
+            self._violation(operation, os.path.realpath(path), *args, **kw)
+        return path
+
+    def _remap_pair(self, operation, src, dst, *args, **kw):
+        """Called for path pairs like rename, link, and symlink operations"""
+        if not self._ok(src) or not self._ok(dst):
+            self._violation(operation, src, dst, *args, **kw)
+        return (src, dst)
+
+    def open(self, file, flags, mode: int = 0o777, *args, **kw) -> int:
+        """Called for low-level os.open()"""
+        if flags & WRITE_FLAGS and not self._ok(file):
+            self._violation("os.open", file, flags, mode, *args, **kw)
+        return _os.open(file, flags, mode, *args, **kw)
+
+
+WRITE_FLAGS = functools.reduce(
+    operator.or_,
+    [
+        getattr(_os, a, 0)
+        for a in "O_WRONLY O_RDWR O_APPEND O_CREAT O_TRUNC O_TEMPORARY".split()
+    ],
+)
+
+
+class SandboxViolation(DistutilsError):
+    """A setup script attempted to modify the filesystem outside the sandbox"""
+
+    tmpl = textwrap.dedent(
+        """
+        SandboxViolation: {cmd}{args!r} {kwargs}
+
+        The package setup script has attempted to modify files on your system
+        that are not within the EasyInstall build area, and has been aborted.
+
+        This package cannot be safely installed by EasyInstall, and may not
+        support alternate installation locations even if you run its setup
+        script by hand.  Please inform the package's author and the EasyInstall
+        maintainers to find out if a fix or workaround is available.
+        """
+    ).lstrip()
+
+    def __str__(self) -> str:
+        cmd, args, kwargs = self.args
+        return self.tmpl.format(**locals())
diff --git a/.venv/lib/python3.12/site-packages/setuptools/script (dev).tmpl b/.venv/lib/python3.12/site-packages/setuptools/script (dev).tmpl
new file mode 100644
index 0000000000000000000000000000000000000000..39a24b04888e79df51e2237577b303a2f901be63
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/script (dev).tmpl	
@@ -0,0 +1,6 @@
+# EASY-INSTALL-DEV-SCRIPT: %(spec)r,%(script_name)r
+__requires__ = %(spec)r
+__import__('pkg_resources').require(%(spec)r)
+__file__ = %(dev_path)r
+with open(__file__) as f:
+    exec(compile(f.read(), __file__, 'exec'))
diff --git a/.venv/lib/python3.12/site-packages/setuptools/script.tmpl b/.venv/lib/python3.12/site-packages/setuptools/script.tmpl
new file mode 100644
index 0000000000000000000000000000000000000000..ff5efbcab3b58063dd84787181c26a95fb663d94
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/script.tmpl
@@ -0,0 +1,3 @@
+# EASY-INSTALL-SCRIPT: %(spec)r,%(script_name)r
+__requires__ = %(spec)r
+__import__('pkg_resources').run_script(%(spec)r, %(script_name)r)
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__init__.py b/.venv/lib/python3.12/site-packages/setuptools/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..eb70bfb7115a2a94a8b942b31cafc3a550f0c005
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/tests/__init__.py
@@ -0,0 +1,13 @@
+import locale
+import sys
+
+import pytest
+
+__all__ = ['fail_on_ascii']
+
+if sys.version_info >= (3, 11):
+    locale_encoding = locale.getencoding()
+else:
+    locale_encoding = locale.getpreferredencoding(False)
+is_ascii = locale_encoding == 'ANSI_X3.4-1968'
+fail_on_ascii = pytest.mark.xfail(is_ascii, reason="Test fails in this locale")
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..33a1adc171cd675251e6b21412ddbe4bb1d79058
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/contexts.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/contexts.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aaf06751d7869b615fea242e7bad38f0cc865a1b
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/contexts.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/environment.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/environment.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c97be3a09e9bc8e090256474e1bccffcb94850ca
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/environment.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/fixtures.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/fixtures.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..843b85f4ba641db6667a711091b7ef99494ee32a
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/fixtures.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/mod_with_constant.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/mod_with_constant.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..49aa33fbd14980b7037499653f7519e0b842a72c
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/mod_with_constant.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/namespaces.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/namespaces.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8b098bd467cb8edd29eec1cc9df55903f8281d7b
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/namespaces.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/script-with-bom.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/script-with-bom.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..821e43051ceee03a537d0ea2ab85b03f8479954b
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/script-with-bom.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/server.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/server.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4dbcfeb45a3879123be83c89679230572a5483b5
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/server.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_archive_util.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_archive_util.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..409b9ba19e90243ff92da535308e419bc5fb399d
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_archive_util.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_bdist_deprecations.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_bdist_deprecations.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..045ac59c1ce3dec023adf1989472970e3ef57c06
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_bdist_deprecations.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_bdist_egg.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_bdist_egg.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b439aa9c5c331d90585e5126653301b6d1c44ef5
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_bdist_egg.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_bdist_wheel.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_bdist_wheel.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ae11ff5eff8d151cbf7287d525d910155231f734
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_bdist_wheel.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_build.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_build.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4b2396aa8e88738e932811f64756454469301830
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_build.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_build_clib.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_build_clib.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8360df2a54827c45d6cee14ff6d03d9ad736a2f3
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_build_clib.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_build_ext.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_build_ext.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cec14e80c324e2550c04201935e483903706b63f
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_build_ext.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_build_meta.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_build_meta.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f0fe210623d1b5a3b3b55c171f317842c6fda0bf
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_build_meta.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_build_py.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_build_py.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0da219978629f1e4367e5948d2579715f9703bcc
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_build_py.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_config_discovery.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_config_discovery.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9243222a90ad89039d014cdb70d86174114a5848
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_config_discovery.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_core_metadata.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_core_metadata.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b6a8a7b363eec18cc5086f2432f5d39d2ab9d863
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_core_metadata.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_depends.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_depends.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3f8ca1ad23d40bdda65d80ab510099ff8f205fcd
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_depends.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_develop.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_develop.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2b73261decf63265fc26d7477a705fd519c425bf
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_develop.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_dist.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_dist.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d2bf511d1b58ba172051ead125c8a8bfa5e39231
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_dist.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_dist_info.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_dist_info.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4a8123a10db8a5b4d0a182cbd53542601b230d2b
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_dist_info.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_distutils_adoption.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_distutils_adoption.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..70522811a0a2d41b45d27c613c4032b0e3319296
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_distutils_adoption.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_easy_install.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_easy_install.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c4ad0cfdbb9f2cabcc6a0deea035159e6dea8672
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_easy_install.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_editable_install.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_editable_install.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a7a8323a82988eaefd22bbe2bb5b1334fc2afad0
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_editable_install.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_egg_info.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_egg_info.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..41be3e8320b22db44dcbc23aa86436148dd201cc
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_egg_info.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_extern.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_extern.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..119aaeeaf6fa3d3ee12334ca0adf57bff5c40820
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_extern.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_find_packages.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_find_packages.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8f87f54735eb5213cb8137eeea18e5f606d995b8
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_find_packages.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_find_py_modules.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_find_py_modules.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bd6680284aa60c603b049f459f517366414c4f5e
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_find_py_modules.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_glob.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_glob.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..24dda09031c0ecbeb26cdec8195c396bbc917218
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_glob.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_install_scripts.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_install_scripts.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9059d0b1b90052151b3ba2d75bcea31bc7c29217
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_install_scripts.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_logging.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_logging.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..720201dc9a0bba35e905fe1f5397b5e9fc2fb268
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_logging.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_manifest.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_manifest.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..86aae690388138850478f058b505b509c9081f85
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_manifest.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_namespaces.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_namespaces.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..63e5718778852777138cbe2161c321fb59671fd0
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_namespaces.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_packageindex.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_packageindex.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b7c1038944b265534f67a8ef041cf22296b189b4
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_packageindex.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_sandbox.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_sandbox.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..32fc5fcaf21c8a5739b19940dfb9a0ccc3c182ee
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_sandbox.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_sdist.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_sdist.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5fd2e0624e6074594fa13f1312463015024865a3
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_sdist.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_setopt.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_setopt.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..67f352a5ab52a3c8edf5690e8805a33a8fee5cf7
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_setopt.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_setuptools.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_setuptools.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..54d529a983b5c5747ed8efe104b8b0c486e9ed2b
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_setuptools.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_shutil_wrapper.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_shutil_wrapper.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4ab030bcbb68d588a61a9a3e3d9679eda967456e
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_shutil_wrapper.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_unicode_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_unicode_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..313e1a72b42c137d450c4055649784a458fc2287
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_unicode_utils.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_virtualenv.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_virtualenv.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e72a74a570f8d34a7943ed761f74b2c9ae25b857
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_virtualenv.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_warnings.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_warnings.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cef857009e78c782aac8dabc9fe98d70c08973ad
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_warnings.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_wheel.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_wheel.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2bcaeab6630058cd63ce5910c370e874ecdbd823
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_wheel.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_windows_wrappers.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_windows_wrappers.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..01267262e8b9ed54d0a69bf07e0a3592305a0800
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/test_windows_wrappers.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/text.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/text.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0564d056706a1ecfa4a0291564728872720d6ad6
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/text.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/textwrap.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/textwrap.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..06cf5a01bdb03c4e311b463075c527d0befcdbb3
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/__pycache__/textwrap.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/compat/__init__.py b/.venv/lib/python3.12/site-packages/setuptools/tests/compat/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/compat/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/compat/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2e19f0370d4a681e4b8f2d82062df7554dca8b62
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/compat/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/compat/__pycache__/py39.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/compat/__pycache__/py39.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4b01361a2794f886ff8e3e9ff9fc9d8617215128
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/compat/__pycache__/py39.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/compat/py39.py b/.venv/lib/python3.12/site-packages/setuptools/tests/compat/py39.py
new file mode 100644
index 0000000000000000000000000000000000000000..1fdb9dac1fa3f121a634082515d1a305fc09793c
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/tests/compat/py39.py
@@ -0,0 +1,3 @@
+from jaraco.test.cpython import from_test_support, try_import
+
+os_helper = try_import('os_helper') or from_test_support('can_symlink')
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/config/__init__.py b/.venv/lib/python3.12/site-packages/setuptools/tests/config/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/config/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/config/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6ac23e2c8f9c43a17201a2409e1a3b1bc925ec72
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/config/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/config/__pycache__/test_apply_pyprojecttoml.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/config/__pycache__/test_apply_pyprojecttoml.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..33bc4577d8c92def1d5143de6af08df20f8b5807
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/config/__pycache__/test_apply_pyprojecttoml.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/config/__pycache__/test_expand.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/config/__pycache__/test_expand.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0ebed7c5a3a56be2303a7b928cae281e5d9e4368
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/config/__pycache__/test_expand.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/config/__pycache__/test_pyprojecttoml.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/config/__pycache__/test_pyprojecttoml.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9a3783dd2041e605fb8e7ef55fb5b101f2c5af14
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/config/__pycache__/test_pyprojecttoml.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/config/__pycache__/test_pyprojecttoml_dynamic_deps.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/config/__pycache__/test_pyprojecttoml_dynamic_deps.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..316e7caf5eb97b0e5ba6f3e028e5d479b959d7ff
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/config/__pycache__/test_pyprojecttoml_dynamic_deps.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/config/__pycache__/test_setupcfg.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/config/__pycache__/test_setupcfg.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1d399dbd500b040f88d35f9ac87e3b7bbd5c6578
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/config/__pycache__/test_setupcfg.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/config/downloads/__init__.py b/.venv/lib/python3.12/site-packages/setuptools/tests/config/downloads/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..00a16423f448e7773f5e6dc9b365efe80f40a778
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/tests/config/downloads/__init__.py
@@ -0,0 +1,59 @@
+from __future__ import annotations
+
+import re
+import time
+from pathlib import Path
+from urllib.error import HTTPError
+from urllib.request import urlopen
+
+__all__ = ["DOWNLOAD_DIR", "retrieve_file", "output_file", "urls_from_file"]
+
+
+NAME_REMOVE = ("http://", "https://", "github.com/", "/raw/")
+DOWNLOAD_DIR = Path(__file__).parent
+
+
+# ----------------------------------------------------------------------
+# Please update ./preload.py accordingly when modifying this file
+# ----------------------------------------------------------------------
+
+
+def output_file(url: str, download_dir: Path = DOWNLOAD_DIR) -> Path:
+    file_name = url.strip()
+    for part in NAME_REMOVE:
+        file_name = file_name.replace(part, '').strip().strip('/:').strip()
+    return Path(download_dir, re.sub(r"[^\-_\.\w\d]+", "_", file_name))
+
+
+def retrieve_file(url: str, download_dir: Path = DOWNLOAD_DIR, wait: float = 5) -> Path:
+    path = output_file(url, download_dir)
+    if path.exists():
+        print(f"Skipping {url} (already exists: {path})")
+    else:
+        download_dir.mkdir(exist_ok=True, parents=True)
+        print(f"Downloading {url} to {path}")
+        try:
+            download(url, path)
+        except HTTPError:
+            time.sleep(wait)  # wait a few seconds and try again.
+            download(url, path)
+    return path
+
+
+def urls_from_file(list_file: Path) -> list[str]:
+    """``list_file`` should be a text file where each line corresponds to a URL to
+    download.
+    """
+    print(f"file: {list_file}")
+    content = list_file.read_text(encoding="utf-8")
+    return [url for url in content.splitlines() if not url.startswith("#")]
+
+
+def download(url: str, dest: Path):
+    with urlopen(url) as f:
+        data = f.read()
+
+    with open(dest, "wb") as f:
+        f.write(data)
+
+    assert Path(dest).exists()
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/config/downloads/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/config/downloads/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cbf0b1e8bda8d571d9c6f512971236086043c813
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/config/downloads/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/config/downloads/__pycache__/preload.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/config/downloads/__pycache__/preload.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c19a8b797c0170abe53d821f1c8367cc4303b99c
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/config/downloads/__pycache__/preload.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/config/downloads/preload.py b/.venv/lib/python3.12/site-packages/setuptools/tests/config/downloads/preload.py
new file mode 100644
index 0000000000000000000000000000000000000000..8eeb5dd75d3dcb375cee5acaf11ad385084bff5a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/tests/config/downloads/preload.py
@@ -0,0 +1,18 @@
+"""This file can be used to preload files needed for testing.
+
+For example you can use::
+
+    cd setuptools/tests/config
+    python -m downloads.preload setupcfg_examples.txt
+
+to make sure the `setup.cfg` examples are downloaded before starting the tests.
+"""
+
+import sys
+from pathlib import Path
+
+from . import retrieve_file, urls_from_file
+
+if __name__ == "__main__":
+    urls = urls_from_file(Path(sys.argv[1]))
+    list(map(retrieve_file, urls))
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/config/setupcfg_examples.txt b/.venv/lib/python3.12/site-packages/setuptools/tests/config/setupcfg_examples.txt
new file mode 100644
index 0000000000000000000000000000000000000000..6aab887ff1fe631d97f1abea90a8448040746a12
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/tests/config/setupcfg_examples.txt
@@ -0,0 +1,22 @@
+# ====================================================================
+# Some popular packages that use setup.cfg (and others not so popular)
+# Reference: https://hugovk.github.io/top-pypi-packages/
+# ====================================================================
+https://github.com/pypa/setuptools/raw/52c990172fec37766b3566679724aa8bf70ae06d/setup.cfg
+https://github.com/pypa/wheel/raw/0acd203cd896afec7f715aa2ff5980a403459a3b/setup.cfg
+https://github.com/python/importlib_metadata/raw/2f05392ca980952a6960d82b2f2d2ea10aa53239/setup.cfg
+https://github.com/jaraco/skeleton/raw/d9008b5c510cd6969127a6a2ab6f832edddef296/setup.cfg
+https://github.com/jaraco/zipp/raw/700d3a96390e970b6b962823bfea78b4f7e1c537/setup.cfg
+https://github.com/pallets/jinja/raw/7d72eb7fefb7dce065193967f31f805180508448/setup.cfg
+https://github.com/tkem/cachetools/raw/2fd87a94b8d3861d80e9e4236cd480bfdd21c90d/setup.cfg
+https://github.com/aio-libs/aiohttp/raw/5e0e6b7080f2408d5f1dd544c0e1cf88378b7b10/setup.cfg
+https://github.com/pallets/flask/raw/9486b6cf57bd6a8a261f67091aca8ca78eeec1e3/setup.cfg
+https://github.com/pallets/click/raw/6411f425fae545f42795665af4162006b36c5e4a/setup.cfg
+https://github.com/sqlalchemy/sqlalchemy/raw/533f5718904b620be8d63f2474229945d6f8ba5d/setup.cfg
+https://github.com/pytest-dev/pluggy/raw/461ef63291d13589c4e21aa182cd1529257e9a0a/setup.cfg
+https://github.com/pytest-dev/pytest/raw/c7be96dae487edbd2f55b561b31b68afac1dabe6/setup.cfg
+https://github.com/platformdirs/platformdirs/raw/7b7852128dd6f07511b618d6edea35046bd0c6ff/setup.cfg
+https://github.com/pandas-dev/pandas/raw/bc17343f934a33dc231c8c74be95d8365537c376/setup.cfg
+https://github.com/django/django/raw/4e249d11a6e56ca8feb4b055b681cec457ef3a3d/setup.cfg
+https://github.com/pyscaffold/pyscaffold/raw/de7aa5dc059fbd04307419c667cc4961bc9df4b8/setup.cfg
+https://github.com/pypa/virtualenv/raw/f92eda6e3da26a4d28c2663ffb85c4960bdb990c/setup.cfg
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/config/test_apply_pyprojecttoml.py b/.venv/lib/python3.12/site-packages/setuptools/tests/config/test_apply_pyprojecttoml.py
new file mode 100644
index 0000000000000000000000000000000000000000..489fd98e26710e74d66204b6f51c2523586aaa04
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/tests/config/test_apply_pyprojecttoml.py
@@ -0,0 +1,772 @@
+"""Make sure that applying the configuration from pyproject.toml is equivalent to
+applying a similar configuration from setup.cfg
+
+To run these tests offline, please have a look on ``./downloads/preload.py``
+"""
+
+from __future__ import annotations
+
+import io
+import re
+import tarfile
+from inspect import cleandoc
+from pathlib import Path
+from unittest.mock import Mock
+
+import pytest
+from ini2toml.api import LiteTranslator
+from packaging.metadata import Metadata
+
+import setuptools  # noqa: F401 # ensure monkey patch to metadata
+from setuptools._static import is_static
+from setuptools.command.egg_info import write_requirements
+from setuptools.config import expand, pyprojecttoml, setupcfg
+from setuptools.config._apply_pyprojecttoml import _MissingDynamic, _some_attrgetter
+from setuptools.dist import Distribution
+from setuptools.errors import InvalidConfigError, RemovedConfigError
+from setuptools.warnings import InformationOnly, SetuptoolsDeprecationWarning
+
+from .downloads import retrieve_file, urls_from_file
+
+HERE = Path(__file__).parent
+EXAMPLES_FILE = "setupcfg_examples.txt"
+
+
+def makedist(path, **attrs):
+    return Distribution({"src_root": path, **attrs})
+
+
+def _mock_expand_patterns(patterns, *_, **__):
+    """
+    Allow comparing the given patterns for 2 dist objects.
+    We need to strip special chars to avoid errors when validating.
+    """
+    return [re.sub("[^a-z0-9]+", "", p, flags=re.I) or "empty" for p in patterns]
+
+
+@pytest.mark.parametrize("url", urls_from_file(HERE / EXAMPLES_FILE))
+@pytest.mark.filterwarnings("ignore")
+@pytest.mark.uses_network
+def test_apply_pyproject_equivalent_to_setupcfg(url, monkeypatch, tmp_path):
+    monkeypatch.setattr(expand, "read_attr", Mock(return_value="0.0.1"))
+    monkeypatch.setattr(
+        Distribution, "_expand_patterns", Mock(side_effect=_mock_expand_patterns)
+    )
+    setupcfg_example = retrieve_file(url)
+    pyproject_example = Path(tmp_path, "pyproject.toml")
+    setupcfg_text = setupcfg_example.read_text(encoding="utf-8")
+    toml_config = LiteTranslator().translate(setupcfg_text, "setup.cfg")
+    pyproject_example.write_text(toml_config, encoding="utf-8")
+
+    dist_toml = pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject_example)
+    dist_cfg = setupcfg.apply_configuration(makedist(tmp_path), setupcfg_example)
+
+    pkg_info_toml = core_metadata(dist_toml)
+    pkg_info_cfg = core_metadata(dist_cfg)
+    assert pkg_info_toml == pkg_info_cfg
+
+    if any(getattr(d, "license_files", None) for d in (dist_toml, dist_cfg)):
+        assert set(dist_toml.license_files) == set(dist_cfg.license_files)
+
+    if any(getattr(d, "entry_points", None) for d in (dist_toml, dist_cfg)):
+        print(dist_cfg.entry_points)
+        ep_toml = {
+            (k, *sorted(i.replace(" ", "") for i in v))
+            for k, v in dist_toml.entry_points.items()
+        }
+        ep_cfg = {
+            (k, *sorted(i.replace(" ", "") for i in v))
+            for k, v in dist_cfg.entry_points.items()
+        }
+        assert ep_toml == ep_cfg
+
+    if any(getattr(d, "package_data", None) for d in (dist_toml, dist_cfg)):
+        pkg_data_toml = {(k, *sorted(v)) for k, v in dist_toml.package_data.items()}
+        pkg_data_cfg = {(k, *sorted(v)) for k, v in dist_cfg.package_data.items()}
+        assert pkg_data_toml == pkg_data_cfg
+
+    if any(getattr(d, "data_files", None) for d in (dist_toml, dist_cfg)):
+        data_files_toml = {(k, *sorted(v)) for k, v in dist_toml.data_files}
+        data_files_cfg = {(k, *sorted(v)) for k, v in dist_cfg.data_files}
+        assert data_files_toml == data_files_cfg
+
+    assert set(dist_toml.install_requires) == set(dist_cfg.install_requires)
+    if any(getattr(d, "extras_require", None) for d in (dist_toml, dist_cfg)):
+        extra_req_toml = {(k, *sorted(v)) for k, v in dist_toml.extras_require.items()}
+        extra_req_cfg = {(k, *sorted(v)) for k, v in dist_cfg.extras_require.items()}
+        assert extra_req_toml == extra_req_cfg
+
+
+PEP621_EXAMPLE = """\
+[project]
+name = "spam"
+version = "2020.0.0"
+description = "Lovely Spam! Wonderful Spam!"
+readme = "README.rst"
+requires-python = ">=3.8"
+license-files = ["LICENSE.txt"]  # Updated to be PEP 639 compliant
+keywords = ["egg", "bacon", "sausage", "tomatoes", "Lobster Thermidor"]
+authors = [
+  {email = "hi@pradyunsg.me"},
+  {name = "Tzu-Ping Chung"}
+]
+maintainers = [
+  {name = "Brett Cannon", email = "brett@python.org"},
+  {name = "John X. Ãørçeč", email = "john@utf8.org"},
+  {name = "Γαμα קּ 東", email = "gama@utf8.org"},
+]
+classifiers = [
+  "Development Status :: 4 - Beta",
+  "Programming Language :: Python"
+]
+
+dependencies = [
+  "httpx",
+  "gidgethub[httpx]>4.0.0",
+  "django>2.1; os_name != 'nt'",
+  "django>2.0; os_name == 'nt'"
+]
+
+[project.optional-dependencies]
+test = [
+  "pytest < 5.0.0",
+  "pytest-cov[all]"
+]
+
+[project.urls]
+homepage = "http://example.com"
+documentation = "http://readthedocs.org"
+repository = "http://github.com"
+changelog = "http://github.com/me/spam/blob/master/CHANGELOG.md"
+
+[project.scripts]
+spam-cli = "spam:main_cli"
+
+[project.gui-scripts]
+spam-gui = "spam:main_gui"
+
+[project.entry-points."spam.magical"]
+tomatoes = "spam:main_tomatoes"
+"""
+
+PEP621_INTERNATIONAL_EMAIL_EXAMPLE = """\
+[project]
+name = "spam"
+version = "2020.0.0"
+authors = [
+  {email = "hi@pradyunsg.me"},
+  {name = "Tzu-Ping Chung"}
+]
+maintainers = [
+  {name = "Степан Бандера", email = "криївка@оун-упа.укр"},
+]
+"""
+
+PEP621_EXAMPLE_SCRIPT = """
+def main_cli(): pass
+def main_gui(): pass
+def main_tomatoes(): pass
+"""
+
+PEP639_LICENSE_TEXT = """\
+[project]
+name = "spam"
+version = "2020.0.0"
+authors = [
+  {email = "hi@pradyunsg.me"},
+  {name = "Tzu-Ping Chung"}
+]
+license = {text = "MIT"}
+"""
+
+PEP639_LICENSE_EXPRESSION = """\
+[project]
+name = "spam"
+version = "2020.0.0"
+authors = [
+  {email = "hi@pradyunsg.me"},
+  {name = "Tzu-Ping Chung"}
+]
+license = "mit or apache-2.0"  # should be normalized in metadata
+classifiers = [
+    "Development Status :: 5 - Production/Stable",
+    "Programming Language :: Python",
+]
+"""
+
+
+def _pep621_example_project(
+    tmp_path,
+    readme="README.rst",
+    pyproject_text=PEP621_EXAMPLE,
+):
+    pyproject = tmp_path / "pyproject.toml"
+    text = pyproject_text
+    replacements = {'readme = "README.rst"': f'readme = "{readme}"'}
+    for orig, subst in replacements.items():
+        text = text.replace(orig, subst)
+    pyproject.write_text(text, encoding="utf-8")
+
+    (tmp_path / readme).write_text("hello world", encoding="utf-8")
+    (tmp_path / "LICENSE.txt").write_text("--- LICENSE stub ---", encoding="utf-8")
+    (tmp_path / "spam.py").write_text(PEP621_EXAMPLE_SCRIPT, encoding="utf-8")
+    return pyproject
+
+
+def test_pep621_example(tmp_path):
+    """Make sure the example in PEP 621 works"""
+    pyproject = _pep621_example_project(tmp_path)
+    dist = pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+    assert set(dist.metadata.license_files) == {"LICENSE.txt"}
+
+
+@pytest.mark.parametrize(
+    ("readme", "ctype"),
+    [
+        ("Readme.txt", "text/plain"),
+        ("readme.md", "text/markdown"),
+        ("text.rst", "text/x-rst"),
+    ],
+)
+def test_readme_content_type(tmp_path, readme, ctype):
+    pyproject = _pep621_example_project(tmp_path, readme)
+    dist = pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+    assert dist.metadata.long_description_content_type == ctype
+
+
+def test_undefined_content_type(tmp_path):
+    pyproject = _pep621_example_project(tmp_path, "README.tex")
+    with pytest.raises(ValueError, match="Undefined content type for README.tex"):
+        pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+
+
+def test_no_explicit_content_type_for_missing_extension(tmp_path):
+    pyproject = _pep621_example_project(tmp_path, "README")
+    dist = pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+    assert dist.metadata.long_description_content_type is None
+
+
+@pytest.mark.parametrize(
+    ("pyproject_text", "expected_maintainers_meta_value"),
+    (
+        pytest.param(
+            PEP621_EXAMPLE,
+            (
+                'Brett Cannon , "John X. Ãørçeč" , '
+                'Γαμα קּ 東 '
+            ),
+            id='non-international-emails',
+        ),
+        pytest.param(
+            PEP621_INTERNATIONAL_EMAIL_EXAMPLE,
+            'Степан Бандера <криївка@оун-упа.укр>',
+            marks=pytest.mark.xfail(
+                reason="CPython's `email.headerregistry.Address` only supports "
+                'RFC 5322, as of Nov 10, 2022 and latest Python 3.11.0',
+                strict=True,
+            ),
+            id='international-email',
+        ),
+    ),
+)
+def test_utf8_maintainer_in_metadata(  # issue-3663
+    expected_maintainers_meta_value,
+    pyproject_text,
+    tmp_path,
+):
+    pyproject = _pep621_example_project(
+        tmp_path,
+        "README",
+        pyproject_text=pyproject_text,
+    )
+    dist = pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+    assert dist.metadata.maintainer_email == expected_maintainers_meta_value
+    pkg_file = tmp_path / "PKG-FILE"
+    with open(pkg_file, "w", encoding="utf-8") as fh:
+        dist.metadata.write_pkg_file(fh)
+    content = pkg_file.read_text(encoding="utf-8")
+    assert f"Maintainer-email: {expected_maintainers_meta_value}" in content
+
+
+@pytest.mark.parametrize(
+    (
+        'pyproject_text',
+        'license',
+        'license_expression',
+        'content_str',
+        'not_content_str',
+    ),
+    (
+        pytest.param(
+            PEP639_LICENSE_TEXT,
+            'MIT',
+            None,
+            'License: MIT',
+            'License-Expression: ',
+            id='license-text',
+            marks=[
+                pytest.mark.filterwarnings(
+                    "ignore:.project.license. as a TOML table is deprecated",
+                )
+            ],
+        ),
+        pytest.param(
+            PEP639_LICENSE_EXPRESSION,
+            None,
+            'MIT OR Apache-2.0',
+            'License-Expression: MIT OR Apache-2.0',
+            'License: ',
+            id='license-expression',
+        ),
+    ),
+)
+def test_license_in_metadata(
+    license,
+    license_expression,
+    content_str,
+    not_content_str,
+    pyproject_text,
+    tmp_path,
+):
+    pyproject = _pep621_example_project(
+        tmp_path,
+        "README",
+        pyproject_text=pyproject_text,
+    )
+    dist = pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+    assert dist.metadata.license == license
+    assert dist.metadata.license_expression == license_expression
+    pkg_file = tmp_path / "PKG-FILE"
+    with open(pkg_file, "w", encoding="utf-8") as fh:
+        dist.metadata.write_pkg_file(fh)
+    content = pkg_file.read_text(encoding="utf-8")
+    assert "Metadata-Version: 2.4" in content
+    assert content_str in content
+    assert not_content_str not in content
+
+
+def test_license_classifier_with_license_expression(tmp_path):
+    text = PEP639_LICENSE_EXPRESSION.rsplit("\n", 2)[0]
+    pyproject = _pep621_example_project(
+        tmp_path,
+        "README",
+        f"{text}\n    \"License :: OSI Approved :: MIT License\"\n]",
+    )
+    msg = "License classifiers have been superseded by license expressions"
+    with pytest.raises(InvalidConfigError, match=msg) as exc:
+        pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+
+    assert "License :: OSI Approved :: MIT License" in str(exc.value)
+
+
+def test_license_classifier_without_license_expression(tmp_path):
+    text = """\
+    [project]
+    name = "spam"
+    version = "2020.0.0"
+    license = {text = "mit or apache-2.0"}
+    classifiers = ["License :: OSI Approved :: MIT License"]
+    """
+    pyproject = _pep621_example_project(tmp_path, "README", text)
+
+    msg1 = "License classifiers are deprecated(?:.|\n)*MIT License"
+    msg2 = ".project.license. as a TOML table is deprecated"
+    with (
+        pytest.warns(SetuptoolsDeprecationWarning, match=msg1),
+        pytest.warns(SetuptoolsDeprecationWarning, match=msg2),
+    ):
+        dist = pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+
+    # Check license classifier is still included
+    assert dist.metadata.get_classifiers() == ["License :: OSI Approved :: MIT License"]
+
+
+class TestLicenseFiles:
+    def base_pyproject(
+        self,
+        tmp_path,
+        additional_text="",
+        license_toml='license = {file = "LICENSE.txt"}\n',
+    ):
+        text = PEP639_LICENSE_EXPRESSION
+
+        # Sanity-check
+        assert 'license = "mit or apache-2.0"' in text
+        assert 'license-files' not in text
+        assert "[tool.setuptools]" not in text
+
+        text = re.sub(
+            r"(license = .*)\n",
+            license_toml,
+            text,
+            count=1,
+        )
+        assert license_toml in text  # sanity check
+        text = f"{text}\n{additional_text}\n"
+        pyproject = _pep621_example_project(tmp_path, "README", pyproject_text=text)
+        return pyproject
+
+    def base_pyproject_license_pep639(self, tmp_path, additional_text=""):
+        return self.base_pyproject(
+            tmp_path,
+            additional_text=additional_text,
+            license_toml='license = "licenseref-Proprietary"'
+            '\nlicense-files = ["_FILE*"]\n',
+        )
+
+    def test_both_license_and_license_files_defined(self, tmp_path):
+        setuptools_config = '[tool.setuptools]\nlicense-files = ["_FILE*"]'
+        pyproject = self.base_pyproject(tmp_path, setuptools_config)
+
+        (tmp_path / "_FILE.txt").touch()
+        (tmp_path / "_FILE.rst").touch()
+
+        # Would normally match the `license_files` patterns, but we want to exclude it
+        # by being explicit. On the other hand, contents should be added to `license`
+        license = tmp_path / "LICENSE.txt"
+        license.write_text("LicenseRef-Proprietary\n", encoding="utf-8")
+
+        msg1 = "'tool.setuptools.license-files' is deprecated in favor of 'project.license-files'"
+        msg2 = ".project.license. as a TOML table is deprecated"
+        with (
+            pytest.warns(SetuptoolsDeprecationWarning, match=msg1),
+            pytest.warns(SetuptoolsDeprecationWarning, match=msg2),
+        ):
+            dist = pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+        assert set(dist.metadata.license_files) == {"_FILE.rst", "_FILE.txt"}
+        assert dist.metadata.license == "LicenseRef-Proprietary\n"
+
+    def test_both_license_and_license_files_defined_pep639(self, tmp_path):
+        # Set license and license-files
+        pyproject = self.base_pyproject_license_pep639(tmp_path)
+
+        (tmp_path / "_FILE.txt").touch()
+        (tmp_path / "_FILE.rst").touch()
+
+        msg = "Normalizing.*LicenseRef"
+        with pytest.warns(InformationOnly, match=msg):
+            dist = pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+
+        assert set(dist.metadata.license_files) == {"_FILE.rst", "_FILE.txt"}
+        assert dist.metadata.license is None
+        assert dist.metadata.license_expression == "LicenseRef-Proprietary"
+
+    def test_license_files_defined_twice(self, tmp_path):
+        # Set project.license-files and tools.setuptools.license-files
+        setuptools_config = '[tool.setuptools]\nlicense-files = ["_FILE*"]'
+        pyproject = self.base_pyproject_license_pep639(tmp_path, setuptools_config)
+
+        msg = "'project.license-files' is defined already. Remove 'tool.setuptools.license-files'"
+        with pytest.raises(InvalidConfigError, match=msg):
+            pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+
+    def test_default_patterns(self, tmp_path):
+        setuptools_config = '[tool.setuptools]\nzip-safe = false'
+        # ^ used just to trigger section validation
+        pyproject = self.base_pyproject(tmp_path, setuptools_config, license_toml="")
+
+        license_files = "LICENCE-a.html COPYING-abc.txt AUTHORS-xyz NOTICE,def".split()
+
+        for fname in license_files:
+            (tmp_path / fname).write_text(f"{fname}\n", encoding="utf-8")
+
+        dist = pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+
+        assert (tmp_path / "LICENSE.txt").exists()  # from base example
+        assert set(dist.metadata.license_files) == {*license_files, "LICENSE.txt"}
+
+    def test_missing_patterns(self, tmp_path):
+        pyproject = self.base_pyproject_license_pep639(tmp_path)
+        assert list(tmp_path.glob("_FILE*")) == []  # sanity check
+
+        msg1 = "Cannot find any files for the given pattern.*"
+        msg2 = "Normalizing 'licenseref-Proprietary' to 'LicenseRef-Proprietary'"
+        with (
+            pytest.warns(SetuptoolsDeprecationWarning, match=msg1),
+            pytest.warns(InformationOnly, match=msg2),
+        ):
+            pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+
+    def test_deprecated_file_expands_to_text(self, tmp_path):
+        """Make sure the old example with ``license = {text = ...}`` works"""
+
+        assert 'license-files = ["LICENSE.txt"]' in PEP621_EXAMPLE  # sanity check
+        text = PEP621_EXAMPLE.replace(
+            'license-files = ["LICENSE.txt"]',
+            'license = {file = "LICENSE.txt"}',
+        )
+        pyproject = _pep621_example_project(tmp_path, pyproject_text=text)
+
+        msg = ".project.license. as a TOML table is deprecated"
+        with pytest.warns(SetuptoolsDeprecationWarning, match=msg):
+            dist = pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+
+        assert dist.metadata.license == "--- LICENSE stub ---"
+        assert set(dist.metadata.license_files) == {"LICENSE.txt"}  # auto-filled
+
+
+class TestPyModules:
+    # https://github.com/pypa/setuptools/issues/4316
+
+    def dist(self, name):
+        toml_config = f"""
+        [project]
+        name = "test"
+        version = "42.0"
+        [tool.setuptools]
+        py-modules = [{name!r}]
+        """
+        pyproject = Path("pyproject.toml")
+        pyproject.write_text(cleandoc(toml_config), encoding="utf-8")
+        return pyprojecttoml.apply_configuration(Distribution({}), pyproject)
+
+    @pytest.mark.parametrize("module", ["pip-run", "abc-d.λ-xyz-e"])
+    def test_valid_module_name(self, tmp_path, monkeypatch, module):
+        monkeypatch.chdir(tmp_path)
+        assert module in self.dist(module).py_modules
+
+    @pytest.mark.parametrize("module", ["pip run", "-pip-run", "pip-run-stubs"])
+    def test_invalid_module_name(self, tmp_path, monkeypatch, module):
+        monkeypatch.chdir(tmp_path)
+        with pytest.raises(ValueError, match="py-modules"):
+            self.dist(module).py_modules
+
+
+class TestExtModules:
+    def test_pyproject_sets_attribute(self, tmp_path, monkeypatch):
+        monkeypatch.chdir(tmp_path)
+        pyproject = Path("pyproject.toml")
+        toml_config = """
+        [project]
+        name = "test"
+        version = "42.0"
+        [tool.setuptools]
+        ext-modules = [
+          {name = "my.ext", sources = ["hello.c", "world.c"]}
+        ]
+        """
+        pyproject.write_text(cleandoc(toml_config), encoding="utf-8")
+        with pytest.warns(pyprojecttoml._ExperimentalConfiguration):
+            dist = pyprojecttoml.apply_configuration(Distribution({}), pyproject)
+        assert len(dist.ext_modules) == 1
+        assert dist.ext_modules[0].name == "my.ext"
+        assert set(dist.ext_modules[0].sources) == {"hello.c", "world.c"}
+
+
+class TestDeprecatedFields:
+    def test_namespace_packages(self, tmp_path):
+        pyproject = tmp_path / "pyproject.toml"
+        config = """
+        [project]
+        name = "myproj"
+        version = "42"
+        [tool.setuptools]
+        namespace-packages = ["myproj.pkg"]
+        """
+        pyproject.write_text(cleandoc(config), encoding="utf-8")
+        with pytest.raises(RemovedConfigError, match="namespace-packages"):
+            pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+
+
+class TestPresetField:
+    def pyproject(self, tmp_path, dynamic, extra_content=""):
+        content = f"[project]\nname = 'proj'\ndynamic = {dynamic!r}\n"
+        if "version" not in dynamic:
+            content += "version = '42'\n"
+        file = tmp_path / "pyproject.toml"
+        file.write_text(content + extra_content, encoding="utf-8")
+        return file
+
+    @pytest.mark.parametrize(
+        ("attr", "field", "value"),
+        [
+            ("license_expression", "license", "MIT"),
+            pytest.param(
+                *("license", "license", "Not SPDX"),
+                marks=[pytest.mark.filterwarnings("ignore:.*license. overwritten")],
+            ),
+            ("classifiers", "classifiers", ["Private :: Classifier"]),
+            ("entry_points", "scripts", {"console_scripts": ["foobar=foobar:main"]}),
+            ("entry_points", "gui-scripts", {"gui_scripts": ["bazquux=bazquux:main"]}),
+            pytest.param(
+                *("install_requires", "dependencies", ["six"]),
+                marks=[
+                    pytest.mark.filterwarnings("ignore:.*install_requires. overwritten")
+                ],
+            ),
+        ],
+    )
+    def test_not_listed_in_dynamic(self, tmp_path, attr, field, value):
+        """Setuptools cannot set a field if not listed in ``dynamic``"""
+        pyproject = self.pyproject(tmp_path, [])
+        dist = makedist(tmp_path, **{attr: value})
+        msg = re.compile(f"defined outside of `pyproject.toml`:.*{field}", re.S)
+        with pytest.warns(_MissingDynamic, match=msg):
+            dist = pyprojecttoml.apply_configuration(dist, pyproject)
+
+        dist_value = _some_attrgetter(f"metadata.{attr}", attr)(dist)
+        assert not dist_value
+
+    @pytest.mark.parametrize(
+        ("attr", "field", "value"),
+        [
+            ("license_expression", "license", "MIT"),
+            ("install_requires", "dependencies", []),
+            ("extras_require", "optional-dependencies", {}),
+            ("install_requires", "dependencies", ["six"]),
+            ("classifiers", "classifiers", ["Private :: Classifier"]),
+        ],
+    )
+    def test_listed_in_dynamic(self, tmp_path, attr, field, value):
+        pyproject = self.pyproject(tmp_path, [field])
+        dist = makedist(tmp_path, **{attr: value})
+        dist = pyprojecttoml.apply_configuration(dist, pyproject)
+        dist_value = _some_attrgetter(f"metadata.{attr}", attr)(dist)
+        assert dist_value == value
+
+    def test_license_files_exempt_from_dynamic(self, monkeypatch, tmp_path):
+        """
+        license-file is currently not considered in the context of dynamic.
+        As per 2025-02-19, https://packaging.python.org/en/latest/specifications/pyproject-toml/#license-files
+        allows setuptools to fill-in `license-files` the way it sees fit:
+
+        > If the license-files key is not defined, tools can decide how to handle license files.
+        > For example they can choose not to include any files or use their own
+        > logic to discover the appropriate files in the distribution.
+
+        Using license_files from setup.py to fill-in the value is in accordance
+        with this rule.
+        """
+        monkeypatch.chdir(tmp_path)
+        pyproject = self.pyproject(tmp_path, [])
+        dist = makedist(tmp_path, license_files=["LIC*"])
+        (tmp_path / "LIC1").write_text("42", encoding="utf-8")
+        dist = pyprojecttoml.apply_configuration(dist, pyproject)
+        assert dist.metadata.license_files == ["LIC1"]
+
+    def test_warning_overwritten_dependencies(self, tmp_path):
+        src = "[project]\nname='pkg'\nversion='0.1'\ndependencies=['click']\n"
+        pyproject = tmp_path / "pyproject.toml"
+        pyproject.write_text(src, encoding="utf-8")
+        dist = makedist(tmp_path, install_requires=["wheel"])
+        with pytest.warns(match="`install_requires` overwritten"):
+            dist = pyprojecttoml.apply_configuration(dist, pyproject)
+        assert "wheel" not in dist.install_requires
+
+    def test_optional_dependencies_dont_remove_env_markers(self, tmp_path):
+        """
+        Internally setuptools converts dependencies with markers to "extras".
+        If ``install_requires`` is given by ``setup.py``, we have to ensure that
+        applying ``optional-dependencies`` does not overwrite the mandatory
+        dependencies with markers (see #3204).
+        """
+        # If setuptools replace its internal mechanism that uses `requires.txt`
+        # this test has to be rewritten to adapt accordingly
+        extra = "\n[project.optional-dependencies]\nfoo = ['bar>1']\n"
+        pyproject = self.pyproject(tmp_path, ["dependencies"], extra)
+        install_req = ['importlib-resources (>=3.0.0) ; python_version < "3.7"']
+        dist = makedist(tmp_path, install_requires=install_req)
+        dist = pyprojecttoml.apply_configuration(dist, pyproject)
+        assert "foo" in dist.extras_require
+        egg_info = dist.get_command_obj("egg_info")
+        write_requirements(egg_info, tmp_path, tmp_path / "requires.txt")
+        reqs = (tmp_path / "requires.txt").read_text(encoding="utf-8")
+        assert "importlib-resources" in reqs
+        assert "bar" in reqs
+        assert ':python_version < "3.7"' in reqs
+
+    @pytest.mark.parametrize(
+        ("field", "group"),
+        [("scripts", "console_scripts"), ("gui-scripts", "gui_scripts")],
+    )
+    @pytest.mark.filterwarnings("error")
+    def test_scripts_dont_require_dynamic_entry_points(self, tmp_path, field, group):
+        # Issue 3862
+        pyproject = self.pyproject(tmp_path, [field])
+        dist = makedist(tmp_path, entry_points={group: ["foobar=foobar:main"]})
+        dist = pyprojecttoml.apply_configuration(dist, pyproject)
+        assert group in dist.entry_points
+
+
+class TestMeta:
+    def test_example_file_in_sdist(self, setuptools_sdist):
+        """Meta test to ensure tests can run from sdist"""
+        with tarfile.open(setuptools_sdist) as tar:
+            assert any(name.endswith(EXAMPLES_FILE) for name in tar.getnames())
+
+
+class TestInteropCommandLineParsing:
+    def test_version(self, tmp_path, monkeypatch, capsys):
+        # See pypa/setuptools#4047
+        # This test can be removed once the CLI interface of setup.py is removed
+        monkeypatch.chdir(tmp_path)
+        toml_config = """
+        [project]
+        name = "test"
+        version = "42.0"
+        """
+        pyproject = Path(tmp_path, "pyproject.toml")
+        pyproject.write_text(cleandoc(toml_config), encoding="utf-8")
+        opts = {"script_args": ["--version"]}
+        dist = pyprojecttoml.apply_configuration(Distribution(opts), pyproject)
+        dist.parse_command_line()  # <-- there should be no exception here.
+        captured = capsys.readouterr()
+        assert "42.0" in captured.out
+
+
+class TestStaticConfig:
+    def test_mark_static_fields(self, tmp_path, monkeypatch):
+        monkeypatch.chdir(tmp_path)
+        toml_config = """
+        [project]
+        name = "test"
+        version = "42.0"
+        dependencies = ["hello"]
+        keywords = ["world"]
+        classifiers = ["private :: hello world"]
+        [tool.setuptools]
+        obsoletes = ["abcd"]
+        provides = ["abcd"]
+        platforms = ["abcd"]
+        """
+        pyproject = Path(tmp_path, "pyproject.toml")
+        pyproject.write_text(cleandoc(toml_config), encoding="utf-8")
+        dist = pyprojecttoml.apply_configuration(Distribution({}), pyproject)
+        assert is_static(dist.install_requires)
+        assert is_static(dist.metadata.keywords)
+        assert is_static(dist.metadata.classifiers)
+        assert is_static(dist.metadata.obsoletes)
+        assert is_static(dist.metadata.provides)
+        assert is_static(dist.metadata.platforms)
+
+
+# --- Auxiliary Functions ---
+
+
+def core_metadata(dist) -> str:
+    with io.StringIO() as buffer:
+        dist.metadata.write_pkg_file(buffer)
+        pkg_file_txt = buffer.getvalue()
+
+    # Make sure core metadata is valid
+    Metadata.from_email(pkg_file_txt, validate=True)  # can raise exceptions
+
+    skip_prefixes: tuple[str, ...] = ()
+    skip_lines = set()
+    # ---- DIFF NORMALISATION ----
+    # PEP 621 is very particular about author/maintainer metadata conversion, so skip
+    skip_prefixes += ("Author:", "Author-email:", "Maintainer:", "Maintainer-email:")
+    # May be redundant with Home-page
+    skip_prefixes += ("Project-URL: Homepage,", "Home-page:")
+    # May be missing in original (relying on default) but backfilled in the TOML
+    skip_prefixes += ("Description-Content-Type:",)
+    # Remove empty lines
+    skip_lines.add("")
+
+    result = []
+    for line in pkg_file_txt.splitlines():
+        if line.startswith(skip_prefixes) or line in skip_lines:
+            continue
+        result.append(line + "\n")
+
+    return "".join(result)
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/config/test_expand.py b/.venv/lib/python3.12/site-packages/setuptools/tests/config/test_expand.py
new file mode 100644
index 0000000000000000000000000000000000000000..c5710ec63d7d9d4ed7b709203bb2fc4b512f2093
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/tests/config/test_expand.py
@@ -0,0 +1,247 @@
+import os
+import sys
+from pathlib import Path
+
+import pytest
+
+from setuptools._static import is_static
+from setuptools.config import expand
+from setuptools.discovery import find_package_path
+
+from distutils.errors import DistutilsOptionError
+
+
+def write_files(files, root_dir):
+    for file, content in files.items():
+        path = root_dir / file
+        path.parent.mkdir(exist_ok=True, parents=True)
+        path.write_text(content, encoding="utf-8")
+
+
+def test_glob_relative(tmp_path, monkeypatch):
+    files = {
+        "dir1/dir2/dir3/file1.txt",
+        "dir1/dir2/file2.txt",
+        "dir1/file3.txt",
+        "a.ini",
+        "b.ini",
+        "dir1/c.ini",
+        "dir1/dir2/a.ini",
+    }
+
+    write_files({k: "" for k in files}, tmp_path)
+    patterns = ["**/*.txt", "[ab].*", "**/[ac].ini"]
+    monkeypatch.chdir(tmp_path)
+    assert set(expand.glob_relative(patterns)) == files
+    # Make sure the same APIs work outside cwd
+    assert set(expand.glob_relative(patterns, tmp_path)) == files
+
+
+def test_read_files(tmp_path, monkeypatch):
+    dir_ = tmp_path / "dir_"
+    (tmp_path / "_dir").mkdir(exist_ok=True)
+    (tmp_path / "a.txt").touch()
+    files = {"a.txt": "a", "dir1/b.txt": "b", "dir1/dir2/c.txt": "c"}
+    write_files(files, dir_)
+
+    secrets = Path(str(dir_) + "secrets")
+    secrets.mkdir(exist_ok=True)
+    write_files({"secrets.txt": "secret keys"}, secrets)
+
+    with monkeypatch.context() as m:
+        m.chdir(dir_)
+        assert expand.read_files(list(files)) == "a\nb\nc"
+
+        cannot_access_msg = r"Cannot access '.*\.\..a\.txt'"
+        with pytest.raises(DistutilsOptionError, match=cannot_access_msg):
+            expand.read_files(["../a.txt"])
+
+        cannot_access_secrets_msg = r"Cannot access '.*secrets\.txt'"
+        with pytest.raises(DistutilsOptionError, match=cannot_access_secrets_msg):
+            expand.read_files(["../dir_secrets/secrets.txt"])
+
+    # Make sure the same APIs work outside cwd
+    assert expand.read_files(list(files), dir_) == "a\nb\nc"
+    with pytest.raises(DistutilsOptionError, match=cannot_access_msg):
+        expand.read_files(["../a.txt"], dir_)
+
+
+class TestReadAttr:
+    @pytest.mark.parametrize(
+        "example",
+        [
+            # No cookie means UTF-8:
+            b"__version__ = '\xc3\xa9'\nraise SystemExit(1)\n",
+            # If a cookie is present, honor it:
+            b"# -*- coding: utf-8 -*-\n__version__ = '\xc3\xa9'\nraise SystemExit(1)\n",
+            b"# -*- coding: latin1 -*-\n__version__ = '\xe9'\nraise SystemExit(1)\n",
+        ],
+    )
+    def test_read_attr_encoding_cookie(self, example, tmp_path):
+        (tmp_path / "mod.py").write_bytes(example)
+        assert expand.read_attr('mod.__version__', root_dir=tmp_path) == 'é'
+
+    def test_read_attr(self, tmp_path, monkeypatch):
+        files = {
+            "pkg/__init__.py": "",
+            "pkg/sub/__init__.py": "VERSION = '0.1.1'",
+            "pkg/sub/mod.py": (
+                "VALUES = {'a': 0, 'b': {42}, 'c': (0, 1, 1)}\nraise SystemExit(1)"
+            ),
+        }
+        write_files(files, tmp_path)
+
+        with monkeypatch.context() as m:
+            m.chdir(tmp_path)
+            # Make sure it can read the attr statically without evaluating the module
+            version = expand.read_attr('pkg.sub.VERSION')
+            values = expand.read_attr('lib.mod.VALUES', {'lib': 'pkg/sub'})
+
+        assert version == '0.1.1'
+        assert is_static(values)
+
+        assert values['a'] == 0
+        assert values['b'] == {42}
+        assert is_static(values)
+
+        # Make sure the same APIs work outside cwd
+        assert expand.read_attr('pkg.sub.VERSION', root_dir=tmp_path) == '0.1.1'
+        values = expand.read_attr('lib.mod.VALUES', {'lib': 'pkg/sub'}, tmp_path)
+        assert values['c'] == (0, 1, 1)
+
+    @pytest.mark.parametrize(
+        "example",
+        [
+            "VERSION: str\nVERSION = '0.1.1'\nraise SystemExit(1)\n",
+            "VERSION: str = '0.1.1'\nraise SystemExit(1)\n",
+        ],
+    )
+    def test_read_annotated_attr(self, tmp_path, example):
+        files = {
+            "pkg/__init__.py": "",
+            "pkg/sub/__init__.py": example,
+        }
+        write_files(files, tmp_path)
+        # Make sure this attribute can be read statically
+        version = expand.read_attr('pkg.sub.VERSION', root_dir=tmp_path)
+        assert version == '0.1.1'
+        assert is_static(version)
+
+    @pytest.mark.parametrize(
+        "example",
+        [
+            "VERSION = (lambda: '0.1.1')()\n",
+            "def fn(): return '0.1.1'\nVERSION = fn()\n",
+            "VERSION: str = (lambda: '0.1.1')()\n",
+        ],
+    )
+    def test_read_dynamic_attr(self, tmp_path, monkeypatch, example):
+        files = {
+            "pkg/__init__.py": "",
+            "pkg/sub/__init__.py": example,
+        }
+        write_files(files, tmp_path)
+        monkeypatch.chdir(tmp_path)
+        version = expand.read_attr('pkg.sub.VERSION')
+        assert version == '0.1.1'
+        assert not is_static(version)
+
+    def test_import_order(self, tmp_path):
+        """
+        Sometimes the import machinery will import the parent package of a nested
+        module, which triggers side-effects and might create problems (see issue #3176)
+
+        ``read_attr`` should bypass these limitations by resolving modules statically
+        (via ast.literal_eval).
+        """
+        files = {
+            "src/pkg/__init__.py": "from .main import func\nfrom .about import version",
+            "src/pkg/main.py": "import super_complicated_dep\ndef func(): return 42",
+            "src/pkg/about.py": "version = '42'",
+        }
+        write_files(files, tmp_path)
+        attr_desc = "pkg.about.version"
+        package_dir = {"": "src"}
+        # `import super_complicated_dep` should not run, otherwise the build fails
+        assert expand.read_attr(attr_desc, package_dir, tmp_path) == "42"
+
+
+@pytest.mark.parametrize(
+    ("package_dir", "file", "module", "return_value"),
+    [
+        ({"": "src"}, "src/pkg/main.py", "pkg.main", 42),
+        ({"pkg": "lib"}, "lib/main.py", "pkg.main", 13),
+        ({}, "single_module.py", "single_module", 70),
+        ({}, "flat_layout/pkg.py", "flat_layout.pkg", 836),
+    ],
+)
+def test_resolve_class(monkeypatch, tmp_path, package_dir, file, module, return_value):
+    monkeypatch.setattr(sys, "modules", {})  # reproducibility
+    files = {file: f"class Custom:\n    def testing(self): return {return_value}"}
+    write_files(files, tmp_path)
+    cls = expand.resolve_class(f"{module}.Custom", package_dir, tmp_path)
+    assert cls().testing() == return_value
+
+
+@pytest.mark.parametrize(
+    ("args", "pkgs"),
+    [
+        ({"where": ["."], "namespaces": False}, {"pkg", "other"}),
+        ({"where": [".", "dir1"], "namespaces": False}, {"pkg", "other", "dir2"}),
+        ({"namespaces": True}, {"pkg", "other", "dir1", "dir1.dir2"}),
+        ({}, {"pkg", "other", "dir1", "dir1.dir2"}),  # default value for `namespaces`
+    ],
+)
+def test_find_packages(tmp_path, args, pkgs):
+    files = {
+        "pkg/__init__.py",
+        "other/__init__.py",
+        "dir1/dir2/__init__.py",
+    }
+    write_files({k: "" for k in files}, tmp_path)
+
+    package_dir = {}
+    kwargs = {"root_dir": tmp_path, "fill_package_dir": package_dir, **args}
+    where = kwargs.get("where", ["."])
+    assert set(expand.find_packages(**kwargs)) == pkgs
+    for pkg in pkgs:
+        pkg_path = find_package_path(pkg, package_dir, tmp_path)
+        assert os.path.exists(pkg_path)
+
+    # Make sure the same APIs work outside cwd
+    where = [
+        str((tmp_path / p).resolve()).replace(os.sep, "/")  # ensure posix-style paths
+        for p in args.pop("where", ["."])
+    ]
+
+    assert set(expand.find_packages(where=where, **args)) == pkgs
+
+
+@pytest.mark.parametrize(
+    ("files", "where", "expected_package_dir"),
+    [
+        (["pkg1/__init__.py", "pkg1/other.py"], ["."], {}),
+        (["pkg1/__init__.py", "pkg2/__init__.py"], ["."], {}),
+        (["src/pkg1/__init__.py", "src/pkg1/other.py"], ["src"], {"": "src"}),
+        (["src/pkg1/__init__.py", "src/pkg2/__init__.py"], ["src"], {"": "src"}),
+        (
+            ["src1/pkg1/__init__.py", "src2/pkg2/__init__.py"],
+            ["src1", "src2"],
+            {"pkg1": "src1/pkg1", "pkg2": "src2/pkg2"},
+        ),
+        (
+            ["src/pkg1/__init__.py", "pkg2/__init__.py"],
+            ["src", "."],
+            {"pkg1": "src/pkg1"},
+        ),
+    ],
+)
+def test_fill_package_dir(tmp_path, files, where, expected_package_dir):
+    write_files({k: "" for k in files}, tmp_path)
+    pkg_dir = {}
+    kwargs = {"root_dir": tmp_path, "fill_package_dir": pkg_dir, "namespaces": False}
+    pkgs = expand.find_packages(where=where, **kwargs)
+    assert set(pkg_dir.items()) == set(expected_package_dir.items())
+    for pkg in pkgs:
+        pkg_path = find_package_path(pkg, pkg_dir, tmp_path)
+        assert os.path.exists(pkg_path)
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/config/test_pyprojecttoml.py b/.venv/lib/python3.12/site-packages/setuptools/tests/config/test_pyprojecttoml.py
new file mode 100644
index 0000000000000000000000000000000000000000..db40fcd23da137dfb2f4ddde7ffb722193ee83e2
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/tests/config/test_pyprojecttoml.py
@@ -0,0 +1,396 @@
+import re
+from configparser import ConfigParser
+from inspect import cleandoc
+
+import jaraco.path
+import pytest
+import tomli_w
+from path import Path
+
+import setuptools  # noqa: F401 # force distutils.core to be patched
+from setuptools.config.pyprojecttoml import (
+    _ToolsTypoInMetadata,
+    apply_configuration,
+    expand_configuration,
+    read_configuration,
+    validate,
+)
+from setuptools.dist import Distribution
+from setuptools.errors import OptionError
+
+import distutils.core
+
+EXAMPLE = """
+[project]
+name = "myproj"
+keywords = ["some", "key", "words"]
+dynamic = ["version", "readme"]
+requires-python = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*"
+dependencies = [
+    'importlib-metadata>=0.12;python_version<"3.8"',
+    'importlib-resources>=1.0;python_version<"3.7"',
+    'pathlib2>=2.3.3,<3;python_version < "3.4" and sys.platform != "win32"',
+]
+
+[project.optional-dependencies]
+docs = [
+    "sphinx>=3",
+    "sphinx-argparse>=0.2.5",
+    "sphinx-rtd-theme>=0.4.3",
+]
+testing = [
+    "pytest>=1",
+    "coverage>=3,<5",
+]
+
+[project.scripts]
+exec = "pkg.__main__:exec"
+
+[build-system]
+requires = ["setuptools", "wheel"]
+build-backend = "setuptools.build_meta"
+
+[tool.setuptools]
+package-dir = {"" = "src"}
+zip-safe = true
+platforms = ["any"]
+
+[tool.setuptools.packages.find]
+where = ["src"]
+
+[tool.setuptools.cmdclass]
+sdist = "pkg.mod.CustomSdist"
+
+[tool.setuptools.dynamic.version]
+attr = "pkg.__version__.VERSION"
+
+[tool.setuptools.dynamic.readme]
+file = ["README.md"]
+content-type = "text/markdown"
+
+[tool.setuptools.package-data]
+"*" = ["*.txt"]
+
+[tool.setuptools.data-files]
+"data" = ["_files/*.txt"]
+
+[tool.distutils.sdist]
+formats = "gztar"
+
+[tool.distutils.bdist_wheel]
+universal = true
+"""
+
+
+def create_example(path, pkg_root):
+    files = {
+        "pyproject.toml": EXAMPLE,
+        "README.md": "hello world",
+        "_files": {
+            "file.txt": "",
+        },
+    }
+    packages = {
+        "pkg": {
+            "__init__.py": "",
+            "mod.py": "class CustomSdist: pass",
+            "__version__.py": "VERSION = (3, 10)",
+            "__main__.py": "def exec(): print('hello')",
+        },
+    }
+
+    assert pkg_root  # Meta-test: cannot be empty string.
+
+    if pkg_root == ".":
+        files = {**files, **packages}
+        # skip other files: flat-layout will raise error for multi-package dist
+    else:
+        # Use this opportunity to ensure namespaces are discovered
+        files[pkg_root] = {**packages, "other": {"nested": {"__init__.py": ""}}}
+
+    jaraco.path.build(files, prefix=path)
+
+
+def verify_example(config, path, pkg_root):
+    pyproject = path / "pyproject.toml"
+    pyproject.write_text(tomli_w.dumps(config), encoding="utf-8")
+    expanded = expand_configuration(config, path)
+    expanded_project = expanded["project"]
+    assert read_configuration(pyproject, expand=True) == expanded
+    assert expanded_project["version"] == "3.10"
+    assert expanded_project["readme"]["text"] == "hello world"
+    assert "packages" in expanded["tool"]["setuptools"]
+    if pkg_root == ".":
+        # Auto-discovery will raise error for multi-package dist
+        assert set(expanded["tool"]["setuptools"]["packages"]) == {"pkg"}
+    else:
+        assert set(expanded["tool"]["setuptools"]["packages"]) == {
+            "pkg",
+            "other",
+            "other.nested",
+        }
+    assert expanded["tool"]["setuptools"]["include-package-data"] is True
+    assert "" in expanded["tool"]["setuptools"]["package-data"]
+    assert "*" not in expanded["tool"]["setuptools"]["package-data"]
+    assert expanded["tool"]["setuptools"]["data-files"] == [
+        ("data", ["_files/file.txt"])
+    ]
+
+
+def test_read_configuration(tmp_path):
+    create_example(tmp_path, "src")
+    pyproject = tmp_path / "pyproject.toml"
+
+    config = read_configuration(pyproject, expand=False)
+    assert config["project"].get("version") is None
+    assert config["project"].get("readme") is None
+
+    verify_example(config, tmp_path, "src")
+
+
+@pytest.mark.parametrize(
+    ("pkg_root", "opts"),
+    [
+        (".", {}),
+        ("src", {}),
+        ("lib", {"packages": {"find": {"where": ["lib"]}}}),
+    ],
+)
+def test_discovered_package_dir_with_attr_directive_in_config(tmp_path, pkg_root, opts):
+    create_example(tmp_path, pkg_root)
+
+    pyproject = tmp_path / "pyproject.toml"
+
+    config = read_configuration(pyproject, expand=False)
+    assert config["project"].get("version") is None
+    assert config["project"].get("readme") is None
+    config["tool"]["setuptools"].pop("packages", None)
+    config["tool"]["setuptools"].pop("package-dir", None)
+
+    config["tool"]["setuptools"].update(opts)
+    verify_example(config, tmp_path, pkg_root)
+
+
+ENTRY_POINTS = {
+    "console_scripts": {"a": "mod.a:func"},
+    "gui_scripts": {"b": "mod.b:func"},
+    "other": {"c": "mod.c:func [extra]"},
+}
+
+
+class TestEntryPoints:
+    def write_entry_points(self, tmp_path):
+        entry_points = ConfigParser()
+        entry_points.read_dict(ENTRY_POINTS)
+        with open(tmp_path / "entry-points.txt", "w", encoding="utf-8") as f:
+            entry_points.write(f)
+
+    def pyproject(self, dynamic=None):
+        project = {"dynamic": dynamic or ["scripts", "gui-scripts", "entry-points"]}
+        tool = {"dynamic": {"entry-points": {"file": "entry-points.txt"}}}
+        return {"project": project, "tool": {"setuptools": tool}}
+
+    def test_all_listed_in_dynamic(self, tmp_path):
+        self.write_entry_points(tmp_path)
+        expanded = expand_configuration(self.pyproject(), tmp_path)
+        expanded_project = expanded["project"]
+        assert len(expanded_project["scripts"]) == 1
+        assert expanded_project["scripts"]["a"] == "mod.a:func"
+        assert len(expanded_project["gui-scripts"]) == 1
+        assert expanded_project["gui-scripts"]["b"] == "mod.b:func"
+        assert len(expanded_project["entry-points"]) == 1
+        assert expanded_project["entry-points"]["other"]["c"] == "mod.c:func [extra]"
+
+    @pytest.mark.parametrize("missing_dynamic", ("scripts", "gui-scripts"))
+    def test_scripts_not_listed_in_dynamic(self, tmp_path, missing_dynamic):
+        self.write_entry_points(tmp_path)
+        dynamic = {"scripts", "gui-scripts", "entry-points"} - {missing_dynamic}
+
+        msg = f"defined outside of `pyproject.toml`:.*{missing_dynamic}"
+        with pytest.raises(OptionError, match=re.compile(msg, re.S)):
+            expand_configuration(self.pyproject(dynamic), tmp_path)
+
+
+class TestClassifiers:
+    def test_dynamic(self, tmp_path):
+        # Let's create a project example that has dynamic classifiers
+        # coming from a txt file.
+        create_example(tmp_path, "src")
+        classifiers = cleandoc(
+            """
+            Framework :: Flask
+            Programming Language :: Haskell
+            """
+        )
+        (tmp_path / "classifiers.txt").write_text(classifiers, encoding="utf-8")
+
+        pyproject = tmp_path / "pyproject.toml"
+        config = read_configuration(pyproject, expand=False)
+        dynamic = config["project"]["dynamic"]
+        config["project"]["dynamic"] = list({*dynamic, "classifiers"})
+        dynamic_config = config["tool"]["setuptools"]["dynamic"]
+        dynamic_config["classifiers"] = {"file": "classifiers.txt"}
+
+        # When the configuration is expanded,
+        # each line of the file should be an different classifier.
+        validate(config, pyproject)
+        expanded = expand_configuration(config, tmp_path)
+
+        assert set(expanded["project"]["classifiers"]) == {
+            "Framework :: Flask",
+            "Programming Language :: Haskell",
+        }
+
+    def test_dynamic_without_config(self, tmp_path):
+        config = """
+        [project]
+        name = "myproj"
+        version = '42'
+        dynamic = ["classifiers"]
+        """
+
+        pyproject = tmp_path / "pyproject.toml"
+        pyproject.write_text(cleandoc(config), encoding="utf-8")
+        with pytest.raises(OptionError, match="No configuration .* .classifiers."):
+            read_configuration(pyproject)
+
+    def test_dynamic_readme_from_setup_script_args(self, tmp_path):
+        config = """
+        [project]
+        name = "myproj"
+        version = '42'
+        dynamic = ["readme"]
+        """
+        pyproject = tmp_path / "pyproject.toml"
+        pyproject.write_text(cleandoc(config), encoding="utf-8")
+        dist = Distribution(attrs={"long_description": "42"})
+        # No error should occur because of missing `readme`
+        dist = apply_configuration(dist, pyproject)
+        assert dist.metadata.long_description == "42"
+
+    def test_dynamic_without_file(self, tmp_path):
+        config = """
+        [project]
+        name = "myproj"
+        version = '42'
+        dynamic = ["classifiers"]
+
+        [tool.setuptools.dynamic]
+        classifiers = {file = ["classifiers.txt"]}
+        """
+
+        pyproject = tmp_path / "pyproject.toml"
+        pyproject.write_text(cleandoc(config), encoding="utf-8")
+        with pytest.warns(UserWarning, match="File .*classifiers.txt. cannot be found"):
+            expanded = read_configuration(pyproject)
+        assert "classifiers" not in expanded["project"]
+
+
+@pytest.mark.parametrize(
+    "example",
+    (
+        """
+        [project]
+        name = "myproj"
+        version = "1.2"
+
+        [my-tool.that-disrespect.pep518]
+        value = 42
+        """,
+    ),
+)
+def test_ignore_unrelated_config(tmp_path, example):
+    pyproject = tmp_path / "pyproject.toml"
+    pyproject.write_text(cleandoc(example), encoding="utf-8")
+
+    # Make sure no error is raised due to 3rd party configs in pyproject.toml
+    assert read_configuration(pyproject) is not None
+
+
+@pytest.mark.parametrize(
+    ("example", "error_msg"),
+    [
+        (
+            """
+            [project]
+            name = "myproj"
+            version = "1.2"
+            requires = ['pywin32; platform_system=="Windows"' ]
+            """,
+            "configuration error: .project. must not contain ..requires.. properties",
+        ),
+    ],
+)
+def test_invalid_example(tmp_path, example, error_msg):
+    pyproject = tmp_path / "pyproject.toml"
+    pyproject.write_text(cleandoc(example), encoding="utf-8")
+
+    pattern = re.compile(f"invalid pyproject.toml.*{error_msg}.*", re.M | re.S)
+    with pytest.raises(ValueError, match=pattern):
+        read_configuration(pyproject)
+
+
+@pytest.mark.parametrize("config", ("", "[tool.something]\nvalue = 42"))
+def test_empty(tmp_path, config):
+    pyproject = tmp_path / "pyproject.toml"
+    pyproject.write_text(config, encoding="utf-8")
+
+    # Make sure no error is raised
+    assert read_configuration(pyproject) == {}
+
+
+@pytest.mark.parametrize("config", ("[project]\nname = 'myproj'\nversion='42'\n",))
+def test_include_package_data_by_default(tmp_path, config):
+    """Builds with ``pyproject.toml`` should consider ``include-package-data=True`` as
+    default.
+    """
+    pyproject = tmp_path / "pyproject.toml"
+    pyproject.write_text(config, encoding="utf-8")
+
+    config = read_configuration(pyproject)
+    assert config["tool"]["setuptools"]["include-package-data"] is True
+
+
+def test_include_package_data_in_setuppy(tmp_path):
+    """Builds with ``pyproject.toml`` should consider ``include_package_data`` set in
+    ``setup.py``.
+
+    See https://github.com/pypa/setuptools/issues/3197#issuecomment-1079023889
+    """
+    files = {
+        "pyproject.toml": "[project]\nname = 'myproj'\nversion='42'\n",
+        "setup.py": "__import__('setuptools').setup(include_package_data=False)",
+    }
+    jaraco.path.build(files, prefix=tmp_path)
+
+    with Path(tmp_path):
+        dist = distutils.core.run_setup("setup.py", {}, stop_after="config")
+
+    assert dist.get_name() == "myproj"
+    assert dist.get_version() == "42"
+    assert dist.include_package_data is False
+
+
+def test_warn_tools_typo(tmp_path):
+    """Test that the common ``tools.setuptools`` typo in ``pyproject.toml`` issues a warning
+
+    See https://github.com/pypa/setuptools/issues/4150
+    """
+    config = """
+    [build-system]
+    requires = ["setuptools"]
+    build-backend = "setuptools.build_meta"
+
+    [project]
+    name = "myproj"
+    version = '42'
+
+    [tools.setuptools]
+    packages = ["package"]
+    """
+
+    pyproject = tmp_path / "pyproject.toml"
+    pyproject.write_text(cleandoc(config), encoding="utf-8")
+
+    with pytest.warns(_ToolsTypoInMetadata):
+        read_configuration(pyproject)
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/config/test_pyprojecttoml_dynamic_deps.py b/.venv/lib/python3.12/site-packages/setuptools/tests/config/test_pyprojecttoml_dynamic_deps.py
new file mode 100644
index 0000000000000000000000000000000000000000..e42f28ffaaf5270a74fe9f03885b75bb91858030
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/tests/config/test_pyprojecttoml_dynamic_deps.py
@@ -0,0 +1,109 @@
+from inspect import cleandoc
+
+import pytest
+from jaraco import path
+
+from setuptools.config.pyprojecttoml import apply_configuration
+from setuptools.dist import Distribution
+from setuptools.warnings import SetuptoolsWarning
+
+
+def test_dynamic_dependencies(tmp_path):
+    files = {
+        "requirements.txt": "six\n  # comment\n",
+        "pyproject.toml": cleandoc(
+            """
+            [project]
+            name = "myproj"
+            version = "1.0"
+            dynamic = ["dependencies"]
+
+            [build-system]
+            requires = ["setuptools", "wheel"]
+            build-backend = "setuptools.build_meta"
+
+            [tool.setuptools.dynamic.dependencies]
+            file = ["requirements.txt"]
+            """
+        ),
+    }
+    path.build(files, prefix=tmp_path)
+    dist = Distribution()
+    dist = apply_configuration(dist, tmp_path / "pyproject.toml")
+    assert dist.install_requires == ["six"]
+
+
+def test_dynamic_optional_dependencies(tmp_path):
+    files = {
+        "requirements-docs.txt": "sphinx\n  # comment\n",
+        "pyproject.toml": cleandoc(
+            """
+            [project]
+            name = "myproj"
+            version = "1.0"
+            dynamic = ["optional-dependencies"]
+
+            [tool.setuptools.dynamic.optional-dependencies.docs]
+            file = ["requirements-docs.txt"]
+
+            [build-system]
+            requires = ["setuptools", "wheel"]
+            build-backend = "setuptools.build_meta"
+            """
+        ),
+    }
+    path.build(files, prefix=tmp_path)
+    dist = Distribution()
+    dist = apply_configuration(dist, tmp_path / "pyproject.toml")
+    assert dist.extras_require == {"docs": ["sphinx"]}
+
+
+def test_mixed_dynamic_optional_dependencies(tmp_path):
+    """
+    Test that if PEP 621 was loosened to allow mixing of dynamic and static
+    configurations in the case of fields containing sub-fields (groups),
+    things would work out.
+    """
+    files = {
+        "requirements-images.txt": "pillow~=42.0\n  # comment\n",
+        "pyproject.toml": cleandoc(
+            """
+            [project]
+            name = "myproj"
+            version = "1.0"
+            dynamic = ["optional-dependencies"]
+
+            [project.optional-dependencies]
+            docs = ["sphinx"]
+
+            [tool.setuptools.dynamic.optional-dependencies.images]
+            file = ["requirements-images.txt"]
+            """
+        ),
+    }
+
+    path.build(files, prefix=tmp_path)
+    pyproject = tmp_path / "pyproject.toml"
+    with pytest.raises(ValueError, match="project.optional-dependencies"):
+        apply_configuration(Distribution(), pyproject)
+
+
+def test_mixed_extras_require_optional_dependencies(tmp_path):
+    files = {
+        "pyproject.toml": cleandoc(
+            """
+            [project]
+            name = "myproj"
+            version = "1.0"
+            optional-dependencies.docs = ["sphinx"]
+            """
+        ),
+    }
+
+    path.build(files, prefix=tmp_path)
+    pyproject = tmp_path / "pyproject.toml"
+
+    with pytest.warns(SetuptoolsWarning, match=".extras_require. overwritten"):
+        dist = Distribution({"extras_require": {"hello": ["world"]}})
+        dist = apply_configuration(dist, pyproject)
+        assert dist.extras_require == {"docs": ["sphinx"]}
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/config/test_setupcfg.py b/.venv/lib/python3.12/site-packages/setuptools/tests/config/test_setupcfg.py
new file mode 100644
index 0000000000000000000000000000000000000000..61af99044742b46ec99ad1d38f34f576908f3e68
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/tests/config/test_setupcfg.py
@@ -0,0 +1,980 @@
+import configparser
+import contextlib
+import inspect
+import re
+from pathlib import Path
+from unittest.mock import Mock, patch
+
+import pytest
+from packaging.requirements import InvalidRequirement
+
+from setuptools.config.setupcfg import ConfigHandler, Target, read_configuration
+from setuptools.dist import Distribution, _Distribution
+from setuptools.warnings import SetuptoolsDeprecationWarning
+
+from ..textwrap import DALS
+
+from distutils.errors import DistutilsFileError, DistutilsOptionError
+
+
+class ErrConfigHandler(ConfigHandler[Target]):
+    """Erroneous handler. Fails to implement required methods."""
+
+    section_prefix = "**err**"
+
+
+def make_package_dir(name, base_dir, ns=False):
+    dir_package = base_dir
+    for dir_name in name.split('/'):
+        dir_package = dir_package.mkdir(dir_name)
+    init_file = None
+    if not ns:
+        init_file = dir_package.join('__init__.py')
+        init_file.write('')
+    return dir_package, init_file
+
+
+def fake_env(
+    tmpdir, setup_cfg, setup_py=None, encoding='ascii', package_path='fake_package'
+):
+    if setup_py is None:
+        setup_py = 'from setuptools import setup\nsetup()\n'
+
+    tmpdir.join('setup.py').write(setup_py)
+    config = tmpdir.join('setup.cfg')
+    config.write(setup_cfg.encode(encoding), mode='wb')
+
+    package_dir, init_file = make_package_dir(package_path, tmpdir)
+
+    init_file.write(
+        'VERSION = (1, 2, 3)\n'
+        '\n'
+        'VERSION_MAJOR = 1'
+        '\n'
+        'def get_version():\n'
+        '    return [3, 4, 5, "dev"]\n'
+        '\n'
+    )
+
+    return package_dir, config
+
+
+@contextlib.contextmanager
+def get_dist(tmpdir, kwargs_initial=None, parse=True):
+    kwargs_initial = kwargs_initial or {}
+
+    with tmpdir.as_cwd():
+        dist = Distribution(kwargs_initial)
+        dist.script_name = 'setup.py'
+        parse and dist.parse_config_files()
+
+        yield dist
+
+
+def test_parsers_implemented():
+    with pytest.raises(NotImplementedError):
+        handler = ErrConfigHandler(None, {}, False, Mock())
+        handler.parsers
+
+
+class TestConfigurationReader:
+    def test_basic(self, tmpdir):
+        _, config = fake_env(
+            tmpdir,
+            '[metadata]\n'
+            'version = 10.1.1\n'
+            'keywords = one, two\n'
+            '\n'
+            '[options]\n'
+            'scripts = bin/a.py, bin/b.py\n',
+        )
+        config_dict = read_configuration(str(config))
+        assert config_dict['metadata']['version'] == '10.1.1'
+        assert config_dict['metadata']['keywords'] == ['one', 'two']
+        assert config_dict['options']['scripts'] == ['bin/a.py', 'bin/b.py']
+
+    def test_no_config(self, tmpdir):
+        with pytest.raises(DistutilsFileError):
+            read_configuration(str(tmpdir.join('setup.cfg')))
+
+    def test_ignore_errors(self, tmpdir):
+        _, config = fake_env(
+            tmpdir,
+            '[metadata]\nversion = attr: none.VERSION\nkeywords = one, two\n',
+        )
+        with pytest.raises(ImportError):
+            read_configuration(str(config))
+
+        config_dict = read_configuration(str(config), ignore_option_errors=True)
+
+        assert config_dict['metadata']['keywords'] == ['one', 'two']
+        assert 'version' not in config_dict['metadata']
+
+        config.remove()
+
+
+class TestMetadata:
+    def test_basic(self, tmpdir):
+        fake_env(
+            tmpdir,
+            '[metadata]\n'
+            'version = 10.1.1\n'
+            'description = Some description\n'
+            'long_description_content_type = text/something\n'
+            'long_description = file: README\n'
+            'name = fake_name\n'
+            'keywords = one, two\n'
+            'provides = package, package.sub\n'
+            'license = otherlic\n'
+            'download_url = http://test.test.com/test/\n'
+            'maintainer_email = test@test.com\n',
+        )
+
+        tmpdir.join('README').write('readme contents\nline2')
+
+        meta_initial = {
+            # This will be used so `otherlic` won't replace it.
+            'license': 'BSD 3-Clause License',
+        }
+
+        with get_dist(tmpdir, meta_initial) as dist:
+            metadata = dist.metadata
+
+            assert metadata.version == '10.1.1'
+            assert metadata.description == 'Some description'
+            assert metadata.long_description_content_type == 'text/something'
+            assert metadata.long_description == 'readme contents\nline2'
+            assert metadata.provides == ['package', 'package.sub']
+            assert metadata.license == 'BSD 3-Clause License'
+            assert metadata.name == 'fake_name'
+            assert metadata.keywords == ['one', 'two']
+            assert metadata.download_url == 'http://test.test.com/test/'
+            assert metadata.maintainer_email == 'test@test.com'
+
+    def test_license_cfg(self, tmpdir):
+        fake_env(
+            tmpdir,
+            DALS(
+                """
+            [metadata]
+            name=foo
+            version=0.0.1
+            license=Apache 2.0
+            """
+            ),
+        )
+
+        with get_dist(tmpdir) as dist:
+            metadata = dist.metadata
+
+            assert metadata.name == "foo"
+            assert metadata.version == "0.0.1"
+            assert metadata.license == "Apache 2.0"
+
+    def test_file_mixed(self, tmpdir):
+        fake_env(
+            tmpdir,
+            '[metadata]\nlong_description = file: README.rst, CHANGES.rst\n\n',
+        )
+
+        tmpdir.join('README.rst').write('readme contents\nline2')
+        tmpdir.join('CHANGES.rst').write('changelog contents\nand stuff')
+
+        with get_dist(tmpdir) as dist:
+            assert dist.metadata.long_description == (
+                'readme contents\nline2\nchangelog contents\nand stuff'
+            )
+
+    def test_file_sandboxed(self, tmpdir):
+        tmpdir.ensure("README")
+        project = tmpdir.join('depth1', 'depth2')
+        project.ensure(dir=True)
+        fake_env(project, '[metadata]\nlong_description = file: ../../README\n')
+
+        with get_dist(project, parse=False) as dist:
+            with pytest.raises(DistutilsOptionError):
+                dist.parse_config_files()  # file: out of sandbox
+
+    def test_aliases(self, tmpdir):
+        fake_env(
+            tmpdir,
+            '[metadata]\n'
+            'author_email = test@test.com\n'
+            'home_page = http://test.test.com/test/\n'
+            'summary = Short summary\n'
+            'platform = a, b\n'
+            'classifier =\n'
+            '  Framework :: Django\n'
+            '  Programming Language :: Python :: 3.5\n',
+        )
+
+        with get_dist(tmpdir) as dist:
+            metadata = dist.metadata
+            assert metadata.author_email == 'test@test.com'
+            assert metadata.url == 'http://test.test.com/test/'
+            assert metadata.description == 'Short summary'
+            assert metadata.platforms == ['a', 'b']
+            assert metadata.classifiers == [
+                'Framework :: Django',
+                'Programming Language :: Python :: 3.5',
+            ]
+
+    def test_multiline(self, tmpdir):
+        fake_env(
+            tmpdir,
+            '[metadata]\n'
+            'name = fake_name\n'
+            'keywords =\n'
+            '  one\n'
+            '  two\n'
+            'classifiers =\n'
+            '  Framework :: Django\n'
+            '  Programming Language :: Python :: 3.5\n',
+        )
+        with get_dist(tmpdir) as dist:
+            metadata = dist.metadata
+            assert metadata.keywords == ['one', 'two']
+            assert metadata.classifiers == [
+                'Framework :: Django',
+                'Programming Language :: Python :: 3.5',
+            ]
+
+    def test_dict(self, tmpdir):
+        fake_env(
+            tmpdir,
+            '[metadata]\n'
+            'project_urls =\n'
+            '  Link One = https://example.com/one/\n'
+            '  Link Two = https://example.com/two/\n',
+        )
+        with get_dist(tmpdir) as dist:
+            metadata = dist.metadata
+            assert metadata.project_urls == {
+                'Link One': 'https://example.com/one/',
+                'Link Two': 'https://example.com/two/',
+            }
+
+    def test_version(self, tmpdir):
+        package_dir, config = fake_env(
+            tmpdir, '[metadata]\nversion = attr: fake_package.VERSION\n'
+        )
+
+        sub_a = package_dir.mkdir('subpkg_a')
+        sub_a.join('__init__.py').write('')
+        sub_a.join('mod.py').write('VERSION = (2016, 11, 26)')
+
+        sub_b = package_dir.mkdir('subpkg_b')
+        sub_b.join('__init__.py').write('')
+        sub_b.join('mod.py').write(
+            'import third_party_module\nVERSION = (2016, 11, 26)'
+        )
+
+        with get_dist(tmpdir) as dist:
+            assert dist.metadata.version == '1.2.3'
+
+        config.write('[metadata]\nversion = attr: fake_package.get_version\n')
+        with get_dist(tmpdir) as dist:
+            assert dist.metadata.version == '3.4.5.dev'
+
+        config.write('[metadata]\nversion = attr: fake_package.VERSION_MAJOR\n')
+        with get_dist(tmpdir) as dist:
+            assert dist.metadata.version == '1'
+
+        config.write('[metadata]\nversion = attr: fake_package.subpkg_a.mod.VERSION\n')
+        with get_dist(tmpdir) as dist:
+            assert dist.metadata.version == '2016.11.26'
+
+        config.write('[metadata]\nversion = attr: fake_package.subpkg_b.mod.VERSION\n')
+        with get_dist(tmpdir) as dist:
+            assert dist.metadata.version == '2016.11.26'
+
+    def test_version_file(self, tmpdir):
+        fake_env(tmpdir, '[metadata]\nversion = file: fake_package/version.txt\n')
+        tmpdir.join('fake_package', 'version.txt').write('1.2.3\n')
+
+        with get_dist(tmpdir) as dist:
+            assert dist.metadata.version == '1.2.3'
+
+        tmpdir.join('fake_package', 'version.txt').write('1.2.3\n4.5.6\n')
+        with pytest.raises(DistutilsOptionError):
+            with get_dist(tmpdir) as dist:
+                dist.metadata.version
+
+    def test_version_with_package_dir_simple(self, tmpdir):
+        fake_env(
+            tmpdir,
+            '[metadata]\n'
+            'version = attr: fake_package_simple.VERSION\n'
+            '[options]\n'
+            'package_dir =\n'
+            '    = src\n',
+            package_path='src/fake_package_simple',
+        )
+
+        with get_dist(tmpdir) as dist:
+            assert dist.metadata.version == '1.2.3'
+
+    def test_version_with_package_dir_rename(self, tmpdir):
+        fake_env(
+            tmpdir,
+            '[metadata]\n'
+            'version = attr: fake_package_rename.VERSION\n'
+            '[options]\n'
+            'package_dir =\n'
+            '    fake_package_rename = fake_dir\n',
+            package_path='fake_dir',
+        )
+
+        with get_dist(tmpdir) as dist:
+            assert dist.metadata.version == '1.2.3'
+
+    def test_version_with_package_dir_complex(self, tmpdir):
+        fake_env(
+            tmpdir,
+            '[metadata]\n'
+            'version = attr: fake_package_complex.VERSION\n'
+            '[options]\n'
+            'package_dir =\n'
+            '    fake_package_complex = src/fake_dir\n',
+            package_path='src/fake_dir',
+        )
+
+        with get_dist(tmpdir) as dist:
+            assert dist.metadata.version == '1.2.3'
+
+    def test_unknown_meta_item(self, tmpdir):
+        fake_env(tmpdir, '[metadata]\nname = fake_name\nunknown = some\n')
+        with get_dist(tmpdir, parse=False) as dist:
+            dist.parse_config_files()  # Skip unknown.
+
+    def test_usupported_section(self, tmpdir):
+        fake_env(tmpdir, '[metadata.some]\nkey = val\n')
+        with get_dist(tmpdir, parse=False) as dist:
+            with pytest.raises(DistutilsOptionError):
+                dist.parse_config_files()
+
+    def test_classifiers(self, tmpdir):
+        expected = set([
+            'Framework :: Django',
+            'Programming Language :: Python :: 3',
+            'Programming Language :: Python :: 3.5',
+        ])
+
+        # From file.
+        _, config = fake_env(tmpdir, '[metadata]\nclassifiers = file: classifiers\n')
+
+        tmpdir.join('classifiers').write(
+            'Framework :: Django\n'
+            'Programming Language :: Python :: 3\n'
+            'Programming Language :: Python :: 3.5\n'
+        )
+
+        with get_dist(tmpdir) as dist:
+            assert set(dist.metadata.classifiers) == expected
+
+        # From list notation
+        config.write(
+            '[metadata]\n'
+            'classifiers =\n'
+            '    Framework :: Django\n'
+            '    Programming Language :: Python :: 3\n'
+            '    Programming Language :: Python :: 3.5\n'
+        )
+        with get_dist(tmpdir) as dist:
+            assert set(dist.metadata.classifiers) == expected
+
+    def test_interpolation(self, tmpdir):
+        fake_env(tmpdir, '[metadata]\ndescription = %(message)s\n')
+        with pytest.raises(configparser.InterpolationMissingOptionError):
+            with get_dist(tmpdir):
+                pass
+
+    def test_non_ascii_1(self, tmpdir):
+        fake_env(tmpdir, '[metadata]\ndescription = éàïôñ\n', encoding='utf-8')
+        with get_dist(tmpdir):
+            pass
+
+    def test_non_ascii_3(self, tmpdir):
+        fake_env(tmpdir, '\n# -*- coding: invalid\n')
+        with get_dist(tmpdir):
+            pass
+
+    def test_non_ascii_4(self, tmpdir):
+        fake_env(
+            tmpdir,
+            '# -*- coding: utf-8\n[metadata]\ndescription = éàïôñ\n',
+            encoding='utf-8',
+        )
+        with get_dist(tmpdir) as dist:
+            assert dist.metadata.description == 'éàïôñ'
+
+    def test_not_utf8(self, tmpdir):
+        """
+        Config files encoded not in UTF-8 will fail
+        """
+        fake_env(
+            tmpdir,
+            '# vim: set fileencoding=iso-8859-15 :\n[metadata]\ndescription = éàïôñ\n',
+            encoding='iso-8859-15',
+        )
+        with pytest.raises(UnicodeDecodeError):
+            with get_dist(tmpdir):
+                pass
+
+    @pytest.mark.parametrize(
+        ("error_msg", "config", "invalid"),
+        [
+            (
+                "Invalid dash-separated key 'author-email' in 'metadata' (setup.cfg)",
+                DALS(
+                    """
+                    [metadata]
+                    author-email = test@test.com
+                    maintainer_email = foo@foo.com
+                    """
+                ),
+                {"author-email": "test@test.com"},
+            ),
+            (
+                "Invalid uppercase key 'Name' in 'metadata' (setup.cfg)",
+                DALS(
+                    """
+                    [metadata]
+                    Name = foo
+                    description = Some description
+                    """
+                ),
+                {"Name": "foo"},
+            ),
+        ],
+    )
+    def test_invalid_options_previously_deprecated(
+        self, tmpdir, error_msg, config, invalid
+    ):
+        # This test and related methods can be removed when no longer needed.
+        # Deprecation postponed due to push-back from the community in
+        # https://github.com/pypa/setuptools/issues/4910
+        fake_env(tmpdir, config)
+        with pytest.warns(SetuptoolsDeprecationWarning, match=re.escape(error_msg)):
+            dist = get_dist(tmpdir).__enter__()
+
+        tmpdir.join('setup.cfg').remove()
+
+        for field, value in invalid.items():
+            attr = field.replace("-", "_").lower()
+            assert getattr(dist.metadata, attr) == value
+
+
+class TestOptions:
+    def test_basic(self, tmpdir):
+        fake_env(
+            tmpdir,
+            '[options]\n'
+            'zip_safe = True\n'
+            'include_package_data = yes\n'
+            'package_dir = b=c, =src\n'
+            'packages = pack_a, pack_b.subpack\n'
+            'namespace_packages = pack1, pack2\n'
+            'scripts = bin/one.py, bin/two.py\n'
+            'eager_resources = bin/one.py, bin/two.py\n'
+            'install_requires = docutils>=0.3; pack ==1.1, ==1.3; hey\n'
+            'setup_requires = docutils>=0.3; spack ==1.1, ==1.3; there\n'
+            'dependency_links = http://some.com/here/1, '
+            'http://some.com/there/2\n'
+            'python_requires = >=1.0, !=2.8\n'
+            'py_modules = module1, module2\n',
+        )
+        deprec = pytest.warns(SetuptoolsDeprecationWarning, match="namespace_packages")
+        with deprec, get_dist(tmpdir) as dist:
+            assert dist.zip_safe
+            assert dist.include_package_data
+            assert dist.package_dir == {'': 'src', 'b': 'c'}
+            assert dist.packages == ['pack_a', 'pack_b.subpack']
+            assert dist.namespace_packages == ['pack1', 'pack2']
+            assert dist.scripts == ['bin/one.py', 'bin/two.py']
+            assert dist.dependency_links == ([
+                'http://some.com/here/1',
+                'http://some.com/there/2',
+            ])
+            assert dist.install_requires == ([
+                'docutils>=0.3',
+                'pack==1.1,==1.3',
+                'hey',
+            ])
+            assert dist.setup_requires == ([
+                'docutils>=0.3',
+                'spack ==1.1, ==1.3',
+                'there',
+            ])
+            assert dist.python_requires == '>=1.0, !=2.8'
+            assert dist.py_modules == ['module1', 'module2']
+
+    def test_multiline(self, tmpdir):
+        fake_env(
+            tmpdir,
+            '[options]\n'
+            'package_dir = \n'
+            '  b=c\n'
+            '  =src\n'
+            'packages = \n'
+            '  pack_a\n'
+            '  pack_b.subpack\n'
+            'namespace_packages = \n'
+            '  pack1\n'
+            '  pack2\n'
+            'scripts = \n'
+            '  bin/one.py\n'
+            '  bin/two.py\n'
+            'eager_resources = \n'
+            '  bin/one.py\n'
+            '  bin/two.py\n'
+            'install_requires = \n'
+            '  docutils>=0.3\n'
+            '  pack ==1.1, ==1.3\n'
+            '  hey\n'
+            'setup_requires = \n'
+            '  docutils>=0.3\n'
+            '  spack ==1.1, ==1.3\n'
+            '  there\n'
+            'dependency_links = \n'
+            '  http://some.com/here/1\n'
+            '  http://some.com/there/2\n',
+        )
+        deprec = pytest.warns(SetuptoolsDeprecationWarning, match="namespace_packages")
+        with deprec, get_dist(tmpdir) as dist:
+            assert dist.package_dir == {'': 'src', 'b': 'c'}
+            assert dist.packages == ['pack_a', 'pack_b.subpack']
+            assert dist.namespace_packages == ['pack1', 'pack2']
+            assert dist.scripts == ['bin/one.py', 'bin/two.py']
+            assert dist.dependency_links == ([
+                'http://some.com/here/1',
+                'http://some.com/there/2',
+            ])
+            assert dist.install_requires == ([
+                'docutils>=0.3',
+                'pack==1.1,==1.3',
+                'hey',
+            ])
+            assert dist.setup_requires == ([
+                'docutils>=0.3',
+                'spack ==1.1, ==1.3',
+                'there',
+            ])
+
+    def test_package_dir_fail(self, tmpdir):
+        fake_env(tmpdir, '[options]\npackage_dir = a b\n')
+        with get_dist(tmpdir, parse=False) as dist:
+            with pytest.raises(DistutilsOptionError):
+                dist.parse_config_files()
+
+    def test_package_data(self, tmpdir):
+        fake_env(
+            tmpdir,
+            '[options.package_data]\n'
+            '* = *.txt, *.rst\n'
+            'hello = *.msg\n'
+            '\n'
+            '[options.exclude_package_data]\n'
+            '* = fake1.txt, fake2.txt\n'
+            'hello = *.dat\n',
+        )
+
+        with get_dist(tmpdir) as dist:
+            assert dist.package_data == {
+                '': ['*.txt', '*.rst'],
+                'hello': ['*.msg'],
+            }
+            assert dist.exclude_package_data == {
+                '': ['fake1.txt', 'fake2.txt'],
+                'hello': ['*.dat'],
+            }
+
+    def test_packages(self, tmpdir):
+        fake_env(tmpdir, '[options]\npackages = find:\n')
+
+        with get_dist(tmpdir) as dist:
+            assert dist.packages == ['fake_package']
+
+    def test_find_directive(self, tmpdir):
+        dir_package, config = fake_env(tmpdir, '[options]\npackages = find:\n')
+
+        make_package_dir('sub_one', dir_package)
+        make_package_dir('sub_two', dir_package)
+
+        with get_dist(tmpdir) as dist:
+            assert set(dist.packages) == set([
+                'fake_package',
+                'fake_package.sub_two',
+                'fake_package.sub_one',
+            ])
+
+        config.write(
+            '[options]\n'
+            'packages = find:\n'
+            '\n'
+            '[options.packages.find]\n'
+            'where = .\n'
+            'include =\n'
+            '    fake_package.sub_one\n'
+            '    two\n'
+        )
+        with get_dist(tmpdir) as dist:
+            assert dist.packages == ['fake_package.sub_one']
+
+        config.write(
+            '[options]\n'
+            'packages = find:\n'
+            '\n'
+            '[options.packages.find]\n'
+            'exclude =\n'
+            '    fake_package.sub_one\n'
+        )
+        with get_dist(tmpdir) as dist:
+            assert set(dist.packages) == set(['fake_package', 'fake_package.sub_two'])
+
+    def test_find_namespace_directive(self, tmpdir):
+        dir_package, config = fake_env(
+            tmpdir, '[options]\npackages = find_namespace:\n'
+        )
+
+        make_package_dir('sub_one', dir_package)
+        make_package_dir('sub_two', dir_package, ns=True)
+
+        with get_dist(tmpdir) as dist:
+            assert set(dist.packages) == {
+                'fake_package',
+                'fake_package.sub_two',
+                'fake_package.sub_one',
+            }
+
+        config.write(
+            '[options]\n'
+            'packages = find_namespace:\n'
+            '\n'
+            '[options.packages.find]\n'
+            'where = .\n'
+            'include =\n'
+            '    fake_package.sub_one\n'
+            '    two\n'
+        )
+        with get_dist(tmpdir) as dist:
+            assert dist.packages == ['fake_package.sub_one']
+
+        config.write(
+            '[options]\n'
+            'packages = find_namespace:\n'
+            '\n'
+            '[options.packages.find]\n'
+            'exclude =\n'
+            '    fake_package.sub_one\n'
+        )
+        with get_dist(tmpdir) as dist:
+            assert set(dist.packages) == {'fake_package', 'fake_package.sub_two'}
+
+    def test_extras_require(self, tmpdir):
+        fake_env(
+            tmpdir,
+            '[options.extras_require]\n'
+            'pdf = ReportLab>=1.2; RXP\n'
+            'rest = \n'
+            '  docutils>=0.3\n'
+            '  pack ==1.1, ==1.3\n',
+        )
+
+        with get_dist(tmpdir) as dist:
+            assert dist.extras_require == {
+                'pdf': ['ReportLab>=1.2', 'RXP'],
+                'rest': ['docutils>=0.3', 'pack==1.1,==1.3'],
+            }
+            assert set(dist.metadata.provides_extras) == {'pdf', 'rest'}
+
+    @pytest.mark.parametrize(
+        "config",
+        [
+            "[options.extras_require]\nfoo = bar;python_version<'3'",
+            "[options.extras_require]\nfoo = bar;os_name=='linux'",
+            "[options.extras_require]\nfoo = bar;python_version<'3'\n",
+            "[options.extras_require]\nfoo = bar;os_name=='linux'\n",
+            "[options]\ninstall_requires = bar;python_version<'3'",
+            "[options]\ninstall_requires = bar;os_name=='linux'",
+            "[options]\ninstall_requires = bar;python_version<'3'\n",
+            "[options]\ninstall_requires = bar;os_name=='linux'\n",
+        ],
+    )
+    def test_raises_accidental_env_marker_misconfig(self, config, tmpdir):
+        fake_env(tmpdir, config)
+        match = (
+            r"One of the parsed requirements in `(install_requires|extras_require.+)` "
+            "looks like a valid environment marker.*"
+        )
+        with pytest.raises(InvalidRequirement, match=match):
+            with get_dist(tmpdir) as _:
+                pass
+
+    @pytest.mark.parametrize(
+        "config",
+        [
+            "[options.extras_require]\nfoo = bar;python_version<3",
+            "[options.extras_require]\nfoo = bar;python_version<3\n",
+            "[options]\ninstall_requires = bar;python_version<3",
+            "[options]\ninstall_requires = bar;python_version<3\n",
+        ],
+    )
+    def test_warn_accidental_env_marker_misconfig(self, config, tmpdir):
+        fake_env(tmpdir, config)
+        match = (
+            r"One of the parsed requirements in `(install_requires|extras_require.+)` "
+            "looks like a valid environment marker.*"
+        )
+        with pytest.warns(SetuptoolsDeprecationWarning, match=match):
+            with get_dist(tmpdir) as _:
+                pass
+
+    @pytest.mark.parametrize(
+        "config",
+        [
+            "[options.extras_require]\nfoo =\n    bar;python_version<'3'",
+            "[options.extras_require]\nfoo = bar;baz\nboo = xxx;yyy",
+            "[options.extras_require]\nfoo =\n    bar;python_version<'3'\n",
+            "[options.extras_require]\nfoo = bar;baz\nboo = xxx;yyy\n",
+            "[options.extras_require]\nfoo =\n    bar\n    python_version<3\n",
+            "[options]\ninstall_requires =\n    bar;python_version<'3'",
+            "[options]\ninstall_requires = bar;baz\nboo = xxx;yyy",
+            "[options]\ninstall_requires =\n    bar;python_version<'3'\n",
+            "[options]\ninstall_requires = bar;baz\nboo = xxx;yyy\n",
+            "[options]\ninstall_requires =\n    bar\n    python_version<3\n",
+        ],
+    )
+    @pytest.mark.filterwarnings("error::setuptools.SetuptoolsDeprecationWarning")
+    def test_nowarn_accidental_env_marker_misconfig(self, config, tmpdir, recwarn):
+        fake_env(tmpdir, config)
+        num_warnings = len(recwarn)
+        with get_dist(tmpdir) as _:
+            pass
+        # The examples are valid, no warnings shown
+        assert len(recwarn) == num_warnings
+
+    def test_dash_preserved_extras_require(self, tmpdir):
+        fake_env(tmpdir, '[options.extras_require]\nfoo-a = foo\nfoo_b = test\n')
+
+        with get_dist(tmpdir) as dist:
+            assert dist.extras_require == {'foo-a': ['foo'], 'foo_b': ['test']}
+
+    def test_entry_points(self, tmpdir):
+        _, config = fake_env(
+            tmpdir,
+            '[options.entry_points]\n'
+            'group1 = point1 = pack.module:func, '
+            '.point2 = pack.module2:func_rest [rest]\n'
+            'group2 = point3 = pack.module:func2\n',
+        )
+
+        with get_dist(tmpdir) as dist:
+            assert dist.entry_points == {
+                'group1': [
+                    'point1 = pack.module:func',
+                    '.point2 = pack.module2:func_rest [rest]',
+                ],
+                'group2': ['point3 = pack.module:func2'],
+            }
+
+        expected = (
+            '[blogtool.parsers]\n'
+            '.rst = some.nested.module:SomeClass.some_classmethod[reST]\n'
+        )
+
+        tmpdir.join('entry_points').write(expected)
+
+        # From file.
+        config.write('[options]\nentry_points = file: entry_points\n')
+
+        with get_dist(tmpdir) as dist:
+            assert dist.entry_points == expected
+
+    def test_case_sensitive_entry_points(self, tmpdir):
+        fake_env(
+            tmpdir,
+            '[options.entry_points]\n'
+            'GROUP1 = point1 = pack.module:func, '
+            '.point2 = pack.module2:func_rest [rest]\n'
+            'group2 = point3 = pack.module:func2\n',
+        )
+
+        with get_dist(tmpdir) as dist:
+            assert dist.entry_points == {
+                'GROUP1': [
+                    'point1 = pack.module:func',
+                    '.point2 = pack.module2:func_rest [rest]',
+                ],
+                'group2': ['point3 = pack.module:func2'],
+            }
+
+    def test_data_files(self, tmpdir):
+        fake_env(
+            tmpdir,
+            '[options.data_files]\n'
+            'cfg =\n'
+            '      a/b.conf\n'
+            '      c/d.conf\n'
+            'data = e/f.dat, g/h.dat\n',
+        )
+
+        with get_dist(tmpdir) as dist:
+            expected = [
+                ('cfg', ['a/b.conf', 'c/d.conf']),
+                ('data', ['e/f.dat', 'g/h.dat']),
+            ]
+            assert sorted(dist.data_files) == sorted(expected)
+
+    def test_data_files_globby(self, tmpdir):
+        fake_env(
+            tmpdir,
+            '[options.data_files]\n'
+            'cfg =\n'
+            '      a/b.conf\n'
+            '      c/d.conf\n'
+            'data = *.dat\n'
+            'icons = \n'
+            '      *.ico\n'
+            'audio = \n'
+            '      *.wav\n'
+            '      sounds.db\n',
+        )
+
+        # Create dummy files for glob()'s sake:
+        tmpdir.join('a.dat').write('')
+        tmpdir.join('b.dat').write('')
+        tmpdir.join('c.dat').write('')
+        tmpdir.join('a.ico').write('')
+        tmpdir.join('b.ico').write('')
+        tmpdir.join('c.ico').write('')
+        tmpdir.join('beep.wav').write('')
+        tmpdir.join('boop.wav').write('')
+        tmpdir.join('sounds.db').write('')
+
+        with get_dist(tmpdir) as dist:
+            expected = [
+                ('cfg', ['a/b.conf', 'c/d.conf']),
+                ('data', ['a.dat', 'b.dat', 'c.dat']),
+                ('icons', ['a.ico', 'b.ico', 'c.ico']),
+                ('audio', ['beep.wav', 'boop.wav', 'sounds.db']),
+            ]
+            assert sorted(dist.data_files) == sorted(expected)
+
+    def test_python_requires_simple(self, tmpdir):
+        fake_env(
+            tmpdir,
+            DALS(
+                """
+            [options]
+            python_requires=>=2.7
+            """
+            ),
+        )
+        with get_dist(tmpdir) as dist:
+            dist.parse_config_files()
+
+    def test_python_requires_compound(self, tmpdir):
+        fake_env(
+            tmpdir,
+            DALS(
+                """
+            [options]
+            python_requires=>=2.7,!=3.0.*
+            """
+            ),
+        )
+        with get_dist(tmpdir) as dist:
+            dist.parse_config_files()
+
+    def test_python_requires_invalid(self, tmpdir):
+        fake_env(
+            tmpdir,
+            DALS(
+                """
+            [options]
+            python_requires=invalid
+            """
+            ),
+        )
+        with pytest.raises(Exception):
+            with get_dist(tmpdir) as dist:
+                dist.parse_config_files()
+
+    def test_cmdclass(self, tmpdir):
+        module_path = Path(tmpdir, "src/custom_build.py")  # auto discovery for src
+        module_path.parent.mkdir(parents=True, exist_ok=True)
+        module_path.write_text(
+            "from distutils.core import Command\nclass CustomCmd(Command): pass\n",
+            encoding="utf-8",
+        )
+
+        setup_cfg = """
+            [options]
+            cmdclass =
+                customcmd = custom_build.CustomCmd
+        """
+        fake_env(tmpdir, inspect.cleandoc(setup_cfg))
+
+        with get_dist(tmpdir) as dist:
+            cmdclass = dist.cmdclass['customcmd']
+            assert cmdclass.__name__ == "CustomCmd"
+            assert cmdclass.__module__ == "custom_build"
+            assert module_path.samefile(inspect.getfile(cmdclass))
+
+    def test_requirements_file(self, tmpdir):
+        fake_env(
+            tmpdir,
+            DALS(
+                """
+            [options]
+            install_requires = file:requirements.txt
+            [options.extras_require]
+            colors = file:requirements-extra.txt
+            """
+            ),
+        )
+
+        tmpdir.join('requirements.txt').write('\ndocutils>=0.3\n\n')
+        tmpdir.join('requirements-extra.txt').write('colorama')
+
+        with get_dist(tmpdir) as dist:
+            assert dist.install_requires == ['docutils>=0.3']
+            assert dist.extras_require == {'colors': ['colorama']}
+
+
+saved_dist_init = _Distribution.__init__
+
+
+class TestExternalSetters:
+    # During creation of the setuptools Distribution() object, we call
+    # the init of the parent distutils Distribution object via
+    # _Distribution.__init__ ().
+    #
+    # It's possible distutils calls out to various keyword
+    # implementations (i.e. distutils.setup_keywords entry points)
+    # that may set a range of variables.
+    #
+    # This wraps distutil's Distribution.__init__ and simulates
+    # pbr or something else setting these values.
+    def _fake_distribution_init(self, dist, attrs):
+        saved_dist_init(dist, attrs)
+        # see self._DISTUTILS_UNSUPPORTED_METADATA
+        dist.metadata.long_description_content_type = 'text/something'
+        # Test overwrite setup() args
+        dist.metadata.project_urls = {
+            'Link One': 'https://example.com/one/',
+            'Link Two': 'https://example.com/two/',
+        }
+
+    @patch.object(_Distribution, '__init__', autospec=True)
+    def test_external_setters(self, mock_parent_init, tmpdir):
+        mock_parent_init.side_effect = self._fake_distribution_init
+
+        dist = Distribution(attrs={'project_urls': {'will_be': 'ignored'}})
+
+        assert dist.metadata.long_description_content_type == 'text/something'
+        assert dist.metadata.project_urls == {
+            'Link One': 'https://example.com/one/',
+            'Link Two': 'https://example.com/two/',
+        }
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/contexts.py b/.venv/lib/python3.12/site-packages/setuptools/tests/contexts.py
new file mode 100644
index 0000000000000000000000000000000000000000..97cceea0e7060c6e3568956e1ba20893301da387
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/tests/contexts.py
@@ -0,0 +1,145 @@
+import contextlib
+import io
+import os
+import shutil
+import site
+import sys
+import tempfile
+
+from filelock import FileLock
+
+
+@contextlib.contextmanager
+def tempdir(cd=lambda dir: None, **kwargs):
+    temp_dir = tempfile.mkdtemp(**kwargs)
+    orig_dir = os.getcwd()
+    try:
+        cd(temp_dir)
+        yield temp_dir
+    finally:
+        cd(orig_dir)
+        shutil.rmtree(temp_dir)
+
+
+@contextlib.contextmanager
+def environment(**replacements):
+    """
+    In a context, patch the environment with replacements. Pass None values
+    to clear the values.
+    """
+    saved = dict((key, os.environ[key]) for key in replacements if key in os.environ)
+
+    # remove values that are null
+    remove = (key for (key, value) in replacements.items() if value is None)
+    for key in list(remove):
+        os.environ.pop(key, None)
+        replacements.pop(key)
+
+    os.environ.update(replacements)
+
+    try:
+        yield saved
+    finally:
+        for key in replacements:
+            os.environ.pop(key, None)
+        os.environ.update(saved)
+
+
+@contextlib.contextmanager
+def quiet():
+    """
+    Redirect stdout/stderr to StringIO objects to prevent console output from
+    distutils commands.
+    """
+
+    old_stdout = sys.stdout
+    old_stderr = sys.stderr
+    new_stdout = sys.stdout = io.StringIO()
+    new_stderr = sys.stderr = io.StringIO()
+    try:
+        yield new_stdout, new_stderr
+    finally:
+        new_stdout.seek(0)
+        new_stderr.seek(0)
+        sys.stdout = old_stdout
+        sys.stderr = old_stderr
+
+
+@contextlib.contextmanager
+def save_user_site_setting():
+    saved = site.ENABLE_USER_SITE
+    try:
+        yield saved
+    finally:
+        site.ENABLE_USER_SITE = saved
+
+
+@contextlib.contextmanager
+def save_pkg_resources_state():
+    import pkg_resources
+
+    pr_state = pkg_resources.__getstate__()
+    # also save sys.path
+    sys_path = sys.path[:]
+    try:
+        yield pr_state, sys_path
+    finally:
+        sys.path[:] = sys_path
+        pkg_resources.__setstate__(pr_state)
+
+
+@contextlib.contextmanager
+def suppress_exceptions(*excs):
+    try:
+        yield
+    except excs:
+        pass
+
+
+def multiproc(request):
+    """
+    Return True if running under xdist and multiple
+    workers are used.
+    """
+    try:
+        worker_id = request.getfixturevalue('worker_id')
+    except Exception:
+        return False
+    return worker_id != 'master'
+
+
+@contextlib.contextmanager
+def session_locked_tmp_dir(request, tmp_path_factory, name):
+    """Uses a file lock to guarantee only one worker can access a temp dir"""
+    # get the temp directory shared by all workers
+    base = tmp_path_factory.getbasetemp()
+    shared_dir = base.parent if multiproc(request) else base
+
+    locked_dir = shared_dir / name
+    with FileLock(locked_dir.with_suffix(".lock")):
+        # ^-- prevent multiple workers to access the directory at once
+        locked_dir.mkdir(exist_ok=True, parents=True)
+        yield locked_dir
+
+
+@contextlib.contextmanager
+def save_paths():
+    """Make sure ``sys.path``, ``sys.meta_path`` and ``sys.path_hooks`` are preserved"""
+    prev = sys.path[:], sys.meta_path[:], sys.path_hooks[:]
+
+    try:
+        yield
+    finally:
+        sys.path, sys.meta_path, sys.path_hooks = prev
+
+
+@contextlib.contextmanager
+def save_sys_modules():
+    """Make sure initial ``sys.modules`` is preserved"""
+    prev_modules = sys.modules
+
+    try:
+        sys.modules = sys.modules.copy()
+        yield
+    finally:
+        sys.modules = prev_modules
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/environment.py b/.venv/lib/python3.12/site-packages/setuptools/tests/environment.py
new file mode 100644
index 0000000000000000000000000000000000000000..ed5499ef7d73762d033a4877bfe586d6c0b82235
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/tests/environment.py
@@ -0,0 +1,95 @@
+import os
+import subprocess
+import sys
+import unicodedata
+from subprocess import PIPE as _PIPE, Popen as _Popen
+
+import jaraco.envs
+
+
+class VirtualEnv(jaraco.envs.VirtualEnv):
+    name = '.env'
+    # Some version of PyPy will import distutils on startup, implicitly
+    # importing setuptools, and thus leading to BackendInvalid errors
+    # when upgrading Setuptools. Bypass this behavior by avoiding the
+    # early availability and need to upgrade.
+    create_opts = ['--no-setuptools']
+
+    def run(self, cmd, *args, **kwargs):
+        cmd = [self.exe(cmd[0])] + cmd[1:]
+        kwargs = {"cwd": self.root, "encoding": "utf-8", **kwargs}  # Allow overriding
+        # In some environments (eg. downstream distro packaging), where:
+        # - tox isn't used to run tests and
+        # - PYTHONPATH is set to point to a specific setuptools codebase and
+        # - no custom env is explicitly set by a test
+        # PYTHONPATH will leak into the spawned processes.
+        # In that case tests look for module in the wrong place (on PYTHONPATH).
+        # Unless the test sets its own special env, pass a copy of the existing
+        # environment with removed PYTHONPATH to the subprocesses.
+        if "env" not in kwargs:
+            env = dict(os.environ)
+            if "PYTHONPATH" in env:
+                del env["PYTHONPATH"]
+            kwargs["env"] = env
+        return subprocess.check_output(cmd, *args, **kwargs)
+
+
+def _which_dirs(cmd):
+    result = set()
+    for path in os.environ.get('PATH', '').split(os.pathsep):
+        filename = os.path.join(path, cmd)
+        if os.access(filename, os.X_OK):
+            result.add(path)
+    return result
+
+
+def run_setup_py(cmd, pypath=None, path=None, data_stream=0, env=None):
+    """
+    Execution command for tests, separate from those used by the
+    code directly to prevent accidental behavior issues
+    """
+    if env is None:
+        env = dict()
+        for envname in os.environ:
+            env[envname] = os.environ[envname]
+
+    # override the python path if needed
+    if pypath is not None:
+        env["PYTHONPATH"] = pypath
+
+    # override the execution path if needed
+    if path is not None:
+        env["PATH"] = path
+    if not env.get("PATH", ""):
+        env["PATH"] = _which_dirs("tar").union(_which_dirs("gzip"))
+        env["PATH"] = os.pathsep.join(env["PATH"])
+
+    cmd = [sys.executable, "setup.py"] + list(cmd)
+
+    # https://bugs.python.org/issue8557
+    shell = sys.platform == 'win32'
+
+    try:
+        proc = _Popen(
+            cmd,
+            stdout=_PIPE,
+            stderr=_PIPE,
+            shell=shell,
+            env=env,
+            encoding="utf-8",
+        )
+
+        if isinstance(data_stream, tuple):
+            data_stream = slice(*data_stream)
+        data = proc.communicate()[data_stream]
+    except OSError:
+        return 1, ''
+
+    # decode the console string if needed
+    if hasattr(data, "decode"):
+        # use the default encoding
+        data = data.decode()
+        data = unicodedata.normalize('NFC', data)
+
+    # communicate calls wait()
+    return proc.returncode, data
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/fixtures.py b/.venv/lib/python3.12/site-packages/setuptools/tests/fixtures.py
new file mode 100644
index 0000000000000000000000000000000000000000..a5472984b5690572285a84575f6c2d598f06dd11
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/tests/fixtures.py
@@ -0,0 +1,157 @@
+import contextlib
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+import path
+import pytest
+
+from . import contexts, environment
+
+
+@pytest.fixture
+def user_override(monkeypatch):
+    """
+    Override site.USER_BASE and site.USER_SITE with temporary directories in
+    a context.
+    """
+    with contexts.tempdir() as user_base:
+        monkeypatch.setattr('site.USER_BASE', user_base)
+        with contexts.tempdir() as user_site:
+            monkeypatch.setattr('site.USER_SITE', user_site)
+            with contexts.save_user_site_setting():
+                yield
+
+
+@pytest.fixture
+def tmpdir_cwd(tmpdir):
+    with tmpdir.as_cwd() as orig:
+        yield orig
+
+
+@pytest.fixture(autouse=True, scope="session")
+def workaround_xdist_376(request):
+    """
+    Workaround pytest-dev/pytest-xdist#376
+
+    ``pytest-xdist`` tends to inject '' into ``sys.path``,
+    which may break certain isolation expectations.
+    Remove the entry so the import
+    machinery behaves the same irrespective of xdist.
+    """
+    if not request.config.pluginmanager.has_plugin('xdist'):
+        return
+
+    with contextlib.suppress(ValueError):
+        sys.path.remove('')
+
+
+@pytest.fixture
+def sample_project(tmp_path):
+    """
+    Clone the 'sampleproject' and return a path to it.
+    """
+    cmd = ['git', 'clone', 'https://github.com/pypa/sampleproject']
+    try:
+        subprocess.check_call(cmd, cwd=str(tmp_path))
+    except Exception:
+        pytest.skip("Unable to clone sampleproject")
+    return tmp_path / 'sampleproject'
+
+
+# sdist and wheel artifacts should be stable across a round of tests
+# so we can build them once per session and use the files as "readonly"
+
+# In the case of setuptools, building the wheel without sdist may cause
+# it to contain the `build` directory, and therefore create situations with
+# `setuptools/build/lib/build/lib/...`. To avoid that, build both artifacts at once.
+
+
+def _build_distributions(tmp_path_factory, request):
+    with contexts.session_locked_tmp_dir(
+        request, tmp_path_factory, "dist_build"
+    ) as tmp:  # pragma: no cover
+        sdist = next(tmp.glob("*.tar.gz"), None)
+        wheel = next(tmp.glob("*.whl"), None)
+        if sdist and wheel:
+            return (sdist, wheel)
+
+        # Sanity check: should not create recursive setuptools/build/lib/build/lib/...
+        assert not Path(request.config.rootdir, "build/lib/build").exists()
+
+        subprocess.check_output([
+            sys.executable,
+            "-m",
+            "build",
+            "--outdir",
+            str(tmp),
+            str(request.config.rootdir),
+        ])
+
+        # Sanity check: should not create recursive setuptools/build/lib/build/lib/...
+        assert not Path(request.config.rootdir, "build/lib/build").exists()
+
+        return next(tmp.glob("*.tar.gz")), next(tmp.glob("*.whl"))
+
+
+@pytest.fixture(scope="session")
+def setuptools_sdist(tmp_path_factory, request):
+    prebuilt = os.getenv("PRE_BUILT_SETUPTOOLS_SDIST")
+    if prebuilt and os.path.exists(prebuilt):  # pragma: no cover
+        return Path(prebuilt).resolve()
+
+    sdist, _ = _build_distributions(tmp_path_factory, request)
+    return sdist
+
+
+@pytest.fixture(scope="session")
+def setuptools_wheel(tmp_path_factory, request):
+    prebuilt = os.getenv("PRE_BUILT_SETUPTOOLS_WHEEL")
+    if prebuilt and os.path.exists(prebuilt):  # pragma: no cover
+        return Path(prebuilt).resolve()
+
+    _, wheel = _build_distributions(tmp_path_factory, request)
+    return wheel
+
+
+@pytest.fixture
+def venv(tmp_path, setuptools_wheel):
+    """Virtual env with the version of setuptools under test installed"""
+    env = environment.VirtualEnv()
+    env.root = path.Path(tmp_path / 'venv')
+    env.create_opts = ['--no-setuptools', '--wheel=bundle']
+    # TODO: Use `--no-wheel` when setuptools implements its own bdist_wheel
+    env.req = str(setuptools_wheel)
+    # In some environments (eg. downstream distro packaging),
+    # where tox isn't used to run tests and PYTHONPATH is set to point to
+    # a specific setuptools codebase, PYTHONPATH will leak into the spawned
+    # processes.
+    # env.create() should install the just created setuptools
+    # wheel, but it doesn't if it finds another existing matching setuptools
+    # installation present on PYTHONPATH:
+    # `setuptools is already installed with the same version as the provided
+    # wheel. Use --force-reinstall to force an installation of the wheel.`
+    # This prevents leaking PYTHONPATH to the created environment.
+    with contexts.environment(PYTHONPATH=None):
+        return env.create()
+
+
+@pytest.fixture
+def venv_without_setuptools(tmp_path):
+    """Virtual env without any version of setuptools installed"""
+    env = environment.VirtualEnv()
+    env.root = path.Path(tmp_path / 'venv_without_setuptools')
+    env.create_opts = ['--no-setuptools', '--no-wheel']
+    env.ensure_env()
+    return env
+
+
+@pytest.fixture
+def bare_venv(tmp_path):
+    """Virtual env without any common packages installed"""
+    env = environment.VirtualEnv()
+    env.root = path.Path(tmp_path / 'bare_venv')
+    env.create_opts = ['--no-setuptools', '--no-pip', '--no-wheel', '--no-seed']
+    env.ensure_env()
+    return env
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/indexes/test_links_priority/external.html b/.venv/lib/python3.12/site-packages/setuptools/tests/indexes/test_links_priority/external.html
new file mode 100644
index 0000000000000000000000000000000000000000..92e4702f634dfb37a404bec3103b76f6afcaa917
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/tests/indexes/test_links_priority/external.html
@@ -0,0 +1,3 @@
+
+bad old link
+
diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/indexes/test_links_priority/simple/foobar/index.html b/.venv/lib/python3.12/site-packages/setuptools/tests/indexes/test_links_priority/simple/foobar/index.html
new file mode 100644
index 0000000000000000000000000000000000000000..fefb028bd3ee7d45a414d6e96a7b2a21ffd7eda7
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/setuptools/tests/indexes/test_links_priority/simple/foobar/index.html
@@ -0,0 +1,4 @@
+
+foobar-0.1.tar.gz
+external homepage
+ diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/integration/__init__.py b/.venv/lib/python3.12/site-packages/setuptools/tests/integration/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/integration/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/integration/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db7426ef914385298a859a62b159f75c81be0764 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/integration/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/integration/__pycache__/helpers.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/integration/__pycache__/helpers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4272ce9ac64a69797cead217ad2da36f6cf883c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/integration/__pycache__/helpers.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/integration/__pycache__/test_pip_install_sdist.cpython-312.pyc b/.venv/lib/python3.12/site-packages/setuptools/tests/integration/__pycache__/test_pip_install_sdist.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d28a08d353a2aa41f6949dcb3e2cd4b197219806 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/setuptools/tests/integration/__pycache__/test_pip_install_sdist.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/integration/helpers.py b/.venv/lib/python3.12/site-packages/setuptools/tests/integration/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..77b196e029b6d2eeb25f0b84a4f7630f65201189 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/integration/helpers.py @@ -0,0 +1,77 @@ +"""Reusable functions and classes for different types of integration tests. + +For example ``Archive`` can be used to check the contents of distribution built +with setuptools, and ``run`` will always try to be as verbose as possible to +facilitate debugging. +""" + +import os +import subprocess +import tarfile +from pathlib import Path +from zipfile import ZipFile + + +def run(cmd, env=None): + r = subprocess.run( + cmd, + capture_output=True, + text=True, + encoding="utf-8", + env={**os.environ, **(env or {})}, + # ^-- allow overwriting instead of discarding the current env + ) + + out = r.stdout + "\n" + r.stderr + # pytest omits stdout/err by default, if the test fails they help debugging + print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") + print(f"Command: {cmd}\nreturn code: {r.returncode}\n\n{out}") + + if r.returncode == 0: + return out + raise subprocess.CalledProcessError(r.returncode, cmd, r.stdout, r.stderr) + + +class Archive: + """Compatibility layer for ZipFile/Info and TarFile/Info""" + + def __init__(self, filename): + self._filename = filename + if filename.endswith("tar.gz"): + self._obj = tarfile.open(filename, "r:gz") + elif filename.endswith("zip"): + self._obj = ZipFile(filename) + else: + raise ValueError(f"{filename} doesn't seem to be a zip or tar.gz") + + def __iter__(self): + if hasattr(self._obj, "infolist"): + return iter(self._obj.infolist()) + return iter(self._obj) + + def get_name(self, zip_or_tar_info): + if hasattr(zip_or_tar_info, "filename"): + return zip_or_tar_info.filename + return zip_or_tar_info.name + + def get_content(self, zip_or_tar_info): + if hasattr(self._obj, "extractfile"): + content = self._obj.extractfile(zip_or_tar_info) + if content is None: + msg = f"Invalid {zip_or_tar_info.name} in {self._filename}" + raise ValueError(msg) + return str(content.read(), "utf-8") + return str(self._obj.read(zip_or_tar_info), "utf-8") + + +def get_sdist_members(sdist_path): + with tarfile.open(sdist_path, "r:gz") as tar: + files = [Path(f) for f in tar.getnames()] + # remove root folder + relative_files = ("/".join(f.parts[1:]) for f in files) + return {f for f in relative_files if f} + + +def get_wheel_members(wheel_path): + with ZipFile(wheel_path) as zipfile: + return set(zipfile.namelist()) diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/integration/test_pip_install_sdist.py b/.venv/lib/python3.12/site-packages/setuptools/tests/integration/test_pip_install_sdist.py new file mode 100644 index 0000000000000000000000000000000000000000..4e84f218323e6ad67adfbce07cea5a16e91a311c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/integration/test_pip_install_sdist.py @@ -0,0 +1,223 @@ +# https://github.com/python/mypy/issues/16936 +# mypy: disable-error-code="has-type" +"""Integration tests for setuptools that focus on building packages via pip. + +The idea behind these tests is not to exhaustively check all the possible +combinations of packages, operating systems, supporting libraries, etc, but +rather check a limited number of popular packages and how they interact with +the exposed public API. This way if any change in API is introduced, we hope to +identify backward compatibility problems before publishing a release. + +The number of tested packages is purposefully kept small, to minimise duration +and the associated maintenance cost (changes in the way these packages define +their build process may require changes in the tests). +""" + +import json +import os +import shutil +import sys +from enum import Enum +from glob import glob +from hashlib import md5 +from urllib.request import urlopen + +import pytest +from packaging.requirements import Requirement + +from .helpers import Archive, run + +pytestmark = pytest.mark.integration + + +(LATEST,) = Enum("v", "LATEST") # type: ignore[misc] # https://github.com/python/mypy/issues/16936 +"""Default version to be checked""" +# There are positive and negative aspects of checking the latest version of the +# packages. +# The main positive aspect is that the latest version might have already +# removed the use of APIs deprecated in previous releases of setuptools. + + +# Packages to be tested: +# (Please notice the test environment cannot support EVERY library required for +# compiling binary extensions. In Ubuntu/Debian nomenclature, we only assume +# that `build-essential`, `gfortran` and `libopenblas-dev` are installed, +# due to their relevance to the numerical/scientific programming ecosystem) +EXAMPLES = [ + ("pip", LATEST), # just in case... + ("pytest", LATEST), # uses setuptools_scm + ("mypy", LATEST), # custom build_py + ext_modules + # --- Popular packages: https://hugovk.github.io/top-pypi-packages/ --- + ("botocore", LATEST), + ("kiwisolver", LATEST), # build_ext + ("brotli", LATEST), # not in the list but used by urllib3 + ("pyyaml", LATEST), # cython + custom build_ext + custom distclass + ("charset-normalizer", LATEST), # uses mypyc, used by aiohttp + ("protobuf", LATEST), + # ("requests", LATEST), # XXX: https://github.com/psf/requests/pull/6920 + ("celery", LATEST), + # When adding packages to this list, make sure they expose a `__version__` + # attribute, or modify the tests below +] + + +# Some packages have "optional" dependencies that modify their build behaviour +# and are not listed in pyproject.toml, others still use `setup_requires` +EXTRA_BUILD_DEPS = { + "pyyaml": ("Cython<3.0",), # constraint to avoid errors + "charset-normalizer": ("mypy>=1.4.1",), # no pyproject.toml available +} + +EXTRA_ENV_VARS = { + "pyyaml": {"PYYAML_FORCE_CYTHON": "1"}, + "charset-normalizer": {"CHARSET_NORMALIZER_USE_MYPYC": "1"}, +} + +IMPORT_NAME = { + "pyyaml": "yaml", + "protobuf": "google.protobuf", +} + + +VIRTUALENV = (sys.executable, "-m", "virtualenv") + + +# By default, pip will try to build packages in isolation (PEP 517), which +# means it will download the previous stable version of setuptools. +# `pip` flags can avoid that (the version of setuptools under test +# should be the one to be used) +INSTALL_OPTIONS = ( + "--ignore-installed", + "--no-build-isolation", + # Omit "--no-binary :all:" the sdist is supplied directly. + # Allows dependencies as wheels. +) +# The downside of `--no-build-isolation` is that pip will not download build +# dependencies. The test script will have to also handle that. + + +@pytest.fixture +def venv_python(tmp_path): + run([*VIRTUALENV, str(tmp_path / ".venv")]) + possible_path = (str(p.parent) for p in tmp_path.glob(".venv/*/python*")) + return shutil.which("python", path=os.pathsep.join(possible_path)) + + +@pytest.fixture(autouse=True) +def _prepare(tmp_path, venv_python, monkeypatch): + download_path = os.getenv("DOWNLOAD_PATH", str(tmp_path)) + os.makedirs(download_path, exist_ok=True) + + # Environment vars used for building some of the packages + monkeypatch.setenv("USE_MYPYC", "1") + + yield + + # Let's provide the maximum amount of information possible in the case + # it is necessary to debug the tests directly from the CI logs. + print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") + print("Temporary directory:") + map(print, tmp_path.glob("*")) + print("Virtual environment:") + run([venv_python, "-m", "pip", "freeze"]) + + +@pytest.mark.parametrize(("package", "version"), EXAMPLES) +@pytest.mark.uses_network +def test_install_sdist(package, version, tmp_path, venv_python, setuptools_wheel): + venv_pip = (venv_python, "-m", "pip") + sdist = retrieve_sdist(package, version, tmp_path) + deps = build_deps(package, sdist) + if deps: + print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") + print("Dependencies:", deps) + run([*venv_pip, "install", *deps]) + + # Use a virtualenv to simulate PEP 517 isolation + # but install fresh setuptools wheel to ensure the version under development + env = EXTRA_ENV_VARS.get(package, {}) + run([*venv_pip, "install", "--force-reinstall", setuptools_wheel]) + run([*venv_pip, "install", *INSTALL_OPTIONS, sdist], env) + + # Execute a simple script to make sure the package was installed correctly + pkg = IMPORT_NAME.get(package, package).replace("-", "_") + script = f"import {pkg}; print(getattr({pkg}, '__version__', 0))" + run([venv_python, "-c", script]) + + +# ---- Helper Functions ---- + + +def retrieve_sdist(package, version, tmp_path): + """Either use cached sdist file or download it from PyPI""" + # `pip download` cannot be used due to + # https://github.com/pypa/pip/issues/1884 + # https://discuss.python.org/t/pep-625-file-name-of-a-source-distribution/4686 + # We have to find the correct distribution file and download it + download_path = os.getenv("DOWNLOAD_PATH", str(tmp_path)) + dist = retrieve_pypi_sdist_metadata(package, version) + + # Remove old files to prevent cache to grow indefinitely + for file in glob(os.path.join(download_path, f"{package}*")): + if dist["filename"] != file: + os.unlink(file) + + dist_file = os.path.join(download_path, dist["filename"]) + if not os.path.exists(dist_file): + download(dist["url"], dist_file, dist["md5_digest"]) + return dist_file + + +def retrieve_pypi_sdist_metadata(package, version): + # https://warehouse.pypa.io/api-reference/json.html + id_ = package if version is LATEST else f"{package}/{version}" + with urlopen(f"https://pypi.org/pypi/{id_}/json") as f: + metadata = json.load(f) + + if metadata["info"]["yanked"]: + raise ValueError(f"Release for {package} {version} was yanked") + + version = metadata["info"]["version"] + release = metadata["releases"][version] if version is LATEST else metadata["urls"] + (sdist,) = filter(lambda d: d["packagetype"] == "sdist", release) + return sdist + + +def download(url, dest, md5_digest): + with urlopen(url) as f: + data = f.read() + + assert md5(data).hexdigest() == md5_digest + + with open(dest, "wb") as f: + f.write(data) + + assert os.path.exists(dest) + + +def build_deps(package, sdist_file): + """Find out what are the build dependencies for a package. + + "Manually" install them, since pip will not install build + deps with `--no-build-isolation`. + """ + # delay importing, since pytest discovery phase may hit this file from a + # testenv without tomli + from setuptools.compat.py310 import tomllib + + archive = Archive(sdist_file) + info = tomllib.loads(_read_pyproject(archive)) + deps = info.get("build-system", {}).get("requires", []) + deps += EXTRA_BUILD_DEPS.get(package, []) + # Remove setuptools from requirements (and deduplicate) + requirements = {Requirement(d).name: d for d in deps} + return [v for k, v in requirements.items() if k != "setuptools"] + + +def _read_pyproject(archive): + contents = ( + archive.get_content(member) + for member in archive + if os.path.basename(archive.get_name(member)) == "pyproject.toml" + ) + return next(contents, "") diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/mod_with_constant.py b/.venv/lib/python3.12/site-packages/setuptools/tests/mod_with_constant.py new file mode 100644 index 0000000000000000000000000000000000000000..ef755dd1c7a8d1f116fe51f1b43315057f03379d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/mod_with_constant.py @@ -0,0 +1 @@ +value = 'three, sir!' diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/namespaces.py b/.venv/lib/python3.12/site-packages/setuptools/tests/namespaces.py new file mode 100644 index 0000000000000000000000000000000000000000..248db98f97951aeeee0222131417e73074cc72d2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/namespaces.py @@ -0,0 +1,90 @@ +import ast +import json +import textwrap +from pathlib import Path + + +def iter_namespace_pkgs(namespace): + parts = namespace.split(".") + for i in range(len(parts)): + yield ".".join(parts[: i + 1]) + + +def build_namespace_package(tmpdir, name, version="1.0", impl="pkg_resources"): + src_dir = tmpdir / name + src_dir.mkdir() + setup_py = src_dir / 'setup.py' + namespace, _, rest = name.rpartition('.') + namespaces = list(iter_namespace_pkgs(namespace)) + setup_args = { + "name": name, + "version": version, + "packages": namespaces, + } + + if impl == "pkg_resources": + tmpl = '__import__("pkg_resources").declare_namespace(__name__)' + setup_args["namespace_packages"] = namespaces + elif impl == "pkgutil": + tmpl = '__path__ = __import__("pkgutil").extend_path(__path__, __name__)' + else: + raise ValueError(f"Cannot recognise {impl=} when creating namespaces") + + args = json.dumps(setup_args, indent=4) + assert ast.literal_eval(args) # ensure it is valid Python + + script = textwrap.dedent( + """\ + import setuptools + args = {args} + setuptools.setup(**args) + """ + ).format(args=args) + setup_py.write_text(script, encoding='utf-8') + + ns_pkg_dir = Path(src_dir, namespace.replace(".", "/")) + ns_pkg_dir.mkdir(parents=True) + + for ns in namespaces: + pkg_init = src_dir / ns.replace(".", "/") / '__init__.py' + pkg_init.write_text(tmpl, encoding='utf-8') + + pkg_mod = ns_pkg_dir / (rest + '.py') + some_functionality = 'name = {rest!r}'.format(**locals()) + pkg_mod.write_text(some_functionality, encoding='utf-8') + return src_dir + + +def build_pep420_namespace_package(tmpdir, name): + src_dir = tmpdir / name + src_dir.mkdir() + pyproject = src_dir / "pyproject.toml" + namespace, _, rest = name.rpartition(".") + script = f"""\ + [build-system] + requires = ["setuptools"] + build-backend = "setuptools.build_meta" + + [project] + name = "{name}" + version = "3.14159" + """ + pyproject.write_text(textwrap.dedent(script), encoding='utf-8') + ns_pkg_dir = Path(src_dir, namespace.replace(".", "/")) + ns_pkg_dir.mkdir(parents=True) + pkg_mod = ns_pkg_dir / (rest + ".py") + some_functionality = f"name = {rest!r}" + pkg_mod.write_text(some_functionality, encoding='utf-8') + return src_dir + + +def make_site_dir(target): + """ + Add a sitecustomize.py module in target to cause + target to be added to site dirs such that .pth files + are processed there. + """ + sc = target / 'sitecustomize.py' + target_str = str(target) + tmpl = '__import__("site").addsitedir({target_str!r})' + sc.write_text(tmpl.format(**locals()), encoding='utf-8') diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/script-with-bom.py b/.venv/lib/python3.12/site-packages/setuptools/tests/script-with-bom.py new file mode 100644 index 0000000000000000000000000000000000000000..c074d263c45bcaebe32fdba328d975c73d1ad5ca --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/script-with-bom.py @@ -0,0 +1 @@ +result = 'passed' diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/server.py b/.venv/lib/python3.12/site-packages/setuptools/tests/server.py new file mode 100644 index 0000000000000000000000000000000000000000..623a49a550f161f117d3af2173f91a2af260181d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/server.py @@ -0,0 +1,86 @@ +"""Basic http server for tests to simulate PyPI or custom indexes""" + +import http.server +import os +import threading +import time +import urllib.parse +import urllib.request + + +class IndexServer(http.server.HTTPServer): + """Basic single-threaded http server simulating a package index + + You can use this server in unittest like this:: + s = IndexServer() + s.start() + index_url = s.base_url() + 'mytestindex' + # do some test requests to the index + # The index files should be located in setuptools/tests/indexes + s.stop() + """ + + def __init__( + self, + server_address=('', 0), + RequestHandlerClass=http.server.SimpleHTTPRequestHandler, + ): + http.server.HTTPServer.__init__(self, server_address, RequestHandlerClass) + self._run = True + + def start(self): + self.thread = threading.Thread(target=self.serve_forever) + self.thread.start() + + def stop(self): + "Stop the server" + + # Let the server finish the last request and wait for a new one. + time.sleep(0.1) + + self.shutdown() + self.thread.join() + self.socket.close() + + def base_url(self): + port = self.server_port + return f'http://127.0.0.1:{port}/setuptools/tests/indexes/' + + +class RequestRecorder(http.server.BaseHTTPRequestHandler): + def do_GET(self): + requests = vars(self.server).setdefault('requests', []) + requests.append(self) + self.send_response(200, 'OK') + + +class MockServer(http.server.HTTPServer, threading.Thread): + """ + A simple HTTP Server that records the requests made to it. + """ + + def __init__(self, server_address=('', 0), RequestHandlerClass=RequestRecorder): + http.server.HTTPServer.__init__(self, server_address, RequestHandlerClass) + threading.Thread.__init__(self) + self.daemon = True + self.requests = [] + + def run(self): + self.serve_forever() + + @property + def netloc(self): + return f'localhost:{self.server_port}' + + @property + def url(self): + return f'http://{self.netloc}/' + + +def path_to_url(path, authority=None): + """Convert a path to a file: URL.""" + path = os.path.normpath(os.path.abspath(path)) + base = 'file:' + if authority is not None: + base += '//' + authority + return urllib.parse.urljoin(base, urllib.request.pathname2url(path)) diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/test_archive_util.py b/.venv/lib/python3.12/site-packages/setuptools/tests/test_archive_util.py new file mode 100644 index 0000000000000000000000000000000000000000..e3efc62889994fa68bc9170e8a0e403f48a204e1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/test_archive_util.py @@ -0,0 +1,36 @@ +import io +import tarfile + +import pytest + +from setuptools import archive_util + + +@pytest.fixture +def tarfile_with_unicode(tmpdir): + """ + Create a tarfile containing only a file whose name is + a zero byte file called testimäge.png. + """ + tarobj = io.BytesIO() + + with tarfile.open(fileobj=tarobj, mode="w:gz") as tgz: + data = b"" + + filename = "testimäge.png" + + t = tarfile.TarInfo(filename) + t.size = len(data) + + tgz.addfile(t, io.BytesIO(data)) + + target = tmpdir / 'unicode-pkg-1.0.tar.gz' + with open(str(target), mode='wb') as tf: + tf.write(tarobj.getvalue()) + return str(target) + + +@pytest.mark.xfail(reason="#710 and #712") +def test_unicode_files(tarfile_with_unicode, tmpdir): + target = tmpdir / 'out' + archive_util.unpack_archive(tarfile_with_unicode, str(target)) diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/test_bdist_deprecations.py b/.venv/lib/python3.12/site-packages/setuptools/tests/test_bdist_deprecations.py new file mode 100644 index 0000000000000000000000000000000000000000..d9d67b06161a2b36e7b15fab09f797c5c15575c2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/test_bdist_deprecations.py @@ -0,0 +1,28 @@ +"""develop tests""" + +import sys +from unittest import mock + +import pytest + +from setuptools import SetuptoolsDeprecationWarning +from setuptools.dist import Distribution + + +@pytest.mark.skipif(sys.platform == 'win32', reason='non-Windows only') +@pytest.mark.xfail(reason="bdist_rpm is long deprecated, should we remove it? #1988") +@mock.patch('distutils.command.bdist_rpm.bdist_rpm') +def test_bdist_rpm_warning(distutils_cmd, tmpdir_cwd): + dist = Distribution( + dict( + script_name='setup.py', + script_args=['bdist_rpm'], + name='foo', + py_modules=['hi'], + ) + ) + dist.parse_command_line() + with pytest.warns(SetuptoolsDeprecationWarning): + dist.run_commands() + + distutils_cmd.run.assert_called_once() diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/test_bdist_egg.py b/.venv/lib/python3.12/site-packages/setuptools/tests/test_bdist_egg.py new file mode 100644 index 0000000000000000000000000000000000000000..036167dd951e70ad543775529d5ce3f6d6544c71 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/test_bdist_egg.py @@ -0,0 +1,73 @@ +"""develop tests""" + +import os +import re +import zipfile + +import pytest + +from setuptools.dist import Distribution + +from . import contexts + +SETUP_PY = """\ +from setuptools import setup + +setup(py_modules=['hi']) +""" + + +@pytest.fixture +def setup_context(tmpdir): + with (tmpdir / 'setup.py').open('w') as f: + f.write(SETUP_PY) + with (tmpdir / 'hi.py').open('w') as f: + f.write('1\n') + with tmpdir.as_cwd(): + yield tmpdir + + +class Test: + @pytest.mark.usefixtures("user_override") + @pytest.mark.usefixtures("setup_context") + def test_bdist_egg(self): + dist = Distribution( + dict( + script_name='setup.py', + script_args=['bdist_egg'], + name='foo', + py_modules=['hi'], + ) + ) + os.makedirs(os.path.join('build', 'src')) + with contexts.quiet(): + dist.parse_command_line() + dist.run_commands() + + # let's see if we got our egg link at the right place + [content] = os.listdir('dist') + assert re.match(r'foo-0.0.0-py[23].\d+.egg$', content) + + @pytest.mark.xfail( + os.environ.get('PYTHONDONTWRITEBYTECODE', False), + reason="Byte code disabled", + ) + @pytest.mark.usefixtures("user_override") + @pytest.mark.usefixtures("setup_context") + def test_exclude_source_files(self): + dist = Distribution( + dict( + script_name='setup.py', + script_args=['bdist_egg', '--exclude-source-files'], + py_modules=['hi'], + ) + ) + with contexts.quiet(): + dist.parse_command_line() + dist.run_commands() + [dist_name] = os.listdir('dist') + dist_filename = os.path.join('dist', dist_name) + zip = zipfile.ZipFile(dist_filename) + names = list(zi.filename for zi in zip.filelist) + assert 'hi.pyc' in names + assert 'hi.py' not in names diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/test_bdist_wheel.py b/.venv/lib/python3.12/site-packages/setuptools/tests/test_bdist_wheel.py new file mode 100644 index 0000000000000000000000000000000000000000..2ab4e9cfc6cf0d930b3ceeececcce10cfe91a687 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/test_bdist_wheel.py @@ -0,0 +1,708 @@ +from __future__ import annotations + +import builtins +import importlib +import os.path +import platform +import shutil +import stat +import struct +import sys +import sysconfig +from contextlib import suppress +from inspect import cleandoc +from zipfile import ZipFile + +import jaraco.path +import pytest +from packaging import tags + +import setuptools +from setuptools.command.bdist_wheel import bdist_wheel, get_abi_tag +from setuptools.dist import Distribution +from setuptools.warnings import SetuptoolsDeprecationWarning + +from distutils.core import run_setup + +DEFAULT_FILES = { + "dummy_dist-1.0.dist-info/top_level.txt", + "dummy_dist-1.0.dist-info/METADATA", + "dummy_dist-1.0.dist-info/WHEEL", + "dummy_dist-1.0.dist-info/RECORD", +} +DEFAULT_LICENSE_FILES = { + "LICENSE", + "LICENSE.txt", + "LICENCE", + "LICENCE.txt", + "COPYING", + "COPYING.md", + "NOTICE", + "NOTICE.rst", + "AUTHORS", + "AUTHORS.txt", +} +OTHER_IGNORED_FILES = { + "LICENSE~", + "AUTHORS~", +} +SETUPPY_EXAMPLE = """\ +from setuptools import setup + +setup( + name='dummy_dist', + version='1.0', +) +""" + + +EXAMPLES = { + "dummy-dist": { + "setup.py": SETUPPY_EXAMPLE, + "licenses_dir": {"DUMMYFILE": ""}, + **dict.fromkeys(DEFAULT_LICENSE_FILES | OTHER_IGNORED_FILES, ""), + }, + "simple-dist": { + "setup.py": cleandoc( + """ + from setuptools import setup + + setup( + name="simple.dist", + version="0.1", + description="A testing distribution \N{SNOWMAN}", + extras_require={"voting": ["beaglevote"]}, + ) + """ + ), + "simpledist": "", + }, + "complex-dist": { + "setup.py": cleandoc( + """ + from setuptools import setup + + setup( + name="complex-dist", + version="0.1", + description="Another testing distribution \N{SNOWMAN}", + long_description="Another testing distribution \N{SNOWMAN}", + author="Illustrious Author", + author_email="illustrious@example.org", + url="http://example.org/exemplary", + packages=["complexdist"], + setup_requires=["setuptools"], + install_requires=["quux", "splort"], + extras_require={"simple": ["simple.dist"]}, + entry_points={ + "console_scripts": [ + "complex-dist=complexdist:main", + "complex-dist2=complexdist:main", + ], + }, + ) + """ + ), + "complexdist": {"__init__.py": "def main(): return"}, + }, + "headers-dist": { + "setup.py": cleandoc( + """ + from setuptools import setup + + setup( + name="headers.dist", + version="0.1", + description="A distribution with headers", + headers=["header.h"], + ) + """ + ), + "headersdist.py": "", + "header.h": "", + }, + "commasinfilenames-dist": { + "setup.py": cleandoc( + """ + from setuptools import setup + + setup( + name="testrepo", + version="0.1", + packages=["mypackage"], + description="A test package with commas in file names", + include_package_data=True, + package_data={"mypackage.data": ["*"]}, + ) + """ + ), + "mypackage": { + "__init__.py": "", + "data": {"__init__.py": "", "1,2,3.txt": ""}, + }, + "testrepo-0.1.0": { + "mypackage": {"__init__.py": ""}, + }, + }, + "unicode-dist": { + "setup.py": cleandoc( + """ + from setuptools import setup + + setup( + name="unicode.dist", + version="0.1", + description="A testing distribution \N{SNOWMAN}", + packages=["unicodedist"], + zip_safe=True, + ) + """ + ), + "unicodedist": {"__init__.py": "", "åäö_日本語.py": ""}, + }, + "utf8-metadata-dist": { + "setup.cfg": cleandoc( + """ + [metadata] + name = utf8-metadata-dist + version = 42 + author_email = "John X. Ãørçeč" , Γαμα קּ 東 + long_description = file: README.rst + """ + ), + "README.rst": "UTF-8 描述 説明", + }, + "licenses-dist": { + "setup.cfg": cleandoc( + """ + [metadata] + name = licenses-dist + version = 1.0 + license_files = **/LICENSE + """ + ), + "LICENSE": "", + "src": { + "vendor": {"LICENSE": ""}, + }, + }, +} + + +if sys.platform != "win32": + # ABI3 extensions don't really work on Windows + EXAMPLES["abi3extension-dist"] = { + "setup.py": cleandoc( + """ + from setuptools import Extension, setup + + setup( + name="extension.dist", + version="0.1", + description="A testing distribution \N{SNOWMAN}", + ext_modules=[ + Extension( + name="extension", sources=["extension.c"], py_limited_api=True + ) + ], + ) + """ + ), + "setup.cfg": "[bdist_wheel]\npy_limited_api=cp32", + "extension.c": "#define Py_LIMITED_API 0x03020000\n#include ", + } + + +def bdist_wheel_cmd(**kwargs): + """Run command in the same process so that it is easier to collect coverage""" + dist_obj = ( + run_setup("setup.py", stop_after="init") + if os.path.exists("setup.py") + else Distribution({"script_name": "%%build_meta%%"}) + ) + dist_obj.parse_config_files() + cmd = bdist_wheel(dist_obj) + for attr, value in kwargs.items(): + setattr(cmd, attr, value) + cmd.finalize_options() + return cmd + + +def mkexample(tmp_path_factory, name): + basedir = tmp_path_factory.mktemp(name) + jaraco.path.build(EXAMPLES[name], prefix=str(basedir)) + return basedir + + +@pytest.fixture(scope="session") +def wheel_paths(tmp_path_factory): + build_base = tmp_path_factory.mktemp("build") + dist_dir = tmp_path_factory.mktemp("dist") + for name in EXAMPLES: + example_dir = mkexample(tmp_path_factory, name) + build_dir = build_base / name + with jaraco.path.DirectoryStack().context(example_dir): + bdist_wheel_cmd(bdist_dir=str(build_dir), dist_dir=str(dist_dir)).run() + + return sorted(str(fname) for fname in dist_dir.glob("*.whl")) + + +@pytest.fixture +def dummy_dist(tmp_path_factory): + return mkexample(tmp_path_factory, "dummy-dist") + + +@pytest.fixture +def licenses_dist(tmp_path_factory): + return mkexample(tmp_path_factory, "licenses-dist") + + +def test_no_scripts(wheel_paths): + """Make sure entry point scripts are not generated.""" + path = next(path for path in wheel_paths if "complex_dist" in path) + for entry in ZipFile(path).infolist(): + assert ".data/scripts/" not in entry.filename + + +def test_unicode_record(wheel_paths): + path = next(path for path in wheel_paths if "unicode_dist" in path) + with ZipFile(path) as zf: + record = zf.read("unicode_dist-0.1.dist-info/RECORD") + + assert "åäö_日本語.py".encode() in record + + +UTF8_PKG_INFO = """\ +Metadata-Version: 2.1 +Name: helloworld +Version: 42 +Author-email: "John X. Ãørçeč" , Γαμα קּ 東 + + +UTF-8 描述 説明 +""" + + +def test_preserve_unicode_metadata(monkeypatch, tmp_path): + monkeypatch.chdir(tmp_path) + egginfo = tmp_path / "dummy_dist.egg-info" + distinfo = tmp_path / "dummy_dist.dist-info" + + egginfo.mkdir() + (egginfo / "PKG-INFO").write_text(UTF8_PKG_INFO, encoding="utf-8") + (egginfo / "dependency_links.txt").touch() + + class simpler_bdist_wheel(bdist_wheel): + """Avoid messing with setuptools/distutils internals""" + + def __init__(self): + pass + + @property + def license_paths(self): + return [] + + cmd_obj = simpler_bdist_wheel() + cmd_obj.egg2dist(egginfo, distinfo) + + metadata = (distinfo / "METADATA").read_text(encoding="utf-8") + assert 'Author-email: "John X. Ãørçeč"' in metadata + assert "Γαμα קּ 東 " in metadata + assert "UTF-8 描述 説明" in metadata + + +def test_licenses_default(dummy_dist, monkeypatch, tmp_path): + monkeypatch.chdir(dummy_dist) + bdist_wheel_cmd(bdist_dir=str(tmp_path)).run() + with ZipFile("dist/dummy_dist-1.0-py3-none-any.whl") as wf: + license_files = { + "dummy_dist-1.0.dist-info/licenses/" + fname + for fname in DEFAULT_LICENSE_FILES + } + assert set(wf.namelist()) == DEFAULT_FILES | license_files + + +def test_licenses_deprecated(dummy_dist, monkeypatch, tmp_path): + dummy_dist.joinpath("setup.cfg").write_text( + "[metadata]\nlicense_file=licenses_dir/DUMMYFILE", encoding="utf-8" + ) + monkeypatch.chdir(dummy_dist) + + bdist_wheel_cmd(bdist_dir=str(tmp_path)).run() + + with ZipFile("dist/dummy_dist-1.0-py3-none-any.whl") as wf: + license_files = {"dummy_dist-1.0.dist-info/licenses/licenses_dir/DUMMYFILE"} + assert set(wf.namelist()) == DEFAULT_FILES | license_files + + +@pytest.mark.parametrize( + ("config_file", "config"), + [ + ("setup.cfg", "[metadata]\nlicense_files=licenses_dir/*\n LICENSE"), + ("setup.cfg", "[metadata]\nlicense_files=licenses_dir/*, LICENSE"), + ( + "setup.py", + SETUPPY_EXAMPLE.replace( + ")", " license_files=['licenses_dir/DUMMYFILE', 'LICENSE'])" + ), + ), + ], +) +def test_licenses_override(dummy_dist, monkeypatch, tmp_path, config_file, config): + dummy_dist.joinpath(config_file).write_text(config, encoding="utf-8") + monkeypatch.chdir(dummy_dist) + bdist_wheel_cmd(bdist_dir=str(tmp_path)).run() + with ZipFile("dist/dummy_dist-1.0-py3-none-any.whl") as wf: + license_files = { + "dummy_dist-1.0.dist-info/licenses/" + fname + for fname in {"licenses_dir/DUMMYFILE", "LICENSE"} + } + assert set(wf.namelist()) == DEFAULT_FILES | license_files + metadata = wf.read("dummy_dist-1.0.dist-info/METADATA").decode("utf8") + assert "License-File: licenses_dir/DUMMYFILE" in metadata + assert "License-File: LICENSE" in metadata + + +def test_licenses_preserve_folder_structure(licenses_dist, monkeypatch, tmp_path): + monkeypatch.chdir(licenses_dist) + bdist_wheel_cmd(bdist_dir=str(tmp_path)).run() + print(os.listdir("dist")) + with ZipFile("dist/licenses_dist-1.0-py3-none-any.whl") as wf: + default_files = {name.replace("dummy_", "licenses_") for name in DEFAULT_FILES} + license_files = { + "licenses_dist-1.0.dist-info/licenses/LICENSE", + "licenses_dist-1.0.dist-info/licenses/src/vendor/LICENSE", + } + assert set(wf.namelist()) == default_files | license_files + metadata = wf.read("licenses_dist-1.0.dist-info/METADATA").decode("utf8") + assert "License-File: src/vendor/LICENSE" in metadata + assert "License-File: LICENSE" in metadata + + +def test_licenses_disabled(dummy_dist, monkeypatch, tmp_path): + dummy_dist.joinpath("setup.cfg").write_text( + "[metadata]\nlicense_files=\n", encoding="utf-8" + ) + monkeypatch.chdir(dummy_dist) + bdist_wheel_cmd(bdist_dir=str(tmp_path)).run() + with ZipFile("dist/dummy_dist-1.0-py3-none-any.whl") as wf: + assert set(wf.namelist()) == DEFAULT_FILES + + +def test_build_number(dummy_dist, monkeypatch, tmp_path): + monkeypatch.chdir(dummy_dist) + bdist_wheel_cmd(bdist_dir=str(tmp_path), build_number="2").run() + with ZipFile("dist/dummy_dist-1.0-2-py3-none-any.whl") as wf: + filenames = set(wf.namelist()) + assert "dummy_dist-1.0.dist-info/RECORD" in filenames + assert "dummy_dist-1.0.dist-info/METADATA" in filenames + + +def test_universal_deprecated(dummy_dist, monkeypatch, tmp_path): + monkeypatch.chdir(dummy_dist) + with pytest.warns(SetuptoolsDeprecationWarning, match=".*universal is deprecated"): + bdist_wheel_cmd(bdist_dir=str(tmp_path), universal=True).run() + + # For now we still respect the option + assert os.path.exists("dist/dummy_dist-1.0-py2.py3-none-any.whl") + + +EXTENSION_EXAMPLE = """\ +#include + +static PyMethodDef methods[] = { + { NULL, NULL, 0, NULL } +}; + +static struct PyModuleDef module_def = { + PyModuleDef_HEAD_INIT, + "extension", + "Dummy extension module", + -1, + methods +}; + +PyMODINIT_FUNC PyInit_extension(void) { + return PyModule_Create(&module_def); +} +""" +EXTENSION_SETUPPY = """\ +from __future__ import annotations + +from setuptools import Extension, setup + +setup( + name="extension.dist", + version="0.1", + description="A testing distribution \N{SNOWMAN}", + ext_modules=[Extension(name="extension", sources=["extension.c"])], +) +""" + + +@pytest.mark.filterwarnings( + "once:Config variable '.*' is unset.*, Python ABI tag may be incorrect" +) +def test_limited_abi(monkeypatch, tmp_path, tmp_path_factory): + """Test that building a binary wheel with the limited ABI works.""" + source_dir = tmp_path_factory.mktemp("extension_dist") + (source_dir / "setup.py").write_text(EXTENSION_SETUPPY, encoding="utf-8") + (source_dir / "extension.c").write_text(EXTENSION_EXAMPLE, encoding="utf-8") + build_dir = tmp_path.joinpath("build") + dist_dir = tmp_path.joinpath("dist") + monkeypatch.chdir(source_dir) + bdist_wheel_cmd(bdist_dir=str(build_dir), dist_dir=str(dist_dir)).run() + + +def test_build_from_readonly_tree(dummy_dist, monkeypatch, tmp_path): + basedir = str(tmp_path.joinpath("dummy")) + shutil.copytree(str(dummy_dist), basedir) + monkeypatch.chdir(basedir) + + # Make the tree read-only + for root, _dirs, files in os.walk(basedir): + for fname in files: + os.chmod(os.path.join(root, fname), stat.S_IREAD) + + bdist_wheel_cmd().run() + + +@pytest.mark.parametrize( + ("option", "compress_type"), + list(bdist_wheel.supported_compressions.items()), + ids=list(bdist_wheel.supported_compressions), +) +def test_compression(dummy_dist, monkeypatch, tmp_path, option, compress_type): + monkeypatch.chdir(dummy_dist) + bdist_wheel_cmd(bdist_dir=str(tmp_path), compression=option).run() + with ZipFile("dist/dummy_dist-1.0-py3-none-any.whl") as wf: + filenames = set(wf.namelist()) + assert "dummy_dist-1.0.dist-info/RECORD" in filenames + assert "dummy_dist-1.0.dist-info/METADATA" in filenames + for zinfo in wf.filelist: + assert zinfo.compress_type == compress_type + + +def test_wheelfile_line_endings(wheel_paths): + for path in wheel_paths: + with ZipFile(path) as wf: + wheelfile = next(fn for fn in wf.filelist if fn.filename.endswith("WHEEL")) + wheelfile_contents = wf.read(wheelfile) + assert b"\r" not in wheelfile_contents + + +def test_unix_epoch_timestamps(dummy_dist, monkeypatch, tmp_path): + monkeypatch.setenv("SOURCE_DATE_EPOCH", "0") + monkeypatch.chdir(dummy_dist) + bdist_wheel_cmd(bdist_dir=str(tmp_path), build_number="2a").run() + with ZipFile("dist/dummy_dist-1.0-2a-py3-none-any.whl") as wf: + for zinfo in wf.filelist: + assert zinfo.date_time >= (1980, 1, 1, 0, 0, 0) # min epoch is used + + +def test_get_abi_tag_windows(monkeypatch): + monkeypatch.setattr(tags, "interpreter_name", lambda: "cp") + monkeypatch.setattr(sysconfig, "get_config_var", lambda x: "cp313-win_amd64") + assert get_abi_tag() == "cp313" + monkeypatch.setattr(sys, "gettotalrefcount", lambda: 1, False) + assert get_abi_tag() == "cp313d" + monkeypatch.setattr(sysconfig, "get_config_var", lambda x: "cp313t-win_amd64") + assert get_abi_tag() == "cp313td" + monkeypatch.delattr(sys, "gettotalrefcount") + assert get_abi_tag() == "cp313t" + + +def test_get_abi_tag_pypy_old(monkeypatch): + monkeypatch.setattr(tags, "interpreter_name", lambda: "pp") + monkeypatch.setattr(sysconfig, "get_config_var", lambda x: "pypy36-pp73") + assert get_abi_tag() == "pypy36_pp73" + + +def test_get_abi_tag_pypy_new(monkeypatch): + monkeypatch.setattr(sysconfig, "get_config_var", lambda x: "pypy37-pp73-darwin") + monkeypatch.setattr(tags, "interpreter_name", lambda: "pp") + assert get_abi_tag() == "pypy37_pp73" + + +def test_get_abi_tag_graalpy(monkeypatch): + monkeypatch.setattr( + sysconfig, "get_config_var", lambda x: "graalpy231-310-native-x86_64-linux" + ) + monkeypatch.setattr(tags, "interpreter_name", lambda: "graalpy") + assert get_abi_tag() == "graalpy231_310_native" + + +def test_get_abi_tag_fallback(monkeypatch): + monkeypatch.setattr(sysconfig, "get_config_var", lambda x: "unknown-python-310") + monkeypatch.setattr(tags, "interpreter_name", lambda: "unknown-python") + assert get_abi_tag() == "unknown_python_310" + + +def test_platform_with_space(dummy_dist, monkeypatch): + """Ensure building on platforms with a space in the name succeed.""" + monkeypatch.chdir(dummy_dist) + bdist_wheel_cmd(plat_name="isilon onefs").run() + + +def test_data_dir_with_tag_build(monkeypatch, tmp_path): + """ + Setuptools allow authors to set PEP 440's local version segments + using ``egg_info.tag_build``. This should be reflected not only in the + ``.whl`` file name, but also in the ``.dist-info`` and ``.data`` dirs. + See pypa/setuptools#3997. + """ + monkeypatch.chdir(tmp_path) + files = { + "setup.py": """ + from setuptools import setup + setup(headers=["hello.h"]) + """, + "setup.cfg": """ + [metadata] + name = test + version = 1.0 + + [options.data_files] + hello/world = file.txt + + [egg_info] + tag_build = +what + tag_date = 0 + """, + "file.txt": "", + "hello.h": "", + } + for file, content in files.items(): + with open(file, "w", encoding="utf-8") as fh: + fh.write(cleandoc(content)) + + bdist_wheel_cmd().run() + + # Ensure .whl, .dist-info and .data contain the local segment + wheel_path = "dist/test-1.0+what-py3-none-any.whl" + assert os.path.exists(wheel_path) + entries = set(ZipFile(wheel_path).namelist()) + for expected in ( + "test-1.0+what.data/headers/hello.h", + "test-1.0+what.data/data/hello/world/file.txt", + "test-1.0+what.dist-info/METADATA", + "test-1.0+what.dist-info/WHEEL", + ): + assert expected in entries + + for not_expected in ( + "test.data/headers/hello.h", + "test-1.0.data/data/hello/world/file.txt", + "test.dist-info/METADATA", + "test-1.0.dist-info/WHEEL", + ): + assert not_expected not in entries + + +@pytest.mark.parametrize( + ("reported", "expected"), + [("linux-x86_64", "linux_i686"), ("linux-aarch64", "linux_armv7l")], +) +@pytest.mark.skipif( + platform.system() != "Linux", reason="Only makes sense to test on Linux" +) +def test_platform_linux32(reported, expected, monkeypatch): + monkeypatch.setattr(struct, "calcsize", lambda x: 4) + dist = setuptools.Distribution() + cmd = bdist_wheel(dist) + cmd.plat_name = reported + cmd.root_is_pure = False + _, _, actual = cmd.get_tag() + assert actual == expected + + +def test_no_ctypes(monkeypatch) -> None: + def _fake_import(name: str, *args, **kwargs): + if name == "ctypes": + raise ModuleNotFoundError(f"No module named {name}") + + return importlib.__import__(name, *args, **kwargs) + + with suppress(KeyError): + monkeypatch.delitem(sys.modules, "wheel.macosx_libfile") + + # Install an importer shim that refuses to load ctypes + monkeypatch.setattr(builtins, "__import__", _fake_import) + with pytest.raises(ModuleNotFoundError, match="No module named ctypes"): + import wheel.macosx_libfile # noqa: F401 + + # Unload and reimport the bdist_wheel command module to make sure it won't try to + # import ctypes + monkeypatch.delitem(sys.modules, "setuptools.command.bdist_wheel") + + import setuptools.command.bdist_wheel # noqa: F401 + + +def test_dist_info_provided(dummy_dist, monkeypatch, tmp_path): + monkeypatch.chdir(dummy_dist) + distinfo = tmp_path / "dummy_dist.dist-info" + + distinfo.mkdir() + (distinfo / "METADATA").write_text("name: helloworld", encoding="utf-8") + + # We don't control the metadata. According to PEP-517, "The hook MAY also + # create other files inside this directory, and a build frontend MUST + # preserve". + (distinfo / "FOO").write_text("bar", encoding="utf-8") + + bdist_wheel_cmd(bdist_dir=str(tmp_path), dist_info_dir=str(distinfo)).run() + expected = { + "dummy_dist-1.0.dist-info/FOO", + "dummy_dist-1.0.dist-info/RECORD", + } + with ZipFile("dist/dummy_dist-1.0-py3-none-any.whl") as wf: + files_found = set(wf.namelist()) + # Check that all expected files are there. + assert expected - files_found == set() + # Make sure there is no accidental egg-info bleeding into the wheel. + assert not [path for path in files_found if 'egg-info' in str(path)] + + +def test_allow_grace_period_parent_directory_license(monkeypatch, tmp_path): + # Motivation: https://github.com/pypa/setuptools/issues/4892 + # TODO: Remove this test after deprecation period is over + files = { + "LICENSE.txt": "parent license", # <---- the license files are outside + "NOTICE.txt": "parent notice", + "python": { + "pyproject.toml": cleandoc( + """ + [project] + name = "test-proj" + dynamic = ["version"] # <---- testing dynamic will not break + [tool.setuptools.dynamic] + version.file = "VERSION" + """ + ), + "setup.cfg": cleandoc( + """ + [metadata] + license_files = + ../LICENSE.txt + ../NOTICE.txt + """ + ), + "VERSION": "42", + }, + } + jaraco.path.build(files, prefix=str(tmp_path)) + monkeypatch.chdir(tmp_path / "python") + msg = "Pattern '../.*.txt' cannot contain '..'" + with pytest.warns(SetuptoolsDeprecationWarning, match=msg): + bdist_wheel_cmd().run() + with ZipFile("dist/test_proj-42-py3-none-any.whl") as wf: + files_found = set(wf.namelist()) + expected_files = { + "test_proj-42.dist-info/licenses/LICENSE.txt", + "test_proj-42.dist-info/licenses/NOTICE.txt", + } + assert expected_files <= files_found + + metadata = wf.read("test_proj-42.dist-info/METADATA").decode("utf8") + assert "License-File: LICENSE.txt" in metadata + assert "License-File: NOTICE.txt" in metadata diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/test_build.py b/.venv/lib/python3.12/site-packages/setuptools/tests/test_build.py new file mode 100644 index 0000000000000000000000000000000000000000..f0f1d9dcf21bafe9dc82a76d373b366ddeecfcec --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/test_build.py @@ -0,0 +1,33 @@ +from setuptools import Command +from setuptools.command.build import build +from setuptools.dist import Distribution + + +def test_distribution_gives_setuptools_build_obj(tmpdir_cwd): + """ + Check that the setuptools Distribution uses the + setuptools specific build object. + """ + + dist = Distribution( + dict( + script_name='setup.py', + script_args=['build'], + packages=[], + package_data={'': ['path/*']}, + ) + ) + assert isinstance(dist.get_command_obj("build"), build) + + +class Subcommand(Command): + """Dummy command to be used in tests""" + + def initialize_options(self): + pass + + def finalize_options(self): + pass + + def run(self): + raise NotImplementedError("just to check if the command runs") diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/test_build_clib.py b/.venv/lib/python3.12/site-packages/setuptools/tests/test_build_clib.py new file mode 100644 index 0000000000000000000000000000000000000000..b5315df4f6599cd376e628c0d74cb14129cd89b8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/test_build_clib.py @@ -0,0 +1,84 @@ +import random +from unittest import mock + +import pytest + +from setuptools.command.build_clib import build_clib +from setuptools.dist import Distribution + +from distutils.errors import DistutilsSetupError + + +class TestBuildCLib: + @mock.patch('setuptools.command.build_clib.newer_pairwise_group') + def test_build_libraries(self, mock_newer): + dist = Distribution() + cmd = build_clib(dist) + + # this will be a long section, just making sure all + # exceptions are properly raised + libs = [('example', {'sources': 'broken.c'})] + with pytest.raises(DistutilsSetupError): + cmd.build_libraries(libs) + + obj_deps = 'some_string' + libs = [('example', {'sources': ['source.c'], 'obj_deps': obj_deps})] + with pytest.raises(DistutilsSetupError): + cmd.build_libraries(libs) + + obj_deps = {'': ''} + libs = [('example', {'sources': ['source.c'], 'obj_deps': obj_deps})] + with pytest.raises(DistutilsSetupError): + cmd.build_libraries(libs) + + obj_deps = {'source.c': ''} + libs = [('example', {'sources': ['source.c'], 'obj_deps': obj_deps})] + with pytest.raises(DistutilsSetupError): + cmd.build_libraries(libs) + + # with that out of the way, let's see if the crude dependency + # system works + cmd.compiler = mock.MagicMock(spec=cmd.compiler) + mock_newer.return_value = ([], []) + + obj_deps = {'': ('global.h',), 'example.c': ('example.h',)} + libs = [('example', {'sources': ['example.c'], 'obj_deps': obj_deps})] + + cmd.build_libraries(libs) + assert [['example.c', 'global.h', 'example.h']] in mock_newer.call_args[0] + assert not cmd.compiler.compile.called + assert cmd.compiler.create_static_lib.call_count == 1 + + # reset the call numbers so we can test again + cmd.compiler.reset_mock() + + mock_newer.return_value = '' # anything as long as it's not ([],[]) + cmd.build_libraries(libs) + assert cmd.compiler.compile.call_count == 1 + assert cmd.compiler.create_static_lib.call_count == 1 + + @mock.patch('setuptools.command.build_clib.newer_pairwise_group') + def test_build_libraries_reproducible(self, mock_newer): + dist = Distribution() + cmd = build_clib(dist) + + # with that out of the way, let's see if the crude dependency + # system works + cmd.compiler = mock.MagicMock(spec=cmd.compiler) + mock_newer.return_value = ([], []) + + original_sources = ['a-example.c', 'example.c'] + sources = original_sources + + obj_deps = {'': ('global.h',), 'example.c': ('example.h',)} + libs = [('example', {'sources': sources, 'obj_deps': obj_deps})] + + cmd.build_libraries(libs) + computed_call_args = mock_newer.call_args[0] + + while sources == original_sources: + sources = random.sample(original_sources, len(original_sources)) + libs = [('example', {'sources': sources, 'obj_deps': obj_deps})] + + cmd.build_libraries(libs) + assert computed_call_args == mock_newer.call_args[0] diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/test_build_ext.py b/.venv/lib/python3.12/site-packages/setuptools/tests/test_build_ext.py new file mode 100644 index 0000000000000000000000000000000000000000..c7b60ac32fcd6628cf96396a7e5d8fdb50f67c19 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/test_build_ext.py @@ -0,0 +1,293 @@ +from __future__ import annotations + +import os +import sys +from importlib.util import cache_from_source as _compiled_file_name + +import pytest +from jaraco import path + +from setuptools.command.build_ext import build_ext, get_abi3_suffix +from setuptools.dist import Distribution +from setuptools.errors import CompileError +from setuptools.extension import Extension + +from . import environment +from .textwrap import DALS + +import distutils.command.build_ext as orig +from distutils.sysconfig import get_config_var + +IS_PYPY = '__pypy__' in sys.builtin_module_names + + +class TestBuildExt: + def test_get_ext_filename(self): + """ + Setuptools needs to give back the same + result as distutils, even if the fullname + is not in ext_map. + """ + dist = Distribution() + cmd = build_ext(dist) + cmd.ext_map['foo/bar'] = '' + res = cmd.get_ext_filename('foo') + wanted = orig.build_ext.get_ext_filename(cmd, 'foo') + assert res == wanted + + def test_abi3_filename(self): + """ + Filename needs to be loadable by several versions + of Python 3 if 'is_abi3' is truthy on Extension() + """ + print(get_abi3_suffix()) + + extension = Extension('spam.eggs', ['eggs.c'], py_limited_api=True) + dist = Distribution(dict(ext_modules=[extension])) + cmd = build_ext(dist) + cmd.finalize_options() + assert 'spam.eggs' in cmd.ext_map + res = cmd.get_ext_filename('spam.eggs') + + if not get_abi3_suffix(): + assert res.endswith(get_config_var('EXT_SUFFIX')) + elif sys.platform == 'win32': + assert res.endswith('eggs.pyd') + else: + assert 'abi3' in res + + def test_ext_suffix_override(self): + """ + SETUPTOOLS_EXT_SUFFIX variable always overrides + default extension options. + """ + dist = Distribution() + cmd = build_ext(dist) + cmd.ext_map['for_abi3'] = ext = Extension( + 'for_abi3', + ['s.c'], + # Override shouldn't affect abi3 modules + py_limited_api=True, + ) + # Mock value needed to pass tests + ext._links_to_dynamic = False + + if not IS_PYPY: + expect = cmd.get_ext_filename('for_abi3') + else: + # PyPy builds do not use ABI3 tag, so they will + # also get the overridden suffix. + expect = 'for_abi3.test-suffix' + + try: + os.environ['SETUPTOOLS_EXT_SUFFIX'] = '.test-suffix' + res = cmd.get_ext_filename('normal') + assert 'normal.test-suffix' == res + res = cmd.get_ext_filename('for_abi3') + assert expect == res + finally: + del os.environ['SETUPTOOLS_EXT_SUFFIX'] + + def dist_with_example(self): + files = { + "src": {"mypkg": {"subpkg": {"ext2.c": ""}}}, + "c-extensions": {"ext1": {"main.c": ""}}, + } + + ext1 = Extension("mypkg.ext1", ["c-extensions/ext1/main.c"]) + ext2 = Extension("mypkg.subpkg.ext2", ["src/mypkg/subpkg/ext2.c"]) + ext3 = Extension("ext3", ["c-extension/ext3.c"]) + + path.build(files) + return Distribution({ + "script_name": "%test%", + "ext_modules": [ext1, ext2, ext3], + "package_dir": {"": "src"}, + }) + + def test_get_outputs(self, tmpdir_cwd, monkeypatch): + monkeypatch.setenv('SETUPTOOLS_EXT_SUFFIX', '.mp3') # make test OS-independent + monkeypatch.setattr('setuptools.command.build_ext.use_stubs', False) + dist = self.dist_with_example() + + # Regular build: get_outputs not empty, but get_output_mappings is empty + build_ext = dist.get_command_obj("build_ext") + build_ext.editable_mode = False + build_ext.ensure_finalized() + build_lib = build_ext.build_lib.replace(os.sep, "/") + outputs = [x.replace(os.sep, "/") for x in build_ext.get_outputs()] + assert outputs == [ + f"{build_lib}/ext3.mp3", + f"{build_lib}/mypkg/ext1.mp3", + f"{build_lib}/mypkg/subpkg/ext2.mp3", + ] + assert build_ext.get_output_mapping() == {} + + # Editable build: get_output_mappings should contain everything in get_outputs + dist.reinitialize_command("build_ext") + build_ext.editable_mode = True + build_ext.ensure_finalized() + mapping = { + k.replace(os.sep, "/"): v.replace(os.sep, "/") + for k, v in build_ext.get_output_mapping().items() + } + assert mapping == { + f"{build_lib}/ext3.mp3": "src/ext3.mp3", + f"{build_lib}/mypkg/ext1.mp3": "src/mypkg/ext1.mp3", + f"{build_lib}/mypkg/subpkg/ext2.mp3": "src/mypkg/subpkg/ext2.mp3", + } + + def test_get_output_mapping_with_stub(self, tmpdir_cwd, monkeypatch): + monkeypatch.setenv('SETUPTOOLS_EXT_SUFFIX', '.mp3') # make test OS-independent + monkeypatch.setattr('setuptools.command.build_ext.use_stubs', True) + dist = self.dist_with_example() + + # Editable build should create compiled stubs (.pyc files only, no .py) + build_ext = dist.get_command_obj("build_ext") + build_ext.editable_mode = True + build_ext.ensure_finalized() + for ext in build_ext.extensions: + monkeypatch.setattr(ext, "_needs_stub", True) + + build_lib = build_ext.build_lib.replace(os.sep, "/") + mapping = { + k.replace(os.sep, "/"): v.replace(os.sep, "/") + for k, v in build_ext.get_output_mapping().items() + } + + def C(file): + """Make it possible to do comparisons and tests in a OS-independent way""" + return _compiled_file_name(file).replace(os.sep, "/") + + assert mapping == { + C(f"{build_lib}/ext3.py"): C("src/ext3.py"), + f"{build_lib}/ext3.mp3": "src/ext3.mp3", + C(f"{build_lib}/mypkg/ext1.py"): C("src/mypkg/ext1.py"), + f"{build_lib}/mypkg/ext1.mp3": "src/mypkg/ext1.mp3", + C(f"{build_lib}/mypkg/subpkg/ext2.py"): C("src/mypkg/subpkg/ext2.py"), + f"{build_lib}/mypkg/subpkg/ext2.mp3": "src/mypkg/subpkg/ext2.mp3", + } + + # Ensure only the compiled stubs are present not the raw .py stub + assert f"{build_lib}/mypkg/ext1.py" not in mapping + assert f"{build_lib}/mypkg/subpkg/ext2.py" not in mapping + + # Visualize what the cached stub files look like + example_stub = C(f"{build_lib}/mypkg/ext1.py") + assert example_stub in mapping + assert example_stub.startswith(f"{build_lib}/mypkg/__pycache__/ext1") + assert example_stub.endswith(".pyc") + + +class TestBuildExtInplace: + def get_build_ext_cmd(self, optional: bool, **opts) -> build_ext: + files: dict[str, str | dict[str, dict[str, str]]] = { + "eggs.c": "#include missingheader.h\n", + ".build": {"lib": {}, "tmp": {}}, + } + path.build(files) + extension = Extension('spam.eggs', ['eggs.c'], optional=optional) + dist = Distribution(dict(ext_modules=[extension])) + dist.script_name = 'setup.py' + cmd = build_ext(dist) + vars(cmd).update(build_lib=".build/lib", build_temp=".build/tmp", **opts) + cmd.ensure_finalized() + return cmd + + def get_log_messages(self, caplog, capsys): + """ + Historically, distutils "logged" by printing to sys.std*. + Later versions adopted the logging framework. Grab + messages regardless of how they were captured. + """ + std = capsys.readouterr() + return std.out.splitlines() + std.err.splitlines() + caplog.messages + + def test_optional(self, tmpdir_cwd, caplog, capsys): + """ + If optional extensions fail to build, setuptools should show the error + in the logs but not fail to build + """ + cmd = self.get_build_ext_cmd(optional=True, inplace=True) + cmd.run() + assert any( + 'build_ext: building extension "spam.eggs" failed' + for msg in self.get_log_messages(caplog, capsys) + ) + # No compile error exception should be raised + + def test_non_optional(self, tmpdir_cwd): + # Non-optional extensions should raise an exception + cmd = self.get_build_ext_cmd(optional=False, inplace=True) + with pytest.raises(CompileError): + cmd.run() + + +def test_build_ext_config_handling(tmpdir_cwd): + files = { + 'setup.py': DALS( + """ + from setuptools import Extension, setup + setup( + name='foo', + version='0.0.0', + ext_modules=[Extension('foo', ['foo.c'])], + ) + """ + ), + 'foo.c': DALS( + """ + #include "Python.h" + + #if PY_MAJOR_VERSION >= 3 + + static struct PyModuleDef moduledef = { + PyModuleDef_HEAD_INIT, + "foo", + NULL, + 0, + NULL, + NULL, + NULL, + NULL, + NULL + }; + + #define INITERROR return NULL + + PyMODINIT_FUNC PyInit_foo(void) + + #else + + #define INITERROR return + + void initfoo(void) + + #endif + { + #if PY_MAJOR_VERSION >= 3 + PyObject *module = PyModule_Create(&moduledef); + #else + PyObject *module = Py_InitModule("extension", NULL); + #endif + if (module == NULL) + INITERROR; + #if PY_MAJOR_VERSION >= 3 + return module; + #endif + } + """ + ), + 'setup.cfg': DALS( + """ + [build] + build_base = foo_build + """ + ), + } + path.build(files) + code, (stdout, stderr) = environment.run_setup_py( + cmd=['build'], + data_stream=(0, 2), + ) + assert code == 0, f'\nSTDOUT:\n{stdout}\nSTDERR:\n{stderr}' diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/test_build_meta.py b/.venv/lib/python3.12/site-packages/setuptools/tests/test_build_meta.py new file mode 100644 index 0000000000000000000000000000000000000000..624bba862eaed942802e68ee37427438c7d389ad --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/test_build_meta.py @@ -0,0 +1,983 @@ +import contextlib +import importlib +import os +import re +import shutil +import signal +import sys +import tarfile +import warnings +from concurrent import futures +from pathlib import Path +from typing import Any, Callable +from zipfile import ZipFile + +import pytest +from jaraco import path +from packaging.requirements import Requirement + +from setuptools.warnings import SetuptoolsDeprecationWarning + +from .textwrap import DALS + +SETUP_SCRIPT_STUB = "__import__('setuptools').setup()" + + +TIMEOUT = int(os.getenv("TIMEOUT_BACKEND_TEST", "180")) # in seconds +IS_PYPY = '__pypy__' in sys.builtin_module_names + + +pytestmark = pytest.mark.skipif( + sys.platform == "win32" and IS_PYPY, + reason="The combination of PyPy + Windows + pytest-xdist + ProcessPoolExecutor " + "is flaky and problematic", +) + + +class BuildBackendBase: + def __init__(self, cwd='.', env=None, backend_name='setuptools.build_meta'): + self.cwd = cwd + self.env = env or {} + self.backend_name = backend_name + + +class BuildBackend(BuildBackendBase): + """PEP 517 Build Backend""" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.pool = futures.ProcessPoolExecutor(max_workers=1) + + def __getattr__(self, name: str) -> Callable[..., Any]: + """Handles arbitrary function invocations on the build backend.""" + + def method(*args, **kw): + root = os.path.abspath(self.cwd) + caller = BuildBackendCaller(root, self.env, self.backend_name) + pid = None + try: + pid = self.pool.submit(os.getpid).result(TIMEOUT) + return self.pool.submit(caller, name, *args, **kw).result(TIMEOUT) + except futures.TimeoutError: + self.pool.shutdown(wait=False) # doesn't stop already running processes + self._kill(pid) + pytest.xfail(f"Backend did not respond before timeout ({TIMEOUT} s)") + except (futures.process.BrokenProcessPool, MemoryError, OSError): + if IS_PYPY: + pytest.xfail("PyPy frequently fails tests with ProcessPoolExector") + raise + + return method + + def _kill(self, pid): + if pid is None: + return + with contextlib.suppress(ProcessLookupError, OSError): + os.kill(pid, signal.SIGTERM if os.name == "nt" else signal.SIGKILL) + + +class BuildBackendCaller(BuildBackendBase): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + (self.backend_name, _, self.backend_obj) = self.backend_name.partition(':') + + def __call__(self, name, *args, **kw): + """Handles arbitrary function invocations on the build backend.""" + os.chdir(self.cwd) + os.environ.update(self.env) + mod = importlib.import_module(self.backend_name) + + if self.backend_obj: + backend = getattr(mod, self.backend_obj) + else: + backend = mod + + return getattr(backend, name)(*args, **kw) + + +defns = [ + { # simple setup.py script + 'setup.py': DALS( + """ + __import__('setuptools').setup( + name='foo', + version='0.0.0', + py_modules=['hello'], + setup_requires=['six'], + ) + """ + ), + 'hello.py': DALS( + """ + def run(): + print('hello') + """ + ), + }, + { # setup.py that relies on __name__ + 'setup.py': DALS( + """ + assert __name__ == '__main__' + __import__('setuptools').setup( + name='foo', + version='0.0.0', + py_modules=['hello'], + setup_requires=['six'], + ) + """ + ), + 'hello.py': DALS( + """ + def run(): + print('hello') + """ + ), + }, + { # setup.py script that runs arbitrary code + 'setup.py': DALS( + """ + variable = True + def function(): + return variable + assert variable + __import__('setuptools').setup( + name='foo', + version='0.0.0', + py_modules=['hello'], + setup_requires=['six'], + ) + """ + ), + 'hello.py': DALS( + """ + def run(): + print('hello') + """ + ), + }, + { # setup.py script that constructs temp files to be included in the distribution + 'setup.py': DALS( + """ + # Some packages construct files on the fly, include them in the package, + # and immediately remove them after `setup()` (e.g. pybind11==2.9.1). + # Therefore, we cannot use `distutils.core.run_setup(..., stop_after=...)` + # to obtain a distribution object first, and then run the distutils + # commands later, because these files will be removed in the meantime. + + with open('world.py', 'w', encoding="utf-8") as f: + f.write('x = 42') + + try: + __import__('setuptools').setup( + name='foo', + version='0.0.0', + py_modules=['world'], + setup_requires=['six'], + ) + finally: + # Some packages will clean temporary files + __import__('os').unlink('world.py') + """ + ), + }, + { # setup.cfg only + 'setup.cfg': DALS( + """ + [metadata] + name = foo + version = 0.0.0 + + [options] + py_modules=hello + setup_requires=six + """ + ), + 'hello.py': DALS( + """ + def run(): + print('hello') + """ + ), + }, + { # setup.cfg and setup.py + 'setup.cfg': DALS( + """ + [metadata] + name = foo + version = 0.0.0 + + [options] + py_modules=hello + setup_requires=six + """ + ), + 'setup.py': "__import__('setuptools').setup()", + 'hello.py': DALS( + """ + def run(): + print('hello') + """ + ), + }, +] + + +class TestBuildMetaBackend: + backend_name = 'setuptools.build_meta' + + def get_build_backend(self): + return BuildBackend(backend_name=self.backend_name) + + @pytest.fixture(params=defns) + def build_backend(self, tmpdir, request): + path.build(request.param, prefix=str(tmpdir)) + with tmpdir.as_cwd(): + yield self.get_build_backend() + + def test_get_requires_for_build_wheel(self, build_backend): + actual = build_backend.get_requires_for_build_wheel() + expected = ['six'] + assert sorted(actual) == sorted(expected) + + def test_get_requires_for_build_sdist(self, build_backend): + actual = build_backend.get_requires_for_build_sdist() + expected = ['six'] + assert sorted(actual) == sorted(expected) + + def test_build_wheel(self, build_backend): + dist_dir = os.path.abspath('pip-wheel') + os.makedirs(dist_dir) + wheel_name = build_backend.build_wheel(dist_dir) + + wheel_file = os.path.join(dist_dir, wheel_name) + assert os.path.isfile(wheel_file) + + # Temporary files should be removed + assert not os.path.isfile('world.py') + + with ZipFile(wheel_file) as zipfile: + wheel_contents = set(zipfile.namelist()) + + # Each one of the examples have a single module + # that should be included in the distribution + python_scripts = (f for f in wheel_contents if f.endswith('.py')) + modules = [f for f in python_scripts if not f.endswith('setup.py')] + assert len(modules) == 1 + + @pytest.mark.parametrize('build_type', ('wheel', 'sdist')) + def test_build_with_existing_file_present(self, build_type, tmpdir_cwd): + # Building a sdist/wheel should still succeed if there's + # already a sdist/wheel in the destination directory. + files = { + 'setup.py': "from setuptools import setup\nsetup()", + 'VERSION': "0.0.1", + 'setup.cfg': DALS( + """ + [metadata] + name = foo + version = file: VERSION + """ + ), + 'pyproject.toml': DALS( + """ + [build-system] + requires = ["setuptools", "wheel"] + build-backend = "setuptools.build_meta" + """ + ), + } + + path.build(files) + + dist_dir = os.path.abspath('preexisting-' + build_type) + + build_backend = self.get_build_backend() + build_method = getattr(build_backend, 'build_' + build_type) + + # Build a first sdist/wheel. + # Note: this also check the destination directory is + # successfully created if it does not exist already. + first_result = build_method(dist_dir) + + # Change version. + with open("VERSION", "wt", encoding="utf-8") as version_file: + version_file.write("0.0.2") + + # Build a *second* sdist/wheel. + second_result = build_method(dist_dir) + + assert os.path.isfile(os.path.join(dist_dir, first_result)) + assert first_result != second_result + + # And if rebuilding the exact same sdist/wheel? + open(os.path.join(dist_dir, second_result), 'wb').close() + third_result = build_method(dist_dir) + assert third_result == second_result + assert os.path.getsize(os.path.join(dist_dir, third_result)) > 0 + + @pytest.mark.parametrize("setup_script", [None, SETUP_SCRIPT_STUB]) + def test_build_with_pyproject_config(self, tmpdir, setup_script): + files = { + 'pyproject.toml': DALS( + """ + [build-system] + requires = ["setuptools", "wheel"] + build-backend = "setuptools.build_meta" + + [project] + name = "foo" + license = {text = "MIT"} + description = "This is a Python package" + dynamic = ["version", "readme"] + classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers" + ] + urls = {Homepage = "http://github.com"} + dependencies = [ + "appdirs", + ] + + [project.optional-dependencies] + all = [ + "tomli>=1", + "pyscaffold>=4,<5", + 'importlib; python_version == "2.6"', + ] + + [project.scripts] + foo = "foo.cli:main" + + [tool.setuptools] + zip-safe = false + package-dir = {"" = "src"} + packages = {find = {where = ["src"]}} + license-files = ["LICENSE*"] + + [tool.setuptools.dynamic] + version = {attr = "foo.__version__"} + readme = {file = "README.rst"} + + [tool.distutils.sdist] + formats = "gztar" + """ + ), + "MANIFEST.in": DALS( + """ + global-include *.py *.txt + global-exclude *.py[cod] + """ + ), + "README.rst": "This is a ``README``", + "LICENSE.txt": "---- placeholder MIT license ----", + "src": { + "foo": { + "__init__.py": "__version__ = '0.1'", + "__init__.pyi": "__version__: str", + "cli.py": "def main(): print('hello world')", + "data.txt": "def main(): print('hello world')", + "py.typed": "", + } + }, + } + if setup_script: + files["setup.py"] = setup_script + + build_backend = self.get_build_backend() + with tmpdir.as_cwd(): + path.build(files) + msgs = [ + "'tool.setuptools.license-files' is deprecated in favor of 'project.license-files'", + "`project.license` as a TOML table is deprecated", + ] + with warnings.catch_warnings(): + for msg in msgs: + warnings.filterwarnings("ignore", msg, SetuptoolsDeprecationWarning) + sdist_path = build_backend.build_sdist("temp") + wheel_file = build_backend.build_wheel("temp") + + with tarfile.open(os.path.join(tmpdir, "temp", sdist_path)) as tar: + sdist_contents = set(tar.getnames()) + + with ZipFile(os.path.join(tmpdir, "temp", wheel_file)) as zipfile: + wheel_contents = set(zipfile.namelist()) + metadata = str(zipfile.read("foo-0.1.dist-info/METADATA"), "utf-8") + license = str( + zipfile.read("foo-0.1.dist-info/licenses/LICENSE.txt"), "utf-8" + ) + epoints = str(zipfile.read("foo-0.1.dist-info/entry_points.txt"), "utf-8") + + assert sdist_contents - {"foo-0.1/setup.py"} == { + 'foo-0.1', + 'foo-0.1/LICENSE.txt', + 'foo-0.1/MANIFEST.in', + 'foo-0.1/PKG-INFO', + 'foo-0.1/README.rst', + 'foo-0.1/pyproject.toml', + 'foo-0.1/setup.cfg', + 'foo-0.1/src', + 'foo-0.1/src/foo', + 'foo-0.1/src/foo/__init__.py', + 'foo-0.1/src/foo/__init__.pyi', + 'foo-0.1/src/foo/cli.py', + 'foo-0.1/src/foo/data.txt', + 'foo-0.1/src/foo/py.typed', + 'foo-0.1/src/foo.egg-info', + 'foo-0.1/src/foo.egg-info/PKG-INFO', + 'foo-0.1/src/foo.egg-info/SOURCES.txt', + 'foo-0.1/src/foo.egg-info/dependency_links.txt', + 'foo-0.1/src/foo.egg-info/entry_points.txt', + 'foo-0.1/src/foo.egg-info/requires.txt', + 'foo-0.1/src/foo.egg-info/top_level.txt', + 'foo-0.1/src/foo.egg-info/not-zip-safe', + } + assert wheel_contents == { + "foo/__init__.py", + "foo/__init__.pyi", # include type information by default + "foo/cli.py", + "foo/data.txt", # include_package_data defaults to True + "foo/py.typed", # include type information by default + "foo-0.1.dist-info/licenses/LICENSE.txt", + "foo-0.1.dist-info/METADATA", + "foo-0.1.dist-info/WHEEL", + "foo-0.1.dist-info/entry_points.txt", + "foo-0.1.dist-info/top_level.txt", + "foo-0.1.dist-info/RECORD", + } + assert license == "---- placeholder MIT license ----" + + for line in ( + "Summary: This is a Python package", + "License: MIT", + "License-File: LICENSE.txt", + "Classifier: Intended Audience :: Developers", + "Requires-Dist: appdirs", + "Requires-Dist: " + str(Requirement('tomli>=1 ; extra == "all"')), + "Requires-Dist: " + + str(Requirement('importlib; python_version=="2.6" and extra =="all"')), + ): + assert line in metadata, (line, metadata) + + assert metadata.strip().endswith("This is a ``README``") + assert epoints.strip() == "[console_scripts]\nfoo = foo.cli:main" + + def test_static_metadata_in_pyproject_config(self, tmpdir): + # Make sure static metadata in pyproject.toml is not overwritten by setup.py + # as required by PEP 621 + files = { + 'pyproject.toml': DALS( + """ + [build-system] + requires = ["setuptools", "wheel"] + build-backend = "setuptools.build_meta" + + [project] + name = "foo" + description = "This is a Python package" + version = "42" + dependencies = ["six"] + """ + ), + 'hello.py': DALS( + """ + def run(): + print('hello') + """ + ), + 'setup.py': DALS( + """ + __import__('setuptools').setup( + name='bar', + version='13', + ) + """ + ), + } + build_backend = self.get_build_backend() + with tmpdir.as_cwd(): + path.build(files) + sdist_path = build_backend.build_sdist("temp") + wheel_file = build_backend.build_wheel("temp") + + assert (tmpdir / "temp/foo-42.tar.gz").exists() + assert (tmpdir / "temp/foo-42-py3-none-any.whl").exists() + assert not (tmpdir / "temp/bar-13.tar.gz").exists() + assert not (tmpdir / "temp/bar-42.tar.gz").exists() + assert not (tmpdir / "temp/foo-13.tar.gz").exists() + assert not (tmpdir / "temp/bar-13-py3-none-any.whl").exists() + assert not (tmpdir / "temp/bar-42-py3-none-any.whl").exists() + assert not (tmpdir / "temp/foo-13-py3-none-any.whl").exists() + + with tarfile.open(os.path.join(tmpdir, "temp", sdist_path)) as tar: + pkg_info = str(tar.extractfile('foo-42/PKG-INFO').read(), "utf-8") + members = tar.getnames() + assert "bar-13/PKG-INFO" not in members + + with ZipFile(os.path.join(tmpdir, "temp", wheel_file)) as zipfile: + metadata = str(zipfile.read("foo-42.dist-info/METADATA"), "utf-8") + members = zipfile.namelist() + assert "bar-13.dist-info/METADATA" not in members + + for file in pkg_info, metadata: + for line in ("Name: foo", "Version: 42"): + assert line in file + for line in ("Name: bar", "Version: 13"): + assert line not in file + + def test_build_sdist(self, build_backend): + dist_dir = os.path.abspath('pip-sdist') + os.makedirs(dist_dir) + sdist_name = build_backend.build_sdist(dist_dir) + + assert os.path.isfile(os.path.join(dist_dir, sdist_name)) + + def test_prepare_metadata_for_build_wheel(self, build_backend): + dist_dir = os.path.abspath('pip-dist-info') + os.makedirs(dist_dir) + + dist_info = build_backend.prepare_metadata_for_build_wheel(dist_dir) + + assert os.path.isfile(os.path.join(dist_dir, dist_info, 'METADATA')) + + def test_prepare_metadata_inplace(self, build_backend): + """ + Some users might pass metadata_directory pre-populated with `.tox` or `.venv`. + See issue #3523. + """ + for pre_existing in [ + ".tox/python/lib/python3.10/site-packages/attrs-22.1.0.dist-info", + ".tox/python/lib/python3.10/site-packages/autocommand-2.2.1.dist-info", + ".nox/python/lib/python3.10/site-packages/build-0.8.0.dist-info", + ".venv/python3.10/site-packages/click-8.1.3.dist-info", + "venv/python3.10/site-packages/distlib-0.3.5.dist-info", + "env/python3.10/site-packages/docutils-0.19.dist-info", + ]: + os.makedirs(pre_existing, exist_ok=True) + dist_info = build_backend.prepare_metadata_for_build_wheel(".") + assert os.path.isfile(os.path.join(dist_info, 'METADATA')) + + def test_build_sdist_explicit_dist(self, build_backend): + # explicitly specifying the dist folder should work + # the folder sdist_directory and the ``--dist-dir`` can be the same + dist_dir = os.path.abspath('dist') + sdist_name = build_backend.build_sdist(dist_dir) + assert os.path.isfile(os.path.join(dist_dir, sdist_name)) + + def test_build_sdist_version_change(self, build_backend): + sdist_into_directory = os.path.abspath("out_sdist") + os.makedirs(sdist_into_directory) + + sdist_name = build_backend.build_sdist(sdist_into_directory) + assert os.path.isfile(os.path.join(sdist_into_directory, sdist_name)) + + # if the setup.py changes subsequent call of the build meta + # should still succeed, given the + # sdist_directory the frontend specifies is empty + setup_loc = os.path.abspath("setup.py") + if not os.path.exists(setup_loc): + setup_loc = os.path.abspath("setup.cfg") + + with open(setup_loc, 'rt', encoding="utf-8") as file_handler: + content = file_handler.read() + with open(setup_loc, 'wt', encoding="utf-8") as file_handler: + file_handler.write(content.replace("version='0.0.0'", "version='0.0.1'")) + + shutil.rmtree(sdist_into_directory) + os.makedirs(sdist_into_directory) + + sdist_name = build_backend.build_sdist("out_sdist") + assert os.path.isfile(os.path.join(os.path.abspath("out_sdist"), sdist_name)) + + def test_build_sdist_pyproject_toml_exists(self, tmpdir_cwd): + files = { + 'setup.py': DALS( + """ + __import__('setuptools').setup( + name='foo', + version='0.0.0', + py_modules=['hello'] + )""" + ), + 'hello.py': '', + 'pyproject.toml': DALS( + """ + [build-system] + requires = ["setuptools", "wheel"] + build-backend = "setuptools.build_meta" + """ + ), + } + path.build(files) + build_backend = self.get_build_backend() + targz_path = build_backend.build_sdist("temp") + with tarfile.open(os.path.join("temp", targz_path)) as tar: + assert any('pyproject.toml' in name for name in tar.getnames()) + + def test_build_sdist_setup_py_exists(self, tmpdir_cwd): + # If build_sdist is called from a script other than setup.py, + # ensure setup.py is included + path.build(defns[0]) + + build_backend = self.get_build_backend() + targz_path = build_backend.build_sdist("temp") + with tarfile.open(os.path.join("temp", targz_path)) as tar: + assert any('setup.py' in name for name in tar.getnames()) + + def test_build_sdist_setup_py_manifest_excluded(self, tmpdir_cwd): + # Ensure that MANIFEST.in can exclude setup.py + files = { + 'setup.py': DALS( + """ + __import__('setuptools').setup( + name='foo', + version='0.0.0', + py_modules=['hello'] + )""" + ), + 'hello.py': '', + 'MANIFEST.in': DALS( + """ + exclude setup.py + """ + ), + } + + path.build(files) + + build_backend = self.get_build_backend() + targz_path = build_backend.build_sdist("temp") + with tarfile.open(os.path.join("temp", targz_path)) as tar: + assert not any('setup.py' in name for name in tar.getnames()) + + def test_build_sdist_builds_targz_even_if_zip_indicated(self, tmpdir_cwd): + files = { + 'setup.py': DALS( + """ + __import__('setuptools').setup( + name='foo', + version='0.0.0', + py_modules=['hello'] + )""" + ), + 'hello.py': '', + 'setup.cfg': DALS( + """ + [sdist] + formats=zip + """ + ), + } + + path.build(files) + + build_backend = self.get_build_backend() + build_backend.build_sdist("temp") + + _relative_path_import_files = { + 'setup.py': DALS( + """ + __import__('setuptools').setup( + name='foo', + version=__import__('hello').__version__, + py_modules=['hello'] + )""" + ), + 'hello.py': '__version__ = "0.0.0"', + 'setup.cfg': DALS( + """ + [sdist] + formats=zip + """ + ), + } + + def test_build_sdist_relative_path_import(self, tmpdir_cwd): + path.build(self._relative_path_import_files) + build_backend = self.get_build_backend() + with pytest.raises(ImportError, match="^No module named 'hello'$"): + build_backend.build_sdist("temp") + + _simple_pyproject_example = { + "pyproject.toml": DALS( + """ + [project] + name = "proj" + version = "42" + """ + ), + "src": {"proj": {"__init__.py": ""}}, + } + + def _assert_link_tree(self, parent_dir): + """All files in the directory should be either links or hard links""" + files = list(Path(parent_dir).glob("**/*")) + assert files # Should not be empty + for file in files: + assert file.is_symlink() or os.stat(file).st_nlink > 0 + + def test_editable_without_config_settings(self, tmpdir_cwd): + """ + Sanity check to ensure tests with --mode=strict are different from the ones + without --mode. + + --mode=strict should create a local directory with a package tree. + The directory should not get created otherwise. + """ + path.build(self._simple_pyproject_example) + build_backend = self.get_build_backend() + assert not Path("build").exists() + build_backend.build_editable("temp") + assert not Path("build").exists() + + def test_build_wheel_inplace(self, tmpdir_cwd): + config_settings = {"--build-option": ["build_ext", "--inplace"]} + path.build(self._simple_pyproject_example) + build_backend = self.get_build_backend() + assert not Path("build").exists() + Path("build").mkdir() + build_backend.prepare_metadata_for_build_wheel("build", config_settings) + build_backend.build_wheel("build", config_settings) + assert Path("build/proj-42-py3-none-any.whl").exists() + + @pytest.mark.parametrize("config_settings", [{"editable-mode": "strict"}]) + def test_editable_with_config_settings(self, tmpdir_cwd, config_settings): + path.build({**self._simple_pyproject_example, '_meta': {}}) + assert not Path("build").exists() + build_backend = self.get_build_backend() + build_backend.prepare_metadata_for_build_editable("_meta", config_settings) + build_backend.build_editable("temp", config_settings, "_meta") + self._assert_link_tree(next(Path("build").glob("__editable__.*"))) + + @pytest.mark.parametrize( + ("setup_literal", "requirements"), + [ + ("'foo'", ['foo']), + ("['foo']", ['foo']), + (r"'foo\n'", ['foo']), + (r"'foo\n\n'", ['foo']), + ("['foo', 'bar']", ['foo', 'bar']), + (r"'# Has a comment line\nfoo'", ['foo']), + (r"'foo # Has an inline comment'", ['foo']), + (r"'foo \\\n >=3.0'", ['foo>=3.0']), + (r"'foo\nbar'", ['foo', 'bar']), + (r"'foo\nbar\n'", ['foo', 'bar']), + (r"['foo\n', 'bar\n']", ['foo', 'bar']), + ], + ) + @pytest.mark.parametrize('use_wheel', [True, False]) + def test_setup_requires(self, setup_literal, requirements, use_wheel, tmpdir_cwd): + files = { + 'setup.py': DALS( + """ + from setuptools import setup + + setup( + name="qux", + version="0.0.0", + py_modules=["hello"], + setup_requires={setup_literal}, + ) + """ + ).format(setup_literal=setup_literal), + 'hello.py': DALS( + """ + def run(): + print('hello') + """ + ), + } + + path.build(files) + + build_backend = self.get_build_backend() + + if use_wheel: + get_requires = build_backend.get_requires_for_build_wheel + else: + get_requires = build_backend.get_requires_for_build_sdist + + # Ensure that the build requirements are properly parsed + expected = sorted(requirements) + actual = get_requires() + + assert expected == sorted(actual) + + def test_setup_requires_with_auto_discovery(self, tmpdir_cwd): + # Make sure patches introduced to retrieve setup_requires don't accidentally + # activate auto-discovery and cause problems due to the incomplete set of + # attributes passed to MinimalDistribution + files = { + 'pyproject.toml': DALS( + """ + [project] + name = "proj" + version = "42" + """ + ), + "setup.py": DALS( + """ + __import__('setuptools').setup( + setup_requires=["foo"], + py_modules = ["hello", "world"] + ) + """ + ), + 'hello.py': "'hello'", + 'world.py': "'world'", + } + path.build(files) + build_backend = self.get_build_backend() + setup_requires = build_backend.get_requires_for_build_wheel() + assert setup_requires == ["foo"] + + def test_dont_install_setup_requires(self, tmpdir_cwd): + files = { + 'setup.py': DALS( + """ + from setuptools import setup + + setup( + name="qux", + version="0.0.0", + py_modules=["hello"], + setup_requires=["does-not-exist >99"], + ) + """ + ), + 'hello.py': DALS( + """ + def run(): + print('hello') + """ + ), + } + + path.build(files) + + build_backend = self.get_build_backend() + + dist_dir = os.path.abspath('pip-dist-info') + os.makedirs(dist_dir) + + # does-not-exist can't be satisfied, so if it attempts to install + # setup_requires, it will fail. + build_backend.prepare_metadata_for_build_wheel(dist_dir) + + _sys_argv_0_passthrough = { + 'setup.py': DALS( + """ + import os + import sys + + __import__('setuptools').setup( + name='foo', + version='0.0.0', + ) + + sys_argv = os.path.abspath(sys.argv[0]) + file_path = os.path.abspath('setup.py') + assert sys_argv == file_path + """ + ) + } + + def test_sys_argv_passthrough(self, tmpdir_cwd): + path.build(self._sys_argv_0_passthrough) + build_backend = self.get_build_backend() + with pytest.raises(AssertionError): + build_backend.build_sdist("temp") + + _setup_py_file_abspath = { + 'setup.py': DALS( + """ + import os + assert os.path.isabs(__file__) + __import__('setuptools').setup( + name='foo', + version='0.0.0', + py_modules=['hello'], + setup_requires=['six'], + ) + """ + ) + } + + def test_setup_py_file_abspath(self, tmpdir_cwd): + path.build(self._setup_py_file_abspath) + build_backend = self.get_build_backend() + build_backend.build_sdist("temp") + + @pytest.mark.parametrize('build_hook', ('build_sdist', 'build_wheel')) + def test_build_with_empty_setuppy(self, build_backend, build_hook): + files = {'setup.py': ''} + path.build(files) + + msg = re.escape('No distribution was found.') + with pytest.raises(ValueError, match=msg): + getattr(build_backend, build_hook)("temp") + + +class TestBuildMetaLegacyBackend(TestBuildMetaBackend): + backend_name = 'setuptools.build_meta:__legacy__' + + # build_meta_legacy-specific tests + def test_build_sdist_relative_path_import(self, tmpdir_cwd): + # This must fail in build_meta, but must pass in build_meta_legacy + path.build(self._relative_path_import_files) + + build_backend = self.get_build_backend() + build_backend.build_sdist("temp") + + def test_sys_argv_passthrough(self, tmpdir_cwd): + path.build(self._sys_argv_0_passthrough) + + build_backend = self.get_build_backend() + build_backend.build_sdist("temp") + + +def test_legacy_editable_install(venv, tmpdir, tmpdir_cwd): + pyproject = """ + [build-system] + requires = ["setuptools"] + build-backend = "setuptools.build_meta" + [project] + name = "myproj" + version = "42" + """ + path.build({"pyproject.toml": DALS(pyproject), "mymod.py": ""}) + + # First: sanity check + cmd = ["pip", "install", "--no-build-isolation", "-e", "."] + output = venv.run(cmd, cwd=tmpdir).lower() + assert "running setup.py develop for myproj" not in output + assert "created wheel for myproj" in output + + # Then: real test + env = {**os.environ, "SETUPTOOLS_ENABLE_FEATURES": "legacy-editable"} + cmd = ["pip", "install", "--no-build-isolation", "-e", "."] + output = venv.run(cmd, cwd=tmpdir, env=env).lower() + assert "running setup.py develop for myproj" in output + + +@pytest.mark.filterwarnings("ignore::setuptools.SetuptoolsDeprecationWarning") +def test_sys_exit_0_in_setuppy(monkeypatch, tmp_path): + """Setuptools should be resilient to setup.py with ``sys.exit(0)`` (#3973).""" + monkeypatch.chdir(tmp_path) + setuppy = """ + import sys, setuptools + setuptools.setup(name='foo', version='0.0.0') + sys.exit(0) + """ + (tmp_path / "setup.py").write_text(DALS(setuppy), encoding="utf-8") + backend = BuildBackend(backend_name="setuptools.build_meta") + assert backend.get_requires_for_build_wheel() == [] + + +def test_system_exit_in_setuppy(monkeypatch, tmp_path): + monkeypatch.chdir(tmp_path) + setuppy = "import sys; sys.exit('some error')" + (tmp_path / "setup.py").write_text(setuppy, encoding="utf-8") + with pytest.raises(SystemExit, match="some error"): + backend = BuildBackend(backend_name="setuptools.build_meta") + backend.get_requires_for_build_wheel() diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/test_build_py.py b/.venv/lib/python3.12/site-packages/setuptools/tests/test_build_py.py new file mode 100644 index 0000000000000000000000000000000000000000..1e3a660833933717310de66978771c4e48b5b914 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/test_build_py.py @@ -0,0 +1,480 @@ +import os +import shutil +import stat +import warnings +from pathlib import Path +from unittest.mock import Mock + +import jaraco.path +import pytest + +from setuptools import SetuptoolsDeprecationWarning +from setuptools.dist import Distribution + +from .textwrap import DALS + + +def test_directories_in_package_data_glob(tmpdir_cwd): + """ + Directories matching the glob in package_data should + not be included in the package data. + + Regression test for #261. + """ + dist = Distribution( + dict( + script_name='setup.py', + script_args=['build_py'], + packages=[''], + package_data={'': ['path/*']}, + ) + ) + os.makedirs('path/subpath') + dist.parse_command_line() + dist.run_commands() + + +def test_recursive_in_package_data_glob(tmpdir_cwd): + """ + Files matching recursive globs (**) in package_data should + be included in the package data. + + #1806 + """ + dist = Distribution( + dict( + script_name='setup.py', + script_args=['build_py'], + packages=[''], + package_data={'': ['path/**/data']}, + ) + ) + os.makedirs('path/subpath/subsubpath') + open('path/subpath/subsubpath/data', 'wb').close() + + dist.parse_command_line() + dist.run_commands() + + assert stat.S_ISREG(os.stat('build/lib/path/subpath/subsubpath/data').st_mode), ( + "File is not included" + ) + + +def test_read_only(tmpdir_cwd): + """ + Ensure read-only flag is not preserved in copy + for package modules and package data, as that + causes problems with deleting read-only files on + Windows. + + #1451 + """ + dist = Distribution( + dict( + script_name='setup.py', + script_args=['build_py'], + packages=['pkg'], + package_data={'pkg': ['data.dat']}, + ) + ) + os.makedirs('pkg') + open('pkg/__init__.py', 'wb').close() + open('pkg/data.dat', 'wb').close() + os.chmod('pkg/__init__.py', stat.S_IREAD) + os.chmod('pkg/data.dat', stat.S_IREAD) + dist.parse_command_line() + dist.run_commands() + shutil.rmtree('build') + + +@pytest.mark.xfail( + 'platform.system() == "Windows"', + reason="On Windows, files do not have executable bits", + raises=AssertionError, + strict=True, +) +def test_executable_data(tmpdir_cwd): + """ + Ensure executable bit is preserved in copy for + package data, as users rely on it for scripts. + + #2041 + """ + dist = Distribution( + dict( + script_name='setup.py', + script_args=['build_py'], + packages=['pkg'], + package_data={'pkg': ['run-me']}, + ) + ) + os.makedirs('pkg') + open('pkg/__init__.py', 'wb').close() + open('pkg/run-me', 'wb').close() + os.chmod('pkg/run-me', 0o700) + + dist.parse_command_line() + dist.run_commands() + + assert os.stat('build/lib/pkg/run-me').st_mode & stat.S_IEXEC, ( + "Script is not executable" + ) + + +EXAMPLE_WITH_MANIFEST = { + "setup.cfg": DALS( + """ + [metadata] + name = mypkg + version = 42 + + [options] + include_package_data = True + packages = find: + + [options.packages.find] + exclude = *.tests* + """ + ), + "mypkg": { + "__init__.py": "", + "resource_file.txt": "", + "tests": { + "__init__.py": "", + "test_mypkg.py": "", + "test_file.txt": "", + }, + }, + "MANIFEST.in": DALS( + """ + global-include *.py *.txt + global-exclude *.py[cod] + prune dist + prune build + prune *.egg-info + """ + ), +} + + +def test_excluded_subpackages(tmpdir_cwd): + jaraco.path.build(EXAMPLE_WITH_MANIFEST) + dist = Distribution({"script_name": "%PEP 517%"}) + dist.parse_config_files() + + build_py = dist.get_command_obj("build_py") + + msg = r"Python recognizes 'mypkg\.tests' as an importable package" + with pytest.warns(SetuptoolsDeprecationWarning, match=msg): + # TODO: To fix #3260 we need some transition period to deprecate the + # existing behavior of `include_package_data`. After the transition, we + # should remove the warning and fix the behavior. + + if os.getenv("SETUPTOOLS_USE_DISTUTILS") == "stdlib": + # pytest.warns reset the warning filter temporarily + # https://github.com/pytest-dev/pytest/issues/4011#issuecomment-423494810 + warnings.filterwarnings( + "ignore", + "'encoding' argument not specified", + module="distutils.text_file", + # This warning is already fixed in pypa/distutils but not in stdlib + ) + + build_py.finalize_options() + build_py.run() + + build_dir = Path(dist.get_command_obj("build_py").build_lib) + assert (build_dir / "mypkg/__init__.py").exists() + assert (build_dir / "mypkg/resource_file.txt").exists() + + # Setuptools is configured to ignore `mypkg.tests`, therefore the following + # files/dirs should not be included in the distribution. + for f in [ + "mypkg/tests/__init__.py", + "mypkg/tests/test_mypkg.py", + "mypkg/tests/test_file.txt", + "mypkg/tests", + ]: + with pytest.raises(AssertionError): + # TODO: Enforce the following assertion once #3260 is fixed + # (remove context manager and the following xfail). + assert not (build_dir / f).exists() + + pytest.xfail("#3260") + + +@pytest.mark.filterwarnings("ignore::setuptools.SetuptoolsDeprecationWarning") +def test_existing_egg_info(tmpdir_cwd, monkeypatch): + """When provided with the ``existing_egg_info_dir`` attribute, build_py should not + attempt to run egg_info again. + """ + # == Pre-condition == + # Generate an egg-info dir + jaraco.path.build(EXAMPLE_WITH_MANIFEST) + dist = Distribution({"script_name": "%PEP 517%"}) + dist.parse_config_files() + assert dist.include_package_data + + egg_info = dist.get_command_obj("egg_info") + dist.run_command("egg_info") + egg_info_dir = next(Path(egg_info.egg_base).glob("*.egg-info")) + assert egg_info_dir.is_dir() + + # == Setup == + build_py = dist.get_command_obj("build_py") + build_py.finalize_options() + egg_info = dist.get_command_obj("egg_info") + egg_info_run = Mock(side_effect=egg_info.run) + monkeypatch.setattr(egg_info, "run", egg_info_run) + + # == Remove caches == + # egg_info is called when build_py looks for data_files, which gets cached. + # We need to ensure it is not cached yet, otherwise it may impact on the tests + build_py.__dict__.pop('data_files', None) + dist.reinitialize_command(egg_info) + + # == Sanity check == + # Ensure that if existing_egg_info is not given, build_py attempts to run egg_info + build_py.existing_egg_info_dir = None + build_py.run() + egg_info_run.assert_called() + + # == Remove caches == + egg_info_run.reset_mock() + build_py.__dict__.pop('data_files', None) + dist.reinitialize_command(egg_info) + + # == Actual test == + # Ensure that if existing_egg_info_dir is given, egg_info doesn't run + build_py.existing_egg_info_dir = egg_info_dir + build_py.run() + egg_info_run.assert_not_called() + assert build_py.data_files + + # Make sure the list of outputs is actually OK + outputs = map(lambda x: x.replace(os.sep, "/"), build_py.get_outputs()) + assert outputs + example = str(Path(build_py.build_lib, "mypkg/__init__.py")).replace(os.sep, "/") + assert example in outputs + + +EXAMPLE_ARBITRARY_MAPPING = { + "pyproject.toml": DALS( + """ + [project] + name = "mypkg" + version = "42" + + [tool.setuptools] + packages = ["mypkg", "mypkg.sub1", "mypkg.sub2", "mypkg.sub2.nested"] + + [tool.setuptools.package-dir] + "" = "src" + "mypkg.sub2" = "src/mypkg/_sub2" + "mypkg.sub2.nested" = "other" + """ + ), + "src": { + "mypkg": { + "__init__.py": "", + "resource_file.txt": "", + "sub1": { + "__init__.py": "", + "mod1.py": "", + }, + "_sub2": { + "mod2.py": "", + }, + }, + }, + "other": { + "__init__.py": "", + "mod3.py": "", + }, + "MANIFEST.in": DALS( + """ + global-include *.py *.txt + global-exclude *.py[cod] + """ + ), +} + + +def test_get_outputs(tmpdir_cwd): + jaraco.path.build(EXAMPLE_ARBITRARY_MAPPING) + dist = Distribution({"script_name": "%test%"}) + dist.parse_config_files() + + build_py = dist.get_command_obj("build_py") + build_py.editable_mode = True + build_py.ensure_finalized() + build_lib = build_py.build_lib.replace(os.sep, "/") + outputs = {x.replace(os.sep, "/") for x in build_py.get_outputs()} + assert outputs == { + f"{build_lib}/mypkg/__init__.py", + f"{build_lib}/mypkg/resource_file.txt", + f"{build_lib}/mypkg/sub1/__init__.py", + f"{build_lib}/mypkg/sub1/mod1.py", + f"{build_lib}/mypkg/sub2/mod2.py", + f"{build_lib}/mypkg/sub2/nested/__init__.py", + f"{build_lib}/mypkg/sub2/nested/mod3.py", + } + mapping = { + k.replace(os.sep, "/"): v.replace(os.sep, "/") + for k, v in build_py.get_output_mapping().items() + } + assert mapping == { + f"{build_lib}/mypkg/__init__.py": "src/mypkg/__init__.py", + f"{build_lib}/mypkg/resource_file.txt": "src/mypkg/resource_file.txt", + f"{build_lib}/mypkg/sub1/__init__.py": "src/mypkg/sub1/__init__.py", + f"{build_lib}/mypkg/sub1/mod1.py": "src/mypkg/sub1/mod1.py", + f"{build_lib}/mypkg/sub2/mod2.py": "src/mypkg/_sub2/mod2.py", + f"{build_lib}/mypkg/sub2/nested/__init__.py": "other/__init__.py", + f"{build_lib}/mypkg/sub2/nested/mod3.py": "other/mod3.py", + } + + +class TestTypeInfoFiles: + PYPROJECTS = { + "default_pyproject": DALS( + """ + [project] + name = "foo" + version = "1" + """ + ), + "dont_include_package_data": DALS( + """ + [project] + name = "foo" + version = "1" + + [tool.setuptools] + include-package-data = false + """ + ), + "exclude_type_info": DALS( + """ + [project] + name = "foo" + version = "1" + + [tool.setuptools] + include-package-data = false + + [tool.setuptools.exclude-package-data] + "*" = ["py.typed", "*.pyi"] + """ + ), + } + + EXAMPLES = { + "simple_namespace": { + "directory_structure": { + "foo": { + "bar.pyi": "", + "py.typed": "", + "__init__.py": "", + } + }, + "expected_type_files": {"foo/bar.pyi", "foo/py.typed"}, + }, + "nested_inside_namespace": { + "directory_structure": { + "foo": { + "bar": { + "py.typed": "", + "mod.pyi": "", + } + } + }, + "expected_type_files": {"foo/bar/mod.pyi", "foo/bar/py.typed"}, + }, + "namespace_nested_inside_regular": { + "directory_structure": { + "foo": { + "namespace": { + "foo.pyi": "", + }, + "__init__.pyi": "", + "py.typed": "", + } + }, + "expected_type_files": { + "foo/namespace/foo.pyi", + "foo/__init__.pyi", + "foo/py.typed", + }, + }, + } + + @pytest.mark.parametrize( + "pyproject", + [ + "default_pyproject", + pytest.param( + "dont_include_package_data", + marks=pytest.mark.xfail(reason="pypa/setuptools#4350"), + ), + ], + ) + @pytest.mark.parametrize("example", EXAMPLES.keys()) + def test_type_files_included_by_default(self, tmpdir_cwd, pyproject, example): + structure = { + **self.EXAMPLES[example]["directory_structure"], + "pyproject.toml": self.PYPROJECTS[pyproject], + } + expected_type_files = self.EXAMPLES[example]["expected_type_files"] + jaraco.path.build(structure) + + build_py = get_finalized_build_py() + outputs = get_outputs(build_py) + assert expected_type_files <= outputs + + @pytest.mark.parametrize("pyproject", ["exclude_type_info"]) + @pytest.mark.parametrize("example", EXAMPLES.keys()) + def test_type_files_can_be_excluded(self, tmpdir_cwd, pyproject, example): + structure = { + **self.EXAMPLES[example]["directory_structure"], + "pyproject.toml": self.PYPROJECTS[pyproject], + } + expected_type_files = self.EXAMPLES[example]["expected_type_files"] + jaraco.path.build(structure) + + build_py = get_finalized_build_py() + outputs = get_outputs(build_py) + assert expected_type_files.isdisjoint(outputs) + + def test_stub_only_package(self, tmpdir_cwd): + structure = { + "pyproject.toml": DALS( + """ + [project] + name = "foo-stubs" + version = "1" + """ + ), + "foo-stubs": {"__init__.pyi": "", "bar.pyi": ""}, + } + expected_type_files = {"foo-stubs/__init__.pyi", "foo-stubs/bar.pyi"} + jaraco.path.build(structure) + + build_py = get_finalized_build_py() + outputs = get_outputs(build_py) + assert expected_type_files <= outputs + + +def get_finalized_build_py(script_name="%build_py-test%"): + dist = Distribution({"script_name": script_name}) + dist.parse_config_files() + build_py = dist.get_command_obj("build_py") + build_py.finalize_options() + return build_py + + +def get_outputs(build_py): + build_dir = Path(build_py.build_lib) + return { + os.path.relpath(x, build_dir).replace(os.sep, "/") + for x in build_py.get_outputs() + } diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/test_config_discovery.py b/.venv/lib/python3.12/site-packages/setuptools/tests/test_config_discovery.py new file mode 100644 index 0000000000000000000000000000000000000000..b5df8203cdb6f9129a65d0c503c4f51e21315b1f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/test_config_discovery.py @@ -0,0 +1,647 @@ +import os +import sys +from configparser import ConfigParser +from itertools import product +from typing import cast + +import jaraco.path +import pytest +from path import Path + +import setuptools # noqa: F401 # force distutils.core to be patched +from setuptools.command.sdist import sdist +from setuptools.discovery import find_package_path, find_parent_package +from setuptools.dist import Distribution +from setuptools.errors import PackageDiscoveryError + +from .contexts import quiet +from .integration.helpers import get_sdist_members, get_wheel_members, run +from .textwrap import DALS + +import distutils.core + + +class TestFindParentPackage: + def test_single_package(self, tmp_path): + # find_parent_package should find a non-namespace parent package + (tmp_path / "src/namespace/pkg/nested").mkdir(exist_ok=True, parents=True) + (tmp_path / "src/namespace/pkg/nested/__init__.py").touch() + (tmp_path / "src/namespace/pkg/__init__.py").touch() + packages = ["namespace", "namespace.pkg", "namespace.pkg.nested"] + assert find_parent_package(packages, {"": "src"}, tmp_path) == "namespace.pkg" + + def test_multiple_toplevel(self, tmp_path): + # find_parent_package should return null if the given list of packages does not + # have a single parent package + multiple = ["pkg", "pkg1", "pkg2"] + for name in multiple: + (tmp_path / f"src/{name}").mkdir(exist_ok=True, parents=True) + (tmp_path / f"src/{name}/__init__.py").touch() + assert find_parent_package(multiple, {"": "src"}, tmp_path) is None + + +class TestDiscoverPackagesAndPyModules: + """Make sure discovered values for ``packages`` and ``py_modules`` work + similarly to explicit configuration for the simple scenarios. + """ + + OPTIONS = { + # Different options according to the circumstance being tested + "explicit-src": {"package_dir": {"": "src"}, "packages": ["pkg"]}, + "variation-lib": { + "package_dir": {"": "lib"}, # variation of the source-layout + }, + "explicit-flat": {"packages": ["pkg"]}, + "explicit-single_module": {"py_modules": ["pkg"]}, + "explicit-namespace": {"packages": ["ns", "ns.pkg"]}, + "automatic-src": {}, + "automatic-flat": {}, + "automatic-single_module": {}, + "automatic-namespace": {}, + } + FILES = { + "src": ["src/pkg/__init__.py", "src/pkg/main.py"], + "lib": ["lib/pkg/__init__.py", "lib/pkg/main.py"], + "flat": ["pkg/__init__.py", "pkg/main.py"], + "single_module": ["pkg.py"], + "namespace": ["ns/pkg/__init__.py"], + } + + def _get_info(self, circumstance): + _, _, layout = circumstance.partition("-") + files = self.FILES[layout] + options = self.OPTIONS[circumstance] + return files, options + + @pytest.mark.parametrize("circumstance", OPTIONS.keys()) + def test_sdist_filelist(self, tmp_path, circumstance): + files, options = self._get_info(circumstance) + _populate_project_dir(tmp_path, files, options) + + _, cmd = _run_sdist_programatically(tmp_path, options) + + manifest = [f.replace(os.sep, "/") for f in cmd.filelist.files] + for file in files: + assert any(f.endswith(file) for f in manifest) + + @pytest.mark.parametrize("circumstance", OPTIONS.keys()) + def test_project(self, tmp_path, circumstance): + files, options = self._get_info(circumstance) + _populate_project_dir(tmp_path, files, options) + + # Simulate a pre-existing `build` directory + (tmp_path / "build").mkdir() + (tmp_path / "build/lib").mkdir() + (tmp_path / "build/bdist.linux-x86_64").mkdir() + (tmp_path / "build/bdist.linux-x86_64/file.py").touch() + (tmp_path / "build/lib/__init__.py").touch() + (tmp_path / "build/lib/file.py").touch() + (tmp_path / "dist").mkdir() + (tmp_path / "dist/file.py").touch() + + _run_build(tmp_path) + + sdist_files = get_sdist_members(next(tmp_path.glob("dist/*.tar.gz"))) + print("~~~~~ sdist_members ~~~~~") + print('\n'.join(sdist_files)) + assert sdist_files >= set(files) + + wheel_files = get_wheel_members(next(tmp_path.glob("dist/*.whl"))) + print("~~~~~ wheel_members ~~~~~") + print('\n'.join(wheel_files)) + orig_files = {f.replace("src/", "").replace("lib/", "") for f in files} + assert wheel_files >= orig_files + + # Make sure build files are not included by mistake + for file in wheel_files: + assert "build" not in files + assert "dist" not in files + + PURPOSEFULLY_EMPY = { + "setup.cfg": DALS( + """ + [metadata] + name = myproj + version = 0.0.0 + + [options] + {param} = + """ + ), + "setup.py": DALS( + """ + __import__('setuptools').setup( + name="myproj", + version="0.0.0", + {param}=[] + ) + """ + ), + "pyproject.toml": DALS( + """ + [build-system] + requires = [] + build-backend = 'setuptools.build_meta' + + [project] + name = "myproj" + version = "0.0.0" + + [tool.setuptools] + {param} = [] + """ + ), + "template-pyproject.toml": DALS( + """ + [build-system] + requires = [] + build-backend = 'setuptools.build_meta' + """ + ), + } + + @pytest.mark.parametrize( + ("config_file", "param", "circumstance"), + product( + ["setup.cfg", "setup.py", "pyproject.toml"], + ["packages", "py_modules"], + FILES.keys(), + ), + ) + def test_purposefully_empty(self, tmp_path, config_file, param, circumstance): + files = self.FILES[circumstance] + ["mod.py", "other.py", "src/pkg/__init__.py"] + _populate_project_dir(tmp_path, files, {}) + + if config_file == "pyproject.toml": + template_param = param.replace("_", "-") + else: + # Make sure build works with or without setup.cfg + pyproject = self.PURPOSEFULLY_EMPY["template-pyproject.toml"] + (tmp_path / "pyproject.toml").write_text(pyproject, encoding="utf-8") + template_param = param + + config = self.PURPOSEFULLY_EMPY[config_file].format(param=template_param) + (tmp_path / config_file).write_text(config, encoding="utf-8") + + dist = _get_dist(tmp_path, {}) + # When either parameter package or py_modules is an empty list, + # then there should be no discovery + assert getattr(dist, param) == [] + other = {"py_modules": "packages", "packages": "py_modules"}[param] + assert getattr(dist, other) is None + + @pytest.mark.parametrize( + ("extra_files", "pkgs"), + [ + (["venv/bin/simulate_venv"], {"pkg"}), + (["pkg-stubs/__init__.pyi"], {"pkg", "pkg-stubs"}), + (["other-stubs/__init__.pyi"], {"pkg", "other-stubs"}), + ( + # Type stubs can also be namespaced + ["namespace-stubs/pkg/__init__.pyi"], + {"pkg", "namespace-stubs", "namespace-stubs.pkg"}, + ), + ( + # Just the top-level package can have `-stubs`, ignore nested ones + ["namespace-stubs/pkg-stubs/__init__.pyi"], + {"pkg", "namespace-stubs"}, + ), + (["_hidden/file.py"], {"pkg"}), + (["news/finalize.py"], {"pkg"}), + ], + ) + def test_flat_layout_with_extra_files(self, tmp_path, extra_files, pkgs): + files = self.FILES["flat"] + extra_files + _populate_project_dir(tmp_path, files, {}) + dist = _get_dist(tmp_path, {}) + assert set(dist.packages) == pkgs + + @pytest.mark.parametrize( + "extra_files", + [ + ["other/__init__.py"], + ["other/finalize.py"], + ], + ) + def test_flat_layout_with_dangerous_extra_files(self, tmp_path, extra_files): + files = self.FILES["flat"] + extra_files + _populate_project_dir(tmp_path, files, {}) + with pytest.raises(PackageDiscoveryError, match="multiple (packages|modules)"): + _get_dist(tmp_path, {}) + + def test_flat_layout_with_single_module(self, tmp_path): + files = self.FILES["single_module"] + ["invalid-module-name.py"] + _populate_project_dir(tmp_path, files, {}) + dist = _get_dist(tmp_path, {}) + assert set(dist.py_modules) == {"pkg"} + + def test_flat_layout_with_multiple_modules(self, tmp_path): + files = self.FILES["single_module"] + ["valid_module_name.py"] + _populate_project_dir(tmp_path, files, {}) + with pytest.raises(PackageDiscoveryError, match="multiple (packages|modules)"): + _get_dist(tmp_path, {}) + + def test_py_modules_when_wheel_dir_is_cwd(self, tmp_path): + """Regression for issue 3692""" + from setuptools import build_meta + + pyproject = '[project]\nname = "test"\nversion = "1"' + (tmp_path / "pyproject.toml").write_text(DALS(pyproject), encoding="utf-8") + (tmp_path / "foo.py").touch() + with jaraco.path.DirectoryStack().context(tmp_path): + build_meta.build_wheel(".") + # Ensure py_modules are found + wheel_files = get_wheel_members(next(tmp_path.glob("*.whl"))) + assert "foo.py" in wheel_files + + +class TestNoConfig: + DEFAULT_VERSION = "0.0.0" # Default version given by setuptools + + EXAMPLES = { + "pkg1": ["src/pkg1.py"], + "pkg2": ["src/pkg2/__init__.py"], + "pkg3": ["src/pkg3/__init__.py", "src/pkg3-stubs/__init__.py"], + "pkg4": ["pkg4/__init__.py", "pkg4-stubs/__init__.py"], + "ns.nested.pkg1": ["src/ns/nested/pkg1/__init__.py"], + "ns.nested.pkg2": ["ns/nested/pkg2/__init__.py"], + } + + @pytest.mark.parametrize("example", EXAMPLES.keys()) + def test_discover_name(self, tmp_path, example): + _populate_project_dir(tmp_path, self.EXAMPLES[example], {}) + dist = _get_dist(tmp_path, {}) + assert dist.get_name() == example + + def test_build_with_discovered_name(self, tmp_path): + files = ["src/ns/nested/pkg/__init__.py"] + _populate_project_dir(tmp_path, files, {}) + _run_build(tmp_path, "--sdist") + # Expected distribution file + dist_file = tmp_path / f"dist/ns_nested_pkg-{self.DEFAULT_VERSION}.tar.gz" + assert dist_file.is_file() + + +class TestWithAttrDirective: + @pytest.mark.parametrize( + ("folder", "opts"), + [ + ("src", {}), + ("lib", {"packages": "find:", "packages.find": {"where": "lib"}}), + ], + ) + def test_setupcfg_metadata(self, tmp_path, folder, opts): + files = [f"{folder}/pkg/__init__.py", "setup.cfg"] + _populate_project_dir(tmp_path, files, opts) + + config = (tmp_path / "setup.cfg").read_text(encoding="utf-8") + overwrite = { + folder: {"pkg": {"__init__.py": "version = 42"}}, + "setup.cfg": "[metadata]\nversion = attr: pkg.version\n" + config, + } + jaraco.path.build(overwrite, prefix=tmp_path) + + dist = _get_dist(tmp_path, {}) + assert dist.get_name() == "pkg" + assert dist.get_version() == "42" + assert dist.package_dir + package_path = find_package_path("pkg", dist.package_dir, tmp_path) + assert os.path.exists(package_path) + assert folder in Path(package_path).parts() + + _run_build(tmp_path, "--sdist") + dist_file = tmp_path / "dist/pkg-42.tar.gz" + assert dist_file.is_file() + + def test_pyproject_metadata(self, tmp_path): + _populate_project_dir(tmp_path, ["src/pkg/__init__.py"], {}) + + overwrite = { + "src": {"pkg": {"__init__.py": "version = 42"}}, + "pyproject.toml": ( + "[project]\nname = 'pkg'\ndynamic = ['version']\n" + "[tool.setuptools.dynamic]\nversion = {attr = 'pkg.version'}\n" + ), + } + jaraco.path.build(overwrite, prefix=tmp_path) + + dist = _get_dist(tmp_path, {}) + assert dist.get_version() == "42" + assert dist.package_dir == {"": "src"} + + +class TestWithCExtension: + def _simulate_package_with_extension(self, tmp_path): + # This example is based on: https://github.com/nucleic/kiwi/tree/1.4.0 + files = [ + "benchmarks/file.py", + "docs/Makefile", + "docs/requirements.txt", + "docs/source/conf.py", + "proj/header.h", + "proj/file.py", + "py/proj.cpp", + "py/other.cpp", + "py/file.py", + "py/py.typed", + "py/tests/test_proj.py", + "README.rst", + ] + _populate_project_dir(tmp_path, files, {}) + + setup_script = """ + from setuptools import Extension, setup + + ext_modules = [ + Extension( + "proj", + ["py/proj.cpp", "py/other.cpp"], + include_dirs=["."], + language="c++", + ), + ] + setup(ext_modules=ext_modules) + """ + (tmp_path / "setup.py").write_text(DALS(setup_script), encoding="utf-8") + + def test_skip_discovery_with_setupcfg_metadata(self, tmp_path): + """Ensure that auto-discovery is not triggered when the project is based on + C-extensions only, for backward compatibility. + """ + self._simulate_package_with_extension(tmp_path) + + pyproject = """ + [build-system] + requires = [] + build-backend = 'setuptools.build_meta' + """ + (tmp_path / "pyproject.toml").write_text(DALS(pyproject), encoding="utf-8") + + setupcfg = """ + [metadata] + name = proj + version = 42 + """ + (tmp_path / "setup.cfg").write_text(DALS(setupcfg), encoding="utf-8") + + dist = _get_dist(tmp_path, {}) + assert dist.get_name() == "proj" + assert dist.get_version() == "42" + assert dist.py_modules is None + assert dist.packages is None + assert len(dist.ext_modules) == 1 + assert dist.ext_modules[0].name == "proj" + + def test_dont_skip_discovery_with_pyproject_metadata(self, tmp_path): + """When opting-in to pyproject.toml metadata, auto-discovery will be active if + the package lists C-extensions, but does not configure py-modules or packages. + + This way we ensure users with complex package layouts that would lead to the + discovery of multiple top-level modules/packages see errors and are forced to + explicitly set ``packages`` or ``py-modules``. + """ + self._simulate_package_with_extension(tmp_path) + + pyproject = """ + [project] + name = 'proj' + version = '42' + """ + (tmp_path / "pyproject.toml").write_text(DALS(pyproject), encoding="utf-8") + with pytest.raises(PackageDiscoveryError, match="multiple (packages|modules)"): + _get_dist(tmp_path, {}) + + +class TestWithPackageData: + def _simulate_package_with_data_files(self, tmp_path, src_root): + files = [ + f"{src_root}/proj/__init__.py", + f"{src_root}/proj/file1.txt", + f"{src_root}/proj/nested/file2.txt", + ] + _populate_project_dir(tmp_path, files, {}) + + manifest = """ + global-include *.py *.txt + """ + (tmp_path / "MANIFEST.in").write_text(DALS(manifest), encoding="utf-8") + + EXAMPLE_SETUPCFG = """ + [metadata] + name = proj + version = 42 + + [options] + include_package_data = True + """ + EXAMPLE_PYPROJECT = """ + [project] + name = "proj" + version = "42" + """ + + PYPROJECT_PACKAGE_DIR = """ + [tool.setuptools] + package-dir = {"" = "src"} + """ + + @pytest.mark.parametrize( + ("src_root", "files"), + [ + (".", {"setup.cfg": DALS(EXAMPLE_SETUPCFG)}), + (".", {"pyproject.toml": DALS(EXAMPLE_PYPROJECT)}), + ("src", {"setup.cfg": DALS(EXAMPLE_SETUPCFG)}), + ("src", {"pyproject.toml": DALS(EXAMPLE_PYPROJECT)}), + ( + "src", + { + "setup.cfg": DALS(EXAMPLE_SETUPCFG) + + DALS( + """ + packages = find: + package_dir = + =src + + [options.packages.find] + where = src + """ + ) + }, + ), + ( + "src", + { + "pyproject.toml": DALS(EXAMPLE_PYPROJECT) + + DALS( + """ + [tool.setuptools] + package-dir = {"" = "src"} + """ + ) + }, + ), + ], + ) + def test_include_package_data(self, tmp_path, src_root, files): + """ + Make sure auto-discovery does not affect package include_package_data. + See issue #3196. + """ + jaraco.path.build(files, prefix=str(tmp_path)) + self._simulate_package_with_data_files(tmp_path, src_root) + + expected = { + os.path.normpath(f"{src_root}/proj/file1.txt").replace(os.sep, "/"), + os.path.normpath(f"{src_root}/proj/nested/file2.txt").replace(os.sep, "/"), + } + + _run_build(tmp_path) + + sdist_files = get_sdist_members(next(tmp_path.glob("dist/*.tar.gz"))) + print("~~~~~ sdist_members ~~~~~") + print('\n'.join(sdist_files)) + assert sdist_files >= expected + + wheel_files = get_wheel_members(next(tmp_path.glob("dist/*.whl"))) + print("~~~~~ wheel_members ~~~~~") + print('\n'.join(wheel_files)) + orig_files = {f.replace("src/", "").replace("lib/", "") for f in expected} + assert wheel_files >= orig_files + + +def test_compatible_with_numpy_configuration(tmp_path): + files = [ + "dir1/__init__.py", + "dir2/__init__.py", + "file.py", + ] + _populate_project_dir(tmp_path, files, {}) + dist = Distribution({}) + dist.configuration = object() + dist.set_defaults() + assert dist.py_modules is None + assert dist.packages is None + + +def test_name_discovery_doesnt_break_cli(tmpdir_cwd): + jaraco.path.build({"pkg.py": ""}) + dist = Distribution({}) + dist.script_args = ["--name"] + dist.set_defaults() + dist.parse_command_line() # <-- no exception should be raised here. + assert dist.get_name() == "pkg" + + +def test_preserve_explicit_name_with_dynamic_version(tmpdir_cwd, monkeypatch): + """According to #3545 it seems that ``name`` discovery is running, + even when the project already explicitly sets it. + This seems to be related to parsing of dynamic versions (via ``attr`` directive), + which requires the auto-discovery of ``package_dir``. + """ + files = { + "src": { + "pkg": {"__init__.py": "__version__ = 42\n"}, + }, + "pyproject.toml": DALS( + """ + [project] + name = "myproj" # purposefully different from package name + dynamic = ["version"] + [tool.setuptools.dynamic] + version = {"attr" = "pkg.__version__"} + """ + ), + } + jaraco.path.build(files) + dist = Distribution({}) + orig_analyse_name = dist.set_defaults.analyse_name + + def spy_analyse_name(): + # We can check if name discovery was triggered by ensuring the original + # name remains instead of the package name. + orig_analyse_name() + assert dist.get_name() == "myproj" + + monkeypatch.setattr(dist.set_defaults, "analyse_name", spy_analyse_name) + dist.parse_config_files() + assert dist.get_version() == "42" + assert set(dist.packages) == {"pkg"} + + +def _populate_project_dir(root, files, options): + # NOTE: Currently pypa/build will refuse to build the project if no + # `pyproject.toml` or `setup.py` is found. So it is impossible to do + # completely "config-less" projects. + basic = { + "setup.py": "import setuptools\nsetuptools.setup()", + "README.md": "# Example Package", + "LICENSE": "Copyright (c) 2018", + } + jaraco.path.build(basic, prefix=root) + _write_setupcfg(root, options) + paths = (root / f for f in files) + for path in paths: + path.parent.mkdir(exist_ok=True, parents=True) + path.touch() + + +def _write_setupcfg(root, options): + if not options: + print("~~~~~ **NO** setup.cfg ~~~~~") + return + setupcfg = ConfigParser() + setupcfg.add_section("options") + for key, value in options.items(): + if key == "packages.find": + setupcfg.add_section(f"options.{key}") + setupcfg[f"options.{key}"].update(value) + elif isinstance(value, list): + setupcfg["options"][key] = ", ".join(value) + elif isinstance(value, dict): + str_value = "\n".join(f"\t{k} = {v}" for k, v in value.items()) + setupcfg["options"][key] = "\n" + str_value + else: + setupcfg["options"][key] = str(value) + with open(root / "setup.cfg", "w", encoding="utf-8") as f: + setupcfg.write(f) + print("~~~~~ setup.cfg ~~~~~") + print((root / "setup.cfg").read_text(encoding="utf-8")) + + +def _run_build(path, *flags): + cmd = [sys.executable, "-m", "build", "--no-isolation", *flags, str(path)] + return run(cmd, env={'DISTUTILS_DEBUG': ''}) + + +def _get_dist(dist_path, attrs): + root = "/".join(os.path.split(dist_path)) # POSIX-style + + script = dist_path / 'setup.py' + if script.exists(): + with Path(dist_path): + dist = cast( + Distribution, + distutils.core.run_setup("setup.py", {}, stop_after="init"), + ) + else: + dist = Distribution(attrs) + + dist.src_root = root + dist.script_name = "setup.py" + with Path(dist_path): + dist.parse_config_files() + + dist.set_defaults() + return dist + + +def _run_sdist_programatically(dist_path, attrs): + dist = _get_dist(dist_path, attrs) + cmd = sdist(dist) + cmd.ensure_finalized() + assert cmd.distribution.packages or cmd.distribution.py_modules + + with quiet(), Path(dist_path): + cmd.run() + + return dist, cmd diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/test_core_metadata.py b/.venv/lib/python3.12/site-packages/setuptools/tests/test_core_metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..0d925111fa6e611ae919df8bb30bcda0f248c5b6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/test_core_metadata.py @@ -0,0 +1,622 @@ +from __future__ import annotations + +import functools +import importlib +import io +from email import message_from_string +from email.generator import Generator +from email.message import EmailMessage, Message +from email.parser import Parser +from email.policy import EmailPolicy +from inspect import cleandoc +from pathlib import Path +from unittest.mock import Mock + +import jaraco.path +import pytest +from packaging.metadata import Metadata +from packaging.requirements import Requirement + +from setuptools import _reqs, sic +from setuptools._core_metadata import rfc822_escape, rfc822_unescape +from setuptools.command.egg_info import egg_info, write_requirements +from setuptools.config import expand, setupcfg +from setuptools.dist import Distribution + +from .config.downloads import retrieve_file, urls_from_file + +EXAMPLE_BASE_INFO = dict( + name="package", + version="0.0.1", + author="Foo Bar", + author_email="foo@bar.net", + long_description="Long\ndescription", + description="Short description", + keywords=["one", "two"], +) + + +@pytest.mark.parametrize( + ("content", "result"), + ( + pytest.param( + "Just a single line", + None, + id="single_line", + ), + pytest.param( + "Multiline\nText\nwithout\nextra indents\n", + None, + id="multiline", + ), + pytest.param( + "Multiline\n With\n\nadditional\n indentation", + None, + id="multiline_with_indentation", + ), + pytest.param( + " Leading whitespace", + "Leading whitespace", + id="remove_leading_whitespace", + ), + pytest.param( + " Leading whitespace\nIn\n Multiline comment", + "Leading whitespace\nIn\n Multiline comment", + id="remove_leading_whitespace_multiline", + ), + ), +) +def test_rfc822_unescape(content, result): + assert (result or content) == rfc822_unescape(rfc822_escape(content)) + + +def __read_test_cases(): + base = EXAMPLE_BASE_INFO + + params = functools.partial(dict, base) + + return [ + ('Metadata version 1.0', params()), + ( + 'Metadata Version 1.0: Short long description', + params( + long_description='Short long description', + ), + ), + ( + 'Metadata version 1.1: Classifiers', + params( + classifiers=[ + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.7', + 'License :: OSI Approved :: MIT License', + ], + ), + ), + ( + 'Metadata version 1.1: Download URL', + params( + download_url='https://example.com', + ), + ), + ( + 'Metadata Version 1.2: Requires-Python', + params( + python_requires='>=3.7', + ), + ), + pytest.param( + 'Metadata Version 1.2: Project-Url', + params(project_urls=dict(Foo='https://example.bar')), + marks=pytest.mark.xfail( + reason="Issue #1578: project_urls not read", + ), + ), + ( + 'Metadata Version 2.1: Long Description Content Type', + params( + long_description_content_type='text/x-rst; charset=UTF-8', + ), + ), + ( + 'License', + params( + license='MIT', + ), + ), + ( + 'License multiline', + params( + license='This is a long license \nover multiple lines', + ), + ), + pytest.param( + 'Metadata Version 2.1: Provides Extra', + params(provides_extras=['foo', 'bar']), + marks=pytest.mark.xfail(reason="provides_extras not read"), + ), + ( + 'Missing author', + dict( + name='foo', + version='1.0.0', + author_email='snorri@sturluson.name', + ), + ), + ( + 'Missing author e-mail', + dict( + name='foo', + version='1.0.0', + author='Snorri Sturluson', + ), + ), + ( + 'Missing author and e-mail', + dict( + name='foo', + version='1.0.0', + ), + ), + ( + 'Bypass normalized version', + dict( + name='foo', + version=sic('1.0.0a'), + ), + ), + ] + + +@pytest.mark.parametrize(("name", "attrs"), __read_test_cases()) +def test_read_metadata(name, attrs): + dist = Distribution(attrs) + metadata_out = dist.metadata + dist_class = metadata_out.__class__ + + # Write to PKG_INFO and then load into a new metadata object + PKG_INFO = io.StringIO() + + metadata_out.write_pkg_file(PKG_INFO) + PKG_INFO.seek(0) + pkg_info = PKG_INFO.read() + assert _valid_metadata(pkg_info) + + PKG_INFO.seek(0) + metadata_in = dist_class() + metadata_in.read_pkg_file(PKG_INFO) + + tested_attrs = [ + ('name', dist_class.get_name), + ('version', dist_class.get_version), + ('author', dist_class.get_contact), + ('author_email', dist_class.get_contact_email), + ('metadata_version', dist_class.get_metadata_version), + ('provides', dist_class.get_provides), + ('description', dist_class.get_description), + ('long_description', dist_class.get_long_description), + ('download_url', dist_class.get_download_url), + ('keywords', dist_class.get_keywords), + ('platforms', dist_class.get_platforms), + ('obsoletes', dist_class.get_obsoletes), + ('requires', dist_class.get_requires), + ('classifiers', dist_class.get_classifiers), + ('project_urls', lambda s: getattr(s, 'project_urls', {})), + ('provides_extras', lambda s: getattr(s, 'provides_extras', {})), + ] + + for attr, getter in tested_attrs: + assert getter(metadata_in) == getter(metadata_out) + + +def __maintainer_test_cases(): + attrs = {"name": "package", "version": "1.0", "description": "xxx"} + + def merge_dicts(d1, d2): + d1 = d1.copy() + d1.update(d2) + + return d1 + + return [ + ('No author, no maintainer', attrs.copy()), + ( + 'Author (no e-mail), no maintainer', + merge_dicts(attrs, {'author': 'Author Name'}), + ), + ( + 'Author (e-mail), no maintainer', + merge_dicts( + attrs, {'author': 'Author Name', 'author_email': 'author@name.com'} + ), + ), + ( + 'No author, maintainer (no e-mail)', + merge_dicts(attrs, {'maintainer': 'Maintainer Name'}), + ), + ( + 'No author, maintainer (e-mail)', + merge_dicts( + attrs, + { + 'maintainer': 'Maintainer Name', + 'maintainer_email': 'maintainer@name.com', + }, + ), + ), + ( + 'Author (no e-mail), Maintainer (no-email)', + merge_dicts( + attrs, {'author': 'Author Name', 'maintainer': 'Maintainer Name'} + ), + ), + ( + 'Author (e-mail), Maintainer (e-mail)', + merge_dicts( + attrs, + { + 'author': 'Author Name', + 'author_email': 'author@name.com', + 'maintainer': 'Maintainer Name', + 'maintainer_email': 'maintainer@name.com', + }, + ), + ), + ( + 'No author (e-mail), no maintainer (e-mail)', + merge_dicts( + attrs, + { + 'author_email': 'author@name.com', + 'maintainer_email': 'maintainer@name.com', + }, + ), + ), + ('Author unicode', merge_dicts(attrs, {'author': '鉄沢寛'})), + ('Maintainer unicode', merge_dicts(attrs, {'maintainer': 'Jan Łukasiewicz'})), + ] + + +@pytest.mark.parametrize(("name", "attrs"), __maintainer_test_cases()) +def test_maintainer_author(name, attrs, tmpdir): + tested_keys = { + 'author': 'Author', + 'author_email': 'Author-email', + 'maintainer': 'Maintainer', + 'maintainer_email': 'Maintainer-email', + } + + # Generate a PKG-INFO file + dist = Distribution(attrs) + fn = tmpdir.mkdir('pkg_info') + fn_s = str(fn) + + dist.metadata.write_pkg_info(fn_s) + + with open(str(fn.join('PKG-INFO')), 'r', encoding='utf-8') as f: + pkg_info = f.read() + + assert _valid_metadata(pkg_info) + + # Drop blank lines and strip lines from default description + raw_pkg_lines = pkg_info.splitlines() + pkg_lines = list(filter(None, raw_pkg_lines[:-2])) + + pkg_lines_set = set(pkg_lines) + + # Duplicate lines should not be generated + assert len(pkg_lines) == len(pkg_lines_set) + + for fkey, dkey in tested_keys.items(): + val = attrs.get(dkey, None) + if val is None: + for line in pkg_lines: + assert not line.startswith(fkey + ':') + else: + line = f'{fkey}: {val}' + assert line in pkg_lines_set + + +class TestParityWithMetadataFromPyPaWheel: + def base_example(self): + attrs = dict( + **EXAMPLE_BASE_INFO, + # Example with complex requirement definition + python_requires=">=3.8", + install_requires=""" + packaging==23.2 + more-itertools==8.8.0; extra == "other" + jaraco.text==3.7.0 + importlib-resources==5.10.2; python_version<"3.8" + importlib-metadata==6.0.0 ; python_version<"3.8" + colorama>=0.4.4; sys_platform == "win32" + """, + extras_require={ + "testing": """ + pytest >= 6 + pytest-checkdocs >= 2.4 + tomli ; \\ + # Using stdlib when possible + python_version < "3.11" + ini2toml[lite]>=0.9 + """, + "other": [], + }, + ) + # Generate a PKG-INFO file using setuptools + return Distribution(attrs) + + def test_requires_dist(self, tmp_path): + dist = self.base_example() + pkg_info = _get_pkginfo(dist) + assert _valid_metadata(pkg_info) + + # Ensure Requires-Dist is present + expected = [ + 'Metadata-Version:', + 'Requires-Python: >=3.8', + 'Provides-Extra: other', + 'Provides-Extra: testing', + 'Requires-Dist: tomli; python_version < "3.11" and extra == "testing"', + 'Requires-Dist: more-itertools==8.8.0; extra == "other"', + 'Requires-Dist: ini2toml[lite]>=0.9; extra == "testing"', + ] + for line in expected: + assert line in pkg_info + + HERE = Path(__file__).parent + EXAMPLES_FILE = HERE / "config/setupcfg_examples.txt" + + @pytest.fixture(params=[None, *urls_from_file(EXAMPLES_FILE)]) + def dist(self, request, monkeypatch, tmp_path): + """Example of distribution with arbitrary configuration""" + monkeypatch.chdir(tmp_path) + monkeypatch.setattr(expand, "read_attr", Mock(return_value="0.42")) + monkeypatch.setattr(expand, "read_files", Mock(return_value="hello world")) + monkeypatch.setattr( + Distribution, "_finalize_license_files", Mock(return_value=None) + ) + if request.param is None: + yield self.base_example() + else: + # Real-world usage + config = retrieve_file(request.param) + yield setupcfg.apply_configuration(Distribution({}), config) + + @pytest.mark.uses_network + def test_equivalent_output(self, tmp_path, dist): + """Ensure output from setuptools is equivalent to the one from `pypa/wheel`""" + # Generate a METADATA file using pypa/wheel for comparison + wheel_metadata = importlib.import_module("wheel.metadata") + pkginfo_to_metadata = getattr(wheel_metadata, "pkginfo_to_metadata", None) + + if pkginfo_to_metadata is None: # pragma: nocover + pytest.xfail( + "wheel.metadata.pkginfo_to_metadata is undefined, " + "(this is likely to be caused by API changes in pypa/wheel" + ) + + # Generate an simplified "egg-info" dir for pypa/wheel to convert + pkg_info = _get_pkginfo(dist) + egg_info_dir = tmp_path / "pkg.egg-info" + egg_info_dir.mkdir(parents=True) + (egg_info_dir / "PKG-INFO").write_text(pkg_info, encoding="utf-8") + write_requirements(egg_info(dist), egg_info_dir, egg_info_dir / "requires.txt") + + # Get pypa/wheel generated METADATA but normalize requirements formatting + metadata_msg = pkginfo_to_metadata(egg_info_dir, egg_info_dir / "PKG-INFO") + metadata_str = _normalize_metadata(metadata_msg) + pkg_info_msg = message_from_string(pkg_info) + pkg_info_str = _normalize_metadata(pkg_info_msg) + + # Compare setuptools PKG-INFO x pypa/wheel METADATA + assert metadata_str == pkg_info_str + + # Make sure it parses/serializes well in pypa/wheel + _assert_roundtrip_message(pkg_info) + + +class TestPEP643: + STATIC_CONFIG = { + "setup.cfg": cleandoc( + """ + [metadata] + name = package + version = 0.0.1 + author = Foo Bar + author_email = foo@bar.net + long_description = Long + description + description = Short description + keywords = one, two + platforms = abcd + [options] + install_requires = requests + """ + ), + "pyproject.toml": cleandoc( + """ + [project] + name = "package" + version = "0.0.1" + authors = [ + {name = "Foo Bar", email = "foo@bar.net"} + ] + description = "Short description" + readme = {text = "Long\\ndescription", content-type = "text/plain"} + keywords = ["one", "two"] + dependencies = ["requests"] + license = "AGPL-3.0-or-later" + [tool.setuptools] + provides = ["abcd"] + obsoletes = ["abcd"] + """ + ), + } + + @pytest.mark.parametrize("file", STATIC_CONFIG.keys()) + def test_static_config_has_no_dynamic(self, file, tmpdir_cwd): + Path(file).write_text(self.STATIC_CONFIG[file], encoding="utf-8") + metadata = _get_metadata() + assert metadata.get_all("Dynamic") is None + assert metadata.get_all("dynamic") is None + + @pytest.mark.parametrize("file", STATIC_CONFIG.keys()) + @pytest.mark.parametrize( + "fields", + [ + # Single dynamic field + {"requires-python": ("python_requires", ">=3.12")}, + {"author-email": ("author_email", "snoopy@peanuts.com")}, + {"keywords": ("keywords", ["hello", "world"])}, + {"platform": ("platforms", ["abcd"])}, + # Multiple dynamic fields + { + "summary": ("description", "hello world"), + "description": ("long_description", "bla bla bla bla"), + "requires-dist": ("install_requires", ["hello-world"]), + }, + ], + ) + def test_modified_fields_marked_as_dynamic(self, file, fields, tmpdir_cwd): + # We start with a static config + Path(file).write_text(self.STATIC_CONFIG[file], encoding="utf-8") + dist = _makedist() + + # ... but then we simulate the effects of a plugin modifying the distribution + for attr, value in fields.values(): + # `dist` and `dist.metadata` are complicated... + # Some attributes work when set on `dist`, others on `dist.metadata`... + # Here we set in both just in case (this also avoids calling `_finalize_*`) + setattr(dist, attr, value) + setattr(dist.metadata, attr, value) + + # Then we should be able to list the modified fields as Dynamic + metadata = _get_metadata(dist) + assert set(metadata.get_all("Dynamic")) == set(fields) + + @pytest.mark.parametrize( + "extra_toml", + [ + "# Let setuptools autofill license-files", + "license-files = ['LICENSE*', 'AUTHORS*', 'NOTICE']", + ], + ) + def test_license_files_dynamic(self, extra_toml, tmpdir_cwd): + # For simplicity (and for the time being) setuptools is not making + # any special handling to guarantee `License-File` is considered static. + # Instead we rely in the fact that, although suboptimal, it is OK to have + # it as dynamics, as per: + # https://github.com/pypa/setuptools/issues/4629#issuecomment-2331233677 + files = { + "pyproject.toml": self.STATIC_CONFIG["pyproject.toml"].replace( + 'license = "AGPL-3.0-or-later"', + f"dynamic = ['license']\n{extra_toml}", + ), + "LICENSE.md": "--- mock license ---", + "NOTICE": "--- mock notice ---", + "AUTHORS.txt": "--- me ---", + } + # Sanity checks: + assert extra_toml in files["pyproject.toml"] + assert 'license = "AGPL-3.0-or-later"' not in extra_toml + + jaraco.path.build(files) + dist = _makedist(license_expression="AGPL-3.0-or-later") + metadata = _get_metadata(dist) + assert set(metadata.get_all("Dynamic")) == { + 'license-file', + 'license-expression', + } + assert metadata.get("License-Expression") == "AGPL-3.0-or-later" + assert set(metadata.get_all("License-File")) == { + "NOTICE", + "AUTHORS.txt", + "LICENSE.md", + } + + +def _makedist(**attrs): + dist = Distribution(attrs) + dist.parse_config_files() + return dist + + +def _assert_roundtrip_message(metadata: str) -> None: + """Emulate the way wheel.bdist_wheel parses and regenerates the message, + then ensures the metadata generated by setuptools is compatible. + """ + with io.StringIO(metadata) as buffer: + msg = Parser(EmailMessage).parse(buffer) + + serialization_policy = EmailPolicy( + utf8=True, + mangle_from_=False, + max_line_length=0, + ) + with io.BytesIO() as buffer: + out = io.TextIOWrapper(buffer, encoding="utf-8") + Generator(out, policy=serialization_policy).flatten(msg) + out.flush() + regenerated = buffer.getvalue() + + raw_metadata = bytes(metadata, "utf-8") + # Normalise newlines to avoid test errors on Windows: + raw_metadata = b"\n".join(raw_metadata.splitlines()) + regenerated = b"\n".join(regenerated.splitlines()) + assert regenerated == raw_metadata + + +def _normalize_metadata(msg: Message) -> str: + """Allow equivalent metadata to be compared directly""" + # The main challenge regards the requirements and extras. + # Both setuptools and wheel already apply some level of normalization + # but they differ regarding which character is chosen, according to the + # following spec it should be "-": + # https://packaging.python.org/en/latest/specifications/name-normalization/ + + # Related issues: + # https://github.com/pypa/packaging/issues/845 + # https://github.com/pypa/packaging/issues/644#issuecomment-2429813968 + + extras = {x.replace("_", "-"): x for x in msg.get_all("Provides-Extra", [])} + reqs = [ + _normalize_req(req, extras) + for req in _reqs.parse(msg.get_all("Requires-Dist", [])) + ] + del msg["Requires-Dist"] + del msg["Provides-Extra"] + + # Ensure consistent ord + for req in sorted(reqs): + msg["Requires-Dist"] = req + for extra in sorted(extras): + msg["Provides-Extra"] = extra + + # TODO: Handle lack of PEP 643 implementation in pypa/wheel? + del msg["Metadata-Version"] + + return msg.as_string() + + +def _normalize_req(req: Requirement, extras: dict[str, str]) -> str: + """Allow equivalent requirement objects to be compared directly""" + as_str = str(req).replace(req.name, req.name.replace("_", "-")) + for norm, orig in extras.items(): + as_str = as_str.replace(orig, norm) + return as_str + + +def _get_pkginfo(dist: Distribution): + with io.StringIO() as fp: + dist.metadata.write_pkg_file(fp) + return fp.getvalue() + + +def _get_metadata(dist: Distribution | None = None): + return message_from_string(_get_pkginfo(dist or _makedist())) + + +def _valid_metadata(text: str) -> bool: + metadata = Metadata.from_email(text, validate=True) # can raise exceptions + return metadata is not None diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/test_depends.py b/.venv/lib/python3.12/site-packages/setuptools/tests/test_depends.py new file mode 100644 index 0000000000000000000000000000000000000000..1714c041f7a23e1ecbfc3245bf964f75c13734ca --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/test_depends.py @@ -0,0 +1,15 @@ +import sys + +from setuptools import depends + + +class TestGetModuleConstant: + def test_basic(self): + """ + Invoke get_module_constant on a module in + the test package. + """ + mod_name = 'setuptools.tests.mod_with_constant' + val = depends.get_module_constant(mod_name, 'value') + assert val == 'three, sir!' + assert 'setuptools.tests.mod_with_constant' not in sys.modules diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/test_develop.py b/.venv/lib/python3.12/site-packages/setuptools/tests/test_develop.py new file mode 100644 index 0000000000000000000000000000000000000000..929fa9c285eb4d11e646dab2864be6d5fa023e2b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/test_develop.py @@ -0,0 +1,175 @@ +"""develop tests""" + +import os +import pathlib +import platform +import subprocess +import sys + +import pytest + +from setuptools._path import paths_on_pythonpath +from setuptools.command.develop import develop +from setuptools.dist import Distribution + +from . import contexts, namespaces + +SETUP_PY = """\ +from setuptools import setup + +setup(name='foo', + packages=['foo'], +) +""" + +INIT_PY = """print "foo" +""" + + +@pytest.fixture +def temp_user(monkeypatch): + with contexts.tempdir() as user_base: + with contexts.tempdir() as user_site: + monkeypatch.setattr('site.USER_BASE', user_base) + monkeypatch.setattr('site.USER_SITE', user_site) + yield + + +@pytest.fixture +def test_env(tmpdir, temp_user): + target = tmpdir + foo = target.mkdir('foo') + setup = target / 'setup.py' + if setup.isfile(): + raise ValueError(dir(target)) + with setup.open('w') as f: + f.write(SETUP_PY) + init = foo / '__init__.py' + with init.open('w') as f: + f.write(INIT_PY) + with target.as_cwd(): + yield target + + +class TestDevelop: + in_virtualenv = hasattr(sys, 'real_prefix') + in_venv = hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix + + def test_console_scripts(self, tmpdir): + """ + Test that console scripts are installed and that they reference + only the project by name and not the current version. + """ + pytest.skip( + "TODO: needs a fixture to cause 'develop' " + "to be invoked without mutating environment." + ) + settings = dict( + name='foo', + packages=['foo'], + version='0.0', + entry_points={ + 'console_scripts': [ + 'foocmd = foo:foo', + ], + }, + ) + dist = Distribution(settings) + dist.script_name = 'setup.py' + cmd = develop(dist) + cmd.ensure_finalized() + cmd.install_dir = tmpdir + cmd.run() + # assert '0.0' not in foocmd_text + + @pytest.mark.xfail(reason="legacy behavior retained for compatibility #4167") + def test_egg_link_filename(self): + settings = dict( + name='Foo $$$ Bar_baz-bing', + ) + dist = Distribution(settings) + cmd = develop(dist) + cmd.ensure_finalized() + link = pathlib.Path(cmd.egg_link) + assert link.suffix == '.egg-link' + assert link.stem == 'Foo_Bar_baz_bing' + + +class TestResolver: + """ + TODO: These tests were written with a minimal understanding + of what _resolve_setup_path is intending to do. Come up with + more meaningful cases that look like real-world scenarios. + """ + + def test_resolve_setup_path_cwd(self): + assert develop._resolve_setup_path('.', '.', '.') == '.' + + def test_resolve_setup_path_one_dir(self): + assert develop._resolve_setup_path('pkgs', '.', 'pkgs') == '../' + + def test_resolve_setup_path_one_dir_trailing_slash(self): + assert develop._resolve_setup_path('pkgs/', '.', 'pkgs') == '../' + + +class TestNamespaces: + @staticmethod + def install_develop(src_dir, target): + develop_cmd = [ + sys.executable, + 'setup.py', + 'develop', + '--install-dir', + str(target), + ] + with src_dir.as_cwd(): + with paths_on_pythonpath([str(target)]): + subprocess.check_call(develop_cmd) + + @pytest.mark.skipif( + bool(os.environ.get("APPVEYOR")), + reason="https://github.com/pypa/setuptools/issues/851", + ) + @pytest.mark.skipif( + platform.python_implementation() == 'PyPy', + reason="https://github.com/pypa/setuptools/issues/1202", + ) + def test_namespace_package_importable(self, tmpdir): + """ + Installing two packages sharing the same namespace, one installed + naturally using pip or `--single-version-externally-managed` + and the other installed using `develop` should leave the namespace + in tact and both packages reachable by import. + """ + pkg_A = namespaces.build_namespace_package(tmpdir, 'myns.pkgA') + pkg_B = namespaces.build_namespace_package(tmpdir, 'myns.pkgB') + target = tmpdir / 'packages' + # use pip to install to the target directory + install_cmd = [ + sys.executable, + '-m', + 'pip', + 'install', + str(pkg_A), + '-t', + str(target), + ] + subprocess.check_call(install_cmd) + self.install_develop(pkg_B, target) + namespaces.make_site_dir(target) + try_import = [ + sys.executable, + '-c', + 'import myns.pkgA; import myns.pkgB', + ] + with paths_on_pythonpath([str(target)]): + subprocess.check_call(try_import) + + # additionally ensure that pkg_resources import works + pkg_resources_imp = [ + sys.executable, + '-c', + 'import pkg_resources', + ] + with paths_on_pythonpath([str(target)]): + subprocess.check_call(pkg_resources_imp) diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/test_dist.py b/.venv/lib/python3.12/site-packages/setuptools/tests/test_dist.py new file mode 100644 index 0000000000000000000000000000000000000000..e65ab310e7f2ad98b591affb352c855a2f86eda1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/test_dist.py @@ -0,0 +1,278 @@ +import os +import re +import urllib.parse +import urllib.request + +import pytest + +from setuptools import Distribution +from setuptools.dist import check_package_data, check_specifier + +from .test_easy_install import make_trivial_sdist +from .test_find_packages import ensure_files +from .textwrap import DALS + +from distutils.errors import DistutilsSetupError + + +def test_dist_fetch_build_egg(tmpdir): + """ + Check multiple calls to `Distribution.fetch_build_egg` work as expected. + """ + index = tmpdir.mkdir('index') + index_url = urllib.parse.urljoin('file://', urllib.request.pathname2url(str(index))) + + def sdist_with_index(distname, version): + dist_dir = index.mkdir(distname) + dist_sdist = f'{distname}-{version}.tar.gz' + make_trivial_sdist(str(dist_dir.join(dist_sdist)), distname, version) + with dist_dir.join('index.html').open('w') as fp: + fp.write( + DALS( + """ + + {dist_sdist}
+ + """ + ).format(dist_sdist=dist_sdist) + ) + + sdist_with_index('barbazquux', '3.2.0') + sdist_with_index('barbazquux-runner', '2.11.1') + with tmpdir.join('setup.cfg').open('w') as fp: + fp.write( + DALS( + """ + [easy_install] + index_url = {index_url} + """ + ).format(index_url=index_url) + ) + reqs = """ + barbazquux-runner + barbazquux + """.split() + with tmpdir.as_cwd(): + dist = Distribution() + dist.parse_config_files() + resolved_dists = [dist.fetch_build_egg(r) for r in reqs] + assert [dist.key for dist in resolved_dists if dist] == reqs + + +EXAMPLE_BASE_INFO = dict( + name="package", + version="0.0.1", + author="Foo Bar", + author_email="foo@bar.net", + long_description="Long\ndescription", + description="Short description", + keywords=["one", "two"], +) + + +def test_provides_extras_deterministic_order(): + attrs = dict(extras_require=dict(a=['foo'], b=['bar'])) + dist = Distribution(attrs) + assert list(dist.metadata.provides_extras) == ['a', 'b'] + attrs['extras_require'] = dict(reversed(attrs['extras_require'].items())) + dist = Distribution(attrs) + assert list(dist.metadata.provides_extras) == ['b', 'a'] + + +CHECK_PACKAGE_DATA_TESTS = ( + # Valid. + ( + { + '': ['*.txt', '*.rst'], + 'hello': ['*.msg'], + }, + None, + ), + # Not a dictionary. + ( + ( + ('', ['*.txt', '*.rst']), + ('hello', ['*.msg']), + ), + ( + "'package_data' must be a dictionary mapping package" + " names to lists of string wildcard patterns" + ), + ), + # Invalid key type. + ( + { + 400: ['*.txt', '*.rst'], + }, + ("keys of 'package_data' dict must be strings (got 400)"), + ), + # Invalid value type. + ( + { + 'hello': '*.msg', + }, + ( + "\"values of 'package_data' dict\" must be of type " + " (got '*.msg')" + ), + ), + # Invalid value type (generators are single use) + ( + { + 'hello': (x for x in "generator"), + }, + ( + "\"values of 'package_data' dict\" must be of type " + " (got =3.0, !=3.1'} + dist = Distribution(attrs) + check_specifier(dist, attrs, attrs['python_requires']) + + attrs = {'name': 'foo', 'python_requires': ['>=3.0', '!=3.1']} + dist = Distribution(attrs) + check_specifier(dist, attrs, attrs['python_requires']) + + # invalid specifier value + attrs = {'name': 'foo', 'python_requires': '>=invalid-version'} + with pytest.raises(DistutilsSetupError): + dist = Distribution(attrs) + + +def test_metadata_name(): + with pytest.raises(DistutilsSetupError, match='missing.*name'): + Distribution()._validate_metadata() + + +@pytest.mark.parametrize( + ('dist_name', 'py_module'), + [ + ("my.pkg", "my_pkg"), + ("my-pkg", "my_pkg"), + ("my_pkg", "my_pkg"), + ("pkg", "pkg"), + ], +) +def test_dist_default_py_modules(tmp_path, dist_name, py_module): + (tmp_path / f"{py_module}.py").touch() + + (tmp_path / "setup.py").touch() + (tmp_path / "noxfile.py").touch() + # ^-- make sure common tool files are ignored + + attrs = {**EXAMPLE_BASE_INFO, "name": dist_name, "src_root": str(tmp_path)} + # Find `py_modules` corresponding to dist_name if not given + dist = Distribution(attrs) + dist.set_defaults() + assert dist.py_modules == [py_module] + # When `py_modules` is given, don't do anything + dist = Distribution({**attrs, "py_modules": ["explicity_py_module"]}) + dist.set_defaults() + assert dist.py_modules == ["explicity_py_module"] + # When `packages` is given, don't do anything + dist = Distribution({**attrs, "packages": ["explicity_package"]}) + dist.set_defaults() + assert not dist.py_modules + + +@pytest.mark.parametrize( + ('dist_name', 'package_dir', 'package_files', 'packages'), + [ + ("my.pkg", None, ["my_pkg/__init__.py", "my_pkg/mod.py"], ["my_pkg"]), + ("my-pkg", None, ["my_pkg/__init__.py", "my_pkg/mod.py"], ["my_pkg"]), + ("my_pkg", None, ["my_pkg/__init__.py", "my_pkg/mod.py"], ["my_pkg"]), + ("my.pkg", None, ["my/pkg/__init__.py"], ["my", "my.pkg"]), + ( + "my_pkg", + None, + ["src/my_pkg/__init__.py", "src/my_pkg2/__init__.py"], + ["my_pkg", "my_pkg2"], + ), + ( + "my_pkg", + {"pkg": "lib", "pkg2": "lib2"}, + ["lib/__init__.py", "lib/nested/__init__.pyt", "lib2/__init__.py"], + ["pkg", "pkg.nested", "pkg2"], + ), + ], +) +def test_dist_default_packages( + tmp_path, dist_name, package_dir, package_files, packages +): + ensure_files(tmp_path, package_files) + + (tmp_path / "setup.py").touch() + (tmp_path / "noxfile.py").touch() + # ^-- should not be included by default + + attrs = { + **EXAMPLE_BASE_INFO, + "name": dist_name, + "src_root": str(tmp_path), + "package_dir": package_dir, + } + # Find `packages` either corresponding to dist_name or inside src + dist = Distribution(attrs) + dist.set_defaults() + assert not dist.py_modules + assert not dist.py_modules + assert set(dist.packages) == set(packages) + # When `py_modules` is given, don't do anything + dist = Distribution({**attrs, "py_modules": ["explicit_py_module"]}) + dist.set_defaults() + assert not dist.packages + assert set(dist.py_modules) == {"explicit_py_module"} + # When `packages` is given, don't do anything + dist = Distribution({**attrs, "packages": ["explicit_package"]}) + dist.set_defaults() + assert not dist.py_modules + assert set(dist.packages) == {"explicit_package"} + + +@pytest.mark.parametrize( + ('dist_name', 'package_dir', 'package_files'), + [ + ("my.pkg.nested", None, ["my/pkg/nested/__init__.py"]), + ("my.pkg", None, ["my/pkg/__init__.py", "my/pkg/file.py"]), + ("my_pkg", None, ["my_pkg.py"]), + ("my_pkg", None, ["my_pkg/__init__.py", "my_pkg/nested/__init__.py"]), + ("my_pkg", None, ["src/my_pkg/__init__.py", "src/my_pkg/nested/__init__.py"]), + ( + "my_pkg", + {"my_pkg": "lib", "my_pkg.lib2": "lib2"}, + ["lib/__init__.py", "lib/nested/__init__.pyt", "lib2/__init__.py"], + ), + # Should not try to guess a name from multiple py_modules/packages + ("UNKNOWN", None, ["src/mod1.py", "src/mod2.py"]), + ("UNKNOWN", None, ["src/pkg1/__ini__.py", "src/pkg2/__init__.py"]), + ], +) +def test_dist_default_name(tmp_path, dist_name, package_dir, package_files): + """Make sure dist.name is discovered from packages/py_modules""" + ensure_files(tmp_path, package_files) + attrs = { + **EXAMPLE_BASE_INFO, + "src_root": "/".join(os.path.split(tmp_path)), # POSIX-style + "package_dir": package_dir, + } + del attrs["name"] + + dist = Distribution(attrs) + dist.set_defaults() + assert dist.py_modules or dist.packages + assert dist.get_name() == dist_name diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/test_dist_info.py b/.venv/lib/python3.12/site-packages/setuptools/tests/test_dist_info.py new file mode 100644 index 0000000000000000000000000000000000000000..426694e0198fdbe6ee7466822bc7c15634e2b648 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/test_dist_info.py @@ -0,0 +1,210 @@ +"""Test .dist-info style distributions.""" + +import pathlib +import re +import shutil +import subprocess +import sys +from functools import partial + +import pytest + +import pkg_resources +from setuptools.archive_util import unpack_archive + +from .textwrap import DALS + +read = partial(pathlib.Path.read_text, encoding="utf-8") + + +class TestDistInfo: + metadata_base = DALS( + """ + Metadata-Version: 1.2 + Requires-Dist: splort (==4) + Provides-Extra: baz + Requires-Dist: quux (>=1.1); extra == 'baz' + """ + ) + + @classmethod + def build_metadata(cls, **kwargs): + lines = ('{key}: {value}\n'.format(**locals()) for key, value in kwargs.items()) + return cls.metadata_base + ''.join(lines) + + @pytest.fixture + def metadata(self, tmpdir): + dist_info_name = 'VersionedDistribution-2.718.dist-info' + versioned = tmpdir / dist_info_name + versioned.mkdir() + filename = versioned / 'METADATA' + content = self.build_metadata( + Name='VersionedDistribution', + ) + filename.write_text(content, encoding='utf-8') + + dist_info_name = 'UnversionedDistribution.dist-info' + unversioned = tmpdir / dist_info_name + unversioned.mkdir() + filename = unversioned / 'METADATA' + content = self.build_metadata( + Name='UnversionedDistribution', + Version='0.3', + ) + filename.write_text(content, encoding='utf-8') + + return str(tmpdir) + + def test_distinfo(self, metadata): + dists = dict( + (d.project_name, d) for d in pkg_resources.find_distributions(metadata) + ) + + assert len(dists) == 2, dists + + unversioned = dists['UnversionedDistribution'] + versioned = dists['VersionedDistribution'] + + assert versioned.version == '2.718' # from filename + assert unversioned.version == '0.3' # from METADATA + + def test_conditional_dependencies(self, metadata): + specs = 'splort==4', 'quux>=1.1' + requires = list(map(pkg_resources.Requirement.parse, specs)) + + for d in pkg_resources.find_distributions(metadata): + assert d.requires() == requires[:1] + assert d.requires(extras=('baz',)) == [ + requires[0], + pkg_resources.Requirement.parse('quux>=1.1;extra=="baz"'), + ] + assert d.extras == ['baz'] + + def test_invalid_version(self, tmp_path): + """ + Supplying an invalid version crashes dist_info. + """ + config = "[metadata]\nname=proj\nversion=42\n[egg_info]\ntag_build=invalid!!!\n" + (tmp_path / "setup.cfg").write_text(config, encoding="utf-8") + msg = re.compile("invalid version", re.M | re.I) + proc = run_command_inner("dist_info", cwd=tmp_path, check=False) + assert proc.returncode + assert msg.search(proc.stdout) + assert not list(tmp_path.glob("*.dist-info")) + + def test_tag_arguments(self, tmp_path): + config = """ + [metadata] + name=proj + version=42 + [egg_info] + tag_date=1 + tag_build=.post + """ + (tmp_path / "setup.cfg").write_text(config, encoding="utf-8") + + print(run_command("dist_info", "--no-date", cwd=tmp_path)) + dist_info = next(tmp_path.glob("*.dist-info")) + assert dist_info.name.startswith("proj-42") + shutil.rmtree(dist_info) + + print(run_command("dist_info", "--tag-build", ".a", cwd=tmp_path)) + dist_info = next(tmp_path.glob("*.dist-info")) + assert dist_info.name.startswith("proj-42a") + + @pytest.mark.parametrize("keep_egg_info", (False, True)) + def test_output_dir(self, tmp_path, keep_egg_info): + config = "[metadata]\nname=proj\nversion=42\n" + (tmp_path / "setup.cfg").write_text(config, encoding="utf-8") + out = tmp_path / "__out" + out.mkdir() + opts = ["--keep-egg-info"] if keep_egg_info else [] + run_command("dist_info", "--output-dir", out, *opts, cwd=tmp_path) + assert len(list(out.glob("*.dist-info"))) == 1 + assert len(list(tmp_path.glob("*.dist-info"))) == 0 + expected_egg_info = int(keep_egg_info) + assert len(list(out.glob("*.egg-info"))) == expected_egg_info + assert len(list(tmp_path.glob("*.egg-info"))) == 0 + assert len(list(out.glob("*.__bkp__"))) == 0 + assert len(list(tmp_path.glob("*.__bkp__"))) == 0 + + +class TestWheelCompatibility: + """Make sure the .dist-info directory produced with the ``dist_info`` command + is the same as the one produced by ``bdist_wheel``. + """ + + SETUPCFG = DALS( + """ + [metadata] + name = {name} + version = {version} + + [options] + install_requires = + foo>=12; sys_platform != "linux" + + [options.extras_require] + test = pytest + + [options.entry_points] + console_scripts = + executable-name = my_package.module:function + discover = + myproj = my_package.other_module:function + """ + ) + + EGG_INFO_OPTS = [ + # Related: #3088 #2872 + ("", ""), + (".post", "[egg_info]\ntag_build = post\n"), + (".post", "[egg_info]\ntag_build = .post\n"), + (".post", "[egg_info]\ntag_build = post\ntag_date = 1\n"), + (".dev", "[egg_info]\ntag_build = .dev\n"), + (".dev", "[egg_info]\ntag_build = .dev\ntag_date = 1\n"), + ("a1", "[egg_info]\ntag_build = .a1\n"), + ("+local", "[egg_info]\ntag_build = +local\n"), + ] + + @pytest.mark.parametrize("name", "my-proj my_proj my.proj My.Proj".split()) + @pytest.mark.parametrize("version", ["0.42.13"]) + @pytest.mark.parametrize(("suffix", "cfg"), EGG_INFO_OPTS) + def test_dist_info_is_the_same_as_in_wheel( + self, name, version, tmp_path, suffix, cfg + ): + config = self.SETUPCFG.format(name=name, version=version) + cfg + + for i in "dir_wheel", "dir_dist": + (tmp_path / i).mkdir() + (tmp_path / i / "setup.cfg").write_text(config, encoding="utf-8") + + run_command("bdist_wheel", cwd=tmp_path / "dir_wheel") + wheel = next(tmp_path.glob("dir_wheel/dist/*.whl")) + unpack_archive(wheel, tmp_path / "unpack") + wheel_dist_info = next(tmp_path.glob("unpack/*.dist-info")) + + run_command("dist_info", cwd=tmp_path / "dir_dist") + dist_info = next(tmp_path.glob("dir_dist/*.dist-info")) + + assert dist_info.name == wheel_dist_info.name + assert dist_info.name.startswith(f"my_proj-{version}{suffix}") + for file in "METADATA", "entry_points.txt": + assert read(dist_info / file) == read(wheel_dist_info / file) + + +def run_command_inner(*cmd, **kwargs): + opts = { + "stderr": subprocess.STDOUT, + "stdout": subprocess.PIPE, + "text": True, + "encoding": "utf-8", + "check": True, + **kwargs, + } + cmd = [sys.executable, "-c", "__import__('setuptools').setup()", *map(str, cmd)] + return subprocess.run(cmd, **opts) + + +def run_command(*args, **kwargs): + return run_command_inner(*args, **kwargs).stdout diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/test_distutils_adoption.py b/.venv/lib/python3.12/site-packages/setuptools/tests/test_distutils_adoption.py new file mode 100644 index 0000000000000000000000000000000000000000..f99a58849950029f53322c19cde1c171fe26622c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/test_distutils_adoption.py @@ -0,0 +1,198 @@ +import os +import platform +import sys +import textwrap + +import pytest + +IS_PYPY = '__pypy__' in sys.builtin_module_names + +_TEXT_KWARGS = {"text": True, "encoding": "utf-8"} # For subprocess.run + + +def win_sr(env): + """ + On Windows, SYSTEMROOT must be present to avoid + + > Fatal Python error: _Py_HashRandomization_Init: failed to + > get random numbers to initialize Python + """ + if env and platform.system() == 'Windows': + env['SYSTEMROOT'] = os.environ['SYSTEMROOT'] + return env + + +def find_distutils(venv, imports='distutils', env=None, **kwargs): + py_cmd = 'import {imports}; print(distutils.__file__)'.format(**locals()) + cmd = ['python', '-c', py_cmd] + return venv.run(cmd, env=win_sr(env), **_TEXT_KWARGS, **kwargs) + + +def count_meta_path(venv, env=None): + py_cmd = textwrap.dedent( + """ + import sys + is_distutils = lambda finder: finder.__class__.__name__ == "DistutilsMetaFinder" + print(len(list(filter(is_distutils, sys.meta_path)))) + """ + ) + cmd = ['python', '-c', py_cmd] + return int(venv.run(cmd, env=win_sr(env), **_TEXT_KWARGS)) + + +skip_without_stdlib_distutils = pytest.mark.skipif( + sys.version_info >= (3, 12), + reason='stdlib distutils is removed from Python 3.12+', +) + + +@skip_without_stdlib_distutils +def test_distutils_stdlib(venv): + """ + Ensure stdlib distutils is used when appropriate. + """ + env = dict(SETUPTOOLS_USE_DISTUTILS='stdlib') + assert venv.name not in find_distutils(venv, env=env).split(os.sep) + assert count_meta_path(venv, env=env) == 0 + + +def test_distutils_local_with_setuptools(venv): + """ + Ensure local distutils is used when appropriate. + """ + env = dict(SETUPTOOLS_USE_DISTUTILS='local') + loc = find_distutils(venv, imports='setuptools, distutils', env=env) + assert venv.name in loc.split(os.sep) + assert count_meta_path(venv, env=env) <= 1 + + +@pytest.mark.xfail('IS_PYPY', reason='pypy imports distutils on startup') +def test_distutils_local(venv): + """ + Even without importing, the setuptools-local copy of distutils is + preferred. + """ + env = dict(SETUPTOOLS_USE_DISTUTILS='local') + assert venv.name in find_distutils(venv, env=env).split(os.sep) + assert count_meta_path(venv, env=env) <= 1 + + +def test_pip_import(venv): + """ + Ensure pip can be imported. + Regression test for #3002. + """ + cmd = ['python', '-c', 'import pip'] + venv.run(cmd, **_TEXT_KWARGS) + + +def test_distutils_has_origin(): + """ + Distutils module spec should have an origin. #2990. + """ + assert __import__('distutils').__spec__.origin + + +ENSURE_IMPORTS_ARE_NOT_DUPLICATED = r""" +# Depending on the importlib machinery and _distutils_hack, some imports are +# duplicated resulting in different module objects being loaded, which prevents +# patches as shown in #3042. +# This script provides a way of verifying if this duplication is happening. + +from distutils import cmd +import distutils.command.sdist as sdist + +# import last to prevent caching +from distutils import {imported_module} + +for mod in (cmd, sdist): + assert mod.{imported_module} == {imported_module}, ( + f"\n{{mod.dir_util}}\n!=\n{{{imported_module}}}" + ) + +print("success") +""" + + +@pytest.mark.usefixtures("tmpdir_cwd") +@pytest.mark.parametrize( + ('distutils_version', 'imported_module'), + [ + pytest.param("stdlib", "dir_util", marks=skip_without_stdlib_distutils), + pytest.param("stdlib", "file_util", marks=skip_without_stdlib_distutils), + pytest.param("stdlib", "archive_util", marks=skip_without_stdlib_distutils), + ("local", "dir_util"), + ("local", "file_util"), + ("local", "archive_util"), + ], +) +def test_modules_are_not_duplicated_on_import(distutils_version, imported_module, venv): + env = dict(SETUPTOOLS_USE_DISTUTILS=distutils_version) + script = ENSURE_IMPORTS_ARE_NOT_DUPLICATED.format(imported_module=imported_module) + cmd = ['python', '-c', script] + output = venv.run(cmd, env=win_sr(env), **_TEXT_KWARGS).strip() + assert output == "success" + + +ENSURE_LOG_IMPORT_IS_NOT_DUPLICATED = r""" +import types +import distutils.dist as dist +from distutils import log +if isinstance(dist.log, types.ModuleType): + assert dist.log == log, f"\n{dist.log}\n!=\n{log}" +print("success") +""" + + +@pytest.mark.usefixtures("tmpdir_cwd") +@pytest.mark.parametrize( + "distutils_version", + [ + "local", + pytest.param("stdlib", marks=skip_without_stdlib_distutils), + ], +) +def test_log_module_is_not_duplicated_on_import(distutils_version, venv): + env = dict(SETUPTOOLS_USE_DISTUTILS=distutils_version) + cmd = ['python', '-c', ENSURE_LOG_IMPORT_IS_NOT_DUPLICATED] + output = venv.run(cmd, env=win_sr(env), **_TEXT_KWARGS).strip() + assert output == "success" + + +ENSURE_CONSISTENT_ERROR_FROM_MODIFIED_PY = r""" +from setuptools.modified import newer +from {imported_module}.errors import DistutilsError + +# Can't use pytest.raises in this context +try: + newer("", "") +except DistutilsError: + print("success") +else: + raise AssertionError("Expected to raise") +""" + + +@pytest.mark.usefixtures("tmpdir_cwd") +@pytest.mark.parametrize( + ('distutils_version', 'imported_module'), + [ + ("local", "distutils"), + # Unfortunately we still get ._distutils.errors.DistutilsError with SETUPTOOLS_USE_DISTUTILS=stdlib + # But that's a deprecated use-case we don't mind not fully supporting in newer code + pytest.param( + "stdlib", "setuptools._distutils", marks=skip_without_stdlib_distutils + ), + ], +) +def test_consistent_error_from_modified_py(distutils_version, imported_module, venv): + env = dict(SETUPTOOLS_USE_DISTUTILS=distutils_version) + cmd = [ + 'python', + '-c', + ENSURE_CONSISTENT_ERROR_FROM_MODIFIED_PY.format( + imported_module=imported_module + ), + ] + output = venv.run(cmd, env=win_sr(env), **_TEXT_KWARGS).strip() + assert output == "success" diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/test_easy_install.py b/.venv/lib/python3.12/site-packages/setuptools/tests/test_easy_install.py new file mode 100644 index 0000000000000000000000000000000000000000..b58b0b66663e4bfb6e26bd730e62bff8267eeff5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/test_easy_install.py @@ -0,0 +1,1476 @@ +"""Easy install Tests""" + +import contextlib +import io +import itertools +import logging +import os +import pathlib +import re +import site +import subprocess +import sys +import tarfile +import tempfile +import time +import warnings +import zipfile +from pathlib import Path +from typing import NamedTuple +from unittest import mock + +import pytest +from jaraco import path + +import pkg_resources +import setuptools.command.easy_install as ei +from pkg_resources import Distribution as PRDistribution, normalize_path, working_set +from setuptools import sandbox +from setuptools._normalization import safer_name +from setuptools.command.easy_install import PthDistributions +from setuptools.dist import Distribution +from setuptools.sandbox import run_setup +from setuptools.tests import fail_on_ascii +from setuptools.tests.server import MockServer, path_to_url + +from . import contexts +from .textwrap import DALS + +import distutils.errors + + +@pytest.fixture(autouse=True) +def pip_disable_index(monkeypatch): + """ + Important: Disable the default index for pip to avoid + querying packages in the index and potentially resolving + and installing packages there. + """ + monkeypatch.setenv('PIP_NO_INDEX', 'true') + + +class FakeDist: + def get_entry_map(self, group): + if group != 'console_scripts': + return {} + return {'name': 'ep'} + + def as_requirement(self): + return 'spec' + + +SETUP_PY = DALS( + """ + from setuptools import setup + + setup() + """ +) + + +class TestEasyInstallTest: + def test_get_script_args(self): + header = ei.CommandSpec.best().from_environment().as_header() + dist = FakeDist() + args = next(ei.ScriptWriter.get_args(dist)) + _name, script = itertools.islice(args, 2) + assert script.startswith(header) + assert "'spec'" in script + assert "'console_scripts'" in script + assert "'name'" in script + assert re.search('^# EASY-INSTALL-ENTRY-SCRIPT', script, flags=re.MULTILINE) + + def test_no_find_links(self): + # new option '--no-find-links', that blocks find-links added at + # the project level + dist = Distribution() + cmd = ei.easy_install(dist) + cmd.check_pth_processing = lambda: True + cmd.no_find_links = True + cmd.find_links = ['link1', 'link2'] + cmd.install_dir = os.path.join(tempfile.mkdtemp(), 'ok') + cmd.args = ['ok'] + cmd.ensure_finalized() + assert cmd.package_index.scanned_urls == {} + + # let's try without it (default behavior) + cmd = ei.easy_install(dist) + cmd.check_pth_processing = lambda: True + cmd.find_links = ['link1', 'link2'] + cmd.install_dir = os.path.join(tempfile.mkdtemp(), 'ok') + cmd.args = ['ok'] + cmd.ensure_finalized() + keys = sorted(cmd.package_index.scanned_urls.keys()) + assert keys == ['link1', 'link2'] + + def test_write_exception(self): + """ + Test that `cant_write_to_target` is rendered as a DistutilsError. + """ + dist = Distribution() + cmd = ei.easy_install(dist) + cmd.install_dir = os.getcwd() + with pytest.raises(distutils.errors.DistutilsError): + cmd.cant_write_to_target() + + def test_all_site_dirs(self, monkeypatch): + """ + get_site_dirs should always return site dirs reported by + site.getsitepackages. + """ + path = normalize_path('/setuptools/test/site-packages') + + def mock_gsp(): + return [path] + + monkeypatch.setattr(site, 'getsitepackages', mock_gsp, raising=False) + assert path in ei.get_site_dirs() + + def test_all_site_dirs_works_without_getsitepackages(self, monkeypatch): + monkeypatch.delattr(site, 'getsitepackages', raising=False) + assert ei.get_site_dirs() + + @pytest.fixture + def sdist_unicode(self, tmpdir): + files = [ + ( + 'setup.py', + DALS( + """ + import setuptools + setuptools.setup( + name="setuptools-test-unicode", + version="1.0", + packages=["mypkg"], + include_package_data=True, + ) + """ + ), + ), + ( + 'mypkg/__init__.py', + "", + ), + ( + 'mypkg/☃.txt', + "", + ), + ] + sdist_name = 'setuptools-test-unicode-1.0.zip' + sdist = tmpdir / sdist_name + # can't use make_sdist, because the issue only occurs + # with zip sdists. + sdist_zip = zipfile.ZipFile(str(sdist), 'w') + for filename, content in files: + sdist_zip.writestr(filename, content) + sdist_zip.close() + return str(sdist) + + @fail_on_ascii + def test_unicode_filename_in_sdist(self, sdist_unicode, tmpdir, monkeypatch): + """ + The install command should execute correctly even if + the package has unicode filenames. + """ + dist = Distribution({'script_args': ['easy_install']}) + target = (tmpdir / 'target').ensure_dir() + cmd = ei.easy_install( + dist, + install_dir=str(target), + args=['x'], + ) + monkeypatch.setitem(os.environ, 'PYTHONPATH', str(target)) + cmd.ensure_finalized() + cmd.easy_install(sdist_unicode) + + @pytest.fixture + def sdist_unicode_in_script(self, tmpdir): + files = [ + ( + "setup.py", + DALS( + """ + import setuptools + setuptools.setup( + name="setuptools-test-unicode", + version="1.0", + packages=["mypkg"], + include_package_data=True, + scripts=['mypkg/unicode_in_script'], + ) + """ + ), + ), + ("mypkg/__init__.py", ""), + ( + "mypkg/unicode_in_script", + DALS( + """ + #!/bin/sh + # á + + non_python_fn() { + } + """ + ), + ), + ] + sdist_name = "setuptools-test-unicode-script-1.0.zip" + sdist = tmpdir / sdist_name + # can't use make_sdist, because the issue only occurs + # with zip sdists. + sdist_zip = zipfile.ZipFile(str(sdist), "w") + for filename, content in files: + sdist_zip.writestr(filename, content.encode('utf-8')) + sdist_zip.close() + return str(sdist) + + @fail_on_ascii + def test_unicode_content_in_sdist( + self, sdist_unicode_in_script, tmpdir, monkeypatch + ): + """ + The install command should execute correctly even if + the package has unicode in scripts. + """ + dist = Distribution({"script_args": ["easy_install"]}) + target = (tmpdir / "target").ensure_dir() + cmd = ei.easy_install(dist, install_dir=str(target), args=["x"]) + monkeypatch.setitem(os.environ, "PYTHONPATH", str(target)) + cmd.ensure_finalized() + cmd.easy_install(sdist_unicode_in_script) + + @pytest.fixture + def sdist_script(self, tmpdir): + files = [ + ( + 'setup.py', + DALS( + """ + import setuptools + setuptools.setup( + name="setuptools-test-script", + version="1.0", + scripts=["mypkg_script"], + ) + """ + ), + ), + ( + 'mypkg_script', + DALS( + """ + #/usr/bin/python + print('mypkg_script') + """ + ), + ), + ] + sdist_name = 'setuptools-test-script-1.0.zip' + sdist = str(tmpdir / sdist_name) + make_sdist(sdist, files) + return sdist + + @pytest.mark.skipif( + not sys.platform.startswith('linux'), reason="Test can only be run on Linux" + ) + def test_script_install(self, sdist_script, tmpdir, monkeypatch): + """ + Check scripts are installed. + """ + dist = Distribution({'script_args': ['easy_install']}) + target = (tmpdir / 'target').ensure_dir() + cmd = ei.easy_install( + dist, + install_dir=str(target), + args=['x'], + ) + monkeypatch.setitem(os.environ, 'PYTHONPATH', str(target)) + cmd.ensure_finalized() + cmd.easy_install(sdist_script) + assert (target / 'mypkg_script').exists() + + +@pytest.mark.filterwarnings('ignore:Unbuilt egg') +class TestPTHFileWriter: + def test_add_from_cwd_site_sets_dirty(self): + """a pth file manager should set dirty + if a distribution is in site but also the cwd + """ + pth = PthDistributions('does-not_exist', [os.getcwd()]) + assert not pth.dirty + pth.add(PRDistribution(os.getcwd())) + assert pth.dirty + + def test_add_from_site_is_ignored(self): + location = '/test/location/does-not-have-to-exist' + # PthDistributions expects all locations to be normalized + location = pkg_resources.normalize_path(location) + pth = PthDistributions( + 'does-not_exist', + [ + location, + ], + ) + assert not pth.dirty + pth.add(PRDistribution(location)) + assert not pth.dirty + + def test_many_pth_distributions_merge_together(self, tmpdir): + """ + If the pth file is modified under the hood, then PthDistribution + will refresh its content before saving, merging contents when + necessary. + """ + # putting the pth file in a dedicated sub-folder, + pth_subdir = tmpdir.join("pth_subdir") + pth_subdir.mkdir() + pth_path = str(pth_subdir.join("file1.pth")) + pth1 = PthDistributions(pth_path) + pth2 = PthDistributions(pth_path) + assert pth1.paths == pth2.paths == [], ( + "unless there would be some default added at some point" + ) + # and so putting the src_subdir in folder distinct than the pth one, + # so to keep it absolute by PthDistributions + new_src_path = tmpdir.join("src_subdir") + new_src_path.mkdir() # must exist to be accounted + new_src_path_str = str(new_src_path) + pth1.paths.append(new_src_path_str) + pth1.save() + assert pth1.paths, ( + "the new_src_path added must still be present/valid in pth1 after save" + ) + # now, + assert new_src_path_str not in pth2.paths, ( + "right before we save the entry should still not be present" + ) + pth2.save() + assert new_src_path_str in pth2.paths, ( + "the new_src_path entry should have been added by pth2 with its save() call" + ) + assert pth2.paths[-1] == new_src_path, ( + "and it should match exactly on the last entry actually " + "given we append to it in save()" + ) + # finally, + assert PthDistributions(pth_path).paths == pth2.paths, ( + "and we should have the exact same list at the end " + "with a fresh PthDistributions instance" + ) + + +@pytest.fixture +def setup_context(tmpdir): + with (tmpdir / 'setup.py').open('w', encoding="utf-8") as f: + f.write(SETUP_PY) + with tmpdir.as_cwd(): + yield tmpdir + + +@pytest.mark.usefixtures("user_override") +@pytest.mark.usefixtures("setup_context") +class TestUserInstallTest: + # prevent check that site-packages is writable. easy_install + # shouldn't be writing to system site-packages during finalize + # options, but while it does, bypass the behavior. + prev_sp_write = mock.patch( + 'setuptools.command.easy_install.easy_install.check_site_dir', + mock.Mock(), + ) + + # simulate setuptools installed in user site packages + @mock.patch('setuptools.command.easy_install.__file__', site.USER_SITE) + @mock.patch('site.ENABLE_USER_SITE', True) + @prev_sp_write + def test_user_install_not_implied_user_site_enabled(self): + self.assert_not_user_site() + + @mock.patch('site.ENABLE_USER_SITE', False) + @prev_sp_write + def test_user_install_not_implied_user_site_disabled(self): + self.assert_not_user_site() + + @staticmethod + def assert_not_user_site(): + # create a finalized easy_install command + dist = Distribution() + dist.script_name = 'setup.py' + cmd = ei.easy_install(dist) + cmd.args = ['py'] + cmd.ensure_finalized() + assert not cmd.user, 'user should not be implied' + + def test_multiproc_atexit(self): + pytest.importorskip('multiprocessing') + + log = logging.getLogger('test_easy_install') + logging.basicConfig(level=logging.INFO, stream=sys.stderr) + log.info('this should not break') + + @pytest.fixture + def foo_package(self, tmpdir): + egg_file = tmpdir / 'foo-1.0.egg-info' + with egg_file.open('w') as f: + f.write('Name: foo\n') + return str(tmpdir) + + @pytest.fixture + def install_target(self, tmpdir): + target = str(tmpdir) + with mock.patch('sys.path', sys.path + [target]): + python_path = os.path.pathsep.join(sys.path) + with mock.patch.dict(os.environ, PYTHONPATH=python_path): + yield target + + def test_local_index(self, foo_package, install_target): + """ + The local index must be used when easy_install locates installed + packages. + """ + dist = Distribution() + dist.script_name = 'setup.py' + cmd = ei.easy_install(dist) + cmd.install_dir = install_target + cmd.args = ['foo'] + cmd.ensure_finalized() + cmd.local_index.scan([foo_package]) + res = cmd.easy_install('foo') + actual = os.path.normcase(os.path.realpath(res.location)) + expected = os.path.normcase(os.path.realpath(foo_package)) + assert actual == expected + + @contextlib.contextmanager + def user_install_setup_context(self, *args, **kwargs): + """ + Wrap sandbox.setup_context to patch easy_install in that context to + appear as user-installed. + """ + with self.orig_context(*args, **kwargs): + import setuptools.command.easy_install as ei + + ei.__file__ = site.USER_SITE + yield + + def patched_setup_context(self): + self.orig_context = sandbox.setup_context + + return mock.patch( + 'setuptools.sandbox.setup_context', + self.user_install_setup_context, + ) + + +@pytest.fixture +def distutils_package(): + distutils_setup_py = SETUP_PY.replace( + 'from setuptools import setup', + 'from distutils.core import setup', + ) + with contexts.tempdir(cd=os.chdir): + with open('setup.py', 'w', encoding="utf-8") as f: + f.write(distutils_setup_py) + yield + + +@pytest.mark.usefixtures("distutils_package") +class TestDistutilsPackage: + def test_bdist_egg_available_on_distutils_pkg(self): + run_setup('setup.py', ['bdist_egg']) + + +@pytest.fixture +def mock_index(): + # set up a server which will simulate an alternate package index. + p_index = MockServer() + if p_index.server_port == 0: + # Some platforms (Jython) don't find a port to which to bind, + # so skip test for them. + pytest.skip("could not find a valid port") + p_index.start() + return p_index + + +class TestInstallRequires: + def test_setup_install_includes_dependencies(self, tmp_path, mock_index): + """ + When ``python setup.py install`` is called directly, it will use easy_install + to fetch dependencies. + """ + # TODO: Remove these tests once `setup.py install` is completely removed + project_root = tmp_path / "project" + project_root.mkdir(exist_ok=True) + install_root = tmp_path / "install" + install_root.mkdir(exist_ok=True) + + self.create_project(project_root) + cmd = [ + sys.executable, + '-c', + '__import__("setuptools").setup()', + 'install', + '--install-base', + str(install_root), + '--install-lib', + str(install_root), + '--install-headers', + str(install_root), + '--install-scripts', + str(install_root), + '--install-data', + str(install_root), + '--install-purelib', + str(install_root), + '--install-platlib', + str(install_root), + ] + env = {**os.environ, "__EASYINSTALL_INDEX": mock_index.url} + cp = subprocess.run( + cmd, + cwd=str(project_root), + env=env, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + encoding="utf-8", + ) + assert cp.returncode != 0 + try: + assert '/does-not-exist/' in {r.path for r in mock_index.requests} + assert next( + line + for line in cp.stdout.splitlines() + if "not find suitable distribution for" in line + and "does-not-exist" in line + ) + except Exception: + if "failed to get random numbers" in cp.stdout: + pytest.xfail(f"{sys.platform} failure - {cp.stdout}") + raise + + def create_project(self, root): + config = """ + [metadata] + name = project + version = 42 + + [options] + install_requires = does-not-exist + py_modules = mod + """ + (root / 'setup.cfg').write_text(DALS(config), encoding="utf-8") + (root / 'mod.py').touch() + + +class TestSetupRequires: + def test_setup_requires_honors_fetch_params(self, mock_index, monkeypatch): + """ + When easy_install installs a source distribution which specifies + setup_requires, it should honor the fetch parameters (such as + index-url, and find-links). + """ + monkeypatch.setenv('PIP_RETRIES', '0') + monkeypatch.setenv('PIP_TIMEOUT', '0') + monkeypatch.setenv('PIP_NO_INDEX', 'false') + with contexts.quiet(): + # create an sdist that has a build-time dependency. + with TestSetupRequires.create_sdist() as dist_file: + with contexts.tempdir() as temp_install_dir: + with contexts.environment(PYTHONPATH=temp_install_dir): + cmd = [ + sys.executable, + '-c', + '__import__("setuptools").setup()', + 'easy_install', + '--index-url', + mock_index.url, + '--exclude-scripts', + '--install-dir', + temp_install_dir, + dist_file, + ] + subprocess.Popen(cmd).wait() + # there should have been one requests to the server + assert [r.path for r in mock_index.requests] == ['/does-not-exist/'] + + @staticmethod + @contextlib.contextmanager + def create_sdist(): + """ + Return an sdist with a setup_requires dependency (of something that + doesn't exist) + """ + with contexts.tempdir() as dir: + dist_path = os.path.join(dir, 'setuptools-test-fetcher-1.0.tar.gz') + make_sdist( + dist_path, + [ + ( + 'setup.py', + DALS( + """ + import setuptools + setuptools.setup( + name="setuptools-test-fetcher", + version="1.0", + setup_requires = ['does-not-exist'], + ) + """ + ), + ), + ('setup.cfg', ''), + ], + ) + yield dist_path + + use_setup_cfg = ( + (), + ('dependency_links',), + ('setup_requires',), + ('dependency_links', 'setup_requires'), + ) + + @pytest.mark.parametrize('use_setup_cfg', use_setup_cfg) + def test_setup_requires_overrides_version_conflict(self, use_setup_cfg): + """ + Regression test for distribution issue 323: + https://bitbucket.org/tarek/distribute/issues/323 + + Ensures that a distribution's setup_requires requirements can still be + installed and used locally even if a conflicting version of that + requirement is already on the path. + """ + + fake_dist = PRDistribution( + 'does-not-matter', project_name='foobar', version='0.0' + ) + working_set.add(fake_dist) + + with contexts.save_pkg_resources_state(): + with contexts.tempdir() as temp_dir: + test_pkg = create_setup_requires_package( + temp_dir, use_setup_cfg=use_setup_cfg + ) + test_setup_py = os.path.join(test_pkg, 'setup.py') + with contexts.quiet() as (stdout, _stderr): + # Don't even need to install the package, just + # running the setup.py at all is sufficient + run_setup(test_setup_py, ['--name']) + + lines = stdout.readlines() + assert len(lines) > 0 + assert lines[-1].strip() == 'test_pkg' + + @pytest.mark.parametrize('use_setup_cfg', use_setup_cfg) + def test_setup_requires_override_nspkg(self, use_setup_cfg): + """ + Like ``test_setup_requires_overrides_version_conflict`` but where the + ``setup_requires`` package is part of a namespace package that has + *already* been imported. + """ + + with contexts.save_pkg_resources_state(): + with contexts.tempdir() as temp_dir: + foobar_1_archive = os.path.join(temp_dir, 'foo_bar-0.1.tar.gz') + make_nspkg_sdist(foobar_1_archive, 'foo.bar', '0.1') + # Now actually go ahead an extract to the temp dir and add the + # extracted path to sys.path so foo.bar v0.1 is importable + foobar_1_dir = os.path.join(temp_dir, 'foo_bar-0.1') + os.mkdir(foobar_1_dir) + with tarfile.open(foobar_1_archive) as tf: + tf.extraction_filter = lambda member, path: member + tf.extractall(foobar_1_dir) + sys.path.insert(1, foobar_1_dir) + + dist = PRDistribution( + foobar_1_dir, project_name='foo.bar', version='0.1' + ) + working_set.add(dist) + + template = DALS( + """\ + import foo # Even with foo imported first the + # setup_requires package should override + import setuptools + setuptools.setup(**%r) + + if not (hasattr(foo, '__path__') and + len(foo.__path__) == 2): + print('FAIL') + + if 'foo_bar-0.2' not in foo.__path__[0]: + print('FAIL') + """ + ) + + test_pkg = create_setup_requires_package( + temp_dir, + 'foo.bar', + '0.2', + make_nspkg_sdist, + template, + use_setup_cfg=use_setup_cfg, + ) + + test_setup_py = os.path.join(test_pkg, 'setup.py') + + with contexts.quiet() as (stdout, _stderr): + try: + # Don't even need to install the package, just + # running the setup.py at all is sufficient + run_setup(test_setup_py, ['--name']) + except pkg_resources.VersionConflict: # pragma: nocover + pytest.fail( + 'Installing setup.py requirements caused a VersionConflict' + ) + + assert 'FAIL' not in stdout.getvalue() + lines = stdout.readlines() + assert len(lines) > 0 + assert lines[-1].strip() == 'test_pkg' + + @pytest.mark.parametrize('use_setup_cfg', use_setup_cfg) + def test_setup_requires_with_attr_version(self, use_setup_cfg): + def make_dependency_sdist(dist_path, distname, version): + files = [ + ( + 'setup.py', + DALS( + f""" + import setuptools + setuptools.setup( + name={distname!r}, + version={version!r}, + py_modules=[{distname!r}], + ) + """ + ), + ), + ( + distname + '.py', + DALS( + """ + version = 42 + """ + ), + ), + ] + make_sdist(dist_path, files) + + with contexts.save_pkg_resources_state(): + with contexts.tempdir() as temp_dir: + test_pkg = create_setup_requires_package( + temp_dir, + setup_attrs=dict(version='attr: foobar.version'), + make_package=make_dependency_sdist, + use_setup_cfg=use_setup_cfg + ('version',), + ) + test_setup_py = os.path.join(test_pkg, 'setup.py') + with contexts.quiet() as (stdout, _stderr): + run_setup(test_setup_py, ['--version']) + lines = stdout.readlines() + assert len(lines) > 0 + assert lines[-1].strip() == '42' + + def test_setup_requires_honors_pip_env(self, mock_index, monkeypatch): + monkeypatch.setenv('PIP_RETRIES', '0') + monkeypatch.setenv('PIP_TIMEOUT', '0') + monkeypatch.setenv('PIP_NO_INDEX', 'false') + monkeypatch.setenv('PIP_INDEX_URL', mock_index.url) + with contexts.save_pkg_resources_state(): + with contexts.tempdir() as temp_dir: + test_pkg = create_setup_requires_package( + temp_dir, + 'python-xlib', + '0.19', + setup_attrs=dict(dependency_links=[]), + ) + test_setup_cfg = os.path.join(test_pkg, 'setup.cfg') + with open(test_setup_cfg, 'w', encoding="utf-8") as fp: + fp.write( + DALS( + """ + [easy_install] + index_url = https://pypi.org/legacy/ + """ + ) + ) + test_setup_py = os.path.join(test_pkg, 'setup.py') + with pytest.raises(distutils.errors.DistutilsError): + run_setup(test_setup_py, ['--version']) + assert len(mock_index.requests) == 1 + assert mock_index.requests[0].path == '/python-xlib/' + + def test_setup_requires_with_pep508_url(self, mock_index, monkeypatch): + monkeypatch.setenv('PIP_RETRIES', '0') + monkeypatch.setenv('PIP_TIMEOUT', '0') + monkeypatch.setenv('PIP_INDEX_URL', mock_index.url) + with contexts.save_pkg_resources_state(): + with contexts.tempdir() as temp_dir: + dep_sdist = os.path.join(temp_dir, 'dep.tar.gz') + make_trivial_sdist(dep_sdist, 'dependency', '42') + dep_url = path_to_url(dep_sdist, authority='localhost') + test_pkg = create_setup_requires_package( + temp_dir, + # Ignored (overridden by setup_attrs) + 'python-xlib', + '0.19', + setup_attrs=dict(setup_requires=f'dependency @ {dep_url}'), + ) + test_setup_py = os.path.join(test_pkg, 'setup.py') + run_setup(test_setup_py, ['--version']) + assert len(mock_index.requests) == 0 + + def test_setup_requires_with_allow_hosts(self, mock_index): + """The `allow-hosts` option in not supported anymore.""" + files = { + 'test_pkg': { + 'setup.py': DALS( + """ + from setuptools import setup + setup(setup_requires='python-xlib') + """ + ), + 'setup.cfg': DALS( + """ + [easy_install] + allow_hosts = * + """ + ), + } + } + with contexts.save_pkg_resources_state(): + with contexts.tempdir() as temp_dir: + path.build(files, prefix=temp_dir) + setup_py = str(pathlib.Path(temp_dir, 'test_pkg', 'setup.py')) + with pytest.raises(distutils.errors.DistutilsError): + run_setup(setup_py, ['--version']) + assert len(mock_index.requests) == 0 + + def test_setup_requires_with_python_requires(self, monkeypatch, tmpdir): + """Check `python_requires` is honored.""" + monkeypatch.setenv('PIP_RETRIES', '0') + monkeypatch.setenv('PIP_TIMEOUT', '0') + monkeypatch.setenv('PIP_NO_INDEX', '1') + monkeypatch.setenv('PIP_VERBOSE', '1') + dep_1_0_sdist = 'dep-1.0.tar.gz' + dep_1_0_url = path_to_url(str(tmpdir / dep_1_0_sdist)) + dep_1_0_python_requires = '>=2.7' + make_python_requires_sdist( + str(tmpdir / dep_1_0_sdist), 'dep', '1.0', dep_1_0_python_requires + ) + dep_2_0_sdist = 'dep-2.0.tar.gz' + dep_2_0_url = path_to_url(str(tmpdir / dep_2_0_sdist)) + dep_2_0_python_requires = ( + f'!={sys.version_info.major}.{sys.version_info.minor}.*' + ) + make_python_requires_sdist( + str(tmpdir / dep_2_0_sdist), 'dep', '2.0', dep_2_0_python_requires + ) + index = tmpdir / 'index.html' + index.write_text( + DALS( + """ + + Links for dep + +

Links for dep

+ {dep_1_0_sdist}
+ {dep_2_0_sdist}
+ + + """ + ).format( + dep_1_0_url=dep_1_0_url, + dep_1_0_sdist=dep_1_0_sdist, + dep_1_0_python_requires=dep_1_0_python_requires, + dep_2_0_url=dep_2_0_url, + dep_2_0_sdist=dep_2_0_sdist, + dep_2_0_python_requires=dep_2_0_python_requires, + ), + 'utf-8', + ) + index_url = path_to_url(str(index)) + with contexts.save_pkg_resources_state(): + test_pkg = create_setup_requires_package( + str(tmpdir), + 'python-xlib', + '0.19', # Ignored (overridden by setup_attrs). + setup_attrs=dict(setup_requires='dep', dependency_links=[index_url]), + ) + test_setup_py = os.path.join(test_pkg, 'setup.py') + run_setup(test_setup_py, ['--version']) + eggs = list( + map(str, pkg_resources.find_distributions(os.path.join(test_pkg, '.eggs'))) + ) + assert eggs == ['dep 1.0'] + + @pytest.mark.parametrize('with_dependency_links_in_setup_py', (False, True)) + def test_setup_requires_with_find_links_in_setup_cfg( + self, monkeypatch, with_dependency_links_in_setup_py + ): + monkeypatch.setenv('PIP_RETRIES', '0') + monkeypatch.setenv('PIP_TIMEOUT', '0') + with contexts.save_pkg_resources_state(): + with contexts.tempdir() as temp_dir: + make_trivial_sdist( + os.path.join(temp_dir, 'python-xlib-42.tar.gz'), 'python-xlib', '42' + ) + test_pkg = os.path.join(temp_dir, 'test_pkg') + test_setup_py = os.path.join(test_pkg, 'setup.py') + test_setup_cfg = os.path.join(test_pkg, 'setup.cfg') + os.mkdir(test_pkg) + with open(test_setup_py, 'w', encoding="utf-8") as fp: + if with_dependency_links_in_setup_py: + dependency_links = [os.path.join(temp_dir, 'links')] + else: + dependency_links = [] + fp.write( + DALS( + """ + from setuptools import installer, setup + setup(setup_requires='python-xlib==42', + dependency_links={dependency_links!r}) + """ + ).format(dependency_links=dependency_links) + ) + with open(test_setup_cfg, 'w', encoding="utf-8") as fp: + fp.write( + DALS( + """ + [easy_install] + index_url = {index_url} + find_links = {find_links} + """ + ).format( + index_url=os.path.join(temp_dir, 'index'), + find_links=temp_dir, + ) + ) + run_setup(test_setup_py, ['--version']) + + def test_setup_requires_with_transitive_extra_dependency(self, monkeypatch): + """ + Use case: installing a package with a build dependency on + an already installed `dep[extra]`, which in turn depends + on `extra_dep` (whose is not already installed). + """ + with contexts.save_pkg_resources_state(): + with contexts.tempdir() as temp_dir: + # Create source distribution for `extra_dep`. + make_trivial_sdist( + os.path.join(temp_dir, 'extra_dep-1.0.tar.gz'), 'extra_dep', '1.0' + ) + # Create source tree for `dep`. + dep_pkg = os.path.join(temp_dir, 'dep') + os.mkdir(dep_pkg) + path.build( + { + 'setup.py': DALS( + """ + import setuptools + setuptools.setup( + name='dep', version='2.0', + extras_require={'extra': ['extra_dep']}, + ) + """ + ), + 'setup.cfg': '', + }, + prefix=dep_pkg, + ) + # "Install" dep. + run_setup(os.path.join(dep_pkg, 'setup.py'), ['dist_info']) + working_set.add_entry(dep_pkg) + # Create source tree for test package. + test_pkg = os.path.join(temp_dir, 'test_pkg') + test_setup_py = os.path.join(test_pkg, 'setup.py') + os.mkdir(test_pkg) + with open(test_setup_py, 'w', encoding="utf-8") as fp: + fp.write( + DALS( + """ + from setuptools import installer, setup + setup(setup_requires='dep[extra]') + """ + ) + ) + # Check... + monkeypatch.setenv('PIP_FIND_LINKS', str(temp_dir)) + monkeypatch.setenv('PIP_NO_INDEX', '1') + monkeypatch.setenv('PIP_RETRIES', '0') + monkeypatch.setenv('PIP_TIMEOUT', '0') + run_setup(test_setup_py, ['--version']) + + def test_setup_requires_with_distutils_command_dep(self, monkeypatch): + """ + Use case: ensure build requirements' extras + are properly installed and activated. + """ + with contexts.save_pkg_resources_state(): + with contexts.tempdir() as temp_dir: + # Create source distribution for `extra_dep`. + make_sdist( + os.path.join(temp_dir, 'extra_dep-1.0.tar.gz'), + [ + ( + 'setup.py', + DALS( + """ + import setuptools + setuptools.setup( + name='extra_dep', + version='1.0', + py_modules=['extra_dep'], + ) + """ + ), + ), + ('setup.cfg', ''), + ('extra_dep.py', ''), + ], + ) + # Create source tree for `epdep`. + dep_pkg = os.path.join(temp_dir, 'epdep') + os.mkdir(dep_pkg) + path.build( + { + 'setup.py': DALS( + """ + import setuptools + setuptools.setup( + name='dep', version='2.0', + py_modules=['epcmd'], + extras_require={'extra': ['extra_dep']}, + entry_points=''' + [distutils.commands] + epcmd = epcmd:epcmd [extra] + ''', + ) + """ + ), + 'setup.cfg': '', + 'epcmd.py': DALS( + """ + from distutils.command.build_py import build_py + + import extra_dep + + class epcmd(build_py): + pass + """ + ), + }, + prefix=dep_pkg, + ) + # "Install" dep. + run_setup(os.path.join(dep_pkg, 'setup.py'), ['dist_info']) + working_set.add_entry(dep_pkg) + # Create source tree for test package. + test_pkg = os.path.join(temp_dir, 'test_pkg') + test_setup_py = os.path.join(test_pkg, 'setup.py') + os.mkdir(test_pkg) + with open(test_setup_py, 'w', encoding="utf-8") as fp: + fp.write( + DALS( + """ + from setuptools import installer, setup + setup(setup_requires='dep[extra]') + """ + ) + ) + # Check... + monkeypatch.setenv('PIP_FIND_LINKS', str(temp_dir)) + monkeypatch.setenv('PIP_NO_INDEX', '1') + monkeypatch.setenv('PIP_RETRIES', '0') + monkeypatch.setenv('PIP_TIMEOUT', '0') + run_setup(test_setup_py, ['epcmd']) + + +def make_trivial_sdist(dist_path, distname, version): + """ + Create a simple sdist tarball at dist_path, containing just a simple + setup.py. + """ + + make_sdist( + dist_path, + [ + ( + 'setup.py', + DALS( + f"""\ + import setuptools + setuptools.setup( + name={distname!r}, + version={version!r} + ) + """ + ), + ), + ('setup.cfg', ''), + ], + ) + + +def make_nspkg_sdist(dist_path, distname, version): + """ + Make an sdist tarball with distname and version which also contains one + package with the same name as distname. The top-level package is + designated a namespace package). + """ + # Assert that the distname contains at least one period + assert '.' in distname + + parts = distname.split('.') + nspackage = parts[0] + + packages = ['.'.join(parts[:idx]) for idx in range(1, len(parts) + 1)] + + setup_py = DALS( + f"""\ + import setuptools + setuptools.setup( + name={distname!r}, + version={version!r}, + packages={packages!r}, + namespace_packages=[{nspackage!r}] + ) + """ + ) + + init = "__import__('pkg_resources').declare_namespace(__name__)" + + files = [('setup.py', setup_py), (os.path.join(nspackage, '__init__.py'), init)] + for package in packages[1:]: + filename = os.path.join(*(package.split('.') + ['__init__.py'])) + files.append((filename, '')) + + make_sdist(dist_path, files) + + +def make_python_requires_sdist(dist_path, distname, version, python_requires): + make_sdist( + dist_path, + [ + ( + 'setup.py', + DALS( + """\ + import setuptools + setuptools.setup( + name={name!r}, + version={version!r}, + python_requires={python_requires!r}, + ) + """ + ).format( + name=distname, version=version, python_requires=python_requires + ), + ), + ('setup.cfg', ''), + ], + ) + + +def make_sdist(dist_path, files): + """ + Create a simple sdist tarball at dist_path, containing the files + listed in ``files`` as ``(filename, content)`` tuples. + """ + + # Distributions with only one file don't play well with pip. + assert len(files) > 1 + with tarfile.open(dist_path, 'w:gz') as dist: + for filename, content in files: + file_bytes = io.BytesIO(content.encode('utf-8')) + file_info = tarfile.TarInfo(name=filename) + file_info.size = len(file_bytes.getvalue()) + file_info.mtime = int(time.time()) + dist.addfile(file_info, fileobj=file_bytes) + + +def create_setup_requires_package( + path, + distname='foobar', + version='0.1', + make_package=make_trivial_sdist, + setup_py_template=None, + setup_attrs=None, + use_setup_cfg=(), +): + """Creates a source tree under path for a trivial test package that has a + single requirement in setup_requires--a tarball for that requirement is + also created and added to the dependency_links argument. + + ``distname`` and ``version`` refer to the name/version of the package that + the test package requires via ``setup_requires``. The name of the test + package itself is just 'test_pkg'. + """ + + normalized_distname = safer_name(distname) + test_setup_attrs = { + 'name': 'test_pkg', + 'version': '0.0', + 'setup_requires': [f'{normalized_distname}=={version}'], + 'dependency_links': [os.path.abspath(path)], + } + if setup_attrs: + test_setup_attrs.update(setup_attrs) + + test_pkg = os.path.join(path, 'test_pkg') + os.mkdir(test_pkg) + + # setup.cfg + if use_setup_cfg: + options = [] + metadata = [] + for name in use_setup_cfg: + value = test_setup_attrs.pop(name) + if name in 'name version'.split(): + section = metadata + else: + section = options + if isinstance(value, (tuple, list)): + value = ';'.join(value) + section.append(f'{name}: {value}') + test_setup_cfg_contents = DALS( + """ + [metadata] + {metadata} + [options] + {options} + """ + ).format( + options='\n'.join(options), + metadata='\n'.join(metadata), + ) + else: + test_setup_cfg_contents = '' + with open(os.path.join(test_pkg, 'setup.cfg'), 'w', encoding="utf-8") as f: + f.write(test_setup_cfg_contents) + + # setup.py + if setup_py_template is None: + setup_py_template = DALS( + """\ + import setuptools + setuptools.setup(**%r) + """ + ) + with open(os.path.join(test_pkg, 'setup.py'), 'w', encoding="utf-8") as f: + f.write(setup_py_template % test_setup_attrs) + + foobar_path = os.path.join(path, f'{normalized_distname}-{version}.tar.gz') + make_package(foobar_path, distname, version) + + return test_pkg + + +@pytest.mark.skipif( + sys.platform.startswith('java') and ei.is_sh(sys.executable), + reason="Test cannot run under java when executable is sh", +) +class TestScriptHeader: + non_ascii_exe = '/Users/José/bin/python' + exe_with_spaces = r'C:\Program Files\Python36\python.exe' + + def test_get_script_header(self): + expected = f'#!{ei.nt_quote_arg(os.path.normpath(sys.executable))}\n' + actual = ei.ScriptWriter.get_header('#!/usr/local/bin/python') + assert actual == expected + + def test_get_script_header_args(self): + expected = f'#!{ei.nt_quote_arg(os.path.normpath(sys.executable))} -x\n' + actual = ei.ScriptWriter.get_header('#!/usr/bin/python -x') + assert actual == expected + + def test_get_script_header_non_ascii_exe(self): + actual = ei.ScriptWriter.get_header( + '#!/usr/bin/python', executable=self.non_ascii_exe + ) + expected = f'#!{self.non_ascii_exe} -x\n' + assert actual == expected + + def test_get_script_header_exe_with_spaces(self): + actual = ei.ScriptWriter.get_header( + '#!/usr/bin/python', executable='"' + self.exe_with_spaces + '"' + ) + expected = f'#!"{self.exe_with_spaces}"\n' + assert actual == expected + + +class TestCommandSpec: + def test_custom_launch_command(self): + """ + Show how a custom CommandSpec could be used to specify a #! executable + which takes parameters. + """ + cmd = ei.CommandSpec(['/usr/bin/env', 'python3']) + assert cmd.as_header() == '#!/usr/bin/env python3\n' + + def test_from_param_for_CommandSpec_is_passthrough(self): + """ + from_param should return an instance of a CommandSpec + """ + cmd = ei.CommandSpec(['python']) + cmd_new = ei.CommandSpec.from_param(cmd) + assert cmd is cmd_new + + @mock.patch('sys.executable', TestScriptHeader.exe_with_spaces) + @mock.patch.dict(os.environ) + def test_from_environment_with_spaces_in_executable(self): + os.environ.pop('__PYVENV_LAUNCHER__', None) + cmd = ei.CommandSpec.from_environment() + assert len(cmd) == 1 + assert cmd.as_header().startswith('#!"') + + def test_from_simple_string_uses_shlex(self): + """ + In order to support `executable = /usr/bin/env my-python`, make sure + from_param invokes shlex on that input. + """ + cmd = ei.CommandSpec.from_param('/usr/bin/env my-python') + assert len(cmd) == 2 + assert '"' not in cmd.as_header() + + def test_from_param_raises_expected_error(self) -> None: + """ + from_param should raise its own TypeError when the argument's type is unsupported + """ + with pytest.raises(TypeError) as exc_info: + ei.CommandSpec.from_param(object()) # type: ignore[arg-type] # We want a type error here + assert ( + str(exc_info.value) == "Argument has an unsupported type " + ), exc_info.value + + +class TestWindowsScriptWriter: + def test_header(self): + hdr = ei.WindowsScriptWriter.get_header('') + assert hdr.startswith('#!') + assert hdr.endswith('\n') + hdr = hdr.lstrip('#!') + hdr = hdr.rstrip('\n') + # header should not start with an escaped quote + assert not hdr.startswith('\\"') + + +class VersionStub(NamedTuple): + major: int + minor: int + micro: int + releaselevel: str + serial: int + + +def test_use_correct_python_version_string(tmpdir, tmpdir_cwd, monkeypatch): + # In issue #3001, easy_install wrongly uses the `python3.1` directory + # when the interpreter is `python3.10` and the `--user` option is given. + # See pypa/setuptools#3001. + dist = Distribution() + cmd = dist.get_command_obj('easy_install') + cmd.args = ['ok'] + cmd.optimize = 0 + cmd.user = True + cmd.install_userbase = str(tmpdir) + cmd.install_usersite = None + install_cmd = dist.get_command_obj('install') + install_cmd.install_userbase = str(tmpdir) + install_cmd.install_usersite = None + + with monkeypatch.context() as patch, warnings.catch_warnings(): + warnings.simplefilter("ignore") + version = '3.10.1 (main, Dec 21 2021, 09:17:12) [GCC 10.2.1 20210110]' + info = VersionStub(3, 10, 1, "final", 0) + patch.setattr('site.ENABLE_USER_SITE', True) + patch.setattr('sys.version', version) + patch.setattr('sys.version_info', info) + patch.setattr(cmd, 'create_home_path', mock.Mock()) + cmd.finalize_options() + + name = "pypy" if hasattr(sys, 'pypy_version_info') else "python" + install_dir = cmd.install_dir.lower() + + # In some platforms (e.g. Windows), install_dir is mostly determined + # via `sysconfig`, which define constants eagerly at module creation. + # This means that monkeypatching `sys.version` to emulate 3.10 for testing + # may have no effect. + # The safest test here is to rely on the fact that 3.1 is no longer + # supported/tested, and make sure that if 'python3.1' ever appears in the string + # it is followed by another digit (e.g. 'python3.10'). + if re.search(name + r'3\.?1', install_dir): + assert re.search(name + r'3\.?1\d', install_dir) + + # The following "variables" are used for interpolation in distutils + # installation schemes, so it should be fair to treat them as "semi-public", + # or at least public enough so we can have a test to make sure they are correct + assert cmd.config_vars['py_version'] == '3.10.1' + assert cmd.config_vars['py_version_short'] == '3.10' + assert cmd.config_vars['py_version_nodot'] == '310' + + +@pytest.mark.xfail( + sys.platform == "darwin", + reason="https://github.com/pypa/setuptools/pull/4716#issuecomment-2447624418", +) +def test_editable_user_and_build_isolation(setup_context, monkeypatch, tmp_path): + """`setup.py develop` should honor `--user` even under build isolation""" + + # == Arrange == + # Pretend that build isolation was enabled + # e.g pip sets the environment variable PYTHONNOUSERSITE=1 + monkeypatch.setattr('site.ENABLE_USER_SITE', False) + + # Patching $HOME for 2 reasons: + # 1. setuptools/command/easy_install.py:create_home_path + # tries creating directories in $HOME. + # Given:: + # self.config_vars['DESTDIRS'] = ( + # "/home/user/.pyenv/versions/3.9.10 " + # "/home/user/.pyenv/versions/3.9.10/lib " + # "/home/user/.pyenv/versions/3.9.10/lib/python3.9 " + # "/home/user/.pyenv/versions/3.9.10/lib/python3.9/lib-dynload") + # `create_home_path` will:: + # makedirs( + # "/home/user/.pyenv/versions/3.9.10 " + # "/home/user/.pyenv/versions/3.9.10/lib " + # "/home/user/.pyenv/versions/3.9.10/lib/python3.9 " + # "/home/user/.pyenv/versions/3.9.10/lib/python3.9/lib-dynload") + # + # 2. We are going to force `site` to update site.USER_BASE and site.USER_SITE + # To point inside our new home + monkeypatch.setenv('HOME', str(tmp_path / '.home')) + monkeypatch.setenv('USERPROFILE', str(tmp_path / '.home')) + monkeypatch.setenv('APPDATA', str(tmp_path / '.home')) + monkeypatch.setattr('site.USER_BASE', None) + monkeypatch.setattr('site.USER_SITE', None) + user_site = Path(site.getusersitepackages()) + user_site.mkdir(parents=True, exist_ok=True) + + sys_prefix = tmp_path / '.sys_prefix' + sys_prefix.mkdir(parents=True, exist_ok=True) + monkeypatch.setattr('sys.prefix', str(sys_prefix)) + + setup_script = ( + "__import__('setuptools').setup(name='aproj', version=42, packages=[])\n" + ) + (tmp_path / "setup.py").write_text(setup_script, encoding="utf-8") + + # == Sanity check == + assert list(sys_prefix.glob("*")) == [] + assert list(user_site.glob("*")) == [] + + # == Act == + run_setup('setup.py', ['develop', '--user']) + + # == Assert == + # Should not install to sys.prefix + assert list(sys_prefix.glob("*")) == [] + # Should install to user site + installed = {f.name for f in user_site.glob("*")} + # sometimes easy-install.pth is created and sometimes not + installed = installed - {"easy-install.pth"} + assert installed == {'aproj.egg-link'} diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/test_editable_install.py b/.venv/lib/python3.12/site-packages/setuptools/tests/test_editable_install.py new file mode 100644 index 0000000000000000000000000000000000000000..038dcadf934af20dbe11dcb13ba324ceb30bf90d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/test_editable_install.py @@ -0,0 +1,1289 @@ +from __future__ import annotations + +import os +import platform +import stat +import subprocess +import sys +from copy import deepcopy +from importlib import import_module +from importlib.machinery import EXTENSION_SUFFIXES +from pathlib import Path +from textwrap import dedent +from typing import Any +from unittest.mock import Mock +from uuid import uuid4 + +import jaraco.envs +import jaraco.path +import pytest +from path import Path as _Path + +from setuptools._importlib import resources as importlib_resources +from setuptools.command.editable_wheel import ( + _DebuggingTips, + _encode_pth, + _find_namespaces, + _find_package_roots, + _find_virtual_namespaces, + _finder_template, + _LinkTree, + _TopLevelFinder, + editable_wheel, +) +from setuptools.dist import Distribution +from setuptools.extension import Extension +from setuptools.warnings import SetuptoolsDeprecationWarning + +from . import contexts, namespaces + +from distutils.core import run_setup + + +@pytest.fixture(params=["strict", "lenient"]) +def editable_opts(request): + if request.param == "strict": + return ["--config-settings", "editable-mode=strict"] + return [] + + +EXAMPLE = { + 'pyproject.toml': dedent( + """\ + [build-system] + requires = ["setuptools"] + build-backend = "setuptools.build_meta" + + [project] + name = "mypkg" + version = "3.14159" + license = {text = "MIT"} + description = "This is a Python package" + dynamic = ["readme"] + classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers" + ] + urls = {Homepage = "https://github.com"} + + [tool.setuptools] + package-dir = {"" = "src"} + packages = {find = {where = ["src"]}} + license-files = ["LICENSE*"] + + [tool.setuptools.dynamic] + readme = {file = "README.rst"} + + [tool.distutils.egg_info] + tag-build = ".post0" + """ + ), + "MANIFEST.in": dedent( + """\ + global-include *.py *.txt + global-exclude *.py[cod] + prune dist + prune build + """ + ).strip(), + "README.rst": "This is a ``README``", + "LICENSE.txt": "---- placeholder MIT license ----", + "src": { + "mypkg": { + "__init__.py": dedent( + """\ + import sys + from importlib.metadata import PackageNotFoundError, version + + try: + __version__ = version(__name__) + except PackageNotFoundError: + __version__ = "unknown" + """ + ), + "__main__.py": dedent( + """\ + from importlib.resources import read_text + from . import __version__, __name__ as parent + from .mod import x + + data = read_text(parent, "data.txt") + print(__version__, data, x) + """ + ), + "mod.py": "x = ''", + "data.txt": "Hello World", + } + }, +} + + +SETUP_SCRIPT_STUB = "__import__('setuptools').setup()" + + +@pytest.mark.xfail(sys.platform == "darwin", reason="pypa/setuptools#4328") +@pytest.mark.parametrize( + "files", + [ + {**EXAMPLE, "setup.py": SETUP_SCRIPT_STUB}, + EXAMPLE, # No setup.py script + ], +) +def test_editable_with_pyproject(tmp_path, venv, files, editable_opts): + project = tmp_path / "mypkg" + project.mkdir() + jaraco.path.build(files, prefix=project) + + cmd = [ + "python", + "-m", + "pip", + "install", + "--no-build-isolation", # required to force current version of setuptools + "-e", + str(project), + *editable_opts, + ] + print(venv.run(cmd)) + + cmd = ["python", "-m", "mypkg"] + assert venv.run(cmd).strip() == "3.14159.post0 Hello World" + + (project / "src/mypkg/data.txt").write_text("foobar", encoding="utf-8") + (project / "src/mypkg/mod.py").write_text("x = 42", encoding="utf-8") + assert venv.run(cmd).strip() == "3.14159.post0 foobar 42" + + +def test_editable_with_flat_layout(tmp_path, venv, editable_opts): + files = { + "mypkg": { + "pyproject.toml": dedent( + """\ + [build-system] + requires = ["setuptools", "wheel"] + build-backend = "setuptools.build_meta" + + [project] + name = "mypkg" + version = "3.14159" + + [tool.setuptools] + packages = ["pkg"] + py-modules = ["mod"] + """ + ), + "pkg": {"__init__.py": "a = 4"}, + "mod.py": "b = 2", + }, + } + jaraco.path.build(files, prefix=tmp_path) + project = tmp_path / "mypkg" + + cmd = [ + "python", + "-m", + "pip", + "install", + "--no-build-isolation", # required to force current version of setuptools + "-e", + str(project), + *editable_opts, + ] + print(venv.run(cmd)) + cmd = ["python", "-c", "import pkg, mod; print(pkg.a, mod.b)"] + assert venv.run(cmd).strip() == "4 2" + + +def test_editable_with_single_module(tmp_path, venv, editable_opts): + files = { + "mypkg": { + "pyproject.toml": dedent( + """\ + [build-system] + requires = ["setuptools", "wheel"] + build-backend = "setuptools.build_meta" + + [project] + name = "mod" + version = "3.14159" + + [tool.setuptools] + py-modules = ["mod"] + """ + ), + "mod.py": "b = 2", + }, + } + jaraco.path.build(files, prefix=tmp_path) + project = tmp_path / "mypkg" + + cmd = [ + "python", + "-m", + "pip", + "install", + "--no-build-isolation", # required to force current version of setuptools + "-e", + str(project), + *editable_opts, + ] + print(venv.run(cmd)) + cmd = ["python", "-c", "import mod; print(mod.b)"] + assert venv.run(cmd).strip() == "2" + + +class TestLegacyNamespaces: + # legacy => pkg_resources.declare_namespace(...) + setup(namespace_packages=...) + + def test_nspkg_file_is_unique(self, tmp_path, monkeypatch): + deprecation = pytest.warns( + SetuptoolsDeprecationWarning, match=".*namespace_packages parameter.*" + ) + installation_dir = tmp_path / ".installation_dir" + installation_dir.mkdir() + examples = ( + "myns.pkgA", + "myns.pkgB", + "myns.n.pkgA", + "myns.n.pkgB", + ) + + for name in examples: + pkg = namespaces.build_namespace_package(tmp_path, name, version="42") + with deprecation, monkeypatch.context() as ctx: + ctx.chdir(pkg) + dist = run_setup("setup.py", stop_after="config") + cmd = editable_wheel(dist) + cmd.finalize_options() + editable_name = cmd.get_finalized_command("dist_info").name + cmd._install_namespaces(installation_dir, editable_name) + + files = list(installation_dir.glob("*-nspkg.pth")) + assert len(files) == len(examples) + + @pytest.mark.parametrize( + "impl", + ( + "pkg_resources", + # "pkgutil", => does not work + ), + ) + @pytest.mark.parametrize("ns", ("myns.n",)) + def test_namespace_package_importable( + self, venv, tmp_path, ns, impl, editable_opts + ): + """ + Installing two packages sharing the same namespace, one installed + naturally using pip or `--single-version-externally-managed` + and the other installed in editable mode should leave the namespace + intact and both packages reachable by import. + (Ported from test_develop). + """ + build_system = """\ + [build-system] + requires = ["setuptools"] + build-backend = "setuptools.build_meta" + """ + pkg_A = namespaces.build_namespace_package(tmp_path, f"{ns}.pkgA", impl=impl) + pkg_B = namespaces.build_namespace_package(tmp_path, f"{ns}.pkgB", impl=impl) + (pkg_A / "pyproject.toml").write_text(build_system, encoding="utf-8") + (pkg_B / "pyproject.toml").write_text(build_system, encoding="utf-8") + # use pip to install to the target directory + opts = editable_opts[:] + opts.append("--no-build-isolation") # force current version of setuptools + venv.run(["python", "-m", "pip", "install", str(pkg_A), *opts]) + venv.run(["python", "-m", "pip", "install", "-e", str(pkg_B), *opts]) + venv.run(["python", "-c", f"import {ns}.pkgA; import {ns}.pkgB"]) + # additionally ensure that pkg_resources import works + venv.run(["python", "-c", "import pkg_resources"]) + + +class TestPep420Namespaces: + def test_namespace_package_importable(self, venv, tmp_path, editable_opts): + """ + Installing two packages sharing the same namespace, one installed + normally using pip and the other installed in editable mode + should allow importing both packages. + """ + pkg_A = namespaces.build_pep420_namespace_package(tmp_path, 'myns.n.pkgA') + pkg_B = namespaces.build_pep420_namespace_package(tmp_path, 'myns.n.pkgB') + # use pip to install to the target directory + opts = editable_opts[:] + opts.append("--no-build-isolation") # force current version of setuptools + venv.run(["python", "-m", "pip", "install", str(pkg_A), *opts]) + venv.run(["python", "-m", "pip", "install", "-e", str(pkg_B), *opts]) + venv.run(["python", "-c", "import myns.n.pkgA; import myns.n.pkgB"]) + + def test_namespace_created_via_package_dir(self, venv, tmp_path, editable_opts): + """Currently users can create a namespace by tweaking `package_dir`""" + files = { + "pkgA": { + "pyproject.toml": dedent( + """\ + [build-system] + requires = ["setuptools", "wheel"] + build-backend = "setuptools.build_meta" + + [project] + name = "pkgA" + version = "3.14159" + + [tool.setuptools] + package-dir = {"myns.n.pkgA" = "src"} + """ + ), + "src": {"__init__.py": "a = 1"}, + }, + } + jaraco.path.build(files, prefix=tmp_path) + pkg_A = tmp_path / "pkgA" + pkg_B = namespaces.build_pep420_namespace_package(tmp_path, 'myns.n.pkgB') + pkg_C = namespaces.build_pep420_namespace_package(tmp_path, 'myns.n.pkgC') + + # use pip to install to the target directory + opts = editable_opts[:] + opts.append("--no-build-isolation") # force current version of setuptools + venv.run(["python", "-m", "pip", "install", str(pkg_A), *opts]) + venv.run(["python", "-m", "pip", "install", "-e", str(pkg_B), *opts]) + venv.run(["python", "-m", "pip", "install", "-e", str(pkg_C), *opts]) + venv.run(["python", "-c", "from myns.n import pkgA, pkgB, pkgC"]) + + def test_namespace_accidental_config_in_lenient_mode(self, venv, tmp_path): + """Sometimes users might specify an ``include`` pattern that ignores parent + packages. In a normal installation this would ignore all modules inside the + parent packages, and make them namespaces (reported in issue #3504), + so the editable mode should preserve this behaviour. + """ + files = { + "pkgA": { + "pyproject.toml": dedent( + """\ + [build-system] + requires = ["setuptools", "wheel"] + build-backend = "setuptools.build_meta" + + [project] + name = "pkgA" + version = "3.14159" + + [tool.setuptools] + packages.find.include = ["mypkg.*"] + """ + ), + "mypkg": { + "__init__.py": "", + "other.py": "b = 1", + "n": { + "__init__.py": "", + "pkgA.py": "a = 1", + }, + }, + "MANIFEST.in": EXAMPLE["MANIFEST.in"], + }, + } + jaraco.path.build(files, prefix=tmp_path) + pkg_A = tmp_path / "pkgA" + + # use pip to install to the target directory + opts = ["--no-build-isolation"] # force current version of setuptools + venv.run(["python", "-m", "pip", "-v", "install", "-e", str(pkg_A), *opts]) + out = venv.run(["python", "-c", "from mypkg.n import pkgA; print(pkgA.a)"]) + assert out.strip() == "1" + cmd = """\ + try: + import mypkg.other + except ImportError: + print("mypkg.other not defined") + """ + out = venv.run(["python", "-c", dedent(cmd)]) + assert "mypkg.other not defined" in out + + +def test_editable_with_prefix(tmp_path, sample_project, editable_opts): + """ + Editable install to a prefix should be discoverable. + """ + prefix = tmp_path / 'prefix' + + # figure out where pip will likely install the package + site_packages_all = [ + prefix / Path(path).relative_to(sys.prefix) + for path in sys.path + if 'site-packages' in path and path.startswith(sys.prefix) + ] + + for sp in site_packages_all: + sp.mkdir(parents=True) + + # install workaround + _addsitedirs(site_packages_all) + + env = dict(os.environ, PYTHONPATH=os.pathsep.join(map(str, site_packages_all))) + cmd = [ + sys.executable, + '-m', + 'pip', + 'install', + '--editable', + str(sample_project), + '--prefix', + str(prefix), + '--no-build-isolation', + *editable_opts, + ] + subprocess.check_call(cmd, env=env) + + # now run 'sample' with the prefix on the PYTHONPATH + bin = 'Scripts' if platform.system() == 'Windows' else 'bin' + exe = prefix / bin / 'sample' + subprocess.check_call([exe], env=env) + + +class TestFinderTemplate: + """This test focus in getting a particular implementation detail right. + If at some point in time the implementation is changed for something different, + this test can be modified or even excluded. + """ + + def install_finder(self, finder): + loc = {} + exec(finder, loc, loc) + loc["install"]() + + def test_packages(self, tmp_path): + files = { + "src1": { + "pkg1": { + "__init__.py": "", + "subpkg": {"mod1.py": "a = 42"}, + }, + }, + "src2": {"mod2.py": "a = 43"}, + } + jaraco.path.build(files, prefix=tmp_path) + + mapping = { + "pkg1": str(tmp_path / "src1/pkg1"), + "mod2": str(tmp_path / "src2/mod2"), + } + template = _finder_template(str(uuid4()), mapping, {}) + + with contexts.save_paths(), contexts.save_sys_modules(): + for mod in ("pkg1", "pkg1.subpkg", "pkg1.subpkg.mod1", "mod2"): + sys.modules.pop(mod, None) + + self.install_finder(template) + mod1 = import_module("pkg1.subpkg.mod1") + mod2 = import_module("mod2") + subpkg = import_module("pkg1.subpkg") + + assert mod1.a == 42 + assert mod2.a == 43 + expected = str((tmp_path / "src1/pkg1/subpkg").resolve()) + assert_path(subpkg, expected) + + def test_namespace(self, tmp_path): + files = {"pkg": {"__init__.py": "a = 13", "text.txt": "abc"}} + jaraco.path.build(files, prefix=tmp_path) + + mapping = {"ns.othername": str(tmp_path / "pkg")} + namespaces = {"ns": []} + + template = _finder_template(str(uuid4()), mapping, namespaces) + with contexts.save_paths(), contexts.save_sys_modules(): + for mod in ("ns", "ns.othername"): + sys.modules.pop(mod, None) + + self.install_finder(template) + pkg = import_module("ns.othername") + text = importlib_resources.files(pkg) / "text.txt" + + expected = str((tmp_path / "pkg").resolve()) + assert_path(pkg, expected) + assert pkg.a == 13 + + # Make sure resources can also be found + assert text.read_text(encoding="utf-8") == "abc" + + def test_combine_namespaces(self, tmp_path): + files = { + "src1": {"ns": {"pkg1": {"__init__.py": "a = 13"}}}, + "src2": {"ns": {"mod2.py": "b = 37"}}, + } + jaraco.path.build(files, prefix=tmp_path) + + mapping = { + "ns.pkgA": str(tmp_path / "src1/ns/pkg1"), + "ns": str(tmp_path / "src2/ns"), + } + namespaces_ = {"ns": [str(tmp_path / "src1"), str(tmp_path / "src2")]} + template = _finder_template(str(uuid4()), mapping, namespaces_) + + with contexts.save_paths(), contexts.save_sys_modules(): + for mod in ("ns", "ns.pkgA", "ns.mod2"): + sys.modules.pop(mod, None) + + self.install_finder(template) + pkgA = import_module("ns.pkgA") + mod2 = import_module("ns.mod2") + + expected = str((tmp_path / "src1/ns/pkg1").resolve()) + assert_path(pkgA, expected) + assert pkgA.a == 13 + assert mod2.b == 37 + + def test_combine_namespaces_nested(self, tmp_path): + """ + Users may attempt to combine namespace packages in a nested way via + ``package_dir`` as shown in pypa/setuptools#4248. + """ + + files = { + "src": {"my_package": {"my_module.py": "a = 13"}}, + "src2": {"my_package2": {"my_module2.py": "b = 37"}}, + } + + stack = jaraco.path.DirectoryStack() + with stack.context(tmp_path): + jaraco.path.build(files) + attrs = { + "script_name": "%PEP 517%", + "package_dir": { + "different_name": "src/my_package", + "different_name.subpkg": "src2/my_package2", + }, + "packages": ["different_name", "different_name.subpkg"], + } + dist = Distribution(attrs) + finder = _TopLevelFinder(dist, str(uuid4())) + code = next(v for k, v in finder.get_implementation() if k.endswith(".py")) + + with contexts.save_paths(), contexts.save_sys_modules(): + for mod in attrs["packages"]: + sys.modules.pop(mod, None) + + self.install_finder(code) + mod1 = import_module("different_name.my_module") + mod2 = import_module("different_name.subpkg.my_module2") + + expected = str((tmp_path / "src/my_package/my_module.py").resolve()) + assert str(Path(mod1.__file__).resolve()) == expected + + expected = str((tmp_path / "src2/my_package2/my_module2.py").resolve()) + assert str(Path(mod2.__file__).resolve()) == expected + + assert mod1.a == 13 + assert mod2.b == 37 + + def test_dynamic_path_computation(self, tmp_path): + # Follows the example in PEP 420 + files = { + "project1": {"parent": {"child": {"one.py": "x = 1"}}}, + "project2": {"parent": {"child": {"two.py": "x = 2"}}}, + "project3": {"parent": {"child": {"three.py": "x = 3"}}}, + } + jaraco.path.build(files, prefix=tmp_path) + mapping = {} + namespaces_ = {"parent": [str(tmp_path / "project1/parent")]} + template = _finder_template(str(uuid4()), mapping, namespaces_) + + mods = (f"parent.child.{name}" for name in ("one", "two", "three")) + with contexts.save_paths(), contexts.save_sys_modules(): + for mod in ("parent", "parent.child", "parent.child", *mods): + sys.modules.pop(mod, None) + + self.install_finder(template) + + one = import_module("parent.child.one") + assert one.x == 1 + + with pytest.raises(ImportError): + import_module("parent.child.two") + + sys.path.append(str(tmp_path / "project2")) + two = import_module("parent.child.two") + assert two.x == 2 + + with pytest.raises(ImportError): + import_module("parent.child.three") + + sys.path.append(str(tmp_path / "project3")) + three = import_module("parent.child.three") + assert three.x == 3 + + def test_no_recursion(self, tmp_path): + # See issue #3550 + files = { + "pkg": { + "__init__.py": "from . import pkg", + }, + } + jaraco.path.build(files, prefix=tmp_path) + + mapping = { + "pkg": str(tmp_path / "pkg"), + } + template = _finder_template(str(uuid4()), mapping, {}) + + with contexts.save_paths(), contexts.save_sys_modules(): + sys.modules.pop("pkg", None) + + self.install_finder(template) + with pytest.raises(ImportError, match="pkg"): + import_module("pkg") + + def test_similar_name(self, tmp_path): + files = { + "foo": { + "__init__.py": "", + "bar": { + "__init__.py": "", + }, + }, + } + jaraco.path.build(files, prefix=tmp_path) + + mapping = { + "foo": str(tmp_path / "foo"), + } + template = _finder_template(str(uuid4()), mapping, {}) + + with contexts.save_paths(), contexts.save_sys_modules(): + sys.modules.pop("foo", None) + sys.modules.pop("foo.bar", None) + + self.install_finder(template) + with pytest.raises(ImportError, match="foobar"): + import_module("foobar") + + def test_case_sensitivity(self, tmp_path): + files = { + "foo": { + "__init__.py": "", + "lowercase.py": "x = 1", + "bar": { + "__init__.py": "", + "lowercase.py": "x = 2", + }, + }, + } + jaraco.path.build(files, prefix=tmp_path) + mapping = { + "foo": str(tmp_path / "foo"), + } + template = _finder_template(str(uuid4()), mapping, {}) + with contexts.save_paths(), contexts.save_sys_modules(): + sys.modules.pop("foo", None) + + self.install_finder(template) + with pytest.raises(ImportError, match="'FOO'"): + import_module("FOO") + + with pytest.raises(ImportError, match="'foo\\.LOWERCASE'"): + import_module("foo.LOWERCASE") + + with pytest.raises(ImportError, match="'foo\\.bar\\.Lowercase'"): + import_module("foo.bar.Lowercase") + + with pytest.raises(ImportError, match="'foo\\.BAR'"): + import_module("foo.BAR.lowercase") + + with pytest.raises(ImportError, match="'FOO'"): + import_module("FOO.bar.lowercase") + + mod = import_module("foo.lowercase") + assert mod.x == 1 + + mod = import_module("foo.bar.lowercase") + assert mod.x == 2 + + def test_namespace_case_sensitivity(self, tmp_path): + files = { + "pkg": { + "__init__.py": "a = 13", + "foo": { + "__init__.py": "b = 37", + "bar.py": "c = 42", + }, + }, + } + jaraco.path.build(files, prefix=tmp_path) + + mapping = {"ns.othername": str(tmp_path / "pkg")} + namespaces = {"ns": []} + + template = _finder_template(str(uuid4()), mapping, namespaces) + with contexts.save_paths(), contexts.save_sys_modules(): + for mod in ("ns", "ns.othername"): + sys.modules.pop(mod, None) + + self.install_finder(template) + pkg = import_module("ns.othername") + expected = str((tmp_path / "pkg").resolve()) + assert_path(pkg, expected) + assert pkg.a == 13 + + foo = import_module("ns.othername.foo") + assert foo.b == 37 + + bar = import_module("ns.othername.foo.bar") + assert bar.c == 42 + + with pytest.raises(ImportError, match="'NS'"): + import_module("NS.othername.foo") + + with pytest.raises(ImportError, match="'ns\\.othername\\.FOO\\'"): + import_module("ns.othername.FOO") + + with pytest.raises(ImportError, match="'ns\\.othername\\.foo\\.BAR\\'"): + import_module("ns.othername.foo.BAR") + + def test_intermediate_packages(self, tmp_path): + """ + The finder should not import ``fullname`` if the intermediate segments + don't exist (see pypa/setuptools#4019). + """ + files = { + "src": { + "mypkg": { + "__init__.py": "", + "config.py": "a = 13", + "helloworld.py": "b = 13", + "components": { + "config.py": "a = 37", + }, + }, + } + } + jaraco.path.build(files, prefix=tmp_path) + + mapping = {"mypkg": str(tmp_path / "src/mypkg")} + template = _finder_template(str(uuid4()), mapping, {}) + + with contexts.save_paths(), contexts.save_sys_modules(): + for mod in ( + "mypkg", + "mypkg.config", + "mypkg.helloworld", + "mypkg.components", + "mypkg.components.config", + "mypkg.components.helloworld", + ): + sys.modules.pop(mod, None) + + self.install_finder(template) + + config = import_module("mypkg.components.config") + assert config.a == 37 + + helloworld = import_module("mypkg.helloworld") + assert helloworld.b == 13 + + with pytest.raises(ImportError): + import_module("mypkg.components.helloworld") + + +def test_pkg_roots(tmp_path): + """This test focus in getting a particular implementation detail right. + If at some point in time the implementation is changed for something different, + this test can be modified or even excluded. + """ + files = { + "a": {"b": {"__init__.py": "ab = 1"}, "__init__.py": "a = 1"}, + "d": {"__init__.py": "d = 1", "e": {"__init__.py": "de = 1"}}, + "f": {"g": {"h": {"__init__.py": "fgh = 1"}}}, + "other": {"__init__.py": "abc = 1"}, + "another": {"__init__.py": "abcxyz = 1"}, + "yet_another": {"__init__.py": "mnopq = 1"}, + } + jaraco.path.build(files, prefix=tmp_path) + package_dir = { + "a.b.c": "other", + "a.b.c.x.y.z": "another", + "m.n.o.p.q": "yet_another", + } + packages = [ + "a", + "a.b", + "a.b.c", + "a.b.c.x.y", + "a.b.c.x.y.z", + "d", + "d.e", + "f", + "f.g", + "f.g.h", + "m.n.o.p.q", + ] + roots = _find_package_roots(packages, package_dir, tmp_path) + assert roots == { + "a": str(tmp_path / "a"), + "a.b.c": str(tmp_path / "other"), + "a.b.c.x.y.z": str(tmp_path / "another"), + "d": str(tmp_path / "d"), + "f": str(tmp_path / "f"), + "m.n.o.p.q": str(tmp_path / "yet_another"), + } + + ns = set(dict(_find_namespaces(packages, roots))) + assert ns == {"f", "f.g"} + + ns = set(_find_virtual_namespaces(roots)) + assert ns == {"a.b", "a.b.c.x", "a.b.c.x.y", "m", "m.n", "m.n.o", "m.n.o.p"} + + +class TestOverallBehaviour: + PYPROJECT = """\ + [build-system] + requires = ["setuptools"] + build-backend = "setuptools.build_meta" + + [project] + name = "mypkg" + version = "3.14159" + """ + + # Any: Would need a TypedDict. Keep it simple for tests + FLAT_LAYOUT: dict[str, Any] = { + "pyproject.toml": dedent(PYPROJECT), + "MANIFEST.in": EXAMPLE["MANIFEST.in"], + "otherfile.py": "", + "mypkg": { + "__init__.py": "", + "mod1.py": "var = 42", + "subpackage": { + "__init__.py": "", + "mod2.py": "var = 13", + "resource_file.txt": "resource 39", + }, + }, + } + + EXAMPLES = { + "flat-layout": FLAT_LAYOUT, + "src-layout": { + "pyproject.toml": dedent(PYPROJECT), + "MANIFEST.in": EXAMPLE["MANIFEST.in"], + "otherfile.py": "", + "src": {"mypkg": FLAT_LAYOUT["mypkg"]}, + }, + "custom-layout": { + "pyproject.toml": dedent(PYPROJECT) + + dedent( + """\ + [tool.setuptools] + packages = ["mypkg", "mypkg.subpackage"] + + [tool.setuptools.package-dir] + "mypkg.subpackage" = "other" + """ + ), + "MANIFEST.in": EXAMPLE["MANIFEST.in"], + "otherfile.py": "", + "mypkg": { + "__init__.py": "", + "mod1.py": FLAT_LAYOUT["mypkg"]["mod1.py"], + }, + "other": FLAT_LAYOUT["mypkg"]["subpackage"], + }, + "namespace": { + "pyproject.toml": dedent(PYPROJECT), + "MANIFEST.in": EXAMPLE["MANIFEST.in"], + "otherfile.py": "", + "src": { + "mypkg": { + "mod1.py": FLAT_LAYOUT["mypkg"]["mod1.py"], + "subpackage": FLAT_LAYOUT["mypkg"]["subpackage"], + }, + }, + }, + } + + @pytest.mark.xfail(sys.platform == "darwin", reason="pypa/setuptools#4328") + @pytest.mark.parametrize("layout", EXAMPLES.keys()) + def test_editable_install(self, tmp_path, venv, layout, editable_opts): + project, _ = install_project( + "mypkg", venv, tmp_path, self.EXAMPLES[layout], *editable_opts + ) + + # Ensure stray files are not importable + cmd_import_error = """\ + try: + import otherfile + except ImportError as ex: + print(ex) + """ + out = venv.run(["python", "-c", dedent(cmd_import_error)]) + assert "No module named 'otherfile'" in out + + # Ensure the modules are importable + cmd_get_vars = """\ + import mypkg, mypkg.mod1, mypkg.subpackage.mod2 + print(mypkg.mod1.var, mypkg.subpackage.mod2.var) + """ + out = venv.run(["python", "-c", dedent(cmd_get_vars)]) + assert "42 13" in out + + # Ensure resources are reachable + cmd_get_resource = """\ + import mypkg.subpackage + from setuptools._importlib import resources as importlib_resources + text = importlib_resources.files(mypkg.subpackage) / "resource_file.txt" + print(text.read_text(encoding="utf-8")) + """ + out = venv.run(["python", "-c", dedent(cmd_get_resource)]) + assert "resource 39" in out + + # Ensure files are editable + mod1 = next(project.glob("**/mod1.py")) + mod2 = next(project.glob("**/mod2.py")) + resource_file = next(project.glob("**/resource_file.txt")) + + mod1.write_text("var = 17", encoding="utf-8") + mod2.write_text("var = 781", encoding="utf-8") + resource_file.write_text("resource 374", encoding="utf-8") + + out = venv.run(["python", "-c", dedent(cmd_get_vars)]) + assert "42 13" not in out + assert "17 781" in out + + out = venv.run(["python", "-c", dedent(cmd_get_resource)]) + assert "resource 39" not in out + assert "resource 374" in out + + +class TestLinkTree: + FILES = deepcopy(TestOverallBehaviour.EXAMPLES["src-layout"]) + FILES["pyproject.toml"] += dedent( + """\ + [tool.setuptools] + # Temporary workaround: both `include-package-data` and `package-data` configs + # can be removed after #3260 is fixed. + include-package-data = false + package-data = {"*" = ["*.txt"]} + + [tool.setuptools.packages.find] + where = ["src"] + exclude = ["*.subpackage*"] + """ + ) + FILES["src"]["mypkg"]["resource.not_in_manifest"] = "abc" + + def test_generated_tree(self, tmp_path): + jaraco.path.build(self.FILES, prefix=tmp_path) + + with _Path(tmp_path): + name = "mypkg-3.14159" + dist = Distribution({"script_name": "%PEP 517%"}) + dist.parse_config_files() + + wheel = Mock() + aux = tmp_path / ".aux" + build = tmp_path / ".build" + aux.mkdir() + build.mkdir() + + build_py = dist.get_command_obj("build_py") + build_py.editable_mode = True + build_py.build_lib = str(build) + build_py.ensure_finalized() + outputs = build_py.get_outputs() + output_mapping = build_py.get_output_mapping() + + make_tree = _LinkTree(dist, name, aux, build) + make_tree(wheel, outputs, output_mapping) + + mod1 = next(aux.glob("**/mod1.py")) + expected = tmp_path / "src/mypkg/mod1.py" + assert_link_to(mod1, expected) + + assert next(aux.glob("**/subpackage"), None) is None + assert next(aux.glob("**/mod2.py"), None) is None + assert next(aux.glob("**/resource_file.txt"), None) is None + + assert next(aux.glob("**/resource.not_in_manifest"), None) is None + + def test_strict_install(self, tmp_path, venv): + opts = ["--config-settings", "editable-mode=strict"] + install_project("mypkg", venv, tmp_path, self.FILES, *opts) + + out = venv.run(["python", "-c", "import mypkg.mod1; print(mypkg.mod1.var)"]) + assert "42" in out + + # Ensure packages excluded from distribution are not importable + cmd_import_error = """\ + try: + from mypkg import subpackage + except ImportError as ex: + print(ex) + """ + out = venv.run(["python", "-c", dedent(cmd_import_error)]) + assert "cannot import name 'subpackage'" in out + + # Ensure resource files excluded from distribution are not reachable + cmd_get_resource = """\ + import mypkg + from setuptools._importlib import resources as importlib_resources + try: + text = importlib_resources.files(mypkg) / "resource.not_in_manifest" + print(text.read_text(encoding="utf-8")) + except FileNotFoundError as ex: + print(ex) + """ + out = venv.run(["python", "-c", dedent(cmd_get_resource)]) + assert "No such file or directory" in out + assert "resource.not_in_manifest" in out + + +@pytest.mark.filterwarnings("ignore:.*compat.*:setuptools.SetuptoolsDeprecationWarning") +def test_compat_install(tmp_path, venv): + # TODO: Remove `compat` after Dec/2022. + opts = ["--config-settings", "editable-mode=compat"] + files = TestOverallBehaviour.EXAMPLES["custom-layout"] + install_project("mypkg", venv, tmp_path, files, *opts) + + out = venv.run(["python", "-c", "import mypkg.mod1; print(mypkg.mod1.var)"]) + assert "42" in out + + expected_path = comparable_path(str(tmp_path)) + + # Compatible behaviour will make spurious modules and excluded + # files importable directly from the original path + for cmd in ( + "import otherfile; print(otherfile)", + "import other; print(other)", + "import mypkg; print(mypkg)", + ): + out = comparable_path(venv.run(["python", "-c", cmd])) + assert expected_path in out + + # Compatible behaviour will not consider custom mappings + cmd = """\ + try: + from mypkg import subpackage; + except ImportError as ex: + print(ex) + """ + out = venv.run(["python", "-c", dedent(cmd)]) + assert "cannot import name 'subpackage'" in out + + +def test_pbr_integration(tmp_path, venv, editable_opts): + """Ensure editable installs work with pbr, issue #3500""" + files = { + "pyproject.toml": dedent( + """\ + [build-system] + requires = ["setuptools"] + build-backend = "setuptools.build_meta" + """ + ), + "setup.py": dedent( + """\ + __import__('setuptools').setup( + pbr=True, + setup_requires=["pbr"], + ) + """ + ), + "setup.cfg": dedent( + """\ + [metadata] + name = mypkg + + [files] + packages = + mypkg + """ + ), + "mypkg": { + "__init__.py": "", + "hello.py": "print('Hello world!')", + }, + "other": {"test.txt": "Another file in here."}, + } + venv.run(["python", "-m", "pip", "install", "pbr"]) + + with contexts.environment(PBR_VERSION="0.42"): + install_project("mypkg", venv, tmp_path, files, *editable_opts) + + out = venv.run(["python", "-c", "import mypkg.hello"]) + assert "Hello world!" in out + + +class TestCustomBuildPy: + """ + Issue #3501 indicates that some plugins/customizations might rely on: + + 1. ``build_py`` not running + 2. ``build_py`` always copying files to ``build_lib`` + + During the transition period setuptools should prevent potential errors from + happening due to those assumptions. + """ + + # TODO: Remove tests after _run_build_steps is removed. + + FILES = { + **TestOverallBehaviour.EXAMPLES["flat-layout"], + "setup.py": dedent( + """\ + import pathlib + from setuptools import setup + from setuptools.command.build_py import build_py as orig + + class my_build_py(orig): + def run(self): + super().run() + raise ValueError("TEST_RAISE") + + setup(cmdclass={"build_py": my_build_py}) + """ + ), + } + + def test_safeguarded_from_errors(self, tmp_path, venv): + """Ensure that errors in custom build_py are reported as warnings""" + # Warnings should show up + _, out = install_project("mypkg", venv, tmp_path, self.FILES) + assert "SetuptoolsDeprecationWarning" in out + assert "ValueError: TEST_RAISE" in out + # but installation should be successful + out = venv.run(["python", "-c", "import mypkg.mod1; print(mypkg.mod1.var)"]) + assert "42" in out + + +class TestCustomBuildWheel: + def install_custom_build_wheel(self, dist): + bdist_wheel_cls = dist.get_command_class("bdist_wheel") + + class MyBdistWheel(bdist_wheel_cls): + def get_tag(self): + # In issue #3513, we can see that some extensions may try to access + # the `plat_name` property in bdist_wheel + if self.plat_name.startswith("macosx-"): + _ = "macOS platform" + return super().get_tag() + + dist.cmdclass["bdist_wheel"] = MyBdistWheel + + def test_access_plat_name(self, tmpdir_cwd): + # Even when a custom bdist_wheel tries to access plat_name the build should + # be successful + jaraco.path.build({"module.py": "x = 42"}) + dist = Distribution() + dist.script_name = "setup.py" + dist.set_defaults() + self.install_custom_build_wheel(dist) + cmd = editable_wheel(dist) + cmd.ensure_finalized() + cmd.run() + wheel_file = str(next(Path().glob('dist/*.whl'))) + assert "editable" in wheel_file + + +class TestCustomBuildExt: + def install_custom_build_ext_distutils(self, dist): + from distutils.command.build_ext import build_ext as build_ext_cls + + class MyBuildExt(build_ext_cls): + pass + + dist.cmdclass["build_ext"] = MyBuildExt + + @pytest.mark.skipif( + sys.platform != "linux", reason="compilers may fail without correct setup" + ) + def test_distutils_leave_inplace_files(self, tmpdir_cwd): + jaraco.path.build({"module.c": ""}) + attrs = { + "ext_modules": [Extension("module", ["module.c"])], + } + dist = Distribution(attrs) + dist.script_name = "setup.py" + dist.set_defaults() + self.install_custom_build_ext_distutils(dist) + cmd = editable_wheel(dist) + cmd.ensure_finalized() + cmd.run() + wheel_file = str(next(Path().glob('dist/*.whl'))) + assert "editable" in wheel_file + files = [p for p in Path().glob("module.*") if p.suffix != ".c"] + assert len(files) == 1 + name = files[0].name + assert any(name.endswith(ext) for ext in EXTENSION_SUFFIXES) + + +def test_debugging_tips(tmpdir_cwd, monkeypatch): + """Make sure to display useful debugging tips to the user.""" + jaraco.path.build({"module.py": "x = 42"}) + dist = Distribution() + dist.script_name = "setup.py" + dist.set_defaults() + cmd = editable_wheel(dist) + cmd.ensure_finalized() + + SimulatedErr = type("SimulatedErr", (Exception,), {}) + simulated_failure = Mock(side_effect=SimulatedErr()) + monkeypatch.setattr(cmd, "get_finalized_command", simulated_failure) + + expected_msg = "following steps are recommended to help debug" + with pytest.raises(SimulatedErr), pytest.warns(_DebuggingTips, match=expected_msg): + cmd.run() + + +@pytest.mark.filterwarnings("error") +def test_encode_pth(): + """Ensure _encode_pth function does not produce encoding warnings""" + content = _encode_pth("tkmilan_ç_utf8") # no warnings (would be turned into errors) + assert isinstance(content, bytes) + + +def install_project(name, venv, tmp_path, files, *opts): + project = tmp_path / name + project.mkdir() + jaraco.path.build(files, prefix=project) + opts = [*opts, "--no-build-isolation"] # force current version of setuptools + out = venv.run( + ["python", "-m", "pip", "-v", "install", "-e", str(project), *opts], + stderr=subprocess.STDOUT, + ) + return project, out + + +def _addsitedirs(new_dirs): + """To use this function, it is necessary to insert new_dir in front of sys.path. + The Python process will try to import a ``sitecustomize`` module on startup. + If we manipulate sys.path/PYTHONPATH, we can force it to run our code, + which invokes ``addsitedir`` and ensure ``.pth`` files are loaded. + """ + content = '\n'.join( + ("import site",) + + tuple(f"site.addsitedir({os.fspath(new_dir)!r})" for new_dir in new_dirs) + ) + (new_dirs[0] / "sitecustomize.py").write_text(content, encoding="utf-8") + + +# ---- Assertion Helpers ---- + + +def assert_path(pkg, expected): + # __path__ is not guaranteed to exist, so we have to account for that + if pkg.__path__: + path = next(iter(pkg.__path__), None) + if path: + assert str(Path(path).resolve()) == expected + + +def assert_link_to(file: Path, other: Path) -> None: + if file.is_symlink(): + assert str(file.resolve()) == str(other.resolve()) + else: + file_stat = file.stat() + other_stat = other.stat() + assert file_stat[stat.ST_INO] == other_stat[stat.ST_INO] + assert file_stat[stat.ST_DEV] == other_stat[stat.ST_DEV] + + +def comparable_path(str_with_path: str) -> str: + return str_with_path.lower().replace(os.sep, "/").replace("//", "/") diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/test_egg_info.py b/.venv/lib/python3.12/site-packages/setuptools/tests/test_egg_info.py new file mode 100644 index 0000000000000000000000000000000000000000..528e2c13d8513727794cf65272aa20ce33e87d9d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/test_egg_info.py @@ -0,0 +1,1305 @@ +from __future__ import annotations + +import ast +import glob +import os +import re +import stat +import sys +import time +from pathlib import Path +from unittest import mock + +import pytest +from jaraco import path + +from setuptools import errors +from setuptools.command.egg_info import egg_info, manifest_maker, write_entries +from setuptools.dist import Distribution + +from . import contexts, environment +from .textwrap import DALS + + +class Environment(str): + pass + + +@pytest.fixture +def env(): + with contexts.tempdir(prefix='setuptools-test.') as env_dir: + env = Environment(env_dir) + os.chmod(env_dir, stat.S_IRWXU) + subs = 'home', 'lib', 'scripts', 'data', 'egg-base' + env.paths = dict((dirname, os.path.join(env_dir, dirname)) for dirname in subs) + list(map(os.mkdir, env.paths.values())) + path.build({ + env.paths['home']: { + '.pydistutils.cfg': DALS( + """ + [egg_info] + egg-base = {egg-base} + """.format(**env.paths) + ) + } + }) + yield env + + +class TestEggInfo: + setup_script = DALS( + """ + from setuptools import setup + + setup( + name='foo', + py_modules=['hello'], + entry_points={'console_scripts': ['hi = hello.run']}, + zip_safe=False, + ) + """ + ) + + def _create_project(self): + path.build({ + 'setup.py': self.setup_script, + 'hello.py': DALS( + """ + def run(): + print('hello') + """ + ), + }) + + @staticmethod + def _extract_mv_version(pkg_info_lines: list[str]) -> tuple[int, int]: + version_str = pkg_info_lines[0].split(' ')[1] + major, minor = map(int, version_str.split('.')[:2]) + return major, minor + + def test_egg_info_save_version_info_setup_empty(self, tmpdir_cwd, env): + """ + When the egg_info section is empty or not present, running + save_version_info should add the settings to the setup.cfg + in a deterministic order. + """ + setup_cfg = os.path.join(env.paths['home'], 'setup.cfg') + dist = Distribution() + ei = egg_info(dist) + ei.initialize_options() + ei.save_version_info(setup_cfg) + + with open(setup_cfg, 'r', encoding="utf-8") as f: + content = f.read() + + assert '[egg_info]' in content + assert 'tag_build =' in content + assert 'tag_date = 0' in content + + expected_order = ( + 'tag_build', + 'tag_date', + ) + + self._validate_content_order(content, expected_order) + + @staticmethod + def _validate_content_order(content, expected): + """ + Assert that the strings in expected appear in content + in order. + """ + pattern = '.*'.join(expected) + flags = re.MULTILINE | re.DOTALL + assert re.search(pattern, content, flags) + + def test_egg_info_save_version_info_setup_defaults(self, tmpdir_cwd, env): + """ + When running save_version_info on an existing setup.cfg + with the 'default' values present from a previous run, + the file should remain unchanged. + """ + setup_cfg = os.path.join(env.paths['home'], 'setup.cfg') + path.build({ + setup_cfg: DALS( + """ + [egg_info] + tag_build = + tag_date = 0 + """ + ), + }) + dist = Distribution() + ei = egg_info(dist) + ei.initialize_options() + ei.save_version_info(setup_cfg) + + with open(setup_cfg, 'r', encoding="utf-8") as f: + content = f.read() + + assert '[egg_info]' in content + assert 'tag_build =' in content + assert 'tag_date = 0' in content + + expected_order = ( + 'tag_build', + 'tag_date', + ) + + self._validate_content_order(content, expected_order) + + def test_expected_files_produced(self, tmpdir_cwd, env): + self._create_project() + + self._run_egg_info_command(tmpdir_cwd, env) + actual = os.listdir('foo.egg-info') + + expected = [ + 'PKG-INFO', + 'SOURCES.txt', + 'dependency_links.txt', + 'entry_points.txt', + 'not-zip-safe', + 'top_level.txt', + ] + assert sorted(actual) == expected + + def test_handling_utime_error(self, tmpdir_cwd, env): + dist = Distribution() + ei = egg_info(dist) + utime_patch = mock.patch('os.utime', side_effect=OSError("TEST")) + mkpath_patch = mock.patch( + 'setuptools.command.egg_info.egg_info.mkpath', return_val=None + ) + + with utime_patch, mkpath_patch: + import distutils.errors + + msg = r"Cannot update time stamp of directory 'None'" + with pytest.raises(distutils.errors.DistutilsFileError, match=msg): + ei.run() + + def test_license_is_a_string(self, tmpdir_cwd, env): + setup_config = DALS( + """ + [metadata] + name=foo + version=0.0.1 + license=file:MIT + """ + ) + + setup_script = DALS( + """ + from setuptools import setup + + setup() + """ + ) + + path.build({ + 'setup.py': setup_script, + 'setup.cfg': setup_config, + }) + + # This command should fail with a ValueError, but because it's + # currently configured to use a subprocess, the actual traceback + # object is lost and we need to parse it from stderr + with pytest.raises(AssertionError) as exc: + self._run_egg_info_command(tmpdir_cwd, env) + + # The only argument to the assertion error should be a traceback + # containing a ValueError + assert 'ValueError' in exc.value.args[0] + + def test_rebuilt(self, tmpdir_cwd, env): + """Ensure timestamps are updated when the command is re-run.""" + self._create_project() + + self._run_egg_info_command(tmpdir_cwd, env) + timestamp_a = os.path.getmtime('foo.egg-info') + + # arbitrary sleep just to handle *really* fast systems + time.sleep(0.001) + + self._run_egg_info_command(tmpdir_cwd, env) + timestamp_b = os.path.getmtime('foo.egg-info') + + assert timestamp_a != timestamp_b + + def test_manifest_template_is_read(self, tmpdir_cwd, env): + self._create_project() + path.build({ + 'MANIFEST.in': DALS( + """ + recursive-include docs *.rst + """ + ), + 'docs': { + 'usage.rst': "Run 'hi'", + }, + }) + self._run_egg_info_command(tmpdir_cwd, env) + egg_info_dir = os.path.join('.', 'foo.egg-info') + sources_txt = os.path.join(egg_info_dir, 'SOURCES.txt') + with open(sources_txt, encoding="utf-8") as f: + assert 'docs/usage.rst' in f.read().split('\n') + + def _setup_script_with_requires(self, requires, use_setup_cfg=False): + setup_script = DALS( + """ + from setuptools import setup + + setup(name='foo', zip_safe=False, %s) + """ + ) % ('' if use_setup_cfg else requires) + setup_config = requires if use_setup_cfg else '' + path.build({ + 'setup.py': setup_script, + 'setup.cfg': setup_config, + }) + + mismatch_marker = f"python_version<'{sys.version_info[0]}'" + # Alternate equivalent syntax. + mismatch_marker_alternate = f'python_version < "{sys.version_info[0]}"' + invalid_marker = "<=>++" + + class RequiresTestHelper: + @staticmethod + def parametrize(*test_list, **format_dict): + idlist = [] + argvalues = [] + for test in test_list: + test_params = test.lstrip().split('\n\n', 3) + name_kwargs = test_params.pop(0).split('\n') + if len(name_kwargs) > 1: + val = name_kwargs[1].strip() + install_cmd_kwargs = ast.literal_eval(val) + else: + install_cmd_kwargs = {} + name = name_kwargs[0].strip() + setup_py_requires, setup_cfg_requires, expected_requires = [ + DALS(a).format(**format_dict) for a in test_params + ] + for id_, requires, use_cfg in ( + (name, setup_py_requires, False), + (name + '_in_setup_cfg', setup_cfg_requires, True), + ): + idlist.append(id_) + marks = () + if requires.startswith('@xfail\n'): + requires = requires[7:] + marks = pytest.mark.xfail + argvalues.append( + pytest.param( + requires, + use_cfg, + expected_requires, + install_cmd_kwargs, + marks=marks, + ) + ) + return pytest.mark.parametrize( + ( + "requires", + "use_setup_cfg", + "expected_requires", + "install_cmd_kwargs", + ), + argvalues, + ids=idlist, + ) + + @RequiresTestHelper.parametrize( + # Format of a test: + # + # id + # install_cmd_kwargs [optional] + # + # requires block (when used in setup.py) + # + # requires block (when used in setup.cfg) + # + # expected contents of requires.txt + """ + install_requires_deterministic + + install_requires=["wheel>=0.5", "pytest"] + + [options] + install_requires = + wheel>=0.5 + pytest + + wheel>=0.5 + pytest + """, + """ + install_requires_ordered + + install_requires=["pytest>=3.0.2,!=10.9999"] + + [options] + install_requires = + pytest>=3.0.2,!=10.9999 + + pytest!=10.9999,>=3.0.2 + """, + """ + install_requires_with_marker + + install_requires=["barbazquux;{mismatch_marker}"], + + [options] + install_requires = + barbazquux; {mismatch_marker} + + [:{mismatch_marker_alternate}] + barbazquux + """, + """ + install_requires_with_extra + {'cmd': ['egg_info']} + + install_requires=["barbazquux [test]"], + + [options] + install_requires = + barbazquux [test] + + barbazquux[test] + """, + """ + install_requires_with_extra_and_marker + + install_requires=["barbazquux [test]; {mismatch_marker}"], + + [options] + install_requires = + barbazquux [test]; {mismatch_marker} + + [:{mismatch_marker_alternate}] + barbazquux[test] + """, + """ + setup_requires_with_markers + + setup_requires=["barbazquux;{mismatch_marker}"], + + [options] + setup_requires = + barbazquux; {mismatch_marker} + + """, + """ + extras_require_with_extra + {'cmd': ['egg_info']} + + extras_require={{"extra": ["barbazquux [test]"]}}, + + [options.extras_require] + extra = barbazquux [test] + + [extra] + barbazquux[test] + """, + """ + extras_require_with_extra_and_marker_in_req + + extras_require={{"extra": ["barbazquux [test]; {mismatch_marker}"]}}, + + [options.extras_require] + extra = + barbazquux [test]; {mismatch_marker} + + [extra] + + [extra:{mismatch_marker_alternate}] + barbazquux[test] + """, + # FIXME: ConfigParser does not allow : in key names! + """ + extras_require_with_marker + + extras_require={{":{mismatch_marker}": ["barbazquux"]}}, + + @xfail + [options.extras_require] + :{mismatch_marker} = barbazquux + + [:{mismatch_marker}] + barbazquux + """, + """ + extras_require_with_marker_in_req + + extras_require={{"extra": ["barbazquux; {mismatch_marker}"]}}, + + [options.extras_require] + extra = + barbazquux; {mismatch_marker} + + [extra] + + [extra:{mismatch_marker_alternate}] + barbazquux + """, + """ + extras_require_with_empty_section + + extras_require={{"empty": []}}, + + [options.extras_require] + empty = + + [empty] + """, + # Format arguments. + invalid_marker=invalid_marker, + mismatch_marker=mismatch_marker, + mismatch_marker_alternate=mismatch_marker_alternate, + ) + def test_requires( + self, + tmpdir_cwd, + env, + requires, + use_setup_cfg, + expected_requires, + install_cmd_kwargs, + ): + self._setup_script_with_requires(requires, use_setup_cfg) + self._run_egg_info_command(tmpdir_cwd, env, **install_cmd_kwargs) + egg_info_dir = os.path.join('.', 'foo.egg-info') + requires_txt = os.path.join(egg_info_dir, 'requires.txt') + if os.path.exists(requires_txt): + with open(requires_txt, encoding="utf-8") as fp: + install_requires = fp.read() + else: + install_requires = '' + assert install_requires.lstrip() == expected_requires + assert glob.glob(os.path.join(env.paths['lib'], 'barbazquux*')) == [] + + def test_install_requires_unordered_disallowed(self, tmpdir_cwd, env): + """ + Packages that pass unordered install_requires sequences + should be rejected as they produce non-deterministic + builds. See #458. + """ + req = 'install_requires={"fake-factory==0.5.2", "pytz"}' + self._setup_script_with_requires(req) + with pytest.raises(AssertionError): + self._run_egg_info_command(tmpdir_cwd, env) + + def test_extras_require_with_invalid_marker(self, tmpdir_cwd, env): + tmpl = 'extras_require={{":{marker}": ["barbazquux"]}},' + req = tmpl.format(marker=self.invalid_marker) + self._setup_script_with_requires(req) + with pytest.raises(AssertionError): + self._run_egg_info_command(tmpdir_cwd, env) + assert glob.glob(os.path.join(env.paths['lib'], 'barbazquux*')) == [] + + def test_extras_require_with_invalid_marker_in_req(self, tmpdir_cwd, env): + tmpl = 'extras_require={{"extra": ["barbazquux; {marker}"]}},' + req = tmpl.format(marker=self.invalid_marker) + self._setup_script_with_requires(req) + with pytest.raises(AssertionError): + self._run_egg_info_command(tmpdir_cwd, env) + assert glob.glob(os.path.join(env.paths['lib'], 'barbazquux*')) == [] + + def test_provides_extra(self, tmpdir_cwd, env): + self._setup_script_with_requires('extras_require={"foobar": ["barbazquux"]},') + environ = os.environ.copy().update( + HOME=env.paths['home'], + ) + environment.run_setup_py( + cmd=['egg_info'], + pypath=os.pathsep.join([env.paths['lib'], str(tmpdir_cwd)]), + data_stream=1, + env=environ, + ) + egg_info_dir = os.path.join('.', 'foo.egg-info') + with open(os.path.join(egg_info_dir, 'PKG-INFO'), encoding="utf-8") as fp: + pkg_info_lines = fp.read().split('\n') + assert 'Provides-Extra: foobar' in pkg_info_lines + assert 'Metadata-Version: 2.4' in pkg_info_lines + + def test_doesnt_provides_extra(self, tmpdir_cwd, env): + self._setup_script_with_requires( + """install_requires=["spam ; python_version<'3.6'"]""" + ) + environ = os.environ.copy().update( + HOME=env.paths['home'], + ) + environment.run_setup_py( + cmd=['egg_info'], + pypath=os.pathsep.join([env.paths['lib'], str(tmpdir_cwd)]), + data_stream=1, + env=environ, + ) + egg_info_dir = os.path.join('.', 'foo.egg-info') + with open(os.path.join(egg_info_dir, 'PKG-INFO'), encoding="utf-8") as fp: + pkg_info_text = fp.read() + assert 'Provides-Extra:' not in pkg_info_text + + @pytest.mark.parametrize( + ('files', 'license_in_sources'), + [ + ( + { + 'setup.cfg': DALS( + """ + [metadata] + license_file = LICENSE + """ + ), + 'LICENSE': "Test license", + }, + True, + ), # with license + ( + { + 'setup.cfg': DALS( + """ + [metadata] + license_file = INVALID_LICENSE + """ + ), + 'LICENSE': "Test license", + }, + False, + ), # with an invalid license + ( + { + 'setup.cfg': DALS( + """ + """ + ), + 'LICENSE': "Test license", + }, + True, + ), # no license_file attribute, LICENSE auto-included + ( + { + 'setup.cfg': DALS( + """ + [metadata] + license_file = LICENSE + """ + ), + 'MANIFEST.in': "exclude LICENSE", + 'LICENSE': "Test license", + }, + True, + ), # manifest is overwritten by license_file + pytest.param( + { + 'setup.cfg': DALS( + """ + [metadata] + license_file = LICEN[CS]E* + """ + ), + 'LICENSE': "Test license", + }, + True, + id="glob_pattern", + ), + ], + ) + def test_setup_cfg_license_file(self, tmpdir_cwd, env, files, license_in_sources): + self._create_project() + path.build(files) + + environment.run_setup_py( + cmd=['egg_info'], + pypath=os.pathsep.join([env.paths['lib'], str(tmpdir_cwd)]), + ) + egg_info_dir = os.path.join('.', 'foo.egg-info') + + sources_text = Path(egg_info_dir, "SOURCES.txt").read_text(encoding="utf-8") + + if license_in_sources: + assert 'LICENSE' in sources_text + else: + assert 'LICENSE' not in sources_text + # for invalid license test + assert 'INVALID_LICENSE' not in sources_text + + @pytest.mark.parametrize( + ('files', 'incl_licenses', 'excl_licenses'), + [ + ( + { + 'setup.cfg': DALS( + """ + [metadata] + license_files = + LICENSE-ABC + LICENSE-XYZ + """ + ), + 'LICENSE-ABC': "ABC license", + 'LICENSE-XYZ': "XYZ license", + }, + ['LICENSE-ABC', 'LICENSE-XYZ'], + [], + ), # with licenses + ( + { + 'setup.cfg': DALS( + """ + [metadata] + license_files = LICENSE-ABC, LICENSE-XYZ + """ + ), + 'LICENSE-ABC': "ABC license", + 'LICENSE-XYZ': "XYZ license", + }, + ['LICENSE-ABC', 'LICENSE-XYZ'], + [], + ), # with commas + ( + { + 'setup.cfg': DALS( + """ + [metadata] + license_files = + LICENSE-ABC + """ + ), + 'LICENSE-ABC': "ABC license", + 'LICENSE-XYZ': "XYZ license", + }, + ['LICENSE-ABC'], + ['LICENSE-XYZ'], + ), # with one license + ( + { + 'setup.cfg': DALS( + """ + [metadata] + license_files = + """ + ), + 'LICENSE-ABC': "ABC license", + 'LICENSE-XYZ': "XYZ license", + }, + [], + ['LICENSE-ABC', 'LICENSE-XYZ'], + ), # empty + ( + { + 'setup.cfg': DALS( + """ + [metadata] + license_files = LICENSE-XYZ + """ + ), + 'LICENSE-ABC': "ABC license", + 'LICENSE-XYZ': "XYZ license", + }, + ['LICENSE-XYZ'], + ['LICENSE-ABC'], + ), # on same line + ( + { + 'setup.cfg': DALS( + """ + [metadata] + license_files = + LICENSE-ABC + INVALID_LICENSE + """ + ), + 'LICENSE-ABC': "Test license", + }, + ['LICENSE-ABC'], + ['INVALID_LICENSE'], + ), # with an invalid license + ( + { + 'setup.cfg': DALS( + """ + """ + ), + 'LICENSE': "Test license", + }, + ['LICENSE'], + [], + ), # no license_files attribute, LICENSE auto-included + ( + { + 'setup.cfg': DALS( + """ + [metadata] + license_files = LICENSE + """ + ), + 'MANIFEST.in': "exclude LICENSE", + 'LICENSE': "Test license", + }, + ['LICENSE'], + [], + ), # manifest is overwritten by license_files + ( + { + 'setup.cfg': DALS( + """ + [metadata] + license_files = + LICENSE-ABC + LICENSE-XYZ + """ + ), + 'MANIFEST.in': "exclude LICENSE-XYZ", + 'LICENSE-ABC': "ABC license", + 'LICENSE-XYZ': "XYZ license", + # manifest is overwritten by license_files + }, + ['LICENSE-ABC', 'LICENSE-XYZ'], + [], + ), + pytest.param( + { + 'setup.cfg': "", + 'LICENSE-ABC': "ABC license", + 'COPYING-ABC': "ABC copying", + 'NOTICE-ABC': "ABC notice", + 'AUTHORS-ABC': "ABC authors", + 'LICENCE-XYZ': "XYZ license", + 'LICENSE': "License", + 'INVALID-LICENSE': "Invalid license", + }, + [ + 'LICENSE-ABC', + 'COPYING-ABC', + 'NOTICE-ABC', + 'AUTHORS-ABC', + 'LICENCE-XYZ', + 'LICENSE', + ], + ['INVALID-LICENSE'], + # ('LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*') + id="default_glob_patterns", + ), + pytest.param( + { + 'setup.cfg': DALS( + """ + [metadata] + license_files = + LICENSE* + """ + ), + 'LICENSE-ABC': "ABC license", + 'NOTICE-XYZ': "XYZ notice", + }, + ['LICENSE-ABC'], + ['NOTICE-XYZ'], + id="no_default_glob_patterns", + ), + pytest.param( + { + 'setup.cfg': DALS( + """ + [metadata] + license_files = + LICENSE-ABC + LICENSE* + """ + ), + 'LICENSE-ABC': "ABC license", + }, + ['LICENSE-ABC'], + [], + id="files_only_added_once", + ), + pytest.param( + { + 'setup.cfg': DALS( + """ + [metadata] + license_files = **/LICENSE + """ + ), + 'LICENSE': "ABC license", + 'LICENSE-OTHER': "Don't include", + 'vendor': {'LICENSE': "Vendor license"}, + }, + ['LICENSE', 'vendor/LICENSE'], + ['LICENSE-OTHER'], + id="recursive_glob", + ), + ], + ) + def test_setup_cfg_license_files( + self, tmpdir_cwd, env, files, incl_licenses, excl_licenses + ): + self._create_project() + path.build(files) + + environment.run_setup_py( + cmd=['egg_info'], + pypath=os.pathsep.join([env.paths['lib'], str(tmpdir_cwd)]), + ) + egg_info_dir = os.path.join('.', 'foo.egg-info') + + sources_text = Path(egg_info_dir, "SOURCES.txt").read_text(encoding="utf-8") + sources_lines = [line.strip() for line in sources_text.splitlines()] + + for lf in incl_licenses: + assert sources_lines.count(lf) == 1 + + for lf in excl_licenses: + assert sources_lines.count(lf) == 0 + + @pytest.mark.parametrize( + ('files', 'incl_licenses', 'excl_licenses'), + [ + ( + { + 'setup.cfg': DALS( + """ + [metadata] + license_file = + license_files = + """ + ), + 'LICENSE-ABC': "ABC license", + 'LICENSE-XYZ': "XYZ license", + }, + [], + ['LICENSE-ABC', 'LICENSE-XYZ'], + ), # both empty + ( + { + 'setup.cfg': DALS( + """ + [metadata] + license_file = + LICENSE-ABC + LICENSE-XYZ + """ + ), + 'LICENSE-ABC': "ABC license", + 'LICENSE-XYZ': "XYZ license", + # license_file is still singular + }, + [], + ['LICENSE-ABC', 'LICENSE-XYZ'], + ), + ( + { + 'setup.cfg': DALS( + """ + [metadata] + license_file = LICENSE-ABC + license_files = + LICENSE-XYZ + LICENSE-PQR + """ + ), + 'LICENSE-ABC': "ABC license", + 'LICENSE-PQR': "PQR license", + 'LICENSE-XYZ': "XYZ license", + }, + ['LICENSE-ABC', 'LICENSE-PQR', 'LICENSE-XYZ'], + [], + ), # combined + ( + { + 'setup.cfg': DALS( + """ + [metadata] + license_file = LICENSE-ABC + license_files = + LICENSE-ABC + LICENSE-XYZ + LICENSE-PQR + """ + ), + 'LICENSE-ABC': "ABC license", + 'LICENSE-PQR': "PQR license", + 'LICENSE-XYZ': "XYZ license", + # duplicate license + }, + ['LICENSE-ABC', 'LICENSE-PQR', 'LICENSE-XYZ'], + [], + ), + ( + { + 'setup.cfg': DALS( + """ + [metadata] + license_file = LICENSE-ABC + license_files = + LICENSE-XYZ + """ + ), + 'LICENSE-ABC': "ABC license", + 'LICENSE-PQR': "PQR license", + 'LICENSE-XYZ': "XYZ license", + # combined subset + }, + ['LICENSE-ABC', 'LICENSE-XYZ'], + ['LICENSE-PQR'], + ), + ( + { + 'setup.cfg': DALS( + """ + [metadata] + license_file = LICENSE-ABC + license_files = + LICENSE-XYZ + LICENSE-PQR + """ + ), + 'LICENSE-PQR': "Test license", + # with invalid licenses + }, + ['LICENSE-PQR'], + ['LICENSE-ABC', 'LICENSE-XYZ'], + ), + ( + { + 'setup.cfg': DALS( + """ + [metadata] + license_file = LICENSE-ABC + license_files = + LICENSE-PQR + LICENSE-XYZ + """ + ), + 'MANIFEST.in': "exclude LICENSE-ABC\nexclude LICENSE-PQR", + 'LICENSE-ABC': "ABC license", + 'LICENSE-PQR': "PQR license", + 'LICENSE-XYZ': "XYZ license", + # manifest is overwritten + }, + ['LICENSE-ABC', 'LICENSE-PQR', 'LICENSE-XYZ'], + [], + ), + pytest.param( + { + 'setup.cfg': DALS( + """ + [metadata] + license_file = LICENSE* + """ + ), + 'LICENSE-ABC': "ABC license", + 'NOTICE-XYZ': "XYZ notice", + }, + ['LICENSE-ABC'], + ['NOTICE-XYZ'], + id="no_default_glob_patterns", + ), + pytest.param( + { + 'setup.cfg': DALS( + """ + [metadata] + license_file = LICENSE* + license_files = + NOTICE* + """ + ), + 'LICENSE-ABC': "ABC license", + 'NOTICE-ABC': "ABC notice", + 'AUTHORS-ABC': "ABC authors", + }, + ['LICENSE-ABC', 'NOTICE-ABC'], + ['AUTHORS-ABC'], + id="combined_glob_patterrns", + ), + ], + ) + def test_setup_cfg_license_file_license_files( + self, tmpdir_cwd, env, files, incl_licenses, excl_licenses + ): + self._create_project() + path.build(files) + + environment.run_setup_py( + cmd=['egg_info'], + pypath=os.pathsep.join([env.paths['lib'], str(tmpdir_cwd)]), + ) + egg_info_dir = os.path.join('.', 'foo.egg-info') + + sources_text = Path(egg_info_dir, "SOURCES.txt").read_text(encoding="utf-8") + sources_lines = [line.strip() for line in sources_text.splitlines()] + + for lf in incl_licenses: + assert sources_lines.count(lf) == 1 + + for lf in excl_licenses: + assert sources_lines.count(lf) == 0 + + def test_license_file_attr_pkg_info(self, tmpdir_cwd, env): + """All matched license files should have a corresponding License-File.""" + self._create_project() + path.build({ + "setup.cfg": DALS( + """ + [metadata] + license_files = + NOTICE* + LICENSE* + **/LICENSE + """ + ), + "LICENSE-ABC": "ABC license", + "LICENSE-XYZ": "XYZ license", + "NOTICE": "included", + "IGNORE": "not include", + "vendor": {'LICENSE': "Vendor license"}, + }) + + environment.run_setup_py( + cmd=['egg_info'], + pypath=os.pathsep.join([env.paths['lib'], str(tmpdir_cwd)]), + ) + egg_info_dir = os.path.join('.', 'foo.egg-info') + with open(os.path.join(egg_info_dir, 'PKG-INFO'), encoding="utf-8") as fp: + pkg_info_lines = fp.read().split('\n') + license_file_lines = [ + line for line in pkg_info_lines if line.startswith('License-File:') + ] + + # Only 'NOTICE', LICENSE-ABC', and 'LICENSE-XYZ' should have been matched + # Also assert that order from license_files is keeped + assert len(license_file_lines) == 4 + assert "License-File: NOTICE" == license_file_lines[0] + assert "License-File: LICENSE-ABC" in license_file_lines[1:] + assert "License-File: LICENSE-XYZ" in license_file_lines[1:] + assert "License-File: vendor/LICENSE" in license_file_lines[3] + + def test_metadata_version(self, tmpdir_cwd, env): + """Make sure latest metadata version is used by default.""" + self._setup_script_with_requires("") + environment.run_setup_py( + cmd=['egg_info'], + pypath=os.pathsep.join([env.paths['lib'], str(tmpdir_cwd)]), + data_stream=1, + ) + egg_info_dir = os.path.join('.', 'foo.egg-info') + with open(os.path.join(egg_info_dir, 'PKG-INFO'), encoding="utf-8") as fp: + pkg_info_lines = fp.read().split('\n') + # Update metadata version if changed + assert self._extract_mv_version(pkg_info_lines) == (2, 4) + + def test_long_description_content_type(self, tmpdir_cwd, env): + # Test that specifying a `long_description_content_type` keyword arg to + # the `setup` function results in writing a `Description-Content-Type` + # line to the `PKG-INFO` file in the `.egg-info` + # directory. + # `Description-Content-Type` is described at + # https://github.com/pypa/python-packaging-user-guide/pull/258 + + self._setup_script_with_requires( + """long_description_content_type='text/markdown',""" + ) + environ = os.environ.copy().update( + HOME=env.paths['home'], + ) + environment.run_setup_py( + cmd=['egg_info'], + pypath=os.pathsep.join([env.paths['lib'], str(tmpdir_cwd)]), + data_stream=1, + env=environ, + ) + egg_info_dir = os.path.join('.', 'foo.egg-info') + with open(os.path.join(egg_info_dir, 'PKG-INFO'), encoding="utf-8") as fp: + pkg_info_lines = fp.read().split('\n') + expected_line = 'Description-Content-Type: text/markdown' + assert expected_line in pkg_info_lines + assert 'Metadata-Version: 2.4' in pkg_info_lines + + def test_long_description(self, tmpdir_cwd, env): + # Test that specifying `long_description` and `long_description_content_type` + # keyword args to the `setup` function results in writing + # the description in the message payload of the `PKG-INFO` file + # in the `.egg-info` directory. + self._setup_script_with_requires( + "long_description='This is a long description\\nover multiple lines'," + "long_description_content_type='text/markdown'," + ) + environment.run_setup_py( + cmd=['egg_info'], + pypath=os.pathsep.join([env.paths['lib'], str(tmpdir_cwd)]), + data_stream=1, + ) + egg_info_dir = os.path.join('.', 'foo.egg-info') + with open(os.path.join(egg_info_dir, 'PKG-INFO'), encoding="utf-8") as fp: + pkg_info_lines = fp.read().split('\n') + assert 'Metadata-Version: 2.4' in pkg_info_lines + assert '' == pkg_info_lines[-1] # last line should be empty + long_desc_lines = pkg_info_lines[pkg_info_lines.index('') :] + assert 'This is a long description' in long_desc_lines + assert 'over multiple lines' in long_desc_lines + + def test_project_urls(self, tmpdir_cwd, env): + # Test that specifying a `project_urls` dict to the `setup` + # function results in writing multiple `Project-URL` lines to + # the `PKG-INFO` file in the `.egg-info` + # directory. + # `Project-URL` is described at https://packaging.python.org + # /specifications/core-metadata/#project-url-multiple-use + + self._setup_script_with_requires( + """project_urls={ + 'Link One': 'https://example.com/one/', + 'Link Two': 'https://example.com/two/', + },""" + ) + environ = os.environ.copy().update( + HOME=env.paths['home'], + ) + environment.run_setup_py( + cmd=['egg_info'], + pypath=os.pathsep.join([env.paths['lib'], str(tmpdir_cwd)]), + data_stream=1, + env=environ, + ) + egg_info_dir = os.path.join('.', 'foo.egg-info') + with open(os.path.join(egg_info_dir, 'PKG-INFO'), encoding="utf-8") as fp: + pkg_info_lines = fp.read().split('\n') + expected_line = 'Project-URL: Link One, https://example.com/one/' + assert expected_line in pkg_info_lines + expected_line = 'Project-URL: Link Two, https://example.com/two/' + assert expected_line in pkg_info_lines + assert self._extract_mv_version(pkg_info_lines) >= (1, 2) + + def test_license(self, tmpdir_cwd, env): + """Test single line license.""" + self._setup_script_with_requires("license='MIT',") + environment.run_setup_py( + cmd=['egg_info'], + pypath=os.pathsep.join([env.paths['lib'], str(tmpdir_cwd)]), + data_stream=1, + ) + egg_info_dir = os.path.join('.', 'foo.egg-info') + with open(os.path.join(egg_info_dir, 'PKG-INFO'), encoding="utf-8") as fp: + pkg_info_lines = fp.read().split('\n') + assert 'License: MIT' in pkg_info_lines + + def test_license_escape(self, tmpdir_cwd, env): + """Test license is escaped correctly if longer than one line.""" + self._setup_script_with_requires( + "license='This is a long license text \\nover multiple lines'," + ) + environment.run_setup_py( + cmd=['egg_info'], + pypath=os.pathsep.join([env.paths['lib'], str(tmpdir_cwd)]), + data_stream=1, + ) + egg_info_dir = os.path.join('.', 'foo.egg-info') + with open(os.path.join(egg_info_dir, 'PKG-INFO'), encoding="utf-8") as fp: + pkg_info_lines = fp.read().split('\n') + + assert 'License: This is a long license text ' in pkg_info_lines + assert ' over multiple lines' in pkg_info_lines + assert 'text \n over multiple' in '\n'.join(pkg_info_lines) + + def test_python_requires_egg_info(self, tmpdir_cwd, env): + self._setup_script_with_requires("""python_requires='>=2.7.12',""") + environ = os.environ.copy().update( + HOME=env.paths['home'], + ) + environment.run_setup_py( + cmd=['egg_info'], + pypath=os.pathsep.join([env.paths['lib'], str(tmpdir_cwd)]), + data_stream=1, + env=environ, + ) + egg_info_dir = os.path.join('.', 'foo.egg-info') + with open(os.path.join(egg_info_dir, 'PKG-INFO'), encoding="utf-8") as fp: + pkg_info_lines = fp.read().split('\n') + assert 'Requires-Python: >=2.7.12' in pkg_info_lines + assert self._extract_mv_version(pkg_info_lines) >= (1, 2) + + def test_manifest_maker_warning_suppression(self): + fixtures = [ + "standard file not found: should have one of foo.py, bar.py", + "standard file 'setup.py' not found", + ] + + for msg in fixtures: + assert manifest_maker._should_suppress_warning(msg) + + def test_egg_info_includes_setup_py(self, tmpdir_cwd): + self._create_project() + dist = Distribution({"name": "foo", "version": "0.0.1"}) + dist.script_name = "non_setup.py" + egg_info_instance = egg_info(dist) + egg_info_instance.finalize_options() + egg_info_instance.run() + + assert 'setup.py' in egg_info_instance.filelist.files + + with open(egg_info_instance.egg_info + "/SOURCES.txt", encoding="utf-8") as f: + sources = f.read().split('\n') + assert 'setup.py' in sources + + def _run_egg_info_command(self, tmpdir_cwd, env, cmd=None, output=None): + environ = os.environ.copy().update( + HOME=env.paths['home'], + ) + if cmd is None: + cmd = [ + 'egg_info', + ] + code, data = environment.run_setup_py( + cmd=cmd, + pypath=os.pathsep.join([env.paths['lib'], str(tmpdir_cwd)]), + data_stream=1, + env=environ, + ) + assert not code, data + + if output: + assert output in data + + def test_egg_info_tag_only_once(self, tmpdir_cwd, env): + self._create_project() + path.build({ + 'setup.cfg': DALS( + """ + [egg_info] + tag_build = dev + tag_date = 0 + tag_svn_revision = 0 + """ + ), + }) + self._run_egg_info_command(tmpdir_cwd, env) + egg_info_dir = os.path.join('.', 'foo.egg-info') + with open(os.path.join(egg_info_dir, 'PKG-INFO'), encoding="utf-8") as fp: + pkg_info_lines = fp.read().split('\n') + assert 'Version: 0.0.0.dev0' in pkg_info_lines + + +class TestWriteEntries: + def test_invalid_entry_point(self, tmpdir_cwd, env): + dist = Distribution({"name": "foo", "version": "0.0.1"}) + dist.entry_points = {"foo": "foo = invalid-identifier:foo"} + cmd = dist.get_command_obj("egg_info") + expected_msg = r"Problems to parse .*invalid-identifier.*" + with pytest.raises(errors.OptionError, match=expected_msg) as ex: + write_entries(cmd, "entry_points", "entry_points.txt") + assert "ensure entry-point follows the spec" in ex.value.args[0] + + def test_valid_entry_point(self, tmpdir_cwd, env): + dist = Distribution({"name": "foo", "version": "0.0.1"}) + dist.entry_points = { + "abc": "foo = bar:baz", + "def": ["faa = bor:boz"], + } + cmd = dist.get_command_obj("egg_info") + write_entries(cmd, "entry_points", "entry_points.txt") + content = Path("entry_points.txt").read_text(encoding="utf-8") + assert "[abc]\nfoo = bar:baz\n" in content + assert "[def]\nfaa = bor:boz\n" in content diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/test_extern.py b/.venv/lib/python3.12/site-packages/setuptools/tests/test_extern.py new file mode 100644 index 0000000000000000000000000000000000000000..d7eb3c62c190dacdd4a054d2934962be2f4ee860 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/test_extern.py @@ -0,0 +1,15 @@ +import importlib +import pickle + +import packaging + +from setuptools import Distribution + + +def test_reimport_extern(): + packaging2 = importlib.import_module(packaging.__name__) + assert packaging is packaging2 + + +def test_distribution_picklable(): + pickle.loads(pickle.dumps(Distribution())) diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/test_find_packages.py b/.venv/lib/python3.12/site-packages/setuptools/tests/test_find_packages.py new file mode 100644 index 0000000000000000000000000000000000000000..9fd9f8f6637d13cb898fcd446a6b090323d02014 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/test_find_packages.py @@ -0,0 +1,218 @@ +"""Tests for automatic package discovery""" + +import os +import shutil +import tempfile + +import pytest + +from setuptools import find_namespace_packages, find_packages +from setuptools.discovery import FlatLayoutPackageFinder + +from .compat.py39 import os_helper + + +class TestFindPackages: + def setup_method(self, method): + self.dist_dir = tempfile.mkdtemp() + self._make_pkg_structure() + + def teardown_method(self, method): + shutil.rmtree(self.dist_dir) + + def _make_pkg_structure(self): + """Make basic package structure. + + dist/ + docs/ + conf.py + pkg/ + __pycache__/ + nspkg/ + mod.py + subpkg/ + assets/ + asset + __init__.py + setup.py + + """ + self.docs_dir = self._mkdir('docs', self.dist_dir) + self._touch('conf.py', self.docs_dir) + self.pkg_dir = self._mkdir('pkg', self.dist_dir) + self._mkdir('__pycache__', self.pkg_dir) + self.ns_pkg_dir = self._mkdir('nspkg', self.pkg_dir) + self._touch('mod.py', self.ns_pkg_dir) + self.sub_pkg_dir = self._mkdir('subpkg', self.pkg_dir) + self.asset_dir = self._mkdir('assets', self.sub_pkg_dir) + self._touch('asset', self.asset_dir) + self._touch('__init__.py', self.sub_pkg_dir) + self._touch('setup.py', self.dist_dir) + + def _mkdir(self, path, parent_dir=None): + if parent_dir: + path = os.path.join(parent_dir, path) + os.mkdir(path) + return path + + def _touch(self, path, dir_=None): + if dir_: + path = os.path.join(dir_, path) + open(path, 'wb').close() + return path + + def test_regular_package(self): + self._touch('__init__.py', self.pkg_dir) + packages = find_packages(self.dist_dir) + assert packages == ['pkg', 'pkg.subpkg'] + + def test_exclude(self): + self._touch('__init__.py', self.pkg_dir) + packages = find_packages(self.dist_dir, exclude=('pkg.*',)) + assert packages == ['pkg'] + + def test_exclude_recursive(self): + """ + Excluding a parent package should not exclude child packages as well. + """ + self._touch('__init__.py', self.pkg_dir) + self._touch('__init__.py', self.sub_pkg_dir) + packages = find_packages(self.dist_dir, exclude=('pkg',)) + assert packages == ['pkg.subpkg'] + + def test_include_excludes_other(self): + """ + If include is specified, other packages should be excluded. + """ + self._touch('__init__.py', self.pkg_dir) + alt_dir = self._mkdir('other_pkg', self.dist_dir) + self._touch('__init__.py', alt_dir) + packages = find_packages(self.dist_dir, include=['other_pkg']) + assert packages == ['other_pkg'] + + def test_dir_with_dot_is_skipped(self): + shutil.rmtree(os.path.join(self.dist_dir, 'pkg/subpkg/assets')) + data_dir = self._mkdir('some.data', self.pkg_dir) + self._touch('__init__.py', data_dir) + self._touch('file.dat', data_dir) + packages = find_packages(self.dist_dir) + assert 'pkg.some.data' not in packages + + def test_dir_with_packages_in_subdir_is_excluded(self): + """ + Ensure that a package in a non-package such as build/pkg/__init__.py + is excluded. + """ + build_dir = self._mkdir('build', self.dist_dir) + build_pkg_dir = self._mkdir('pkg', build_dir) + self._touch('__init__.py', build_pkg_dir) + packages = find_packages(self.dist_dir) + assert 'build.pkg' not in packages + + @pytest.mark.skipif(not os_helper.can_symlink(), reason='Symlink support required') + def test_symlinked_packages_are_included(self): + """ + A symbolically-linked directory should be treated like any other + directory when matched as a package. + + Create a link from lpkg -> pkg. + """ + self._touch('__init__.py', self.pkg_dir) + linked_pkg = os.path.join(self.dist_dir, 'lpkg') + os.symlink('pkg', linked_pkg) + assert os.path.isdir(linked_pkg) + packages = find_packages(self.dist_dir) + assert 'lpkg' in packages + + def _assert_packages(self, actual, expected): + assert set(actual) == set(expected) + + def test_pep420_ns_package(self): + packages = find_namespace_packages( + self.dist_dir, include=['pkg*'], exclude=['pkg.subpkg.assets'] + ) + self._assert_packages(packages, ['pkg', 'pkg.nspkg', 'pkg.subpkg']) + + def test_pep420_ns_package_no_includes(self): + packages = find_namespace_packages(self.dist_dir, exclude=['pkg.subpkg.assets']) + self._assert_packages(packages, ['docs', 'pkg', 'pkg.nspkg', 'pkg.subpkg']) + + def test_pep420_ns_package_no_includes_or_excludes(self): + packages = find_namespace_packages(self.dist_dir) + expected = ['docs', 'pkg', 'pkg.nspkg', 'pkg.subpkg', 'pkg.subpkg.assets'] + self._assert_packages(packages, expected) + + def test_regular_package_with_nested_pep420_ns_packages(self): + self._touch('__init__.py', self.pkg_dir) + packages = find_namespace_packages( + self.dist_dir, exclude=['docs', 'pkg.subpkg.assets'] + ) + self._assert_packages(packages, ['pkg', 'pkg.nspkg', 'pkg.subpkg']) + + def test_pep420_ns_package_no_non_package_dirs(self): + shutil.rmtree(self.docs_dir) + shutil.rmtree(os.path.join(self.dist_dir, 'pkg/subpkg/assets')) + packages = find_namespace_packages(self.dist_dir) + self._assert_packages(packages, ['pkg', 'pkg.nspkg', 'pkg.subpkg']) + + +class TestFlatLayoutPackageFinder: + EXAMPLES = { + "hidden-folders": ( + [".pkg/__init__.py", "pkg/__init__.py", "pkg/nested/file.txt"], + ["pkg", "pkg.nested"], + ), + "private-packages": ( + ["_pkg/__init__.py", "pkg/_private/__init__.py"], + ["pkg", "pkg._private"], + ), + "invalid-name": ( + ["invalid-pkg/__init__.py", "other.pkg/__init__.py", "yet,another/file.py"], + [], + ), + "docs": (["pkg/__init__.py", "docs/conf.py", "docs/readme.rst"], ["pkg"]), + "tests": ( + ["pkg/__init__.py", "tests/test_pkg.py", "tests/__init__.py"], + ["pkg"], + ), + "examples": ( + [ + "pkg/__init__.py", + "examples/__init__.py", + "examples/file.py", + "example/other_file.py", + # Sub-packages should always be fine + "pkg/example/__init__.py", + "pkg/examples/__init__.py", + ], + ["pkg", "pkg.examples", "pkg.example"], + ), + "tool-specific": ( + [ + "htmlcov/index.html", + "pkg/__init__.py", + "tasks/__init__.py", + "tasks/subpackage/__init__.py", + "fabfile/__init__.py", + "fabfile/subpackage/__init__.py", + # Sub-packages should always be fine + "pkg/tasks/__init__.py", + "pkg/fabfile/__init__.py", + ], + ["pkg", "pkg.tasks", "pkg.fabfile"], + ), + } + + @pytest.mark.parametrize("example", EXAMPLES.keys()) + def test_unwanted_directories_not_included(self, tmp_path, example): + files, expected_packages = self.EXAMPLES[example] + ensure_files(tmp_path, files) + found_packages = FlatLayoutPackageFinder.find(str(tmp_path)) + assert set(found_packages) == set(expected_packages) + + +def ensure_files(root_path, files): + for file in files: + path = root_path / file + path.parent.mkdir(parents=True, exist_ok=True) + path.touch() diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/test_find_py_modules.py b/.venv/lib/python3.12/site-packages/setuptools/tests/test_find_py_modules.py new file mode 100644 index 0000000000000000000000000000000000000000..8034b544294e5d30274bac82f24f93613120a0d4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/test_find_py_modules.py @@ -0,0 +1,73 @@ +"""Tests for automatic discovery of modules""" + +import os + +import pytest + +from setuptools.discovery import FlatLayoutModuleFinder, ModuleFinder + +from .compat.py39 import os_helper +from .test_find_packages import ensure_files + + +class TestModuleFinder: + def find(self, path, *args, **kwargs): + return set(ModuleFinder.find(str(path), *args, **kwargs)) + + EXAMPLES = { + # circumstance: (files, kwargs, expected_modules) + "simple_folder": ( + ["file.py", "other.py"], + {}, # kwargs + ["file", "other"], + ), + "exclude": ( + ["file.py", "other.py"], + {"exclude": ["f*"]}, + ["other"], + ), + "include": ( + ["file.py", "fole.py", "other.py"], + {"include": ["f*"], "exclude": ["fo*"]}, + ["file"], + ), + "invalid-name": (["my-file.py", "other.file.py"], {}, []), + } + + @pytest.mark.parametrize("example", EXAMPLES.keys()) + def test_finder(self, tmp_path, example): + files, kwargs, expected_modules = self.EXAMPLES[example] + ensure_files(tmp_path, files) + assert self.find(tmp_path, **kwargs) == set(expected_modules) + + @pytest.mark.skipif(not os_helper.can_symlink(), reason='Symlink support required') + def test_symlinked_packages_are_included(self, tmp_path): + src = "_myfiles/file.py" + ensure_files(tmp_path, [src]) + os.symlink(tmp_path / src, tmp_path / "link.py") + assert self.find(tmp_path) == {"link"} + + +class TestFlatLayoutModuleFinder: + def find(self, path, *args, **kwargs): + return set(FlatLayoutModuleFinder.find(str(path))) + + EXAMPLES = { + # circumstance: (files, expected_modules) + "hidden-files": ([".module.py"], []), + "private-modules": (["_module.py"], []), + "common-names": ( + ["setup.py", "conftest.py", "test.py", "tests.py", "example.py", "mod.py"], + ["mod"], + ), + "tool-specific": ( + ["tasks.py", "fabfile.py", "noxfile.py", "dodo.py", "manage.py", "mod.py"], + ["mod"], + ), + } + + @pytest.mark.parametrize("example", EXAMPLES.keys()) + def test_unwanted_files_not_included(self, tmp_path, example): + files, expected_modules = self.EXAMPLES[example] + ensure_files(tmp_path, files) + assert self.find(tmp_path) == set(expected_modules) diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/test_glob.py b/.venv/lib/python3.12/site-packages/setuptools/tests/test_glob.py new file mode 100644 index 0000000000000000000000000000000000000000..8d225a44610163c7d56d65b07c06f0f598ccfe84 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/test_glob.py @@ -0,0 +1,45 @@ +import pytest +from jaraco import path + +from setuptools.glob import glob + + +@pytest.mark.parametrize( + ('tree', 'pattern', 'matches'), + ( + ('', b'', []), + ('', '', []), + ( + """ + appveyor.yml + CHANGES.rst + LICENSE + MANIFEST.in + pyproject.toml + README.rst + setup.cfg + setup.py + """, + '*.rst', + ('CHANGES.rst', 'README.rst'), + ), + ( + """ + appveyor.yml + CHANGES.rst + LICENSE + MANIFEST.in + pyproject.toml + README.rst + setup.cfg + setup.py + """, + b'*.rst', + (b'CHANGES.rst', b'README.rst'), + ), + ), +) +def test_glob(monkeypatch, tmpdir, tree, pattern, matches): + monkeypatch.chdir(tmpdir) + path.build({name: '' for name in tree.split()}) + assert list(sorted(glob(pattern))) == list(sorted(matches)) diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/test_install_scripts.py b/.venv/lib/python3.12/site-packages/setuptools/tests/test_install_scripts.py new file mode 100644 index 0000000000000000000000000000000000000000..e62a6b7f318df2da0cf29e53c41f74e5525e78ac --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/test_install_scripts.py @@ -0,0 +1,89 @@ +"""install_scripts tests""" + +import sys + +import pytest + +from setuptools.command.install_scripts import install_scripts +from setuptools.dist import Distribution + +from . import contexts + + +class TestInstallScripts: + settings = dict( + name='foo', + entry_points={'console_scripts': ['foo=foo:foo']}, + version='0.0', + ) + unix_exe = '/usr/dummy-test-path/local/bin/python' + unix_spaces_exe = '/usr/bin/env dummy-test-python' + win32_exe = 'C:\\Dummy Test Path\\Program Files\\Python 3.6\\python.exe' + + def _run_install_scripts(self, install_dir, executable=None): + dist = Distribution(self.settings) + dist.script_name = 'setup.py' + cmd = install_scripts(dist) + cmd.install_dir = install_dir + if executable is not None: + bs = cmd.get_finalized_command('build_scripts') + bs.executable = executable + cmd.ensure_finalized() + with contexts.quiet(): + cmd.run() + + @pytest.mark.skipif(sys.platform == 'win32', reason='non-Windows only') + def test_sys_executable_escaping_unix(self, tmpdir, monkeypatch): + """ + Ensure that shebang is not quoted on Unix when getting the Python exe + from sys.executable. + """ + expected = f'#!{self.unix_exe}\n' + monkeypatch.setattr('sys.executable', self.unix_exe) + with tmpdir.as_cwd(): + self._run_install_scripts(str(tmpdir)) + with open(str(tmpdir.join('foo')), 'r', encoding="utf-8") as f: + actual = f.readline() + assert actual == expected + + @pytest.mark.skipif(sys.platform != 'win32', reason='Windows only') + def test_sys_executable_escaping_win32(self, tmpdir, monkeypatch): + """ + Ensure that shebang is quoted on Windows when getting the Python exe + from sys.executable and it contains a space. + """ + expected = f'#!"{self.win32_exe}"\n' + monkeypatch.setattr('sys.executable', self.win32_exe) + with tmpdir.as_cwd(): + self._run_install_scripts(str(tmpdir)) + with open(str(tmpdir.join('foo-script.py')), 'r', encoding="utf-8") as f: + actual = f.readline() + assert actual == expected + + @pytest.mark.skipif(sys.platform == 'win32', reason='non-Windows only') + def test_executable_with_spaces_escaping_unix(self, tmpdir): + """ + Ensure that shebang on Unix is not quoted, even when + a value with spaces + is specified using --executable. + """ + expected = f'#!{self.unix_spaces_exe}\n' + with tmpdir.as_cwd(): + self._run_install_scripts(str(tmpdir), self.unix_spaces_exe) + with open(str(tmpdir.join('foo')), 'r', encoding="utf-8") as f: + actual = f.readline() + assert actual == expected + + @pytest.mark.skipif(sys.platform != 'win32', reason='Windows only') + def test_executable_arg_escaping_win32(self, tmpdir): + """ + Ensure that shebang on Windows is quoted when + getting a path with spaces + from --executable, that is itself properly quoted. + """ + expected = f'#!"{self.win32_exe}"\n' + with tmpdir.as_cwd(): + self._run_install_scripts(str(tmpdir), '"' + self.win32_exe + '"') + with open(str(tmpdir.join('foo-script.py')), 'r', encoding="utf-8") as f: + actual = f.readline() + assert actual == expected diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/test_logging.py b/.venv/lib/python3.12/site-packages/setuptools/tests/test_logging.py new file mode 100644 index 0000000000000000000000000000000000000000..ea58001e93d8e4bcbd50bfd49303324d71858d16 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/test_logging.py @@ -0,0 +1,76 @@ +import functools +import inspect +import logging +import sys + +import pytest + +IS_PYPY = '__pypy__' in sys.builtin_module_names + + +setup_py = """\ +from setuptools import setup + +setup( + name="test_logging", + version="0.0" +) +""" + + +@pytest.mark.parametrize( + ('flag', 'expected_level'), [("--dry-run", "INFO"), ("--verbose", "DEBUG")] +) +def test_verbosity_level(tmp_path, monkeypatch, flag, expected_level): + """Make sure the correct verbosity level is set (issue #3038)""" + import setuptools # noqa: F401 # import setuptools to monkeypatch distutils + + import distutils # <- load distutils after all the patches take place + + logger = logging.Logger(__name__) + monkeypatch.setattr(logging, "root", logger) + unset_log_level = logger.getEffectiveLevel() + assert logging.getLevelName(unset_log_level) == "NOTSET" + + setup_script = tmp_path / "setup.py" + setup_script.write_text(setup_py, encoding="utf-8") + dist = distutils.core.run_setup(setup_script, stop_after="init") + dist.script_args = [flag, "sdist"] + dist.parse_command_line() # <- where the log level is set + log_level = logger.getEffectiveLevel() + log_level_name = logging.getLevelName(log_level) + assert log_level_name == expected_level + + +def flaky_on_pypy(func): + @functools.wraps(func) + def _func(): + try: + func() + except AssertionError: # pragma: no cover + if IS_PYPY: + msg = "Flaky monkeypatch on PyPy (#4124)" + pytest.xfail(f"{msg}. Original discussion in #3707, #3709.") + raise + + return _func + + +@flaky_on_pypy +def test_patching_does_not_cause_problems(): + # Ensure `dist.log` is only patched if necessary + + import _distutils_hack + + import setuptools.logging + + from distutils import dist + + setuptools.logging.configure() + + if _distutils_hack.enabled(): + # Modern logging infra, no problematic patching. + assert dist.__file__ is None or "setuptools" in dist.__file__ + assert isinstance(dist.log, logging.Logger) + else: + assert inspect.ismodule(dist.log) diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/test_manifest.py b/.venv/lib/python3.12/site-packages/setuptools/tests/test_manifest.py new file mode 100644 index 0000000000000000000000000000000000000000..903a528db0cc2bba27bbcef24aa1c59dc4156528 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/test_manifest.py @@ -0,0 +1,622 @@ +"""sdist tests""" + +from __future__ import annotations + +import contextlib +import io +import itertools +import logging +import os +import shutil +import sys +import tempfile + +import pytest + +from setuptools.command.egg_info import FileList, egg_info, translate_pattern +from setuptools.dist import Distribution +from setuptools.tests.textwrap import DALS + +from distutils import log +from distutils.errors import DistutilsTemplateError + +IS_PYPY = '__pypy__' in sys.builtin_module_names + + +def make_local_path(s): + """Converts '/' in a string to os.sep""" + return s.replace('/', os.sep) + + +SETUP_ATTRS = { + 'name': 'app', + 'version': '0.0', + 'packages': ['app'], +} + +SETUP_PY = f"""\ +from setuptools import setup + +setup(**{SETUP_ATTRS!r}) +""" + + +@contextlib.contextmanager +def quiet(): + old_stdout, old_stderr = sys.stdout, sys.stderr + sys.stdout, sys.stderr = io.StringIO(), io.StringIO() + try: + yield + finally: + sys.stdout, sys.stderr = old_stdout, old_stderr + + +def touch(filename): + open(filename, 'wb').close() + + +# The set of files always in the manifest, including all files in the +# .egg-info directory +default_files = frozenset( + map( + make_local_path, + [ + 'README.rst', + 'MANIFEST.in', + 'setup.py', + 'app.egg-info/PKG-INFO', + 'app.egg-info/SOURCES.txt', + 'app.egg-info/dependency_links.txt', + 'app.egg-info/top_level.txt', + 'app/__init__.py', + ], + ) +) + + +translate_specs: list[tuple[str, list[str], list[str]]] = [ + ('foo', ['foo'], ['bar', 'foobar']), + ('foo/bar', ['foo/bar'], ['foo/bar/baz', './foo/bar', 'foo']), + # Glob matching + ('*.txt', ['foo.txt', 'bar.txt'], ['foo/foo.txt']), + ('dir/*.txt', ['dir/foo.txt', 'dir/bar.txt', 'dir/.txt'], ['notdir/foo.txt']), + ('*/*.py', ['bin/start.py'], []), + ('docs/page-?.txt', ['docs/page-9.txt'], ['docs/page-10.txt']), + # Globstars change what they mean depending upon where they are + ( + 'foo/**/bar', + ['foo/bing/bar', 'foo/bing/bang/bar', 'foo/bar'], + ['foo/abar'], + ), + ( + 'foo/**', + ['foo/bar/bing.py', 'foo/x'], + ['/foo/x'], + ), + ( + '**', + ['x', 'abc/xyz', '@nything'], + [], + ), + # Character classes + ( + 'pre[one]post', + ['preopost', 'prenpost', 'preepost'], + ['prepost', 'preonepost'], + ), + ( + 'hello[!one]world', + ['helloxworld', 'helloyworld'], + ['hellooworld', 'helloworld', 'hellooneworld'], + ), + ( + '[]one].txt', + ['o.txt', '].txt', 'e.txt'], + ['one].txt'], + ), + ( + 'foo[!]one]bar', + ['fooybar'], + ['foo]bar', 'fooobar', 'fooebar'], + ), +] +""" +A spec of inputs for 'translate_pattern' and matches and mismatches +for that input. +""" + +match_params = itertools.chain.from_iterable( + zip(itertools.repeat(pattern), matches) + for pattern, matches, mismatches in translate_specs +) + + +@pytest.fixture(params=match_params) +def pattern_match(request): + return map(make_local_path, request.param) + + +mismatch_params = itertools.chain.from_iterable( + zip(itertools.repeat(pattern), mismatches) + for pattern, matches, mismatches in translate_specs +) + + +@pytest.fixture(params=mismatch_params) +def pattern_mismatch(request): + return map(make_local_path, request.param) + + +def test_translated_pattern_match(pattern_match): + pattern, target = pattern_match + assert translate_pattern(pattern).match(target) + + +def test_translated_pattern_mismatch(pattern_mismatch): + pattern, target = pattern_mismatch + assert not translate_pattern(pattern).match(target) + + +class TempDirTestCase: + def setup_method(self, method): + self.temp_dir = tempfile.mkdtemp() + self.old_cwd = os.getcwd() + os.chdir(self.temp_dir) + + def teardown_method(self, method): + os.chdir(self.old_cwd) + shutil.rmtree(self.temp_dir) + + +class TestManifestTest(TempDirTestCase): + def setup_method(self, method): + super().setup_method(method) + + f = open(os.path.join(self.temp_dir, 'setup.py'), 'w', encoding="utf-8") + f.write(SETUP_PY) + f.close() + """ + Create a file tree like: + - LICENSE + - README.rst + - testing.rst + - .hidden.rst + - app/ + - __init__.py + - a.txt + - b.txt + - c.rst + - static/ + - app.js + - app.js.map + - app.css + - app.css.map + """ + + for fname in ['README.rst', '.hidden.rst', 'testing.rst', 'LICENSE']: + touch(os.path.join(self.temp_dir, fname)) + + # Set up the rest of the test package + test_pkg = os.path.join(self.temp_dir, 'app') + os.mkdir(test_pkg) + for fname in ['__init__.py', 'a.txt', 'b.txt', 'c.rst']: + touch(os.path.join(test_pkg, fname)) + + # Some compiled front-end assets to include + static = os.path.join(test_pkg, 'static') + os.mkdir(static) + for fname in ['app.js', 'app.js.map', 'app.css', 'app.css.map']: + touch(os.path.join(static, fname)) + + def make_manifest(self, contents): + """Write a MANIFEST.in.""" + manifest = os.path.join(self.temp_dir, 'MANIFEST.in') + with open(manifest, 'w', encoding="utf-8") as f: + f.write(DALS(contents)) + + def get_files(self): + """Run egg_info and get all the files to include, as a set""" + dist = Distribution(SETUP_ATTRS) + dist.script_name = 'setup.py' + cmd = egg_info(dist) + cmd.ensure_finalized() + + cmd.run() + + return set(cmd.filelist.files) + + def test_no_manifest(self): + """Check a missing MANIFEST.in includes only the standard files.""" + assert (default_files - set(['MANIFEST.in'])) == self.get_files() + + def test_empty_files(self): + """Check an empty MANIFEST.in includes only the standard files.""" + self.make_manifest("") + assert default_files == self.get_files() + + def test_include(self): + """Include extra rst files in the project root.""" + self.make_manifest("include *.rst") + files = default_files | set(['testing.rst', '.hidden.rst']) + assert files == self.get_files() + + def test_exclude(self): + """Include everything in app/ except the text files""" + ml = make_local_path + self.make_manifest( + """ + include app/* + exclude app/*.txt + """ + ) + files = default_files | set([ml('app/c.rst')]) + assert files == self.get_files() + + def test_include_multiple(self): + """Include with multiple patterns.""" + ml = make_local_path + self.make_manifest("include app/*.txt app/static/*") + files = default_files | set([ + ml('app/a.txt'), + ml('app/b.txt'), + ml('app/static/app.js'), + ml('app/static/app.js.map'), + ml('app/static/app.css'), + ml('app/static/app.css.map'), + ]) + assert files == self.get_files() + + def test_graft(self): + """Include the whole app/static/ directory.""" + ml = make_local_path + self.make_manifest("graft app/static") + files = default_files | set([ + ml('app/static/app.js'), + ml('app/static/app.js.map'), + ml('app/static/app.css'), + ml('app/static/app.css.map'), + ]) + assert files == self.get_files() + + def test_graft_glob_syntax(self): + """Include the whole app/static/ directory.""" + ml = make_local_path + self.make_manifest("graft */static") + files = default_files | set([ + ml('app/static/app.js'), + ml('app/static/app.js.map'), + ml('app/static/app.css'), + ml('app/static/app.css.map'), + ]) + assert files == self.get_files() + + def test_graft_global_exclude(self): + """Exclude all *.map files in the project.""" + ml = make_local_path + self.make_manifest( + """ + graft app/static + global-exclude *.map + """ + ) + files = default_files | set([ml('app/static/app.js'), ml('app/static/app.css')]) + assert files == self.get_files() + + def test_global_include(self): + """Include all *.rst, *.js, and *.css files in the whole tree.""" + ml = make_local_path + self.make_manifest( + """ + global-include *.rst *.js *.css + """ + ) + files = default_files | set([ + '.hidden.rst', + 'testing.rst', + ml('app/c.rst'), + ml('app/static/app.js'), + ml('app/static/app.css'), + ]) + assert files == self.get_files() + + def test_graft_prune(self): + """Include all files in app/, except for the whole app/static/ dir.""" + ml = make_local_path + self.make_manifest( + """ + graft app + prune app/static + """ + ) + files = default_files | set([ml('app/a.txt'), ml('app/b.txt'), ml('app/c.rst')]) + assert files == self.get_files() + + +class TestFileListTest(TempDirTestCase): + """ + A copy of the relevant bits of distutils/tests/test_filelist.py, + to ensure setuptools' version of FileList keeps parity with distutils. + """ + + @pytest.fixture(autouse=os.getenv("SETUPTOOLS_USE_DISTUTILS") == "stdlib") + def _compat_record_logs(self, monkeypatch, caplog): + """Account for stdlib compatibility""" + + def _log(_logger, level, msg, args): + exc = sys.exc_info() + rec = logging.LogRecord("distutils", level, "", 0, msg, args, exc) + caplog.records.append(rec) + + monkeypatch.setattr(log.Log, "_log", _log) + + def get_records(self, caplog, *levels): + return [r for r in caplog.records if r.levelno in levels] + + def assertNoWarnings(self, caplog): + assert self.get_records(caplog, log.WARN) == [] + caplog.clear() + + def assertWarnings(self, caplog): + if IS_PYPY and not caplog.records: + pytest.xfail("caplog checks may not work well in PyPy") + else: + assert len(self.get_records(caplog, log.WARN)) > 0 + caplog.clear() + + def make_files(self, files): + for file in files: + file = os.path.join(self.temp_dir, file) + dirname, _basename = os.path.split(file) + os.makedirs(dirname, exist_ok=True) + touch(file) + + def test_process_template_line(self): + # testing all MANIFEST.in template patterns + file_list = FileList() + ml = make_local_path + + # simulated file list + self.make_files([ + 'foo.tmp', + 'ok', + 'xo', + 'four.txt', + 'buildout.cfg', + # filelist does not filter out VCS directories, + # it's sdist that does + ml('.hg/last-message.txt'), + ml('global/one.txt'), + ml('global/two.txt'), + ml('global/files.x'), + ml('global/here.tmp'), + ml('f/o/f.oo'), + ml('dir/graft-one'), + ml('dir/dir2/graft2'), + ml('dir3/ok'), + ml('dir3/sub/ok.txt'), + ]) + + MANIFEST_IN = DALS( + """\ + include ok + include xo + exclude xo + include foo.tmp + include buildout.cfg + global-include *.x + global-include *.txt + global-exclude *.tmp + recursive-include f *.oo + recursive-exclude global *.x + graft dir + prune dir3 + """ + ) + + for line in MANIFEST_IN.split('\n'): + if not line: + continue + file_list.process_template_line(line) + + wanted = [ + 'buildout.cfg', + 'four.txt', + 'ok', + ml('.hg/last-message.txt'), + ml('dir/graft-one'), + ml('dir/dir2/graft2'), + ml('f/o/f.oo'), + ml('global/one.txt'), + ml('global/two.txt'), + ] + + file_list.sort() + assert file_list.files == wanted + + def test_exclude_pattern(self): + # return False if no match + file_list = FileList() + assert not file_list.exclude_pattern('*.py') + + # return True if files match + file_list = FileList() + file_list.files = ['a.py', 'b.py'] + assert file_list.exclude_pattern('*.py') + + # test excludes + file_list = FileList() + file_list.files = ['a.py', 'a.txt'] + file_list.exclude_pattern('*.py') + file_list.sort() + assert file_list.files == ['a.txt'] + + def test_include_pattern(self): + # return False if no match + file_list = FileList() + self.make_files([]) + assert not file_list.include_pattern('*.py') + + # return True if files match + file_list = FileList() + self.make_files(['a.py', 'b.txt']) + assert file_list.include_pattern('*.py') + + # test * matches all files + file_list = FileList() + self.make_files(['a.py', 'b.txt']) + file_list.include_pattern('*') + file_list.sort() + assert file_list.files == ['a.py', 'b.txt'] + + def test_process_template_line_invalid(self): + # invalid lines + file_list = FileList() + for action in ( + 'include', + 'exclude', + 'global-include', + 'global-exclude', + 'recursive-include', + 'recursive-exclude', + 'graft', + 'prune', + 'blarg', + ): + with pytest.raises(DistutilsTemplateError): + file_list.process_template_line(action) + + def test_include(self, caplog): + caplog.set_level(logging.DEBUG) + ml = make_local_path + # include + file_list = FileList() + self.make_files(['a.py', 'b.txt', ml('d/c.py')]) + + file_list.process_template_line('include *.py') + file_list.sort() + assert file_list.files == ['a.py'] + self.assertNoWarnings(caplog) + + file_list.process_template_line('include *.rb') + file_list.sort() + assert file_list.files == ['a.py'] + self.assertWarnings(caplog) + + def test_exclude(self, caplog): + caplog.set_level(logging.DEBUG) + ml = make_local_path + # exclude + file_list = FileList() + file_list.files = ['a.py', 'b.txt', ml('d/c.py')] + + file_list.process_template_line('exclude *.py') + file_list.sort() + assert file_list.files == ['b.txt', ml('d/c.py')] + self.assertNoWarnings(caplog) + + file_list.process_template_line('exclude *.rb') + file_list.sort() + assert file_list.files == ['b.txt', ml('d/c.py')] + self.assertWarnings(caplog) + + def test_global_include(self, caplog): + caplog.set_level(logging.DEBUG) + ml = make_local_path + # global-include + file_list = FileList() + self.make_files(['a.py', 'b.txt', ml('d/c.py')]) + + file_list.process_template_line('global-include *.py') + file_list.sort() + assert file_list.files == ['a.py', ml('d/c.py')] + self.assertNoWarnings(caplog) + + file_list.process_template_line('global-include *.rb') + file_list.sort() + assert file_list.files == ['a.py', ml('d/c.py')] + self.assertWarnings(caplog) + + def test_global_exclude(self, caplog): + caplog.set_level(logging.DEBUG) + ml = make_local_path + # global-exclude + file_list = FileList() + file_list.files = ['a.py', 'b.txt', ml('d/c.py')] + + file_list.process_template_line('global-exclude *.py') + file_list.sort() + assert file_list.files == ['b.txt'] + self.assertNoWarnings(caplog) + + file_list.process_template_line('global-exclude *.rb') + file_list.sort() + assert file_list.files == ['b.txt'] + self.assertWarnings(caplog) + + def test_recursive_include(self, caplog): + caplog.set_level(logging.DEBUG) + ml = make_local_path + # recursive-include + file_list = FileList() + self.make_files(['a.py', ml('d/b.py'), ml('d/c.txt'), ml('d/d/e.py')]) + + file_list.process_template_line('recursive-include d *.py') + file_list.sort() + assert file_list.files == [ml('d/b.py'), ml('d/d/e.py')] + self.assertNoWarnings(caplog) + + file_list.process_template_line('recursive-include e *.py') + file_list.sort() + assert file_list.files == [ml('d/b.py'), ml('d/d/e.py')] + self.assertWarnings(caplog) + + def test_recursive_exclude(self, caplog): + caplog.set_level(logging.DEBUG) + ml = make_local_path + # recursive-exclude + file_list = FileList() + file_list.files = ['a.py', ml('d/b.py'), ml('d/c.txt'), ml('d/d/e.py')] + + file_list.process_template_line('recursive-exclude d *.py') + file_list.sort() + assert file_list.files == ['a.py', ml('d/c.txt')] + self.assertNoWarnings(caplog) + + file_list.process_template_line('recursive-exclude e *.py') + file_list.sort() + assert file_list.files == ['a.py', ml('d/c.txt')] + self.assertWarnings(caplog) + + def test_graft(self, caplog): + caplog.set_level(logging.DEBUG) + ml = make_local_path + # graft + file_list = FileList() + self.make_files(['a.py', ml('d/b.py'), ml('d/d/e.py'), ml('f/f.py')]) + + file_list.process_template_line('graft d') + file_list.sort() + assert file_list.files == [ml('d/b.py'), ml('d/d/e.py')] + self.assertNoWarnings(caplog) + + file_list.process_template_line('graft e') + file_list.sort() + assert file_list.files == [ml('d/b.py'), ml('d/d/e.py')] + self.assertWarnings(caplog) + + def test_prune(self, caplog): + caplog.set_level(logging.DEBUG) + ml = make_local_path + # prune + file_list = FileList() + file_list.files = ['a.py', ml('d/b.py'), ml('d/d/e.py'), ml('f/f.py')] + + file_list.process_template_line('prune d') + file_list.sort() + assert file_list.files == ['a.py', ml('f/f.py')] + self.assertNoWarnings(caplog) + + file_list.process_template_line('prune e') + file_list.sort() + assert file_list.files == ['a.py', ml('f/f.py')] + self.assertWarnings(caplog) diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/test_namespaces.py b/.venv/lib/python3.12/site-packages/setuptools/tests/test_namespaces.py new file mode 100644 index 0000000000000000000000000000000000000000..a0f4120bf7900b2118cc066034e036ab7af1798b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/test_namespaces.py @@ -0,0 +1,138 @@ +import subprocess +import sys + +from setuptools._path import paths_on_pythonpath + +from . import namespaces + + +class TestNamespaces: + def test_mixed_site_and_non_site(self, tmpdir): + """ + Installing two packages sharing the same namespace, one installed + to a site dir and the other installed just to a path on PYTHONPATH + should leave the namespace in tact and both packages reachable by + import. + """ + pkg_A = namespaces.build_namespace_package(tmpdir, 'myns.pkgA') + pkg_B = namespaces.build_namespace_package(tmpdir, 'myns.pkgB') + site_packages = tmpdir / 'site-packages' + path_packages = tmpdir / 'path-packages' + targets = site_packages, path_packages + # use pip to install to the target directory + install_cmd = [ + sys.executable, + '-m', + 'pip.__main__', + 'install', + str(pkg_A), + '-t', + str(site_packages), + ] + subprocess.check_call(install_cmd) + namespaces.make_site_dir(site_packages) + install_cmd = [ + sys.executable, + '-m', + 'pip.__main__', + 'install', + str(pkg_B), + '-t', + str(path_packages), + ] + subprocess.check_call(install_cmd) + try_import = [ + sys.executable, + '-c', + 'import myns.pkgA; import myns.pkgB', + ] + with paths_on_pythonpath(map(str, targets)): + subprocess.check_call(try_import) + + def test_pkg_resources_import(self, tmpdir): + """ + Ensure that a namespace package doesn't break on import + of pkg_resources. + """ + pkg = namespaces.build_namespace_package(tmpdir, 'myns.pkgA') + target = tmpdir / 'packages' + target.mkdir() + install_cmd = [ + sys.executable, + '-m', + 'pip', + 'install', + '-t', + str(target), + str(pkg), + ] + with paths_on_pythonpath([str(target)]): + subprocess.check_call(install_cmd) + namespaces.make_site_dir(target) + try_import = [ + sys.executable, + '-c', + 'import pkg_resources', + ] + with paths_on_pythonpath([str(target)]): + subprocess.check_call(try_import) + + def test_namespace_package_installed_and_cwd(self, tmpdir): + """ + Installing a namespace packages but also having it in the current + working directory, only one version should take precedence. + """ + pkg_A = namespaces.build_namespace_package(tmpdir, 'myns.pkgA') + target = tmpdir / 'packages' + # use pip to install to the target directory + install_cmd = [ + sys.executable, + '-m', + 'pip.__main__', + 'install', + str(pkg_A), + '-t', + str(target), + ] + subprocess.check_call(install_cmd) + namespaces.make_site_dir(target) + + # ensure that package imports and pkg_resources imports + pkg_resources_imp = [ + sys.executable, + '-c', + 'import pkg_resources; import myns.pkgA', + ] + with paths_on_pythonpath([str(target)]): + subprocess.check_call(pkg_resources_imp, cwd=str(pkg_A)) + + def test_packages_in_the_same_namespace_installed_and_cwd(self, tmpdir): + """ + Installing one namespace package and also have another in the same + namespace in the current working directory, both of them must be + importable. + """ + pkg_A = namespaces.build_namespace_package(tmpdir, 'myns.pkgA') + pkg_B = namespaces.build_namespace_package(tmpdir, 'myns.pkgB') + target = tmpdir / 'packages' + # use pip to install to the target directory + install_cmd = [ + sys.executable, + '-m', + 'pip.__main__', + 'install', + str(pkg_A), + '-t', + str(target), + ] + subprocess.check_call(install_cmd) + namespaces.make_site_dir(target) + + # ensure that all packages import and pkg_resources imports + pkg_resources_imp = [ + sys.executable, + '-c', + 'import pkg_resources; import myns.pkgA; import myns.pkgB', + ] + with paths_on_pythonpath([str(target)]): + subprocess.check_call(pkg_resources_imp, cwd=str(pkg_B)) diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/test_packageindex.py b/.venv/lib/python3.12/site-packages/setuptools/tests/test_packageindex.py new file mode 100644 index 0000000000000000000000000000000000000000..2a6e5917a8733c71a5d9b29d4bde6fc12cc1e183 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/test_packageindex.py @@ -0,0 +1,267 @@ +import http.client +import re +import urllib.error +import urllib.request +from inspect import cleandoc + +import pytest + +import setuptools.package_index + +import distutils.errors + + +class TestPackageIndex: + def test_regex(self): + hash_url = 'http://other_url?:action=show_md5&' + hash_url += 'digest=0123456789abcdef0123456789abcdef' + doc = """ + Name + (md5) + """.lstrip().format(**locals()) + assert setuptools.package_index.PYPI_MD5.match(doc) + + def test_bad_url_bad_port(self): + index = setuptools.package_index.PackageIndex() + url = 'http://127.0.0.1:0/nonesuch/test_package_index' + with pytest.raises(Exception, match=re.escape(url)): + v = index.open_url(url) + assert isinstance(v, urllib.error.HTTPError) + + def test_bad_url_typo(self): + # issue 16 + # easy_install inquant.contentmirror.plone breaks because of a typo + # in its home URL + index = setuptools.package_index.PackageIndex(hosts=('www.example.com',)) + + url = 'url:%20https://svn.plone.org/svn/collective/inquant.contentmirror.plone/trunk' + + with pytest.raises(Exception, match=re.escape(url)): + v = index.open_url(url) + assert isinstance(v, urllib.error.HTTPError) + + def test_bad_url_bad_status_line(self): + index = setuptools.package_index.PackageIndex(hosts=('www.example.com',)) + + def _urlopen(*args): + raise http.client.BadStatusLine('line') + + index.opener = _urlopen + url = 'http://example.com' + with pytest.raises(Exception, match=r'line'): + index.open_url(url) + + def test_bad_url_double_scheme(self): + """ + A bad URL with a double scheme should raise a DistutilsError. + """ + index = setuptools.package_index.PackageIndex(hosts=('www.example.com',)) + + # issue 20 + url = 'http://http://svn.pythonpaste.org/Paste/wphp/trunk' + try: + index.open_url(url) + except distutils.errors.DistutilsError as error: + msg = str(error) + assert ( + 'nonnumeric port' in msg + or 'getaddrinfo failed' in msg + or 'Name or service not known' in msg + ) + return + raise RuntimeError("Did not raise") + + def test_url_ok(self): + index = setuptools.package_index.PackageIndex(hosts=('www.example.com',)) + url = 'file:///tmp/test_package_index' + assert index.url_ok(url, True) + + def test_parse_bdist_wininst(self): + parse = setuptools.package_index.parse_bdist_wininst + + actual = parse('reportlab-2.5.win32-py2.4.exe') + expected = 'reportlab-2.5', '2.4', 'win32' + assert actual == expected + + actual = parse('reportlab-2.5.win32.exe') + expected = 'reportlab-2.5', None, 'win32' + assert actual == expected + + actual = parse('reportlab-2.5.win-amd64-py2.7.exe') + expected = 'reportlab-2.5', '2.7', 'win-amd64' + assert actual == expected + + actual = parse('reportlab-2.5.win-amd64.exe') + expected = 'reportlab-2.5', None, 'win-amd64' + assert actual == expected + + def test__vcs_split_rev_from_url(self): + """ + Test the basic usage of _vcs_split_rev_from_url + """ + vsrfu = setuptools.package_index.PackageIndex._vcs_split_rev_from_url + url, rev = vsrfu('https://example.com/bar@2995') + assert url == 'https://example.com/bar' + assert rev == '2995' + + def test_local_index(self, tmpdir): + """ + local_open should be able to read an index from the file system. + """ + index_file = tmpdir / 'index.html' + with index_file.open('w') as f: + f.write('
content
') + url = 'file:' + urllib.request.pathname2url(str(tmpdir)) + '/' + res = setuptools.package_index.local_open(url) + assert 'content' in res.read() + + def test_egg_fragment(self): + """ + EGG fragments must comply to PEP 440 + """ + epoch = [ + '', + '1!', + ] + releases = [ + '0', + '0.0', + '0.0.0', + ] + pre = [ + 'a0', + 'b0', + 'rc0', + ] + post = ['.post0'] + dev = [ + '.dev0', + ] + local = [ + ('', ''), + ('+ubuntu.0', '+ubuntu.0'), + ('+ubuntu-0', '+ubuntu.0'), + ('+ubuntu_0', '+ubuntu.0'), + ] + versions = [ + [''.join([e, r, p, loc]) for loc in locs] + for e in epoch + for r in releases + for p in sum([pre, post, dev], ['']) + for locs in local + ] + for v, vc in versions: + dists = list( + setuptools.package_index.distros_for_url( + 'http://example.com/example-foo.zip#egg=example-foo-' + v + ) + ) + assert dists[0].version == '' + assert dists[1].version == vc + + def test_download_git_with_rev(self, tmp_path, fp): + url = 'git+https://github.example/group/project@master#egg=foo' + index = setuptools.package_index.PackageIndex() + + expected_dir = tmp_path / 'project@master' + fp.register([ + 'git', + 'clone', + '--quiet', + 'https://github.example/group/project', + expected_dir, + ]) + fp.register(['git', '-C', expected_dir, 'checkout', '--quiet', 'master']) + + result = index.download(url, tmp_path) + + assert result == str(expected_dir) + assert len(fp.calls) == 2 + + def test_download_git_no_rev(self, tmp_path, fp): + url = 'git+https://github.example/group/project#egg=foo' + index = setuptools.package_index.PackageIndex() + + expected_dir = tmp_path / 'project' + fp.register([ + 'git', + 'clone', + '--quiet', + 'https://github.example/group/project', + expected_dir, + ]) + index.download(url, tmp_path) + + def test_download_svn(self, tmp_path): + url = 'svn+https://svn.example/project#egg=foo' + index = setuptools.package_index.PackageIndex() + + msg = r".*SVN download is not supported.*" + with pytest.raises(distutils.errors.DistutilsError, match=msg): + index.download(url, tmp_path) + + +class TestContentCheckers: + def test_md5(self): + checker = setuptools.package_index.HashChecker.from_url( + 'http://foo/bar#md5=f12895fdffbd45007040d2e44df98478' + ) + checker.feed('You should probably not be using MD5'.encode('ascii')) + assert checker.hash.hexdigest() == 'f12895fdffbd45007040d2e44df98478' + assert checker.is_valid() + + def test_other_fragment(self): + "Content checks should succeed silently if no hash is present" + checker = setuptools.package_index.HashChecker.from_url( + 'http://foo/bar#something%20completely%20different' + ) + checker.feed('anything'.encode('ascii')) + assert checker.is_valid() + + def test_blank_md5(self): + "Content checks should succeed if a hash is empty" + checker = setuptools.package_index.HashChecker.from_url('http://foo/bar#md5=') + checker.feed('anything'.encode('ascii')) + assert checker.is_valid() + + def test_get_hash_name_md5(self): + checker = setuptools.package_index.HashChecker.from_url( + 'http://foo/bar#md5=f12895fdffbd45007040d2e44df98478' + ) + assert checker.hash_name == 'md5' + + def test_report(self): + checker = setuptools.package_index.HashChecker.from_url( + 'http://foo/bar#md5=f12895fdffbd45007040d2e44df98478' + ) + rep = checker.report(lambda x: x, 'My message about %s') + assert rep == 'My message about md5' + + +class TestPyPIConfig: + def test_percent_in_password(self, tmp_home_dir): + pypirc = tmp_home_dir / '.pypirc' + pypirc.write_text( + cleandoc( + """ + [pypi] + repository=https://pypi.org + username=jaraco + password=pity% + """ + ), + encoding="utf-8", + ) + cfg = setuptools.package_index.PyPIConfig() + cred = cfg.creds_by_repository['https://pypi.org'] + assert cred.username == 'jaraco' + assert cred.password == 'pity%' + + +@pytest.mark.timeout(1) +def test_REL_DoS(): + """ + REL should not hang on a contrived attack string. + """ + setuptools.package_index.REL.search('< rel=' + ' ' * 2**12) diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/test_sandbox.py b/.venv/lib/python3.12/site-packages/setuptools/tests/test_sandbox.py new file mode 100644 index 0000000000000000000000000000000000000000..a476b7c93d7441834f415223cb386859581724f8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/test_sandbox.py @@ -0,0 +1,134 @@ +"""develop tests""" + +import os +import types + +import pytest + +import pkg_resources +import setuptools.sandbox + + +class TestSandbox: + def test_devnull(self, tmpdir): + with setuptools.sandbox.DirectorySandbox(str(tmpdir)): + self._file_writer(os.devnull) + + @staticmethod + def _file_writer(path): + def do_write(): + with open(path, 'w', encoding="utf-8") as f: + f.write('xxx') + + return do_write + + def test_setup_py_with_BOM(self): + """ + It should be possible to execute a setup.py with a Byte Order Mark + """ + target = pkg_resources.resource_filename(__name__, 'script-with-bom.py') + namespace = types.ModuleType('namespace') + setuptools.sandbox._execfile(target, vars(namespace)) + assert namespace.result == 'passed' + + def test_setup_py_with_CRLF(self, tmpdir): + setup_py = tmpdir / 'setup.py' + with setup_py.open('wb') as stream: + stream.write(b'"degenerate script"\r\n') + setuptools.sandbox._execfile(str(setup_py), globals()) + + +class TestExceptionSaver: + def test_exception_trapped(self): + with setuptools.sandbox.ExceptionSaver(): + raise ValueError("details") + + def test_exception_resumed(self): + with setuptools.sandbox.ExceptionSaver() as saved_exc: + raise ValueError("details") + + with pytest.raises(ValueError) as caught: + saved_exc.resume() + + assert isinstance(caught.value, ValueError) + assert str(caught.value) == 'details' + + def test_exception_reconstructed(self): + orig_exc = ValueError("details") + + with setuptools.sandbox.ExceptionSaver() as saved_exc: + raise orig_exc + + with pytest.raises(ValueError) as caught: + saved_exc.resume() + + assert isinstance(caught.value, ValueError) + assert caught.value is not orig_exc + + def test_no_exception_passes_quietly(self): + with setuptools.sandbox.ExceptionSaver() as saved_exc: + pass + + saved_exc.resume() + + def test_unpickleable_exception(self): + class CantPickleThis(Exception): + "This Exception is unpickleable because it's not in globals" + + def __repr__(self) -> str: + return f'CantPickleThis{self.args!r}' + + with setuptools.sandbox.ExceptionSaver() as saved_exc: + raise CantPickleThis('detail') + + with pytest.raises(setuptools.sandbox.UnpickleableException) as caught: + saved_exc.resume() + + assert str(caught.value) == "CantPickleThis('detail',)" + + def test_unpickleable_exception_when_hiding_setuptools(self): + """ + As revealed in #440, an infinite recursion can occur if an unpickleable + exception while setuptools is hidden. Ensure this doesn't happen. + """ + + class ExceptionUnderTest(Exception): + """ + An unpickleable exception (not in globals). + """ + + with pytest.raises(setuptools.sandbox.UnpickleableException) as caught: + with setuptools.sandbox.save_modules(): + setuptools.sandbox.hide_setuptools() + raise ExceptionUnderTest + + (msg,) = caught.value.args + assert msg == 'ExceptionUnderTest()' + + def test_sandbox_violation_raised_hiding_setuptools(self, tmpdir): + """ + When in a sandbox with setuptools hidden, a SandboxViolation + should reflect a proper exception and not be wrapped in + an UnpickleableException. + """ + + def write_file(): + "Trigger a SandboxViolation by writing outside the sandbox" + with open('/etc/foo', 'w', encoding="utf-8"): + pass + + with pytest.raises(setuptools.sandbox.SandboxViolation) as caught: + with setuptools.sandbox.save_modules(): + setuptools.sandbox.hide_setuptools() + with setuptools.sandbox.DirectorySandbox(str(tmpdir)): + write_file() + + cmd, args, kwargs = caught.value.args + assert cmd == 'open' + assert args == ('/etc/foo', 'w') + assert kwargs == {"encoding": "utf-8"} + + msg = str(caught.value) + assert 'open' in msg + assert "('/etc/foo', 'w')" in msg + assert "{'encoding': 'utf-8'}" in msg diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/test_sdist.py b/.venv/lib/python3.12/site-packages/setuptools/tests/test_sdist.py new file mode 100644 index 0000000000000000000000000000000000000000..19d8ddf6dafb0cacc044a6021f283d3e9faaf800 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/test_sdist.py @@ -0,0 +1,984 @@ +"""sdist tests""" + +import contextlib +import io +import logging +import os +import pathlib +import sys +import tarfile +import tempfile +import unicodedata +from inspect import cleandoc +from pathlib import Path +from unittest import mock + +import jaraco.path +import pytest + +from setuptools import Command, SetuptoolsDeprecationWarning +from setuptools._importlib import metadata +from setuptools.command.egg_info import manifest_maker +from setuptools.command.sdist import sdist +from setuptools.dist import Distribution +from setuptools.extension import Extension +from setuptools.tests import fail_on_ascii + +from .text import Filenames + +import distutils +from distutils.core import run_setup + +SETUP_ATTRS = { + 'name': 'sdist_test', + 'version': '0.0', + 'packages': ['sdist_test'], + 'package_data': {'sdist_test': ['*.txt']}, + 'data_files': [("data", [os.path.join("d", "e.dat")])], +} + +SETUP_PY = f"""\ +from setuptools import setup + +setup(**{SETUP_ATTRS!r}) +""" + +EXTENSION = Extension( + name="sdist_test.f", + sources=[os.path.join("sdist_test", "f.c")], + depends=[os.path.join("sdist_test", "f.h")], +) +EXTENSION_SOURCES = EXTENSION.sources + EXTENSION.depends + + +@contextlib.contextmanager +def quiet(): + old_stdout, old_stderr = sys.stdout, sys.stderr + sys.stdout, sys.stderr = io.StringIO(), io.StringIO() + try: + yield + finally: + sys.stdout, sys.stderr = old_stdout, old_stderr + + +# Convert to POSIX path +def posix(path): + if not isinstance(path, str): + return path.replace(os.sep.encode('ascii'), b'/') + else: + return path.replace(os.sep, '/') + + +# HFS Plus uses decomposed UTF-8 +def decompose(path): + if isinstance(path, str): + return unicodedata.normalize('NFD', path) + try: + path = path.decode('utf-8') + path = unicodedata.normalize('NFD', path) + path = path.encode('utf-8') + except UnicodeError: + pass # Not UTF-8 + return path + + +def read_all_bytes(filename): + with open(filename, 'rb') as fp: + return fp.read() + + +def latin1_fail(): + try: + desc, filename = tempfile.mkstemp(suffix=Filenames.latin_1) + os.close(desc) + os.remove(filename) + except Exception: + return True + + +fail_on_latin1_encoded_filenames = pytest.mark.xfail( + latin1_fail(), + reason="System does not support latin-1 filenames", +) + + +skip_under_xdist = pytest.mark.skipif( + "os.environ.get('PYTEST_XDIST_WORKER')", + reason="pytest-dev/pytest-xdist#843", +) +skip_under_stdlib_distutils = pytest.mark.skipif( + not distutils.__package__.startswith('setuptools'), + reason="the test is not supported with stdlib distutils", +) + + +def touch(path): + open(path, 'wb').close() + return path + + +def symlink_or_skip_test(src, dst): + try: + os.symlink(src, dst) + except (OSError, NotImplementedError): + pytest.skip("symlink not supported in OS") + return None + return dst + + +class TestSdistTest: + @pytest.fixture(autouse=True) + def source_dir(self, tmpdir): + tmpdir = tmpdir / "project_root" + tmpdir.mkdir() + + (tmpdir / 'setup.py').write_text(SETUP_PY, encoding='utf-8') + + # Set up the rest of the test package + test_pkg = tmpdir / 'sdist_test' + test_pkg.mkdir() + data_folder = tmpdir / 'd' + data_folder.mkdir() + # *.rst was not included in package_data, so c.rst should not be + # automatically added to the manifest when not under version control + for fname in ['__init__.py', 'a.txt', 'b.txt', 'c.rst']: + touch(test_pkg / fname) + touch(data_folder / 'e.dat') + # C sources are not included by default, but they will be, + # if an extension module uses them as sources or depends + for fname in EXTENSION_SOURCES: + touch(tmpdir / fname) + + with tmpdir.as_cwd(): + yield tmpdir + + def assert_package_data_in_manifest(self, cmd): + manifest = cmd.filelist.files + assert os.path.join('sdist_test', 'a.txt') in manifest + assert os.path.join('sdist_test', 'b.txt') in manifest + assert os.path.join('sdist_test', 'c.rst') not in manifest + assert os.path.join('d', 'e.dat') in manifest + + def setup_with_extension(self): + setup_attrs = {**SETUP_ATTRS, 'ext_modules': [EXTENSION]} + + dist = Distribution(setup_attrs) + dist.script_name = 'setup.py' + cmd = sdist(dist) + cmd.ensure_finalized() + + with quiet(): + cmd.run() + + return cmd + + def test_package_data_in_sdist(self): + """Regression test for pull request #4: ensures that files listed in + package_data are included in the manifest even if they're not added to + version control. + """ + + dist = Distribution(SETUP_ATTRS) + dist.script_name = 'setup.py' + cmd = sdist(dist) + cmd.ensure_finalized() + + with quiet(): + cmd.run() + + self.assert_package_data_in_manifest(cmd) + + def test_package_data_and_include_package_data_in_sdist(self): + """ + Ensure package_data and include_package_data work + together. + """ + setup_attrs = {**SETUP_ATTRS, 'include_package_data': True} + assert setup_attrs['package_data'] + + dist = Distribution(setup_attrs) + dist.script_name = 'setup.py' + cmd = sdist(dist) + cmd.ensure_finalized() + + with quiet(): + cmd.run() + + self.assert_package_data_in_manifest(cmd) + + def test_extension_sources_in_sdist(self): + """ + Ensure that the files listed in Extension.sources and Extension.depends + are automatically included in the manifest. + """ + cmd = self.setup_with_extension() + self.assert_package_data_in_manifest(cmd) + manifest = cmd.filelist.files + for path in EXTENSION_SOURCES: + assert path in manifest + + def test_missing_extension_sources(self): + """ + Similar to test_extension_sources_in_sdist but the referenced files don't exist. + Missing files should not be included in distribution (with no error raised). + """ + for path in EXTENSION_SOURCES: + os.remove(path) + + cmd = self.setup_with_extension() + self.assert_package_data_in_manifest(cmd) + manifest = cmd.filelist.files + for path in EXTENSION_SOURCES: + assert path not in manifest + + def test_symlinked_extension_sources(self): + """ + Similar to test_extension_sources_in_sdist but the referenced files are + instead symbolic links to project-local files. Referenced file paths + should be included. Symlink targets themselves should NOT be included. + """ + symlinked = [] + for path in EXTENSION_SOURCES: + base, ext = os.path.splitext(path) + target = base + "_target." + ext + + os.rename(path, target) + symlink_or_skip_test(os.path.basename(target), path) + symlinked.append(target) + + cmd = self.setup_with_extension() + self.assert_package_data_in_manifest(cmd) + manifest = cmd.filelist.files + for path in EXTENSION_SOURCES: + assert path in manifest + for path in symlinked: + assert path not in manifest + + _INVALID_PATHS = { + "must be relative": lambda: ( + os.path.abspath(os.path.join("sdist_test", "f.h")) + ), + "can't have `..` segments": lambda: ( + os.path.join("sdist_test", "..", "sdist_test", "f.h") + ), + "doesn't exist": lambda: ( + os.path.join("sdist_test", "this_file_does_not_exist.h") + ), + "must be inside the project root": lambda: ( + symlink_or_skip_test( + touch(os.path.join("..", "outside_of_project_root.h")), + "symlink.h", + ) + ), + } + + @skip_under_stdlib_distutils + @pytest.mark.parametrize("reason", _INVALID_PATHS.keys()) + def test_invalid_extension_depends(self, reason, caplog): + """ + Due to backwards compatibility reasons, `Extension.depends` should accept + invalid/weird paths, but then ignore them when building a sdist. + + This test verifies that the source distribution is still built + successfully with such paths, but that instead of adding these paths to + the manifest, we emit an informational message, notifying the user that + the invalid path won't be automatically included. + """ + invalid_path = self._INVALID_PATHS[reason]() + extension = Extension( + name="sdist_test.f", + sources=[], + depends=[invalid_path], + ) + setup_attrs = {**SETUP_ATTRS, 'ext_modules': [extension]} + + dist = Distribution(setup_attrs) + dist.script_name = 'setup.py' + cmd = sdist(dist) + cmd.ensure_finalized() + + with quiet(), caplog.at_level(logging.INFO): + cmd.run() + + self.assert_package_data_in_manifest(cmd) + manifest = cmd.filelist.files + assert invalid_path not in manifest + + expected_message = [ + message + for (logger, level, message) in caplog.record_tuples + if ( + logger == "root" # + and level == logging.INFO # + and invalid_path in message # + ) + ] + assert len(expected_message) == 1 + (expected_message,) = expected_message + assert reason in expected_message + + def test_custom_build_py(self): + """ + Ensure projects defining custom build_py don't break + when creating sdists (issue #2849) + """ + from distutils.command.build_py import build_py as OrigBuildPy + + using_custom_command_guard = mock.Mock() + + class CustomBuildPy(OrigBuildPy): + """ + Some projects have custom commands inheriting from `distutils` + """ + + def get_data_files(self): + using_custom_command_guard() + return super().get_data_files() + + setup_attrs = {**SETUP_ATTRS, 'include_package_data': True} + assert setup_attrs['package_data'] + + dist = Distribution(setup_attrs) + dist.script_name = 'setup.py' + cmd = sdist(dist) + cmd.ensure_finalized() + + # Make sure we use the custom command + cmd.cmdclass = {'build_py': CustomBuildPy} + cmd.distribution.cmdclass = {'build_py': CustomBuildPy} + assert cmd.distribution.get_command_class('build_py') == CustomBuildPy + + msg = "setuptools instead of distutils" + with quiet(), pytest.warns(SetuptoolsDeprecationWarning, match=msg): + cmd.run() + + using_custom_command_guard.assert_called() + self.assert_package_data_in_manifest(cmd) + + def test_setup_py_exists(self): + dist = Distribution(SETUP_ATTRS) + dist.script_name = 'foo.py' + cmd = sdist(dist) + cmd.ensure_finalized() + + with quiet(): + cmd.run() + + manifest = cmd.filelist.files + assert 'setup.py' in manifest + + def test_setup_py_missing(self): + dist = Distribution(SETUP_ATTRS) + dist.script_name = 'foo.py' + cmd = sdist(dist) + cmd.ensure_finalized() + + if os.path.exists("setup.py"): + os.remove("setup.py") + with quiet(): + cmd.run() + + manifest = cmd.filelist.files + assert 'setup.py' not in manifest + + def test_setup_py_excluded(self): + with open("MANIFEST.in", "w", encoding="utf-8") as manifest_file: + manifest_file.write("exclude setup.py") + + dist = Distribution(SETUP_ATTRS) + dist.script_name = 'foo.py' + cmd = sdist(dist) + cmd.ensure_finalized() + + with quiet(): + cmd.run() + + manifest = cmd.filelist.files + assert 'setup.py' not in manifest + + def test_defaults_case_sensitivity(self, source_dir): + """ + Make sure default files (README.*, etc.) are added in a case-sensitive + way to avoid problems with packages built on Windows. + """ + + touch(source_dir / 'readme.rst') + touch(source_dir / 'SETUP.cfg') + + dist = Distribution(SETUP_ATTRS) + # the extension deliberately capitalized for this test + # to make sure the actual filename (not capitalized) gets added + # to the manifest + dist.script_name = 'setup.PY' + cmd = sdist(dist) + cmd.ensure_finalized() + + with quiet(): + cmd.run() + + # lowercase all names so we can test in a + # case-insensitive way to make sure the files + # are not included. + manifest = map(lambda x: x.lower(), cmd.filelist.files) + assert 'readme.rst' not in manifest, manifest + assert 'setup.py' not in manifest, manifest + assert 'setup.cfg' not in manifest, manifest + + def test_exclude_dev_only_cache_folders(self, source_dir): + included = { + # Emulate problem in https://github.com/pypa/setuptools/issues/4601 + "MANIFEST.in": ( + "global-include LICEN[CS]E* COPYING* NOTICE* AUTHORS*\n" + "global-include *.txt\n" + ), + # For the sake of being conservative and limiting unforeseen side-effects + # we just exclude dev-only cache folders at the root of the repository: + "test/.venv/lib/python3.9/site-packages/bar-2.dist-info/AUTHORS.rst": "", + "src/.nox/py/lib/python3.12/site-packages/bar-2.dist-info/COPYING.txt": "", + "doc/.tox/default/lib/python3.11/site-packages/foo-4.dist-info/LICENSE": "", + # Let's test against false positives with similarly named files: + ".venv-requirements.txt": "", + ".tox-coveragerc.txt": "", + ".noxy/coveragerc.txt": "", + } + + excluded = { + # .tox/.nox/.venv are well-know folders present at the root of Python repos + # and therefore should be excluded + ".tox/release/lib/python3.11/site-packages/foo-4.dist-info/LICENSE": "", + ".nox/py/lib/python3.12/site-packages/bar-2.dist-info/COPYING.txt": "", + ".venv/lib/python3.9/site-packages/bar-2.dist-info/AUTHORS.rst": "", + } + + for file, content in {**excluded, **included}.items(): + Path(source_dir, file).parent.mkdir(parents=True, exist_ok=True) + Path(source_dir, file).write_text(content, encoding="utf-8") + + cmd = self.setup_with_extension() + self.assert_package_data_in_manifest(cmd) + manifest = {f.replace(os.sep, '/') for f in cmd.filelist.files} + for path in excluded: + assert os.path.exists(path) + assert path not in manifest, (path, manifest) + for path in included: + assert os.path.exists(path) + assert path in manifest, (path, manifest) + + @fail_on_ascii + def test_manifest_is_written_with_utf8_encoding(self): + # Test for #303. + dist = Distribution(SETUP_ATTRS) + dist.script_name = 'setup.py' + mm = manifest_maker(dist) + mm.manifest = os.path.join('sdist_test.egg-info', 'SOURCES.txt') + os.mkdir('sdist_test.egg-info') + + # UTF-8 filename + filename = os.path.join('sdist_test', 'smörbröd.py') + + # Must create the file or it will get stripped. + touch(filename) + + # Add UTF-8 filename and write manifest + with quiet(): + mm.run() + mm.filelist.append(filename) + mm.write_manifest() + + contents = read_all_bytes(mm.manifest) + + # The manifest should be UTF-8 encoded + u_contents = contents.decode('UTF-8') + + # The manifest should contain the UTF-8 filename + assert posix(filename) in u_contents + + @fail_on_ascii + def test_write_manifest_allows_utf8_filenames(self): + # Test for #303. + dist = Distribution(SETUP_ATTRS) + dist.script_name = 'setup.py' + mm = manifest_maker(dist) + mm.manifest = os.path.join('sdist_test.egg-info', 'SOURCES.txt') + os.mkdir('sdist_test.egg-info') + + filename = os.path.join(b'sdist_test', Filenames.utf_8) + + # Must touch the file or risk removal + touch(filename) + + # Add filename and write manifest + with quiet(): + mm.run() + u_filename = filename.decode('utf-8') + mm.filelist.files.append(u_filename) + # Re-write manifest + mm.write_manifest() + + contents = read_all_bytes(mm.manifest) + + # The manifest should be UTF-8 encoded + contents.decode('UTF-8') + + # The manifest should contain the UTF-8 filename + assert posix(filename) in contents + + # The filelist should have been updated as well + assert u_filename in mm.filelist.files + + @skip_under_xdist + def test_write_manifest_skips_non_utf8_filenames(self): + """ + Files that cannot be encoded to UTF-8 (specifically, those that + weren't originally successfully decoded and have surrogate + escapes) should be omitted from the manifest. + See https://bitbucket.org/tarek/distribute/issue/303 for history. + """ + dist = Distribution(SETUP_ATTRS) + dist.script_name = 'setup.py' + mm = manifest_maker(dist) + mm.manifest = os.path.join('sdist_test.egg-info', 'SOURCES.txt') + os.mkdir('sdist_test.egg-info') + + # Latin-1 filename + filename = os.path.join(b'sdist_test', Filenames.latin_1) + + # Add filename with surrogates and write manifest + with quiet(): + mm.run() + u_filename = filename.decode('utf-8', 'surrogateescape') + mm.filelist.append(u_filename) + # Re-write manifest + mm.write_manifest() + + contents = read_all_bytes(mm.manifest) + + # The manifest should be UTF-8 encoded + contents.decode('UTF-8') + + # The Latin-1 filename should have been skipped + assert posix(filename) not in contents + + # The filelist should have been updated as well + assert u_filename not in mm.filelist.files + + @fail_on_ascii + def test_manifest_is_read_with_utf8_encoding(self): + # Test for #303. + dist = Distribution(SETUP_ATTRS) + dist.script_name = 'setup.py' + cmd = sdist(dist) + cmd.ensure_finalized() + + # Create manifest + with quiet(): + cmd.run() + + # Add UTF-8 filename to manifest + filename = os.path.join(b'sdist_test', Filenames.utf_8) + cmd.manifest = os.path.join('sdist_test.egg-info', 'SOURCES.txt') + manifest = open(cmd.manifest, 'ab') + manifest.write(b'\n' + filename) + manifest.close() + + # The file must exist to be included in the filelist + touch(filename) + + # Re-read manifest + cmd.filelist.files = [] + with quiet(): + cmd.read_manifest() + + # The filelist should contain the UTF-8 filename + filename = filename.decode('utf-8') + assert filename in cmd.filelist.files + + @fail_on_latin1_encoded_filenames + def test_read_manifest_skips_non_utf8_filenames(self): + # Test for #303. + dist = Distribution(SETUP_ATTRS) + dist.script_name = 'setup.py' + cmd = sdist(dist) + cmd.ensure_finalized() + + # Create manifest + with quiet(): + cmd.run() + + # Add Latin-1 filename to manifest + filename = os.path.join(b'sdist_test', Filenames.latin_1) + cmd.manifest = os.path.join('sdist_test.egg-info', 'SOURCES.txt') + manifest = open(cmd.manifest, 'ab') + manifest.write(b'\n' + filename) + manifest.close() + + # The file must exist to be included in the filelist + touch(filename) + + # Re-read manifest + cmd.filelist.files = [] + with quiet(): + cmd.read_manifest() + + # The Latin-1 filename should have been skipped + filename = filename.decode('latin-1') + assert filename not in cmd.filelist.files + + @fail_on_ascii + @fail_on_latin1_encoded_filenames + def test_sdist_with_utf8_encoded_filename(self): + # Test for #303. + dist = Distribution(self.make_strings(SETUP_ATTRS)) + dist.script_name = 'setup.py' + cmd = sdist(dist) + cmd.ensure_finalized() + + filename = os.path.join(b'sdist_test', Filenames.utf_8) + touch(filename) + + with quiet(): + cmd.run() + + if sys.platform == 'darwin': + filename = decompose(filename) + + fs_enc = sys.getfilesystemencoding() + + if sys.platform == 'win32': + if fs_enc == 'cp1252': + # Python mangles the UTF-8 filename + filename = filename.decode('cp1252') + assert filename in cmd.filelist.files + else: + filename = filename.decode('mbcs') + assert filename in cmd.filelist.files + else: + filename = filename.decode('utf-8') + assert filename in cmd.filelist.files + + @classmethod + def make_strings(cls, item): + if isinstance(item, dict): + return {key: cls.make_strings(value) for key, value in item.items()} + if isinstance(item, list): + return list(map(cls.make_strings, item)) + return str(item) + + @fail_on_latin1_encoded_filenames + @skip_under_xdist + def test_sdist_with_latin1_encoded_filename(self): + # Test for #303. + dist = Distribution(self.make_strings(SETUP_ATTRS)) + dist.script_name = 'setup.py' + cmd = sdist(dist) + cmd.ensure_finalized() + + # Latin-1 filename + filename = os.path.join(b'sdist_test', Filenames.latin_1) + touch(filename) + assert os.path.isfile(filename) + + with quiet(): + cmd.run() + + # not all windows systems have a default FS encoding of cp1252 + if sys.platform == 'win32': + # Latin-1 is similar to Windows-1252 however + # on mbcs filesys it is not in latin-1 encoding + fs_enc = sys.getfilesystemencoding() + if fs_enc != 'mbcs': + fs_enc = 'latin-1' + filename = filename.decode(fs_enc) + + assert filename in cmd.filelist.files + else: + # The Latin-1 filename should have been skipped + filename = filename.decode('latin-1') + assert filename not in cmd.filelist.files + + _EXAMPLE_DIRECTIVES = { + "setup.cfg - long_description and version": """ + [metadata] + name = testing + version = file: src/VERSION.txt + license_files = DOWHATYOUWANT + long_description = file: README.rst, USAGE.rst + """, + "pyproject.toml - static readme/license files and dynamic version": """ + [project] + name = "testing" + readme = "USAGE.rst" + license-files = ["DOWHATYOUWANT"] + dynamic = ["version"] + [tool.setuptools.dynamic] + version = {file = ["src/VERSION.txt"]} + """, + "pyproject.toml - directive with str instead of list": """ + [project] + name = "testing" + readme = "USAGE.rst" + license-files = ["DOWHATYOUWANT"] + dynamic = ["version"] + [tool.setuptools.dynamic] + version = {file = "src/VERSION.txt"} + """, + "pyproject.toml - deprecated license table with file entry": """ + [project] + name = "testing" + readme = "USAGE.rst" + license = {file = "DOWHATYOUWANT"} + dynamic = ["version"] + [tool.setuptools.dynamic] + version = {file = "src/VERSION.txt"} + """, + } + + @pytest.mark.parametrize("config", _EXAMPLE_DIRECTIVES.keys()) + @pytest.mark.filterwarnings( + "ignore:.project.license. as a TOML table is deprecated" + ) + def test_add_files_referenced_by_config_directives(self, source_dir, config): + config_file, _, _ = config.partition(" - ") + config_text = self._EXAMPLE_DIRECTIVES[config] + (source_dir / 'src').mkdir() + (source_dir / 'src/VERSION.txt').write_text("0.42", encoding="utf-8") + (source_dir / 'README.rst').write_text("hello world!", encoding="utf-8") + (source_dir / 'USAGE.rst').write_text("hello world!", encoding="utf-8") + (source_dir / 'DOWHATYOUWANT').write_text("hello world!", encoding="utf-8") + (source_dir / config_file).write_text(config_text, encoding="utf-8") + + dist = Distribution({"packages": []}) + dist.script_name = 'setup.py' + dist.parse_config_files() + + cmd = sdist(dist) + cmd.ensure_finalized() + with quiet(): + cmd.run() + + assert ( + 'src/VERSION.txt' in cmd.filelist.files + or 'src\\VERSION.txt' in cmd.filelist.files + ) + assert 'USAGE.rst' in cmd.filelist.files + assert 'DOWHATYOUWANT' in cmd.filelist.files + assert '/' not in cmd.filelist.files + assert '\\' not in cmd.filelist.files + + def test_pyproject_toml_in_sdist(self, source_dir): + """ + Check if pyproject.toml is included in source distribution if present + """ + touch(source_dir / 'pyproject.toml') + dist = Distribution(SETUP_ATTRS) + dist.script_name = 'setup.py' + cmd = sdist(dist) + cmd.ensure_finalized() + with quiet(): + cmd.run() + manifest = cmd.filelist.files + assert 'pyproject.toml' in manifest + + def test_pyproject_toml_excluded(self, source_dir): + """ + Check that pyproject.toml can excluded even if present + """ + touch(source_dir / 'pyproject.toml') + with open('MANIFEST.in', 'w', encoding="utf-8") as mts: + print('exclude pyproject.toml', file=mts) + dist = Distribution(SETUP_ATTRS) + dist.script_name = 'setup.py' + cmd = sdist(dist) + cmd.ensure_finalized() + with quiet(): + cmd.run() + manifest = cmd.filelist.files + assert 'pyproject.toml' not in manifest + + def test_build_subcommand_source_files(self, source_dir): + touch(source_dir / '.myfile~') + + # Sanity check: without custom commands file list should not be affected + dist = Distribution({**SETUP_ATTRS, "script_name": "setup.py"}) + cmd = sdist(dist) + cmd.ensure_finalized() + with quiet(): + cmd.run() + manifest = cmd.filelist.files + assert '.myfile~' not in manifest + + # Test: custom command should be able to augment file list + dist = Distribution({**SETUP_ATTRS, "script_name": "setup.py"}) + build = dist.get_command_obj("build") + build.sub_commands = [*build.sub_commands, ("build_custom", None)] + + class build_custom(Command): + def initialize_options(self): ... + + def finalize_options(self): ... + + def run(self): ... + + def get_source_files(self): + return ['.myfile~'] + + dist.cmdclass.update(build_custom=build_custom) + + cmd = sdist(dist) + cmd.use_defaults = True + cmd.ensure_finalized() + with quiet(): + cmd.run() + manifest = cmd.filelist.files + assert '.myfile~' in manifest + + @pytest.mark.skipif("os.environ.get('SETUPTOOLS_USE_DISTUTILS') == 'stdlib'") + def test_build_base_pathlib(self, source_dir): + """ + Ensure if build_base is a pathlib.Path, the build still succeeds. + """ + dist = Distribution({ + **SETUP_ATTRS, + "script_name": "setup.py", + "options": {"build": {"build_base": pathlib.Path('build')}}, + }) + cmd = sdist(dist) + cmd.ensure_finalized() + with quiet(): + cmd.run() + + +def test_default_revctrl(): + """ + When _default_revctrl was removed from the `setuptools.command.sdist` + module in 10.0, it broke some systems which keep an old install of + setuptools (Distribute) around. Those old versions require that the + setuptools package continue to implement that interface, so this + function provides that interface, stubbed. See #320 for details. + + This interface must be maintained until Ubuntu 12.04 is no longer + supported (by Setuptools). + """ + (ep,) = metadata.EntryPoints._from_text( + """ + [setuptools.file_finders] + svn_cvs = setuptools.command.sdist:_default_revctrl + """ + ) + res = ep.load() + assert hasattr(res, '__iter__') + + +class TestRegressions: + """ + Can be removed/changed if the project decides to change how it handles symlinks + or external files. + """ + + @staticmethod + def files_for_symlink_in_extension_depends(tmp_path, dep_path): + return { + "external": { + "dir": {"file.h": ""}, + }, + "project": { + "setup.py": cleandoc( + f""" + from setuptools import Extension, setup + setup( + name="myproj", + version="42", + ext_modules=[ + Extension( + "hello", sources=["hello.pyx"], + depends=[{dep_path!r}] + ) + ], + ) + """ + ), + "hello.pyx": "", + "MANIFEST.in": "global-include *.h", + }, + } + + @pytest.mark.parametrize( + "dep_path", ("myheaders/dir/file.h", "myheaders/dir/../dir/file.h") + ) + def test_symlink_in_extension_depends(self, monkeypatch, tmp_path, dep_path): + # Given a project with a symlinked dir and a "depends" targeting that dir + files = self.files_for_symlink_in_extension_depends(tmp_path, dep_path) + jaraco.path.build(files, prefix=str(tmp_path)) + symlink_or_skip_test(tmp_path / "external", tmp_path / "project/myheaders") + + # When `sdist` runs, there should be no error + members = run_sdist(monkeypatch, tmp_path / "project") + # and the sdist should contain the symlinked files + for expected in ( + "myproj-42/hello.pyx", + "myproj-42/myheaders/dir/file.h", + ): + assert expected in members + + @staticmethod + def files_for_external_path_in_extension_depends(tmp_path, dep_path): + head, _, tail = dep_path.partition("$tmp_path$/") + dep_path = tmp_path / tail if tail else head + + return { + "external": { + "dir": {"file.h": ""}, + }, + "project": { + "setup.py": cleandoc( + f""" + from setuptools import Extension, setup + setup( + name="myproj", + version="42", + ext_modules=[ + Extension( + "hello", sources=["hello.pyx"], + depends=[{str(dep_path)!r}] + ) + ], + ) + """ + ), + "hello.pyx": "", + "MANIFEST.in": "global-include *.h", + }, + } + + @pytest.mark.parametrize( + "dep_path", ("$tmp_path$/external/dir/file.h", "../external/dir/file.h") + ) + def test_external_path_in_extension_depends(self, monkeypatch, tmp_path, dep_path): + # Given a project with a "depends" targeting an external dir + files = self.files_for_external_path_in_extension_depends(tmp_path, dep_path) + jaraco.path.build(files, prefix=str(tmp_path)) + # When `sdist` runs, there should be no error + members = run_sdist(monkeypatch, tmp_path / "project") + # and the sdist should not contain the external file + for name in members: + assert "file.h" not in name + + +def run_sdist(monkeypatch, project): + """Given a project directory, run the sdist and return its contents""" + monkeypatch.chdir(project) + with quiet(): + run_setup("setup.py", ["sdist"]) + + archive = next((project / "dist").glob("*.tar.gz")) + with tarfile.open(str(archive)) as tar: + return set(tar.getnames()) + + +def test_sanity_check_setuptools_own_sdist(setuptools_sdist): + with tarfile.open(setuptools_sdist) as tar: + files = tar.getnames() + + # setuptools sdist should not include the .tox folder + tox_files = [name for name in files if ".tox" in name] + assert len(tox_files) == 0, f"not empty {tox_files}" diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/test_setopt.py b/.venv/lib/python3.12/site-packages/setuptools/tests/test_setopt.py new file mode 100644 index 0000000000000000000000000000000000000000..ccf25618a5d6e255ad0be0fbed51fc29c179dcfe --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/test_setopt.py @@ -0,0 +1,40 @@ +import configparser + +from setuptools.command import setopt + + +class TestEdit: + @staticmethod + def parse_config(filename): + parser = configparser.ConfigParser() + with open(filename, encoding='utf-8') as reader: + parser.read_file(reader) + return parser + + @staticmethod + def write_text(file, content): + with open(file, 'wb') as strm: + strm.write(content.encode('utf-8')) + + def test_utf8_encoding_retained(self, tmpdir): + """ + When editing a file, non-ASCII characters encoded in + UTF-8 should be retained. + """ + config = tmpdir.join('setup.cfg') + self.write_text(str(config), '[names]\njaraco=джарако') + setopt.edit_config(str(config), dict(names=dict(other='yes'))) + parser = self.parse_config(str(config)) + assert parser.get('names', 'jaraco') == 'джарако' + assert parser.get('names', 'other') == 'yes' + + def test_case_retained(self, tmpdir): + """ + When editing a file, case of keys should be retained. + """ + config = tmpdir.join('setup.cfg') + self.write_text(str(config), '[names]\nFoO=bAr') + setopt.edit_config(str(config), dict(names=dict(oTher='yes'))) + actual = config.read_text(encoding='ascii') + assert 'FoO' in actual + assert 'oTher' in actual diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/test_setuptools.py b/.venv/lib/python3.12/site-packages/setuptools/tests/test_setuptools.py new file mode 100644 index 0000000000000000000000000000000000000000..1d56e1a8a4ebc5c7aaeb9902ef9972f7de97ecbf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/test_setuptools.py @@ -0,0 +1,290 @@ +"""Tests for the 'setuptools' package""" + +import os +import re +import sys +from zipfile import ZipFile + +import pytest +from packaging.version import Version + +import setuptools +import setuptools.depends as dep +import setuptools.dist +from setuptools.depends import Require + +import distutils.cmd +import distutils.core +from distutils.core import Extension +from distutils.errors import DistutilsSetupError + + +@pytest.fixture(autouse=True) +def isolated_dir(tmpdir_cwd): + return + + +def makeSetup(**args): + """Return distribution from 'setup(**args)', without executing commands""" + + distutils.core._setup_stop_after = "commandline" + + # Don't let system command line leak into tests! + args.setdefault('script_args', ['install']) + + try: + return setuptools.setup(**args) + finally: + distutils.core._setup_stop_after = None + + +needs_bytecode = pytest.mark.skipif( + not hasattr(dep, 'get_module_constant'), + reason="bytecode support not available", +) + + +class TestDepends: + def testExtractConst(self): + if not hasattr(dep, 'extract_constant'): + # skip on non-bytecode platforms + return + + def f1(): + global x, y, z + x = "test" + y = z # pyright: ignore[reportUnboundVariable] # Explicitly testing for this runtime issue + + fc = f1.__code__ + + # unrecognized name + assert dep.extract_constant(fc, 'q', -1) is None + + # constant assigned + assert dep.extract_constant(fc, 'x', -1) == "test" + + # expression assigned + assert dep.extract_constant(fc, 'y', -1) == -1 + + # recognized name, not assigned + assert dep.extract_constant(fc, 'z', -1) is None + + def testFindModule(self): + with pytest.raises(ImportError): + dep.find_module('no-such.-thing') + with pytest.raises(ImportError): + dep.find_module('setuptools.non-existent') + f, _p, _i = dep.find_module('setuptools.tests') + f.close() + + @needs_bytecode + def testModuleExtract(self): + from json import __version__ + + assert dep.get_module_constant('json', '__version__') == __version__ + assert dep.get_module_constant('sys', 'version') == sys.version + assert ( + dep.get_module_constant('setuptools.tests.test_setuptools', '__doc__') + == __doc__ + ) + + @needs_bytecode + def testRequire(self): + req = Require('Json', '1.0.3', 'json') + + assert req.name == 'Json' + assert req.module == 'json' + assert req.requested_version == Version('1.0.3') + assert req.attribute == '__version__' + assert req.full_name() == 'Json-1.0.3' + + from json import __version__ + + assert str(req.get_version()) == __version__ + assert req.version_ok('1.0.9') + assert not req.version_ok('0.9.1') + assert not req.version_ok('unknown') + + assert req.is_present() + assert req.is_current() + + req = Require('Do-what-I-mean', '1.0', 'd-w-i-m') + assert not req.is_present() + assert not req.is_current() + + @needs_bytecode + def test_require_present(self): + # In #1896, this test was failing for months with the only + # complaint coming from test runners (not end users). + # TODO: Evaluate if this code is needed at all. + req = Require('Tests', None, 'tests', homepage="http://example.com") + assert req.format is None + assert req.attribute is None + assert req.requested_version is None + assert req.full_name() == 'Tests' + assert req.homepage == 'http://example.com' + + from setuptools.tests import __path__ + + paths = [os.path.dirname(p) for p in __path__] + assert req.is_present(paths) + assert req.is_current(paths) + + +class TestDistro: + def setup_method(self, method): + self.e1 = Extension('bar.ext', ['bar.c']) + self.e2 = Extension('c.y', ['y.c']) + + self.dist = makeSetup( + packages=['a', 'a.b', 'a.b.c', 'b', 'c'], + py_modules=['b.d', 'x'], + ext_modules=(self.e1, self.e2), + package_dir={}, + ) + + def testDistroType(self): + assert isinstance(self.dist, setuptools.dist.Distribution) + + def testExcludePackage(self): + self.dist.exclude_package('a') + assert self.dist.packages == ['b', 'c'] + + self.dist.exclude_package('b') + assert self.dist.packages == ['c'] + assert self.dist.py_modules == ['x'] + assert self.dist.ext_modules == [self.e1, self.e2] + + self.dist.exclude_package('c') + assert self.dist.packages == [] + assert self.dist.py_modules == ['x'] + assert self.dist.ext_modules == [self.e1] + + # test removals from unspecified options + makeSetup().exclude_package('x') + + def testIncludeExclude(self): + # remove an extension + self.dist.exclude(ext_modules=[self.e1]) + assert self.dist.ext_modules == [self.e2] + + # add it back in + self.dist.include(ext_modules=[self.e1]) + assert self.dist.ext_modules == [self.e2, self.e1] + + # should not add duplicate + self.dist.include(ext_modules=[self.e1]) + assert self.dist.ext_modules == [self.e2, self.e1] + + def testExcludePackages(self): + self.dist.exclude(packages=['c', 'b', 'a']) + assert self.dist.packages == [] + assert self.dist.py_modules == ['x'] + assert self.dist.ext_modules == [self.e1] + + def testEmpty(self): + dist = makeSetup() + dist.include(packages=['a'], py_modules=['b'], ext_modules=[self.e2]) + dist = makeSetup() + dist.exclude(packages=['a'], py_modules=['b'], ext_modules=[self.e2]) + + def testContents(self): + assert self.dist.has_contents_for('a') + self.dist.exclude_package('a') + assert not self.dist.has_contents_for('a') + + assert self.dist.has_contents_for('b') + self.dist.exclude_package('b') + assert not self.dist.has_contents_for('b') + + assert self.dist.has_contents_for('c') + self.dist.exclude_package('c') + assert not self.dist.has_contents_for('c') + + def testInvalidIncludeExclude(self): + with pytest.raises(DistutilsSetupError): + self.dist.include(nonexistent_option='x') + with pytest.raises(DistutilsSetupError): + self.dist.exclude(nonexistent_option='x') + with pytest.raises(DistutilsSetupError): + self.dist.include(packages={'x': 'y'}) + with pytest.raises(DistutilsSetupError): + self.dist.exclude(packages={'x': 'y'}) + with pytest.raises(DistutilsSetupError): + self.dist.include(ext_modules={'x': 'y'}) + with pytest.raises(DistutilsSetupError): + self.dist.exclude(ext_modules={'x': 'y'}) + + with pytest.raises(DistutilsSetupError): + self.dist.include(package_dir=['q']) + with pytest.raises(DistutilsSetupError): + self.dist.exclude(package_dir=['q']) + + +@pytest.fixture +def example_source(tmpdir): + tmpdir.mkdir('foo') + (tmpdir / 'foo/bar.py').write('') + (tmpdir / 'readme.txt').write('') + return tmpdir + + +def test_findall(example_source): + found = list(setuptools.findall(str(example_source))) + expected = ['readme.txt', 'foo/bar.py'] + expected = [example_source.join(fn) for fn in expected] + assert found == expected + + +def test_findall_curdir(example_source): + with example_source.as_cwd(): + found = list(setuptools.findall()) + expected = ['readme.txt', os.path.join('foo', 'bar.py')] + assert found == expected + + +@pytest.fixture +def can_symlink(tmpdir): + """ + Skip if cannot create a symbolic link + """ + link_fn = 'link' + target_fn = 'target' + try: + os.symlink(target_fn, link_fn) + except (OSError, NotImplementedError, AttributeError): + pytest.skip("Cannot create symbolic links") + os.remove(link_fn) + + +@pytest.mark.usefixtures("can_symlink") +def test_findall_missing_symlink(tmpdir): + with tmpdir.as_cwd(): + os.symlink('foo', 'bar') + found = list(setuptools.findall()) + assert found == [] + + +@pytest.mark.xfail(reason="unable to exclude tests; #4475 #3260") +def test_its_own_wheel_does_not_contain_tests(setuptools_wheel): + with ZipFile(setuptools_wheel) as zipfile: + contents = [f.replace(os.sep, '/') for f in zipfile.namelist()] + + for member in contents: + assert '/tests/' not in member + + +def test_wheel_includes_cli_scripts(setuptools_wheel): + with ZipFile(setuptools_wheel) as zipfile: + contents = [f.replace(os.sep, '/') for f in zipfile.namelist()] + + assert any('cli-64.exe' in member for member in contents) + + +def test_wheel_includes_vendored_metadata(setuptools_wheel): + with ZipFile(setuptools_wheel) as zipfile: + contents = [f.replace(os.sep, '/') for f in zipfile.namelist()] + + assert any( + re.search(r'_vendor/.*\.dist-info/METADATA', member) for member in contents + ) diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/test_shutil_wrapper.py b/.venv/lib/python3.12/site-packages/setuptools/tests/test_shutil_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..74ff7e9a896328a3d57ca3639658e3b9d538585f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/test_shutil_wrapper.py @@ -0,0 +1,23 @@ +import stat +import sys +from unittest.mock import Mock + +from setuptools import _shutil + + +def test_rmtree_readonly(monkeypatch, tmp_path): + """Verify onerr works as expected""" + + tmp_dir = tmp_path / "with_readonly" + tmp_dir.mkdir() + some_file = tmp_dir.joinpath("file.txt") + some_file.touch() + some_file.chmod(stat.S_IREAD) + + expected_count = 1 if sys.platform.startswith("win") else 0 + chmod_fn = Mock(wraps=_shutil.attempt_chmod_verbose) + monkeypatch.setattr(_shutil, "attempt_chmod_verbose", chmod_fn) + + _shutil.rmtree(tmp_dir) + assert chmod_fn.call_count == expected_count + assert not tmp_dir.is_dir() diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/test_unicode_utils.py b/.venv/lib/python3.12/site-packages/setuptools/tests/test_unicode_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a24a9bd5305d1de7c1c925466bb7d222c85864a7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/test_unicode_utils.py @@ -0,0 +1,10 @@ +from setuptools import unicode_utils + + +def test_filesys_decode_fs_encoding_is_None(monkeypatch): + """ + Test filesys_decode does not raise TypeError when + getfilesystemencoding returns None. + """ + monkeypatch.setattr('sys.getfilesystemencoding', lambda: None) + unicode_utils.filesys_decode(b'test') diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/test_virtualenv.py b/.venv/lib/python3.12/site-packages/setuptools/tests/test_virtualenv.py new file mode 100644 index 0000000000000000000000000000000000000000..b02949baf9cef8eb4df9c697add28f79a93b64d4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/test_virtualenv.py @@ -0,0 +1,113 @@ +import os +import subprocess +import sys +from urllib.error import URLError +from urllib.request import urlopen + +import pytest + + +@pytest.fixture(autouse=True) +def pytest_virtualenv_works(venv): + """ + pytest_virtualenv may not work. if it doesn't, skip these + tests. See #1284. + """ + venv_prefix = venv.run(["python", "-c", "import sys; print(sys.prefix)"]).strip() + if venv_prefix == sys.prefix: + pytest.skip("virtualenv is broken (see pypa/setuptools#1284)") + + +def test_clean_env_install(venv_without_setuptools, setuptools_wheel): + """ + Check setuptools can be installed in a clean environment. + """ + cmd = ["python", "-m", "pip", "install", str(setuptools_wheel)] + venv_without_setuptools.run(cmd) + + +def access_pypi(): + # Detect if tests are being run without connectivity + if not os.environ.get('NETWORK_REQUIRED', False): # pragma: nocover + try: + urlopen('https://pypi.org', timeout=1) + except URLError: + # No network, disable most of these tests + return False + + return True + + +@pytest.mark.skipif( + 'platform.python_implementation() == "PyPy"', + reason="https://github.com/pypa/setuptools/pull/2865#issuecomment-965834995", +) +@pytest.mark.skipif(not access_pypi(), reason="no network") +# ^-- Even when it is not necessary to install a different version of `pip` +# the build process will still try to download `wheel`, see #3147 and #2986. +@pytest.mark.parametrize( + 'pip_version', + [ + None, + pytest.param( + 'pip<20.1', + marks=pytest.mark.xfail( + 'sys.version_info >= (3, 12)', + reason="pip 23.1.2 required for Python 3.12 and later", + ), + ), + pytest.param( + 'pip<21', + marks=pytest.mark.xfail( + 'sys.version_info >= (3, 12)', + reason="pip 23.1.2 required for Python 3.12 and later", + ), + ), + pytest.param( + 'pip<22', + marks=pytest.mark.xfail( + 'sys.version_info >= (3, 12)', + reason="pip 23.1.2 required for Python 3.12 and later", + ), + ), + pytest.param( + 'pip<23', + marks=pytest.mark.xfail( + 'sys.version_info >= (3, 12)', + reason="pip 23.1.2 required for Python 3.12 and later", + ), + ), + pytest.param( + 'https://github.com/pypa/pip/archive/main.zip', + marks=pytest.mark.xfail(reason='#2975'), + ), + ], +) +def test_pip_upgrade_from_source( + pip_version, venv_without_setuptools, setuptools_wheel, setuptools_sdist +): + """ + Check pip can upgrade setuptools from source. + """ + # Install pip/wheel, in a venv without setuptools (as it + # should not be needed for bootstrapping from source) + venv = venv_without_setuptools + venv.run(["pip", "install", "-U", "wheel"]) + if pip_version is not None: + venv.run(["python", "-m", "pip", "install", "-U", pip_version, "--retries=1"]) + with pytest.raises(subprocess.CalledProcessError): + # Meta-test to make sure setuptools is not installed + venv.run(["python", "-c", "import setuptools"]) + + # Then install from wheel. + venv.run(["pip", "install", str(setuptools_wheel)]) + # And finally try to upgrade from source. + venv.run(["pip", "install", "--no-cache-dir", "--upgrade", str(setuptools_sdist)]) + + +def test_no_missing_dependencies(bare_venv, request): + """ + Quick and dirty test to ensure all external dependencies are vendored. + """ + setuptools_dir = request.config.rootdir + bare_venv.run(['python', 'setup.py', '--help'], cwd=setuptools_dir) diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/test_warnings.py b/.venv/lib/python3.12/site-packages/setuptools/tests/test_warnings.py new file mode 100644 index 0000000000000000000000000000000000000000..41193d4f717344546f8c70ad18b268a04740129b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/test_warnings.py @@ -0,0 +1,106 @@ +from inspect import cleandoc + +import pytest + +from setuptools.warnings import SetuptoolsDeprecationWarning, SetuptoolsWarning + +_EXAMPLES = { + "default": dict( + args=("Hello {x}", "\n\t{target} {v:.1f}"), + kwargs={"x": 5, "v": 3, "target": "World"}, + expected=""" + Hello 5 + !! + + ******************************************************************************** + World 3.0 + ******************************************************************************** + + !! + """, + ), + "futue_due_date": dict( + args=("Summary", "Lorem ipsum"), + kwargs={"due_date": (9999, 11, 22)}, + expected=""" + Summary + !! + + ******************************************************************************** + Lorem ipsum + + By 9999-Nov-22, you need to update your project and remove deprecated calls + or your builds will no longer be supported. + ******************************************************************************** + + !! + """, + ), + "past_due_date_with_docs": dict( + args=("Summary", "Lorem ipsum"), + kwargs={"due_date": (2000, 11, 22), "see_docs": "some_page.html"}, + expected=""" + Summary + !! + + ******************************************************************************** + Lorem ipsum + + This deprecation is overdue, please update your project and remove deprecated + calls to avoid build errors in the future. + + See https://setuptools.pypa.io/en/latest/some_page.html for details. + ******************************************************************************** + + !! + """, + ), +} + + +@pytest.mark.parametrize("example_name", _EXAMPLES.keys()) +def test_formatting(monkeypatch, example_name): + """ + It should automatically handle indentation, interpolation and things like due date. + """ + args = _EXAMPLES[example_name]["args"] + kwargs = _EXAMPLES[example_name]["kwargs"] + expected = _EXAMPLES[example_name]["expected"] + + monkeypatch.setenv("SETUPTOOLS_ENFORCE_DEPRECATION", "false") + with pytest.warns(SetuptoolsWarning) as warn_info: + SetuptoolsWarning.emit(*args, **kwargs) + assert _get_message(warn_info) == cleandoc(expected) + + +def test_due_date_enforcement(monkeypatch): + class _MyDeprecation(SetuptoolsDeprecationWarning): + _SUMMARY = "Summary" + _DETAILS = "Lorem ipsum" + _DUE_DATE = (2000, 11, 22) + _SEE_DOCS = "some_page.html" + + monkeypatch.setenv("SETUPTOOLS_ENFORCE_DEPRECATION", "true") + with pytest.raises(SetuptoolsDeprecationWarning) as exc_info: + _MyDeprecation.emit() + + expected = """ + Summary + !! + + ******************************************************************************** + Lorem ipsum + + This deprecation is overdue, please update your project and remove deprecated + calls to avoid build errors in the future. + + See https://setuptools.pypa.io/en/latest/some_page.html for details. + ******************************************************************************** + + !! + """ + assert str(exc_info.value) == cleandoc(expected) + + +def _get_message(warn_info): + return next(warn.message.args[0] for warn in warn_info) diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/test_wheel.py b/.venv/lib/python3.12/site-packages/setuptools/tests/test_wheel.py new file mode 100644 index 0000000000000000000000000000000000000000..70165c608b60bc70a908a8b56e1f1105feeb4712 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/test_wheel.py @@ -0,0 +1,714 @@ +"""wheel tests""" + +from __future__ import annotations + +import contextlib +import glob +import inspect +import os +import pathlib +import shutil +import stat +import subprocess +import sys +import zipfile +from typing import Any + +import pytest +from jaraco import path +from packaging.tags import parse_tag +from packaging.utils import canonicalize_name + +from pkg_resources import PY_MAJOR, Distribution, PathMetadata +from setuptools.wheel import Wheel + +from .contexts import tempdir +from .textwrap import DALS + +from distutils.sysconfig import get_config_var +from distutils.util import get_platform + +WHEEL_INFO_TESTS = ( + ('invalid.whl', ValueError), + ( + 'simplewheel-2.0-1-py2.py3-none-any.whl', + { + 'project_name': 'simplewheel', + 'version': '2.0', + 'build': '1', + 'py_version': 'py2.py3', + 'abi': 'none', + 'platform': 'any', + }, + ), + ( + 'simple.dist-0.1-py2.py3-none-any.whl', + { + 'project_name': 'simple.dist', + 'version': '0.1', + 'build': None, + 'py_version': 'py2.py3', + 'abi': 'none', + 'platform': 'any', + }, + ), + ( + 'example_pkg_a-1-py3-none-any.whl', + { + 'project_name': 'example_pkg_a', + 'version': '1', + 'build': None, + 'py_version': 'py3', + 'abi': 'none', + 'platform': 'any', + }, + ), + ( + 'PyQt5-5.9-5.9.1-cp35.cp36.cp37-abi3-manylinux1_x86_64.whl', + { + 'project_name': 'PyQt5', + 'version': '5.9', + 'build': '5.9.1', + 'py_version': 'cp35.cp36.cp37', + 'abi': 'abi3', + 'platform': 'manylinux1_x86_64', + }, + ), +) + + +@pytest.mark.parametrize( + ('filename', 'info'), WHEEL_INFO_TESTS, ids=[t[0] for t in WHEEL_INFO_TESTS] +) +def test_wheel_info(filename, info): + if inspect.isclass(info): + with pytest.raises(info): + Wheel(filename) + return + w = Wheel(filename) + assert {k: getattr(w, k) for k in info.keys()} == info + + +@contextlib.contextmanager +def build_wheel(extra_file_defs=None, **kwargs): + file_defs = { + 'setup.py': ( + DALS( + """ + # -*- coding: utf-8 -*- + from setuptools import setup + import setuptools + setup(**%r) + """ + ) + % kwargs + ).encode('utf-8'), + } + if extra_file_defs: + file_defs.update(extra_file_defs) + with tempdir() as source_dir: + path.build(file_defs, source_dir) + subprocess.check_call( + (sys.executable, 'setup.py', '-q', 'bdist_wheel'), cwd=source_dir + ) + yield glob.glob(os.path.join(source_dir, 'dist', '*.whl'))[0] + + +def tree_set(root): + contents = set() + for dirpath, dirnames, filenames in os.walk(root): + for filename in filenames: + contents.add(os.path.join(os.path.relpath(dirpath, root), filename)) + return contents + + +def flatten_tree(tree): + """Flatten nested dicts and lists into a full list of paths""" + output = set() + for node, contents in tree.items(): + if isinstance(contents, dict): + contents = flatten_tree(contents) + + for elem in contents: + if isinstance(elem, dict): + output |= {os.path.join(node, val) for val in flatten_tree(elem)} + else: + output.add(os.path.join(node, elem)) + return output + + +def format_install_tree(tree): + return { + x.format( + py_version=PY_MAJOR, + platform=get_platform(), + shlib_ext=get_config_var('EXT_SUFFIX') or get_config_var('SO'), + ) + for x in tree + } + + +def _check_wheel_install( + filename, install_dir, install_tree_includes, project_name, version, requires_txt +): + w = Wheel(filename) + egg_path = os.path.join(install_dir, w.egg_name()) + w.install_as_egg(egg_path) + if install_tree_includes is not None: + install_tree = format_install_tree(install_tree_includes) + exp = tree_set(install_dir) + assert install_tree.issubset(exp), install_tree - exp + + metadata = PathMetadata(egg_path, os.path.join(egg_path, 'EGG-INFO')) + dist = Distribution.from_filename(egg_path, metadata=metadata) + assert dist.project_name == project_name + assert dist.version == version + if requires_txt is None: + assert not dist.has_metadata('requires.txt') + else: + # Order must match to ensure reproducibility. + assert requires_txt == dist.get_metadata('requires.txt').lstrip() + + +class Record: + def __init__(self, id, **kwargs): + self._id = id + self._fields = kwargs + + def __repr__(self) -> str: + return f'{self._id}(**{self._fields!r})' + + +# Using Any to avoid possible type union issues later in test +# making a TypedDict is not worth in a test and anonymous/inline TypedDict are experimental +# https://github.com/python/mypy/issues/9884 +WHEEL_INSTALL_TESTS: tuple[dict[str, Any], ...] = ( + dict( + id='basic', + file_defs={'foo': {'__init__.py': ''}}, + setup_kwargs=dict( + packages=['foo'], + ), + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}.egg': { + 'EGG-INFO': ['PKG-INFO', 'RECORD', 'WHEEL', 'top_level.txt'], + 'foo': ['__init__.py'], + } + }), + ), + dict( + id='utf-8', + setup_kwargs=dict( + description='Description accentuée', + ), + ), + dict( + id='data', + file_defs={ + 'data.txt': DALS( + """ + Some data... + """ + ), + }, + setup_kwargs=dict( + data_files=[('data_dir', ['data.txt'])], + ), + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}.egg': { + 'EGG-INFO': ['PKG-INFO', 'RECORD', 'WHEEL', 'top_level.txt'], + 'data_dir': ['data.txt'], + } + }), + ), + dict( + id='extension', + file_defs={ + 'extension.c': DALS( + """ + #include "Python.h" + + #if PY_MAJOR_VERSION >= 3 + + static struct PyModuleDef moduledef = { + PyModuleDef_HEAD_INIT, + "extension", + NULL, + 0, + NULL, + NULL, + NULL, + NULL, + NULL + }; + + #define INITERROR return NULL + + PyMODINIT_FUNC PyInit_extension(void) + + #else + + #define INITERROR return + + void initextension(void) + + #endif + { + #if PY_MAJOR_VERSION >= 3 + PyObject *module = PyModule_Create(&moduledef); + #else + PyObject *module = Py_InitModule("extension", NULL); + #endif + if (module == NULL) + INITERROR; + #if PY_MAJOR_VERSION >= 3 + return module; + #endif + } + """ + ), + }, + setup_kwargs=dict( + ext_modules=[ + Record( + 'setuptools.Extension', name='extension', sources=['extension.c'] + ) + ], + ), + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}-{platform}.egg': [ + 'extension{shlib_ext}', + { + 'EGG-INFO': [ + 'PKG-INFO', + 'RECORD', + 'WHEEL', + 'top_level.txt', + ] + }, + ] + }), + ), + dict( + id='header', + file_defs={ + 'header.h': DALS( + """ + """ + ), + }, + setup_kwargs=dict( + headers=['header.h'], + ), + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}.egg': [ + 'header.h', + { + 'EGG-INFO': [ + 'PKG-INFO', + 'RECORD', + 'WHEEL', + 'top_level.txt', + ] + }, + ] + }), + ), + dict( + id='script', + file_defs={ + 'script.py': DALS( + """ + #/usr/bin/python + print('hello world!') + """ + ), + 'script.sh': DALS( + """ + #/bin/sh + echo 'hello world!' + """ + ), + }, + setup_kwargs=dict( + scripts=['script.py', 'script.sh'], + ), + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}.egg': { + 'EGG-INFO': [ + 'PKG-INFO', + 'RECORD', + 'WHEEL', + 'top_level.txt', + {'scripts': ['script.py', 'script.sh']}, + ] + } + }), + ), + dict( + id='requires1', + install_requires='foobar==2.0', + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}.egg': { + 'EGG-INFO': [ + 'PKG-INFO', + 'RECORD', + 'WHEEL', + 'requires.txt', + 'top_level.txt', + ] + } + }), + requires_txt=DALS( + """ + foobar==2.0 + """ + ), + ), + dict( + id='requires2', + install_requires=f""" + bar + foo<=2.0; {sys.platform!r} in sys_platform + """, + requires_txt=DALS( + """ + bar + foo<=2.0 + """ + ), + ), + dict( + id='requires3', + install_requires=f""" + bar; {sys.platform!r} != sys_platform + """, + ), + dict( + id='requires4', + install_requires=""" + foo + """, + extras_require={ + 'extra': 'foobar>3', + }, + requires_txt=DALS( + """ + foo + + [extra] + foobar>3 + """ + ), + ), + dict( + id='requires5', + extras_require={ + 'extra': f'foobar; {sys.platform!r} != sys_platform', + }, + requires_txt=DALS( + """ + [extra] + """ + ), + ), + dict( + id='requires_ensure_order', + install_requires=""" + foo + bar + baz + qux + """, + extras_require={ + 'extra': """ + foobar>3 + barbaz>4 + bazqux>5 + quxzap>6 + """, + }, + requires_txt=DALS( + """ + foo + bar + baz + qux + + [extra] + foobar>3 + barbaz>4 + bazqux>5 + quxzap>6 + """ + ), + ), + dict( + id='namespace_package', + file_defs={ + 'foo': { + 'bar': {'__init__.py': ''}, + }, + }, + setup_kwargs=dict( + namespace_packages=['foo'], + packages=['foo.bar'], + ), + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}.egg': [ + 'foo-1.0-py{py_version}-nspkg.pth', + { + 'EGG-INFO': [ + 'PKG-INFO', + 'RECORD', + 'WHEEL', + 'namespace_packages.txt', + 'top_level.txt', + ] + }, + { + 'foo': [ + '__init__.py', + {'bar': ['__init__.py']}, + ] + }, + ] + }), + ), + dict( + id='empty_namespace_package', + file_defs={ + 'foobar': { + '__init__.py': ( + "__import__('pkg_resources').declare_namespace(__name__)" + ) + }, + }, + setup_kwargs=dict( + namespace_packages=['foobar'], + packages=['foobar'], + ), + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}.egg': [ + 'foo-1.0-py{py_version}-nspkg.pth', + { + 'EGG-INFO': [ + 'PKG-INFO', + 'RECORD', + 'WHEEL', + 'namespace_packages.txt', + 'top_level.txt', + ] + }, + { + 'foobar': [ + '__init__.py', + ] + }, + ] + }), + ), + dict( + id='data_in_package', + file_defs={ + 'foo': { + '__init__.py': '', + 'data_dir': { + 'data.txt': DALS( + """ + Some data... + """ + ), + }, + } + }, + setup_kwargs=dict( + packages=['foo'], + data_files=[('foo/data_dir', ['foo/data_dir/data.txt'])], + ), + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}.egg': { + 'EGG-INFO': [ + 'PKG-INFO', + 'RECORD', + 'WHEEL', + 'top_level.txt', + ], + 'foo': [ + '__init__.py', + { + 'data_dir': [ + 'data.txt', + ] + }, + ], + } + }), + ), +) + + +@pytest.mark.parametrize( + 'params', + WHEEL_INSTALL_TESTS, + ids=[params['id'] for params in WHEEL_INSTALL_TESTS], +) +def test_wheel_install(params): + project_name = params.get('name', 'foo') + version = params.get('version', '1.0') + install_requires = params.get('install_requires', []) + extras_require = params.get('extras_require', {}) + requires_txt = params.get('requires_txt', None) + install_tree = params.get('install_tree') + file_defs = params.get('file_defs', {}) + setup_kwargs = params.get('setup_kwargs', {}) + with ( + build_wheel( + name=project_name, + version=version, + install_requires=install_requires, + extras_require=extras_require, + extra_file_defs=file_defs, + **setup_kwargs, + ) as filename, + tempdir() as install_dir, + ): + _check_wheel_install( + filename, install_dir, install_tree, project_name, version, requires_txt + ) + + +def test_wheel_install_pep_503(): + project_name = 'Foo_Bar' # PEP 503 canonicalized name is "foo-bar" + version = '1.0' + with ( + build_wheel( + name=project_name, + version=version, + ) as filename, + tempdir() as install_dir, + ): + new_filename = filename.replace(project_name, canonicalize_name(project_name)) + shutil.move(filename, new_filename) + _check_wheel_install( + new_filename, + install_dir, + None, + canonicalize_name(project_name), + version, + None, + ) + + +def test_wheel_no_dist_dir(): + project_name = 'nodistinfo' + version = '1.0' + wheel_name = f'{project_name}-{version}-py2.py3-none-any.whl' + with tempdir() as source_dir: + wheel_path = os.path.join(source_dir, wheel_name) + # create an empty zip file + zipfile.ZipFile(wheel_path, 'w').close() + with tempdir() as install_dir: + with pytest.raises(ValueError): + _check_wheel_install( + wheel_path, install_dir, None, project_name, version, None + ) + + +def test_wheel_is_compatible(monkeypatch): + def sys_tags(): + return { + (t.interpreter, t.abi, t.platform) + for t in parse_tag('cp36-cp36m-manylinux1_x86_64') + } + + monkeypatch.setattr('setuptools.wheel._get_supported_tags', sys_tags) + assert Wheel('onnxruntime-0.1.2-cp36-cp36m-manylinux1_x86_64.whl').is_compatible() + + +def test_wheel_mode(): + @contextlib.contextmanager + def build_wheel(extra_file_defs=None, **kwargs): + file_defs = { + 'setup.py': ( + DALS( + """ + # -*- coding: utf-8 -*- + from setuptools import setup + import setuptools + setup(**%r) + """ + ) + % kwargs + ).encode('utf-8'), + } + if extra_file_defs: + file_defs.update(extra_file_defs) + with tempdir() as source_dir: + path.build(file_defs, source_dir) + runsh = pathlib.Path(source_dir) / "script.sh" + os.chmod(runsh, 0o777) + subprocess.check_call( + (sys.executable, 'setup.py', '-q', 'bdist_wheel'), cwd=source_dir + ) + yield glob.glob(os.path.join(source_dir, 'dist', '*.whl'))[0] + + params = dict( + id='script', + file_defs={ + 'script.py': DALS( + """ + #/usr/bin/python + print('hello world!') + """ + ), + 'script.sh': DALS( + """ + #/bin/sh + echo 'hello world!' + """ + ), + }, + setup_kwargs=dict( + scripts=['script.py', 'script.sh'], + ), + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}.egg': { + 'EGG-INFO': [ + 'PKG-INFO', + 'RECORD', + 'WHEEL', + 'top_level.txt', + {'scripts': ['script.py', 'script.sh']}, + ] + } + }), + ) + + project_name = params.get('name', 'foo') + version = params.get('version', '1.0') + install_tree = params.get('install_tree') + file_defs = params.get('file_defs', {}) + setup_kwargs = params.get('setup_kwargs', {}) + + with ( + build_wheel( + name=project_name, + version=version, + install_requires=[], + extras_require={}, + extra_file_defs=file_defs, + **setup_kwargs, + ) as filename, + tempdir() as install_dir, + ): + _check_wheel_install( + filename, install_dir, install_tree, project_name, version, None + ) + w = Wheel(filename) + base = pathlib.Path(install_dir) / w.egg_name() + script_sh = base / "EGG-INFO" / "scripts" / "script.sh" + assert script_sh.exists() + if sys.platform != 'win32': + # Editable file mode has no effect on Windows + assert oct(stat.S_IMODE(script_sh.stat().st_mode)) == "0o777" diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/test_windows_wrappers.py b/.venv/lib/python3.12/site-packages/setuptools/tests/test_windows_wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..f895485387f2f9f673f96f7114629297a381e66c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/test_windows_wrappers.py @@ -0,0 +1,259 @@ +""" +Python Script Wrapper for Windows +================================= + +setuptools includes wrappers for Python scripts that allows them to be +executed like regular windows programs. There are 2 wrappers, one +for command-line programs, cli.exe, and one for graphical programs, +gui.exe. These programs are almost identical, function pretty much +the same way, and are generated from the same source file. The +wrapper programs are used by copying them to the directory containing +the script they are to wrap and with the same name as the script they +are to wrap. +""" + +import pathlib +import platform +import subprocess +import sys +import textwrap + +import pytest + +import pkg_resources +from setuptools.command.easy_install import nt_quote_arg + +pytestmark = pytest.mark.skipif(sys.platform != 'win32', reason="Windows only") + + +class WrapperTester: + @classmethod + def prep_script(cls, template): + python_exe = nt_quote_arg(sys.executable) + return template % locals() + + @classmethod + def create_script(cls, tmpdir): + """ + Create a simple script, foo-script.py + + Note that the script starts with a Unix-style '#!' line saying which + Python executable to run. The wrapper will use this line to find the + correct Python executable. + """ + + script = cls.prep_script(cls.script_tmpl) + + with (tmpdir / cls.script_name).open('w') as f: + f.write(script) + + # also copy cli.exe to the sample directory + with (tmpdir / cls.wrapper_name).open('wb') as f: + w = pkg_resources.resource_string('setuptools', cls.wrapper_source) + f.write(w) + + +def win_launcher_exe(prefix): + """A simple routine to select launcher script based on platform.""" + assert prefix in ('cli', 'gui') + if platform.machine() == "ARM64": + return f"{prefix}-arm64.exe" + else: + return f"{prefix}-32.exe" + + +class TestCLI(WrapperTester): + script_name = 'foo-script.py' + wrapper_name = 'foo.exe' + wrapper_source = win_launcher_exe('cli') + + script_tmpl = textwrap.dedent( + """ + #!%(python_exe)s + import sys + input = repr(sys.stdin.read()) + print(sys.argv[0][-14:]) + print(sys.argv[1:]) + print(input) + if __debug__: + print('non-optimized') + """ + ).lstrip() + + def test_basic(self, tmpdir): + """ + When the copy of cli.exe, foo.exe in this example, runs, it examines + the path name it was run with and computes a Python script path name + by removing the '.exe' suffix and adding the '-script.py' suffix. (For + GUI programs, the suffix '-script.pyw' is added.) This is why we + named out script the way we did. Now we can run out script by running + the wrapper: + + This example was a little pathological in that it exercised windows + (MS C runtime) quoting rules: + + - Strings containing spaces are surrounded by double quotes. + + - Double quotes in strings need to be escaped by preceding them with + back slashes. + + - One or more backslashes preceding double quotes need to be escaped + by preceding each of them with back slashes. + """ + self.create_script(tmpdir) + cmd = [ + str(tmpdir / 'foo.exe'), + 'arg1', + 'arg 2', + 'arg "2\\"', + 'arg 4\\', + 'arg5 a\\\\b', + ] + proc = subprocess.Popen( + cmd, + stdout=subprocess.PIPE, + stdin=subprocess.PIPE, + text=True, + encoding="utf-8", + ) + stdout, _stderr = proc.communicate('hello\nworld\n') + actual = stdout.replace('\r\n', '\n') + expected = textwrap.dedent( + r""" + \foo-script.py + ['arg1', 'arg 2', 'arg "2\\"', 'arg 4\\', 'arg5 a\\\\b'] + 'hello\nworld\n' + non-optimized + """ + ).lstrip() + assert actual == expected + + def test_symlink(self, tmpdir): + """ + Ensure that symlink for the foo.exe is working correctly. + """ + script_dir = tmpdir / "script_dir" + script_dir.mkdir() + self.create_script(script_dir) + symlink = pathlib.Path(tmpdir / "foo.exe") + symlink.symlink_to(script_dir / "foo.exe") + + cmd = [ + str(tmpdir / 'foo.exe'), + 'arg1', + 'arg 2', + 'arg "2\\"', + 'arg 4\\', + 'arg5 a\\\\b', + ] + proc = subprocess.Popen( + cmd, + stdout=subprocess.PIPE, + stdin=subprocess.PIPE, + text=True, + encoding="utf-8", + ) + stdout, _stderr = proc.communicate('hello\nworld\n') + actual = stdout.replace('\r\n', '\n') + expected = textwrap.dedent( + r""" + \foo-script.py + ['arg1', 'arg 2', 'arg "2\\"', 'arg 4\\', 'arg5 a\\\\b'] + 'hello\nworld\n' + non-optimized + """ + ).lstrip() + assert actual == expected + + def test_with_options(self, tmpdir): + """ + Specifying Python Command-line Options + -------------------------------------- + + You can specify a single argument on the '#!' line. This can be used + to specify Python options like -O, to run in optimized mode or -i + to start the interactive interpreter. You can combine multiple + options as usual. For example, to run in optimized mode and + enter the interpreter after running the script, you could use -Oi: + """ + self.create_script(tmpdir) + tmpl = textwrap.dedent( + """ + #!%(python_exe)s -Oi + import sys + input = repr(sys.stdin.read()) + print(sys.argv[0][-14:]) + print(sys.argv[1:]) + print(input) + if __debug__: + print('non-optimized') + sys.ps1 = '---' + """ + ).lstrip() + with (tmpdir / 'foo-script.py').open('w') as f: + f.write(self.prep_script(tmpl)) + cmd = [str(tmpdir / 'foo.exe')] + proc = subprocess.Popen( + cmd, + stdout=subprocess.PIPE, + stdin=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + encoding="utf-8", + ) + stdout, _stderr = proc.communicate() + actual = stdout.replace('\r\n', '\n') + expected = textwrap.dedent( + r""" + \foo-script.py + [] + '' + --- + """ + ).lstrip() + assert actual == expected + + +class TestGUI(WrapperTester): + """ + Testing the GUI Version + ----------------------- + """ + + script_name = 'bar-script.pyw' + wrapper_source = win_launcher_exe('gui') + wrapper_name = 'bar.exe' + + script_tmpl = textwrap.dedent( + """ + #!%(python_exe)s + import sys + f = open(sys.argv[1], 'wb') + bytes_written = f.write(repr(sys.argv[2]).encode('utf-8')) + f.close() + """ + ).strip() + + def test_basic(self, tmpdir): + """Test the GUI version with the simple script, bar-script.py""" + self.create_script(tmpdir) + + cmd = [ + str(tmpdir / 'bar.exe'), + str(tmpdir / 'test_output.txt'), + 'Test Argument', + ] + proc = subprocess.Popen( + cmd, + stdout=subprocess.PIPE, + stdin=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + encoding="utf-8", + ) + stdout, stderr = proc.communicate() + assert not stdout + assert not stderr + with (tmpdir / 'test_output.txt').open('rb') as f_out: + actual = f_out.read().decode('ascii') + assert actual == repr('Test Argument') diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/text.py b/.venv/lib/python3.12/site-packages/setuptools/tests/text.py new file mode 100644 index 0000000000000000000000000000000000000000..e05cc633ede9e5ce4f74b66a7bf76327c2000caa --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/text.py @@ -0,0 +1,4 @@ +class Filenames: + unicode = 'smörbröd.py' + latin_1 = unicode.encode('latin-1') + utf_8 = unicode.encode('utf-8') diff --git a/.venv/lib/python3.12/site-packages/setuptools/tests/textwrap.py b/.venv/lib/python3.12/site-packages/setuptools/tests/textwrap.py new file mode 100644 index 0000000000000000000000000000000000000000..5e39618dca4ad6c3f0d4c8cb20af59ab85fb0eba --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/tests/textwrap.py @@ -0,0 +1,6 @@ +import textwrap + + +def DALS(s): + "dedent and left-strip" + return textwrap.dedent(s).lstrip() diff --git a/.venv/lib/python3.12/site-packages/setuptools/unicode_utils.py b/.venv/lib/python3.12/site-packages/setuptools/unicode_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f502f5b089619eafd28e2c7a61967e34e16920e5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/unicode_utils.py @@ -0,0 +1,102 @@ +import sys +import unicodedata +from configparser import RawConfigParser + +from .compat import py39 +from .warnings import SetuptoolsDeprecationWarning + + +# HFS Plus uses decomposed UTF-8 +def decompose(path): + if isinstance(path, str): + return unicodedata.normalize('NFD', path) + try: + path = path.decode('utf-8') + path = unicodedata.normalize('NFD', path) + path = path.encode('utf-8') + except UnicodeError: + pass # Not UTF-8 + return path + + +def filesys_decode(path): + """ + Ensure that the given path is decoded, + ``None`` when no expected encoding works + """ + + if isinstance(path, str): + return path + + fs_enc = sys.getfilesystemencoding() or 'utf-8' + candidates = fs_enc, 'utf-8' + + for enc in candidates: + try: + return path.decode(enc) + except UnicodeDecodeError: + continue + + return None + + +def try_encode(string, enc): + "turn unicode encoding into a functional routine" + try: + return string.encode(enc) + except UnicodeEncodeError: + return None + + +def _read_utf8_with_fallback(file: str, fallback_encoding=py39.LOCALE_ENCODING) -> str: + """ + First try to read the file with UTF-8, if there is an error fallback to a + different encoding ("locale" by default). Returns the content of the file. + Also useful when reading files that might have been produced by an older version of + setuptools. + """ + try: + with open(file, "r", encoding="utf-8") as f: + return f.read() + except UnicodeDecodeError: # pragma: no cover + _Utf8EncodingNeeded.emit(file=file, fallback_encoding=fallback_encoding) + with open(file, "r", encoding=fallback_encoding) as f: + return f.read() + + +def _cfg_read_utf8_with_fallback( + cfg: RawConfigParser, file: str, fallback_encoding=py39.LOCALE_ENCODING +) -> None: + """Same idea as :func:`_read_utf8_with_fallback`, but for the + :meth:`RawConfigParser.read` method. + + This method may call ``cfg.clear()``. + """ + try: + cfg.read(file, encoding="utf-8") + except UnicodeDecodeError: # pragma: no cover + _Utf8EncodingNeeded.emit(file=file, fallback_encoding=fallback_encoding) + cfg.clear() + cfg.read(file, encoding=fallback_encoding) + + +class _Utf8EncodingNeeded(SetuptoolsDeprecationWarning): + _SUMMARY = """ + `encoding="utf-8"` fails with {file!r}, trying `encoding={fallback_encoding!r}`. + """ + + _DETAILS = """ + Fallback behavior for UTF-8 is considered **deprecated** and future versions of + `setuptools` may not implement it. + + Please encode {file!r} with "utf-8" to ensure future builds will succeed. + + If this file was produced by `setuptools` itself, cleaning up the cached files + and re-building/re-installing the package with a newer version of `setuptools` + (e.g. by updating `build-system.requires` in its `pyproject.toml`) + might solve the problem. + """ + # TODO: Add a deadline? + # Will we be able to remove this? + # The question comes to mind mainly because of sdists that have been produced + # by old versions of setuptools and published to PyPI... diff --git a/.venv/lib/python3.12/site-packages/setuptools/version.py b/.venv/lib/python3.12/site-packages/setuptools/version.py new file mode 100644 index 0000000000000000000000000000000000000000..ec253c414474677d3a5977511cfe901bfb786740 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/version.py @@ -0,0 +1,6 @@ +from ._importlib import metadata + +try: + __version__ = metadata.version('setuptools') or '0.dev0+unknown' +except Exception: + __version__ = '0.dev0+unknown' diff --git a/.venv/lib/python3.12/site-packages/setuptools/warnings.py b/.venv/lib/python3.12/site-packages/setuptools/warnings.py new file mode 100644 index 0000000000000000000000000000000000000000..96467787c237846bfbacf2d44eb833be0a88b633 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/warnings.py @@ -0,0 +1,110 @@ +"""Provide basic warnings used by setuptools modules. + +Using custom classes (other than ``UserWarning``) allow users to set +``PYTHONWARNINGS`` filters to run tests and prepare for upcoming changes in +setuptools. +""" + +from __future__ import annotations + +import os +import warnings +from datetime import date +from inspect import cleandoc +from textwrap import indent +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from typing_extensions import TypeAlias + +_DueDate: TypeAlias = tuple[int, int, int] # time tuple +_INDENT = 8 * " " +_TEMPLATE = f"""{80 * '*'}\n{{details}}\n{80 * '*'}""" + + +class SetuptoolsWarning(UserWarning): + """Base class in ``setuptools`` warning hierarchy.""" + + @classmethod + def emit( + cls, + summary: str | None = None, + details: str | None = None, + due_date: _DueDate | None = None, + see_docs: str | None = None, + see_url: str | None = None, + stacklevel: int = 2, + **kwargs, + ) -> None: + """Private: reserved for ``setuptools`` internal use only""" + # Default values: + summary_ = summary or getattr(cls, "_SUMMARY", None) or "" + details_ = details or getattr(cls, "_DETAILS", None) or "" + due_date = due_date or getattr(cls, "_DUE_DATE", None) + docs_ref = see_docs or getattr(cls, "_SEE_DOCS", None) + docs_url = docs_ref and f"https://setuptools.pypa.io/en/latest/{docs_ref}" + see_url = see_url or getattr(cls, "_SEE_URL", None) + due = date(*due_date) if due_date else None + + text = cls._format(summary_, details_, due, see_url or docs_url, kwargs) + if due and due < date.today() and _should_enforce(): + raise cls(text) + warnings.warn(text, cls, stacklevel=stacklevel + 1) + + @classmethod + def _format( + cls, + summary: str, + details: str, + due_date: date | None = None, + see_url: str | None = None, + format_args: dict | None = None, + ) -> str: + """Private: reserved for ``setuptools`` internal use only""" + today = date.today() + summary = cleandoc(summary).format_map(format_args or {}) + possible_parts = [ + cleandoc(details).format_map(format_args or {}), + ( + f"\nBy {due_date:%Y-%b-%d}, you need to update your project and remove " + "deprecated calls\nor your builds will no longer be supported." + if due_date and due_date > today + else None + ), + ( + "\nThis deprecation is overdue, please update your project and remove " + "deprecated\ncalls to avoid build errors in the future." + if due_date and due_date < today + else None + ), + (f"\nSee {see_url} for details." if see_url else None), + ] + parts = [x for x in possible_parts if x] + if parts: + body = indent(_TEMPLATE.format(details="\n".join(parts)), _INDENT) + return "\n".join([summary, "!!\n", body, "\n!!"]) + return summary + + +class InformationOnly(SetuptoolsWarning): + """Currently there is no clear way of displaying messages to the users + that use the setuptools backend directly via ``pip``. + The only thing that might work is a warning, although it is not the + most appropriate tool for the job... + + See pypa/packaging-problems#558. + """ + + +class SetuptoolsDeprecationWarning(SetuptoolsWarning): + """ + Base class for warning deprecations in ``setuptools`` + + This class is not derived from ``DeprecationWarning``, and as such is + visible by default. + """ + + +def _should_enforce(): + enforce = os.getenv("SETUPTOOLS_ENFORCE_DEPRECATION", "false").lower() + return enforce in ("true", "on", "ok", "1") diff --git a/.venv/lib/python3.12/site-packages/setuptools/wheel.py b/.venv/lib/python3.12/site-packages/setuptools/wheel.py new file mode 100644 index 0000000000000000000000000000000000000000..c7ca43b5cfb2aff8d6983bbba4b7e6fdc9d01f83 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/wheel.py @@ -0,0 +1,236 @@ +"""Wheels support.""" + +import contextlib +import email +import functools +import itertools +import os +import posixpath +import re +import zipfile + +from packaging.tags import sys_tags +from packaging.utils import canonicalize_name +from packaging.version import Version as parse_version + +import setuptools +from setuptools.archive_util import _unpack_zipfile_obj +from setuptools.command.egg_info import _egg_basename, write_requirements + +from .unicode_utils import _read_utf8_with_fallback + +from distutils.util import get_platform + +WHEEL_NAME = re.compile( + r"""^(?P.+?)-(?P\d.*?) + ((-(?P\d.*?))?-(?P.+?)-(?P.+?)-(?P.+?) + )\.whl$""", + re.VERBOSE, +).match + +NAMESPACE_PACKAGE_INIT = "__import__('pkg_resources').declare_namespace(__name__)\n" + + +@functools.cache +def _get_supported_tags(): + # We calculate the supported tags only once, otherwise calling + # this method on thousands of wheels takes seconds instead of + # milliseconds. + return {(t.interpreter, t.abi, t.platform) for t in sys_tags()} + + +def unpack(src_dir, dst_dir) -> None: + """Move everything under `src_dir` to `dst_dir`, and delete the former.""" + for dirpath, dirnames, filenames in os.walk(src_dir): + subdir = os.path.relpath(dirpath, src_dir) + for f in filenames: + src = os.path.join(dirpath, f) + dst = os.path.join(dst_dir, subdir, f) + os.renames(src, dst) + for n, d in reversed(list(enumerate(dirnames))): + src = os.path.join(dirpath, d) + dst = os.path.join(dst_dir, subdir, d) + if not os.path.exists(dst): + # Directory does not exist in destination, + # rename it and prune it from os.walk list. + os.renames(src, dst) + del dirnames[n] + # Cleanup. + for dirpath, dirnames, filenames in os.walk(src_dir, topdown=True): + assert not filenames + os.rmdir(dirpath) + + +@contextlib.contextmanager +def disable_info_traces(): + """ + Temporarily disable info traces. + """ + from distutils import log + + saved = log.set_threshold(log.WARN) + try: + yield + finally: + log.set_threshold(saved) + + +class Wheel: + def __init__(self, filename) -> None: + match = WHEEL_NAME(os.path.basename(filename)) + if match is None: + raise ValueError(f'invalid wheel name: {filename!r}') + self.filename = filename + for k, v in match.groupdict().items(): + setattr(self, k, v) + + def tags(self): + """List tags (py_version, abi, platform) supported by this wheel.""" + return itertools.product( + self.py_version.split('.'), + self.abi.split('.'), + self.platform.split('.'), + ) + + def is_compatible(self): + """Is the wheel compatible with the current platform?""" + return next((True for t in self.tags() if t in _get_supported_tags()), False) + + def egg_name(self): + return ( + _egg_basename( + self.project_name, + self.version, + platform=(None if self.platform == 'any' else get_platform()), + ) + + ".egg" + ) + + def get_dist_info(self, zf): + # find the correct name of the .dist-info dir in the wheel file + for member in zf.namelist(): + dirname = posixpath.dirname(member) + if dirname.endswith('.dist-info') and canonicalize_name(dirname).startswith( + canonicalize_name(self.project_name) + ): + return dirname + raise ValueError("unsupported wheel format. .dist-info not found") + + def install_as_egg(self, destination_eggdir) -> None: + """Install wheel as an egg directory.""" + with zipfile.ZipFile(self.filename) as zf: + self._install_as_egg(destination_eggdir, zf) + + def _install_as_egg(self, destination_eggdir, zf): + dist_basename = f'{self.project_name}-{self.version}' + dist_info = self.get_dist_info(zf) + dist_data = f'{dist_basename}.data' + egg_info = os.path.join(destination_eggdir, 'EGG-INFO') + + self._convert_metadata(zf, destination_eggdir, dist_info, egg_info) + self._move_data_entries(destination_eggdir, dist_data) + self._fix_namespace_packages(egg_info, destination_eggdir) + + @staticmethod + def _convert_metadata(zf, destination_eggdir, dist_info, egg_info): + import pkg_resources + + def get_metadata(name): + with zf.open(posixpath.join(dist_info, name)) as fp: + value = fp.read().decode('utf-8') + return email.parser.Parser().parsestr(value) + + wheel_metadata = get_metadata('WHEEL') + # Check wheel format version is supported. + wheel_version = parse_version(wheel_metadata.get('Wheel-Version')) + wheel_v1 = parse_version('1.0') <= wheel_version < parse_version('2.0dev0') + if not wheel_v1: + raise ValueError(f'unsupported wheel format version: {wheel_version}') + # Extract to target directory. + _unpack_zipfile_obj(zf, destination_eggdir) + # Convert metadata. + dist_info = os.path.join(destination_eggdir, dist_info) + dist = pkg_resources.Distribution.from_location( + destination_eggdir, + dist_info, + metadata=pkg_resources.PathMetadata(destination_eggdir, dist_info), + ) + + # Note: Evaluate and strip markers now, + # as it's difficult to convert back from the syntax: + # foobar; "linux" in sys_platform and extra == 'test' + def raw_req(req): + req.marker = None + return str(req) + + install_requires = list(map(raw_req, dist.requires())) + extras_require = { + extra: [ + req + for req in map(raw_req, dist.requires((extra,))) + if req not in install_requires + ] + for extra in dist.extras + } + os.rename(dist_info, egg_info) + os.rename( + os.path.join(egg_info, 'METADATA'), + os.path.join(egg_info, 'PKG-INFO'), + ) + setup_dist = setuptools.Distribution( + attrs=dict( + install_requires=install_requires, + extras_require=extras_require, + ), + ) + with disable_info_traces(): + write_requirements( + setup_dist.get_command_obj('egg_info'), + None, + os.path.join(egg_info, 'requires.txt'), + ) + + @staticmethod + def _move_data_entries(destination_eggdir, dist_data): + """Move data entries to their correct location.""" + dist_data = os.path.join(destination_eggdir, dist_data) + dist_data_scripts = os.path.join(dist_data, 'scripts') + if os.path.exists(dist_data_scripts): + egg_info_scripts = os.path.join(destination_eggdir, 'EGG-INFO', 'scripts') + os.mkdir(egg_info_scripts) + for entry in os.listdir(dist_data_scripts): + # Remove bytecode, as it's not properly handled + # during easy_install scripts install phase. + if entry.endswith('.pyc'): + os.unlink(os.path.join(dist_data_scripts, entry)) + else: + os.rename( + os.path.join(dist_data_scripts, entry), + os.path.join(egg_info_scripts, entry), + ) + os.rmdir(dist_data_scripts) + for subdir in filter( + os.path.exists, + ( + os.path.join(dist_data, d) + for d in ('data', 'headers', 'purelib', 'platlib') + ), + ): + unpack(subdir, destination_eggdir) + if os.path.exists(dist_data): + os.rmdir(dist_data) + + @staticmethod + def _fix_namespace_packages(egg_info, destination_eggdir): + namespace_packages = os.path.join(egg_info, 'namespace_packages.txt') + if os.path.exists(namespace_packages): + namespace_packages = _read_utf8_with_fallback(namespace_packages).split() + + for mod in namespace_packages: + mod_dir = os.path.join(destination_eggdir, *mod.split('.')) + mod_init = os.path.join(mod_dir, '__init__.py') + if not os.path.exists(mod_dir): + os.mkdir(mod_dir) + if not os.path.exists(mod_init): + with open(mod_init, 'w', encoding="utf-8") as fp: + fp.write(NAMESPACE_PACKAGE_INIT) diff --git a/.venv/lib/python3.12/site-packages/setuptools/windows_support.py b/.venv/lib/python3.12/site-packages/setuptools/windows_support.py new file mode 100644 index 0000000000000000000000000000000000000000..7a2b53a291409c66851961a559eb4d69be0f4acc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/setuptools/windows_support.py @@ -0,0 +1,30 @@ +import platform + + +def windows_only(func): + if platform.system() != 'Windows': + return lambda *args, **kwargs: None + return func + + +@windows_only +def hide_file(path: str) -> None: + """ + Set the hidden attribute on a file or directory. + + From https://stackoverflow.com/questions/19622133/ + + `path` must be text. + """ + import ctypes + import ctypes.wintypes + + SetFileAttributes = ctypes.windll.kernel32.SetFileAttributesW + SetFileAttributes.argtypes = ctypes.wintypes.LPWSTR, ctypes.wintypes.DWORD + SetFileAttributes.restype = ctypes.wintypes.BOOL + + FILE_ATTRIBUTE_HIDDEN = 0x02 + + ret = SetFileAttributes(path, FILE_ATTRIBUTE_HIDDEN) + if not ret: + raise ctypes.WinError() diff --git a/.venv/lib/python3.12/site-packages/six-1.17.0.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/six-1.17.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/six-1.17.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv/lib/python3.12/site-packages/six-1.17.0.dist-info/LICENSE b/.venv/lib/python3.12/site-packages/six-1.17.0.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1cc22a5aa7679ebaa10934212f356823931bdc3e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/six-1.17.0.dist-info/LICENSE @@ -0,0 +1,18 @@ +Copyright (c) 2010-2024 Benjamin Peterson + +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.12/site-packages/six-1.17.0.dist-info/METADATA b/.venv/lib/python3.12/site-packages/six-1.17.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..cfde03c2631c5c1d5cdc0949d0ee3379e7110f0e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/six-1.17.0.dist-info/METADATA @@ -0,0 +1,43 @@ +Metadata-Version: 2.1 +Name: six +Version: 1.17.0 +Summary: Python 2 and 3 compatibility utilities +Home-page: https://github.com/benjaminp/six +Author: Benjamin Peterson +Author-email: benjamin@python.org +License: MIT +Classifier: Development Status :: 5 - Production/Stable +Classifier: Programming Language :: Python :: 2 +Classifier: Programming Language :: Python :: 3 +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Topic :: Software Development :: Libraries +Classifier: Topic :: Utilities +Requires-Python: >=2.7, !=3.0.*, !=3.1.*, !=3.2.* +License-File: LICENSE + +.. image:: https://img.shields.io/pypi/v/six.svg + :target: https://pypi.org/project/six/ + :alt: six on PyPI + +.. image:: https://readthedocs.org/projects/six/badge/?version=latest + :target: https://six.readthedocs.io/ + :alt: six's documentation on Read the Docs + +.. image:: https://img.shields.io/badge/license-MIT-green.svg + :target: https://github.com/benjaminp/six/blob/master/LICENSE + :alt: MIT License badge + +Six is a Python 2 and 3 compatibility library. It provides utility functions +for smoothing over the differences between the Python versions with the goal of +writing Python code that is compatible on both Python versions. See the +documentation for more information on what is provided. + +Six supports Python 2.7 and 3.3+. It is contained in only one Python +file, so it can be easily copied into your project. (The copyright and license +notice must be retained.) + +Online documentation is at https://six.readthedocs.io/. + +Bugs can be reported to https://github.com/benjaminp/six. The code can also +be found there. diff --git a/.venv/lib/python3.12/site-packages/six-1.17.0.dist-info/RECORD b/.venv/lib/python3.12/site-packages/six-1.17.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..bb90c1a52e0f905a3facec665e8600ef20931282 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/six-1.17.0.dist-info/RECORD @@ -0,0 +1,8 @@ +__pycache__/six.cpython-312.pyc,, +six-1.17.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +six-1.17.0.dist-info/LICENSE,sha256=Q3W6IOK5xsTnytKUCmKP2Q6VzD1Q7pKq51VxXYuh-9A,1066 +six-1.17.0.dist-info/METADATA,sha256=ViBCB4wnUlSfbYp8htvF3XCAiKe-bYBnLsewcQC3JGg,1658 +six-1.17.0.dist-info/RECORD,, +six-1.17.0.dist-info/WHEEL,sha256=pxeNX5JdtCe58PUSYP9upmc7jdRPgvT0Gm9kb1SHlVw,109 +six-1.17.0.dist-info/top_level.txt,sha256=_iVH_iYEtEXnD8nYGQYpYFUvkUW9sEO1GYbkeKSAais,4 +six.py,sha256=xRyR9wPT1LNpbJI8tf7CE-BeddkhU5O--sfy-mo5BN8,34703 diff --git a/.venv/lib/python3.12/site-packages/six-1.17.0.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/six-1.17.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..104f3874635f24f0d2918dfeaf6a59652274460c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/six-1.17.0.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: setuptools (75.6.0) +Root-Is-Purelib: true +Tag: py2-none-any +Tag: py3-none-any + diff --git a/.venv/lib/python3.12/site-packages/six-1.17.0.dist-info/top_level.txt b/.venv/lib/python3.12/site-packages/six-1.17.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..ffe2fce498955b628014618b28c6bcf152466a4a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/six-1.17.0.dist-info/top_level.txt @@ -0,0 +1 @@ +six diff --git a/.venv/lib/python3.12/site-packages/six.py b/.venv/lib/python3.12/site-packages/six.py new file mode 100644 index 0000000000000000000000000000000000000000..3de5969b1ad3b973342e5e88ee1770fa7c798152 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/six.py @@ -0,0 +1,1003 @@ +# Copyright (c) 2010-2024 Benjamin Peterson +# +# 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. + +"""Utilities for writing code that runs on Python 2 and 3""" + +from __future__ import absolute_import + +import functools +import itertools +import operator +import sys +import types + +__author__ = "Benjamin Peterson " +__version__ = "1.17.0" + + +# Useful for very coarse version differentiation. +PY2 = sys.version_info[0] == 2 +PY3 = sys.version_info[0] == 3 +PY34 = sys.version_info[0:2] >= (3, 4) + +if PY3: + string_types = str, + integer_types = int, + class_types = type, + text_type = str + binary_type = bytes + + MAXSIZE = sys.maxsize +else: + string_types = basestring, + integer_types = (int, long) + class_types = (type, types.ClassType) + text_type = unicode + binary_type = str + + if sys.platform.startswith("java"): + # Jython always uses 32 bits. + MAXSIZE = int((1 << 31) - 1) + else: + # It's possible to have sizeof(long) != sizeof(Py_ssize_t). + class X(object): + + def __len__(self): + return 1 << 31 + try: + len(X()) + except OverflowError: + # 32-bit + MAXSIZE = int((1 << 31) - 1) + else: + # 64-bit + MAXSIZE = int((1 << 63) - 1) + del X + +if PY34: + from importlib.util import spec_from_loader +else: + spec_from_loader = None + + +def _add_doc(func, doc): + """Add documentation to a function.""" + func.__doc__ = doc + + +def _import_module(name): + """Import module, returning the module after the last dot.""" + __import__(name) + return sys.modules[name] + + +class _LazyDescr(object): + + def __init__(self, name): + self.name = name + + def __get__(self, obj, tp): + result = self._resolve() + setattr(obj, self.name, result) # Invokes __set__. + try: + # This is a bit ugly, but it avoids running this again by + # removing this descriptor. + delattr(obj.__class__, self.name) + except AttributeError: + pass + return result + + +class MovedModule(_LazyDescr): + + def __init__(self, name, old, new=None): + super(MovedModule, self).__init__(name) + if PY3: + if new is None: + new = name + self.mod = new + else: + self.mod = old + + def _resolve(self): + return _import_module(self.mod) + + def __getattr__(self, attr): + _module = self._resolve() + value = getattr(_module, attr) + setattr(self, attr, value) + return value + + +class _LazyModule(types.ModuleType): + + def __init__(self, name): + super(_LazyModule, self).__init__(name) + self.__doc__ = self.__class__.__doc__ + + def __dir__(self): + attrs = ["__doc__", "__name__"] + attrs += [attr.name for attr in self._moved_attributes] + return attrs + + # Subclasses should override this + _moved_attributes = [] + + +class MovedAttribute(_LazyDescr): + + def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None): + super(MovedAttribute, self).__init__(name) + if PY3: + if new_mod is None: + new_mod = name + self.mod = new_mod + if new_attr is None: + if old_attr is None: + new_attr = name + else: + new_attr = old_attr + self.attr = new_attr + else: + self.mod = old_mod + if old_attr is None: + old_attr = name + self.attr = old_attr + + def _resolve(self): + module = _import_module(self.mod) + return getattr(module, self.attr) + + +class _SixMetaPathImporter(object): + + """ + A meta path importer to import six.moves and its submodules. + + This class implements a PEP302 finder and loader. It should be compatible + with Python 2.5 and all existing versions of Python3 + """ + + def __init__(self, six_module_name): + self.name = six_module_name + self.known_modules = {} + + def _add_module(self, mod, *fullnames): + for fullname in fullnames: + self.known_modules[self.name + "." + fullname] = mod + + def _get_module(self, fullname): + return self.known_modules[self.name + "." + fullname] + + def find_module(self, fullname, path=None): + if fullname in self.known_modules: + return self + return None + + def find_spec(self, fullname, path, target=None): + if fullname in self.known_modules: + return spec_from_loader(fullname, self) + return None + + def __get_module(self, fullname): + try: + return self.known_modules[fullname] + except KeyError: + raise ImportError("This loader does not know module " + fullname) + + def load_module(self, fullname): + try: + # in case of a reload + return sys.modules[fullname] + except KeyError: + pass + mod = self.__get_module(fullname) + if isinstance(mod, MovedModule): + mod = mod._resolve() + else: + mod.__loader__ = self + sys.modules[fullname] = mod + return mod + + def is_package(self, fullname): + """ + Return true, if the named module is a package. + + We need this method to get correct spec objects with + Python 3.4 (see PEP451) + """ + return hasattr(self.__get_module(fullname), "__path__") + + def get_code(self, fullname): + """Return None + + Required, if is_package is implemented""" + self.__get_module(fullname) # eventually raises ImportError + return None + get_source = get_code # same as get_code + + def create_module(self, spec): + return self.load_module(spec.name) + + def exec_module(self, module): + pass + +_importer = _SixMetaPathImporter(__name__) + + +class _MovedItems(_LazyModule): + + """Lazy loading of moved objects""" + __path__ = [] # mark as package + + +_moved_attributes = [ + MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"), + MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"), + MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"), + MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"), + MovedAttribute("intern", "__builtin__", "sys"), + MovedAttribute("map", "itertools", "builtins", "imap", "map"), + MovedAttribute("getcwd", "os", "os", "getcwdu", "getcwd"), + MovedAttribute("getcwdb", "os", "os", "getcwd", "getcwdb"), + MovedAttribute("getoutput", "commands", "subprocess"), + MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"), + MovedAttribute("reload_module", "__builtin__", "importlib" if PY34 else "imp", "reload"), + MovedAttribute("reduce", "__builtin__", "functools"), + MovedAttribute("shlex_quote", "pipes", "shlex", "quote"), + MovedAttribute("StringIO", "StringIO", "io"), + MovedAttribute("UserDict", "UserDict", "collections", "IterableUserDict", "UserDict"), + MovedAttribute("UserList", "UserList", "collections"), + MovedAttribute("UserString", "UserString", "collections"), + MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"), + MovedAttribute("zip", "itertools", "builtins", "izip", "zip"), + MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"), + MovedModule("builtins", "__builtin__"), + MovedModule("configparser", "ConfigParser"), + MovedModule("collections_abc", "collections", "collections.abc" if sys.version_info >= (3, 3) else "collections"), + MovedModule("copyreg", "copy_reg"), + MovedModule("dbm_gnu", "gdbm", "dbm.gnu"), + MovedModule("dbm_ndbm", "dbm", "dbm.ndbm"), + MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread" if sys.version_info < (3, 9) else "_thread"), + MovedModule("http_cookiejar", "cookielib", "http.cookiejar"), + MovedModule("http_cookies", "Cookie", "http.cookies"), + MovedModule("html_entities", "htmlentitydefs", "html.entities"), + MovedModule("html_parser", "HTMLParser", "html.parser"), + MovedModule("http_client", "httplib", "http.client"), + MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"), + MovedModule("email_mime_image", "email.MIMEImage", "email.mime.image"), + MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"), + MovedModule("email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"), + MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"), + MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"), + MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"), + MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"), + MovedModule("cPickle", "cPickle", "pickle"), + MovedModule("queue", "Queue"), + MovedModule("reprlib", "repr"), + MovedModule("socketserver", "SocketServer"), + MovedModule("_thread", "thread", "_thread"), + MovedModule("tkinter", "Tkinter"), + MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"), + MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"), + MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"), + MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"), + MovedModule("tkinter_tix", "Tix", "tkinter.tix"), + MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"), + MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"), + MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"), + MovedModule("tkinter_colorchooser", "tkColorChooser", + "tkinter.colorchooser"), + MovedModule("tkinter_commondialog", "tkCommonDialog", + "tkinter.commondialog"), + MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"), + MovedModule("tkinter_font", "tkFont", "tkinter.font"), + MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"), + MovedModule("tkinter_tksimpledialog", "tkSimpleDialog", + "tkinter.simpledialog"), + MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"), + MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"), + MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"), + MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"), + MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"), + MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"), +] +# Add windows specific modules. +if sys.platform == "win32": + _moved_attributes += [ + MovedModule("winreg", "_winreg"), + ] + +for attr in _moved_attributes: + setattr(_MovedItems, attr.name, attr) + if isinstance(attr, MovedModule): + _importer._add_module(attr, "moves." + attr.name) +del attr + +_MovedItems._moved_attributes = _moved_attributes + +moves = _MovedItems(__name__ + ".moves") +_importer._add_module(moves, "moves") + + +class Module_six_moves_urllib_parse(_LazyModule): + + """Lazy loading of moved objects in six.moves.urllib_parse""" + + +_urllib_parse_moved_attributes = [ + MovedAttribute("ParseResult", "urlparse", "urllib.parse"), + MovedAttribute("SplitResult", "urlparse", "urllib.parse"), + MovedAttribute("parse_qs", "urlparse", "urllib.parse"), + MovedAttribute("parse_qsl", "urlparse", "urllib.parse"), + MovedAttribute("urldefrag", "urlparse", "urllib.parse"), + MovedAttribute("urljoin", "urlparse", "urllib.parse"), + MovedAttribute("urlparse", "urlparse", "urllib.parse"), + MovedAttribute("urlsplit", "urlparse", "urllib.parse"), + MovedAttribute("urlunparse", "urlparse", "urllib.parse"), + MovedAttribute("urlunsplit", "urlparse", "urllib.parse"), + MovedAttribute("quote", "urllib", "urllib.parse"), + MovedAttribute("quote_plus", "urllib", "urllib.parse"), + MovedAttribute("unquote", "urllib", "urllib.parse"), + MovedAttribute("unquote_plus", "urllib", "urllib.parse"), + MovedAttribute("unquote_to_bytes", "urllib", "urllib.parse", "unquote", "unquote_to_bytes"), + MovedAttribute("urlencode", "urllib", "urllib.parse"), + MovedAttribute("splitquery", "urllib", "urllib.parse"), + MovedAttribute("splittag", "urllib", "urllib.parse"), + MovedAttribute("splituser", "urllib", "urllib.parse"), + MovedAttribute("splitvalue", "urllib", "urllib.parse"), + MovedAttribute("uses_fragment", "urlparse", "urllib.parse"), + MovedAttribute("uses_netloc", "urlparse", "urllib.parse"), + MovedAttribute("uses_params", "urlparse", "urllib.parse"), + MovedAttribute("uses_query", "urlparse", "urllib.parse"), + MovedAttribute("uses_relative", "urlparse", "urllib.parse"), +] +for attr in _urllib_parse_moved_attributes: + setattr(Module_six_moves_urllib_parse, attr.name, attr) +del attr + +Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes + +_importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"), + "moves.urllib_parse", "moves.urllib.parse") + + +class Module_six_moves_urllib_error(_LazyModule): + + """Lazy loading of moved objects in six.moves.urllib_error""" + + +_urllib_error_moved_attributes = [ + MovedAttribute("URLError", "urllib2", "urllib.error"), + MovedAttribute("HTTPError", "urllib2", "urllib.error"), + MovedAttribute("ContentTooShortError", "urllib", "urllib.error"), +] +for attr in _urllib_error_moved_attributes: + setattr(Module_six_moves_urllib_error, attr.name, attr) +del attr + +Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes + +_importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"), + "moves.urllib_error", "moves.urllib.error") + + +class Module_six_moves_urllib_request(_LazyModule): + + """Lazy loading of moved objects in six.moves.urllib_request""" + + +_urllib_request_moved_attributes = [ + MovedAttribute("urlopen", "urllib2", "urllib.request"), + MovedAttribute("install_opener", "urllib2", "urllib.request"), + MovedAttribute("build_opener", "urllib2", "urllib.request"), + MovedAttribute("pathname2url", "urllib", "urllib.request"), + MovedAttribute("url2pathname", "urllib", "urllib.request"), + MovedAttribute("getproxies", "urllib", "urllib.request"), + MovedAttribute("Request", "urllib2", "urllib.request"), + MovedAttribute("OpenerDirector", "urllib2", "urllib.request"), + MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"), + MovedAttribute("ProxyHandler", "urllib2", "urllib.request"), + MovedAttribute("BaseHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"), + MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"), + MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"), + MovedAttribute("FileHandler", "urllib2", "urllib.request"), + MovedAttribute("FTPHandler", "urllib2", "urllib.request"), + MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"), + MovedAttribute("UnknownHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"), + MovedAttribute("urlretrieve", "urllib", "urllib.request"), + MovedAttribute("urlcleanup", "urllib", "urllib.request"), + MovedAttribute("proxy_bypass", "urllib", "urllib.request"), + MovedAttribute("parse_http_list", "urllib2", "urllib.request"), + MovedAttribute("parse_keqv_list", "urllib2", "urllib.request"), +] +if sys.version_info[:2] < (3, 14): + _urllib_request_moved_attributes.extend( + [ + MovedAttribute("URLopener", "urllib", "urllib.request"), + MovedAttribute("FancyURLopener", "urllib", "urllib.request"), + ] + ) +for attr in _urllib_request_moved_attributes: + setattr(Module_six_moves_urllib_request, attr.name, attr) +del attr + +Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes + +_importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"), + "moves.urllib_request", "moves.urllib.request") + + +class Module_six_moves_urllib_response(_LazyModule): + + """Lazy loading of moved objects in six.moves.urllib_response""" + + +_urllib_response_moved_attributes = [ + MovedAttribute("addbase", "urllib", "urllib.response"), + MovedAttribute("addclosehook", "urllib", "urllib.response"), + MovedAttribute("addinfo", "urllib", "urllib.response"), + MovedAttribute("addinfourl", "urllib", "urllib.response"), +] +for attr in _urllib_response_moved_attributes: + setattr(Module_six_moves_urllib_response, attr.name, attr) +del attr + +Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes + +_importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"), + "moves.urllib_response", "moves.urllib.response") + + +class Module_six_moves_urllib_robotparser(_LazyModule): + + """Lazy loading of moved objects in six.moves.urllib_robotparser""" + + +_urllib_robotparser_moved_attributes = [ + MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"), +] +for attr in _urllib_robotparser_moved_attributes: + setattr(Module_six_moves_urllib_robotparser, attr.name, attr) +del attr + +Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes + +_importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"), + "moves.urllib_robotparser", "moves.urllib.robotparser") + + +class Module_six_moves_urllib(types.ModuleType): + + """Create a six.moves.urllib namespace that resembles the Python 3 namespace""" + __path__ = [] # mark as package + parse = _importer._get_module("moves.urllib_parse") + error = _importer._get_module("moves.urllib_error") + request = _importer._get_module("moves.urllib_request") + response = _importer._get_module("moves.urllib_response") + robotparser = _importer._get_module("moves.urllib_robotparser") + + def __dir__(self): + return ['parse', 'error', 'request', 'response', 'robotparser'] + +_importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"), + "moves.urllib") + + +def add_move(move): + """Add an item to six.moves.""" + setattr(_MovedItems, move.name, move) + + +def remove_move(name): + """Remove item from six.moves.""" + try: + delattr(_MovedItems, name) + except AttributeError: + try: + del moves.__dict__[name] + except KeyError: + raise AttributeError("no such move, %r" % (name,)) + + +if PY3: + _meth_func = "__func__" + _meth_self = "__self__" + + _func_closure = "__closure__" + _func_code = "__code__" + _func_defaults = "__defaults__" + _func_globals = "__globals__" +else: + _meth_func = "im_func" + _meth_self = "im_self" + + _func_closure = "func_closure" + _func_code = "func_code" + _func_defaults = "func_defaults" + _func_globals = "func_globals" + + +try: + advance_iterator = next +except NameError: + def advance_iterator(it): + return it.next() +next = advance_iterator + + +try: + callable = callable +except NameError: + def callable(obj): + return any("__call__" in klass.__dict__ for klass in type(obj).__mro__) + + +if PY3: + def get_unbound_function(unbound): + return unbound + + create_bound_method = types.MethodType + + def create_unbound_method(func, cls): + return func + + Iterator = object +else: + def get_unbound_function(unbound): + return unbound.im_func + + def create_bound_method(func, obj): + return types.MethodType(func, obj, obj.__class__) + + def create_unbound_method(func, cls): + return types.MethodType(func, None, cls) + + class Iterator(object): + + def next(self): + return type(self).__next__(self) + + callable = callable +_add_doc(get_unbound_function, + """Get the function out of a possibly unbound function""") + + +get_method_function = operator.attrgetter(_meth_func) +get_method_self = operator.attrgetter(_meth_self) +get_function_closure = operator.attrgetter(_func_closure) +get_function_code = operator.attrgetter(_func_code) +get_function_defaults = operator.attrgetter(_func_defaults) +get_function_globals = operator.attrgetter(_func_globals) + + +if PY3: + def iterkeys(d, **kw): + return iter(d.keys(**kw)) + + def itervalues(d, **kw): + return iter(d.values(**kw)) + + def iteritems(d, **kw): + return iter(d.items(**kw)) + + def iterlists(d, **kw): + return iter(d.lists(**kw)) + + viewkeys = operator.methodcaller("keys") + + viewvalues = operator.methodcaller("values") + + viewitems = operator.methodcaller("items") +else: + def iterkeys(d, **kw): + return d.iterkeys(**kw) + + def itervalues(d, **kw): + return d.itervalues(**kw) + + def iteritems(d, **kw): + return d.iteritems(**kw) + + def iterlists(d, **kw): + return d.iterlists(**kw) + + viewkeys = operator.methodcaller("viewkeys") + + viewvalues = operator.methodcaller("viewvalues") + + viewitems = operator.methodcaller("viewitems") + +_add_doc(iterkeys, "Return an iterator over the keys of a dictionary.") +_add_doc(itervalues, "Return an iterator over the values of a dictionary.") +_add_doc(iteritems, + "Return an iterator over the (key, value) pairs of a dictionary.") +_add_doc(iterlists, + "Return an iterator over the (key, [values]) pairs of a dictionary.") + + +if PY3: + def b(s): + return s.encode("latin-1") + + def u(s): + return s + unichr = chr + import struct + int2byte = struct.Struct(">B").pack + del struct + byte2int = operator.itemgetter(0) + indexbytes = operator.getitem + iterbytes = iter + import io + StringIO = io.StringIO + BytesIO = io.BytesIO + del io + _assertCountEqual = "assertCountEqual" + if sys.version_info[1] <= 1: + _assertRaisesRegex = "assertRaisesRegexp" + _assertRegex = "assertRegexpMatches" + _assertNotRegex = "assertNotRegexpMatches" + else: + _assertRaisesRegex = "assertRaisesRegex" + _assertRegex = "assertRegex" + _assertNotRegex = "assertNotRegex" +else: + def b(s): + return s + # Workaround for standalone backslash + + def u(s): + return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape") + unichr = unichr + int2byte = chr + + def byte2int(bs): + return ord(bs[0]) + + def indexbytes(buf, i): + return ord(buf[i]) + iterbytes = functools.partial(itertools.imap, ord) + import StringIO + StringIO = BytesIO = StringIO.StringIO + _assertCountEqual = "assertItemsEqual" + _assertRaisesRegex = "assertRaisesRegexp" + _assertRegex = "assertRegexpMatches" + _assertNotRegex = "assertNotRegexpMatches" +_add_doc(b, """Byte literal""") +_add_doc(u, """Text literal""") + + +def assertCountEqual(self, *args, **kwargs): + return getattr(self, _assertCountEqual)(*args, **kwargs) + + +def assertRaisesRegex(self, *args, **kwargs): + return getattr(self, _assertRaisesRegex)(*args, **kwargs) + + +def assertRegex(self, *args, **kwargs): + return getattr(self, _assertRegex)(*args, **kwargs) + + +def assertNotRegex(self, *args, **kwargs): + return getattr(self, _assertNotRegex)(*args, **kwargs) + + +if PY3: + exec_ = getattr(moves.builtins, "exec") + + def reraise(tp, value, tb=None): + try: + if value is None: + value = tp() + if value.__traceback__ is not tb: + raise value.with_traceback(tb) + raise value + finally: + value = None + tb = None + +else: + def exec_(_code_, _globs_=None, _locs_=None): + """Execute code in a namespace.""" + if _globs_ is None: + frame = sys._getframe(1) + _globs_ = frame.f_globals + if _locs_ is None: + _locs_ = frame.f_locals + del frame + elif _locs_ is None: + _locs_ = _globs_ + exec("""exec _code_ in _globs_, _locs_""") + + exec_("""def reraise(tp, value, tb=None): + try: + raise tp, value, tb + finally: + tb = None +""") + + +if sys.version_info[:2] > (3,): + exec_("""def raise_from(value, from_value): + try: + raise value from from_value + finally: + value = None +""") +else: + def raise_from(value, from_value): + raise value + + +print_ = getattr(moves.builtins, "print", None) +if print_ is None: + def print_(*args, **kwargs): + """The new-style print function for Python 2.4 and 2.5.""" + fp = kwargs.pop("file", sys.stdout) + if fp is None: + return + + def write(data): + if not isinstance(data, basestring): + data = str(data) + # If the file has an encoding, encode unicode with it. + if (isinstance(fp, file) and + isinstance(data, unicode) and + fp.encoding is not None): + errors = getattr(fp, "errors", None) + if errors is None: + errors = "strict" + data = data.encode(fp.encoding, errors) + fp.write(data) + want_unicode = False + sep = kwargs.pop("sep", None) + if sep is not None: + if isinstance(sep, unicode): + want_unicode = True + elif not isinstance(sep, str): + raise TypeError("sep must be None or a string") + end = kwargs.pop("end", None) + if end is not None: + if isinstance(end, unicode): + want_unicode = True + elif not isinstance(end, str): + raise TypeError("end must be None or a string") + if kwargs: + raise TypeError("invalid keyword arguments to print()") + if not want_unicode: + for arg in args: + if isinstance(arg, unicode): + want_unicode = True + break + if want_unicode: + newline = unicode("\n") + space = unicode(" ") + else: + newline = "\n" + space = " " + if sep is None: + sep = space + if end is None: + end = newline + for i, arg in enumerate(args): + if i: + write(sep) + write(arg) + write(end) +if sys.version_info[:2] < (3, 3): + _print = print_ + + def print_(*args, **kwargs): + fp = kwargs.get("file", sys.stdout) + flush = kwargs.pop("flush", False) + _print(*args, **kwargs) + if flush and fp is not None: + fp.flush() + +_add_doc(reraise, """Reraise an exception.""") + +if sys.version_info[0:2] < (3, 4): + # This does exactly the same what the :func:`py3:functools.update_wrapper` + # function does on Python versions after 3.2. It sets the ``__wrapped__`` + # attribute on ``wrapper`` object and it doesn't raise an error if any of + # the attributes mentioned in ``assigned`` and ``updated`` are missing on + # ``wrapped`` object. + def _update_wrapper(wrapper, wrapped, + assigned=functools.WRAPPER_ASSIGNMENTS, + updated=functools.WRAPPER_UPDATES): + for attr in assigned: + try: + value = getattr(wrapped, attr) + except AttributeError: + continue + else: + setattr(wrapper, attr, value) + for attr in updated: + getattr(wrapper, attr).update(getattr(wrapped, attr, {})) + wrapper.__wrapped__ = wrapped + return wrapper + _update_wrapper.__doc__ = functools.update_wrapper.__doc__ + + def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, + updated=functools.WRAPPER_UPDATES): + return functools.partial(_update_wrapper, wrapped=wrapped, + assigned=assigned, updated=updated) + wraps.__doc__ = functools.wraps.__doc__ + +else: + wraps = functools.wraps + + +def with_metaclass(meta, *bases): + """Create a base class with a metaclass.""" + # This requires a bit of explanation: the basic idea is to make a dummy + # metaclass for one level of class instantiation that replaces itself with + # the actual metaclass. + class metaclass(type): + + def __new__(cls, name, this_bases, d): + if sys.version_info[:2] >= (3, 7): + # This version introduced PEP 560 that requires a bit + # of extra care (we mimic what is done by __build_class__). + resolved_bases = types.resolve_bases(bases) + if resolved_bases is not bases: + d['__orig_bases__'] = bases + else: + resolved_bases = bases + return meta(name, resolved_bases, d) + + @classmethod + def __prepare__(cls, name, this_bases): + return meta.__prepare__(name, bases) + return type.__new__(metaclass, 'temporary_class', (), {}) + + +def add_metaclass(metaclass): + """Class decorator for creating a class with a metaclass.""" + def wrapper(cls): + orig_vars = cls.__dict__.copy() + slots = orig_vars.get('__slots__') + if slots is not None: + if isinstance(slots, str): + slots = [slots] + for slots_var in slots: + orig_vars.pop(slots_var) + orig_vars.pop('__dict__', None) + orig_vars.pop('__weakref__', None) + if hasattr(cls, '__qualname__'): + orig_vars['__qualname__'] = cls.__qualname__ + return metaclass(cls.__name__, cls.__bases__, orig_vars) + return wrapper + + +def ensure_binary(s, encoding='utf-8', errors='strict'): + """Coerce **s** to six.binary_type. + + For Python 2: + - `unicode` -> encoded to `str` + - `str` -> `str` + + For Python 3: + - `str` -> encoded to `bytes` + - `bytes` -> `bytes` + """ + if isinstance(s, binary_type): + return s + if isinstance(s, text_type): + return s.encode(encoding, errors) + raise TypeError("not expecting type '%s'" % type(s)) + + +def ensure_str(s, encoding='utf-8', errors='strict'): + """Coerce *s* to `str`. + + For Python 2: + - `unicode` -> encoded to `str` + - `str` -> `str` + + For Python 3: + - `str` -> `str` + - `bytes` -> decoded to `str` + """ + # Optimization: Fast return for the common case. + if type(s) is str: + return s + if PY2 and isinstance(s, text_type): + return s.encode(encoding, errors) + elif PY3 and isinstance(s, binary_type): + return s.decode(encoding, errors) + elif not isinstance(s, (text_type, binary_type)): + raise TypeError("not expecting type '%s'" % type(s)) + return s + + +def ensure_text(s, encoding='utf-8', errors='strict'): + """Coerce *s* to six.text_type. + + For Python 2: + - `unicode` -> `unicode` + - `str` -> `unicode` + + For Python 3: + - `str` -> `str` + - `bytes` -> decoded to `str` + """ + if isinstance(s, binary_type): + return s.decode(encoding, errors) + elif isinstance(s, text_type): + return s + else: + raise TypeError("not expecting type '%s'" % type(s)) + + +def python_2_unicode_compatible(klass): + """ + A class decorator that defines __unicode__ and __str__ methods under Python 2. + Under Python 3 it does nothing. + + To support Python 2 and 3 with a single code base, define a __str__ method + returning text and apply this decorator to the class. + """ + if PY2: + if '__str__' not in klass.__dict__: + raise ValueError("@python_2_unicode_compatible cannot be applied " + "to %s because it doesn't define __str__()." % + klass.__name__) + klass.__unicode__ = klass.__str__ + klass.__str__ = lambda self: self.__unicode__().encode('utf-8') + return klass + + +# Complete the moves implementation. +# This code is at the end of this module to speed up module loading. +# Turn this module into a package. +__path__ = [] # required for PEP 302 and PEP 451 +__package__ = __name__ # see PEP 366 @ReservedAssignment +if globals().get("__spec__") is not None: + __spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable +# Remove other six meta path importers, since they cause problems. This can +# happen if six is removed from sys.modules and then reloaded. (Setuptools does +# this for some reason.) +if sys.meta_path: + for i, importer in enumerate(sys.meta_path): + # Here's some real nastiness: Another "instance" of the six module might + # be floating around. Therefore, we can't use isinstance() to check for + # the six meta path importer, since the other six instance will have + # inserted an importer with different class. + if (type(importer).__name__ == "_SixMetaPathImporter" and + importer.name == __name__): + del sys.meta_path[i] + break + del i, importer +# Finally, add the importer to the meta path import hook. +sys.meta_path.append(_importer) diff --git a/.venv/lib/python3.12/site-packages/soupsieve-2.9.2.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/soupsieve-2.9.2.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/soupsieve-2.9.2.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv/lib/python3.12/site-packages/soupsieve-2.9.2.dist-info/METADATA b/.venv/lib/python3.12/site-packages/soupsieve-2.9.2.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..eb7d6d8219ac25ee4fc0af3b83b44ab1d34c55df --- /dev/null +++ b/.venv/lib/python3.12/site-packages/soupsieve-2.9.2.dist-info/METADATA @@ -0,0 +1,114 @@ +Metadata-Version: 2.4 +Name: soupsieve +Version: 2.9.2 +Summary: A modern CSS selector implementation for Beautiful Soup. +Project-URL: Homepage, https://github.com/facelessuser/soupsieve +Author-email: Isaac Muse +License-Expression: MIT +License-File: LICENSE.md +Keywords: CSS,HTML,XML,filter,query,selector,soup +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Console +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +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: Programming Language :: Python :: 3.14 +Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Typing :: Typed +Requires-Python: >=3.10 +Description-Content-Type: text/markdown + +[![Donate via PayPal][donate-image]][donate-link] +[![Build][github-ci-image]][github-ci-link] +[![Coverage Status][codecov-image]][codecov-link] +[![PyPI Version][pypi-image]][pypi-link] +[![PyPI Downloads][pypi-down]][pypi-link] +[![PyPI - Python Version][python-image]][pypi-link] +[![License][license-image-mit]][license-link] + +# Soup Sieve + +## Overview + +Soup Sieve is a CSS selector library designed to be used with [Beautiful Soup 4][bs4]. It aims to provide selecting, +matching, and filtering using modern CSS selectors. Soup Sieve currently provides selectors from the CSS level 1 +specifications up through the latest CSS level 4 drafts and beyond (though some are not yet implemented). + +Soup Sieve was written with the intent to replace Beautiful Soup's builtin select feature, and as of Beautiful Soup +version 4.7.0, it now is :confetti_ball:. Soup Sieve can also be imported in order to use its API directly for +more controlled, specialized parsing. + +Soup Sieve has implemented most of the CSS selectors up through the latest CSS draft specifications, though there are a +number that don't make sense in a non-browser environment. Selectors that cannot provide meaningful functionality simply +do not match anything. Some of the supported selectors are: + +- `.classes` +- `#ids` +- `[attributes=value]` +- `parent child` +- `parent > child` +- `sibling ~ sibling` +- `sibling + sibling` +- `:not(element.class, element2.class)` +- `:is(element.class, element2.class)` +- `parent:has(> child)` +- and [many more](https://facelessuser.github.io/soupsieve/selectors/) + + +## Installation + +You must have Beautiful Soup already installed: + +``` +pip install beautifulsoup4 +``` + +In most cases, assuming you've installed version 4.7.0, that should be all you need to do, but if you've installed via +some alternative method, and Soup Sieve is not automatically installed, you can install it directly: + +``` +pip install soupsieve +``` + +If you want to manually install it from source, first ensure that [`build`](https://pypi.org/project/build/) is +installed: + +``` +pip install build +``` + +Then navigate to the root of the project and build the wheel and install (replacing `` with the current version): + +``` +python -m build -w +pip install dist/soupsieve--py3-none-any.whl +``` + +## Documentation + +Documentation is found here: https://facelessuser.github.io/soupsieve/. + +## License + +MIT + +[bs4]: https://beautiful-soup-4.readthedocs.io/en/latest/# + +[github-ci-image]: https://github.com/facelessuser/soupsieve/workflows/build/badge.svg +[github-ci-link]: https://github.com/facelessuser/soupsieve/actions?query=workflow%3Abuild+branch%3Amain +[codecov-image]: https://img.shields.io/codecov/c/github/facelessuser/soupsieve/master.svg?logo=codecov&logoColor=aaaaaa&labelColor=333333 +[codecov-link]: https://codecov.io/github/facelessuser/soupsieve +[pypi-image]: https://img.shields.io/pypi/v/soupsieve.svg?logo=pypi&logoColor=aaaaaa&labelColor=333333 +[pypi-down]: https://img.shields.io/pypi/dm/soupsieve.svg?logo=pypi&logoColor=aaaaaa&labelColor=333333 +[pypi-link]: https://pypi.python.org/pypi/soupsieve +[python-image]: https://img.shields.io/pypi/pyversions/soupsieve?logo=python&logoColor=aaaaaa&labelColor=333333 +[license-image-mit]: https://img.shields.io/badge/license-MIT-blue.svg?labelColor=333333 +[license-link]: https://github.com/facelessuser/soupsieve/blob/main/LICENSE.md +[donate-image]: https://img.shields.io/badge/Donate-PayPal-3fabd1?logo=paypal +[donate-link]: https://www.paypal.me/facelessuser diff --git a/.venv/lib/python3.12/site-packages/soupsieve-2.9.2.dist-info/RECORD b/.venv/lib/python3.12/site-packages/soupsieve-2.9.2.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..bff4c18a6fbfc31ca101bd92d10846a6af9cac35 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/soupsieve-2.9.2.dist-info/RECORD @@ -0,0 +1,20 @@ +soupsieve-2.9.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +soupsieve-2.9.2.dist-info/METADATA,sha256=Ja3mWAgXOBZXpCt8GKqpAyI-tpZAG-PuqYUNPUoa8YI,4586 +soupsieve-2.9.2.dist-info/RECORD,, +soupsieve-2.9.2.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87 +soupsieve-2.9.2.dist-info/licenses/LICENSE.md,sha256=dqCs25jDpjaB4gtvCWaZ74ytX7NdVu74OH4Ppx15epo,1096 +soupsieve/__init__.py,sha256=FV4Ol2FRldy7rG94nQHNHoJTZIdQbUJdZkGhXkI3tiE,4581 +soupsieve/__meta__.py,sha256=GWNjSuOoU3r23v6D1P38tEs-pavnOjiVpqEyOfDsMBk,6766 +soupsieve/__pycache__/__init__.cpython-312.pyc,, +soupsieve/__pycache__/__meta__.cpython-312.pyc,, +soupsieve/__pycache__/css_match.cpython-312.pyc,, +soupsieve/__pycache__/css_parser.cpython-312.pyc,, +soupsieve/__pycache__/css_types.cpython-312.pyc,, +soupsieve/__pycache__/pretty.cpython-312.pyc,, +soupsieve/__pycache__/util.cpython-312.pyc,, +soupsieve/css_match.py,sha256=UmCH_ltakWVIDyyfKBs619ttpyw9nANbNVdkl3Z65TM,60276 +soupsieve/css_parser.py,sha256=kqwBKDzFgxxHn_prd93D8oTaw00SkRtxdUf7jItTRas,48182 +soupsieve/css_types.py,sha256=OxTs1p2bZK4nvPjJu-TVgPYVrMXnQwQ7RGq0cfzZwC0,10014 +soupsieve/pretty.py,sha256=iSM-NKCzruJQCwEriQT72LrF4slxsib7TB552H2bsqA,4362 +soupsieve/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +soupsieve/util.py,sha256=Q0MVH77cUBXMtKV0D2f8Syf90remPe0EfLqe6-msAeI,3352 diff --git a/.venv/lib/python3.12/site-packages/soupsieve-2.9.2.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/soupsieve-2.9.2.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..7401812e19af977cc5088f3b8fb1ef6bc0441c0a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/soupsieve-2.9.2.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.31.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/.venv/lib/python3.12/site-packages/soupsieve-2.9.2.dist-info/licenses/LICENSE.md b/.venv/lib/python3.12/site-packages/soupsieve-2.9.2.dist-info/licenses/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..128c5342c81d4986cba6d118a41e402d7b676996 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/soupsieve-2.9.2.dist-info/licenses/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 - 2026 Isaac Muse + +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.12/site-packages/soupsieve/__init__.py b/.venv/lib/python3.12/site-packages/soupsieve/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e170c71c5453fd3d19bf25499d8f177c101cb8af --- /dev/null +++ b/.venv/lib/python3.12/site-packages/soupsieve/__init__.py @@ -0,0 +1,168 @@ +""" +Soup Sieve. + +A CSS selector filter for BeautifulSoup4. + +MIT License + +Copyright (c) 2018 Isaac Muse + +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. +""" +from __future__ import annotations +from .__meta__ import __version__, __version_info__ # noqa: F401 +from . import css_parser as cp +from . import css_match as cm +from . import css_types as ct +from .util import DEBUG, SelectorSyntaxError # noqa: F401 +import bs4 +from typing import Any, Iterator, Iterable + +__all__ = ( + 'DEBUG', 'SelectorSyntaxError', 'SoupSieve', + 'closest', 'compile', 'filter', 'iselect', + 'match', 'select', 'select_one' +) + +SoupSieve = cm.SoupSieve + + +def compile( # noqa: A001 + pattern: str, + namespaces: dict[str, str] | None = None, + flags: int = 0, + *, + custom: dict[str, str] | None = None, + **kwargs: Any +) -> cm.SoupSieve: + """Compile CSS pattern.""" + + if isinstance(pattern, SoupSieve): + if flags: + raise ValueError("Cannot process 'flags' argument on a compiled selector list") + elif namespaces is not None: + raise ValueError("Cannot process 'namespaces' argument on a compiled selector list") + elif custom is not None: + raise ValueError("Cannot process 'custom' argument on a compiled selector list") + return pattern + + return cp._cached_css_compile( + pattern, + ct.Namespaces(namespaces) if namespaces is not None else namespaces, + ct.CustomSelectors(custom) if custom is not None else custom, + flags + ) + + +def purge() -> None: + """Purge cached patterns.""" + + cp._purge_cache() + + +def closest( + select: str, + tag: bs4.Tag, + namespaces: dict[str, str] | None = None, + flags: int = 0, + *, + custom: dict[str, str] | None = None, + **kwargs: Any +) -> bs4.Tag | None: + """Match closest ancestor.""" + + return compile(select, namespaces, flags, **kwargs).closest(tag) + + +def match( + select: str, + tag: bs4.Tag, + namespaces: dict[str, str] | None = None, + flags: int = 0, + *, + custom: dict[str, str] | None = None, + **kwargs: Any +) -> bool: + """Match node.""" + + return compile(select, namespaces, flags, **kwargs).match(tag) + + +def filter( # noqa: A001 + select: str, + iterable: Iterable[bs4.Tag], + namespaces: dict[str, str] | None = None, + flags: int = 0, + *, + custom: dict[str, str] | None = None, + **kwargs: Any +) -> list[bs4.Tag]: + """Filter list of nodes.""" + + return compile(select, namespaces, flags, **kwargs).filter(iterable) + + +def select_one( + select: str, + tag: bs4.Tag, + namespaces: dict[str, str] | None = None, + flags: int = 0, + *, + custom: dict[str, str] | None = None, + **kwargs: Any +) -> bs4.Tag | None: + """Select a single tag.""" + + return compile(select, namespaces, flags, **kwargs).select_one(tag) + + +def select( + select: str, + tag: bs4.Tag, + namespaces: dict[str, str] | None = None, + limit: int = 0, + flags: int = 0, + *, + custom: dict[str, str] | None = None, + **kwargs: Any +) -> list[bs4.Tag]: + """Select the specified tags.""" + + return compile(select, namespaces, flags, **kwargs).select(tag, limit) + + +def iselect( + select: str, + tag: bs4.Tag, + namespaces: dict[str, str] | None = None, + limit: int = 0, + flags: int = 0, + *, + custom: dict[str, str] | None = None, + **kwargs: Any +) -> Iterator[bs4.Tag]: + """Iterate the specified tags.""" + + yield from compile(select, namespaces, flags, **kwargs).iselect(tag, limit) + + +def escape(ident: str) -> str: + """Escape identifier.""" + + return cp.escape(ident) diff --git a/.venv/lib/python3.12/site-packages/soupsieve/__meta__.py b/.venv/lib/python3.12/site-packages/soupsieve/__meta__.py new file mode 100644 index 0000000000000000000000000000000000000000..e90cf9bf418aac05985889766c5f922f278922eb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/soupsieve/__meta__.py @@ -0,0 +1,197 @@ +"""Meta related things.""" +from __future__ import annotations +from collections import namedtuple +import re + +RE_VER = re.compile( + r'''(?x) + (?P\d+)(?:\.(?P\d+))?(?:\.(?P\d+))? + (?:(?Pa|b|rc)(?P
\d+))?
+    (?:\.post(?P\d+))?
+    (?:\.dev(?P\d+))?
+    '''
+)
+
+REL_MAP = {
+    ".dev": "",
+    ".dev-alpha": "a",
+    ".dev-beta": "b",
+    ".dev-candidate": "rc",
+    "alpha": "a",
+    "beta": "b",
+    "candidate": "rc",
+    "final": ""
+}
+
+DEV_STATUS = {
+    ".dev": "2 - Pre-Alpha",
+    ".dev-alpha": "2 - Pre-Alpha",
+    ".dev-beta": "2 - Pre-Alpha",
+    ".dev-candidate": "2 - Pre-Alpha",
+    "alpha": "3 - Alpha",
+    "beta": "4 - Beta",
+    "candidate": "4 - Beta",
+    "final": "5 - Production/Stable"
+}
+
+PRE_REL_MAP = {"a": 'alpha', "b": 'beta', "rc": 'candidate'}
+
+
+class Version(namedtuple("Version", ["major", "minor", "micro", "release", "pre", "post", "dev"])):
+    """
+    Get the version (PEP 440).
+
+    A biased approach to the PEP 440 semantic version.
+
+    Provides a tuple structure which is sorted for comparisons `v1 > v2` etc.
+      (major, minor, micro, release type, pre-release build, post-release build, development release build)
+    Release types are named in is such a way they are comparable with ease.
+    Accessors to check if a development, pre-release, or post-release build. Also provides accessor to get
+    development status for setup files.
+
+    How it works (currently):
+
+    - You must specify a release type as either `final`, `alpha`, `beta`, or `candidate`.
+    - To define a development release, you can use either `.dev`, `.dev-alpha`, `.dev-beta`, or `.dev-candidate`.
+      The dot is used to ensure all development specifiers are sorted before `alpha`.
+      You can specify a `dev` number for development builds, but do not have to as implicit development releases
+      are allowed.
+    - You must specify a `pre` value greater than zero if using a prerelease as this project (not PEP 440) does not
+      allow implicit prereleases.
+    - You can optionally set `post` to a value greater than zero to make the build a post release. While post releases
+      are technically allowed in prereleases, it is strongly discouraged, so we are rejecting them. It should be
+      noted that we do not allow `post0` even though PEP 440 does not restrict this. This project specifically
+      does not allow implicit post releases.
+    - It should be noted that we do not support epochs `1!` or local versions `+some-custom.version-1`.
+
+    Acceptable version releases:
+
+    ```
+    Version(1, 0, 0, "final")                    1.0
+    Version(1, 2, 0, "final")                    1.2
+    Version(1, 2, 3, "final")                    1.2.3
+    Version(1, 2, 0, ".dev-alpha", pre=4)        1.2a4
+    Version(1, 2, 0, ".dev-beta", pre=4)         1.2b4
+    Version(1, 2, 0, ".dev-candidate", pre=4)    1.2rc4
+    Version(1, 2, 0, "final", post=1)            1.2.post1
+    Version(1, 2, 3, ".dev")                     1.2.3.dev0
+    Version(1, 2, 3, ".dev", dev=1)              1.2.3.dev1
+    ```
+
+    """
+
+    def __new__(
+        cls,
+        major: int, minor: int, micro: int, release: str = "final",
+        pre: int = 0, post: int = 0, dev: int = 0
+    ) -> Version:
+        """Validate version info."""
+
+        # Ensure all parts are positive integers.
+        for value in (major, minor, micro, pre, post):
+            if not (isinstance(value, int) and value >= 0):
+                raise ValueError("All version parts except 'release' should be integers.")
+
+        if release not in REL_MAP:
+            raise ValueError(f"'{release}' is not a valid release type.")
+
+        # Ensure valid pre-release (we do not allow implicit pre-releases).
+        if ".dev-candidate" < release < "final":
+            if pre == 0:
+                raise ValueError("Implicit pre-releases not allowed.")
+            elif dev:
+                raise ValueError("Version is not a development release.")
+            elif post:
+                raise ValueError("Post-releases are not allowed with pre-releases.")
+
+        # Ensure valid development or development/pre release
+        elif release < "alpha":
+            if release > ".dev" and pre == 0:
+                raise ValueError("Implicit pre-release not allowed.")
+            elif post:
+                raise ValueError("Post-releases are not allowed with pre-releases.")
+
+        # Ensure a valid normal release
+        else:
+            if pre:
+                raise ValueError("Version is not a pre-release.")
+            elif dev:
+                raise ValueError("Version is not a development release.")
+
+        return super().__new__(cls, major, minor, micro, release, pre, post, dev)
+
+    def _is_pre(self) -> bool:
+        """Is prerelease."""
+
+        return bool(self.pre > 0)
+
+    def _is_dev(self) -> bool:
+        """Is development."""
+
+        return bool(self.release < "alpha")
+
+    def _is_post(self) -> bool:
+        """Is post."""
+
+        return bool(self.post > 0)
+
+    def _get_dev_status(self) -> str:  # pragma: no cover
+        """Get development status string."""
+
+        return DEV_STATUS[self.release]
+
+    def _get_canonical(self) -> str:
+        """Get the canonical output string."""
+
+        # Assemble major, minor, micro version and append `pre`, `post`, or `dev` if needed..
+        if self.micro == 0:
+            ver = f"{self.major}.{self.minor}"
+        else:
+            ver = f"{self.major}.{self.minor}.{self.micro}"
+        if self._is_pre():
+            ver += f'{REL_MAP[self.release]}{self.pre}'
+        if self._is_post():
+            ver += f".post{self.post}"
+        if self._is_dev():
+            ver += f".dev{self.dev}"
+
+        return ver
+
+
+def parse_version(ver: str) -> Version:
+    """Parse version into a comparable Version tuple."""
+
+    m = RE_VER.match(ver)
+
+    if m is None:
+        raise ValueError(f"'{ver}' is not a valid version")
+
+    # Handle major, minor, micro
+    major = int(m.group('major'))
+    minor = int(m.group('minor')) if m.group('minor') else 0
+    micro = int(m.group('micro')) if m.group('micro') else 0
+
+    # Handle pre releases
+    if m.group('type'):
+        release = PRE_REL_MAP[m.group('type')]
+        pre = int(m.group('pre'))
+    else:
+        release = "final"
+        pre = 0
+
+    # Handle development releases
+    dev = m.group('dev') if m.group('dev') else 0
+    if m.group('dev'):
+        dev = int(m.group('dev'))
+        release = '.dev-' + release if pre else '.dev'
+    else:
+        dev = 0
+
+    # Handle post
+    post = int(m.group('post')) if m.group('post') else 0
+
+    return Version(major, minor, micro, release, pre, post, dev)
+
+
+__version_info__ = Version(2, 9, 2, "final")
+__version__ = __version_info__._get_canonical()
diff --git a/.venv/lib/python3.12/site-packages/soupsieve/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/soupsieve/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..640f75484aad55ab097f63c8d6b45d9570f039d7
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/soupsieve/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/soupsieve/__pycache__/__meta__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/soupsieve/__pycache__/__meta__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..60ae94cdf95da7431633075313cbb8bc8ee21987
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/soupsieve/__pycache__/__meta__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/soupsieve/__pycache__/css_match.cpython-312.pyc b/.venv/lib/python3.12/site-packages/soupsieve/__pycache__/css_match.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f5e91734fb7dac3bde7ff7e41f0669f1b70f4ee8
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/soupsieve/__pycache__/css_match.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/soupsieve/__pycache__/css_parser.cpython-312.pyc b/.venv/lib/python3.12/site-packages/soupsieve/__pycache__/css_parser.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4c232f680dae37ff57b713cc745d184efd2a049d
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/soupsieve/__pycache__/css_parser.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/soupsieve/__pycache__/css_types.cpython-312.pyc b/.venv/lib/python3.12/site-packages/soupsieve/__pycache__/css_types.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f9b059fe647beb1b1321156d128e3ee8a882f42f
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/soupsieve/__pycache__/css_types.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/soupsieve/__pycache__/pretty.cpython-312.pyc b/.venv/lib/python3.12/site-packages/soupsieve/__pycache__/pretty.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7e7238eee192c2f867cb0d4e616bd228414b9125
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/soupsieve/__pycache__/pretty.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/soupsieve/__pycache__/util.cpython-312.pyc b/.venv/lib/python3.12/site-packages/soupsieve/__pycache__/util.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9bb69de721bd86938733466ab48b7ce994d50a79
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/soupsieve/__pycache__/util.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/soupsieve/css_match.py b/.venv/lib/python3.12/site-packages/soupsieve/css_match.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f4dc1e1189ce3b0f4400802dc99c496553c4eb4
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/soupsieve/css_match.py
@@ -0,0 +1,1628 @@
+"""CSS matcher."""
+from __future__ import annotations
+from datetime import datetime
+from . import util
+import re
+from . import css_types as ct
+import unicodedata
+import bs4
+from typing import Iterator, Iterable, Any, Callable, Sequence, Any, cast  # noqa: F401, F811
+
+# Empty tag pattern (whitespace okay)
+RE_NOT_EMPTY = re.compile('[^ \t\r\n\f]')
+
+RE_NOT_WS = re.compile('[^ \t\r\n\f]+')
+
+# Relationships
+REL_PARENT = ' '
+REL_CLOSE_PARENT = '>'
+REL_SIBLING = '~'
+REL_CLOSE_SIBLING = '+'
+
+# Relationships for :has() (forward looking)
+REL_HAS_PARENT = ': '
+REL_HAS_CLOSE_PARENT = ':>'
+REL_HAS_SIBLING = ':~'
+REL_HAS_CLOSE_SIBLING = ':+'
+
+NS_XHTML = 'http://www.w3.org/1999/xhtml'
+NS_XML = 'http://www.w3.org/XML/1998/namespace'
+
+DIR_FLAGS = ct.SEL_DIR_LTR | ct.SEL_DIR_RTL
+RANGES = ct.SEL_IN_RANGE | ct.SEL_OUT_OF_RANGE
+
+DIR_MAP = {
+    'ltr': ct.SEL_DIR_LTR,
+    'rtl': ct.SEL_DIR_RTL,
+    'auto': 0
+}
+
+RE_NUM = re.compile(r"^(?P-?(?:[0-9]{1,}(\.[0-9]+)?|\.[0-9]+))$")
+RE_TIME = re.compile(r'^(?P[0-9]{2}):(?P[0-9]{2})$')
+RE_MONTH = re.compile(r'^(?P[0-9]{4,})-(?P[0-9]{2})$')
+RE_WEEK = re.compile(r'^(?P[0-9]{4,})-W(?P[0-9]{2})$')
+RE_DATE = re.compile(r'^(?P[0-9]{4,})-(?P[0-9]{2})-(?P[0-9]{2})$')
+RE_DATETIME = re.compile(
+    r'^(?P[0-9]{4,})-(?P[0-9]{2})-(?P[0-9]{2})T(?P[0-9]{2}):(?P[0-9]{2})$'
+)
+RE_WILD_STRIP = re.compile(r'(?:(?:-\*-)(?:\*(?:-|$))*|-\*$)')
+
+MONTHS_30 = (4, 6, 9, 11)  # April, June, September, and November
+FEB = 2
+SHORT_MONTH = 30
+LONG_MONTH = 31
+FEB_MONTH = 28
+FEB_LEAP_MONTH = 29
+DAYS_IN_WEEK = 7
+
+
+class _FakeParent:
+    """
+    Fake parent class.
+
+    When we have a fragment with no `BeautifulSoup` document object,
+    we can't evaluate `nth` selectors properly.  Create a temporary
+    fake parent so we can traverse the root element as a child.
+    """
+
+    def __init__(self, element: bs4.Tag) -> None:
+        """Initialize."""
+
+        self.contents = [element]
+
+    def __len__(self) -> int:
+        """Length."""
+
+        return len(self.contents)
+
+
+class _DocumentNav:
+    """Navigate a Beautiful Soup document."""
+
+    @classmethod
+    def assert_valid_input(cls, tag: Any) -> None:
+        """Check if valid input tag or document."""
+
+        # Fail on unexpected types.
+        if not cls.is_tag(tag):
+            raise TypeError(f"Expected a BeautifulSoup 'Tag', but instead received type {type(tag)}")
+
+    @staticmethod
+    def is_doc(obj: bs4.element.PageElement | None) -> bool:
+        """Is `BeautifulSoup` object."""
+        return isinstance(obj, bs4.BeautifulSoup)
+
+    @staticmethod
+    def is_tag(obj: bs4.element.PageElement | None) -> bool:
+        """Is tag."""
+        return isinstance(obj, bs4.Tag)
+
+    @staticmethod
+    def is_declaration(obj: bs4.element.PageElement | None) -> bool:  # pragma: no cover
+        """Is declaration."""
+        return isinstance(obj, bs4.Declaration)
+
+    @staticmethod
+    def is_cdata(obj: bs4.element.PageElement | None) -> bool:
+        """Is CDATA."""
+        return isinstance(obj, bs4.CData)
+
+    @staticmethod
+    def is_processing_instruction(obj: bs4.element.PageElement | None) -> bool:  # pragma: no cover
+        """Is processing instruction."""
+        return isinstance(obj, bs4.ProcessingInstruction)
+
+    @staticmethod
+    def is_navigable_string(obj: bs4.element.PageElement | None) -> bool:
+        """Is navigable string."""
+        return isinstance(obj, bs4.element.NavigableString)
+
+    @staticmethod
+    def is_special_string(obj: bs4.element.PageElement | None) -> bool:
+        """Is special string."""
+        return isinstance(obj, (bs4.Comment, bs4.Declaration, bs4.CData, bs4.ProcessingInstruction, bs4.Doctype))
+
+    @classmethod
+    def is_content_string(cls, obj: bs4.element.PageElement | None) -> bool:
+        """Check if node is content string."""
+
+        return cls.is_navigable_string(obj) and not cls.is_special_string(obj)
+
+    @staticmethod
+    def create_fake_parent(el: bs4.Tag) -> _FakeParent:
+        """Create fake parent for a given element."""
+
+        return _FakeParent(el)
+
+    @staticmethod
+    def is_xml_tree(el: bs4.Tag | None) -> bool:
+        """Check if element (or document) is from a XML tree."""
+
+        return el is not None and bool(el._is_xml)
+
+    def is_iframe(self, el: bs4.Tag | None) -> bool:
+        """Check if element is an `iframe`."""
+
+        if el is None:  # pragma: no cover
+            return False
+
+        return bool(
+            ((el.name if self.is_xml_tree(el) else util.lower(el.name)) == 'iframe') and
+            self.is_html_tag(el)  # type: ignore[attr-defined]
+        )
+
+    def is_root(self, el: bs4.Tag) -> bool:
+        """
+        Return whether element is a root element.
+
+        We check that the element is the root of the tree (which we have already pre-calculated),
+        and we check if it is the root element under an `iframe`.
+        """
+
+        root = self.root and self.root is el  # type: ignore[attr-defined]
+        if not root:
+            parent = self.get_parent(el)
+            root = parent is not None and self.is_html and self.is_iframe(parent)  # type: ignore[attr-defined]
+        return root
+
+    def get_contents(self, el: bs4.Tag | None, no_iframe: bool = False) -> Iterator[bs4.element.PageElement]:
+        """Get contents or contents in reverse."""
+
+        if el is not None:
+            if not no_iframe or not self.is_iframe(el):
+                yield from el.contents
+
+    def get_tag_children(
+        self,
+        el: bs4.Tag | None,
+        start: int | None = None,
+        reverse: bool = False,
+        no_iframe: bool = False
+    ) -> Iterator[bs4.Tag]:
+        """Get tag children."""
+
+        return self.get_children(el, start, reverse, True, no_iframe)  # type: ignore[return-value]
+
+    def get_children(
+        self,
+        el: bs4.Tag | None,
+        start: int | None = None,
+        reverse: bool = False,
+        tags: bool = False,
+        no_iframe: bool = False
+    ) -> Iterator[bs4.element.PageElement]:
+        """Get children."""
+
+        if el is not None and (not no_iframe or not self.is_iframe(el)):
+            last = len(el.contents) - 1
+            if start is None:
+                index = last if reverse else 0
+            else:
+                index = start
+            end = -1 if reverse else last + 1
+            incr = -1 if reverse else 1
+
+            if 0 <= index <= last:
+                while index != end:
+                    node = el.contents[index]
+                    index += incr
+                    if not tags or self.is_tag(node):
+                        yield node
+
+    def get_tag_descendants(
+        self,
+        el: bs4.Tag | None,
+        no_iframe: bool = False
+    ) -> Iterator[bs4.Tag]:
+        """Specifically get tag descendants."""
+
+        yield from self.get_descendants(el, tags=True, no_iframe=no_iframe)  # type: ignore[misc]
+
+    def get_descendants(
+        self,
+        el: bs4.Tag | None,
+        tags: bool = False,
+        no_iframe: bool = False
+    ) -> Iterator[bs4.element.PageElement]:
+        """Get descendants."""
+
+        if el is not None and (not no_iframe or not self.is_iframe(el)):
+            next_good = None
+            for child in el.descendants:
+
+                if next_good is not None:
+                    if child is not next_good:
+                        continue
+                    next_good = None
+
+                if isinstance(child, bs4.Tag):
+                    if no_iframe and self.is_iframe(child):
+                        if child.next_sibling is not None:
+                            next_good = child.next_sibling
+                        else:
+                            last_child = child  # type: bs4.element.PageElement
+                            while isinstance(last_child, bs4.Tag) and last_child.contents:
+                                last_child = last_child.contents[-1]
+                            next_good = last_child.next_element
+                        yield child
+                        if next_good is None:
+                            break
+                        # Coverage isn't seeing this even though it's executed
+                        continue  # pragma: no cover
+                    yield child
+
+                elif not tags:
+                    yield child
+
+    def get_parent(self, el: bs4.Tag | None, no_iframe: bool = False) -> bs4.Tag | None:
+        """Get parent."""
+
+        parent = el.parent if el is not None else None
+        if no_iframe and parent is not None and self.is_iframe(parent):  # pragma: no cover
+            parent = None
+        return parent
+
+    @staticmethod
+    def get_tag_name(el: bs4.Tag | None) -> str | None:
+        """Get tag."""
+
+        return el.name if el is not None else None
+
+    @staticmethod
+    def get_prefix_name(el: bs4.Tag) -> str | None:
+        """Get prefix."""
+
+        return el.prefix
+
+    @staticmethod
+    def get_uri(el: bs4.Tag | None) -> str | None:
+        """Get namespace `URI`."""
+
+        return el.namespace if el is not None else None
+
+    @classmethod
+    def get_next_tag(cls, el: bs4.Tag) -> bs4.Tag | None:
+        """Get next sibling tag."""
+
+        return cls.get_next(el, tags=True)  # type: ignore[return-value]
+
+    @classmethod
+    def get_next(cls, el: bs4.Tag, tags: bool = False) -> bs4.element.PageElement | None:
+        """Get next sibling tag."""
+
+        sibling = el.next_sibling
+        while tags and not isinstance(sibling, bs4.Tag) and sibling is not None:
+            sibling = sibling.next_sibling
+
+        if tags and not isinstance(sibling, bs4.Tag):
+            sibling = None
+
+        return sibling
+
+    @classmethod
+    def get_previous_tag(cls, el: bs4.Tag, tags: bool = True) -> bs4.Tag | None:
+        """Get previous sibling tag."""
+
+        return cls.get_previous(el, True)  # type: ignore[return-value]
+
+    @classmethod
+    def get_previous(cls, el: bs4.Tag, tags: bool = False) -> bs4.element.PageElement | None:
+        """Get previous sibling tag."""
+
+        sibling = el.previous_sibling
+        while tags and not isinstance(sibling, bs4.Tag) and sibling is not None:
+            sibling = sibling.previous_sibling
+
+        if tags and not isinstance(sibling, bs4.Tag):
+            sibling = None
+
+        return sibling
+
+    @staticmethod
+    def has_html_ns(el: bs4.Tag | None) -> bool:
+        """
+        Check if element has an HTML namespace.
+
+        This is a bit different than whether a element is treated as having an HTML namespace,
+        like we do in the case of `is_html_tag`.
+        """
+
+        ns = getattr(el, 'namespace') if el is not None else None  # noqa: B009
+        return bool(ns and ns == NS_XHTML)
+
+    @staticmethod
+    def split_namespace(el: bs4.Tag | None, attr_name: str) -> tuple[str | None, str | None]:
+        """Return namespace and attribute name without the prefix."""
+
+        if el is None:  # pragma: no cover
+            return None, None
+
+        return getattr(attr_name, 'namespace', None), getattr(attr_name, 'name', None)
+
+    @classmethod
+    def normalize_value(cls, value: Any) -> str | Sequence[str]:
+        """Normalize the value to be a string or list of strings."""
+
+        # Treat `None` as empty string.
+        if value is None:
+            return ''
+
+        # Pass through strings
+        if (isinstance(value, str)):
+            return value
+
+        # If it's a byte string, convert it to Unicode, treating it as UTF-8.
+        if isinstance(value, bytes):
+            return value.decode("utf8")
+
+        # BeautifulSoup supports sequences of attribute values, so make sure the children are strings.
+        if isinstance(value, Sequence):
+            new_value = []
+            for v in value:
+                if not isinstance(v, (str, bytes)) and isinstance(v, Sequence):
+                    # This is most certainly a user error and will crash and burn later.
+                    # To keep things working, we'll do what we do with all objects,
+                    # And convert them to strings.
+                    new_value.append(str(v))
+                else:
+                    # Convert the child to a string
+                    new_value.append(cast(str, cls.normalize_value(v)))
+            return new_value
+
+        # Try and make anything else a string
+        return str(value)
+
+    @classmethod
+    def get_attribute_by_name(
+        cls,
+        el: bs4.Tag,
+        name: str,
+        default: str | Sequence[str] | None = None
+    ) -> str | Sequence[str] | None:
+        """Get attribute by name."""
+
+        value = default
+        if el._is_xml:
+            try:
+                value = cls.normalize_value(el.attrs[name])
+            except KeyError:
+                pass
+        else:
+            for k, v in el.attrs.items():
+                if util.lower(k) == name:
+                    value = cls.normalize_value(v)
+                    break
+        return value
+
+    @classmethod
+    def iter_attributes(cls, el: bs4.Tag | None) -> Iterator[tuple[str, str | Sequence[str] | None]]:
+        """Iterate attributes."""
+
+        if el is not None:
+            for k, v in el.attrs.items():
+                yield k, cls.normalize_value(v)
+
+    @classmethod
+    def get_classes(cls, el: bs4.Tag) -> Sequence[str]:
+        """Get classes."""
+
+        classes = cls.get_attribute_by_name(el, 'class', [])
+        if isinstance(classes, str):
+            classes = RE_NOT_WS.findall(classes)
+        return cast(Sequence[str], classes)
+
+    def get_text(self, el: bs4.Tag, no_iframe: bool = False) -> str:
+        """Get text."""
+
+        return ''.join(
+            [
+                node for node in self.get_descendants(el, no_iframe=no_iframe)  # type: ignore[misc]
+                if self.is_content_string(node)
+            ]
+        )
+
+    def get_own_text(self, el: bs4.Tag, no_iframe: bool = False) -> list[str]:
+        """Get Own Text."""
+
+        return [
+            node for node in self.get_contents(el, no_iframe=no_iframe) if self.is_content_string(node)  # type: ignore[misc]
+        ]
+
+
+class Inputs:
+    """Class for parsing and validating input items."""
+
+    @staticmethod
+    def validate_day(year: int, month: int, day: int) -> bool:
+        """Validate day."""
+
+        max_days = LONG_MONTH
+        if month == FEB:
+            max_days = FEB_LEAP_MONTH if ((year % 4 == 0) and (year % 100 != 0)) or (year % 400 == 0) else FEB_MONTH
+        elif month in MONTHS_30:
+            max_days = SHORT_MONTH
+        return 1 <= day <= max_days
+
+    @staticmethod
+    def validate_week(year: int, week: int) -> bool:
+        """Validate week."""
+
+        # Validate an ISO week number for `year`.
+        #
+        # Per ISO 8601 rules, the last ISO week of a year is the week
+        # containing Dec 28. Using Dec 28 guarantees we obtain the
+        # correct ISO week-number for the final week of `year`, even in
+        # years where Dec 31 falls in ISO week 01 of the following year.
+        #
+        # Example: if Dec 31 is a Thursday the year's last ISO week will
+        # be week 53; if Dec 31 is a Monday and that week is counted as
+        # week 1 of the next year, Dec 28 still belongs to the final
+        # week of the current ISO year and yields the correct max week.
+        max_week = datetime(year, 12, 28).isocalendar()[1]
+        return 1 <= week <= max_week
+
+    @staticmethod
+    def validate_month(month: int) -> bool:
+        """Validate month."""
+
+        return 1 <= month <= 12
+
+    @staticmethod
+    def validate_year(year: int) -> bool:
+        """Validate year."""
+
+        return 1 <= year
+
+    @staticmethod
+    def validate_hour(hour: int) -> bool:
+        """Validate hour."""
+
+        return 0 <= hour <= 23
+
+    @staticmethod
+    def validate_minutes(minutes: int) -> bool:
+        """Validate minutes."""
+
+        return 0 <= minutes <= 59
+
+    @classmethod
+    def parse_value(cls, itype: str, value: str | None) -> tuple[float, ...] | None:
+        """Parse the input value."""
+
+        parsed = None  # type: tuple[float, ...] | None
+        if value is None:
+            return value
+        if itype == "date":
+            m = RE_DATE.match(value)
+            if m:
+                year = int(m.group('year'), 10)
+                month = int(m.group('month'), 10)
+                day = int(m.group('day'), 10)
+                if cls.validate_year(year) and cls.validate_month(month) and cls.validate_day(year, month, day):
+                    parsed = (year, month, day)
+        elif itype == "month":
+            m = RE_MONTH.match(value)
+            if m:
+                year = int(m.group('year'), 10)
+                month = int(m.group('month'), 10)
+                if cls.validate_year(year) and cls.validate_month(month):
+                    parsed = (year, month)
+        elif itype == "week":
+            m = RE_WEEK.match(value)
+            if m:
+                year = int(m.group('year'), 10)
+                week = int(m.group('week'), 10)
+                if cls.validate_year(year) and cls.validate_week(year, week):
+                    parsed = (year, week)
+        elif itype == "time":
+            m = RE_TIME.match(value)
+            if m:
+                hour = int(m.group('hour'), 10)
+                minutes = int(m.group('minutes'), 10)
+                if cls.validate_hour(hour) and cls.validate_minutes(minutes):
+                    parsed = (hour, minutes)
+        elif itype == "datetime-local":
+            m = RE_DATETIME.match(value)
+            if m:
+                year = int(m.group('year'), 10)
+                month = int(m.group('month'), 10)
+                day = int(m.group('day'), 10)
+                hour = int(m.group('hour'), 10)
+                minutes = int(m.group('minutes'), 10)
+                if (
+                    cls.validate_year(year) and cls.validate_month(month) and cls.validate_day(year, month, day) and
+                    cls.validate_hour(hour) and cls.validate_minutes(minutes)
+                ):
+                    parsed = (year, month, day, hour, minutes)
+        elif itype in ("number", "range"):
+            m = RE_NUM.match(value)
+            if m:
+                parsed = (float(m.group('value')),)
+        return parsed
+
+
+class CSSMatch(_DocumentNav):
+    """Perform CSS matching."""
+
+    def __init__(
+        self,
+        selectors: ct.SelectorList,
+        scope: bs4.Tag | None,
+        namespaces: ct.Namespaces | None,
+        flags: int
+    ) -> None:
+        """Initialize."""
+
+        self.assert_valid_input(scope)
+        self.tag = scope
+        self.cached_meta_lang = []  # type: list[tuple[str, str]]
+        self.cached_default_forms = []  # type: list[tuple[bs4.Tag, bs4.Tag]]
+        self.cached_indeterminate_forms = []  # type: list[tuple[bs4.Tag, str, bool]]
+        self.selectors = selectors
+        self.namespaces = {} if namespaces is None else namespaces  # type: ct.Namespaces | dict[str, str]
+        self.flags = flags
+        self.iframe_restrict = False
+
+        # Find the root element for the whole tree
+        doc = scope
+        parent = self.get_parent(doc)
+        while parent:
+            doc = parent
+            parent = self.get_parent(doc)
+        root = None  # type: bs4.Tag | None
+        if not self.is_doc(doc):
+            root = doc
+        else:
+            for child in self.get_tag_children(doc):
+                root = child
+                break
+
+        self.root = root
+        self.scope = scope if scope is not doc else root
+        self.has_html_namespace = self.has_html_ns(root)
+
+        # A document can be both XML and HTML (XHTML)
+        self.is_xml = self.is_xml_tree(doc)
+        self.is_html = not self.is_xml or self.has_html_namespace
+
+    def supports_namespaces(self) -> bool:
+        """Check if namespaces are supported in the HTML type."""
+
+        return self.is_xml or self.has_html_namespace
+
+    def get_tag_ns(self, el: bs4.Tag | None) -> str:
+        """Get tag namespace."""
+
+        namespace = ''
+        if el is None:  # pragma: no cover
+            return namespace
+
+        if self.supports_namespaces():
+            ns = self.get_uri(el)
+            if ns:
+                namespace = ns
+        else:
+            namespace = NS_XHTML
+        return namespace
+
+    def is_html_tag(self, el: bs4.Tag | None) -> bool:
+        """Check if tag is in HTML namespace."""
+
+        return self.get_tag_ns(el) == NS_XHTML
+
+    def get_tag(self, el: bs4.Tag | None) -> str | None:
+        """Get tag."""
+
+        name = self.get_tag_name(el)
+        return util.lower(name) if name is not None and not self.is_xml else name
+
+    def get_prefix(self, el: bs4.Tag) -> str | None:
+        """Get prefix."""
+
+        prefix = self.get_prefix_name(el)
+        return util.lower(prefix) if prefix is not None and not self.is_xml else prefix
+
+    def find_bidi(self, el: bs4.Tag) -> int | None:
+        """Get directionality from element text."""
+
+        for node in self.get_children(el):
+
+            # Analyze child text nodes
+            if self.is_tag(node):
+
+                # Avoid analyzing certain elements specified in the specification.
+                direction = DIR_MAP.get(util.lower(self.get_attribute_by_name(node, 'dir', '')), None)  # type: ignore[arg-type]
+                name = self.get_tag(node)  # type: ignore[arg-type]
+                if (
+                    (name and name in ('bdi', 'script', 'style', 'textarea', 'iframe')) or
+                    not self.is_html_tag(node) or  # type: ignore[arg-type]
+                    direction is not None
+                ):
+                    continue  # pragma: no cover
+
+                # Check directionality of this node's text
+                value = self.find_bidi(node)  # type: ignore[arg-type]
+                if value is not None:
+                    return value
+
+                # Direction could not be determined
+                continue  # pragma: no cover
+
+            # Skip `doctype` comments, etc.
+            if self.is_special_string(node):
+                continue
+
+            # Analyze text nodes for directionality.
+            for c in node:  # type: ignore[attr-defined]
+                bidi = unicodedata.bidirectional(c)
+                if bidi in ('AL', 'R', 'L'):
+                    return ct.SEL_DIR_LTR if bidi == 'L' else ct.SEL_DIR_RTL
+        return None
+
+    def extended_language_filter(self, lang_range: str, lang_tag: str) -> bool:
+        """Filter the language tags."""
+
+        match = True
+        lang_range = RE_WILD_STRIP.sub('-', lang_range).lower()
+        ranges = lang_range.split('-')
+        subtags = lang_tag.lower().split('-')
+        length = len(ranges)
+        slength = len(subtags)
+        rindex = 0
+        sindex = 0
+        r = ranges[rindex]
+        s = subtags[sindex]
+
+        # Empty specified language should match unspecified language attributes
+        if length == 1 and slength == 1 and not r and r == s:
+            return True
+
+        # Primary tag needs to match
+        if (r != '*' and r != s) or (r == '*' and slength == 1 and not s):
+            match = False
+
+        rindex += 1
+        sindex += 1
+
+        # Match until we run out of ranges
+        while match and rindex < length:
+            r = ranges[rindex]
+            try:
+                s = subtags[sindex]
+            except IndexError:
+                # Ran out of subtags,
+                # but we still have ranges
+                match = False
+                continue
+
+            # Empty range
+            if not r:
+                match = False
+                continue
+
+            # Matched range
+            elif s == r:
+                rindex += 1
+
+            # Implicit wildcard cannot match
+            # singletons
+            elif len(s) == 1:
+                match = False
+                continue
+
+            # Implicitly matched, so grab next subtag
+            sindex += 1
+
+        return match
+
+    def match_attribute_name(
+        self,
+        el: bs4.Tag,
+        attr: str,
+        prefix: str | None
+    ) -> str | Sequence[str] | None:
+        """Match attribute name and return value if it exists."""
+
+        value = None
+        if self.supports_namespaces():
+            value = None
+            # If we have not defined namespaces, we can't very well find them, so don't bother trying.
+            if prefix:
+                ns = self.namespaces.get(prefix)
+                if ns is None and prefix != '*':
+                    return None
+            else:
+                ns = None
+
+            for k, v in self.iter_attributes(el):
+
+                # Get attribute parts
+                namespace, name = self.split_namespace(el, k)
+
+                # Can't match a prefix attribute as we haven't specified one to match
+                # Try to match it normally as a whole `p:a` as selector may be trying `p\:a`.
+                if ns is None:
+                    if (self.is_xml and attr == k) or (not self.is_xml and util.lower(attr) == util.lower(k)):
+                        value = v
+                        break
+                    # Coverage is not finding this even though it is executed.
+                    # Adding a print statement before this (and erasing coverage) causes coverage to find the line.
+                    # Ignore the false positive message.
+                    continue  # pragma: no cover
+
+                # We can't match our desired prefix attribute as the attribute doesn't have a prefix
+                if namespace is None or (ns != namespace and prefix != '*'):
+                    continue
+
+                # The attribute doesn't match.
+                if (util.lower(attr) != util.lower(name)) if not self.is_xml else (attr != name):
+                    continue
+
+                value = v
+                break
+        else:
+            for k, v in self.iter_attributes(el):
+                if util.lower(attr) != util.lower(k):
+                    continue
+                value = v
+                break
+        return value
+
+    def match_namespace(self, el: bs4.Tag, tag: ct.SelectorTag) -> bool:
+        """Match the namespace of the element."""
+
+        match = True
+        namespace = self.get_tag_ns(el)
+        default_namespace = self.namespaces.get('')
+        tag_ns = '' if tag.prefix is None else self.namespaces.get(tag.prefix)
+        # We must match the default namespace if one is not provided
+        if tag.prefix is None and (default_namespace is not None and namespace != default_namespace):
+            match = False
+        # If we specified `|tag`, we must not have a namespace.
+        elif (tag.prefix is not None and tag.prefix == '' and namespace):
+            match = False
+        # Verify prefix matches
+        elif (
+            tag.prefix and
+            tag.prefix != '*' and (tag_ns is None or namespace != tag_ns)
+        ):
+            match = False
+        return match
+
+    def match_attributes(self, el: bs4.Tag, attributes: tuple[ct.SelectorAttribute, ...]) -> bool:
+        """Match attributes."""
+
+        match = True
+        if attributes:
+            for a in attributes:
+                temp = self.match_attribute_name(el, a.attribute, a.prefix)
+                pattern = a.xml_type_pattern if self.is_xml and a.xml_type_pattern else a.pattern
+                if temp is None:
+                    match = False
+                    break
+                value = temp if isinstance(temp, str) else ' '.join(temp)
+                if pattern is None:
+                    continue
+                elif pattern.match(value) is None:
+                    match = False
+                    break
+        return match
+
+    def match_tagname(self, el: bs4.Tag, tag: ct.SelectorTag) -> bool:
+        """Match tag name."""
+
+        name = (util.lower(tag.name) if not self.is_xml and tag.name is not None else tag.name)
+        return not (
+            name is not None and
+            name not in (self.get_tag(el), '*')
+        )
+
+    def match_tag(self, el: bs4.Tag, tag: ct.SelectorTag | None) -> bool:
+        """Match the tag."""
+
+        match = True
+        if tag is not None:
+            # Verify namespace
+            if not self.match_namespace(el, tag):
+                match = False
+            if not self.match_tagname(el, tag):
+                match = False
+        return match
+
+    def match_past_relations(self, el: bs4.Tag, relation: ct.SelectorList) -> bool:
+        """Match past relationship."""
+
+        found = False
+        # I don't think this can ever happen, but it makes `mypy` happy
+        if isinstance(relation[0], ct.SelectorNull):  # pragma: no cover
+            return found
+
+        if relation[0].rel_type == REL_PARENT:
+            parent = self.get_parent(el, no_iframe=self.iframe_restrict)
+            while not found and parent:
+                found = self.match_selectors(parent, relation)
+                parent = self.get_parent(parent, no_iframe=self.iframe_restrict)
+        elif relation[0].rel_type == REL_CLOSE_PARENT:
+            parent = self.get_parent(el, no_iframe=self.iframe_restrict)
+            if parent:
+                found = self.match_selectors(parent, relation)
+        elif relation[0].rel_type == REL_SIBLING:
+            sibling = self.get_previous_tag(el)
+            while not found and sibling:
+                found = self.match_selectors(sibling, relation)
+                sibling = self.get_previous_tag(sibling)
+        elif relation[0].rel_type == REL_CLOSE_SIBLING:
+            sibling = self.get_previous_tag(el)
+            if sibling and self.is_tag(sibling):
+                found = self.match_selectors(sibling, relation)
+        return found
+
+    def match_future_child(self, parent: bs4.Tag, relation: ct.SelectorList, recursive: bool = False) -> bool:
+        """Match future child."""
+
+        match = False
+        if recursive:
+            children = self.get_tag_descendants  # type: Callable[..., Iterator[bs4.Tag]]
+        else:
+            children = self.get_tag_children
+        for child in children(parent, no_iframe=self.iframe_restrict):
+            match = self.match_selectors(child, relation)
+            if match:
+                break
+        return match
+
+    def match_future_relations(self, el: bs4.Tag, relation: ct.SelectorList) -> bool:
+        """Match future relationship."""
+
+        found = False
+        # I don't think this can ever happen, but it makes `mypy` happy
+        if isinstance(relation[0], ct.SelectorNull):  # pragma: no cover
+            return found
+
+        if relation[0].rel_type == REL_HAS_PARENT:
+            found = self.match_future_child(el, relation, True)
+        elif relation[0].rel_type == REL_HAS_CLOSE_PARENT:
+            found = self.match_future_child(el, relation)
+        elif relation[0].rel_type == REL_HAS_SIBLING:
+            sibling = self.get_next_tag(el)
+            while not found and sibling:
+                found = self.match_selectors(sibling, relation)
+                sibling = self.get_next_tag(sibling)
+        elif relation[0].rel_type == REL_HAS_CLOSE_SIBLING:
+            sibling = self.get_next_tag(el)
+            if sibling and self.is_tag(sibling):
+                found = self.match_selectors(sibling, relation)
+        return found
+
+    def match_relations(self, el: bs4.Tag, relation: ct.SelectorList) -> bool:
+        """Match relationship to other elements."""
+
+        found = False
+
+        if isinstance(relation[0], ct.SelectorNull) or relation[0].rel_type is None:
+            return found
+
+        if relation[0].rel_type.startswith(':'):
+            found = self.match_future_relations(el, relation)
+        else:
+            found = self.match_past_relations(el, relation)
+
+        return found
+
+    def match_id(self, el: bs4.Tag, ids: tuple[str, ...]) -> bool:
+        """Match element's ID."""
+
+        found = True
+        for i in ids:
+            if i != self.get_attribute_by_name(el, 'id', ''):
+                found = False
+                break
+        return found
+
+    def match_classes(self, el: bs4.Tag, classes: tuple[str, ...]) -> bool:
+        """Match element's classes."""
+
+        current_classes = self.get_classes(el)
+        found = True
+        for c in classes:
+            if c not in current_classes:
+                found = False
+                break
+        return found
+
+    def match_root(self, el: bs4.Tag) -> bool:
+        """Match element as root."""
+
+        is_root = self.is_root(el)
+        if is_root:
+            sibling = self.get_previous(el)  # type: Any
+            while is_root and sibling is not None:
+                if (
+                    self.is_tag(sibling) or (self.is_content_string(sibling) and sibling.strip()) or
+                    self.is_cdata(sibling)
+                ):
+                    is_root = False
+                else:
+                    sibling = self.get_previous(sibling)
+        if is_root:
+            sibling = self.get_next(el)
+            while is_root and sibling is not None:
+                if (
+                    self.is_tag(sibling) or (self.is_content_string(sibling) and sibling.strip()) or
+                    self.is_cdata(sibling)
+                ):
+                    is_root = False
+                else:
+                    sibling = self.get_next(sibling)
+        return is_root
+
+    def match_scope(self, el: bs4.Tag) -> bool:
+        """Match element as scope."""
+
+        return self.scope is el
+
+    def match_nth_tag_type(self, el: bs4.Tag, child: bs4.Tag) -> bool:
+        """Match tag type for `nth` matches."""
+
+        return (
+            (self.get_tag(child) == self.get_tag(el)) and
+            (self.get_tag_ns(child) == self.get_tag_ns(el))
+        )
+
+    def match_nth(self, el: bs4.Tag, nth: tuple[ct.SelectorNth, ...]) -> bool:
+        """Match `nth` elements."""
+
+        matched = True
+
+        for n in nth:
+            matched = False
+            if n.selectors and not self.match_selectors(el, n.selectors):
+                break
+            parent = self.get_parent(el)  # type: bs4.Tag | None
+            if parent is None:
+                parent = cast('bs4.Tag', self.create_fake_parent(el))
+            last = n.last
+            last_index = len(parent) - 1
+            index = last_index if last else 0
+            relative_index = 0
+            a = n.a
+            b = n.b
+            var = n.n
+            count = 0
+            count_incr = 1
+            factor = -1 if last else 1
+            idx = last_idx = a * count + b if var else a
+
+            # We can only adjust bounds within a variable index
+            if var:
+                # Find the count `n` that yields the smallest in-bounds index
+                # (>= 1), then set the increment direction so that the index
+                # ascends from there as the evaluation loop below walks children.
+                if a > 0:
+                    # Ascending sequence: smallest n with a * n + b >= 1.
+                    count = 0 if b >= 1 else -(-(1 - b) // a)
+                elif a < 0:
+                    # Descending sequence: largest n with a * n + b >= 1, then
+                    # walk n back down so the index increases.
+                    count = (b - 1) // -a if b >= 1 else 0
+                    count_incr = -1
+                idx = last_idx = a * count + b
+
+            # Evaluate elements while our calculated nth index is still in range
+            while 1 <= idx <= last_index + 1:
+                child = None  # type: bs4.element.PageElement | None
+                # Evaluate while our child index is still in range.
+                for child in self.get_children(parent, start=index, reverse=factor < 0):
+                    index += factor
+                    if not isinstance(child, bs4.Tag):
+                        continue
+                    # Handle `of S` in `nth-child`
+                    if n.selectors and not self.match_selectors(child, n.selectors):
+                        continue
+                    # Handle `of-type`
+                    if n.of_type and not self.match_nth_tag_type(el, child):
+                        continue
+                    relative_index += 1
+                    if relative_index == idx:
+                        if child is el:
+                            matched = True
+                        else:
+                            break
+                    if child is el:
+                        break
+                if child is el:
+                    break
+                last_idx = idx
+                count += count_incr
+                if count < 0:
+                    # Count is counting down and has now ventured into invalid territory.
+                    break
+                idx = a * count + b if var else a
+                if last_idx == idx:
+                    break
+            if not matched:
+                break
+        return matched
+
+    def match_empty(self, el: bs4.Tag) -> bool:
+        """Check if element is empty (if requested)."""
+
+        is_empty = True
+        for child in self.get_children(el):
+            if self.is_tag(child):
+                is_empty = False
+                break
+            elif self.is_content_string(child) and RE_NOT_EMPTY.search(child):  # type: ignore[call-overload]
+                is_empty = False
+                break
+        return is_empty
+
+    def match_subselectors(self, el: bs4.Tag, selectors: tuple[ct.SelectorList, ...]) -> bool:
+        """Match selectors."""
+
+        match = True
+        for sel in selectors:
+            if not self.match_selectors(el, sel):
+                match = False
+        return match
+
+    def match_contains(self, el: bs4.Tag, contains: tuple[ct.SelectorContains, ...]) -> bool:
+        """Match element if it contains text."""
+
+        match = True
+        content = None  # type: str | Sequence[str] | None
+        for contain_list in contains:
+            if content is None:
+                if contain_list.own:
+                    content = self.get_own_text(el, no_iframe=self.is_html)
+                else:
+                    content = self.get_text(el, no_iframe=self.is_html)
+            found = False
+            for text in contain_list.text:
+                if contain_list.own:
+                    for c in content:
+                        if text in c:
+                            found = True
+                            break
+                    if found:
+                        break
+                else:
+                    if text in content:
+                        found = True
+                        break
+            if not found:
+                match = False
+        return match
+
+    def match_default(self, el: bs4.Tag) -> bool:
+        """Match default."""
+
+        match = False
+
+        # Find this input's form
+        form = None  # type: bs4.Tag | None
+        parent = self.get_parent(el, no_iframe=True)
+        while parent and form is None:
+            if self.get_tag(parent) == 'form' and self.is_html_tag(parent):
+                form = parent
+            else:
+                parent = self.get_parent(parent, no_iframe=True)
+
+        if form is not None:
+            # Look in form cache to see if we've already located its default button
+            found_form = False
+            for f, t in self.cached_default_forms:
+                if f is form:
+                    found_form = True
+                    if t is el:
+                        match = True
+                    break
+
+            # We didn't have the form cached, so look for its default button
+            if not found_form:
+                for child in self.get_tag_descendants(form, no_iframe=True):
+                    name = self.get_tag(child)
+                    # Can't do nested forms (haven't figured out why we never hit this)
+                    if name == 'form':  # pragma: no cover
+                        break
+                    if name in ('input', 'button'):
+                        v = self.get_attribute_by_name(child, 'type', '')
+                        if v and util.lower(v) == 'submit':
+                            self.cached_default_forms.append((form, child))
+                            if el is child:
+                                match = True
+                            break
+        return match
+
+    def match_indeterminate(self, el: bs4.Tag) -> bool:
+        """Match default."""
+
+        match = False
+        name = cast(str, self.get_attribute_by_name(el, 'name'))
+
+        def get_parent_form(el: bs4.Tag) -> bs4.Tag | None:
+            """Find this input's form."""
+            form = None
+            parent = self.get_parent(el, no_iframe=True)
+            while form is None:
+                if self.get_tag(parent) == 'form' and self.is_html_tag(parent):
+                    form = parent
+                    break
+                last_parent = parent
+                parent = self.get_parent(parent, no_iframe=True)
+                if parent is None:
+                    form = last_parent
+                    break
+            return form
+
+        form = get_parent_form(el)
+
+        # Look in form cache to see if we've already evaluated that its fellow radio buttons are indeterminate
+        if form is not None:
+            found_form = False
+            for f, n, i in self.cached_indeterminate_forms:
+                if f is form and n == name:
+                    found_form = True
+                    if i is True:
+                        match = True
+                    break
+
+            # We didn't have the form cached, so validate that the radio button is indeterminate
+            if not found_form:
+                checked = False
+                for child in self.get_tag_descendants(form, no_iframe=True):
+                    if child is el:
+                        continue
+                    tag_name = self.get_tag(child)
+                    if tag_name == 'input':
+                        is_radio = False
+                        check = False
+                        has_name = False
+                        for k, v in self.iter_attributes(child):
+                            if util.lower(k) == 'type' and util.lower(v) == 'radio':
+                                is_radio = True
+                            elif util.lower(k) == 'name' and v == name:
+                                has_name = True
+                            elif util.lower(k) == 'checked':
+                                check = True
+                            if is_radio and check and has_name and get_parent_form(child) is form:
+                                checked = True
+                                break
+                    if checked:
+                        break
+                if not checked:
+                    match = True
+                self.cached_indeterminate_forms.append((form, name, match))
+
+        return match
+
+    def match_lang(self, el: bs4.Tag, langs: tuple[ct.SelectorLang, ...]) -> bool:
+        """Match languages."""
+
+        match = False
+        has_ns = self.supports_namespaces()
+        root = self.root
+        has_html_namespace = self.has_html_namespace
+
+        # Walk parents looking for `lang` (HTML) or `xml:lang` XML property.
+        parent = el  # type: bs4.Tag | None
+        found_lang = None
+        last = None
+        while not found_lang:
+            has_html_ns = self.has_html_ns(parent)
+            for k, v in self.iter_attributes(parent):
+                attr_ns, attr = self.split_namespace(parent, k)
+                if (
+                    ((not has_ns or has_html_ns) and (util.lower(k) if not self.is_xml else k) == 'lang') or
+                    (
+                        has_ns and not has_html_ns and attr_ns == NS_XML and
+                        (util.lower(attr) if not self.is_xml and attr is not None else attr) == 'lang'
+                    )
+                ):
+                    found_lang = v
+                    break
+            last = parent
+            parent = self.get_parent(parent, no_iframe=self.is_html)
+
+            if parent is None:
+                root = last
+                has_html_namespace = self.has_html_ns(root)
+                parent = last
+                break
+
+        # Use cached meta language.
+        if found_lang is None and self.cached_meta_lang:
+            for cache in self.cached_meta_lang:
+                if root is not None and cast(str, root) is cache[0]:
+                    found_lang = cache[1]
+
+        # If we couldn't find a language, and the document is HTML, look to meta to determine language.
+        if found_lang is None and (not self.is_xml or (has_html_namespace and root and root.name == 'html')):
+            # Find head
+            found = False
+            for tag in ('html', 'head'):
+                found = False
+                for child in self.get_tag_children(parent, no_iframe=self.is_html):
+                    if self.get_tag(child) == tag and self.is_html_tag(child):
+                        found = True
+                        parent = child
+                        break
+                if not found:  # pragma: no cover
+                    break
+
+            # Search meta tags
+            if found and parent is not None:
+                for child2 in parent:
+                    if isinstance(child2, bs4.Tag) and self.get_tag(child2) == 'meta' and self.is_html_tag(parent):
+                        c_lang = False
+                        content = None
+                        for k, v in self.iter_attributes(child2):
+                            if util.lower(k) == 'http-equiv' and util.lower(v) == 'content-language':
+                                c_lang = True
+                            if util.lower(k) == 'content':
+                                content = v
+                            if c_lang and content:
+                                found_lang = content
+                                self.cached_meta_lang.append((cast(str, root), cast(str, found_lang)))
+                                break
+                    if found_lang is not None:
+                        break
+                if found_lang is None:
+                    self.cached_meta_lang.append((cast(str, root), ''))
+
+        # If we determined a language, compare.
+        if found_lang is not None:
+            for patterns in langs:
+                match = False
+                for pattern in patterns:
+                    if self.extended_language_filter(pattern, cast(str, found_lang)):
+                        match = True
+                if not match:
+                    break
+
+        return match
+
+    def match_dir(self, el: bs4.Tag | None, directionality: int) -> bool:
+        """Check directionality."""
+
+        # If we have to match both left and right, we can't match either.
+        if directionality & ct.SEL_DIR_LTR and directionality & ct.SEL_DIR_RTL:
+            return False
+
+        if el is None or not self.is_html_tag(el):
+            return False
+
+        # Element has defined direction of left to right or right to left
+        direction = DIR_MAP.get(util.lower(self.get_attribute_by_name(el, 'dir', '')), None)
+        if direction not in (None, 0):
+            return direction == directionality
+
+        # Element is the document element (the root) and no direction assigned, assume left to right.
+        is_root = self.is_root(el)
+        if is_root and direction is None:
+            return ct.SEL_DIR_LTR == directionality
+
+        # If `input[type=telephone]` and no direction is assigned, assume left to right.
+        name = self.get_tag(el)
+        is_input = name == 'input'
+        is_textarea = name == 'textarea'
+        is_bdi = name == 'bdi'
+        itype = util.lower(self.get_attribute_by_name(el, 'type', '')) if is_input else ''
+        if is_input and itype == 'tel' and direction is None:
+            return ct.SEL_DIR_LTR == directionality
+
+        # Auto handling for text inputs
+        if ((is_input and itype in ('text', 'search', 'tel', 'url', 'email')) or is_textarea) and direction == 0:
+            if is_textarea:
+                value = ''.join(node for node in self.get_contents(el, no_iframe=True) if self.is_content_string(node))  # type: ignore[misc]
+            else:
+                value = cast(str, self.get_attribute_by_name(el, 'value', ''))
+            if value:
+                for c in value:
+                    bidi = unicodedata.bidirectional(c)
+                    if bidi in ('AL', 'R', 'L'):
+                        direction = ct.SEL_DIR_LTR if bidi == 'L' else ct.SEL_DIR_RTL
+                        return direction == directionality
+                # Assume left to right
+                return ct.SEL_DIR_LTR == directionality
+            elif is_root:
+                return ct.SEL_DIR_LTR == directionality
+            return self.match_dir(self.get_parent(el, no_iframe=True), directionality)
+
+        # Auto handling for `bdi` and other non text inputs.
+        if (is_bdi and direction is None) or direction == 0:
+            direction = self.find_bidi(el)
+            if direction is not None:
+                return direction == directionality
+            elif is_root:
+                return ct.SEL_DIR_LTR == directionality
+            return self.match_dir(self.get_parent(el, no_iframe=True), directionality)
+
+        # Match parents direction
+        return self.match_dir(self.get_parent(el, no_iframe=True), directionality)
+
+    def match_range(self, el: bs4.Tag, condition: int) -> bool:
+        """
+        Match range.
+
+        Behavior is modeled after what we see in browsers. Browsers seem to evaluate
+        if the value is out of range, and if not, it is in range. So a missing value
+        will not evaluate out of range; therefore, value is in range. Personally, I
+        feel like this should evaluate as neither in or out of range.
+        """
+
+        out_of_range = False
+
+        itype = util.lower(self.get_attribute_by_name(el, 'type'))
+        mn = Inputs.parse_value(itype, cast(str, self.get_attribute_by_name(el, 'min', None)))
+        mx = Inputs.parse_value(itype, cast(str, self.get_attribute_by_name(el, 'max', None)))
+
+        # There is no valid min or max, so we cannot evaluate a range
+        if mn is None and mx is None:
+            return False
+
+        value = Inputs.parse_value(itype, cast(str, self.get_attribute_by_name(el, 'value', None)))
+        if value is not None:
+            if itype in ("date", "datetime-local", "month", "week", "number", "range"):
+                if mn is not None and value < mn:
+                    out_of_range = True
+                if not out_of_range and mx is not None and value > mx:
+                    out_of_range = True
+            elif itype == "time":
+                if mn is not None and mx is not None and mn > mx:
+                    # Time is periodic, so this is a reversed/discontinuous range
+                    if value < mn and value > mx:
+                        out_of_range = True
+                else:
+                    if mn is not None and value < mn:
+                        out_of_range = True
+                    if not out_of_range and mx is not None and value > mx:
+                        out_of_range = True
+
+        return not out_of_range if condition & ct.SEL_IN_RANGE else out_of_range
+
+    def match_defined(self, el: bs4.Tag) -> bool:
+        """
+        Match defined.
+
+        `:defined` is related to custom elements in a browser.
+
+        - If the document is XML (not XHTML), all tags will match.
+        - Tags that are not custom (don't have a hyphen) are marked defined.
+        - If the tag has a prefix (without or without a namespace), it will not match.
+
+        This is of course requires the parser to provide us with the proper prefix and namespace info,
+        if it doesn't, there is nothing we can do.
+        """
+
+        name = self.get_tag(el)
+        return (
+            name is not None and (
+                name.find('-') == -1 or
+                name.find(':') != -1 or
+                self.get_prefix(el) is not None
+            )
+        )
+
+    def match_placeholder_shown(self, el: bs4.Tag) -> bool:
+        """
+        Match placeholder shown according to HTML spec.
+
+        - text area should be checked if they have content. A single newline does not count as content.
+
+        """
+
+        match = False
+        content = self.get_text(el)
+        if content in ('', '\n'):
+            match = True
+
+        return match
+
+    def match_selectors(self, el: bs4.Tag, selectors: ct.SelectorList) -> bool:
+        """Check if element matches one of the selectors."""
+
+        match = False
+        is_not = selectors.is_not
+        is_html = selectors.is_html
+
+        # Internal selector lists that use the HTML flag, will automatically get the `html` namespace.
+        if is_html:
+            namespaces = self.namespaces
+            iframe_restrict = self.iframe_restrict
+            self.namespaces = {'html': NS_XHTML}
+            self.iframe_restrict = True
+
+        if not is_html or self.is_html:
+            for selector in selectors:
+                match = is_not
+                # We have a un-matchable situation (like `:focus` as you can focus an element in this environment)
+                if isinstance(selector, ct.SelectorNull):
+                    continue
+                # Verify tag matches
+                if not self.match_tag(el, selector.tag):
+                    continue
+                # Verify tag is defined
+                if selector.flags & ct.SEL_DEFINED and not self.match_defined(el):
+                    continue
+                # Verify element is root
+                if selector.flags & ct.SEL_ROOT and not self.match_root(el):
+                    continue
+                # Verify element is scope
+                if selector.flags & ct.SEL_SCOPE and not self.match_scope(el):
+                    continue
+                # Verify element has placeholder shown
+                if selector.flags & ct.SEL_PLACEHOLDER_SHOWN and not self.match_placeholder_shown(el):
+                    continue
+                # Verify `nth` matches
+                if not self.match_nth(el, selector.nth):
+                    continue
+                if selector.flags & ct.SEL_EMPTY and not self.match_empty(el):
+                    continue
+                # Verify id matches
+                if selector.ids and not self.match_id(el, selector.ids):
+                    continue
+                # Verify classes match
+                if selector.classes and not self.match_classes(el, selector.classes):
+                    continue
+                # Verify attribute(s) match
+                if not self.match_attributes(el, selector.attributes):
+                    continue
+                # Verify ranges
+                if selector.flags & RANGES and not self.match_range(el, selector.flags & RANGES):
+                    continue
+                # Verify language patterns
+                if selector.lang and not self.match_lang(el, selector.lang):
+                    continue
+                # Verify pseudo selector patterns
+                if selector.selectors and not self.match_subselectors(el, selector.selectors):
+                    continue
+                # Verify relationship selectors
+                if selector.relation and not self.match_relations(el, selector.relation):
+                    continue
+                # Validate that the current default selector match corresponds to the first submit button in the form
+                if selector.flags & ct.SEL_DEFAULT and not self.match_default(el):
+                    continue
+                # Validate that the unset radio button is among radio buttons with the same name in a form that are
+                # also not set.
+                if selector.flags & ct.SEL_INDETERMINATE and not self.match_indeterminate(el):
+                    continue
+                # Validate element directionality
+                if selector.flags & DIR_FLAGS and not self.match_dir(el, selector.flags & DIR_FLAGS):
+                    continue
+                # Validate that the tag contains the specified text.
+                if selector.contains and not self.match_contains(el, selector.contains):
+                    continue
+                match = not is_not
+                break
+
+        # Restore actual namespaces being used for external selector lists
+        if is_html:
+            self.namespaces = namespaces
+            self.iframe_restrict = iframe_restrict
+
+        return match
+
+    def select(self, limit: int = 0) -> Iterator[bs4.Tag]:
+        """Match all tags under the targeted tag."""
+
+        lim = None if limit < 1 else limit
+
+        for child in self.get_tag_descendants(self.tag):
+            if self.match(child):
+                yield child
+                if lim is not None:
+                    lim -= 1
+                    if lim < 1:
+                        break
+
+    def closest(self) -> bs4.Tag | None:
+        """Match closest ancestor."""
+
+        current = self.tag  # type: bs4.Tag | None
+        closest = None
+        while closest is None and current is not None:
+            if self.match(current):
+                closest = current
+            else:
+                current = self.get_parent(current)
+        return closest
+
+    def filter(self) -> list[bs4.Tag]:  # noqa A001
+        """Filter tag's children."""
+
+        return [
+            tag for tag in self.get_contents(self.tag)
+            if isinstance(tag, bs4.Tag) and self.match(tag)
+        ]
+
+    def match(self, el: bs4.Tag) -> bool:
+        """Match."""
+
+        return not self.is_doc(el) and self.is_tag(el) and self.match_selectors(el, self.selectors)
+
+
+class SoupSieve(ct.Immutable):
+    """Compiled Soup Sieve selector matching object."""
+
+    pattern: str
+    selectors: ct.SelectorList
+    namespaces: ct.Namespaces | None
+    custom: dict[str, str]
+    flags: int
+
+    __slots__ = ("pattern", "selectors", "namespaces", "custom", "flags", "_hash")
+
+    def __init__(
+        self,
+        pattern: str,
+        selectors: ct.SelectorList,
+        namespaces: ct.Namespaces | None,
+        custom: ct.CustomSelectors | None,
+        flags: int
+    ):
+        """Initialize."""
+
+        super().__init__(
+            pattern=pattern,
+            selectors=selectors,
+            namespaces=namespaces,
+            custom=custom,
+            flags=flags
+        )
+
+    def match(self, tag: bs4.Tag) -> bool:
+        """Match."""
+
+        return CSSMatch(self.selectors, tag, self.namespaces, self.flags).match(tag)
+
+    def closest(self, tag: bs4.Tag) -> bs4.Tag | None:
+        """Match closest ancestor."""
+
+        return CSSMatch(self.selectors, tag, self.namespaces, self.flags).closest()
+
+    def filter(self, iterable: Iterable[bs4.Tag]) -> list[bs4.Tag]:  # noqa A001
+        """
+        Filter.
+
+        `CSSMatch` can cache certain searches for tags of the same document,
+        so if we are given a tag, all tags are from the same document,
+        and we can take advantage of the optimization.
+
+        Any other kind of iterable could have tags from different documents or detached tags,
+        so for those, we use a new `CSSMatch` for each item in the iterable.
+        """
+
+        if isinstance(iterable, bs4.Tag):
+            return CSSMatch(self.selectors, iterable, self.namespaces, self.flags).filter()
+        else:
+            return [node for node in iterable if not CSSMatch.is_navigable_string(node) and self.match(node)]
+
+    def select_one(self, tag: bs4.Tag) -> bs4.Tag | None:
+        """Select a single tag."""
+
+        tags = self.select(tag, limit=1)
+        return tags[0] if tags else None
+
+    def select(self, tag: bs4.Tag, limit: int = 0) -> list[bs4.Tag]:
+        """Select the specified tags."""
+
+        return list(self.iselect(tag, limit))
+
+    def iselect(self, tag: bs4.Tag, limit: int = 0) -> Iterator[bs4.Tag]:
+        """Iterate the specified tags."""
+
+        yield from CSSMatch(self.selectors, tag, self.namespaces, self.flags).select(limit)
+
+    def __repr__(self) -> str:  # pragma: no cover
+        """Representation."""
+
+        return (
+            f"SoupSieve(pattern={self.pattern!r}, namespaces={self.namespaces!r}, "
+            f"custom={self.custom!r}, flags={self.flags!r})"
+        )
+
+    __str__ = __repr__
+
+
+ct.pickle_register(SoupSieve)
diff --git a/.venv/lib/python3.12/site-packages/soupsieve/css_parser.py b/.venv/lib/python3.12/site-packages/soupsieve/css_parser.py
new file mode 100644
index 0000000000000000000000000000000000000000..8602a41a0ff68b73381164bb2d008920bf18a22a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/soupsieve/css_parser.py
@@ -0,0 +1,1359 @@
+"""CSS selector parser."""
+from __future__ import annotations
+import re
+from functools import lru_cache
+from . import util
+from . import css_match as cm
+from . import css_types as ct
+from .util import SelectorSyntaxError
+import warnings
+from typing import Match, Any, Iterator, cast
+from dataclasses import dataclass
+from collections import UserDict
+import threading
+
+RE_LOCK = threading.Lock()
+SEL_LOCK = threading.RLock()
+
+UNICODE_REPLACEMENT_CHAR = 0xFFFD
+
+SELECTOR_LIMIT = 8192
+
+# Simple pseudo classes that take no parameters
+PSEUDO_SIMPLE = {
+    ":any-link",
+    ":empty",
+    ":first-child",
+    ":first-of-type",
+    ":in-range",
+    ":open",
+    ":out-of-range",
+    ":last-child",
+    ":last-of-type",
+    ":link",
+    ":only-child",
+    ":only-of-type",
+    ":root",
+    ':checked',
+    ':default',
+    ':disabled',
+    ':enabled',
+    ':indeterminate',
+    ':optional',
+    ':placeholder-shown',
+    ':read-only',
+    ':read-write',
+    ':required',
+    ':scope',
+    ':defined',
+    ':muted'
+}
+
+# Supported, simple pseudo classes that match nothing in the Soup Sieve environment
+PSEUDO_SIMPLE_NO_MATCH = {
+    ':active',
+    ':autofill',
+    ':buffering',
+    ':current',
+    ':focus',
+    ':focus-visible',
+    ':focus-within',
+    ':fullscreen',
+    ':future',
+    ':host',
+    ':hover',
+    ':local-link',
+    ':past',
+    ':paused',
+    ':picture-in-picture',
+    ':playing',
+    ':popover-open',
+    ':seeking',
+    ':stalled',
+    ':target',
+    ':target-within',
+    ':user-invalid',
+    ':volume-locked',
+    ':visited'
+}
+
+# Complex pseudo classes that take selector lists
+PSEUDO_COMPLEX = {
+    ':contains',
+    ':-soup-contains',
+    ':-soup-contains-own',
+    ':has',
+    ':is',
+    ':matches',
+    ':not',
+    ':where'
+}
+
+PSEUDO_COMPLEX_NO_MATCH = {
+    ':current',
+    ':host',
+    ':host-context'
+}
+
+# Complex pseudo classes that take very specific parameters and are handled special
+PSEUDO_SPECIAL = {
+    ':dir',
+    ':lang',
+    ':nth-child',
+    ':nth-last-child',
+    ':nth-last-of-type',
+    ':nth-of-type'
+}
+
+PSEUDO_SUPPORTED = PSEUDO_SIMPLE | PSEUDO_SIMPLE_NO_MATCH | PSEUDO_COMPLEX | PSEUDO_COMPLEX_NO_MATCH | PSEUDO_SPECIAL
+
+# Sub-patterns parts
+# Whitespace
+NEWLINE = r'(?:\r\n|(?!\r\n)[\n\f\r])'
+WS = fr'(?:[ \t]|{NEWLINE})'
+# Comments
+COMMENTS = r'(?:/\*(?:[^*]|\*(?!/))*\*/)'
+# Whitespace with comments included
+WSC = fr'(?:{WS}|{COMMENTS})'
+# CSS escapes
+CSS_ESCAPES = fr'(?:\\(?:[a-f0-9]{{1,6}}{WS}?|[^\r\n\f]|$))'
+CSS_STRING_ESCAPES = fr'(?:\\(?:[a-f0-9]{{1,6}}{WS}?|[^\r\n\f]|$|{NEWLINE}))'
+# CSS Identifier
+IDENTIFIER = fr'''
+(?:(?:--|-?(?:[^\x00-\x2f\x30-\x40\x5B-\x5E\x60\x7B-\x9f]|{CSS_ESCAPES}))
+(?:[^\x00-\x2c\x2e\x2f\x3A-\x40\x5B-\x5E\x60\x7B-\x9f]|{CSS_ESCAPES})*)
+'''
+# `nth` content
+NTH = fr'(?:[-+])?(?:[0-9]+n?|n)(?:(?<=n){WSC}*(?:[-+]){WSC}*(?:[0-9]+))?'
+# Value: quoted string or identifier
+VALUE = fr'''(?:"(?:\\(?:.|{NEWLINE})|[^\\"\r\n\f])*?"|'(?:\\(?:.|{NEWLINE})|[^\\'\r\n\f])*?'|{IDENTIFIER})'''
+# Attribute value comparison. `!=` is handled special as it is non-standard.
+ATTR = fr'(?:{WSC}*(?P[!~^|*$]?=){WSC}*(?P{VALUE})(?:{WSC}*(?P[is]))?)?{WSC}*'
+
+# Selector patterns
+# IDs (`#id`)
+PAT_ID = fr'\#{IDENTIFIER}'
+# Classes (`.class`)
+PAT_CLASS = fr'\.{IDENTIFIER}'
+# Prefix:Tag (`prefix|tag`)
+PAT_TAG = fr'(?P(?:{IDENTIFIER}|\*)?\|)?(?P{IDENTIFIER}|\*)'
+# Attributes (`[attr]`, `[attr=value]`, etc.)
+PAT_ATTR = fr'\[{WSC}*(?P(?:{IDENTIFIER}|\*)?\|)?(?P{IDENTIFIER}){ATTR}\]'
+# Pseudo class (`:pseudo-class`, `:pseudo-class(`)
+PAT_PSEUDO_CLASS = fr'(?P:{IDENTIFIER})(?P\({WSC}*)?'
+# Pseudo class special patterns. Matches `:pseudo-class(` for special case pseudo classes.
+PAT_PSEUDO_CLASS_SPECIAL = fr'(?P:{IDENTIFIER})(?P\({WSC}*)'
+# Custom pseudo class (`:--custom-pseudo`)
+PAT_PSEUDO_CLASS_CUSTOM = fr'(?P:(?=--){IDENTIFIER})'
+# Nesting ampersand selector. Matches `&`
+PAT_AMP = r'&'
+# Closing pseudo group (`)`)
+PAT_PSEUDO_CLOSE = fr'{WSC}*\)'
+# Pseudo element (`::pseudo-element`)
+PAT_PSEUDO_ELEMENT = fr':{PAT_PSEUDO_CLASS}'
+# At rule (`@page`, etc.) (not supported)
+PAT_AT_RULE = fr'@P{IDENTIFIER}'
+# Pseudo class `nth-child` (`:nth-child(an+b [of S]?)`, `:first-child`, etc.)
+PAT_PSEUDO_NTH_CHILD = fr'''
+(?P{PAT_PSEUDO_CLASS_SPECIAL}
+(?P{NTH}|even|odd))(?:{WSC}*\)|(?P{COMMENTS}*{WS}{WSC}*of{COMMENTS}*{WS}{WSC}*))
+'''
+# Pseudo class `nth-of-type` (`:nth-of-type(an+b)`, `:first-of-type`, etc.)
+PAT_PSEUDO_NTH_TYPE = fr'''
+(?P{PAT_PSEUDO_CLASS_SPECIAL}
+(?P{NTH}|even|odd)){WSC}*\)
+'''
+# Pseudo class language (`:lang("*-de", en)`)
+PAT_PSEUDO_LANG = fr'{PAT_PSEUDO_CLASS_SPECIAL}(?P{VALUE}(?:{WSC}*,{WSC}*{VALUE})*){WSC}*\)'
+# Pseudo class direction (`:dir(ltr)`)
+PAT_PSEUDO_DIR = fr'{PAT_PSEUDO_CLASS_SPECIAL}(?Pltr|rtl){WSC}*\)'
+# Combining characters (`>`, `~`, ` `, `+`, `,`)
+PAT_COMBINE = fr'{WSC}*?(?P[,+>~]|{WS}(?![,+>~])){WSC}*'
+# Extra: Contains (`:contains(text)`)
+PAT_PSEUDO_CONTAINS = fr'{PAT_PSEUDO_CLASS_SPECIAL}(?P{VALUE}(?:{WSC}*,{WSC}*{VALUE})*){WSC}*\)'
+
+# Regular expressions
+# CSS escape pattern
+RE_CSS_ESC = re.compile(fr'(?:(\\[a-f0-9]{{1,6}}{WSC}?)|(\\[^\r\n\f])|(\\$))', re.I)
+RE_CSS_STR_ESC = re.compile(fr'(?:(\\[a-f0-9]{{1,6}}{WS}?)|(\\[^\r\n\f])|(\\$)|(\\{NEWLINE}))', re.I)
+# Pattern to break up `nth` specifiers
+RE_NTH = re.compile(fr'(?P[-+])?(?P[0-9]+n?|n)(?:(?<=n){WSC}*(?P[-+]){WSC}*(?P[0-9]+))?', re.I)
+# Pattern to iterate multiple values.
+RE_VALUES = re.compile(fr'(?:(?P{VALUE})|(?P{WSC}*,{WSC}*))', re.X)
+# Whitespace checks
+RE_WS = re.compile(WS)
+RE_WS_BEGIN = re.compile(fr'^{WSC}*')
+RE_WS_END = re.compile(fr'^(?:[ \t]|(?:\n\r|(?!\n\r)[\n\f\r])|{COMMENTS})*')
+RE_CUSTOM = re.compile(fr'^{PAT_PSEUDO_CLASS_CUSTOM}$', re.X)
+RE_PSEUDO_CLASS_SPECIAL = re.compile(PAT_PSEUDO_CLASS_SPECIAL, re.I | re.X | re.U)
+
+QUOTED = ("'", '"')
+
+# Constants
+# List split token
+COMMA_COMBINATOR = ','
+# Relation token for descendant
+WS_COMBINATOR = " "
+
+# Parse flags
+FLG_PSEUDO = 0x01
+FLG_NOT = 0x02
+FLG_RELATIVE = 0x04
+FLG_DEFAULT = 0x08
+FLG_HTML = 0x10
+FLG_INDETERMINATE = 0x20
+FLG_OPEN = 0x40
+FLG_IN_RANGE = 0x80
+FLG_OUT_OF_RANGE = 0x100
+FLG_PLACEHOLDER_SHOWN = 0x200
+FLG_FORGIVE = 0x400
+
+# Maximum cached patterns to store
+_MAXCACHE = 500
+
+
+@lru_cache(maxsize=_MAXCACHE)
+def _cached_css_compile(
+    pattern: str,
+    namespaces: ct.Namespaces | None,
+    custom: ct.CustomSelectors | None,
+    flags: int
+) -> cm.SoupSieve:
+    """Cached CSS compile."""
+
+    custom_selectors = process_custom(custom)
+    return cm.SoupSieve(
+        pattern,
+        CSSParser(
+            pattern,
+            custom=custom_selectors,
+            flags=flags
+        ).process_selectors(),
+        namespaces,
+        custom,
+        flags
+    )
+
+
+def _purge_cache() -> None:
+    """Purge the cache."""
+
+    _cached_css_compile.cache_clear()
+
+
+def process_custom(custom: ct.CustomSelectors | None) -> dict[str, str | ct.SelectorList]:
+    """Process custom."""
+
+    custom_selectors = {}
+    if custom is not None:
+        for key, value in custom.items():
+            name = util.lower(key)
+            if RE_CUSTOM.match(name) is None:
+                raise SelectorSyntaxError(f"The name '{name}' is not a valid custom pseudo-class name")
+            if name in custom_selectors:
+                raise KeyError(f"The custom selector '{name}' has already been registered")
+            custom_selectors[css_unescape(name)] = value
+    return custom_selectors
+
+
+def css_unescape(content: str) -> str:
+    """
+    Unescape CSS value.
+
+    Strings allow for spanning the value on multiple strings by escaping a new line.
+    """
+
+    def replace(m: Match[str]) -> str:
+        """Replace with the appropriate substitute."""
+
+        if m.group(1):
+            codepoint = int(m.group(1)[1:], 16)
+            if codepoint == 0:
+                codepoint = UNICODE_REPLACEMENT_CHAR
+            value = chr(codepoint)
+        elif m.group(2):
+            value = m.group(2)[1:]
+        elif m.group(3):
+            value = '\ufffd'
+        else:
+            value = ''
+
+        return value
+
+    quoted = content.startswith(QUOTED)
+    return (RE_CSS_STR_ESC if quoted else RE_CSS_ESC).sub(
+        replace,
+        content[1:-1] if quoted else content
+    )
+
+
+def escape(ident: str) -> str:
+    """Escape identifier."""
+
+    string = []
+    length = len(ident)
+    start_dash = length > 0 and ident[0] == '-'
+    if length == 1 and start_dash:
+        # Need to escape identifier that is a single `-` with no other characters
+        string.append(f'\\{ident}')
+    else:
+        for index, c in enumerate(ident):
+            codepoint = ord(c)
+            if codepoint == 0x00:
+                string.append('\ufffd')
+            elif (0x01 <= codepoint <= 0x1F) or codepoint == 0x7F:
+                string.append(f'\\{codepoint:x} ')
+            elif (index == 0 or (start_dash and index == 1)) and (0x30 <= codepoint <= 0x39):
+                string.append(f'\\{codepoint:x} ')
+            elif (
+                codepoint in (0x2D, 0x5F) or codepoint >= 0x80 or (0x30 <= codepoint <= 0x39) or
+                (0x30 <= codepoint <= 0x39) or (0x41 <= codepoint <= 0x5A) or (0x61 <= codepoint <= 0x7A)
+            ):
+                string.append(c)
+            else:
+                string.append(f'\\{c}')
+    return ''.join(string)
+
+
+class SelectorPattern:
+    """Selector pattern."""
+
+    def __init__(self, name: str, pattern: str) -> None:
+        """Initialize."""
+
+        self.name = name
+        self.pattern = pattern
+        self._re_pattern: re.Pattern[str] | None = None
+
+    @property
+    def re_pattern(self) -> re.Pattern[str]:
+        """Retrieve the compiled regular expression pattern."""
+
+        with RE_LOCK:
+            if self._re_pattern is None:
+                self._re_pattern = re.compile(self.pattern, re.I | re.X | re.U)
+        return self._re_pattern
+
+    def get_name(self) -> str:
+        """Get name."""
+
+        return self.name
+
+    def match(self, selector: str, index: int, flags: int) -> Match[str] | None:
+        """Match the selector."""
+
+        return self.re_pattern.match(selector, index)
+
+
+class SpecialPseudoPattern(SelectorPattern):
+    """Selector pattern."""
+
+    def __init__(self, patterns: tuple[tuple[str, tuple[str, ...], str, type[SelectorPattern]], ...]) -> None:
+        """Initialize."""
+
+        self.patterns = {}
+        for p in patterns:
+            name = p[0]
+            pattern = p[3](name, p[2])
+            for pseudo in p[1]:
+                self.patterns[pseudo] = pattern
+
+        self.matched_name = None  # type: SelectorPattern | None
+
+    def get_name(self) -> str:
+        """Get name."""
+
+        return '' if self.matched_name is None else self.matched_name.get_name()
+
+    def match(self, selector: str, index: int, flags: int) -> Match[str] | None:
+        """Match the selector."""
+
+        pseudo = None
+        m = RE_PSEUDO_CLASS_SPECIAL.match(selector, index)
+        if m:
+            name = util.lower(css_unescape(m.group('name')))
+            pattern = self.patterns.get(name)
+            if pattern:
+                pseudo = pattern.match(selector, index, flags)
+                if pseudo:
+                    self.matched_name = pattern
+
+        return pseudo
+
+
+class _Selector:
+    """
+    Intermediate selector class.
+
+    This stores selector data for a compound selector as we are acquiring them.
+    Once we are done collecting the data for a compound selector, we freeze
+    the data in an object that can be pickled and hashed.
+    """
+
+    def __init__(self, **kwargs: Any) -> None:
+        """Initialize."""
+
+        self.tag = kwargs.get('tag', None)  # type: ct.SelectorTag | None
+        self.ids = kwargs.get('ids', [])  # type: list[str]
+        self.classes = kwargs.get('classes', [])  # type: list[str]
+        self.attributes = kwargs.get('attributes', [])  # type: list[ct.SelectorAttribute]
+        self.nth = kwargs.get('nth', [])  # type: list[ct.SelectorNth]
+        self.selectors = kwargs.get('selectors', [])  # type: list[ct.SelectorList]
+        self.relations = kwargs.get('relations', [])  # type: list[_Selector]
+        self.rel_type = kwargs.get('rel_type', None)  # type: str | None
+        self.contains = kwargs.get('contains', [])  # type: list[ct.SelectorContains]
+        self.lang = kwargs.get('lang', [])  # type: list[ct.SelectorLang]
+        self.flags = kwargs.get('flags', 0)  # type: int
+        self.no_match = kwargs.get('no_match', False)  # type: bool
+
+    def _freeze_relations(self, relations: list[_Selector]) -> ct.SelectorList:
+        """Freeze relation."""
+
+        if relations:
+            sel = relations[0]
+            sel.relations.extend(relations[1:])
+            return ct.SelectorList([sel.freeze()])
+        else:
+            return ct.SelectorList()
+
+    def freeze(self) -> ct.Selector | ct.SelectorNull:
+        """Freeze self."""
+
+        if self.no_match:
+            return ct.SelectorNull()
+        else:
+            return ct.Selector(
+                self.tag,
+                tuple(self.ids),
+                tuple(self.classes),
+                tuple(self.attributes),
+                tuple(self.nth),
+                tuple(self.selectors),
+                self._freeze_relations(self.relations),
+                self.rel_type,
+                tuple(self.contains),
+                tuple(self.lang),
+                self.flags
+            )
+
+    def __str__(self) -> str:  # pragma: no cover
+        """String representation."""
+
+        return (
+            f'_Selector(tag={self.tag!r}, ids={self.ids!r}, classes={self.classes!r}, attributes={self.attributes!r}, '
+            f'nth={self.nth!r}, selectors={self.selectors!r}, relations={self.relations!r}, '
+            f'rel_type={self.rel_type!r}, contains={self.contains!r}, lang={self.lang!r}, flags={self.flags!r}, '
+            f'no_match={self.no_match!r})'
+        )
+
+    __repr__ = __str__
+
+
+@dataclass
+class CSSPattern:
+    """A CSS pattern that hasn't been processed by `CSSParser` yet."""
+
+    selector: str
+    flags: int
+
+
+class PseudoSelectorMap(UserDict[str, CSSPattern | ct.SelectorList]):
+    """Pseudo selector map."""
+
+    def __setitem__(self, key: str, value: CSSPattern | ct.SelectorList) -> None:
+        """Set item."""
+
+        self.data[key] = value
+
+    def __getitem__(self, key: str) -> ct.SelectorList:
+        """Get item."""
+
+        with SEL_LOCK:
+            value = self.data[key]
+            if isinstance(value, CSSPattern):
+                value = CSSParser(value.selector).process_selectors(flags=value.flags)
+                self.data[key] = value
+
+        return value
+
+
+# CSS pattern for `:link` and `:any-link`
+CSS_LINK = CSSPattern('html|*:is(a, area)[href]', FLG_PSEUDO | FLG_HTML)
+# CSS pattern for `:checked`
+CSS_CHECKED = CSSPattern(
+    '''
+    html|*:is(input[type=checkbox], input[type=radio])[checked], html|option[selected]
+    ''',
+    FLG_PSEUDO | FLG_HTML
+)
+# CSS pattern for `:default` (must compile CSS_CHECKED first)
+CSS_DEFAULT = CSSPattern(
+    '''
+    :checked,
+
+    /*
+    This pattern must be at the end.
+    Special logic is applied to the last selector.
+    */
+    html|form html|*:is(button, input)[type="submit"]
+    ''',
+    FLG_PSEUDO | FLG_HTML | FLG_DEFAULT
+)
+# CSS pattern for `:indeterminate`
+CSS_INDETERMINATE = CSSPattern(
+    '''
+    html|input[type="checkbox"][indeterminate],
+    html|input[type="radio"]:is(:not([name]), [name=""]):not([checked]),
+    html|progress:not([value]),
+
+    /*
+    This pattern must be at the end.
+    Special logic is applied to the last selector.
+    */
+    html|input[type="radio"][name]:not([name='']):not([checked])
+    ''',
+    FLG_PSEUDO | FLG_HTML | FLG_INDETERMINATE
+)
+# CSS pattern for `:disabled`
+CSS_DISABLED = CSSPattern(
+    '''
+    html|*:is(input:not([type=hidden]), button, select, textarea, fieldset, optgroup, option, fieldset)[disabled],
+    html|optgroup[disabled] > html|option,
+    html|fieldset[disabled] > html|*:is(input:not([type=hidden]), button, select, textarea, fieldset),
+    html|fieldset[disabled] >
+        html|*:not(legend:nth-of-type(1)) html|*:is(input:not([type=hidden]), button, select, textarea, fieldset)
+    ''',
+    FLG_PSEUDO | FLG_HTML
+)
+# CSS pattern for `:enabled`
+CSS_ENABLED = CSSPattern(
+    '''
+    html|*:is(input:not([type=hidden]), button, select, textarea, fieldset, optgroup, option, fieldset):not(:disabled)
+    ''',
+    FLG_PSEUDO | FLG_HTML
+)
+# CSS pattern for `:required`
+CSS_REQUIRED = CSSPattern('html|*:is(input, textarea, select)[required]', FLG_PSEUDO | FLG_HTML)
+# CSS pattern for `:optional`
+CSS_OPTIONAL = CSSPattern('html|*:is(input, textarea, select):not([required])', FLG_PSEUDO | FLG_HTML)
+# CSS pattern for `:placeholder-shown`
+CSS_PLACEHOLDER_SHOWN = CSSPattern(
+    '''
+    html|input:is(
+        :not([type]),
+        [type=""],
+        [type=text],
+        [type=search],
+        [type=url],
+        [type=tel],
+        [type=email],
+        [type=password],
+        [type=number]
+    )[placeholder]:not([placeholder='']):is(:not([value]), [value=""]),
+    html|textarea[placeholder]:not([placeholder=''])
+    ''',
+    FLG_PSEUDO | FLG_HTML | FLG_PLACEHOLDER_SHOWN
+)
+# CSS pattern for `:read-write` (CSS_DISABLED must be compiled first)
+CSS_READ_WRITE = CSSPattern(
+    '''
+    html|*:is(
+        textarea,
+        input:is(
+            :not([type]),
+            [type=""],
+            [type=text],
+            [type=search],
+            [type=url],
+            [type=tel],
+            [type=email],
+            [type=number],
+            [type=password],
+            [type=date],
+            [type=datetime-local],
+            [type=month],
+            [type=time],
+            [type=week]
+        )
+    ):not([readonly], :disabled),
+    html|*:is([contenteditable=""], [contenteditable="true" i])
+    ''',
+    FLG_PSEUDO | FLG_HTML
+)
+# CSS pattern for `:read-only`
+CSS_READ_ONLY = CSSPattern('html|*:not(:read-write)', FLG_PSEUDO | FLG_HTML)
+# CSS pattern for `:in-range`
+CSS_IN_RANGE = CSSPattern(
+    '''
+    html|input:is(
+        [type="date"],
+        [type="month"],
+        [type="week"],
+        [type="time"],
+        [type="datetime-local"],
+        [type="number"],
+        [type="range"]
+    ):is(
+        [min],
+        [max]
+    )
+    ''',
+    FLG_PSEUDO | FLG_HTML | FLG_IN_RANGE
+)
+# CSS pattern for `:out-of-range`
+CSS_OUT_OF_RANGE = CSSPattern(
+    '''
+    html|input:is(
+        [type="date"],
+        [type="month"],
+        [type="week"],
+        [type="time"],
+        [type="datetime-local"],
+        [type="number"],
+        [type="range"]
+    ):is(
+        [min],
+        [max]
+    )
+    ''',
+    FLG_PSEUDO | FLG_HTML | FLG_OUT_OF_RANGE
+)
+# CSS pattern for :open
+CSS_OPEN = CSSPattern('html|*:is(details, dialog)[open]', FLG_PSEUDO | FLG_HTML)
+# CSS pattern for :muted
+CSS_MUTED = CSSPattern('html|*:is(video, audio)[muted]', FLG_PSEUDO | FLG_HTML)
+# CSS pattern default for `:nth-child` "of S" feature
+CSS_NTH_OF_S_DEFAULT = CSSPattern("*|*", FLG_PSEUDO)
+
+
+class CSSParser:
+    """Parse CSS selectors."""
+
+    CSS_TOKENS = (
+        SelectorPattern("pseudo_close", PAT_PSEUDO_CLOSE),
+        SpecialPseudoPattern(
+            (
+                (
+                    "pseudo_contains",
+                    (':contains', ':-soup-contains', ':-soup-contains-own'),
+                    PAT_PSEUDO_CONTAINS,
+                    SelectorPattern
+                ),
+                ("pseudo_nth_child", (':nth-child', ':nth-last-child'), PAT_PSEUDO_NTH_CHILD, SelectorPattern),
+                ("pseudo_nth_type", (':nth-of-type', ':nth-last-of-type'), PAT_PSEUDO_NTH_TYPE, SelectorPattern),
+                ("pseudo_lang", (':lang',), PAT_PSEUDO_LANG, SelectorPattern),
+                ("pseudo_dir", (':dir',), PAT_PSEUDO_DIR, SelectorPattern)
+            )
+        ),
+        SelectorPattern("pseudo_class_custom", PAT_PSEUDO_CLASS_CUSTOM),
+        SelectorPattern("pseudo_class", PAT_PSEUDO_CLASS),
+        SelectorPattern("pseudo_element", PAT_PSEUDO_ELEMENT),
+        SelectorPattern("amp", PAT_AMP),
+        SelectorPattern("at_rule", PAT_AT_RULE),
+        SelectorPattern("id", PAT_ID),
+        SelectorPattern("class", PAT_CLASS),
+        SelectorPattern("tag", PAT_TAG),
+        SelectorPattern("attribute", PAT_ATTR),
+        SelectorPattern("combine", PAT_COMBINE)
+    )
+
+    # Pseudos that expand to selectors
+    PSEUDO_SELECTORS = PseudoSelectorMap(
+        {
+            ':link': CSS_LINK,
+            ':any-link': CSS_LINK,
+            ':checked': CSS_CHECKED,
+            ':default': CSS_DEFAULT,
+            ':indeterminate': CSS_INDETERMINATE,
+            ':disabled': CSS_DISABLED,
+            ':enabled': CSS_ENABLED,
+            ':required': CSS_REQUIRED,
+            ':muted': CSS_MUTED,
+            ':open': CSS_OPEN,
+            ':optional': CSS_OPTIONAL,
+            ':read-only': CSS_READ_ONLY,
+            ':read-write': CSS_READ_WRITE,
+            ':in-range': CSS_IN_RANGE,
+            ':out-of-range': CSS_OUT_OF_RANGE,
+            ':placeholder-shown': CSS_PLACEHOLDER_SHOWN,
+            '': CSS_NTH_OF_S_DEFAULT
+        }
+    )
+
+    def __init__(
+        self,
+        selector: str,
+        custom: dict[str, str | ct.SelectorList] | None = None,
+        flags: int = 0
+    ) -> None:
+        """Initialize."""
+
+        self.pattern = selector.replace('\x00', '\ufffd')
+        self.flags = flags
+        self.debug = self.flags & util.DEBUG
+        self.custom = {} if custom is None else custom
+        self.count = 0
+
+    def increment_count(self, increment: int = 1) -> None:
+        """Check the current selector count."""
+
+        self.count += increment
+        if self.count > SELECTOR_LIMIT:
+            raise ValueError(f'Selector exceeds pseudo-class nesting limit of {SELECTOR_LIMIT}')
+
+    def parse_attribute_selector(self, sel: _Selector, m: Match[str], has_selector: bool) -> bool:
+        """Create attribute selector from the returned regex match."""
+
+        inverse = False
+        op = m.group('cmp')
+        case = util.lower(m.group('case')) if m.group('case') else None
+        ns = css_unescape(m.group('attr_ns')[:-1]) if m.group('attr_ns') else ''
+        attr = css_unescape(m.group('attr_name'))
+        is_type = False
+        pattern2 = None
+        value = ''
+
+        if case:
+            flags = (re.I if case == 'i' else 0) | re.DOTALL
+        elif util.lower(attr) == 'type':
+            flags = re.I | re.DOTALL
+            is_type = True
+        else:
+            flags = re.DOTALL
+
+        if op:
+            value = css_unescape(m.group('value'))
+
+        if not op:
+            # Attribute name
+            pattern = None
+        elif op.startswith('^'):
+            # Value start with
+            # `^=` should match nothing if the value is empty, so use `(?!)` which cannot be matched.
+            value = r'(?!)' if not value else re.escape(value)
+            pattern = re.compile(r'^%s.*' % value, flags)
+        elif op.startswith('$'):
+            # Value ends with
+            # `$=` should match nothing if the value is empty, so use `(?!)` which cannot be matched.
+            value = r'(?!)' if not value else re.escape(value)
+            pattern = re.compile(r'.*?%s$' % value, flags)
+        elif op.startswith('*'):
+            # Value contains
+            # `*=` should match nothing if the value is empty, so use `(?!)` which cannot be matched.
+            value = r'(?!)' if not value else re.escape(value)
+            pattern = re.compile(r'.*?%s.*' % value, flags)
+        elif op.startswith('~'):
+            # Value contains word within space separated list
+            # `*~` should match nothing if the value is empty, so use `(?!)` which cannot be matched.
+            value = r'(?!)' if not value or RE_WS.search(value) else re.escape(value)
+            pattern = re.compile(r'.*?(?:(?<=^)|(?<=[ \t\r\n\f]))%s(?=(?:[ \t\r\n\f]|$)).*' % value, flags)
+        elif op.startswith('|'):
+            # Value starts with word in dash separated list
+            pattern = re.compile(r'^%s(?:-.*)?$' % re.escape(value), flags)
+        else:
+            # Value matches
+            pattern = re.compile(r'^%s$' % re.escape(value), flags)
+            if op.startswith('!'):
+                # Equivalent to `:not([attr=value])`
+                inverse = True
+        if is_type and pattern:
+            pattern2 = re.compile(pattern.pattern)
+
+        # Append the attribute selector
+        sel_attr = ct.SelectorAttribute(attr, ns, pattern, pattern2)
+        if inverse:
+            # If we are using `!=`, we need to nest the pattern under a `:not()`.
+            sub_sel = _Selector()
+            sub_sel.attributes.append(sel_attr)
+            not_list = ct.SelectorList([sub_sel.freeze()], True, False)
+            sel.selectors.append(not_list)
+        else:
+            sel.attributes.append(sel_attr)
+
+        has_selector = True
+        return has_selector
+
+    def parse_tag_pattern(self, sel: _Selector, m: Match[str], has_selector: bool) -> bool:
+        """Parse tag pattern from regex match."""
+
+        prefix = css_unescape(m.group('tag_ns')[:-1]) if m.group('tag_ns') else None
+        tag = css_unescape(m.group('tag_name'))
+        sel.tag = ct.SelectorTag(tag, prefix)
+        has_selector = True
+        return has_selector
+
+    def parse_pseudo_class_custom(self, sel: _Selector, m: Match[str], has_selector: bool) -> bool:
+        """
+        Parse custom pseudo class alias.
+
+        Compile custom selectors as we need them. When compiling a custom selector,
+        set it to `None` in the dictionary so we can avoid an infinite loop.
+        """
+
+        pseudo = util.lower(css_unescape(m.group('name')))
+        selector = self.custom.get(pseudo)
+        if selector is None:
+            raise SelectorSyntaxError(
+                f"Undefined custom selector '{pseudo}' found at position {m.end(0)}",
+                self.pattern,
+                m.end(0)
+            )
+
+        if not isinstance(selector, ct.SelectorList):
+            del self.custom[pseudo]
+            selector = CSSParser(
+                selector, custom=self.custom, flags=self.flags
+            ).process_selectors(flags=FLG_PSEUDO)
+            self.custom[pseudo] = selector
+
+        self.increment_count(selector.count)
+        sel.selectors.append(selector)
+        has_selector = True
+        return has_selector
+
+    def parse_pseudo_class(
+        self,
+        sel: _Selector,
+        m: Match[str],
+        has_selector: bool,
+        iselector: Iterator[tuple[str, Match[str]]],
+        is_html: bool
+    ) -> tuple[bool, bool]:
+        """Parse pseudo class."""
+
+        complex_pseudo = False
+        pseudo = util.lower(css_unescape(m.group('name')))
+        if m.group('open'):
+            complex_pseudo = True
+        if complex_pseudo and pseudo in PSEUDO_COMPLEX:
+            has_selector = self.parse_pseudo_open(sel, pseudo, has_selector, iselector, m.end(0))
+        elif not complex_pseudo and pseudo in PSEUDO_SIMPLE:
+            if pseudo == ':root':
+                sel.flags |= ct.SEL_ROOT
+            elif pseudo == ':defined':
+                sel.flags |= ct.SEL_DEFINED
+                is_html = True
+            elif pseudo == ':scope':
+                sel.flags |= ct.SEL_SCOPE
+            elif pseudo == ':empty':
+                sel.flags |= ct.SEL_EMPTY
+            elif pseudo in self.PSEUDO_SELECTORS:
+                pseudo_selector = self.PSEUDO_SELECTORS[pseudo]
+                self.increment_count(pseudo_selector.count)
+                sel.selectors.append(pseudo_selector)
+            elif pseudo == ':first-child':
+                sel.nth.append(ct.SelectorNth(1, False, 0, False, False, ct.SelectorList()))
+            elif pseudo == ':last-child':
+                sel.nth.append(ct.SelectorNth(1, False, 0, False, True, ct.SelectorList()))
+            elif pseudo == ':first-of-type':
+                sel.nth.append(ct.SelectorNth(1, False, 0, True, False, ct.SelectorList()))
+            elif pseudo == ':last-of-type':
+                sel.nth.append(ct.SelectorNth(1, False, 0, True, True, ct.SelectorList()))
+            elif pseudo == ':only-child':
+                sel.nth.extend(
+                    [
+                        ct.SelectorNth(1, False, 0, False, False, ct.SelectorList()),
+                        ct.SelectorNth(1, False, 0, False, True, ct.SelectorList())
+                    ]
+                )
+            elif pseudo == ':only-of-type':
+                sel.nth.extend(
+                    [
+                        ct.SelectorNth(1, False, 0, True, False, ct.SelectorList()),
+                        ct.SelectorNth(1, False, 0, True, True, ct.SelectorList())
+                    ]
+                )
+            has_selector = True
+        elif complex_pseudo and pseudo in PSEUDO_COMPLEX_NO_MATCH:
+            self.parse_selectors(iselector, m.end(0), FLG_PSEUDO | FLG_OPEN)
+            sel.no_match = True
+            has_selector = True
+        elif not complex_pseudo and pseudo in PSEUDO_SIMPLE_NO_MATCH:
+            sel.no_match = True
+            has_selector = True
+        elif pseudo in PSEUDO_SUPPORTED:
+            raise SelectorSyntaxError(
+                f"Invalid syntax for pseudo class '{pseudo}'",
+                self.pattern,
+                m.start(0)
+            )
+        else:
+            raise SelectorSyntaxError(
+                f"'{pseudo}' was detected as a pseudo-class and is either unsupported or invalid. "
+                "If the syntax was not intended to be recognized as a pseudo-class, please escape the colon.",
+                self.pattern,
+                m.start(0)
+            )
+
+        return has_selector, is_html
+
+    def parse_pseudo_nth(
+        self,
+        sel: _Selector,
+        m: Match[str],
+        has_selector: bool,
+        iselector: Iterator[tuple[str, Match[str]]]
+    ) -> bool:
+        """Parse `nth` pseudo."""
+
+        mdict = m.groupdict()
+        if mdict.get('pseudo_nth_child'):
+            postfix = '_child'
+        else:
+            postfix = '_type'
+        mdict['name'] = util.lower(css_unescape(mdict['name']))
+        content = util.lower(mdict.get('nth' + postfix))
+        if content == 'even':
+            # 2n
+            s1 = 2
+            s2 = 0
+            var = True
+        elif content == 'odd':
+            # 2n+1
+            s1 = 2
+            s2 = 1
+            var = True
+        else:
+            nth_parts = cast(Match[str], RE_NTH.match(content))
+            _s1 = '-' if nth_parts.group('s1') and nth_parts.group('s1') == '-' else ''
+            a = nth_parts.group('a')
+            var = a.endswith('n')
+            if a.startswith('n'):
+                _s1 += '1'
+            elif var:
+                _s1 += a[:-1]
+            else:
+                _s1 += a
+            _s2 = '-' if nth_parts.group('s2') and nth_parts.group('s2') == '-' else ''
+            if nth_parts.group('b'):
+                _s2 += nth_parts.group('b')
+            else:
+                _s2 = '0'
+            s1 = int(_s1, 10)
+            s2 = int(_s2, 10)
+
+        pseudo_sel = mdict['name']
+        if postfix == '_child':
+            if m.group('of'):
+                # Parse the rest of `of S`.
+                nth_sel = self.parse_selectors(iselector, m.end(0), FLG_PSEUDO | FLG_OPEN)
+            else:
+                # Use default `*|*` for `of S`.
+                nth_sel = self.PSEUDO_SELECTORS['']
+                self.increment_count(nth_sel.count)
+            if pseudo_sel == ':nth-child':
+                sel.nth.append(ct.SelectorNth(s1, var, s2, False, False, nth_sel))
+            elif pseudo_sel == ':nth-last-child':
+                sel.nth.append(ct.SelectorNth(s1, var, s2, False, True, nth_sel))
+        else:
+            if pseudo_sel == ':nth-of-type':
+                sel.nth.append(ct.SelectorNth(s1, var, s2, True, False, ct.SelectorList()))
+            elif pseudo_sel == ':nth-last-of-type':
+                sel.nth.append(ct.SelectorNth(s1, var, s2, True, True, ct.SelectorList()))
+        has_selector = True
+        return has_selector
+
+    def parse_pseudo_open(
+        self,
+        sel: _Selector,
+        name: str,
+        has_selector: bool,
+        iselector: Iterator[tuple[str, Match[str]]],
+        index: int
+    ) -> bool:
+        """Parse pseudo with opening bracket."""
+
+        flags = FLG_PSEUDO | FLG_OPEN
+        if name == ':not':
+            flags |= FLG_NOT
+        elif name == ':has':
+            flags |= FLG_RELATIVE
+        elif name in (':where', ':is'):
+            flags |= FLG_FORGIVE
+
+        sel.selectors.append(self.parse_selectors(iselector, index, flags))
+        has_selector = True
+
+        return has_selector
+
+    def parse_has_combinator(
+        self,
+        sel: _Selector,
+        m: Match[str],
+        has_selector: bool,
+        selectors: list[_Selector],
+        rel_type: str,
+        index: int
+    ) -> tuple[bool, _Selector, str]:
+        """Parse combinator tokens."""
+
+        combinator = m.group('relation').strip()
+        if not combinator:
+            combinator = WS_COMBINATOR
+        if combinator == COMMA_COMBINATOR:
+            if not has_selector:
+                raise SelectorSyntaxError(
+                    f"The combinator '{combinator}' at position {index}, must have a selector before it",
+                    self.pattern,
+                    index
+                )
+            sel.rel_type = rel_type
+            selectors[-1].relations.append(sel)
+            rel_type = ":" + WS_COMBINATOR
+            selectors.append(_Selector())
+        else:
+            if has_selector:
+                # End the current selector and associate the leading combinator with this selector.
+                sel.rel_type = rel_type
+                selectors[-1].relations.append(sel)
+            elif rel_type[1:] != WS_COMBINATOR:
+                # It's impossible to have two whitespace combinators after each other as the patterns
+                # will gobble up trailing whitespace. It is also impossible to have a whitespace
+                # combinator after any other kind for the same reason. But we could have
+                # multiple non-whitespace combinators. So if the current combinator is not a whitespace,
+                # then we've hit the multiple combinator case, so we should fail.
+                raise SelectorSyntaxError(
+                    f'The multiple combinators at position {index}',
+                    self.pattern,
+                    index
+                )
+
+            # Set the leading combinator for the next selector.
+            rel_type = ':' + combinator
+
+        sel = _Selector()
+        has_selector = False
+        return has_selector, sel, rel_type
+
+    def parse_combinator(
+        self,
+        sel: _Selector,
+        m: Match[str],
+        has_selector: bool,
+        selectors: list[_Selector],
+        relations: list[_Selector],
+        is_pseudo: bool,
+        is_forgive: bool,
+        index: int
+    ) -> tuple[bool, _Selector]:
+        """Parse combinator tokens."""
+
+        combinator = m.group('relation').strip()
+        if not combinator:
+            combinator = WS_COMBINATOR
+        if not has_selector:
+            if not is_forgive or combinator != COMMA_COMBINATOR:
+                raise SelectorSyntaxError(
+                    f"The combinator '{combinator}' at position {index}, must have a selector before it",
+                    self.pattern,
+                    index
+                )
+
+            # If we are in a forgiving pseudo class, just make the selector a "no match"
+            if combinator == COMMA_COMBINATOR:
+                self.increment_count()
+                del relations[:]
+        else:
+            if combinator == COMMA_COMBINATOR:
+                if not sel.tag and not is_pseudo:
+                    # Implied `*`
+                    sel.tag = ct.SelectorTag('*', None)
+                sel.relations.extend(relations)
+                selectors.append(sel)
+                del relations[:]
+            else:
+                sel.relations.extend(relations)
+                sel.rel_type = combinator
+                del relations[:]
+                relations.append(sel)
+
+        sel = _Selector()
+        has_selector = False
+
+        return has_selector, sel
+
+    def parse_class_id(self, sel: _Selector, m: Match[str], has_selector: bool) -> bool:
+        """Parse HTML classes and ids."""
+
+        selector = m.group(0)
+        if selector.startswith('.'):
+            sel.classes.append(css_unescape(selector[1:]))
+        else:
+            sel.ids.append(css_unescape(selector[1:]))
+        has_selector = True
+        return has_selector
+
+    def parse_pseudo_contains(self, sel: _Selector, m: Match[str], has_selector: bool) -> bool:
+        """Parse contains."""
+
+        pseudo = util.lower(css_unescape(m.group('name')))
+        if pseudo == ":contains":
+            warnings.warn(  # noqa: B028
+                "The pseudo class ':contains' is deprecated, ':-soup-contains' should be used moving forward.",
+                FutureWarning
+            )
+        contains_own = pseudo == ":-soup-contains-own"
+        patterns = [
+            css_unescape(token.group('value'))
+            for token in RE_VALUES.finditer(m.group('values'))
+            if not token.group('split')
+        ]
+        sel.contains.append(ct.SelectorContains(patterns, contains_own))
+        has_selector = True
+        return has_selector
+
+    def parse_pseudo_lang(self, sel: _Selector, m: Match[str], has_selector: bool) -> bool:
+        """Parse pseudo language."""
+
+        patterns = [
+            css_unescape(token.group('value'))
+            for token in RE_VALUES.finditer(m.group('values'))
+            if not token.group('split')
+        ]
+        sel.lang.append(ct.SelectorLang(patterns))
+        has_selector = True
+
+        return has_selector
+
+    def parse_pseudo_dir(self, sel: _Selector, m: Match[str], has_selector: bool) -> bool:
+        """Parse pseudo direction."""
+
+        value = ct.SEL_DIR_LTR if util.lower(m.group('dir')) == 'ltr' else ct.SEL_DIR_RTL
+        sel.flags |= value
+        has_selector = True
+        return has_selector
+
+    def parse_selectors(
+        self,
+        iselector: Iterator[tuple[str, Match[str]]],
+        index: int = 0,
+        flags: int = 0
+    ) -> ct.SelectorList:
+        """Parse selectors."""
+
+        # Initialize important variables
+        sel = _Selector()
+        selectors = []
+        has_selector = False
+        closed = False
+        relations = []  # type: list[_Selector]
+        rel_type = ":" + WS_COMBINATOR
+        count = self.count
+
+        # Setup various flags
+        is_open = bool(flags & FLG_OPEN)
+        is_pseudo = bool(flags & FLG_PSEUDO)
+        is_relative = bool(flags & FLG_RELATIVE)
+        is_not = bool(flags & FLG_NOT)
+        is_html = bool(flags & FLG_HTML)
+        is_default = bool(flags & FLG_DEFAULT)
+        is_indeterminate = bool(flags & FLG_INDETERMINATE)
+        is_in_range = bool(flags & FLG_IN_RANGE)
+        is_out_of_range = bool(flags & FLG_OUT_OF_RANGE)
+        is_placeholder_shown = bool(flags & FLG_PLACEHOLDER_SHOWN)
+        is_forgive = bool(flags & FLG_FORGIVE)
+
+        # Print out useful debug stuff
+        if self.debug:  # pragma: no cover
+            if is_pseudo:
+                print('    is_pseudo: True')
+            if is_open:
+                print('    is_open: True')
+            if is_relative:
+                print('    is_relative: True')
+            if is_not:
+                print('    is_not: True')
+            if is_html:
+                print('    is_html: True')
+            if is_default:
+                print('    is_default: True')
+            if is_indeterminate:
+                print('    is_indeterminate: True')
+            if is_in_range:
+                print('    is_in_range: True')
+            if is_out_of_range:
+                print('    is_out_of_range: True')
+            if is_placeholder_shown:
+                print('    is_placeholder_shown: True')
+            if is_forgive:
+                print('    is_forgive: True')
+
+        # The algorithm for relative selectors require an initial selector in the selector list
+        if is_relative:
+            selectors.append(_Selector())
+
+        try:
+            while True:
+                key, m = next(iselector)
+
+                if key not in ('combine', 'pseudo_close'):
+                    self.increment_count()
+
+                # Handle parts
+                if key == "at_rule":
+                    raise NotImplementedError(f"At-rules found at position {m.start(0)}")
+                elif key == "amp":
+                    sel.flags |= ct.SEL_SCOPE
+                    has_selector = True
+                elif key == 'pseudo_class_custom':
+                    has_selector = self.parse_pseudo_class_custom(sel, m, has_selector)
+                elif key == 'pseudo_class':
+                    has_selector, is_html = self.parse_pseudo_class(sel, m, has_selector, iselector, is_html)
+                elif key == 'pseudo_element':
+                    raise NotImplementedError(f"Pseudo-element found at position {m.start(0)}")
+                elif key == 'pseudo_contains':
+                    has_selector = self.parse_pseudo_contains(sel, m, has_selector)
+                elif key in ('pseudo_nth_type', 'pseudo_nth_child'):
+                    has_selector = self.parse_pseudo_nth(sel, m, has_selector, iselector)
+                elif key == 'pseudo_lang':
+                    has_selector = self.parse_pseudo_lang(sel, m, has_selector)
+                elif key == 'pseudo_dir':
+                    has_selector = self.parse_pseudo_dir(sel, m, has_selector)
+                    # Currently only supports HTML
+                    is_html = True
+                elif key == 'pseudo_close':
+                    if not has_selector:
+                        if not is_forgive:
+                            raise SelectorSyntaxError(
+                                f"Expected a selector at position {m.start(0)}",
+                                self.pattern,
+                                m.start(0)
+                            )
+                        sel.no_match = True
+                    if is_open:
+                        closed = True
+                        break
+                    else:
+                        raise SelectorSyntaxError(
+                            f"Unmatched pseudo-class close at position {m.start(0)}",
+                            self.pattern,
+                            m.start(0)
+                        )
+                elif key == 'combine':
+                    if is_relative:
+                        has_selector, sel, rel_type = self.parse_has_combinator(
+                            sel, m, has_selector, selectors, rel_type, index
+                        )
+                    else:
+                        has_selector, sel = self.parse_combinator(
+                            sel, m, has_selector, selectors, relations, is_pseudo, is_forgive, index
+                        )
+                elif key == 'attribute':
+                    has_selector = self.parse_attribute_selector(sel, m, has_selector)
+                elif key == 'tag':
+                    if has_selector:
+                        raise SelectorSyntaxError(
+                            f"Tag name found at position {m.start(0)} instead of at the start",
+                            self.pattern,
+                            m.start(0)
+                        )
+                    has_selector = self.parse_tag_pattern(sel, m, has_selector)
+                elif key in ('class', 'id'):
+                    has_selector = self.parse_class_id(sel, m, has_selector)
+
+                index = m.end(0)
+        except StopIteration:
+            pass
+
+        # Handle selectors that are not closed
+        if is_open and not closed:
+            raise SelectorSyntaxError(
+                f"Unclosed pseudo-class at position {index}",
+                self.pattern,
+                index
+            )
+
+        # Cleanup completed selector piece
+        if has_selector:
+            if not sel.tag and not is_pseudo:
+                # Implied `*`
+                sel.tag = ct.SelectorTag('*', None)
+            if is_relative:
+                sel.rel_type = rel_type
+                selectors[-1].relations.append(sel)
+            else:
+                sel.relations.extend(relations)
+                del relations[:]
+                selectors.append(sel)
+
+        # Forgive empty slots in pseudo-classes that have lists (and are forgiving)
+        elif is_forgive and (not selectors or not relations):
+            # Handle normal pseudo-classes with empty slots like `:is()` etc.
+            self.increment_count()
+            sel.no_match = True
+            del relations[:]
+            selectors.append(sel)
+            has_selector = True
+
+        if not has_selector:
+            # We will always need to finish a selector when `:has()` is used as it leads with combining.
+            # May apply to others as well.
+            raise SelectorSyntaxError(
+                f'Expected a selector at position {index}',
+                self.pattern,
+                index
+            )
+
+        # Some patterns require additional logic, such as default. We try to make these the
+        # last pattern, and append the appropriate flag to that selector which communicates
+        # to the matcher what additional logic is required.
+        if is_default:
+            selectors[-1].flags = ct.SEL_DEFAULT
+        if is_indeterminate:
+            selectors[-1].flags = ct.SEL_INDETERMINATE
+        if is_in_range:
+            selectors[-1].flags = ct.SEL_IN_RANGE
+        if is_out_of_range:
+            selectors[-1].flags = ct.SEL_OUT_OF_RANGE
+        if is_placeholder_shown:
+            selectors[-1].flags = ct.SEL_PLACEHOLDER_SHOWN
+
+        # Return selector list
+        return ct.SelectorList([s.freeze() for s in selectors], is_not, is_html, self.count - count)
+
+    def selector_iter(self, pattern: str) -> Iterator[tuple[str, Match[str]]]:
+        """Iterate selector tokens."""
+
+        # Ignore whitespace and comments at start and end of pattern
+        m = RE_WS_BEGIN.search(pattern)
+        index = m.end(0) if m else 0
+        m = RE_WS_END.search(pattern[::-1])
+        offset = m.end(0) if m else 0
+        end = len(pattern) - (1 + offset)
+
+        if self.debug:  # pragma: no cover
+            print(f'## PARSING: {pattern!r}')
+        while index <= end:
+            m = None
+            for v in self.CSS_TOKENS:
+                m = v.match(pattern, index, self.flags)
+                if m:
+                    name = v.get_name()
+                    if self.debug:  # pragma: no cover
+                        print(f"TOKEN: '{name}' --> {m.group(0)!r} at position {m.start(0)}")
+                    index = m.end(0)
+                    yield name, m
+                    break
+            if m is None:
+                c = pattern[index]
+                # If the character represents the start of one of the known selector types,
+                # throw an exception mentioning that the known selector type is in error;
+                # otherwise, report the invalid character.
+                if c == '[':
+                    msg = f"Malformed attribute selector at position {index}"
+                elif c == '.':
+                    msg = f"Malformed class selector at position {index}"
+                elif c == '#':
+                    msg = f"Malformed id selector at position {index}"
+                elif c == ':':
+                    msg = f"Malformed pseudo-class selector at position {index}"
+                else:
+                    msg = f"Invalid character {c!r} position {index}"
+                raise SelectorSyntaxError(msg, self.pattern, index)
+        if self.debug:  # pragma: no cover
+            print('## END PARSING')
+
+    def process_selectors(self, index: int = 0, flags: int = 0) -> ct.SelectorList:
+        """Process selectors."""
+
+        return self.parse_selectors(self.selector_iter(self.pattern), index, flags)
diff --git a/.venv/lib/python3.12/site-packages/soupsieve/css_types.py b/.venv/lib/python3.12/site-packages/soupsieve/css_types.py
new file mode 100644
index 0000000000000000000000000000000000000000..f1af46efed50fa26487e16df8e69895c9e6533aa
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/soupsieve/css_types.py
@@ -0,0 +1,410 @@
+"""CSS selector structure items."""
+from __future__ import annotations
+import copyreg
+from .pretty import pretty
+from typing import Any, Iterator, Hashable, Pattern, Iterable, Mapping
+
+__all__ = (
+    'Selector',
+    'SelectorNull',
+    'SelectorTag',
+    'SelectorAttribute',
+    'SelectorContains',
+    'SelectorNth',
+    'SelectorLang',
+    'SelectorList',
+    'Namespaces',
+    'CustomSelectors'
+)
+
+
+SEL_EMPTY = 0x1
+SEL_ROOT = 0x2
+SEL_DEFAULT = 0x4
+SEL_INDETERMINATE = 0x8
+SEL_SCOPE = 0x10
+SEL_DIR_LTR = 0x20
+SEL_DIR_RTL = 0x40
+SEL_IN_RANGE = 0x80
+SEL_OUT_OF_RANGE = 0x100
+SEL_DEFINED = 0x200
+SEL_PLACEHOLDER_SHOWN = 0x400
+
+
+class Immutable:
+    """Immutable."""
+
+    __slots__: tuple[str, ...] = ('_hash',)
+
+    _hash: int
+
+    def __init__(self, **kwargs: Any) -> None:
+        """Initialize."""
+
+        temp = []
+        for k, v in kwargs.items():
+            temp.append(type(v))
+            temp.append(v)
+            super().__setattr__(k, v)
+        super().__setattr__('_hash', hash(tuple(temp)))
+
+    @classmethod
+    def __base__(cls) -> type[Immutable]:
+        """Get base class."""
+
+        return cls
+
+    def __eq__(self, other: Any) -> bool:
+        """Equal."""
+
+        return (
+            isinstance(other, self.__base__()) and
+            all(getattr(other, key) == getattr(self, key) for key in self.__slots__ if key != '_hash')
+        )
+
+    def __ne__(self, other: Any) -> bool:
+        """Equal."""
+
+        return (
+            not isinstance(other, self.__base__()) or
+            any(getattr(other, key) != getattr(self, key) for key in self.__slots__ if key != '_hash')
+        )
+
+    def __hash__(self) -> int:
+        """Hash."""
+
+        return self._hash
+
+    def __setattr__(self, name: str, value: Any) -> None:
+        """Prevent mutability."""
+
+        raise AttributeError(f"'{self.__class__.__name__}' is immutable")
+
+    def __repr__(self) -> str:  # pragma: no cover
+        """Representation."""
+
+        r = ', '.join([f"{k}={getattr(self, k)!r}" for k in self.__slots__[:-1]])
+        return f"{self.__class__.__name__}({r})"
+
+    __str__ = __repr__
+
+    def pretty(self) -> None:  # pragma: no cover
+        """Pretty print."""
+
+        print(pretty(self))
+
+
+class ImmutableDict(Mapping[Any, Any]):
+    """Hashable, immutable dictionary."""
+
+    def __init__(
+        self,
+        arg: dict[Any, Any] | Iterable[tuple[Any, Any]]
+    ) -> None:
+        """Initialize."""
+
+        self._validate(arg)
+        self._d = dict(arg)
+        self._hash = hash(tuple([(type(x), x, type(y), y) for x, y in sorted(self._d.items())]))
+
+    def _validate(self, arg: dict[Any, Any] | Iterable[tuple[Any, Any]]) -> None:
+        """Validate arguments."""
+
+        if isinstance(arg, dict):
+            if not all(isinstance(v, Hashable) for v in arg.values()):
+                raise TypeError(f'{self.__class__.__name__} values must be hashable')
+        elif not all(isinstance(k, Hashable) and isinstance(v, Hashable) for k, v in arg):
+            raise TypeError(f'{self.__class__.__name__} values must be hashable')
+
+    def __iter__(self) -> Iterator[Any]:
+        """Iterator."""
+
+        return iter(self._d)
+
+    def __len__(self) -> int:
+        """Length."""
+
+        return len(self._d)
+
+    def __getitem__(self, key: Any) -> Any:
+        """Get item: `namespace['key']`."""
+
+        return self._d[key]
+
+    def __hash__(self) -> int:
+        """Hash."""
+
+        return self._hash
+
+    def __repr__(self) -> str:  # pragma: no cover
+        """Representation."""
+
+        return f"{self._d!r}"
+
+    __str__ = __repr__
+
+
+class Namespaces(ImmutableDict):
+    """Namespaces."""
+
+    def __init__(self, arg: dict[str, str] | Iterable[tuple[str, str]]) -> None:
+        """Initialize."""
+
+        super().__init__(arg)
+
+    def _validate(self, arg: dict[str, str] | Iterable[tuple[str, str]]) -> None:
+        """Validate arguments."""
+
+        if not all(
+            isinstance(k, str) and isinstance(v, str)
+            for k, v in (arg.items() if isinstance(arg, dict) else arg)
+        ):
+            raise TypeError(f'{self.__class__.__name__} values must be hashable')
+
+
+class CustomSelectors(ImmutableDict):
+    """Custom selectors."""
+
+    def __init__(self, arg: dict[str, str] | Iterable[tuple[str, str]]) -> None:
+        """Initialize."""
+
+        super().__init__(arg)
+
+    def _validate(self, arg: dict[str, str] | Iterable[tuple[str, str]]) -> None:
+        """Validate arguments."""
+
+        if not all(
+            isinstance(k, str) and isinstance(v, str)
+            for k, v in (arg.items() if isinstance(arg, dict) else arg)
+        ):
+            raise TypeError(f'{self.__class__.__name__} values must be hashable')
+
+
+class Selector(Immutable):
+    """Selector."""
+
+    __slots__ = (
+        'tag', 'ids', 'classes', 'attributes', 'nth', 'selectors',
+        'relation', 'rel_type', 'contains', 'lang', 'flags', '_hash'
+    )
+
+    tag: SelectorTag | None
+    ids: tuple[str, ...]
+    classes: tuple[str, ...]
+    attributes: tuple[SelectorAttribute, ...]
+    nth: tuple[SelectorNth, ...]
+    selectors: tuple[SelectorList, ...]
+    relation: SelectorList
+    rel_type: str | None
+    contains: tuple[SelectorContains, ...]
+    lang: tuple[SelectorLang, ...]
+    flags: int
+
+    def __init__(
+        self,
+        tag: SelectorTag | None,
+        ids: tuple[str, ...],
+        classes: tuple[str, ...],
+        attributes: tuple[SelectorAttribute, ...],
+        nth: tuple[SelectorNth, ...],
+        selectors: tuple[SelectorList, ...],
+        relation: SelectorList,
+        rel_type: str | None,
+        contains: tuple[SelectorContains, ...],
+        lang: tuple[SelectorLang, ...],
+        flags: int
+    ):
+        """Initialize."""
+
+        super().__init__(
+            tag=tag,
+            ids=ids,
+            classes=classes,
+            attributes=attributes,
+            nth=nth,
+            selectors=selectors,
+            relation=relation,
+            rel_type=rel_type,
+            contains=contains,
+            lang=lang,
+            flags=flags
+        )
+
+
+class SelectorNull(Immutable):
+    """Null Selector."""
+
+    def __init__(self) -> None:
+        """Initialize."""
+
+        super().__init__()
+
+
+class SelectorTag(Immutable):
+    """Selector tag."""
+
+    __slots__ = ("name", "prefix", "_hash")
+
+    name: str
+    prefix: str | None
+
+    def __init__(self, name: str, prefix: str | None) -> None:
+        """Initialize."""
+
+        super().__init__(name=name, prefix=prefix)
+
+
+class SelectorAttribute(Immutable):
+    """Selector attribute rule."""
+
+    __slots__ = ("attribute", "prefix", "pattern", "xml_type_pattern", "_hash")
+
+    attribute: str
+    prefix: str
+    pattern: Pattern[str] | None
+    xml_type_pattern: Pattern[str] | None
+
+    def __init__(
+        self,
+        attribute: str,
+        prefix: str,
+        pattern: Pattern[str] | None,
+        xml_type_pattern: Pattern[str] | None
+    ) -> None:
+        """Initialize."""
+
+        super().__init__(
+            attribute=attribute,
+            prefix=prefix,
+            pattern=pattern,
+            xml_type_pattern=xml_type_pattern
+        )
+
+
+class SelectorContains(Immutable):
+    """Selector contains rule."""
+
+    __slots__ = ("text", "own", "_hash")
+
+    text: tuple[str, ...]
+    own: bool
+
+    def __init__(self, text: Iterable[str], own: bool) -> None:
+        """Initialize."""
+
+        super().__init__(text=tuple(text), own=own)
+
+
+class SelectorNth(Immutable):
+    """Selector nth type."""
+
+    __slots__ = ("a", "n", "b", "of_type", "last", "selectors", "_hash")
+
+    a: int
+    n: bool
+    b: int
+    of_type: bool
+    last: bool
+    selectors: SelectorList
+
+    def __init__(self, a: int, n: bool, b: int, of_type: bool, last: bool, selectors: SelectorList) -> None:
+        """Initialize."""
+
+        super().__init__(
+            a=a,
+            n=n,
+            b=b,
+            of_type=of_type,
+            last=last,
+            selectors=selectors
+        )
+
+
+class SelectorLang(Immutable):
+    """Selector language rules."""
+
+    __slots__ = ("languages", "_hash",)
+
+    languages: tuple[str, ...]
+
+    def __init__(self, languages: Iterable[str]):
+        """Initialize."""
+
+        super().__init__(languages=tuple(languages))
+
+    def __iter__(self) -> Iterator[str]:
+        """Iterator."""
+
+        return iter(self.languages)
+
+    def __len__(self) -> int:  # pragma: no cover
+        """Length."""
+
+        return len(self.languages)
+
+    def __getitem__(self, index: int) -> str:  # pragma: no cover
+        """Get item."""
+
+        return self.languages[index]
+
+
+class SelectorList(Immutable):
+    """Selector list."""
+
+    __slots__ = ("selectors", "is_not", "is_html", "count", "_hash")
+
+    selectors: tuple[Selector | SelectorNull, ...]
+    is_not: bool
+    is_html: bool
+    count: int
+
+    def __init__(
+        self,
+        selectors: Iterable[Selector | SelectorNull] | None = None,
+        is_not: bool = False,
+        is_html: bool = False,
+        count: int = 0,
+    ) -> None:
+        """Initialize."""
+
+        super().__init__(
+            selectors=tuple(selectors) if selectors is not None else (),
+            is_not=is_not,
+            is_html=is_html,
+            count=count
+        )
+
+    def __iter__(self) -> Iterator[Selector | SelectorNull]:
+        """Iterator."""
+
+        return iter(self.selectors)
+
+    def __len__(self) -> int:
+        """Length."""
+
+        return len(self.selectors)
+
+    def __getitem__(self, index: int) -> Selector | SelectorNull:
+        """Get item."""
+
+        return self.selectors[index]
+
+
+def _pickle(p: Any) -> Any:
+    return p.__base__(), tuple([getattr(p, s) for s in p.__slots__[:-1]])
+
+
+def pickle_register(obj: Any) -> None:
+    """Allow object to be pickled."""
+
+    copyreg.pickle(obj, _pickle)
+
+
+pickle_register(Selector)
+pickle_register(SelectorNull)
+pickle_register(SelectorTag)
+pickle_register(SelectorAttribute)
+pickle_register(SelectorContains)
+pickle_register(SelectorNth)
+pickle_register(SelectorLang)
+pickle_register(SelectorList)
diff --git a/.venv/lib/python3.12/site-packages/soupsieve/pretty.py b/.venv/lib/python3.12/site-packages/soupsieve/pretty.py
new file mode 100644
index 0000000000000000000000000000000000000000..37d51d8c2bfa0059654a68ab9bb359225932b1cb
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/soupsieve/pretty.py
@@ -0,0 +1,148 @@
+"""
+Format a pretty string of a `SoupSieve` object for easy debugging.
+
+This won't necessarily support all types and such, and definitely
+not support custom outputs.
+
+It is mainly geared towards our types as the `SelectorList`
+object is a beast to look at without some indentation and newlines.
+The format and various output types is fairly known (though it
+hasn't been tested extensively to make sure we aren't missing corners).
+
+Example:
+-------
+```
+>>> import soupsieve as sv
+>>> sv.compile('this > that.class[name=value]').selectors.pretty()
+SelectorList(
+    selectors=(
+        Selector(
+            tag=SelectorTag(
+                name='that',
+                prefix=None),
+            ids=(),
+            classes=(
+                'class',
+                ),
+            attributes=(
+                SelectorAttribute(
+                    attribute='name',
+                    prefix='',
+                    pattern=re.compile(
+                        '^value$'),
+                    xml_type_pattern=None),
+                ),
+            nth=(),
+            selectors=(),
+            relation=SelectorList(
+                selectors=(
+                    Selector(
+                        tag=SelectorTag(
+                            name='this',
+                            prefix=None),
+                        ids=(),
+                        classes=(),
+                        attributes=(),
+                        nth=(),
+                        selectors=(),
+                        relation=SelectorList(
+                            selectors=(),
+                            is_not=False,
+                            is_html=False),
+                        rel_type='>',
+                        contains=(),
+                        lang=(),
+                        flags=0),
+                    ),
+                is_not=False,
+                is_html=False),
+            rel_type=None,
+            contains=(),
+            lang=(),
+            flags=0),
+        ),
+    is_not=False,
+    is_html=False)
+```
+
+"""
+from __future__ import annotations
+import re
+from typing import Any
+
+RE_CLASS = re.compile(r'(?i)[a-z_][_a-z\d.]+\(')
+RE_PARAM = re.compile(r'(?i)[_a-z][_a-z\d]+=')
+RE_EMPTY = re.compile(r'\(\)|\[\]|\{\}')
+RE_LSTRT = re.compile(r'\[')
+RE_DSTRT = re.compile(r'\{')
+RE_TSTRT = re.compile(r'\(')
+RE_LEND = re.compile(r'\]')
+RE_DEND = re.compile(r'\}')
+RE_TEND = re.compile(r'\)')
+RE_INT = re.compile(r'\d+')
+RE_KWORD = re.compile(r'(?i)[_a-z][_a-z\d.]+')
+RE_DQSTR = re.compile(r'"(?:\\.|[^"\\])*"')
+RE_SQSTR = re.compile(r"'(?:\\.|[^'\\])*'")
+RE_SEP = re.compile(r'\s*(,)\s*')
+RE_DSEP = re.compile(r'\s*(:)\s*')
+RE_PSEP = re.compile(r'\s*(\|)\s*')
+
+TOKENS = {
+    'class': RE_CLASS,
+    'param': RE_PARAM,
+    'empty': RE_EMPTY,
+    'lstrt': RE_LSTRT,
+    'dstrt': RE_DSTRT,
+    'tstrt': RE_TSTRT,
+    'lend': RE_LEND,
+    'dend': RE_DEND,
+    'tend': RE_TEND,
+    'sqstr': RE_SQSTR,
+    'sep': RE_SEP,
+    'dsep': RE_DSEP,
+    'psep': RE_PSEP,
+    'int': RE_INT,
+    'kword': RE_KWORD,
+    'dqstr': RE_DQSTR
+}
+
+
+def pretty(obj: Any) -> str:  # pragma: no cover
+    """Make the object output string pretty."""
+
+    sel = str(obj)
+    index = 0
+    end = len(sel) - 1
+    indent = 0
+    output = []
+
+    while index <= end:
+        m = None
+        for k, v in TOKENS.items():
+            m = v.match(sel, index)
+
+            if m:
+                name = k
+                index = m.end(0)
+                if name in ('class', 'lstrt', 'dstrt', 'tstrt'):
+                    indent += 4
+                    output.append(f'{m.group(0)}\n{" " * indent}')
+                elif name in ('param', 'int', 'kword', 'sqstr', 'dqstr', 'empty'):
+                    output.append(m.group(0))
+                elif name in ('lend', 'dend', 'tend'):
+                    indent -= 4
+                    output.append(m.group(0))
+                elif name in ('sep',):
+                    output.append(f'{m.group(1)}\n{" " * indent}')
+                elif name in ('dsep',):
+                    output.append(f'{m.group(1)} ')
+                elif name in ('psep'):
+                    output.append(f' {m.group(1)} ')
+                break
+
+        # We shouldn't hit this, but if we do, store unrecognized character
+        if m is None:  # pragma: no cover
+            output.append(sel[index])
+            index += 1
+
+    return ''.join(output)
diff --git a/.venv/lib/python3.12/site-packages/soupsieve/py.typed b/.venv/lib/python3.12/site-packages/soupsieve/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/soupsieve/util.py b/.venv/lib/python3.12/site-packages/soupsieve/util.py
new file mode 100644
index 0000000000000000000000000000000000000000..9b2e64df22bd3c9259af5273b412d356d6d889c1
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/soupsieve/util.py
@@ -0,0 +1,117 @@
+"""Utility."""
+from __future__ import annotations
+from functools import wraps, lru_cache
+import warnings
+import re
+from typing import Callable, Any
+
+DEBUG = 0x00001
+
+RE_PATTERN_LINE_SPLIT = re.compile(r'(?:\r\n|(?!\r\n)[\n\r])|$')
+
+UC_A = ord('A')
+UC_Z = ord('Z')
+
+
+@lru_cache(maxsize=512)
+def lower(string: str) -> str:
+    """Lower."""
+
+    new_string = []
+    for c in string:
+        o = ord(c)
+        new_string.append(chr(o + 32) if UC_A <= o <= UC_Z else c)
+    return ''.join(new_string)
+
+
+class SelectorSyntaxError(Exception):
+    """Syntax error in a CSS selector."""
+
+    def __init__(self, msg: str, pattern: str | None = None, index: int | None = None) -> None:
+        """Initialize."""
+
+        self.line = None
+        self.col = None
+        self.context = None
+
+        if pattern is not None and index is not None:
+            # Format pattern to show line and column position
+            self.context, self.line, self.col = get_pattern_context(pattern, index)
+            msg = f'{msg}\n  line {self.line}:\n{self.context}'
+
+        super().__init__(msg)
+
+
+def deprecated(message: str, stacklevel: int = 2) -> Callable[..., Any]:  # pragma: no cover
+    """
+    Raise a `DeprecationWarning` when wrapped function/method is called.
+
+    Usage:
+
+        @deprecated("This method will be removed in version X; use Y instead.")
+        def some_method()"
+            pass
+    """
+
+    def _wrapper(func: Callable[..., Any]) -> Callable[..., Any]:
+        @wraps(func)
+        def _deprecated_func(*args: Any, **kwargs: Any) -> Any:
+            warnings.warn(
+                f"'{func.__name__}' is deprecated. {message}",
+                category=DeprecationWarning,
+                stacklevel=stacklevel
+            )
+            return func(*args, **kwargs)
+        return _deprecated_func
+    return _wrapper
+
+
+def warn_deprecated(message: str, stacklevel: int = 2) -> None:  # pragma: no cover
+    """Warn deprecated."""
+
+    warnings.warn(
+        message,
+        category=DeprecationWarning,
+        stacklevel=stacklevel
+    )
+
+
+def get_pattern_context(pattern: str, index: int) -> tuple[str, int, int]:
+    """Get the pattern context."""
+
+    last = 0
+    current_line = 1
+    col = 1
+    text = []  # type: list[str]
+    line = 1
+    offset = None  # type: int | None
+
+    # Split pattern by newline and handle the text before the newline
+    for m in RE_PATTERN_LINE_SPLIT.finditer(pattern):
+        linetext = pattern[last:m.start(0)]
+        if not len(m.group(0)) and not len(text):
+            indent = ''
+            offset = -1
+            col = index - last + 1
+        elif last <= index < m.end(0):
+            indent = '--> '
+            offset = (-1 if index > m.start(0) else 0) + 3
+            col = index - last + 1
+        else:
+            indent = '    '
+            offset = None
+        if len(text):
+            # Regardless of whether we are presented with `\r\n`, `\r`, or `\n`,
+            # we will render the output with just `\n`. We will still log the column
+            # correctly though.
+            text.append('\n')
+        text.append(f'{indent}{linetext}')
+        if offset is not None:
+            text.append('\n')
+            text.append(' ' * (col + offset) + '^')
+            line = current_line
+
+        current_line += 1
+        last = m.end(0)
+
+    return ''.join(text), line, col
diff --git a/.venv/lib/python3.12/site-packages/supervision-0.30.5.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/supervision-0.30.5.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/supervision-0.30.5.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/.venv/lib/python3.12/site-packages/supervision-0.30.5.dist-info/METADATA b/.venv/lib/python3.12/site-packages/supervision-0.30.5.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..dc0b7735eb231724e2ee8ff66c2074bcb63f61b2
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/supervision-0.30.5.dist-info/METADATA
@@ -0,0 +1,371 @@
+Metadata-Version: 2.4
+Name: supervision
+Version: 0.30.5
+Summary: A set of easy-to-use utils that will come in handy in any Computer Vision project
+Author-email: "Roboflow et al." 
+Maintainer-email: Piotr Skalski 
+License-Expression: MIT
+Project-URL: Documentation, https://supervision.roboflow.com/latest/
+Project-URL: Homepage, https://github.com/roboflow/supervision
+Project-URL: Repository, https://github.com/roboflow/supervision
+Keywords: AI,deep-learning,DL,machine-learning,ML,Roboflow,vision
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: Intended Audience :: Education
+Classifier: Intended Audience :: Science/Research
+Classifier: Operating System :: MacOS
+Classifier: Operating System :: Microsoft :: Windows
+Classifier: Operating System :: POSIX :: Linux
+Classifier: Programming Language :: Python :: 3 :: Only
+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: Programming Language :: Python :: 3.14
+Classifier: Topic :: Multimedia :: Graphics
+Classifier: Topic :: Multimedia :: Video
+Classifier: Topic :: Scientific/Engineering
+Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
+Classifier: Topic :: Scientific/Engineering :: Image Recognition
+Classifier: Topic :: Software Development
+Classifier: Typing :: Typed
+Requires-Python: >=3.10
+Description-Content-Type: text/markdown
+License-File: LICENSE.md
+Requires-Dist: av>=14.2
+Requires-Dist: defusedxml>=0.7.1
+Requires-Dist: matplotlib>=3.6
+Requires-Dist: numpy>=1.21.2
+Requires-Dist: pillow>=9.4
+Requires-Dist: pydeprecate<0.12,>=0.9
+Requires-Dist: pyyaml>=5.3
+Requires-Dist: requests>=2.26
+Requires-Dist: scipy>=1.10
+Requires-Dist: tqdm>=4.62.3
+Provides-Extra: geotiff
+Requires-Dist: rasterio>=1.3; extra == "geotiff"
+Provides-Extra: metrics
+Requires-Dist: pandas>=2; extra == "metrics"
+Dynamic: license-file
+
+
+
+
+📑 Table of Contents + +- [👋 Hello](#-hello) +- [💻 Install](#-install) +- [🔥 Quickstart](#-quickstart) + - [Models](#models) + - [Annotators](#annotators) + - [Datasets](#datasets) +- [🎬 Tutorials](#-tutorials) +- [💜 Built with Supervision](#-built-with-supervision) +- [📚 Documentation](#-documentation) +- [🏆 Contribution](#-contribution) + +
+ +## 👋 Hello + +**We are your essential toolkit for computer vision.** From data loading to real-time zone counting, we provide the building blocks so you can focus on building applications around your models. 🤝 + +## 💻 Install + +Pip install the supervision package in a [**Python>=3.10**](https://www.python.org/) environment. + +```bash +pip install supervision +``` + +Read more about conda, mamba, and installing from source in our [guide](https://supervision.roboflow.com/). + +## 🔥 Quickstart + +### Models + +Supervision was designed to be model agnostic. Just plug in any classification, detection, or segmentation model. For your convenience, we have created [connectors](https://supervision.roboflow.com/latest/detection/core/#detections) for the most popular libraries like Ultralytics, Transformers, MMDetection, or Inference. Other integrations, like `rfdetr`, already return `sv.Detections` directly. + +Install the optional dependencies for this example with `pip install pillow rfdetr`. + +```python +import supervision as sv +from PIL import Image +from rfdetr import RFDETRSmall + +image = Image.open("path/to/image.jpg") +model = RFDETRSmall() +detections = model.predict(image, threshold=0.5) + +len(detections) +# 5 +``` + +
+👉 more model connectors + +- inference + + Running with [Inference](https://github.com/roboflow/inference) requires a [Roboflow API KEY](https://docs.roboflow.com/api-reference/authentication#retrieve-an-api-key). + + ```python + import supervision as sv + from PIL import Image + from inference import get_model + + image = Image.open("path/to/image.jpg") + model = get_model(model_id="rfdetr-small", api_key="ROBOFLOW_API_KEY") + result = model.infer(image)[0] + detections = sv.Detections.from_inference(result) + + len(detections) + # 5 + ``` + +
+ +### Annotators + +Supervision offers a wide range of highly customizable [annotators](https://supervision.roboflow.com/latest/detection/annotators/), allowing you to compose the perfect visualization for your use case. + +```python +import cv2 +import supervision as sv + +image = cv2.imread("path/to/image.jpg") +# Assuming detections are obtained from a model +detections = sv.Detections(...) + +box_annotator = sv.BoxAnnotator() +annotated_frame = box_annotator.annotate(scene=image.copy(), detections=detections) +``` + +https://github.com/roboflow/supervision/assets/26109316/691e219c-0565-4403-9218-ab5644f39bce + +### Datasets + +Supervision provides a set of [utils](https://supervision.roboflow.com/latest/datasets/core/) that allow you to load, split, merge, and save datasets in one of the supported formats. + +```python +import supervision as sv +from roboflow import Roboflow + +project = Roboflow().workspace("WORKSPACE_ID").project("PROJECT_ID") +dataset = project.version("PROJECT_VERSION").download("coco") + +ds = sv.DetectionDataset.from_coco( + images_directory_path=f"{dataset.location}/train", + annotations_path=f"{dataset.location}/train/_annotations.coco.json", +) + +path, image, annotation = ds[0] +# loads image on demand + +for path, image, annotation in ds: + # loads image on demand + pass +``` + +
+👉 more dataset utils + +- load + + ```python + dataset = sv.DetectionDataset.from_yolo( + images_directory_path=..., + annotations_directory_path=..., + data_yaml_path=..., + ) + + dataset = sv.DetectionDataset.from_pascal_voc( + images_directory_path=..., + annotations_directory_path=..., + ) + + dataset = sv.DetectionDataset.from_coco( + images_directory_path=..., + annotations_path=..., + ) + ``` + +- split + + ```python + train_dataset, test_dataset = dataset.split(split_ratio=0.7) + test_dataset, valid_dataset = test_dataset.split(split_ratio=0.5) + + len(train_dataset), len(test_dataset), len(valid_dataset) + # (700, 150, 150) + ``` + +- merge + + ```python + ds_1 = sv.DetectionDataset(...) + len(ds_1) + # 100 + ds_1.classes + # ['dog', 'person'] + + ds_2 = sv.DetectionDataset(...) + len(ds_2) + # 200 + ds_2.classes + # ['cat'] + + ds_merged = sv.DetectionDataset.merge([ds_1, ds_2]) + len(ds_merged) + # 300 + ds_merged.classes + # ['cat', 'dog', 'person'] + ``` + +- save + + ```python + dataset.as_yolo( + images_directory_path=..., + annotations_directory_path=..., + data_yaml_path=..., + ) + + dataset.as_pascal_voc( + images_directory_path=..., + annotations_directory_path=..., + ) + + dataset.as_coco( + images_directory_path=..., + annotations_path=..., + ) + ``` + +- convert + + ```python + sv.DetectionDataset.from_yolo( + images_directory_path=..., + annotations_directory_path=..., + data_yaml_path=..., + ).as_pascal_voc( + images_directory_path=..., + annotations_directory_path=..., + ) + ``` + +
+ +## 🎬 Tutorials + +Want to learn how to use Supervision? Explore our [how-to guides](https://supervision.roboflow.com/develop/how_to/detect_and_annotate/), [end-to-end examples](https://github.com/roboflow/supervision/tree/0.30.5/examples), [cheatsheet](https://roboflow.github.io/cheatsheet-supervision/), and [cookbooks](https://supervision.roboflow.com/develop/cookbooks/)! + +
+ +

+Dwell Time Analysis with Computer Vision | Real-Time Stream Processing +Dwell Time Analysis with Computer Vision | Real-Time Stream Processing +

Created: 5 Apr 2024
+
Learn how to use computer vision to analyze wait times and optimize processes. This tutorial covers object detection, tracking, and calculating time spent in designated zones. Use these techniques to improve customer experience in retail, traffic management, or other scenarios.

+ +
+ +

+Speed Estimation & Vehicle Tracking | Computer Vision | Open Source +Speed Estimation & Vehicle Tracking | Computer Vision | Open Source +

Created: 11 Jan 2024
+
Learn how to track and estimate the speed of vehicles using YOLO, ByteTrack, and Roboflow Inference. This comprehensive tutorial covers object detection, multi-object tracking, filtering detections, perspective transformation, speed estimation, visualization improvements, and more.

+ +## 💜 Built with Supervision + +Did you build something cool using supervision? [Let us know!](https://github.com/roboflow/supervision/discussions/categories/built-with-supervision) + +https://user-images.githubusercontent.com/26109316/207858600-ee862b22-0353-440b-ad85-caa0c4777904.mp4 + +https://github.com/roboflow/supervision/assets/26109316/c9436828-9fbf-4c25-ae8c-60e9c81b3900 + +https://github.com/roboflow/supervision/assets/26109316/3ac6982f-4943-4108-9b7f-51787ef1a69f + +## 📚 Documentation + +Visit our [documentation](https://supervision.roboflow.com/) page to learn how supervision can help you build computer vision applications faster and more reliably. + +## 🏆 Contribution + +We love your input! Please see our [contributing guide](https://github.com/roboflow/supervision/blob/0.30.5/.github/CONTRIBUTING.md) to get started. Thank you 🙏 to all our contributors! + +

+ + + +

+ +
+ + diff --git a/.venv/lib/python3.12/site-packages/supervision-0.30.5.dist-info/RECORD b/.venv/lib/python3.12/site-packages/supervision-0.30.5.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..d620148114bde271797b5bc853a43b19683023c0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision-0.30.5.dist-info/RECORD @@ -0,0 +1,204 @@ +supervision-0.30.5.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +supervision-0.30.5.dist-info/METADATA,sha256=MBdGOgq10ROpRSZEauoYeZ8YVGDZt1OiIasYY8gN_Hw,14482 +supervision-0.30.5.dist-info/RECORD,, +supervision-0.30.5.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +supervision-0.30.5.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91 +supervision-0.30.5.dist-info/licenses/LICENSE.md,sha256=crsAn5Yzr5eNpsSfOpJ6g9BN347ZkkkvbypiEi3pUic,1065 +supervision-0.30.5.dist-info/top_level.txt,sha256=nNqFJ85TSqQKq94IDlLXkOAaKzj8ztNvXJQKeU00KcE,12 +supervision/__init__.py,sha256=4RcLn7JSSWlSvFn8UnSIzOIJ_zxaA4BfBVzLSgWoBjE,8244 +supervision/__pycache__/__init__.cpython-312.pyc,, +supervision/__pycache__/config.cpython-312.pyc,, +supervision/_cv2/__init__.py,sha256=tTC_T5d7WuQXNqvUW8JAiGPP7Fvp9O8NoVygij9_UCM,8608 +supervision/_cv2/__pycache__/__init__.cpython-312.pyc,, +supervision/_cv2/__pycache__/_color.cpython-312.pyc,, +supervision/_cv2/__pycache__/_common.cpython-312.pyc,, +supervision/_cv2/__pycache__/_components.cpython-312.pyc,, +supervision/_cv2/__pycache__/_contours.cpython-312.pyc,, +supervision/_cv2/__pycache__/_drawing.cpython-312.pyc,, +supervision/_cv2/__pycache__/_geometry.cpython-312.pyc,, +supervision/_cv2/__pycache__/_image.cpython-312.pyc,, +supervision/_cv2/__pycache__/_text.cpython-312.pyc,, +supervision/_cv2/__pycache__/_transform.cpython-312.pyc,, +supervision/_cv2/__pycache__/_video.cpython-312.pyc,, +supervision/_cv2/__pycache__/constants.cpython-312.pyc,, +supervision/_cv2/_color.py,sha256=bEs4rvolS5IIboCAjDfAKU8pCnOmiL8GQE4C8idq0Bg,3526 +supervision/_cv2/_common.py,sha256=2_cmZZpRtIeJA9t2iFC0bkHDmrBqlQpputpYAiRBijs,687 +supervision/_cv2/_components.py,sha256=l-oUkTgP5wD3NW2aVPG7ob3DnKRurgFmxZGQ88W5Dhk,4335 +supervision/_cv2/_contours.py,sha256=Y3IoFy9aG4vmHi6AAA4YbQShCTBIqcmbM6p3mmUoXH0,5617 +supervision/_cv2/_drawing.py,sha256=U_4bfYf8ZRQiRokUN8A0mCkcqYe7yRtdIjzsyArTsS8,9309 +supervision/_cv2/_geometry.py,sha256=T2Fy6zgsG9yYSh_e-feCzBdxrf5RoTGt2vCWGeU2Neo,8556 +supervision/_cv2/_image.py,sha256=tktgOR0GziPM2X4VTm_kHioAzj9KzfHc9Cu2f6toe_0,13710 +supervision/_cv2/_text.py,sha256=fzYo7A0XXfqp03L8w58WWsh7B5TQKiJkb3fLRw-kBcg,4660 +supervision/_cv2/_transform.py,sha256=OaFb6egrO4AIMUqKSL6u1LLIB7KMKTkT3yw4khgp2kI,862 +supervision/_cv2/_video.py,sha256=rUab6Wiy9MrmGIMybyfjlMHV5m3NECVqJmhpnbJeTlw,17052 +supervision/_cv2/constants.py,sha256=zhRt1lXzwA6ooCyF8Y7lFlsxLmqTxs0_tkxBzW0N7c4,733 +supervision/annotators/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +supervision/annotators/__pycache__/__init__.cpython-312.pyc,, +supervision/annotators/__pycache__/base.cpython-312.pyc,, +supervision/annotators/__pycache__/core.cpython-312.pyc,, +supervision/annotators/__pycache__/utils.cpython-312.pyc,, +supervision/annotators/base.py,sha256=5NwXexOrZnrVWzTXx32DY2PTjguBEk14i4IyweD4MOg,571 +supervision/annotators/core.py,sha256=dcnYJ5-ecPXXABP4-2XZTbILUXra0ObEuPOgZT1OoYY,137426 +supervision/annotators/utils.py,sha256=02aFx6T4kmxhxpbPvCjLAlPCL8FRj9-BVvzWEDeuOAU,19748 +supervision/assets/__init__.py,sha256=oaFsA_n7Ah8kaH7PevI2u-Ra4-eAQo0MV_8EGNR-Lww,180 +supervision/assets/__pycache__/__init__.cpython-312.pyc,, +supervision/assets/__pycache__/downloader.cpython-312.pyc,, +supervision/assets/__pycache__/list.cpython-312.pyc,, +supervision/assets/downloader.py,sha256=wuiOWY5C2uEywJKRdBCHZByhU-WBr9HM9awIA_AQu3U,4562 +supervision/assets/list.py,sha256=WtlHibdQVuqvOUUvsWDyVIiabGTVhgY-MgGOYyGio8w,4553 +supervision/classification/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +supervision/classification/__pycache__/__init__.cpython-312.pyc,, +supervision/classification/__pycache__/core.cpython-312.pyc,, +supervision/classification/core.py,sha256=YCmcoEVkEFcEmFUv6NJAMDZr0pX4ykKJXGZYdhfvqWU,6842 +supervision/config.py,sha256=WZEb9OvLkCMEJOejhxP7aLXQQ_Z2ZGy3x3gVL-x6HrU,1483 +supervision/dataset/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +supervision/dataset/__pycache__/__init__.cpython-312.pyc,, +supervision/dataset/__pycache__/core.cpython-312.pyc,, +supervision/dataset/__pycache__/utils.cpython-312.pyc,, +supervision/dataset/core.py,sha256=BTgj-GWmvrecWkE5uIPfY0i8gEE14L8TJ_qfEjUfUn8,51288 +supervision/dataset/formats/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +supervision/dataset/formats/__pycache__/__init__.cpython-312.pyc,, +supervision/dataset/formats/__pycache__/coco.cpython-312.pyc,, +supervision/dataset/formats/__pycache__/createml.cpython-312.pyc,, +supervision/dataset/formats/__pycache__/labelme.cpython-312.pyc,, +supervision/dataset/formats/__pycache__/pascal_voc.cpython-312.pyc,, +supervision/dataset/formats/__pycache__/yolo.cpython-312.pyc,, +supervision/dataset/formats/coco.py,sha256=frDsucEymHGDonvLk6yJaZBX6a7YTT8KQYEhw81V9P0,30097 +supervision/dataset/formats/createml.py,sha256=-ZpWPzluyv5LArXqV11DoWRii5O593_tkOgFiz_VHxY,12729 +supervision/dataset/formats/labelme.py,sha256=dm7lVb70kAb-iz-bbzd-jxyQFjXFRH7gGTaJ6nSOHQQ,15132 +supervision/dataset/formats/pascal_voc.py,sha256=P-l-6jKPUYd-rK-t83nO8NeAkgc4M01jsD8WQ2gQqAw,18373 +supervision/dataset/formats/yolo.py,sha256=ECga7buR-O-kklzYi6utjw3JJAdFjCqF5ydpbKR1Bp8,20138 +supervision/dataset/utils.py,sha256=c31tXzI_xLqaNvc75UNRas5vwE9MRYbdN1ewrFZTRhI,10055 +supervision/detection/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +supervision/detection/__pycache__/__init__.cpython-312.pyc,, +supervision/detection/__pycache__/_geometry_dispatch.cpython-312.pyc,, +supervision/detection/__pycache__/compact_mask.cpython-312.pyc,, +supervision/detection/__pycache__/core.cpython-312.pyc,, +supervision/detection/__pycache__/line_zone.cpython-312.pyc,, +supervision/detection/__pycache__/vlm.cpython-312.pyc,, +supervision/detection/_geometry_dispatch.py,sha256=MShDimrCQUFIUpK9UJDdC50d6CLzTBimoyh7NxOgJkI,4169 +supervision/detection/compact_mask.py,sha256=CJvBhHHT_nbG9I739H6Z5vncVWfONm-GFYEkrx_crhM,65289 +supervision/detection/core.py,sha256=0VOv_ZdhH3R39aviS11ll93_P7xF8pGaLwPympCX5xE,137442 +supervision/detection/line_zone.py,sha256=7biteAT8VyCtCcDbPwiK8hRN3PB-VTArNfP-bviorbE,35786 +supervision/detection/tools/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +supervision/detection/tools/__pycache__/__init__.cpython-312.pyc,, +supervision/detection/tools/__pycache__/csv_sink.cpython-312.pyc,, +supervision/detection/tools/__pycache__/inference_slicer.cpython-312.pyc,, +supervision/detection/tools/__pycache__/json_sink.cpython-312.pyc,, +supervision/detection/tools/__pycache__/polygon_zone.cpython-312.pyc,, +supervision/detection/tools/__pycache__/smoother.cpython-312.pyc,, +supervision/detection/tools/__pycache__/transformers.cpython-312.pyc,, +supervision/detection/tools/csv_sink.py,sha256=zPLZz4wq2eWqR9ZvfwVe2FPU-cgEPz-MT5msk8Y5ums,10226 +supervision/detection/tools/inference_slicer.py,sha256=xq5t8rb2DeJyiARtOApuVel4p1ZKKZuCRmi71z47Bvc,39600 +supervision/detection/tools/json_sink.py,sha256=yyvY6ozqfEf63LniE7wHdmu6P77DpzXONMshjZScXvI,7623 +supervision/detection/tools/polygon_zone.py,sha256=oodHebXdUFifRTxe4lRz7D1F8tCjcCb3RPxj55ZY22c,10836 +supervision/detection/tools/smoother.py,sha256=Nn0O_Mxi6MspTat-1WqDYdpNxp6_MAeGaZu_hcZnOPU,9819 +supervision/detection/tools/transformers.py,sha256=CpfvTXiW8aRIwV_-AlWj45Fwo1RiWyF7CO8reweaL3U,10897 +supervision/detection/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +supervision/detection/utils/__pycache__/__init__.cpython-312.pyc,, +supervision/detection/utils/__pycache__/_typing.cpython-312.pyc,, +supervision/detection/utils/__pycache__/boxes.cpython-312.pyc,, +supervision/detection/utils/__pycache__/converters.cpython-312.pyc,, +supervision/detection/utils/__pycache__/internal.cpython-312.pyc,, +supervision/detection/utils/__pycache__/iou_and_nms.cpython-312.pyc,, +supervision/detection/utils/__pycache__/masks.cpython-312.pyc,, +supervision/detection/utils/__pycache__/polygons.cpython-312.pyc,, +supervision/detection/utils/__pycache__/vlms.cpython-312.pyc,, +supervision/detection/utils/_typing.py,sha256=EAeOnedx6Rx2MVLT8mdIOOKDj_rv-7R4gRdi8JKXqOo,264 +supervision/detection/utils/boxes.py,sha256=AC5dIvGYHPwL41wZ6huEEi98KF9JaSXUVm_P1yr9Z6I,22742 +supervision/detection/utils/converters.py,sha256=Y6yecvcUfBnWc73l6UTy2OIRNbI-ZgUeLSBcUt4Bex0,27878 +supervision/detection/utils/internal.py,sha256=a0T6AP4KpGcbVexq0Uzge80A92b76M5AA0Gd0aiDOSY,30748 +supervision/detection/utils/iou_and_nms.py,sha256=ywCWE8DGaIJfw60nEFvyki86gzp2s2bcsdfJVDQTOdw,73424 +supervision/detection/utils/masks.py,sha256=77KQrRfq7q9iux4UgU55AWq1MeCMtC759vla-jrq3Eo,23510 +supervision/detection/utils/polygons.py,sha256=mFmVgzJujuht95CzOlen4VwJf7EWSqojSkutFzwS_DQ,6227 +supervision/detection/utils/vlms.py,sha256=NlmiM2zDR_GUdw1hFT53NCiNwI4WRKf5qBVG8UCG9Lg,3018 +supervision/detection/vlm.py,sha256=KPIjBma_nQbIo_tmEOUcuSLUs_brP-87yUCs71ZVKr4,35251 +supervision/draw/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +supervision/draw/__pycache__/__init__.cpython-312.pyc,, +supervision/draw/__pycache__/base.cpython-312.pyc,, +supervision/draw/__pycache__/color.cpython-312.pyc,, +supervision/draw/__pycache__/utils.cpython-312.pyc,, +supervision/draw/base.py,sha256=N4lHOr-t-5u0tJ8wTefXAQDPh9_3glU-L2qXLLj25UY,420 +supervision/draw/color.py,sha256=POJUJhm2RRRHZ7kxyD8V6CndeBmQhsZzz8ACGOD7dVg,17209 +supervision/draw/utils.py,sha256=fRgH9ylcJm6_Lr5CBaCQB4NwPVlYj3xcHfZulgDyCeQ,17211 +supervision/geometry/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +supervision/geometry/__pycache__/__init__.cpython-312.pyc,, +supervision/geometry/__pycache__/core.cpython-312.pyc,, +supervision/geometry/__pycache__/utils.cpython-312.pyc,, +supervision/geometry/core.py,sha256=DMe_thCf9Hu49os9Z-CjOZEIxLPOW-8HZNdvjCtlA7g,5653 +supervision/geometry/utils.py,sha256=dlAEMp7Am1spj4uzbPuE4WeuPgvbpYBOe4fcGH1ogyI,1786 +supervision/key_points/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +supervision/key_points/__pycache__/__init__.cpython-312.pyc,, +supervision/key_points/__pycache__/annotators.cpython-312.pyc,, +supervision/key_points/__pycache__/core.cpython-312.pyc,, +supervision/key_points/__pycache__/skeletons.cpython-312.pyc,, +supervision/key_points/annotators.py,sha256=61VlOP2z4hS82zo5eYIoTXytdJuKRyneckd7amGBtxw,38984 +supervision/key_points/core.py,sha256=lZeButuAQoiKBVCHuoA0eab0VNtoeH1yVLHZ1WeRfQg,58170 +supervision/key_points/skeletons.py,sha256=tR-jTLI2KJwjpK3XKqbH9clYl9S_7IOIn7wMXgmrO3Y,51609 +supervision/keypoint/__init__.py,sha256=_gXhuYGKySHYGrnbsFFuHE-NzgGakHGaMfyOb1tBYrk,393 +supervision/keypoint/__pycache__/__init__.cpython-312.pyc,, +supervision/keypoint/__pycache__/annotators.cpython-312.pyc,, +supervision/keypoint/__pycache__/core.cpython-312.pyc,, +supervision/keypoint/annotators.py,sha256=o5Ioj69uAt-7TeOOZI3ryy7m6uYElHppVG1FRBTe0dc,390 +supervision/keypoint/core.py,sha256=cQ-EhJ9ez_O2xQ3M9b3HO2q6sgtmGf9jRAJJSRqp2kk,297 +supervision/metrics/__init__.py,sha256=chkwodiDqgcUHlCIPq3hd857Iz0cZv4UxNL4vwVVvjw,1044 +supervision/metrics/__pycache__/__init__.cpython-312.pyc,, +supervision/metrics/__pycache__/core.cpython-312.pyc,, +supervision/metrics/__pycache__/detection.cpython-312.pyc,, +supervision/metrics/__pycache__/f1_score.cpython-312.pyc,, +supervision/metrics/__pycache__/mean_average_precision.cpython-312.pyc,, +supervision/metrics/__pycache__/mean_average_recall.cpython-312.pyc,, +supervision/metrics/__pycache__/precision.cpython-312.pyc,, +supervision/metrics/__pycache__/recall.cpython-312.pyc,, +supervision/metrics/core.py,sha256=ajlMmN7Y4jICzxw6WdfdqxLhNE4hquVAWKEx8lRlrqg,2271 +supervision/metrics/detection.py,sha256=H6sR5mn0BzTuXCRA5eruczPC3zqUxmdO1isbo_0jgA4,61778 +supervision/metrics/f1_score.py,sha256=4n5wpuo8gD8TKdqYnLuB06K1dfGRurjK801JjsBn4qQ,33397 +supervision/metrics/mean_average_precision.py,sha256=rCUSxqu7wnbL3YJGm8GcvSP9OGMwsrftXo6DCL4rvdE,67626 +supervision/metrics/mean_average_recall.py,sha256=GgEuy0XUGENPISVWLpGSKbYcBi-aZEEkZkl1wx7xQCo,31516 +supervision/metrics/precision.py,sha256=EBz2xhpf5Vo6aJYGd8yx1xYB3WCRFekf1pmPzbBMfmU,33300 +supervision/metrics/recall.py,sha256=8dFjzDFa812dQNwphrsMrYGG3GdCxHn6N-kLSqCB8dg,34764 +supervision/metrics/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +supervision/metrics/utils/__pycache__/__init__.cpython-312.pyc,, +supervision/metrics/utils/__pycache__/matching.cpython-312.pyc,, +supervision/metrics/utils/__pycache__/object_size.cpython-312.pyc,, +supervision/metrics/utils/__pycache__/utils.cpython-312.pyc,, +supervision/metrics/utils/matching.py,sha256=c_2IuLrR1G6wksQik1ndi3wn6dORg3QEcJbukLBllRU,3699 +supervision/metrics/utils/object_size.py,sha256=k-Ui4_KFHe7Ut5XKxR9iihsz7feJ3WDwvP7G6PTDg9s,10787 +supervision/metrics/utils/utils.py,sha256=vbDk_5fdjnh90-9ApfrGWI-kbbp43zQDM-b-Q7kXAF0,317 +supervision/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +supervision/tracker/__init__.py,sha256=ZHw2RvnyqhXOXfFuZLIAuPMOc7FpO6brQfpJtjWAY6Q,134 +supervision/tracker/__pycache__/__init__.cpython-312.pyc,, +supervision/tracker/byte_tracker/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +supervision/tracker/byte_tracker/__pycache__/__init__.cpython-312.pyc,, +supervision/tracker/byte_tracker/__pycache__/core.cpython-312.pyc,, +supervision/tracker/byte_tracker/__pycache__/kalman_filter.cpython-312.pyc,, +supervision/tracker/byte_tracker/__pycache__/matching.cpython-312.pyc,, +supervision/tracker/byte_tracker/__pycache__/single_object_track.cpython-312.pyc,, +supervision/tracker/byte_tracker/__pycache__/utils.cpython-312.pyc,, +supervision/tracker/byte_tracker/core.py,sha256=AYkR3z3WAMegq70FkTixFhhaRY8rSHe0wf0y9cNByQ0,16117 +supervision/tracker/byte_tracker/kalman_filter.py,sha256=CPIyH-kkhMgQUIj6llMqdpUq4WoL6gVo8OJbAfOc-5Q,6644 +supervision/tracker/byte_tracker/matching.py,sha256=PLQoLXePvwDXjl6hzGwvHO9utbCtVGKM36ejbPzGSgg,2961 +supervision/tracker/byte_tracker/single_object_track.py,sha256=G7o8NHHfGxzwooz3LPoZXhNc81q8u__N-D-YY0dLM3E,6556 +supervision/tracker/byte_tracker/utils.py,sha256=RrAI277cdkZ5bu7LdciUxlvMIDaAvcNwMfIE-vCIxww,876 +supervision/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +supervision/utils/__pycache__/__init__.cpython-312.pyc,, +supervision/utils/__pycache__/conversion.cpython-312.pyc,, +supervision/utils/__pycache__/file.cpython-312.pyc,, +supervision/utils/__pycache__/image.cpython-312.pyc,, +supervision/utils/__pycache__/image_window.cpython-312.pyc,, +supervision/utils/__pycache__/internal.cpython-312.pyc,, +supervision/utils/__pycache__/iterables.cpython-312.pyc,, +supervision/utils/__pycache__/logger.cpython-312.pyc,, +supervision/utils/__pycache__/notebook.cpython-312.pyc,, +supervision/utils/__pycache__/video.cpython-312.pyc,, +supervision/utils/conversion.py,sha256=0Nzd3Yu9f8ksy3Vybssh9lKo0c40aj4g_E3jx4cZDqw,7313 +supervision/utils/file.py,sha256=Xz4Z8iVmNz6AxNJRw4-L3-8F5V-pcsr3wOfa3ahxobQ,10050 +supervision/utils/image.py,sha256=_p5o0gubouDZH0hA-DvasX_g840ZgZZEnYGpDauXyG4,40242 +supervision/utils/image_window.py,sha256=LCyQlkwCx85I4NdxQ0X4URsXwYv7G8KiyXhpdMHoz2E,12510 +supervision/utils/internal.py,sha256=ZYLO0Yv6gC3ZxhtFO5VWEEV9gcg2B8rk_Fix6h4Qc2o,6600 +supervision/utils/iterables.py,sha256=33Btb3nzYrL-ikwecRoi-IfXhnDfpbmrAbwB7M2Jy84,2882 +supervision/utils/logger.py,sha256=I9NKKsd_DvsrltS89vaz_knMJRmO8abfxffJCCc692o,2005 +supervision/utils/notebook.py,sha256=NBjfRf6eZSk319BuHeo4-nEP3l2FbqvSgFELtBVZcyw,3916 +supervision/utils/video.py,sha256=qCbOQ4MT_jmX3vXS8Hp431dDbyiDA39ac4SWxu6Lk_8,22901 +supervision/validators/__init__.py,sha256=Q-9YdbaF4sDmGktSA7n3K6mH0EjqxJmoe3-oHCAj0yg,11443 +supervision/validators/__pycache__/__init__.cpython-312.pyc,, diff --git a/.venv/lib/python3.12/site-packages/supervision-0.30.5.dist-info/REQUESTED b/.venv/lib/python3.12/site-packages/supervision-0.30.5.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/supervision-0.30.5.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/supervision-0.30.5.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..13013d7b49be5a84c3ee5931b06285b9553cf5d0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision-0.30.5.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (84.0.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/.venv/lib/python3.12/site-packages/supervision-0.30.5.dist-info/licenses/LICENSE.md b/.venv/lib/python3.12/site-packages/supervision-0.30.5.dist-info/licenses/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..ab7110e8f2f73a80097d40f3b6ba6da6ce3d942f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision-0.30.5.dist-info/licenses/LICENSE.md @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) 2022 Roboflow + +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.12/site-packages/supervision-0.30.5.dist-info/top_level.txt b/.venv/lib/python3.12/site-packages/supervision-0.30.5.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..43b821deee22603d6da796ef2da66d28a7f65d8c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision-0.30.5.dist-info/top_level.txt @@ -0,0 +1 @@ +supervision diff --git a/.venv/lib/python3.12/site-packages/supervision/__init__.py b/.venv/lib/python3.12/site-packages/supervision/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..77f4e9952473719e582cb425e22bcac5c7f37219 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/__init__.py @@ -0,0 +1,317 @@ +import importlib.metadata as importlib_metadata +from typing import TYPE_CHECKING, Any + +try: + # This will read version from pyproject.toml + __version__ = importlib_metadata.version(__package__ or __name__) +except importlib_metadata.PackageNotFoundError: + __version__ = "development" + +from supervision.annotators.core import ( + BackgroundOverlayAnnotator, + BlurAnnotator, + BoxAnnotator, + BoxCornerAnnotator, + CircleAnnotator, + ColorAnnotator, + ComparisonAnnotator, + CropAnnotator, + DotAnnotator, + EllipseAnnotator, + HaloAnnotator, + HeatMapAnnotator, + IconAnnotator, + LabelAnnotator, + MaskAnnotator, + OrientedBoxAnnotator, + PercentageBarAnnotator, + PixelateAnnotator, + PolygonAnnotator, + RichLabelAnnotator, + RoundBoxAnnotator, + TraceAnnotator, + TriangleAnnotator, +) +from supervision.annotators.utils import ( + ColorLookup, + hex_to_rgba, + is_valid_hex, + rgba_to_hex, +) +from supervision.classification.core import Classifications +from supervision.dataset.core import ( + BaseDataset, + ClassificationDataset, + DetectionDataset, +) +from supervision.dataset.formats.coco import get_coco_class_index_mapping +from supervision.detection.compact_mask import CompactMask +from supervision.detection.core import Detections +from supervision.detection.line_zone import ( + LineZone, + LineZoneAnnotator, + LineZoneAnnotatorMulticlass, +) +from supervision.detection.tools.csv_sink import CSVSink +from supervision.detection.tools.inference_slicer import ( + InferenceSlicer, + WindowedRasterDataset, +) +from supervision.detection.tools.json_sink import JSONSink +from supervision.detection.tools.polygon_zone import PolygonZone, PolygonZoneAnnotator +from supervision.detection.tools.smoother import DetectionsSmoother +from supervision.detection.utils.boxes import ( + clip_boxes, + denormalize_boxes, + move_boxes, + pad_boxes, + scale_boxes, + xyxyxyxy_to_xyxy, +) +from supervision.detection.utils.converters import ( + is_compressed_rle, + mask_to_polygons, + mask_to_rle, + mask_to_xyxy, + polygon_to_mask, + polygon_to_xyxy, + rle_to_mask, + xcycwh_to_xyxy, + xywh_to_xyxy, + xyxy_to_mask, + xyxy_to_polygons, + xyxy_to_xcycarh, + xyxy_to_xywh, +) +from supervision.detection.utils.iou_and_nms import ( + OverlapFilter, + OverlapMetric, + box_iou, + box_iou_batch, + box_iou_batch_with_jaccard, + box_non_max_merge, + box_non_max_suppression, + box_soft_non_max_suppression, + mask_iou_batch, + mask_non_max_merge, + mask_non_max_suppression, + mask_soft_non_max_suppression, + oriented_box_iou_batch, + oriented_box_non_max_merge, + oriented_box_non_max_suppression, +) +from supervision.detection.utils.masks import ( + calculate_masks_centroids, + contains_holes, + contains_multiple_segments, + filter_segments_by_distance, + mask_to_roi, + move_masks, +) +from supervision.detection.utils.polygons import ( + approximate_polygon, + filter_polygons_by_area, +) +from supervision.detection.utils.vlms import edit_distance, fuzzy_match_index +from supervision.detection.vlm import LMM, VLM +from supervision.draw.color import Color, ColorPalette +from supervision.draw.utils import ( + calculate_optimal_line_thickness, + calculate_optimal_text_scale, + draw_filled_polygon, + draw_filled_rectangle, + draw_image, + draw_line, + draw_polygon, + draw_rectangle, + draw_text, +) +from supervision.geometry.core import Point, Position, Rect +from supervision.geometry.utils import get_polygon_center +from supervision.key_points.annotators import ( + EdgeAnnotator, + VertexAnnotator, + VertexEllipseAnnotator, + VertexEllipseAreaAnnotator, + VertexEllipseHaloAnnotator, + VertexEllipseOutlineAnnotator, + VertexLabelAnnotator, +) +from supervision.key_points.core import KeyPoints +from supervision.metrics.detection import ConfusionMatrix, MeanAveragePrecision +from supervision.utils.conversion import cv2_to_pillow, pillow_to_cv2 +from supervision.utils.file import list_files_with_extensions +from supervision.utils.image import ( + ImageSink, + crop_image, + get_image_resolution_wh, + grayscale_image, + letterbox_image, + load_image_from_url, + overlay_image, + resize_image, + scale_image, + tint_image, +) +from supervision.utils.image_window import ImageWindow +from supervision.utils.notebook import plot_image, plot_images_grid +from supervision.utils.video import ( + FPSMonitor, + VideoInfo, + VideoSink, + get_video_frames_generator, + process_video, +) + +if TYPE_CHECKING: + from supervision.tracker.byte_tracker.core import ByteTrack + +__all__ = [ + "LMM", + "VLM", + "BackgroundOverlayAnnotator", + "BaseDataset", + "BlurAnnotator", + "BoxAnnotator", + "BoxCornerAnnotator", + "ByteTrack", + "CSVSink", + "CircleAnnotator", + "ClassificationDataset", + "Classifications", + "Color", + "ColorAnnotator", + "ColorLookup", + "ColorPalette", + "CompactMask", + "ComparisonAnnotator", + "ConfusionMatrix", + "CropAnnotator", + "DetectionDataset", + "Detections", + "DetectionsSmoother", + "DotAnnotator", + "EdgeAnnotator", + "EllipseAnnotator", + "FPSMonitor", + "HaloAnnotator", + "HeatMapAnnotator", + "IconAnnotator", + "ImageSink", + "ImageWindow", + "InferenceSlicer", + "JSONSink", + "KeyPoints", + "LabelAnnotator", + "LineZone", + "LineZoneAnnotator", + "LineZoneAnnotatorMulticlass", + "MaskAnnotator", + "MeanAveragePrecision", + "OrientedBoxAnnotator", + "OverlapFilter", + "OverlapMetric", + "PercentageBarAnnotator", + "PixelateAnnotator", + "Point", + "PolygonAnnotator", + "PolygonZone", + "PolygonZoneAnnotator", + "Position", + "Rect", + "RichLabelAnnotator", + "RoundBoxAnnotator", + "TraceAnnotator", + "TriangleAnnotator", + "VertexAnnotator", + "VertexEllipseAnnotator", + "VertexEllipseAreaAnnotator", + "VertexEllipseHaloAnnotator", + "VertexEllipseOutlineAnnotator", + "VertexLabelAnnotator", + "VideoInfo", + "VideoSink", + "WindowedRasterDataset", + "approximate_polygon", + "box_iou", + "box_iou_batch", + "box_iou_batch_with_jaccard", + "box_non_max_merge", + "box_non_max_suppression", + "box_soft_non_max_suppression", + "calculate_masks_centroids", + "calculate_optimal_line_thickness", + "calculate_optimal_text_scale", + "clip_boxes", + "contains_holes", + "contains_multiple_segments", + "crop_image", + "cv2_to_pillow", + "denormalize_boxes", + "draw_filled_polygon", + "draw_filled_rectangle", + "draw_image", + "draw_line", + "draw_polygon", + "draw_rectangle", + "draw_text", + "edit_distance", + "filter_polygons_by_area", + "filter_segments_by_distance", + "fuzzy_match_index", + "get_coco_class_index_mapping", + "get_image_resolution_wh", + "get_polygon_center", + "get_video_frames_generator", + "grayscale_image", + "hex_to_rgba", + "is_compressed_rle", + "is_valid_hex", + "letterbox_image", + "list_files_with_extensions", + "load_image_from_url", + "mask_iou_batch", + "mask_non_max_merge", + "mask_non_max_suppression", + "mask_soft_non_max_suppression", + "mask_to_polygons", + "mask_to_rle", + "mask_to_roi", + "mask_to_xyxy", + "move_boxes", + "move_masks", + "oriented_box_iou_batch", + "oriented_box_non_max_merge", + "oriented_box_non_max_suppression", + "overlay_image", + "pad_boxes", + "pillow_to_cv2", + "plot_image", + "plot_images_grid", + "polygon_to_mask", + "polygon_to_xyxy", + "process_video", + "resize_image", + "rgba_to_hex", + "rle_to_mask", + "scale_boxes", + "scale_image", + "tint_image", + "xcycwh_to_xyxy", + "xywh_to_xyxy", + "xyxy_to_mask", + "xyxy_to_polygons", + "xyxy_to_xcycarh", + "xyxy_to_xywh", + "xyxyxyxy_to_xyxy", +] + + +def __getattr__(name: str) -> Any: + """Lazily resolve deprecated compatibility exports.""" + if name == "ByteTrack": + from supervision.tracker.byte_tracker.core import ByteTrack as byte_track + + globals()[name] = byte_track + return byte_track + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/.venv/lib/python3.12/site-packages/supervision/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..189605247dbb1d84a823525d4d4fa6ab9707dd10 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/__pycache__/config.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/__pycache__/config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b524f1e1b5b7e90602e9df4630d6a7a35287f7a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/__pycache__/config.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/_cv2/__init__.py b/.venv/lib/python3.12/site-packages/supervision/_cv2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7948ed3387a48fab401e7cc365e836539d80e947 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/_cv2/__init__.py @@ -0,0 +1,302 @@ +"""Private OpenCV compatibility surface used by Supervision.""" + +from __future__ import annotations + +import warnings +from typing import Any + +import numpy.typing as npt + +from supervision._cv2._color import _cvt_color, _merge, _split +from supervision._cv2._common import BackendUnavailableError +from supervision._cv2._components import ( + _connected_components, + _connected_components_with_stats, +) +from supervision._cv2._contours import _find_contours +from supervision._cv2._drawing import ( + _circle, + _draw_contours, + _ellipse, + _fill_poly, + _line, + _polylines, + _rectangle, +) +from supervision._cv2._geometry import ( + _approx_poly_dp, + _contour_area, + _intersect_convex_convex, +) +from supervision._cv2._image import ( + _add_weighted, + _convert_scale_abs, + _copy_make_border, + _flip, + _imdecode, + _imencode, + _imread, + _imwrite, + _mean, + _resize, +) +from supervision._cv2._text import _get_text_size, _put_text +from supervision._cv2._transform import _blur +from supervision._cv2._video import ( + _video_writer_fourcc, + _VideoCapture, + _VideoWriter, +) +from supervision._cv2.constants import ( + _BORDER_CONSTANT, + _CAP_PROP_FPS, + _CAP_PROP_FRAME_COUNT, + _CAP_PROP_FRAME_HEIGHT, + _CAP_PROP_FRAME_WIDTH, + _CAP_PROP_POS_FRAMES, + _CC_STAT_AREA, + _CHAIN_APPROX_SIMPLE, + _COLOR_BGR2GRAY, + _COLOR_BGR2RGB, + _COLOR_GRAY2BGR, + _COLOR_HSV2BGR, + _COLOR_RGB2BGR, + _FONT_HERSHEY_COMPLEX, + _FONT_HERSHEY_COMPLEX_SMALL, + _FONT_HERSHEY_DUPLEX, + _FONT_HERSHEY_PLAIN, + _FONT_HERSHEY_SCRIPT_COMPLEX, + _FONT_HERSHEY_SCRIPT_SIMPLEX, + _FONT_HERSHEY_SIMPLEX, + _FONT_HERSHEY_TRIPLEX, + _FONT_ITALIC, + _IMREAD_COLOR, + _IMREAD_UNCHANGED, + _INTER_LINEAR, + _INTER_NEAREST, + _LINE_4, + _LINE_8, + _LINE_AA, + _RETR_TREE, +) + +try: + import cv2 +except (ImportError, OSError): + _IS_CV2_AVAILABLE = False +else: + _IS_CV2_AVAILABLE = True + +if _IS_CV2_AVAILABLE: + from cv2 import ( # type: ignore[attr-defined] + BORDER_CONSTANT, + CAP_PROP_FPS, + CAP_PROP_FRAME_COUNT, + CAP_PROP_FRAME_HEIGHT, + CAP_PROP_FRAME_WIDTH, + CAP_PROP_POS_FRAMES, + CC_STAT_AREA, + COLOR_BGR2GRAY, + COLOR_BGR2RGB, + COLOR_GRAY2BGR, + COLOR_HSV2BGR, + COLOR_RGB2BGR, + FONT_HERSHEY_COMPLEX, + FONT_HERSHEY_COMPLEX_SMALL, + FONT_HERSHEY_DUPLEX, + FONT_HERSHEY_PLAIN, + FONT_HERSHEY_SCRIPT_COMPLEX, + FONT_HERSHEY_SCRIPT_SIMPLEX, + FONT_HERSHEY_SIMPLEX, + FONT_HERSHEY_TRIPLEX, + FONT_ITALIC, + IMREAD_COLOR, + IMREAD_UNCHANGED, + INTER_LINEAR, + INTER_NEAREST, + LINE_4, + LINE_8, + LINE_AA, + VideoCapture, + VideoWriter, + VideoWriter_fourcc, # type: ignore[attr-defined] + addWeighted, + approxPolyDP, + blur, + circle, + connectedComponents, + connectedComponentsWithStats, + contourArea, + convertScaleAbs, + copyMakeBorder, + cvtColor, + drawContours, + ellipse, + fillPoly, + flip, + getTextSize, + imdecode, + imencode, + imread, + imwrite, + intersectConvexConvex, + line, + mean, + merge, + polylines, + putText, + rectangle, + resize, + split, + ) + from cv2 import ( + findContours as _find_contours_impl, + ) + + BACKEND_NAME = "opencv" +else: + BACKEND_NAME = "fallback" + + warnings.warn( + "OpenCV (`opencv-python`) is not installed; supervision is using its " + "pure NumPy fallback backend instead. Some operations may be slower " + "or behave slightly differently. Install `opencv-python` for full " + "performance and compatibility.", + stacklevel=2, + ) + + BORDER_CONSTANT = _BORDER_CONSTANT + CAP_PROP_FPS = _CAP_PROP_FPS + CAP_PROP_FRAME_COUNT = _CAP_PROP_FRAME_COUNT + CAP_PROP_FRAME_HEIGHT = _CAP_PROP_FRAME_HEIGHT + CAP_PROP_FRAME_WIDTH = _CAP_PROP_FRAME_WIDTH + CAP_PROP_POS_FRAMES = _CAP_PROP_POS_FRAMES + CC_STAT_AREA = _CC_STAT_AREA + COLOR_BGR2GRAY = _COLOR_BGR2GRAY + COLOR_BGR2RGB = _COLOR_BGR2RGB + COLOR_GRAY2BGR = _COLOR_GRAY2BGR + COLOR_HSV2BGR = _COLOR_HSV2BGR + COLOR_RGB2BGR = _COLOR_RGB2BGR + FONT_HERSHEY_COMPLEX = _FONT_HERSHEY_COMPLEX + FONT_HERSHEY_COMPLEX_SMALL = _FONT_HERSHEY_COMPLEX_SMALL + FONT_HERSHEY_DUPLEX = _FONT_HERSHEY_DUPLEX + FONT_HERSHEY_PLAIN = _FONT_HERSHEY_PLAIN + FONT_HERSHEY_SCRIPT_COMPLEX = _FONT_HERSHEY_SCRIPT_COMPLEX + FONT_HERSHEY_SCRIPT_SIMPLEX = _FONT_HERSHEY_SCRIPT_SIMPLEX + FONT_HERSHEY_SIMPLEX = _FONT_HERSHEY_SIMPLEX + FONT_HERSHEY_TRIPLEX = _FONT_HERSHEY_TRIPLEX + FONT_ITALIC = _FONT_ITALIC + IMREAD_COLOR = _IMREAD_COLOR + IMREAD_UNCHANGED = _IMREAD_UNCHANGED + INTER_LINEAR = _INTER_LINEAR + INTER_NEAREST = _INTER_NEAREST + LINE_4 = _LINE_4 + LINE_8 = _LINE_8 + LINE_AA = _LINE_AA + + # Fallback implementations when cv2 is not available. Suppress type errors because + # fallback types differ from cv2 types, but are functionally equivalent. + VideoCapture = _VideoCapture # type: ignore[assignment,misc] + VideoWriter = _VideoWriter # type: ignore[assignment,misc] + VideoWriter_fourcc = _video_writer_fourcc # type: ignore[assignment] + addWeighted = _add_weighted # type: ignore[assignment] + approxPolyDP = _approx_poly_dp # type: ignore[assignment] + blur = _blur # type: ignore[assignment] + circle = _circle # type: ignore[assignment] + connectedComponents = _connected_components # type: ignore[assignment] + connectedComponentsWithStats = _connected_components_with_stats # type: ignore[assignment] + contourArea = _contour_area # type: ignore[assignment] + convertScaleAbs = _convert_scale_abs # type: ignore[assignment] + copyMakeBorder = _copy_make_border # type: ignore[assignment] + cvtColor = _cvt_color # type: ignore[assignment] + drawContours = _draw_contours # type: ignore[assignment] + ellipse = _ellipse # type: ignore[assignment] + fillPoly = _fill_poly # type: ignore[assignment] + _find_contours_impl = _find_contours + flip = _flip # type: ignore[assignment] + getTextSize = _get_text_size # type: ignore[assignment] + imdecode = _imdecode # type: ignore[assignment] + imencode = _imencode # type: ignore[assignment] + imread = _imread # type: ignore[assignment] + imwrite = _imwrite # type: ignore[assignment] + intersectConvexConvex = _intersect_convex_convex # type: ignore[assignment] + line = _line # type: ignore[assignment] + mean = _mean # type: ignore[assignment] + merge = _merge # type: ignore[assignment] + polylines = _polylines # type: ignore[assignment] + putText = _put_text # type: ignore[assignment] + rectangle = _rectangle # type: ignore[assignment] + resize = _resize # type: ignore[assignment] + split = _split # type: ignore[assignment] + + +def find_contours(image: npt.NDArray[Any]) -> list[npt.NDArray[Any]]: + """Return the contour geometry required by mask-to-polygon conversion.""" + contours, _ = _find_contours_impl(image, _RETR_TREE, _CHAIN_APPROX_SIMPLE) + return list(contours) + + +__all__ = [ + "BACKEND_NAME", + "BORDER_CONSTANT", + "CAP_PROP_FPS", + "CAP_PROP_FRAME_COUNT", + "CAP_PROP_FRAME_HEIGHT", + "CAP_PROP_FRAME_WIDTH", + "CAP_PROP_POS_FRAMES", + "CC_STAT_AREA", + "COLOR_BGR2GRAY", + "COLOR_BGR2RGB", + "COLOR_GRAY2BGR", + "COLOR_HSV2BGR", + "COLOR_RGB2BGR", + "FONT_HERSHEY_COMPLEX", + "FONT_HERSHEY_COMPLEX_SMALL", + "FONT_HERSHEY_DUPLEX", + "FONT_HERSHEY_PLAIN", + "FONT_HERSHEY_SCRIPT_COMPLEX", + "FONT_HERSHEY_SCRIPT_SIMPLEX", + "FONT_HERSHEY_SIMPLEX", + "FONT_HERSHEY_TRIPLEX", + "FONT_ITALIC", + "IMREAD_COLOR", + "IMREAD_UNCHANGED", + "INTER_LINEAR", + "INTER_NEAREST", + "LINE_4", + "LINE_8", + "LINE_AA", + "BackendUnavailableError", + "VideoCapture", + "VideoWriter", + "VideoWriter_fourcc", + "addWeighted", + "approxPolyDP", + "blur", + "circle", + "connectedComponents", + "connectedComponentsWithStats", + "contourArea", + "convertScaleAbs", + "copyMakeBorder", + "cvtColor", + "drawContours", + "ellipse", + "fillPoly", + "find_contours", + "flip", + "getTextSize", + "imdecode", + "imencode", + "imread", + "imwrite", + "intersectConvexConvex", + "line", + "mean", + "merge", + "polylines", + "putText", + "rectangle", + "resize", + "split", +] diff --git a/.venv/lib/python3.12/site-packages/supervision/_cv2/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/_cv2/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..72782f261c1942be6ab73ea4b5d34d63fbe34498 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/_cv2/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/_cv2/__pycache__/_color.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/_cv2/__pycache__/_color.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..caa8f7be81293ef1186b8b32601bf13b1a715aed Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/_cv2/__pycache__/_color.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/_cv2/__pycache__/_common.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/_cv2/__pycache__/_common.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..675edbf218f4ef697b2da623bb0aca4a0cf75fa0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/_cv2/__pycache__/_common.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/_cv2/__pycache__/_components.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/_cv2/__pycache__/_components.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd4e2d7037a961142e87603a46999e66c3f780df Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/_cv2/__pycache__/_components.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/_cv2/__pycache__/_contours.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/_cv2/__pycache__/_contours.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13f0613ad144d8dc68a77480ddf4f7f6396ed6fb Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/_cv2/__pycache__/_contours.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/_cv2/__pycache__/_drawing.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/_cv2/__pycache__/_drawing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..443cce31e4edb1ae0ede536a4caf8634f1bc0bcf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/_cv2/__pycache__/_drawing.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/_cv2/__pycache__/_geometry.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/_cv2/__pycache__/_geometry.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1f593206c39934192ff8c1d67a5d1f13715cd8c6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/_cv2/__pycache__/_geometry.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/_cv2/__pycache__/_image.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/_cv2/__pycache__/_image.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be2deef87f564c028952661091947fc9a2d1f86d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/_cv2/__pycache__/_image.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/_cv2/__pycache__/_text.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/_cv2/__pycache__/_text.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e6d1c3e95e7f05962983da41afb588b73d42124 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/_cv2/__pycache__/_text.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/_cv2/__pycache__/_transform.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/_cv2/__pycache__/_transform.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6377c01b9b6e34d4baccc3a2f400863a56a7fc74 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/_cv2/__pycache__/_transform.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/_cv2/__pycache__/_video.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/_cv2/__pycache__/_video.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..929c5e9087344e032994220a7bcc74e1adbbdab6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/_cv2/__pycache__/_video.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/_cv2/__pycache__/constants.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/_cv2/__pycache__/constants.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0271592de24429d3be8878ca5cf3f7a43923ae9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/_cv2/__pycache__/constants.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/_cv2/_color.py b/.venv/lib/python3.12/site-packages/supervision/_cv2/_color.py new file mode 100644 index 0000000000000000000000000000000000000000..c395b6e3c924d170a40e1fbfbf318b3a79db5fae --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/_cv2/_color.py @@ -0,0 +1,96 @@ +"""Private color and channel-operation fallbacks.""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import Any + +import numpy as np +import numpy.typing as npt + +from supervision._cv2._common import _cast_array_like_opencv +from supervision._cv2.constants import ( + _COLOR_BGR2GRAY, + _COLOR_BGR2RGB, + _COLOR_GRAY2BGR, + _COLOR_HSV2BGR, + _COLOR_RGB2BGR, +) + + +def _cvt_color(image: npt.NDArray[Any], code: int) -> npt.NDArray[Any]: + """Convert the BGR, RGB, grayscale, and 8-bit HSV formats used by Supervision.""" + if code in (_COLOR_BGR2RGB, _COLOR_RGB2BGR): + if image.ndim != 3 or image.shape[2] not in (3, 4): + raise ValueError( + "BGR/RGB conversion requires a three- or four-channel image" + ) + return np.ascontiguousarray(image[..., 2::-1]) + + if code == _COLOR_GRAY2BGR: + if image.ndim != 2: + raise ValueError("GRAY2BGR conversion requires a two-dimensional image") + return np.repeat(image[..., np.newaxis], 3, axis=2) + + if code == _COLOR_BGR2GRAY: + if image.ndim != 3 or image.shape[2] != 3: + raise ValueError("BGR2GRAY conversion requires a three-channel image") + if image.dtype == np.uint8: + values = image.astype(np.uint32) + weighted = ( + values[..., 0] * 3735 + + values[..., 1] * 19235 + + values[..., 2] * 9798 + + (1 << 14) + ) >> 15 + return weighted.astype(np.uint8) + float_values = ( + image[..., 0].astype(np.float64) * 0.114 + + image[..., 1].astype(np.float64) * 0.587 + + image[..., 2].astype(np.float64) * 0.299 + ) + return _cast_array_like_opencv(float_values, image.dtype) + + if code == _COLOR_HSV2BGR: + if image.ndim != 3 or image.shape[2] != 3: + raise ValueError("HSV2BGR conversion requires a three-channel image") + return _hsv_to_bgr(image) + + raise ValueError(f"Unsupported color conversion code: {code}") + + +def _hsv_to_bgr(image: npt.NDArray[Any]) -> npt.NDArray[Any]: + """Convert OpenCV's 8-bit HSV representation to BGR.""" + values = image.astype(np.float64) + hue = values[..., 0] / 30.0 + saturation = values[..., 1] / 255.0 + value = values[..., 2] / 255.0 + + chroma = value * saturation + sector_index = np.floor(hue).astype(np.int64) % 6 + sector = hue - np.floor(hue) + x = chroma * (1 - np.abs(((sector_index + sector) % 2) - 1)) + match = value - chroma + zeros = np.zeros_like(chroma) + + red = np.choose(sector_index, (chroma, x, zeros, zeros, x, chroma)) + green = np.choose(sector_index, (x, chroma, chroma, x, zeros, zeros)) + blue = np.choose(sector_index, (zeros, zeros, x, chroma, chroma, x)) + bgr = np.stack((blue + match, green + match, red + match), axis=-1) * 255 + return _cast_array_like_opencv(bgr, image.dtype) + + +def _split(image: npt.NDArray[Any]) -> tuple[npt.NDArray[Any], ...]: + """Split an image into contiguous single-channel arrays.""" + if image.ndim == 2: + return (np.ascontiguousarray(image),) + return tuple( + np.ascontiguousarray(image[..., index]) for index in range(image.shape[2]) + ) + + +def _merge(channels: Sequence[npt.NDArray[Any]]) -> npt.NDArray[Any]: + """Merge single-channel arrays along their final axis.""" + if not channels: + raise ValueError("At least one channel is required") + return np.ascontiguousarray(np.stack(channels, axis=-1)) diff --git a/.venv/lib/python3.12/site-packages/supervision/_cv2/_common.py b/.venv/lib/python3.12/site-packages/supervision/_cv2/_common.py new file mode 100644 index 0000000000000000000000000000000000000000..c6c30167e6e532ac7893afd07fcecc3153048b46 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/_cv2/_common.py @@ -0,0 +1,23 @@ +"""Private helpers shared by OpenCV fallback implementations.""" + +from __future__ import annotations + +from typing import Any + +import numpy as np +import numpy.typing as npt + + +class BackendUnavailableError(RuntimeError): + """Raised when an OpenCV operation is used without an available backend.""" + + +def _cast_array_like_opencv( + values: npt.NDArray[Any], dtype: np.dtype[Any] +) -> npt.NDArray[Any]: + """Round integer results using OpenCV's saturating conversion convention.""" + if np.issubdtype(dtype, np.integer): + info = np.iinfo(dtype) + values = np.rint(values) + values = np.clip(values, info.min, info.max) + return values.astype(dtype, copy=False) diff --git a/.venv/lib/python3.12/site-packages/supervision/_cv2/_components.py b/.venv/lib/python3.12/site-packages/supervision/_cv2/_components.py new file mode 100644 index 0000000000000000000000000000000000000000..fb6b33209ebec67bf6d7954652d0b9b93bf11f31 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/_cv2/_components.py @@ -0,0 +1,128 @@ +"""Private connected-component and mask-topology fallbacks.""" + +from __future__ import annotations + +from typing import Any, cast + +import numpy as np +import numpy.typing as npt + + +def _validate_binary_image(image: npt.NDArray[Any]) -> npt.NDArray[np.bool_]: + """Validate and normalize a two-dimensional component image.""" + values = np.asarray(image) + if values.ndim != 2: + raise ValueError("Connected-component input must be a two-dimensional image") + return cast(npt.NDArray[np.bool_], values != 0) + + +def _label( + image: npt.NDArray[Any], connectivity: int +) -> tuple[int, npt.NDArray[np.int32]]: + """Label foreground pixels with the requested four- or eight-way topology.""" + if connectivity not in (4, 8): + raise ValueError("Only 4- and 8-connectivity are supported") + + from scipy import ndimage + + structure = ndimage.generate_binary_structure(2, 1 if connectivity == 4 else 2) + labels, count = ndimage.label(_validate_binary_image(image), structure=structure) + return int(count), np.ascontiguousarray(labels, dtype=np.int32) + + +def _connected_components( + image: npt.NDArray[Any], + labels: npt.NDArray[Any] | None = None, + connectivity: int = 8, + ltype: int = 4, +) -> tuple[int, npt.NDArray[np.int32]]: + """Return OpenCV-shaped connected-component labels and their count.""" + del ltype + count, result = _label(image, connectivity) + if labels is not None and labels.shape == result.shape and labels.dtype == np.int32: + labels[...] = result + result = labels + return count + 1, result + + +def _connected_components_with_stats( + image: npt.NDArray[Any], connectivity: int = 8, ltype: int = 4 +) -> tuple[ + int, + npt.NDArray[np.int32], + npt.NDArray[np.int32], + npt.NDArray[np.float64], +]: + """Return labels, bounding-box statistics, and centroids for components.""" + del ltype + from scipy import ndimage + + count, labels = _label(image, connectivity) + component_count = count + 1 + flat_labels = labels.ravel() + rows, columns = np.indices(labels.shape) + areas = np.bincount(flat_labels, minlength=component_count) + x_sums = np.bincount( + flat_labels, weights=columns.ravel(), minlength=component_count + ) + y_sums = np.bincount(flat_labels, weights=rows.ravel(), minlength=component_count) + + centroids = np.zeros((component_count, 2), dtype=np.float64) + populated = areas != 0 + centroids[populated, 0] = x_sums[populated] / areas[populated] + centroids[populated, 1] = y_sums[populated] / areas[populated] + + stats = np.zeros((component_count, 5), dtype=np.int32) + stats[:, 4] = areas.astype(np.int32) + objects = ndimage.find_objects(labels, max_label=count) + for component, bounds in enumerate(objects, start=1): + if bounds is None: + continue + row_slice, column_slice = bounds + stats[component, :4] = ( + column_slice.start, + row_slice.start, + column_slice.stop - column_slice.start, + row_slice.stop - row_slice.start, + ) + + background_mask = labels == 0 + if np.any(background_mask): + row_hits = np.any(background_mask, axis=1) + col_hits = np.any(background_mask, axis=0) + y_indices = np.flatnonzero(row_hits) + x_indices = np.flatnonzero(col_hits) + stats[0, :4] = ( + int(x_indices[0]), + int(y_indices[0]), + int(x_indices[-1] - x_indices[0] + 1), + int(y_indices[-1] - y_indices[0] + 1), + ) + return count + 1, labels, stats, centroids + + +def _contains_holes(mask: npt.NDArray[Any]) -> bool: + """Return whether a mask has a background component detached from its border.""" + values = _validate_binary_image(mask) + if values.size == 0 or np.all(values): + return False + + background_count, background_labels = _label(~values, connectivity=4) + if background_count == 0: + return False + + border_labels = np.unique( + np.concatenate( + ( + background_labels[0], + background_labels[-1], + background_labels[:, 0], + background_labels[:, -1], + ) + ) + ) + return bool( + np.any( + ~np.isin(np.arange(1, background_count + 1, dtype=np.int32), border_labels) + ) + ) diff --git a/.venv/lib/python3.12/site-packages/supervision/_cv2/_contours.py b/.venv/lib/python3.12/site-packages/supervision/_cv2/_contours.py new file mode 100644 index 0000000000000000000000000000000000000000..ab56226bb757d54cc0ebce5e4c858f3218041db2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/_cv2/_contours.py @@ -0,0 +1,154 @@ +"""Private Suzuki-Abe contour fallback.""" + +from __future__ import annotations + +from typing import Any + +import numpy as np +import numpy.typing as npt + +from supervision._cv2.constants import _CHAIN_APPROX_SIMPLE, _RETR_TREE + +_NEIGHBORS = ( + (0, 1), + (-1, 1), + (-1, 0), + (-1, -1), + (0, -1), + (1, -1), + (1, 0), + (1, 1), +) + + +def _follow_border( + image: npt.NDArray[np.bool_], + labels: npt.NDArray[np.int32], + start: tuple[int, int], + previous: tuple[int, int], + border_number: int, +) -> list[tuple[int, int]]: + """Trace one border using the Suzuki-Abe neighborhood walk.""" + rows, columns = image.shape + + def is_foreground(row: int, column: int) -> bool: + """Check a pixel while treating the image boundary as background.""" + return 0 <= row < rows and 0 <= column < columns and bool(image[row, column]) + + direction = _NEIGHBORS.index((previous[0] - start[0], previous[1] - start[1])) + first_direction = -1 + for offset in range(1, 9): + candidate_direction = (direction + offset) % 8 + delta_row, delta_column = _NEIGHBORS[candidate_direction] + if is_foreground(start[0] + delta_row, start[1] + delta_column): + first_direction = candidate_direction + break + if first_direction < 0: + labels[start] = -border_number + return [start] + + first_neighbor = ( + start[0] + _NEIGHBORS[first_direction][0], + start[1] + _NEIGHBORS[first_direction][1], + ) + contour: list[tuple[int, int]] = [] + previous_point, current = first_neighbor, start + while True: + direction = _NEIGHBORS.index( + (previous_point[0] - current[0], previous_point[1] - current[1]) + ) + east_zero = False + next_point: tuple[int, int] | None = None + for offset in range(1, 9): + candidate_direction = (direction - offset) % 8 + delta_row, delta_column = _NEIGHBORS[candidate_direction] + row = current[0] + delta_row + column = current[1] + delta_column + if is_foreground(row, column): + next_point = (row, column) + break + if candidate_direction == 0: + east_zero = True + + if east_zero: + labels[current] = -border_number + elif labels[current] == 0: + labels[current] = border_number + contour.append(current) + + if next_point == start and current == first_neighbor and len(contour) > 1: + return contour + if next_point is None: + return contour + previous_point, current = current, next_point + if len(contour) > 4 * image.size: + raise RuntimeError("Contour border tracing did not converge") + + +def _trace_borders(mask: npt.NDArray[np.bool_]) -> list[np.ndarray]: + """Trace all foreground and hole borders in raster candidate order.""" + image = np.ascontiguousarray(mask, dtype=bool) + labels = np.zeros(image.shape, dtype=np.int32) + left_zero = image & ~np.pad(image[:, :-1], ((0, 0), (1, 0))) + right_zero = image & ~np.pad(image[:, 1:], ((0, 0), (0, 1))) + candidates = np.argwhere(left_zero | right_zero) + borders: list[np.ndarray] = [] + border_number = 1 + for row, column in candidates: + row, column = int(row), int(column) + if left_zero[row, column] and labels[row, column] == 0: + border_number += 1 + border = _follow_border( + image, labels, (row, column), (row, column - 1), border_number + ) + borders.append(np.array([(column, row) for row, column in border])) + elif right_zero[row, column] and labels[row, column] >= 0: + border_number += 1 + border = _follow_border( + image, labels, (row, column), (row, column + 1), border_number + ) + borders.append(np.array([(column, row) for row, column in border])) + return borders + + +def _reverse_preserving_start(contour: np.ndarray) -> np.ndarray: + """Reverse a traced contour while retaining its Suzuki-Abe start pixel.""" + if len(contour) < 2: + return contour + return np.concatenate((contour[:1], contour[:0:-1])) + + +def _compress_contour(contour: np.ndarray) -> np.ndarray: + """Apply OpenCV's collinear-run compression for SIMPLE contours.""" + contour = _reverse_preserving_start(contour) + if len(contour) < 3: + return contour + keep: list[np.ndarray] = [] + for index, point in enumerate(contour): + previous = point - contour[index - 1] + following = contour[(index + 1) % len(contour)] - point + if ( + np.any(previous) + and np.any(following) + and np.array_equal(np.sign(previous), np.sign(following)) + ): + continue + keep.append(point) + return np.asarray(keep, dtype=np.int32) + + +def _find_contours( + image: npt.NDArray[Any], mode: int, method: int +) -> tuple[list[npt.NDArray[np.int32]], npt.NDArray[np.int32] | None]: + """Find contours for the supported tree and SIMPLE modes.""" + if mode != _RETR_TREE: + raise ValueError("Only RETR_TREE is supported by the fallback") + if method != _CHAIN_APPROX_SIMPLE: + raise ValueError("Only CHAIN_APPROX_SIMPLE is supported by the fallback") + values = np.asarray(image) + if values.ndim != 2: + raise ValueError("Contour input must be a two-dimensional image") + traced = [_compress_contour(contour) for contour in _trace_borders(values != 0)] + if not traced: + return [], None + return [contour.reshape(-1, 1, 2) for contour in traced], None diff --git a/.venv/lib/python3.12/site-packages/supervision/_cv2/_drawing.py b/.venv/lib/python3.12/site-packages/supervision/_cv2/_drawing.py new file mode 100644 index 0000000000000000000000000000000000000000..db749ac270de470dcc07865b830da03015802487 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/_cv2/_drawing.py @@ -0,0 +1,284 @@ +"""Private Pillow-based drawing fallbacks for the OpenCV facade.""" + +from __future__ import annotations + +from collections.abc import Callable, Sequence +from typing import Any + +import numpy as np +import numpy.typing as npt +from PIL import Image, ImageDraw + +_ImageArray = npt.NDArray[Any] +_Point = tuple[int, int] + + +def _drawing_mask( + image: _ImageArray, draw_operation: Callable[[Any], None] +) -> npt.NDArray[np.bool_]: + """Render a shape into a clipped one-bit mask with Pillow.""" + height, width = image.shape[:2] + mask = Image.new("1", (width, height)) + draw_operation(ImageDraw.Draw(mask)) + return np.asarray(mask, dtype=bool) + + +def _color_for_image(image: _ImageArray, color: Any) -> Any: + """Normalize an OpenCV scalar color to the image channel count.""" + values = np.asarray(color).reshape(-1) + if image.ndim == 2: + return values[0] if values.size else 0 + channels = image.shape[2] + if values.size == 0: + return np.zeros(channels, dtype=image.dtype) + if values.size < channels: + return np.pad(values, (0, channels - values.size)) + return values[:channels] + + +def _paint(image: _ImageArray, mask: npt.NDArray[np.bool_], color: Any) -> _ImageArray: + """Apply a scalar or multi-channel color to a drawing mask.""" + image[mask] = _color_for_image(image, color) + return image + + +def _point(point: Sequence[int | float]) -> _Point: + """Convert an OpenCV point to integer Pillow coordinates.""" + return round(point[0]), round(point[1]) + + +def _points(points: npt.NDArray[Any], offset: tuple[int, int] = (0, 0)) -> list[_Point]: + """Normalize OpenCV polygon shapes to integer Pillow coordinates.""" + values = np.asarray(points) + if values.size == 0: + return [] + if values.ndim not in (2, 3) or values.shape[-1] != 2: + raise ValueError("Drawing points must have shape (N, 2) or (N, 1, 2)") + normalized = np.rint(values.reshape(-1, 2)).astype(np.int64) + normalized += np.asarray(offset, dtype=np.int64) + return [(int(x), int(y)) for x, y in normalized] + + +def _validate_shift(shift: int) -> None: + """Reject fixed-point coordinates not supported by the fallback.""" + if shift != 0: + raise ValueError("Only unshifted drawing coordinates are supported") + + +def _line( + img: _ImageArray, + pt1: Sequence[int | float], + pt2: Sequence[int | float], + color: Any, + thickness: int = 1, + lineType: int = 8, + shift: int = 0, +) -> _ImageArray: + """Draw a line in place using Pillow's integer rasterization.""" + del lineType + _validate_shift(shift) + width = max(1, thickness) + mask = _drawing_mask( + img, + lambda draw: draw.line([_point(pt1), _point(pt2)], fill=1, width=width), + ) + return _paint(img, mask, color) + + +def _rectangle( + img: _ImageArray, + pt1: Sequence[int | float], + pt2: Sequence[int | float], + color: Any, + thickness: int = 1, + lineType: int = 8, + shift: int = 0, +) -> _ImageArray: + """Draw or fill an inclusive-axis-aligned rectangle in place.""" + del lineType + _validate_shift(shift) + first_point, second_point = _point(pt1), _point(pt2) + first = tuple(min(left, right) for left, right in zip(first_point, second_point)) + second = tuple(max(left, right) for left, right in zip(first_point, second_point)) + if thickness < 0: + mask = _drawing_mask(img, lambda draw: draw.rectangle([first, second], fill=1)) + else: + width = max(1, thickness) + mask = _drawing_mask( + img, + lambda draw: draw.rectangle([first, second], outline=1, width=width), + ) + return _paint(img, mask, color) + + +def _circle( + img: _ImageArray, + center: Sequence[int | float], + radius: int, + color: Any, + thickness: int = 1, + lineType: int = 8, + shift: int = 0, +) -> _ImageArray: + """Draw or fill a circle in place.""" + del lineType + _validate_shift(shift) + x, y = _point(center) + bounds = [x - radius, y - radius, x + radius, y + radius] + if thickness < 0: + mask = _drawing_mask(img, lambda draw: draw.ellipse(bounds, fill=1)) + else: + width = max(1, thickness) + mask = _drawing_mask( + img, + lambda draw: draw.ellipse(bounds, outline=1, width=width), + ) + return _paint(img, mask, color) + + +def _ellipse_points( + center: Sequence[int | float], + axes: Sequence[int | float], + angle: float, + start_angle: float, + end_angle: float, +) -> list[_Point]: + """Sample an OpenCV ellipse arc as integer image coordinates.""" + center_x, center_y = center + axis_x, axis_y = axes + span = max(0.0, end_angle - start_angle) + sample_count = max(2, int(np.ceil(span * max(axis_x, axis_y) * np.pi / 90))) + angles = np.linspace(start_angle, end_angle, sample_count + 1) + radians = np.deg2rad(angles) + rotation = np.deg2rad(angle) + cosine, sine = np.cos(rotation), np.sin(rotation) + x = center_x + axis_x * np.cos(radians) * cosine - axis_y * np.sin(radians) * sine + y = center_y + axis_x * np.cos(radians) * sine + axis_y * np.sin(radians) * cosine + return [(round(x_value), round(y_value)) for x_value, y_value in zip(x, y)] + + +def _ellipse( + img: _ImageArray, + center: Sequence[int | float], + axes: Sequence[int | float], + angle: float, + startAngle: float, + endAngle: float, + color: Any, + thickness: int = 1, + lineType: int = 8, + shift: int = 0, +) -> _ImageArray: + """Draw or fill an optionally rotated ellipse arc in place.""" + del lineType + _validate_shift(shift) + ellipse_points = _ellipse_points(center, axes, angle, startAngle, endAngle) + is_full = endAngle - startAngle >= 360 + + def draw_ellipse(draw: Any) -> None: + if thickness < 0: + if is_full: + draw.polygon(ellipse_points, fill=1) + else: + draw.polygon([_point(center), *ellipse_points], fill=1) + return + width = max(1, thickness) + draw.line(ellipse_points, fill=1, width=width, joint="curve") + if is_full and len(ellipse_points) > 1: + draw.line([ellipse_points[-1], ellipse_points[0]], fill=1, width=width) + + return _paint(img, _drawing_mask(img, draw_ellipse), color) + + +def _polylines( + img: _ImageArray, + pts: Sequence[npt.NDArray[Any]], + isClosed: bool, + color: Any, + thickness: int = 1, + lineType: int = 8, + shift: int = 0, +) -> _ImageArray: + """Draw one or more open or closed polylines in place.""" + del lineType + _validate_shift(shift) + width = max(1, thickness) + + def draw_polylines(draw: Any) -> None: + for polygon in pts: + points = _points(polygon) + if not points: + continue + points = [ + point + for index, point in enumerate(points) + if index == 0 or point != points[index - 1] + ] + if len(points) == 1: + draw.point(points[0], fill=1) + continue + if isClosed: + points.append(points[0]) + draw.line(points, fill=1, width=width, joint="curve") + + return _paint(img, _drawing_mask(img, draw_polylines), color) + + +def _fill_poly( + img: _ImageArray, + pts: Sequence[npt.NDArray[Any]], + color: Any, + lineType: int = 8, + shift: int = 0, + offset: tuple[int, int] = (0, 0), +) -> _ImageArray: + """Fill one or more polygons in place.""" + del lineType + _validate_shift(shift) + + def draw_polygons(draw: Any) -> None: + for polygon in pts: + points = _points(polygon, offset=offset) + if len(points) == 1: + draw.point(points[0], fill=1) + elif len(points) == 2: + draw.line(points, fill=1) + elif len(points) >= 3: + draw.polygon(points, fill=1) + + return _paint(img, _drawing_mask(img, draw_polygons), color) + + +def _draw_contours( + image: _ImageArray, + contours: Sequence[npt.NDArray[Any]], + contourIdx: int, + color: Any, + thickness: int = 1, + lineType: int = 8, + hierarchy: npt.NDArray[Any] | None = None, + maxLevel: int = 2**31 - 1, + offset: tuple[int, int] = (0, 0), +) -> _ImageArray: + """Draw selected contours with OpenCV-compatible in-place mutation.""" + del lineType, maxLevel + # OpenCV walks the hierarchy tree to also draw a contour's nested descendants; + # the fallback only does flat contourIdx selection, so reject a hierarchy + # instead of silently diverging. maxLevel is a no-op without a hierarchy, which + # matches OpenCV ignoring it whenever hierarchy is None. + if hierarchy is not None: + raise ValueError("Only None hierarchy is supported by the fallback") + selected = contours if contourIdx < 0 else contours[contourIdx : contourIdx + 1] + + def draw_selected(draw: Any) -> None: + for contour in selected: + points = _points(contour, offset=offset) + if len(points) < 2: + continue + if thickness < 0: + draw.polygon(points, fill=1) + else: + width = max(1, thickness) + draw.line([*points, points[0]], fill=1, width=width, joint="curve") + + return _paint(image, _drawing_mask(image, draw_selected), color) diff --git a/.venv/lib/python3.12/site-packages/supervision/_cv2/_geometry.py b/.venv/lib/python3.12/site-packages/supervision/_cv2/_geometry.py new file mode 100644 index 0000000000000000000000000000000000000000..e57bb8db2eec96f11e78167852fafc2ed1c0c94f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/_cv2/_geometry.py @@ -0,0 +1,234 @@ +"""Private polygon geometry fallbacks.""" + +from __future__ import annotations + +from typing import Any + +import numpy as np +import numpy.typing as npt + + +def _as_points(contour: npt.NDArray[Any]) -> npt.NDArray[np.float64]: + """Normalize an OpenCV contour to an ``(N, 2)`` float64 array.""" + points = np.asarray(contour) + if points.size == 0: + return np.empty((0, 2), dtype=np.float64) + if points.ndim not in (2, 3) or points.shape[-1] != 2: + raise ValueError("Contours must have shape (N, 2) or (N, 1, 2)") + return points.reshape(-1, 2).astype(np.float64, copy=False) + + +def _contour_area(contour: npt.NDArray[Any], oriented: bool = False) -> float: + """Compute a contour's signed or absolute shoelace area.""" + points = _as_points(contour) + if len(points) < 3: + return 0.0 + x = points[:, 0] + y = points[:, 1] + area = 0.5 * float(np.dot(x, np.roll(y, -1)) - np.dot(y, np.roll(x, -1))) + return area if oriented else abs(area) + + +def _simplify_slices( + points: npt.NDArray[np.float64], epsilon_squared: float, closed: bool +) -> npt.NDArray[np.float64]: + """Run OpenCV's stack-based Douglas-Peucker slice traversal.""" + count = len(points) + stack: list[tuple[int, int]] = [] + output: list[npt.NDArray[np.float64]] = [] + + if closed or np.array_equal(points[0], points[-1]): + closed = True + position = 0 + right_start = 0 + start_point = points[0] + within_epsilon = False + for _ in range(3): + position = (position + right_start) % count + start_point = points[position] + maximum_distance = 0.0 + right_start = 0 + for offset in range(1, count): + point = points[(position + offset) % count] + difference = point - start_point + distance = float(np.dot(difference, difference)) + if distance > maximum_distance: + maximum_distance = distance + right_start = offset + within_epsilon = maximum_distance <= epsilon_squared + + if within_epsilon: + output.append(start_point) + else: + split = (position + right_start) % count + stack.extend(((split, position), (position, split))) + else: + stack.append((0, count - 1)) + + while stack: + start, end = stack.pop() + start_point = points[start] + end_point = points[end] + position = (start + 1) % count + maximum_distance = 0.0 + split = start + + if position != end: + segment = end_point - start_point + while position != end: + point = points[position] + distance = abs( + float( + (point[1] - start_point[1]) * segment[0] + - (point[0] - start_point[0]) * segment[1] + ) + ) + if distance > maximum_distance: + maximum_distance = distance + split = position + position = (position + 1) % count + segment_length_squared = float(np.dot(segment, segment)) + within_epsilon = ( + maximum_distance * maximum_distance + <= epsilon_squared * segment_length_squared + ) + else: + within_epsilon = True + + if within_epsilon: + output.append(start_point) + else: + stack.extend(((split, end), (start, split))) + + if not closed: + output.append(points[-1]) + return np.asarray(output, dtype=np.float64) + + +def _cleanup_approximation( + points: npt.NDArray[np.float64], epsilon_squared: float, closed: bool +) -> npt.NDArray[np.float64]: + """Remove OpenCV's final near-collinear points from an approximation.""" + count = len(points) + if count <= 2: + return points + + destination = points.copy() + new_count = count + position = count - 1 if closed else 0 + start_point = destination[position] + position = (position + 1) % count + write_position = position + point = destination[position] + position = (position + 1) % count + index = 0 if closed else 1 + stop = count if closed else count - 1 + + while index < stop and new_count > 2: + end_point = destination[position] + position = (position + 1) % count + segment = end_point - start_point + offset = point - start_point + distance = abs(float(offset[0] * segment[1] - offset[1] * segment[0])) + inner_product = float(np.dot(offset, end_point - point)) + removable = ( + distance * distance + <= 0.5 * epsilon_squared * float(np.dot(segment, segment)) + and segment[0] != 0 + and segment[1] != 0 + and inner_product >= 0 + ) + if removable: + new_count -= 1 + destination[write_position] = end_point + start_point = end_point + write_position = (write_position + 1) % count + point = destination[position] + position = (position + 1) % count + index += 2 + continue + + destination[write_position] = point + start_point = point + write_position = (write_position + 1) % count + point = end_point + index += 1 + + if not closed: + destination[write_position] = point + return np.asarray(destination[:new_count], dtype=np.float64) + + +def _approx_poly_dp( + contour: npt.NDArray[Any], epsilon: float, closed: bool +) -> npt.NDArray[Any]: + """Approximate a contour with the supported OpenCV polygon contract.""" + if epsilon < 0: + raise ValueError("epsilon must be non-negative") + points = _as_points(contour) + if len(points) == 0: + dtype = np.asarray(contour).dtype + return np.empty((0, 1, 2), dtype=dtype) + + epsilon_squared = float(epsilon) ** 2 + simplified = _simplify_slices(points, epsilon_squared, closed) + simplified = _cleanup_approximation(simplified, epsilon_squared, closed) + + dtype = np.asarray(contour).dtype + return simplified.astype(dtype, copy=False).reshape(-1, 1, 2) + + +def _cross(edge: npt.NDArray[np.float64], point: npt.NDArray[np.float64]) -> float: + """Return the two-dimensional cross product of two vectors.""" + return float(edge[0] * point[1] - edge[1] * point[0]) + + +def _intersect_convex_convex( + first: npt.NDArray[Any], + second: npt.NDArray[Any], + handle_nested: bool = True, +) -> tuple[float, npt.NDArray[Any]]: + """Clip two convex polygons and return their intersection area and vertices.""" + del handle_nested + subject = _as_points(first) + clip = _as_points(second) + output = subject + if len(subject) < 3 or len(clip) < 3: + return 0.0, np.empty((0, 1, 2), dtype=np.float32) + + orientation = 1.0 if _contour_area(clip, oriented=True) >= 0 else -1.0 + for index, clip_start in enumerate(clip): + clip_end = clip[(index + 1) % len(clip)] + edge = clip_end - clip_start + input_points = output + if len(input_points) == 0: + break + output_points: list[npt.NDArray[np.float64]] = [] + previous = input_points[-1] + previous_inside = orientation * _cross(edge, previous - clip_start) >= 0 + for current in input_points: + current_inside = orientation * _cross(edge, current - clip_start) >= 0 + if current_inside != previous_inside: + direction = current - previous + denominator = _cross(edge, direction) + if denominator != 0: + factor = _cross(edge, clip_start - previous) / denominator + output_points.append(previous + factor * direction) + if current_inside: + output_points.append(current) + previous = current + previous_inside = current_inside + output = np.asarray(output_points, dtype=np.float64) + + if len(output) == 0: + dtype = np.asarray(first).dtype + result_dtype = dtype if np.issubdtype(dtype, np.floating) else np.float32 + return 0.0, np.empty((0, 1, 2), dtype=result_dtype) + + output = output[np.r_[True, np.any(np.diff(output, axis=0) != 0, axis=1)]] + if len(output) > 1 and np.array_equal(output[0], output[-1]): + output = output[:-1] + area = _contour_area(output) + dtype = np.asarray(first).dtype + result_dtype = dtype if np.issubdtype(dtype, np.floating) else np.float32 + return area, output.astype(result_dtype, copy=False).reshape(-1, 1, 2) diff --git a/.venv/lib/python3.12/site-packages/supervision/_cv2/_image.py b/.venv/lib/python3.12/site-packages/supervision/_cv2/_image.py new file mode 100644 index 0000000000000000000000000000000000000000..29e787d475fc61b1bbac1d63c36748c8883a0e51 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/_cv2/_image.py @@ -0,0 +1,372 @@ +"""Private image-operation and image-I/O fallbacks.""" + +from __future__ import annotations + +import os +from collections.abc import Sequence +from typing import Any, cast + +import numpy as np +import numpy.typing as npt + +from supervision._cv2._common import _cast_array_like_opencv +from supervision._cv2.constants import ( + _BORDER_CONSTANT, + _IMREAD_COLOR, + _IMREAD_UNCHANGED, + _INTER_LINEAR, + _INTER_NEAREST, +) + + +def _flip(image: npt.NDArray[Any], flip_code: int) -> npt.NDArray[Any]: + """Flip an image vertically, horizontally, or along both axes.""" + if flip_code == 0: + axes: tuple[int, ...] = (0,) + elif flip_code == 1: + axes = (1,) + elif flip_code == -1: + axes = (0, 1) + else: + raise ValueError(f"Unsupported flip code: {flip_code}") + return np.ascontiguousarray(np.flip(image, axis=axes)) + + +def _copy_make_border( + image: npt.NDArray[Any], + top: int, + bottom: int, + left: int, + right: int, + border_type: int, + value: int | float | Sequence[int | float] = 0, +) -> npt.NDArray[Any]: + """Add a constant border around an image.""" + if border_type != _BORDER_CONSTANT: + raise ValueError("Only BORDER_CONSTANT is supported by the fallback") + if min(top, bottom, left, right) < 0: + raise ValueError("Border sizes must be non-negative") + + height, width = image.shape[:2] + shape = (height + top + bottom, width + left + right, *image.shape[2:]) + + # OpenCV's Scalar(v) fills only channel 0 and zero-pads the rest for + # multichannel images — a bare scalar is treated the same as a + # length-1 sequence, not broadcast to every channel. + sequence_value = value if isinstance(value, Sequence) else (value,) + values = np.asarray(sequence_value, dtype=image.dtype).reshape(-1) + if image.ndim == 2: + fill_value: Any = values[0] if values.size else 0 + else: + fill = np.zeros(image.shape[2], dtype=image.dtype) + fill[: min(values.size, image.shape[2])] = values[: image.shape[2]] + fill_value = fill.reshape((1, 1, -1)) + + result = np.full(shape, fill_value, dtype=image.dtype) + result[top : top + height, left : left + width] = image + return result + + +def _add_weighted( + src1: npt.NDArray[Any], + alpha: float, + src2: npt.NDArray[Any], + beta: float, + gamma: float, + dst: npt.NDArray[Any] | None = None, + dtype: int | None = None, +) -> npt.NDArray[Any]: + """Blend two arrays with OpenCV-compatible saturation and optional mutation.""" + if dtype is not None and dtype != -1: + raise ValueError( + "addWeighted fallback only supports the default output depth; " + f"unsupported dtype: {dtype}" + ) + if src1.shape != src2.shape: + raise ValueError("addWeighted inputs must have equal shapes") + result = _cast_array_like_opencv( + src1.astype(np.float64) * alpha + src2.astype(np.float64) * beta + gamma, + src1.dtype, + ) + if dst is not None: + dst[...] = result + return dst + return result + + +def _convert_scale_abs( + image: npt.NDArray[Any], alpha: float = 1, beta: float = 0 +) -> npt.NDArray[np.uint8]: + """Scale, offset, take the absolute value, and saturate to uint8.""" + values = np.abs(image.astype(np.float64) * alpha + beta) + return _cast_array_like_opencv(values, np.dtype(np.uint8)) + + +def _mean( + image: npt.NDArray[Any], mask: npt.NDArray[Any] | None = None +) -> tuple[float, float, float, float]: + """Return per-channel means using OpenCV's four-value result contract.""" + if mask is None: + selected = ( + image.reshape(-1, 1) + if image.ndim == 2 + else image.reshape(-1, image.shape[2]) + ) + else: + if mask.shape != image.shape[:2]: + raise ValueError("Mean mask must match the image height and width") + selected = image[mask != 0] + if image.ndim == 2: + selected = selected.reshape(-1, 1) + if selected.size == 0: + means = np.zeros(4, dtype=np.float64) + else: + means = np.zeros(4, dtype=np.float64) + means[: selected.shape[1]] = np.mean(selected, axis=0) + return cast( + tuple[float, float, float, float], + tuple(float(value) for value in means), + ) + + +def _resize( + src: npt.NDArray[Any], + dsize: tuple[int, int] | None, + fx: float = 0, + fy: float = 0, + interpolation: int = _INTER_LINEAR, +) -> npt.NDArray[Any]: + """Resize with exact nearest or OpenCV-compatible linear sampling.""" + source_height, source_width = src.shape[:2] + width, height = dsize if dsize is not None else (0, 0) + if width == 0 or height == 0: + width = round(source_width * fx) + height = round(source_height * fy) + if min(width, height, source_width, source_height) <= 0: + raise ValueError("Resize dimensions must be positive") + + if interpolation == _INTER_NEAREST: + y_indices = np.minimum( + (np.arange(height) * source_height // height), source_height - 1 + ) + x_indices = np.minimum( + (np.arange(width) * source_width // width), source_width - 1 + ) + return np.ascontiguousarray(src[y_indices[:, np.newaxis], x_indices]) + + if interpolation != _INTER_LINEAR: + raise ValueError(f"Unsupported interpolation mode: {interpolation}") + + if src.dtype == np.uint8 and ( + src.ndim == 2 or (src.ndim == 3 and src.shape[2] == 3) + ): + from PIL import Image + + size = (width, height) + image = Image.fromarray(src) + if width >= source_width and height >= source_height: + resized = image.resize(size, resample=Image.Resampling.BILINEAR) + else: + # Affine sampling keeps Pillow from widening its bilinear kernel + # during reduction and maps pixel centers like INTER_LINEAR. + resized = image.transform( + size, + Image.Transform.AFFINE, + (source_width / width, 0, 0, 0, source_height / height, 0), + resample=Image.Resampling.BILINEAR, + ) + return np.ascontiguousarray(np.asarray(resized)) + + y = (np.arange(height) + 0.5) * source_height / height - 0.5 + x = (np.arange(width) + 0.5) * source_width / width - 0.5 + y_floor = np.floor(y).astype(np.int64) + x_floor = np.floor(x).astype(np.int64) + y0 = np.clip(y_floor, 0, source_height - 1) + y1 = np.clip(y_floor + 1, 0, source_height - 1) + x0 = np.clip(x_floor, 0, source_width - 1) + x1 = np.clip(x_floor + 1, 0, source_width - 1) + wy = y - y_floor + wx = x - x_floor + + source = src.astype(np.float64) + top_left = source[y0[:, np.newaxis], x0] + top_right = source[y0[:, np.newaxis], x1] + bottom_left = source[y1[:, np.newaxis], x0] + bottom_right = source[y1[:, np.newaxis], x1] + if src.ndim == 3: + wy = wy[:, np.newaxis, np.newaxis] + wx = wx[np.newaxis, :, np.newaxis] + else: + wy = wy[:, np.newaxis] + wx = wx[np.newaxis, :] + resized = ( + top_left * (1 - wx) * (1 - wy) + + top_right * wx * (1 - wy) + + bottom_left * (1 - wx) * wy + + bottom_right * wx * wy + ) + return np.ascontiguousarray(_cast_array_like_opencv(resized, src.dtype)) + + +_EXIF_ORIENTATION_TAG = 0x0112 + + +def _exif_oriented(image: Any) -> Any: + """Rotate and flip a Pillow image by its EXIF orientation tag, as OpenCV does. + + `cv2.imread` and `cv2.imdecode` apply the tag on every read except + `IMREAD_UNCHANGED`. An image without the tag, or with the identity orientation + `1`, is returned as it is rather than copied. + """ + from PIL import ImageOps + + if image.getexif().get(_EXIF_ORIENTATION_TAG, 1) == 1: + return image + return ImageOps.exif_transpose(image) + + +def _opencv_unchanged_mode(image: Any) -> str | None: + """Return the Pillow mode whose pixels match `cv2.imread(IMREAD_UNCHANGED)`. + + OpenCV keeps an image's bit depth and alpha, but never returns a two-channel or + boolean array the way Pillow's own modes do: it expands palettes to BGR, adds an + alpha channel for grayscale with alpha and for a palette or RGB image with a + transparent color, and reads 1-bit images as 8-bit `0` and `255`. It also never + returns CMYK ink values, whose black channel would pass for alpha: a CMYK JPEG + is converted to BGR, and a CMYK TIFF to BGRA with an opaque alpha channel. `None` + means the image's own mode already matches. + """ + has_transparency = "transparency" in image.info + if image.mode == "P": + return "RGBA" if has_transparency else "RGB" + if image.mode == "LA" or (image.mode == "RGB" and has_transparency): + return "RGBA" + if image.mode == "1": + return "L" + if image.mode == "CMYK": + return "RGBA" if image.format == "TIFF" else "RGB" + return None + + +def _read_pil_source(source: Any, flags: int) -> npt.NDArray[Any] | None: + """Decode any source Pillow can open into BGR or BGRA arrays.""" + from PIL import Image + + try: + with Image.open(source) as image: + if flags == _IMREAD_UNCHANGED: + unchanged_mode = _opencv_unchanged_mode(image) + if unchanged_mode is not None: + converted = image.convert(unchanged_mode) + values = np.asarray(converted) + converted.close() + else: + values = np.asarray(image) + elif image.mode in {"I", "I;16", "I;16B", "I;16L"}: + values = np.asarray(_exif_oriented(image)).astype(np.float64) + values = np.clip(np.rint(values / 256), 0, 255).astype(np.uint8) + if values.ndim == 2: + values = np.repeat(values[..., np.newaxis], 3, axis=2) + else: + values = np.asarray(_exif_oriented(image).convert("RGB")) + except (FileNotFoundError, OSError, ValueError): + return None + + if values.ndim == 3 and values.shape[2] == 3: + values = values[..., ::-1] + elif values.ndim == 3 and values.shape[2] == 4: + values = values[..., [2, 1, 0, 3]] + return np.ascontiguousarray(values) + + +def _imread(filename: str, flags: int = _IMREAD_COLOR) -> npt.NDArray[Any] | None: + """Read an image with Pillow while returning BGR or BGRA arrays.""" + return _read_pil_source(filename, flags) + + +def _imdecode( + buf: npt.NDArray[Any], flags: int = _IMREAD_COLOR +) -> npt.NDArray[Any] | None: + """Decode in-memory encoded image bytes, returning BGR or BGRA arrays.""" + import io + + data = np.asarray(buf, dtype=np.uint8).tobytes() + return _read_pil_source(io.BytesIO(data), flags) + + +def _bgr_to_pil_values(image: npt.NDArray[Any]) -> npt.NDArray[Any]: + """Reorder BGR or BGRA channels into the RGB order Pillow expects.""" + values = np.asarray(image) + if values.ndim == 3 and values.shape[2] == 3: + values = values[..., ::-1] + elif values.ndim == 3 and values.shape[2] == 4: + values = values[..., [2, 1, 0, 3]] + return np.ascontiguousarray(values) + + +def _opencv_default_save_options(image_format: str | None) -> dict[str, Any]: + """Return the Pillow save options that encode like OpenCV's default writers. + + Given no parameters, `cv2.imwrite` and `cv2.imencode` write JPEG at quality 95 and + WebP losslessly, while Pillow's defaults are JPEG at quality 75 and lossy WebP at + quality 80. Formats such as PNG, BMP and TIFF are lossless in both libraries. + """ + if image_format == "JPEG": + return {"quality": 95} + if image_format == "WEBP": + return {"lossless": True} + return {} + + +def _imwrite( + filename: str, image: npt.NDArray[Any], params: Sequence[int] | None = None +) -> bool: + """Write a BGR or BGRA array with Pillow and return OpenCV's boolean status. + + `params` is accepted for compatibility with `cv2.imwrite`'s signature and is + ignored: the file is encoded with the OpenCV defaults that + `_opencv_default_save_options` returns, not with the quality or compression the + caller asked for. + """ + from PIL import Image + + del params + extension = os.path.splitext(filename)[1].lower() + image_format = Image.registered_extensions().get(extension) + save_options = _opencv_default_save_options(image_format) + try: + Image.fromarray(_bgr_to_pil_values(image)).save(filename, **save_options) + except (OSError, ValueError): + return False + return True + + +def _imencode( + ext: str, image: npt.NDArray[Any], params: Sequence[int] | None = None +) -> tuple[bool, npt.NDArray[np.uint8] | None]: + """Encode a BGR or BGRA array in memory, mirroring `cv2.imencode`'s return. + + `params` is accepted for compatibility with `cv2.imencode`'s signature and is + ignored: the image is encoded with the OpenCV defaults that + `_opencv_default_save_options` returns, not with the quality or compression the + caller asked for. + """ + import io + + from PIL import Image + + del params + # A suffix is not its codec's name, so resolve it through the same registry + # `_imwrite` and `Image.save` consult for a file path. An unregistered suffix + # resolves to None, which `Image.save` rejects for a buffer with no file name. + extension = f".{ext.lstrip('.').lower()}" + image_format = Image.registered_extensions().get(extension) + save_options = _opencv_default_save_options(image_format) + buffer = io.BytesIO() + try: + Image.fromarray(_bgr_to_pil_values(image)).save( + buffer, format=image_format, **save_options + ) + except (KeyError, OSError, ValueError): + return False, None + return True, np.frombuffer(buffer.getvalue(), dtype=np.uint8) diff --git a/.venv/lib/python3.12/site-packages/supervision/_cv2/_text.py b/.venv/lib/python3.12/site-packages/supervision/_cv2/_text.py new file mode 100644 index 0000000000000000000000000000000000000000..4caa9d99859583ca70738d3b27d68ce8499aa8a1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/_cv2/_text.py @@ -0,0 +1,133 @@ +"""Private Pillow-based text fallback for the OpenCV compatibility facade. + +OpenCV renders text with built-in Hershey stroke fonts. The fallback instead +draws a proportional TrueType face (DejaVu Sans, shipped with Matplotlib, an +existing required dependency), so glyph shapes and text metrics differ from +OpenCV within the documented visual-divergence tier. ``getTextSize`` derives +its box from the same font ``putText`` renders with, so the reported rectangle +always encloses the drawn text. +""" + +from __future__ import annotations + +from functools import cache +from typing import Any + +import numpy as np +import numpy.typing as npt +from PIL import Image, ImageDraw + +from supervision._cv2._drawing import _paint +from supervision._cv2.constants import _FONT_ITALIC, _LINE_8 + +_ImageArray = npt.NDArray[Any] + +# OpenCV's font_scale is unit-relative rather than a pixel size. This factor +# maps it to a Pillow point size whose cap height lands near OpenCV's Hershey +# Simplex at the same scale; it is a readability choice, not an exact metric +# match (which no proportional TrueType face can provide). +_PIXELS_PER_SCALE = 32 + + +@cache +def _font_path(italic: bool) -> str: + """Locate a bundled DejaVu Sans face through Matplotlib's font manager.""" + from matplotlib import font_manager + + style = "italic" if italic else "normal" + properties = font_manager.FontProperties(family="DejaVu Sans", style=style) + return str(font_manager.findfont(properties)) + + +@cache +def _load_font(font_face: int, font_scale: float) -> Any: + """Return a cached Pillow font sized for an OpenCV font scale.""" + from PIL import ImageFont + + size = max(1, round(font_scale * _PIXELS_PER_SCALE)) + return ImageFont.truetype(_font_path(bool(font_face & _FONT_ITALIC)), size) + + +def _stroke_width(thickness: int) -> int: + """Map an OpenCV stroke thickness to the Pillow stroke_width it renders with.""" + return max(0, thickness - 1) + + +def _get_text_size( + text: str, fontFace: int, fontScale: float, thickness: int +) -> tuple[tuple[int, int], int]: + """Return an OpenCV-shaped ``((width, height), baseline)`` for the face. + + Height is the font ascent and baseline the descent, both string-independent + like OpenCV's contract, so consumers get stable row heights. Padding uses + the same stroke_width _put_text renders with: Pillow's stroke dilates the + glyph outline by stroke_width pixels on every side, so width grows by + twice that (left and right) while height and baseline each grow by one + stroke_width (top and bottom). + """ + font = _load_font(fontFace, fontScale) + ascent, descent = font.getmetrics() + stroke_width = _stroke_width(thickness) + width = round(font.getlength(text)) + 2 * stroke_width + height = ascent + stroke_width + baseline = descent + stroke_width + return (width, height), baseline + + +def _put_text( + img: _ImageArray, + text: str, + org: tuple[int, int], + fontFace: int, + fontScale: float, + color: Any, + thickness: int = 1, + lineType: int = _LINE_8, + bottomLeftOrigin: bool = False, +) -> _ImageArray: + """Render text with a Pillow face, anchored at OpenCV's baseline origin. + + Thickness maps to a Pillow stroke width to emulate OpenCV's bolder strokes. + ``bottomLeftOrigin`` (an inverted-axis mode no Supervision caller uses) is + rejected rather than silently ignored. + """ + del lineType + if bottomLeftOrigin: + raise ValueError("bottomLeftOrigin is not supported by the fallback") + if not text: + return img + + font = _load_font(fontFace, fontScale) + stroke_width = _stroke_width(thickness) + x, y = round(org[0]), round(org[1]) + left, top, right, bottom = font.getbbox( + text, anchor="ls", stroke_width=stroke_width + ) + width, height = right - left, bottom - top + if width <= 0 or height <= 0: + return img + + mask_image = Image.new("1", (width, height)) + ImageDraw.Draw(mask_image).text( + (-left, -top), + text, + fill=1, + font=font, + anchor="ls", + stroke_width=stroke_width, + ) + mask = np.asarray(mask_image, dtype=bool) + + image_height, image_width = img.shape[:2] + x_start, y_start = max(0, x + left), max(0, y + top) + x_stop, y_stop = min(image_width, x + right), min(image_height, y + bottom) + if x_start >= x_stop or y_start >= y_stop: + return img + mask_x = x_start - (x + left) + mask_y = y_start - (y + top) + clipped_mask = mask[ + mask_y : mask_y + (y_stop - y_start), + mask_x : mask_x + (x_stop - x_start), + ] + _paint(img[y_start:y_stop, x_start:x_stop], clipped_mask, color) + return img diff --git a/.venv/lib/python3.12/site-packages/supervision/_cv2/_transform.py b/.venv/lib/python3.12/site-packages/supervision/_cv2/_transform.py new file mode 100644 index 0000000000000000000000000000000000000000..0e5b0a3da1f66706637d7979639373a5c4efb4f0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/_cv2/_transform.py @@ -0,0 +1,26 @@ +"""Private transform and filter fallbacks.""" + +from __future__ import annotations + +from typing import Any + +import numpy as np +import numpy.typing as npt + +from supervision._cv2._common import _cast_array_like_opencv + + +def _blur( + image: npt.NDArray[Any], ksize: tuple[int, int], border_type: int = 4 +) -> npt.NDArray[Any]: + """Apply a box filter with OpenCV's default reflect-101 boundary behavior.""" + if min(ksize) <= 0: + raise ValueError("Blur kernel dimensions must be positive") + if border_type != 4: + raise ValueError("Only OpenCV's default blur border is supported") + + from scipy import ndimage + + size = (*ksize[::-1], 1) if image.ndim == 3 else ksize[::-1] + values = ndimage.uniform_filter(image.astype(np.float64), size=size, mode="mirror") + return np.ascontiguousarray(_cast_array_like_opencv(values, image.dtype)) diff --git a/.venv/lib/python3.12/site-packages/supervision/_cv2/_video.py b/.venv/lib/python3.12/site-packages/supervision/_cv2/_video.py new file mode 100644 index 0000000000000000000000000000000000000000..f7f90bb4b617ba90cdc84b402d75cc0e5d771d64 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/_cv2/_video.py @@ -0,0 +1,431 @@ +"""Private PyAV-backed video and audio fallbacks.""" + +from __future__ import annotations + +import logging +import os +import tempfile +from collections.abc import Callable, Iterator +from fractions import Fraction +from pathlib import Path +from typing import Any + +import numpy as np +import numpy.typing as npt + +from supervision._cv2._common import BackendUnavailableError +from supervision._cv2.constants import ( + _CAP_PROP_FPS, + _CAP_PROP_FRAME_COUNT, + _CAP_PROP_FRAME_HEIGHT, + _CAP_PROP_FRAME_WIDTH, + _CAP_PROP_POS_FRAMES, +) + +logger = logging.getLogger(__name__) + +# PyAV is imported locally in each function below, not at module scope: it +# bundles its own `libavdevice`, which macOS's Objective-C runtime treats as +# a duplicate of the one OpenCV's wheel already bundles when both are loaded +# into the same process (GH-2505). Deferring the import until a PyAV-backed +# capture/writer/remux call actually happens keeps an OpenCV-only import +# from ever touching PyAV's native libraries. + +_CODECS = { + "mp4v": ("mpeg4", "yuv420p"), + "xvid": ("mpeg4", "yuv420p"), + "avc1": ("libx264", "yuv420p"), + "h264": ("libx264", "yuv420p"), + "mjpg": ("mjpeg", "yuvj420p"), + "vp09": ("libvpx-vp9", "yuv420p"), +} + + +def _video_writer_fourcc(*chars: str) -> int: + """Encode four single-character strings using OpenCV's integer layout.""" + if len(chars) != 4 or any(len(char) != 1 for char in chars): + raise TypeError("VideoWriter_fourcc requires exactly four characters") + return sum(ord(char) << (8 * index) for index, char in enumerate(chars)) + + +def _decode_fourcc(fourcc: int) -> str: + """Decode a fourcc integer into its four-character representation.""" + return "".join(chr((fourcc >> (8 * index)) & 0xFF) for index in range(4)) + + +def _codec_details(fourcc: int) -> tuple[str, str]: + """Return the PyAV codec and pixel format for a supported fourcc.""" + code = _decode_fourcc(fourcc).lower() + try: + return _CODECS[code] + except KeyError as exc: + raise ValueError(f"Unsupported video codec: {code!r}") from exc + + +def _quarter_turns(rotation: int) -> int: + """Return the counterclockwise quarter turns OpenCV applies for a display rotation. + + Phones store a portrait video as landscape frames plus a display matrix, and + OpenCV's FFmpeg backend turns every frame upright by that matrix, but only for + multiples of 90 degrees; any other angle is left alone. + """ + quarter_turns, remainder = divmod(rotation, 90) + return 0 if remainder else quarter_turns % 4 + + +class _VideoCapture: + """Expose OpenCV-shaped file capture backed by PyAV decoding.""" + + def __init__(self, source: str | os.PathLike[str] | int) -> None: + """Open a file source and retain a lazy PyAV frame iterator.""" + self._container: Any = None + self._stream: Any = None + self._frames: Iterator[Any] | None = None + self._source = source + self._position = 0 + self._frame_count_cache: int | None = None + self._rotation_cache: int | None = None + self._opened = False + self._error: Exception | None = None + + try: + if isinstance(source, int): + raise BackendUnavailableError( + "PyAV fallback supports file paths, not webcam device indexes." + ) + import av + + self._container = av.open(str(source), mode="r") + if not self._container.streams.video: + raise ValueError(f"Video source has no video stream: {source}") + self._stream = self._container.streams.video[0] + self._frames = iter(self._container.decode(video=self._stream.index)) + self._opened = True + except Exception as exc: + self._error = exc + logger.warning("Failed to open video source %r: %s", source, exc) + self.release() + + def isOpened(self) -> bool: + """Return whether the underlying video file is open for reading.""" + return self._opened + + def _frame_count(self) -> int: + """Return the stream count, decoding a second handle if metadata lacks it.""" + if self._frame_count_cache is not None: + return self._frame_count_cache + + count = int(getattr(self._stream, "frames", 0) or 0) + if count <= 0 and not isinstance(self._source, int): + import av + + container = av.open(str(self._source), mode="r") + try: + count = sum(1 for _ in container.decode(video=self._stream.index)) + finally: + container.close() + self._frame_count_cache = count + return count + + def _rotation(self) -> int: + """Return the stream's display rotation, decoding one frame on a second handle. + + PyAV only exposes the display matrix on decoded frames, so the first frame is + decoded from a separate container to leave this capture's position untouched. + """ + if self._rotation_cache is not None: + return self._rotation_cache + + import av + + container = av.open(str(self._source), mode="r") + try: + frames = container.decode(video=self._stream.index) + rotation = next((int(frame.rotation) for frame in frames), 0) + finally: + container.close() + self._rotation_cache = rotation + return rotation + + def get(self, property_id: int) -> float: + """Return the supported OpenCV capture property as a float. + + Width and height are those of the upright frames `read` returns, so they swap + for a video whose display matrix turns it by a quarter, as in OpenCV. + """ + if not self._opened: + return 0.0 + if property_id in (_CAP_PROP_FRAME_WIDTH, _CAP_PROP_FRAME_HEIGHT): + width, height = self._stream.width, self._stream.height + if _quarter_turns(self._rotation()) % 2: + width, height = height, width + return float(width if property_id == _CAP_PROP_FRAME_WIDTH else height) + if property_id == _CAP_PROP_FPS: + rate = getattr(self._stream, "average_rate", None) or getattr( + self._stream, "base_rate", None + ) + return float(rate) if rate is not None else 0.0 + if property_id == _CAP_PROP_FRAME_COUNT: + return float(self._frame_count()) + if property_id == _CAP_PROP_POS_FRAMES: + return float(self._position) + return 0.0 + + def _reset(self) -> None: + """Seek the decoder to the first frame and reset the logical position.""" + self._container.seek(0, stream=self._stream, backward=True) + self._frames = iter(self._container.decode(video=self._stream.index)) + self._position = 0 + + def set(self, property_id: int, value: float) -> bool: + """Set the supported frame-position property using exact frame decoding.""" + if not self._opened or property_id != _CAP_PROP_POS_FRAMES: + return False + target = max(0, round(value)) + if target > self._frame_count(): + return False + if target < self._position: + self._reset() + while self._position < target: + success, _ = self.read() + if not success: + return False + return True + + def read(self) -> tuple[bool, npt.NDArray[np.uint8] | None]: + """Decode and return the next frame upright in OpenCV's BGR array format.""" + if not self._opened or self._frames is None: + return False, None + try: + frame = next(self._frames) + except StopIteration: + return False, None + except Exception as exc: + self._error = exc + return False, None + + self._position += 1 + image = frame.to_ndarray(format="bgr24") + quarter_turns = _quarter_turns(int(frame.rotation)) + if quarter_turns: + image = np.ascontiguousarray(np.rot90(image, quarter_turns)) + return True, image + + def grab(self) -> bool: + """Decode and discard one frame.""" + success, _ = self.read() + return success + + def release(self) -> None: + """Close the PyAV container and make subsequent reads return false.""" + container = self._container + self._container = None + self._stream = None + self._frames = None + self._opened = False + if container is not None: + container.close() + + +class _VideoWriter: + """Expose OpenCV-shaped video writing backed by PyAV encoding.""" + + def __init__( + self, + filename: str | os.PathLike[str], + fourcc: int, + fps: float, + frame_size: tuple[int, int], + is_color: bool = True, + ) -> None: + """Open a PyAV writer for the requested codec and frame dimensions. + + The PyAV fallback always encodes 3-channel BGR frames, so grayscale + output is unsupported. ``is_color=False`` is rejected up front rather + than silently ignored, keeping the OpenCV-shaped contract honest for + callers that would otherwise expect single-channel writes. + + Raises: + NotImplementedError: If ``is_color`` is ``False``; grayscale + writing is not supported by the PyAV fallback. + """ + if not is_color: + raise NotImplementedError( + "PyAV video fallback only supports color (3-channel BGR) frames; " + "is_color=False is not implemented." + ) + self._container: Any = None + self._stream: Any = None + self._width, self._height = frame_size + self._opened = False + self._error: Exception | None = None + + try: + import av + + codec, pixel_format = _codec_details(fourcc) + self._container = av.open(str(filename), mode="w") + rate = Fraction(str(fps)).limit_denominator(100_000) + self._stream = self._container.add_stream(codec, rate=rate) + self._stream.width = self._width + self._stream.height = self._height + self._stream.pix_fmt = pixel_format + self._opened = True + except Exception as exc: + self._error = exc + self.release() + + def isOpened(self) -> bool: + """Return whether the writer initialized successfully.""" + return self._opened + + def write(self, frame: npt.NDArray[np.uint8]) -> None: + """Encode one BGR frame and mux all packets produced by the encoder.""" + if not self._opened or self._container is None or self._stream is None: + raise RuntimeError("Video writer is not open") from self._error + if frame.shape != (self._height, self._width, 3): + raise ValueError( + "Video frame must have shape " + f"({self._height}, {self._width}, 3), got {frame.shape}" + ) + if frame.dtype != np.uint8: + raise ValueError("Video frames must use uint8 dtype") + + import av + + video_frame = av.VideoFrame.from_ndarray( + np.ascontiguousarray(frame), format="bgr24" + ) + for packet in self._stream.encode(video_frame): + self._container.mux(packet) + + def release(self) -> None: + """Flush delayed encoder packets and close the output container.""" + container = self._container + stream = self._stream + self._container = None + self._stream = None + self._opened = False + if container is None: + return + try: + if stream is not None: + for packet in stream.encode(): + container.mux(packet) + finally: + container.close() + + +def _timestamp_seconds(timestamp: int | None, time_base: Any) -> float | None: + """Convert a stream timestamp to seconds while preserving missing values.""" + return None if timestamp is None else float(timestamp * time_base) + + +def _best_effort_cleanup(action: Callable[[], None], description: str) -> None: + """Run a cleanup action, logging and suppressing any failure. + + Cleanup steps in a ``finally`` block must never raise, otherwise a failing + ``container.close()`` (or file removal) would mask or replace the primary + result or the original exception that sent control into ``finally``. + """ + try: + action() + except Exception as exc: + logger.debug("Cleanup step failed (%s): %s", description, exc) + + +def _mux_audio(source_path: str, video_path: str) -> None: + """Remux the source's first audio stream into the processed video with PyAV.""" + source_container: Any = None + video_container: Any = None + output_container: Any = None + temporary_path: str | None = None + try: + import av + + source_container = av.open(source_path, mode="r") + video_container = av.open(video_path, mode="r") + if not source_container.streams.audio or not video_container.streams.video: + logger.info("No audio or video stream available; leaving output unchanged") + return + + source_audio = source_container.streams.audio[0] + target_video = video_container.streams.video[0] + suffix = Path(video_path).suffix + with tempfile.NamedTemporaryFile( + suffix=suffix, dir=str(Path(video_path).absolute().parent), delete=False + ) as temporary_file: + temporary_path = temporary_file.name + + output_container = av.open(temporary_path, mode="w") + output_video = output_container.add_stream_from_template(target_video) + output_audio = output_container.add_stream_from_template(source_audio) + + # Copy encoded packets to avoid a lossy decode/re-encode cycle for both streams. + video_base: int | None = None + video_duration: float | None = None + for packet in video_container.demux(target_video): + if packet.pts is None and packet.dts is None: + continue + if video_base is None: + video_base = packet.pts if packet.pts is not None else packet.dts + if video_base is None: + continue + packet.pts = None if packet.pts is None else packet.pts - video_base + packet.dts = None if packet.dts is None else packet.dts - video_base + packet.stream = output_video + output_container.mux(packet) + packet_end = packet.pts + if packet_end is not None: + packet_end += packet.duration or 0 + packet_seconds = _timestamp_seconds(packet_end, target_video.time_base) + if packet_seconds is not None: + video_duration = max(video_duration or 0.0, packet_seconds) + + # Rebase audio independently and stop at the processed video duration, matching + # ffmpeg's `-shortest` behavior without requiring a system executable. + audio_base: int | None = None + for packet in source_container.demux(source_audio): + if packet.pts is None and packet.dts is None: + continue + if audio_base is None: + audio_base = packet.pts if packet.pts is not None else packet.dts + if audio_base is None: + continue + relative_pts = None if packet.pts is None else packet.pts - audio_base + relative_seconds = _timestamp_seconds(relative_pts, source_audio.time_base) + if ( + video_duration is not None + and relative_seconds is not None + and relative_seconds > video_duration + ): + break + packet.pts = relative_pts + packet.dts = None if packet.dts is None else packet.dts - audio_base + packet.stream = output_audio + output_container.mux(packet) + + output_container.close() + output_container = None + video_container.close() + video_container = None + source_container.close() + source_container = None + os.replace(temporary_path, video_path) + temporary_path = None + except Exception as exc: + logger.warning("Audio remuxing failed: %s. Output video has no audio.", exc) + finally: + # Cleanup runs best-effort: a failing close/remove here must not mask the + # primary result or replace the original exception handled above. + if output_container is not None: + _best_effort_cleanup(output_container.close, "closing output container") + if video_container is not None: + _best_effort_cleanup(video_container.close, "closing video container") + if source_container is not None: + _best_effort_cleanup(source_container.close, "closing source container") + if temporary_path is not None and os.path.exists(temporary_path): + leftover_path = temporary_path + _best_effort_cleanup( + lambda: os.remove(leftover_path), "removing temporary file" + ) diff --git a/.venv/lib/python3.12/site-packages/supervision/_cv2/constants.py b/.venv/lib/python3.12/site-packages/supervision/_cv2/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..3ab4fc783404d9049d7924230bd3d2df5e421902 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/_cv2/constants.py @@ -0,0 +1,32 @@ +"""Private numeric constants used by the OpenCV compatibility modules.""" + +_BORDER_CONSTANT = 0 +_CAP_PROP_FPS = 5 +_CAP_PROP_FRAME_COUNT = 7 +_CAP_PROP_FRAME_HEIGHT = 4 +_CAP_PROP_FRAME_WIDTH = 3 +_CAP_PROP_POS_FRAMES = 1 +_CC_STAT_AREA = 4 +_CHAIN_APPROX_SIMPLE = 2 +_COLOR_BGR2GRAY = 6 +_COLOR_BGR2RGB = 4 +_COLOR_GRAY2BGR = 8 +_COLOR_HSV2BGR = 54 +_COLOR_RGB2BGR = 4 +_FONT_HERSHEY_SIMPLEX = 0 +_FONT_HERSHEY_PLAIN = 1 +_FONT_HERSHEY_DUPLEX = 2 +_FONT_HERSHEY_COMPLEX = 3 +_FONT_HERSHEY_TRIPLEX = 4 +_FONT_HERSHEY_COMPLEX_SMALL = 5 +_FONT_HERSHEY_SCRIPT_SIMPLEX = 6 +_FONT_HERSHEY_SCRIPT_COMPLEX = 7 +_FONT_ITALIC = 16 +_IMREAD_COLOR = 1 +_IMREAD_UNCHANGED = -1 +_INTER_LINEAR = 1 +_INTER_NEAREST = 0 +_LINE_4 = 4 +_LINE_8 = 8 +_LINE_AA = 16 +_RETR_TREE = 3 diff --git a/.venv/lib/python3.12/site-packages/supervision/annotators/__init__.py b/.venv/lib/python3.12/site-packages/supervision/annotators/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/supervision/annotators/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/annotators/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad1a3e4caa807a287ff088f8f4e5ea0e707afac5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/annotators/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/annotators/__pycache__/base.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/annotators/__pycache__/base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d7c0420674e948babc2ed24f173f1833510689b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/annotators/__pycache__/base.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/annotators/__pycache__/core.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/annotators/__pycache__/core.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f5ed89620ea6d93891d9bcb2670291df15f3039e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/annotators/__pycache__/core.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3052e3da8305f5d139ce024b04f51b551334c6fcc969e432da03ff39ce4e365e +size 147406 diff --git a/.venv/lib/python3.12/site-packages/supervision/annotators/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/annotators/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a6daf6cc72d1e96c1b336db8eb4fda4d8853361 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/annotators/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/annotators/base.py b/.venv/lib/python3.12/site-packages/supervision/annotators/base.py new file mode 100644 index 0000000000000000000000000000000000000000..d8f6f2c67364bc2a890e00c5e966dc6ad0c1d3d1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/annotators/base.py @@ -0,0 +1,21 @@ +from abc import ABC, abstractmethod +from typing import Any + +from supervision.detection.core import Detections + + +class BaseAnnotator(ABC): + """Base class for annotators that consume :class:`Detections`. + + Attributes: + requires_mask: Whether integrations must provide ``Detections.mask`` for + this annotator. Check this before materializing expensive mask payloads. + """ + + requires_mask: bool = False + + @abstractmethod + def annotate( + self, scene: Any, detections: Detections, *args: Any, **kwargs: Any + ) -> Any: + pass diff --git a/.venv/lib/python3.12/site-packages/supervision/annotators/core.py b/.venv/lib/python3.12/site-packages/supervision/annotators/core.py new file mode 100644 index 0000000000000000000000000000000000000000..e43928193e95f2cc595134859dd5d0b6ef70c5cd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/annotators/core.py @@ -0,0 +1,3658 @@ +from collections.abc import Iterator +from functools import lru_cache +from math import sqrt +from typing import Any, ClassVar, cast + +import numpy as np +import numpy.typing as npt +from deprecate import deprecated, void # type: ignore[import-untyped,unused-ignore] +from PIL import Image, ImageDraw, ImageFont +from scipy.interpolate import splev, splprep + +from supervision import _cv2 as cv2 +from supervision.annotators.base import BaseAnnotator +from supervision.annotators.utils import ( + PENDING_TRACK_ID, + ColorLookup, + Trace, + _validate_labels, + calculate_dynamic_kernel_size, + calculate_dynamic_pixel_size, + get_labels_text, + hex_to_rgba, + resolve_color, + resolve_text_background_xyxy, + snap_boxes, + wrap_text, +) +from supervision.config import ORIENTED_BOX_COORDINATES +from supervision.detection.compact_mask import CompactMask +from supervision.detection.core import Detections +from supervision.detection.utils.boxes import clip_boxes, spread_out_boxes +from supervision.detection.utils.converters import ( + mask_to_polygons, + polygon_to_mask, + xyxy_to_polygons, +) +from supervision.detection.utils.masks import _masks_to_roi +from supervision.draw.base import ImageType +from supervision.draw.color import Color, ColorPalette +from supervision.draw.utils import draw_polygon, draw_rounded_rectangle, draw_text +from supervision.geometry.core import Point, Position, Rect +from supervision.utils.conversion import ( + ensure_cv2_image_for_class_method, + ensure_pil_image_for_class_method, +) +from supervision.utils.image import ( + _overlay_image, + crop_image, + letterbox_image, + scale_image, +) +from supervision.utils.logger import _get_logger + +logger = _get_logger(__name__) + + +@lru_cache +def _load_icon_from_path( + icon_path: str, icon_resolution_wh: tuple[int, int] +) -> npt.NDArray[np.uint8]: + """Load and resize an icon image through a cache shared by annotators. + + Icons are read unchanged to keep their alpha channel, which also keeps a grayscale + PNG as a 2-D array and a 16-bit PNG at 16 bits. A 16-bit icon is scaled down to 8 + bits and a grayscale icon is expanded to BGR, the depth and layout the icon overlay + draws; an icon of any other pixel type is rejected. + """ + icon = cv2.imread(icon_path, cv2.IMREAD_UNCHANGED) + if icon is None: + raise FileNotFoundError(f"Error: Couldn't load the icon image from {icon_path}") + icon_array: npt.NDArray[np.uint8] + if icon.dtype == np.uint8: + icon_array = cast(npt.NDArray[np.uint8], icon) + elif icon.dtype == np.uint16: + # The overlay writes the icon into an 8-bit scene, where a 16-bit value wraps + # modulo 256 and redraws a bright icon as a dark one; keep the high byte. + icon_array = np.clip(np.rint(icon / 256), 0, 255).astype(np.uint8) + else: + raise ValueError( + f"Icon image ('{icon_path}') has an unsupported pixel type " + f"('{icon.dtype}'); an icon must be 8-bit or 16-bit." + ) + if icon_array.ndim == 2: + icon_array = cast( + npt.NDArray[np.uint8], cv2.cvtColor(icon_array, cv2.COLOR_GRAY2BGR) + ) + result: npt.NDArray[np.uint8] = letterbox_image( + image=icon_array, resolution_wh=icon_resolution_wh + ) + return result + + +def _normalize_color_input(color: Color | ColorPalette | str) -> Color | ColorPalette: + """Normalize accepted color inputs to internal color objects. + + Accepts `Color`, `ColorPalette`, or hex string input. Hex strings are parsed via + `hex_to_rgba` and converted to `Color` (alpha channel is ignored because annotator + drawing uses RGB/BGR colors). + """ + if isinstance(color, str): + r, g, b, _ = hex_to_rgba(color) + return Color.from_rgb_tuple((r, g, b)) + return color + + +CV2_FONT = cv2.FONT_HERSHEY_SIMPLEX + + +class _BaseLabelAnnotator(BaseAnnotator): + """ + Base class for annotators that add labels to detections. + + Attributes: + color: The color to use for the label background. + color_lookup: The method used to determine the color of the label. + text_color: The color to use for the label text. + text_padding: The padding around the label text, in pixels. + text_anchor: The position of the text relative to the detection + bounding box. + text_offset: A tuple of 2D coordinates `(x, y)` to + offset the text position from the anchor point, in pixels. + border_radius: The radius of the label background corners, in pixels. + smart_position: Whether to intelligently adjust the label position to + avoid overlapping with other elements. + max_line_length: Maximum number of characters per line before + wrapping the text. None means no wrapping. + """ + + def __init__( + self, + color: Color | ColorPalette | str = ColorPalette.DEFAULT, + color_lookup: ColorLookup = ColorLookup.CLASS, + text_color: Color | ColorPalette | str = Color.WHITE, + text_padding: int = 10, + text_position: Position = Position.TOP_LEFT, + text_offset: tuple[int, int] = (0, 0), + border_radius: int = 0, + smart_position: bool = False, + max_line_length: int | None = None, + ): + """ + Initializes the _BaseLabelAnnotator. + + Args: + color: The color to use for the label + background. + color_lookup: The method used to determine the color + of the label + text_color: The color to use for the + label text. + text_padding: The padding around the label text, in pixels. + text_position: The position of the text relative to the + detection bounding box. + text_offset: A tuple of 2D coordinates + `(x, y)` to offset the text position from the anchor point, in pixels. + border_radius: The radius of the label background corners, + in pixels. + smart_position: Whether to intelligently adjust the label + position to avoid overlapping with other elements. + max_line_length: Maximum number of characters per + line before wrapping the text. None means no wrapping. + """ + self.color: Color | ColorPalette = _normalize_color_input(color) + self.color_lookup: ColorLookup = color_lookup + self.text_color: Color | ColorPalette = _normalize_color_input(text_color) + self.text_padding: int = text_padding + self.text_anchor: Position = text_position + self.text_offset: tuple[int, int] = text_offset + self.border_radius: int = border_radius + self.smart_position = smart_position + self.max_line_length: int | None = max_line_length + + def _adjust_labels_in_frame( + self, + resolution_wh: tuple[int, int], + labels: list[str], + label_properties: npt.NDArray[np.float32], + ) -> npt.NDArray[np.float32]: + """ + Adjusts the position of labels to ensure they stay within the frame boundaries. + + Args: + resolution_wh: The width and height of the frame. + labels: The list of text labels. + label_properties: An array of label properties, where each row + contains [x1, y1, x2, y2, text_height, ...]. + + Returns: + The adjusted label properties. + """ + adjusted_properties = label_properties.copy() + + # First, make sure the boxes don't go outside the frame + adjusted_properties[:, :4] = snap_boxes( + adjusted_properties[:, :4], + resolution_wh, + ) + + # Apply the spread out algorithm to avoid box overlaps + if len(labels) > 1: + # Extract the box coordinates + boxes = adjusted_properties[:, :4] + # Use the spread_out_boxes function to adjust overlapping boxes + spread_boxes = spread_out_boxes(boxes) + # Update the properties with the spread out boxes + adjusted_properties[:, :4] = spread_boxes + + # Additional check to ensure boxes are still within frame after spreading + adjusted_properties[:, :4] = snap_boxes( + adjusted_properties[:, :4], resolution_wh + ) + + return cast( + npt.NDArray[np.float32], + np.asarray(adjusted_properties, dtype=np.float32), + ) + + +class BoxAnnotator(BaseAnnotator): + """ + A class for drawing bounding boxes on an image using provided detections. + """ + + def __init__( + self, + color: Color | ColorPalette | str = ColorPalette.DEFAULT, + thickness: int = 2, + color_lookup: ColorLookup = ColorLookup.CLASS, + ): + """ + Args: + color: The color or color palette to use for + annotating detections. + thickness: Thickness of the bounding box lines. + color_lookup: Strategy for mapping colors to annotations. + Options are `INDEX`, `CLASS`, `TRACK`. + """ + self.color: Color | ColorPalette = _normalize_color_input(color) + self.thickness: int = thickness + self.color_lookup: ColorLookup = color_lookup + + @ensure_cv2_image_for_class_method + def annotate( + self, + scene: ImageType, + detections: Detections, + custom_color_lookup: npt.NDArray[np.int_] | None = None, + ) -> ImageType: + """ + Annotates the given scene with bounding boxes based on the provided detections. + + Args: + scene: The image where bounding boxes will be drawn. `ImageType` + is a flexible type, accepting either `numpy.ndarray` or + `PIL.Image.Image`. + detections: Object detections to annotate. + custom_color_lookup: Custom color lookup array. + Allows to override the default color mapping strategy. + + Returns: + The annotated image, matching the type of `scene` (`numpy.ndarray` + or `PIL.Image.Image`) + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> image = np.zeros((100, 100, 3), dtype=np.uint8) + >>> detections = sv.Detections( + ... xyxy=np.array([[20, 20, 80, 80]]), + ... class_id=np.array([0]) + ... ) + >>> box_annotator = sv.BoxAnnotator() + >>> annotated_frame = box_annotator.annotate( + ... scene=image.copy(), + ... detections=detections + ... ) + + ``` + + ![bounding-box-annotator-example](https://media.roboflow.com/ + supervision-annotator-examples/bounding-box-annotator-example-purple.png) + """ + if not isinstance(scene, np.ndarray): + return scene + for detection_idx in range(len(detections)): + x1, y1, x2, y2 = detections.xyxy[detection_idx].astype(int) + color = resolve_color( + color=self.color, + detections=detections, + detection_idx=detection_idx, + color_lookup=self.color_lookup + if custom_color_lookup is None + else custom_color_lookup, + ) + cv2.rectangle( + img=scene, + pt1=(x1, y1), + pt2=(x2, y2), + color=color.as_bgr(), + thickness=self.thickness, + ) + return scene + + +class OrientedBoxAnnotator(BaseAnnotator): + """ + A class for drawing oriented bounding boxes on an image using provided detections. + """ + + def __init__( + self, + color: Color | ColorPalette | str = ColorPalette.DEFAULT, + thickness: int = 2, + color_lookup: ColorLookup = ColorLookup.CLASS, + ): + """ + Args: + color: The color or color palette to use for + annotating detections. + thickness: Thickness of the bounding box lines. + color_lookup: Strategy for mapping colors to annotations. + Options are `INDEX`, `CLASS`, `TRACK`. + """ + self.color: Color | ColorPalette = _normalize_color_input(color) + self.thickness: int = thickness + self.color_lookup: ColorLookup = color_lookup + + @ensure_cv2_image_for_class_method + def annotate( + self, + scene: ImageType, + detections: Detections, + custom_color_lookup: npt.NDArray[np.int_] | None = None, + ) -> ImageType: + """ + Annotates the given scene with oriented bounding boxes based on the + provided detections. + + Args: + scene: The image where bounding boxes will be drawn. + `ImageType` is a flexible type, accepting either `numpy.ndarray` + or `PIL.Image.Image`. + detections: Object detections to annotate. + custom_color_lookup: Custom color lookup array. + Allows to override the default color mapping strategy. + + Returns: + The annotated image, matching the type of `scene` (`numpy.ndarray` + or `PIL.Image.Image`) + + Examples: + ```python + from supervision import _cv2 as cv2 + import supervision as sv + from ultralytics import YOLO + + image = cv2.imread("") + model = YOLO("yolov8n-obb.pt") + + result = model(image)[0] + detections = sv.Detections.from_ultralytics(result) + + oriented_box_annotator = sv.OrientedBoxAnnotator() + annotated_frame = oriented_box_annotator.annotate( + scene=image.copy(), + detections=detections + ) + ``` + + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> from supervision.config import ORIENTED_BOX_COORDINATES + >>> image = np.zeros((100, 100, 3), dtype=np.uint8) + >>> obb = np.array([[[20, 20], [80, 20], [80, 80], [20, 80]]]) + >>> detections = sv.Detections( + ... xyxy=np.array([[20, 20, 80, 80]]), + ... class_id=np.array([0]), + ... data={ORIENTED_BOX_COORDINATES: obb}, + ... ) + >>> oriented_box_annotator = sv.OrientedBoxAnnotator() + >>> annotated_frame = oriented_box_annotator.annotate( + ... scene=image.copy(), + ... detections=detections + ... ) + + ``` + """ + if not isinstance(scene, np.ndarray): + return scene + if detections.data is None or ORIENTED_BOX_COORDINATES not in detections.data: + return scene + obb_boxes = np.array(detections.data[ORIENTED_BOX_COORDINATES]).astype(int) + + for detection_idx in range(len(detections)): + obb = obb_boxes[detection_idx] + color = resolve_color( + color=self.color, + detections=detections, + detection_idx=detection_idx, + color_lookup=self.color_lookup + if custom_color_lookup is None + else custom_color_lookup, + ) + + cv2.drawContours(scene, [obb], 0, color.as_bgr(), self.thickness) + + return scene + + +# --- Shared mask-painting utilities --- +def _iter_mask_crops( + detections: Detections, +) -> Iterator[tuple[int, npt.NDArray[np.bool_], npt.NDArray[np.int32] | None]]: + """Yield ``(detection_idx, mask_or_crop, offset_or_None)`` for each mask. + + Encapsulates the ``CompactMask`` vs dense dispatch so individual annotators + do not need inline ``isinstance`` checks. For ``CompactMask`` inputs yields + the bbox crop and its ``(x1, y1)`` image-space origin; for dense masks + yields the full-frame boolean slice with ``offset=None``. + + Args: + detections: Object detections whose masks to iterate. + + Yields: + Tuple of ``(detection_idx, mask_or_crop, offset_or_None)``. + ``mask_or_crop`` is boolean (crop-sized for ``CompactMask``, full-frame + for dense). ``offset_or_None`` is an int32 ``(x1, y1)`` array for + crop→image translation, or ``None`` for dense masks. + """ + masks = detections.mask + if masks is None: + return + # TODO: replace isinstance dispatch with a MaskLike Protocol (separate PR) + compact_mask = masks if isinstance(masks, CompactMask) else None + for detection_idx in range(len(detections)): + if compact_mask is None: + yield ( + detection_idx, + cast(npt.NDArray[np.bool_], masks[detection_idx]), + None, + ) + else: + yield ( + detection_idx, + compact_mask.crop(detection_idx), + compact_mask.offsets[detection_idx], + ) + + +def _paint_masks_by_area( + canvas: npt.NDArray[np.uint8], + detections: Detections, + color: Color | ColorPalette, + color_lookup: ColorLookup | npt.NDArray[np.int_], + collect_union: bool = False, + canvas_origin: tuple[int, int] = (0, 0), +) -> npt.NDArray[np.bool_] | None: + """Paint each detection's mask into `canvas` in descending-area order. + + Smaller masks are drawn on top of larger ones. `CompactMask` detections + are painted into their bounding-box crop only, avoiding a full `(H, W)` + allocation per mask; dense masks fall back to full-frame boolean indexing. + + Args: + canvas: BGR image array painted in place. Shape ``(H, W, 3)``. + detections: Detections whose masks to paint. Returns immediately + without modifying `canvas` when ``detections.mask`` is ``None``. + color: Single color or palette used to resolve each detection's color. + color_lookup: Strategy for mapping colors to detection indices. + collect_union: When ``True``, allocate and return a ``(H, W)`` + boolean array that accumulates the union of all painted masks + (useful for callers like `HaloAnnotator` that need the combined + mask footprint). When ``False`` (default), returns ``None``. + canvas_origin: Absolute ``(x, y)`` origin of `canvas` within the source + image. Use the default for full-frame painting. + + Returns: + A boolean array matching the canvas dimensions when + ``collect_union=True``, otherwise ``None``. When called with an + ROI sub-canvas, dimensions are the ROI size, not the full image. + """ + masks = detections.mask + if masks is None: + return None + union: npt.NDArray[np.bool_] | None = ( + np.zeros(canvas.shape[:2], dtype=bool) if collect_union else None + ) + compact_mask = masks if isinstance(masks, CompactMask) else None + origin_x, origin_y = canvas_origin + canvas_h, canvas_w = canvas.shape[:2] + for detection_idx in np.flip(np.argsort(detections.area)): + color_bgr = resolve_color( + color=color, + detections=detections, + detection_idx=detection_idx, + color_lookup=color_lookup, + ).as_bgr() + if compact_mask is not None: + x1 = int(compact_mask.offsets[detection_idx, 0]) + y1 = int(compact_mask.offsets[detection_idx, 1]) + crop_m = compact_mask.crop(detection_idx) + crop_h, crop_w = crop_m.shape + crop_x1 = max(0, origin_x - x1) + crop_y1 = max(0, origin_y - y1) + canvas_x1 = max(0, x1 - origin_x) + canvas_y1 = max(0, y1 - origin_y) + paint_w = min(crop_w - crop_x1, canvas_w - canvas_x1) + paint_h = min(crop_h - crop_y1, canvas_h - canvas_y1) + if paint_w <= 0 or paint_h <= 0: + continue + crop_slice = crop_m[ + crop_y1 : crop_y1 + paint_h, crop_x1 : crop_x1 + paint_w + ] + canvas_slice = canvas[ + canvas_y1 : canvas_y1 + paint_h, + canvas_x1 : canvas_x1 + paint_w, + ] + canvas_slice[crop_slice] = color_bgr + if union is not None: + union[ + canvas_y1 : canvas_y1 + paint_h, + canvas_x1 : canvas_x1 + paint_w, + ] |= crop_slice + else: + mask = np.asarray(masks[detection_idx], dtype=bool) + mask = mask[origin_y : origin_y + canvas_h, origin_x : origin_x + canvas_w] + canvas[mask] = color_bgr + if union is not None: + union |= mask + return union + + +class MaskAnnotator(BaseAnnotator): + """ + A class for drawing masks on an image using provided detections. + + !!! warning + + This annotator uses `sv.Detections.mask`. + """ + + requires_mask = True + + def __init__( + self, + color: Color | ColorPalette | str = ColorPalette.DEFAULT, + opacity: float = 0.5, + color_lookup: ColorLookup = ColorLookup.CLASS, + ): + """ + Args: + color: The color or color palette to use for + annotating detections. + opacity: Opacity of the overlay mask. Must be between `0` and `1`. + color_lookup: Strategy for mapping colors to annotations. + Options are `INDEX`, `CLASS`, `TRACK`. + """ + self.color: Color | ColorPalette = _normalize_color_input(color) + self.opacity = opacity + self.color_lookup: ColorLookup = color_lookup + + @ensure_cv2_image_for_class_method + def annotate( + self, + scene: ImageType, + detections: Detections, + custom_color_lookup: npt.NDArray[np.int_] | None = None, + ) -> ImageType: + """ + Annotates the given scene with masks based on the provided detections. + + Args: + scene: The image where masks will be drawn. + `ImageType` is a flexible type, accepting either `numpy.ndarray` + or `PIL.Image.Image`. + detections: Object detections to annotate. + custom_color_lookup: Custom color lookup array. + Allows to override the default color mapping strategy. + + Returns: + The annotated image, matching the type of `scene` (`numpy.ndarray` + or `PIL.Image.Image`) + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> image = np.zeros((100, 100, 3), dtype=np.uint8) + >>> detections = sv.Detections( + ... xyxy=np.array([[20, 20, 80, 80]]), + ... mask=np.zeros((1, 100, 100), dtype=bool), + ... class_id=np.array([0]) + ... ) + >>> mask_annotator = sv.MaskAnnotator() + >>> annotated_frame = mask_annotator.annotate( + ... scene=image.copy(), + ... detections=detections + ... ) + + ``` + + ![mask-annotator-example](https://media.roboflow.com/ + supervision-annotator-examples/mask-annotator-example-purple.png) + """ + if not isinstance(scene, np.ndarray): + return scene + if detections.mask is None: + return scene + + image_shape = (int(scene.shape[0]), int(scene.shape[1])) + effective_lookup = ( + self.color_lookup if custom_color_lookup is None else custom_color_lookup + ) + if len(detections) > 0: + resolve_color( + color=self.color, + detections=detections, + detection_idx=0, + color_lookup=effective_lookup, + ) + roi = _masks_to_roi(detections.mask, image_shape, detections.xyxy) + if roi is None: + return scene + + x1, y1, x2, y2 = roi + scene_roi = scene[y1:y2, x1:x2] + colored_mask = np.array(scene_roi, copy=True, dtype=np.uint8) + _paint_masks_by_area( + colored_mask, + detections, + self.color, + effective_lookup, + canvas_origin=(x1, y1), + ) + tmp = cv2.addWeighted( + colored_mask, self.opacity, scene_roi.copy(), 1 - self.opacity, 0 + ) + scene_roi[:] = tmp + return scene + + +class PolygonAnnotator(BaseAnnotator): + """ + A class for drawing polygons on an image using provided detections. + + !!! warning + + This annotator uses `sv.Detections.mask`. + """ + + requires_mask = True + + def __init__( + self, + color: Color | ColorPalette | str = ColorPalette.DEFAULT, + thickness: int = 2, + color_lookup: ColorLookup = ColorLookup.CLASS, + ): + """ + Args: + color: The color or color palette to use for + annotating detections. + thickness: Thickness of the polygon lines. + color_lookup: Strategy for mapping colors to annotations. + Options are `INDEX`, `CLASS`, `TRACK`. + """ + self.color: Color | ColorPalette = _normalize_color_input(color) + self.thickness: int = thickness + self.color_lookup: ColorLookup = color_lookup + + @ensure_cv2_image_for_class_method + def annotate( + self, + scene: ImageType, + detections: Detections, + custom_color_lookup: npt.NDArray[np.int_] | None = None, + ) -> ImageType: + """ + Annotates the given scene with polygons based on the provided detections. + + Args: + scene: The image where polygons will be drawn. + `ImageType` is a flexible type, accepting either `numpy.ndarray` + or `PIL.Image.Image`. + detections: Object detections to annotate. + custom_color_lookup: Custom color lookup array. + Allows to override the default color mapping strategy. + + Returns: + The annotated image, matching the type of `scene` (`numpy.ndarray` + or `PIL.Image.Image`) + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> image = np.zeros((100, 100, 3), dtype=np.uint8) + >>> detections = sv.Detections( + ... xyxy=np.array([[20, 20, 80, 80]]), + ... class_id=np.array([0]) + ... ) + >>> polygon_annotator = sv.PolygonAnnotator() + >>> annotated_frame = polygon_annotator.annotate( + ... scene=image.copy(), + ... detections=detections + ... ) + + ``` + + Note: + When `detections.mask` is a `CompactMask`, each detection's polygon + is decoded from a bbox-sized crop (O(crop_area)) rather than a + full-frame ``(H, W)`` allocation (O(H·W)). Polygon coordinates are + shifted from crop-local space to image space via the stored + ``(x1, y1)`` bbox origin. Pixels outside the declared ``xyxy`` box + are not represented in compact storage and will not be drawn. + + ![polygon-annotator-example](https://media.roboflow.com/ + supervision-annotator-examples/polygon-annotator-example-purple.png) + """ + if not isinstance(scene, np.ndarray): + return scene + if detections.mask is None: + return scene + + for detection_idx, mask, offset in _iter_mask_crops(detections): + color = resolve_color( + color=self.color, + detections=detections, + detection_idx=detection_idx, + color_lookup=self.color_lookup + if custom_color_lookup is None + else custom_color_lookup, + ) + for polygon in mask_to_polygons(mask=mask): + if offset is not None: + # translate crop-local polygon to image space via (x1, y1) origin + polygon = polygon + offset + scene = draw_polygon( + scene=scene, + polygon=cast(npt.NDArray[np.int_], polygon), + color=color, + thickness=self.thickness, + ) + + return scene + + +class ColorAnnotator(BaseAnnotator): + """ + A class for drawing box masks on an image using provided detections. + """ + + def __init__( + self, + color: Color | ColorPalette | str = ColorPalette.DEFAULT, + opacity: float = 0.5, + color_lookup: ColorLookup = ColorLookup.CLASS, + ): + """ + Args: + color: The color or color palette to use for + annotating detections. + opacity: Opacity of the overlay mask. Must be between `0` and `1`. + color_lookup: Strategy for mapping colors to annotations. + Options are `INDEX`, `CLASS`, `TRACK`. + """ + self.color: Color | ColorPalette = _normalize_color_input(color) + self.color_lookup: ColorLookup = color_lookup + self.opacity = opacity + + @ensure_cv2_image_for_class_method + def annotate( + self, + scene: ImageType, + detections: Detections, + custom_color_lookup: npt.NDArray[np.int_] | None = None, + ) -> ImageType: + """ + Annotates the given scene with box masks based on the provided detections. + + Args: + scene: The image where bounding boxes will be drawn. + `ImageType` is a flexible type, accepting either `numpy.ndarray` + or `PIL.Image.Image`. + detections: Object detections to annotate. + custom_color_lookup: Custom color lookup array. + Allows to override the default color mapping strategy. + + Returns: + The annotated image, matching the type of `scene` (`numpy.ndarray` + or `PIL.Image.Image`) + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> image = np.zeros((100, 100, 3), dtype=np.uint8) + >>> detections = sv.Detections( + ... xyxy=np.array([[20, 20, 80, 80]]), + ... class_id=np.array([0]) + ... ) + >>> color_annotator = sv.ColorAnnotator() + >>> annotated_frame = color_annotator.annotate( + ... scene=image.copy(), + ... detections=detections + ... ) + + ``` + + ![box-mask-annotator-example](https://media.roboflow.com/ + supervision-annotator-examples/box-mask-annotator-example-purple.png) + """ + if not isinstance(scene, np.ndarray): + return scene + scene_with_boxes = scene.copy() + for detection_idx in range(len(detections)): + x1, y1, x2, y2 = detections.xyxy[detection_idx].astype(int) + color = resolve_color( + color=self.color, + detections=detections, + detection_idx=detection_idx, + color_lookup=self.color_lookup + if custom_color_lookup is None + else custom_color_lookup, + ) + cv2.rectangle( + img=scene_with_boxes, + pt1=(x1, y1), + pt2=(x2, y2), + color=color.as_bgr(), + thickness=-1, + ) + + cv2.addWeighted( + scene_with_boxes, self.opacity, scene, 1 - self.opacity, gamma=0, dst=scene + ) + return scene + + +class HaloAnnotator(BaseAnnotator): + """ + A class for drawing Halos on an image using provided detections. + + !!! warning + + This annotator uses `sv.Detections.mask`. + """ + + requires_mask = True + + def __init__( + self, + color: Color | ColorPalette | str = ColorPalette.DEFAULT, + opacity: float = 0.8, + kernel_size: int = 40, + color_lookup: ColorLookup = ColorLookup.CLASS, + ): + """ + Args: + color: The color or color palette to use for + annotating detections. + opacity: Opacity of the overlay mask. Must be between `0` and `1`. + kernel_size: The size of the average pooling kernel used for creating + the halo. + color_lookup: Strategy for mapping colors to annotations. + Options are `INDEX`, `CLASS`, `TRACK`. + """ + self.color: Color | ColorPalette = _normalize_color_input(color) + self.opacity = opacity + self.color_lookup: ColorLookup = color_lookup + self.kernel_size: int = kernel_size + + @ensure_cv2_image_for_class_method + def annotate( + self, + scene: ImageType, + detections: Detections, + custom_color_lookup: npt.NDArray[np.int_] | None = None, + ) -> ImageType: + """ + Annotates the given scene with halos based on the provided detections. + + Args: + scene: The image where the halo effect will be applied. + `ImageType` is a flexible type, accepting either `numpy.ndarray` + or `PIL.Image.Image`. + detections: Object detections to annotate. + custom_color_lookup: Custom color lookup array. + Allows to override the default color mapping strategy. + + Returns: + The annotated image, matching the type of `scene` (`numpy.ndarray` + or `PIL.Image.Image`) + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> image = np.zeros((100, 100, 3), dtype=np.uint8) + >>> detections = sv.Detections( + ... xyxy=np.array([[20, 20, 80, 80]]), + ... mask=np.zeros((1, 100, 100), dtype=bool), + ... class_id=np.array([0]) + ... ) + >>> halo_annotator = sv.HaloAnnotator() + >>> annotated_frame = halo_annotator.annotate( + ... scene=image.copy(), + ... detections=detections + ... ) + + ``` + + ![halo-annotator-example](https://media.roboflow.com/ + supervision-annotator-examples/halo-annotator-example-purple.png) + """ + if not isinstance(scene, np.ndarray): + return scene + if detections.mask is None: + return scene + colored_mask = np.zeros_like(scene, dtype=np.uint8) + fmask = _paint_masks_by_area( + colored_mask, + detections, + self.color, + self.color_lookup if custom_color_lookup is None else custom_color_lookup, + collect_union=True, + ) + assert fmask is not None # collect_union=True always returns an array + + colored_mask = cast( + npt.NDArray[np.uint8], + cv2.blur(colored_mask, (self.kernel_size, self.kernel_size)), + ) + colored_mask[fmask] = [0, 0, 0] + gray = cv2.cvtColor(colored_mask, cv2.COLOR_BGR2GRAY) + gray_max = gray.max() + if gray_max == 0: + # no halo to draw (e.g. empty masks); leave the scene untouched + return scene + alpha = self.opacity * gray / gray_max + alpha_mask = alpha[:, :, np.newaxis] + # Blend in float space so halo opacity cannot wrap around uint8 boundaries. + blended_scene = np.clip( + scene.astype(np.float32) * (1 - alpha_mask) + + colored_mask.astype(np.float32) * alpha_mask, + 0, + 255, + ).astype(np.uint8) + np.copyto(scene, blended_scene) + return scene + + +class EllipseAnnotator(BaseAnnotator): + """ + A class for drawing ellipses on an image using provided detections. + """ + + def __init__( + self, + color: Color | ColorPalette | str = ColorPalette.DEFAULT, + thickness: int = 2, + start_angle: int = -45, + end_angle: int = 235, + color_lookup: ColorLookup = ColorLookup.CLASS, + ): + """ + Args: + color: The color or color palette to use for + annotating detections. + thickness: Thickness of the ellipse lines. + start_angle: Starting angle of the ellipse. + end_angle: Ending angle of the ellipse. + color_lookup: Strategy for mapping colors to annotations. + Options are `INDEX`, `CLASS`, `TRACK`. + """ + self.color: Color | ColorPalette = _normalize_color_input(color) + self.thickness: int = thickness + self.start_angle: int = start_angle + self.end_angle: int = end_angle + self.color_lookup: ColorLookup = color_lookup + + @ensure_cv2_image_for_class_method + def annotate( + self, + scene: ImageType, + detections: Detections, + custom_color_lookup: npt.NDArray[np.int_] | None = None, + ) -> ImageType: + """ + Annotates the given scene with ellipses based on the provided detections. + + Args: + scene: The image where ellipses will be drawn. + `ImageType` is a flexible type, accepting either `numpy.ndarray` + or `PIL.Image.Image`. + detections: Object detections to annotate. + custom_color_lookup: Custom color lookup array. + Allows to override the default color mapping strategy. + + Returns: + The annotated image, matching the type of `scene` (`numpy.ndarray` + or `PIL.Image.Image`) + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> image = np.zeros((100, 100, 3), dtype=np.uint8) + >>> detections = sv.Detections( + ... xyxy=np.array([[20, 20, 80, 80]]), + ... class_id=np.array([0]) + ... ) + >>> ellipse_annotator = sv.EllipseAnnotator() + >>> annotated_frame = ellipse_annotator.annotate( + ... scene=image.copy(), + ... detections=detections + ... ) + + ``` + + ![ellipse-annotator-example](https://media.roboflow.com/ + supervision-annotator-examples/ellipse-annotator-example-purple.png) + """ + if not isinstance(scene, np.ndarray): + return scene + for detection_idx in range(len(detections)): + x1, _y1, x2, y2 = detections.xyxy[detection_idx].astype(int) + color = resolve_color( + color=self.color, + detections=detections, + detection_idx=detection_idx, + color_lookup=self.color_lookup + if custom_color_lookup is None + else custom_color_lookup, + ) + center = (int((x1 + x2) / 2), y2) + width = x2 - x1 + cv2.ellipse( + scene, + center=center, + axes=(int(width), int(0.35 * width)), + angle=0.0, + startAngle=self.start_angle, + endAngle=self.end_angle, + color=color.as_bgr(), + thickness=self.thickness, + lineType=cv2.LINE_4, + ) + return scene + + +class BoxCornerAnnotator(BaseAnnotator): + """ + A class for drawing box corners on an image using provided detections. + """ + + def __init__( + self, + color: Color | ColorPalette | str = ColorPalette.DEFAULT, + thickness: int = 4, + corner_length: int = 15, + color_lookup: ColorLookup = ColorLookup.CLASS, + ): + """ + Args: + color: The color or color palette to use for + annotating detections. + thickness: Thickness of the corner lines. + corner_length: Length of each corner line. + color_lookup: Strategy for mapping colors to annotations. + Options are `INDEX`, `CLASS`, `TRACK`. + """ + self.color: Color | ColorPalette = _normalize_color_input(color) + self.thickness: int = thickness + self.corner_length: int = corner_length + self.color_lookup: ColorLookup = color_lookup + + @ensure_cv2_image_for_class_method + def annotate( + self, + scene: ImageType, + detections: Detections, + custom_color_lookup: npt.NDArray[np.int_] | None = None, + ) -> ImageType: + """ + Annotates the given scene with box corners based on the provided detections. + + Args: + scene: The image where box corners will be drawn. + `ImageType` is a flexible type, accepting either `numpy.ndarray` + or `PIL.Image.Image`. + detections: Object detections to annotate. + custom_color_lookup: Custom color lookup array. + Allows to override the default color mapping strategy. + + Returns: + The annotated image, matching the type of `scene` (`numpy.ndarray` + or `PIL.Image.Image`) + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> image = np.zeros((100, 100, 3), dtype=np.uint8) + >>> detections = sv.Detections( + ... xyxy=np.array([[20, 20, 80, 80]]), + ... class_id=np.array([0]) + ... ) + >>> corner_annotator = sv.BoxCornerAnnotator() + >>> annotated_frame = corner_annotator.annotate( + ... scene=image.copy(), + ... detections=detections + ... ) + + ``` + + ![box-corner-annotator-example](https://media.roboflow.com/ + supervision-annotator-examples/box-corner-annotator-example-purple.png) + """ + if not isinstance(scene, np.ndarray): + return scene + for detection_idx in range(len(detections)): + x1, y1, x2, y2 = detections.xyxy[detection_idx].astype(int) + color = resolve_color( + color=self.color, + detections=detections, + detection_idx=detection_idx, + color_lookup=self.color_lookup + if custom_color_lookup is None + else custom_color_lookup, + ) + corners = [(x1, y1), (x2, y1), (x1, y2), (x2, y2)] + + for x, y in corners: + x_end = x + self.corner_length if x == x1 else x - self.corner_length + cv2.line( + scene, (x, y), (x_end, y), color.as_bgr(), thickness=self.thickness + ) + + y_end = y + self.corner_length if y == y1 else y - self.corner_length + cv2.line( + scene, (x, y), (x, y_end), color.as_bgr(), thickness=self.thickness + ) + return scene + + +class CircleAnnotator(BaseAnnotator): + """ + A class for drawing circle on an image using provided detections. + """ + + def __init__( + self, + color: Color | ColorPalette | str = ColorPalette.DEFAULT, + thickness: int = 2, + color_lookup: ColorLookup = ColorLookup.CLASS, + ): + """ + Args: + color: The color or color palette to use for + annotating detections. + thickness: Thickness of the circle line. + color_lookup: Strategy for mapping colors to annotations. + Options are `INDEX`, `CLASS`, `TRACK`. + """ + + self.color: Color | ColorPalette = _normalize_color_input(color) + self.thickness: int = thickness + self.color_lookup: ColorLookup = color_lookup + + @ensure_cv2_image_for_class_method + def annotate( + self, + scene: ImageType, + detections: Detections, + custom_color_lookup: npt.NDArray[np.int_] | None = None, + ) -> ImageType: + """ + Annotates the given scene with circles based on the provided detections. + + Args: + scene: The image where box corners will be drawn. + `ImageType` is a flexible type, accepting either `numpy.ndarray` + or `PIL.Image.Image`. + detections: Object detections to annotate. + custom_color_lookup: Custom color lookup array. + Allows to override the default color mapping strategy. + + Returns: + The annotated image, matching the type of `scene` (`numpy.ndarray` + or `PIL.Image.Image`) + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> image = np.zeros((100, 100, 3), dtype=np.uint8) + >>> detections = sv.Detections( + ... xyxy=np.array([[20, 20, 80, 80]]), + ... class_id=np.array([0]) + ... ) + >>> circle_annotator = sv.CircleAnnotator() + >>> annotated_frame = circle_annotator.annotate( + ... scene=image.copy(), + ... detections=detections + ... ) + + ``` + + + ![circle-annotator-example](https://media.roboflow.com/ + supervision-annotator-examples/circle-annotator-example-purple.png) + """ + if not isinstance(scene, np.ndarray): + return scene + for detection_idx in range(len(detections)): + x1, y1, x2, y2 = detections.xyxy[detection_idx].astype(int) + center = ((x1 + x2) // 2, (y1 + y2) // 2) + distance = sqrt((x1 - center[0]) ** 2 + (y1 - center[1]) ** 2) + color = resolve_color( + color=self.color, + detections=detections, + detection_idx=detection_idx, + color_lookup=self.color_lookup + if custom_color_lookup is None + else custom_color_lookup, + ) + cv2.circle( + img=scene, + center=center, + radius=int(distance), + color=color.as_bgr(), + thickness=self.thickness, + ) + + return scene + + +class DotAnnotator(BaseAnnotator): + """ + A class for drawing dots on an image at specific coordinates based on provided + detections. + """ + + def __init__( + self, + color: Color | ColorPalette | str = ColorPalette.DEFAULT, + radius: int = 4, + position: Position = Position.CENTER, + color_lookup: ColorLookup = ColorLookup.CLASS, + outline_thickness: int = 0, + outline_color: Color | ColorPalette | str = Color.BLACK, + ): + """ + Args: + color: The color or color palette to use for + annotating detections. + radius: Radius of the drawn dots. + position: The anchor position for placing the dot. + color_lookup: Strategy for mapping colors to annotations. + Options are `INDEX`, `CLASS`, `TRACK`. + outline_thickness: Thickness of the outline of the dot. + outline_color: The color or color palette to + use for outline. It is activated by setting outline_thickness to a value + greater than 0. + """ + self.color: Color | ColorPalette = _normalize_color_input(color) + self.radius: int = radius + self.position: Position = position + self.color_lookup: ColorLookup = color_lookup + self.outline_thickness = outline_thickness + self.outline_color: Color | ColorPalette = _normalize_color_input(outline_color) + + @ensure_cv2_image_for_class_method + def annotate( + self, + scene: ImageType, + detections: Detections, + custom_color_lookup: npt.NDArray[np.int_] | None = None, + ) -> ImageType: + """ + Annotates the given scene with dots based on the provided detections. + + Args: + scene: The image where dots will be drawn. + `ImageType` is a flexible type, accepting either `numpy.ndarray` + or `PIL.Image.Image`. + detections: Object detections to annotate. + custom_color_lookup: Custom color lookup array. + Allows to override the default color mapping strategy. + + Returns: + The annotated image, matching the type of `scene` (`numpy.ndarray` + or `PIL.Image.Image`) + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> image = np.zeros((100, 100, 3), dtype=np.uint8) + >>> detections = sv.Detections( + ... xyxy=np.array([[20, 20, 80, 80]]), + ... class_id=np.array([0]) + ... ) + >>> dot_annotator = sv.DotAnnotator() + >>> annotated_frame = dot_annotator.annotate( + ... scene=image.copy(), + ... detections=detections + ... ) + + ``` + + ![dot-annotator-example](https://media.roboflow.com/ + supervision-annotator-examples/dot-annotator-example-purple.png) + """ + if not isinstance(scene, np.ndarray): + return scene + xy = detections.get_anchors_coordinates(anchor=self.position) + for detection_idx in range(len(detections)): + color = resolve_color( + color=self.color, + detections=detections, + detection_idx=detection_idx, + color_lookup=self.color_lookup + if custom_color_lookup is None + else custom_color_lookup, + ) + center = (int(xy[detection_idx, 0]), int(xy[detection_idx, 1])) + + cv2.circle(scene, center, self.radius, color.as_bgr(), -1) + if self.outline_thickness: + outline_color = resolve_color( + color=self.outline_color, + detections=detections, + detection_idx=detection_idx, + color_lookup=self.color_lookup + if custom_color_lookup is None + else custom_color_lookup, + ) + cv2.circle( + scene, + center, + self.radius, + outline_color.as_bgr(), + self.outline_thickness, + ) + return scene + + +class LabelAnnotator(_BaseLabelAnnotator): + """ + A class for annotating labels on an image using provided detections. + """ + + def __init__( + self, + color: Color | ColorPalette | str = ColorPalette.DEFAULT, + color_lookup: ColorLookup = ColorLookup.CLASS, + text_color: Color | ColorPalette | str = Color.WHITE, + text_scale: float = 0.5, + text_thickness: int = 1, + text_padding: int = 10, + text_position: Position = Position.TOP_LEFT, + text_offset: tuple[int, int] = (0, 0), + border_radius: int = 0, + smart_position: bool = False, + max_line_length: int | None = None, + ): + """ + Args: + color: The color or color palette to use for + annotating the text background. + color_lookup: Strategy for mapping colors to annotations. + Options are `INDEX`, `CLASS`, `TRACK`. + text_color: The color or color palette to use + for the text. + text_scale: Font scale for the text. + text_thickness: Thickness of the text characters. + text_padding: Padding around the text within its background box. + text_position: Position of the text relative to the detection. + Possible values are defined in the `Position` enum. + text_offset: A tuple of 2D coordinates `(x, y)` to + offset the text position from the anchor point, in pixels. + border_radius: The radius to apply round edges. If the selected + value is higher than the lower dimension, width or height, is clipped. + smart_position: Spread out the labels to avoid overlapping. + max_line_length: Maximum number of characters per line + before wrapping the text. None means no wrapping. + """ + self.text_scale: float = text_scale + self.text_thickness: int = text_thickness + super().__init__( + color=color, + color_lookup=color_lookup, + text_color=text_color, + text_padding=text_padding, + text_position=text_position, + text_offset=text_offset, + border_radius=border_radius, + smart_position=smart_position, + max_line_length=max_line_length, + ) + + @ensure_cv2_image_for_class_method + def annotate( + self, + scene: ImageType, + detections: Detections, + labels: list[str] | None = None, + custom_color_lookup: npt.NDArray[np.int_] | None = None, + ) -> ImageType: + """ + Annotates the given scene with labels based on the provided detections. + + Args: + scene: The image where labels will be drawn. + `ImageType` is a flexible type, accepting either `numpy.ndarray` + or `PIL.Image.Image`. + detections: Object detections to annotate. + labels: Custom labels for each detection. + custom_color_lookup: Custom color lookup array. + Allows to override the default color mapping strategy. + + Returns: + The annotated image, matching the type of `scene` (`numpy.ndarray` + or `PIL.Image.Image`) + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> image = np.zeros((100, 100, 3), dtype=np.uint8) + >>> detections = sv.Detections( + ... xyxy=np.array([[20, 20, 80, 80]]), + ... confidence=np.array([0.9]), + ... class_id=np.array([0]), + ... data={'class_name': np.array(['person'])} + ... ) + >>> labels = [ + ... f"{class_name} {confidence:.2f}" + ... for class_name, confidence + ... in zip(detections['class_name'], detections.confidence) + ... ] + >>> label_annotator = sv.LabelAnnotator(text_position=sv.Position.CENTER) + >>> annotated_frame = label_annotator.annotate( + ... scene=image.copy(), + ... detections=detections, + ... labels=labels + ... ) + + ``` + + ![label-annotator-example](https://media.roboflow.com/ + supervision-annotator-examples/label-annotator-example-purple.png) + """ + if not isinstance(scene, np.ndarray): + return scene + _validate_labels(labels, detections) + + labels = get_labels_text(detections, labels) + label_properties: npt.NDArray[np.float32] = self._get_label_properties( + detections, labels + ) + + if self.smart_position: + label_properties = self._adjust_labels_in_frame( + (scene.shape[1], scene.shape[0]), + labels, + label_properties, + ) + + self._draw_labels( + scene=scene, + labels=labels, + label_properties=label_properties, + detections=detections, + custom_color_lookup=custom_color_lookup, + ) + + return scene + + def _get_label_properties( + self, + detections: Detections, + labels: list[str], + ) -> Any: + label_properties = [] + anchors_coordinates: npt.NDArray[np.int32] = detections.get_anchors_coordinates( + anchor=self.text_anchor + ).astype(int) + + for label, center_coordinates in zip(labels, anchors_coordinates): + center_coordinates = ( + center_coordinates[0] + self.text_offset[0], + center_coordinates[1] + self.text_offset[1], + ) + + wrapped_lines = wrap_text(label, self.max_line_length) + line_heights = [] + line_widths = [] + + for line in wrapped_lines: + (text_w, text_h) = cv2.getTextSize( + text=line, + fontFace=CV2_FONT, + fontScale=self.text_scale, + thickness=self.text_thickness, + )[0] + line_heights.append(text_h) + line_widths.append(text_w) + + # Get the maximum width and total height + max_width = max(line_widths) if line_widths else 0 + total_height = ( + sum(line_heights) + (len(line_heights) - 1) * self.text_padding + ) + + # Add padding around all sides + width_padded = max_width + 2 * self.text_padding + height_padded = total_height + 2 * self.text_padding + + text_background_xyxy = resolve_text_background_xyxy( + center_coordinates=center_coordinates, + text_wh=(width_padded, height_padded), + position=self.text_anchor, + ) + + label_properties.append( + [ + *text_background_xyxy, + total_height, + ] + ) + return np.array(label_properties, dtype=np.float32).reshape(-1, 5) + + def _draw_labels( + self, + scene: npt.NDArray[np.uint8], + labels: list[str], + label_properties: npt.NDArray[np.float32], + detections: Detections, + custom_color_lookup: npt.NDArray[np.int_] | None, + ) -> None: + assert len(labels) == len(label_properties) == len(detections), ( + f"Number of label properties ({len(label_properties)}), " + f"labels ({len(labels)}) and detections ({len(detections)}) " + "do not match." + ) + + color_lookup = ( + custom_color_lookup + if custom_color_lookup is not None + else self.color_lookup + ) + + for idx, label_property in enumerate(label_properties): + background_color = resolve_color( + color=self.color, + detections=detections, + detection_idx=idx, + color_lookup=color_lookup, + ) + text_color = resolve_color( + color=self.text_color, + detections=detections, + detection_idx=idx, + color_lookup=color_lookup, + ) + + box_xyxy = label_property[:4].astype(int) + + self.draw_rounded_rectangle( + scene=scene, + xyxy=box_xyxy, + color=background_color.as_bgr(), + border_radius=self.border_radius, + ) + + # Handle multiline text + wrapped_lines = wrap_text(labels[idx], self.max_line_length) + current_y = box_xyxy[1] + self.text_padding # Start y position + + for line in wrapped_lines: + if not line: + # Use a character with ascenders and descenders as height reference + (_, text_h) = cv2.getTextSize( + text="Tg", + fontFace=CV2_FONT, + fontScale=self.text_scale, + thickness=self.text_thickness, + )[0] + current_y += text_h + self.text_padding + continue + + (_, text_h) = cv2.getTextSize( + text=line, + fontFace=CV2_FONT, + fontScale=self.text_scale, + thickness=self.text_thickness, + )[0] + + text_x = box_xyxy[0] + self.text_padding + text_y = current_y + text_h # Add height to get to text baseline + + cv2.putText( + img=scene, + text=line, + org=(text_x, text_y), + fontFace=CV2_FONT, + fontScale=self.text_scale, + color=text_color.as_bgr(), + thickness=self.text_thickness, + lineType=cv2.LINE_AA, + ) + + current_y += text_h + self.text_padding # Move to next line position + + @staticmethod + def draw_rounded_rectangle( + scene: npt.NDArray[np.uint8], + xyxy: tuple[int, int, int, int], + color: tuple[int, int, int], + border_radius: int, + ) -> npt.NDArray[np.uint8]: + """Draw a filled rectangle with optional rounded corners on an image. + + Args: + scene: BGR image array to draw on; modified in-place and returned. + xyxy: Bounding box as (x1, y1, x2, y2) pixel coordinates. + color: Fill color as a BGR tuple (e.g. ``(0, 0, 255)`` for red). + border_radius: Corner rounding radius in pixels. Values <= 0 + (including values clamped to 0 by a degenerate box) draw a + plain filled rectangle with square corners. + + Returns: + The annotated ``scene`` array. + + Example: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> scene = np.zeros((200, 200, 3), dtype=np.uint8) + >>> scene = sv.LabelAnnotator.draw_rounded_rectangle( + ... scene=scene, + ... xyxy=(10, 10, 100, 50), + ... color=(0, 255, 0), + ... border_radius=0, + ... ) + >>> bool(scene[30, 50].tolist() == [0, 255, 0]) + True + + ``` + """ + x1, y1, x2, y2 = xyxy + width = x2 - x1 + height = y2 - y1 + + border_radius = min(border_radius, min(width, height) // 2) + + if border_radius <= 0: + # square corners: a single fill rectangle (the common default), rather + # than two rectangles plus four zero-radius corner circles + cv2.rectangle( + img=scene, + pt1=(x1, y1), + pt2=(x2, y2), + color=color, + thickness=-1, + ) + return scene + + rectangle_coordinates = [ + ((x1 + border_radius, y1), (x2 - border_radius, y2)), + ((x1, y1 + border_radius), (x2, y2 - border_radius)), + ] + circle_centers = [ + (x1 + border_radius, y1 + border_radius), + (x2 - border_radius, y1 + border_radius), + (x1 + border_radius, y2 - border_radius), + (x2 - border_radius, y2 - border_radius), + ] + + for coordinates in rectangle_coordinates: + cv2.rectangle( + img=scene, + pt1=coordinates[0], + pt2=coordinates[1], + color=color, + thickness=-1, + ) + for center in circle_centers: + cv2.circle( + img=scene, + center=center, + radius=border_radius, + color=color, + thickness=-1, + ) + return scene + + +class RichLabelAnnotator(_BaseLabelAnnotator): + """ + A class for annotating labels on an image using provided detections, + with support for Unicode characters by using a custom font. + """ + + def __init__( + self, + color: Color | ColorPalette | str = ColorPalette.DEFAULT, + color_lookup: ColorLookup = ColorLookup.CLASS, + text_color: Color | ColorPalette | str = Color.WHITE, + font_path: str | None = None, + font_size: int = 10, + text_padding: int = 10, + text_position: Position = Position.TOP_LEFT, + text_offset: tuple[int, int] = (0, 0), + border_radius: int = 0, + smart_position: bool = False, + max_line_length: int | None = None, + ): + """ + Args: + color: The color or color palette to use for + annotating the text background. + color_lookup: Strategy for mapping colors to annotations. + Options are `INDEX`, `CLASS`, `TRACK`. + text_color: The color to use for the text. + font_path: Path to the font file (e.g., ".ttf" or ".otf") + to use for rendering text. If `None`, the default PIL font will be used. + font_size: Font size for the text. + text_padding: Padding around the text within its background box. + text_position: Position of the text relative to the detection. + Possible values are defined in the `Position` enum. + text_offset: A tuple of 2D coordinates `(x, y)` to + offset the text position from the anchor point, in pixels. + border_radius: The radius to apply round edges. If the selected + value is higher than the lower dimension, width or height, is clipped. + smart_position: Spread out the labels to avoid overlapping. + max_line_length: Maximum number of characters per line + before wrapping the text. None means no wrapping. + """ + self.font_path = font_path + self.font_size = font_size + self.font = self._load_font(font_size, font_path) + super().__init__( + color=color, + color_lookup=color_lookup, + text_color=text_color, + text_padding=text_padding, + text_position=text_position, + text_offset=text_offset, + border_radius=border_radius, + smart_position=smart_position, + max_line_length=max_line_length, + ) + + @ensure_pil_image_for_class_method + def annotate( + self, + scene: ImageType, + detections: Detections, + labels: list[str] | None = None, + custom_color_lookup: npt.NDArray[np.int_] | None = None, + ) -> ImageType: + """ + Annotates the given scene with labels based on the provided + detections, with support for Unicode characters. + + Args: + scene: The image where labels will be drawn. + `ImageType` is a flexible type, accepting either `numpy.ndarray` + or `PIL.Image.Image`. + detections: Object detections to annotate. + labels: Custom labels for each detection. + custom_color_lookup: Custom color lookup array. + Allows to override the default color mapping strategy. + + Returns: + The annotated image, matching the type of `scene` (`numpy.ndarray` + or `PIL.Image.Image`) + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> from PIL import Image + >>> image = Image.fromarray(np.zeros((100, 100, 3), dtype=np.uint8)) + >>> detections = sv.Detections( + ... xyxy=np.array([[20, 20, 80, 80]]), + ... confidence=np.array([0.9]), + ... class_id=np.array([0]), + ... data={'class_name': np.array(['person'])} + ... ) + >>> labels = [ + ... f"{class_name} {confidence:.2f}" + ... for class_name, confidence + ... in zip(detections['class_name'], detections.confidence) + ... ] + >>> rich_label_annotator = sv.RichLabelAnnotator() + >>> annotated_frame = rich_label_annotator.annotate( + ... scene=image.copy(), + ... detections=detections, + ... labels=labels + ... ) + + ``` + """ + _validate_labels(labels, detections) + + draw = ImageDraw.Draw(scene) + labels = get_labels_text(detections, labels) + label_properties: npt.NDArray[np.float32] = self._get_label_properties( + draw, detections, labels + ) + + if self.smart_position: + scene_pil = cast(Image.Image, scene) + label_properties = self._adjust_labels_in_frame( + (scene_pil.width, scene_pil.height), + labels, + label_properties, + ) + + self._draw_labels( + draw=draw, + labels=labels, + label_properties=label_properties, + detections=detections, + custom_color_lookup=custom_color_lookup, + ) + + return scene + + def _get_label_properties( + self, draw: ImageDraw.ImageDraw, detections: Detections, labels: list[str] + ) -> Any: + label_properties = [] + + anchor_coordinates: npt.NDArray[np.int32] = detections.get_anchors_coordinates( + anchor=self.text_anchor + ).astype(int) + + for label, center_coordinates in zip(labels, anchor_coordinates): + center_coordinates = ( + center_coordinates[0] + self.text_offset[0], + center_coordinates[1] + self.text_offset[1], + ) + + wrapped_lines = wrap_text(label, self.max_line_length) + + # Calculate the total text height and maximum width + max_width = 0.0 + total_height = 0.0 + + for line in wrapped_lines: + left, top, right, bottom = draw.textbbox((0, 0), line, font=self.font) + line_width = right - left + line_height = bottom - top + + max_width = max(max_width, line_width) + total_height += line_height + + # Add inter-line spacing + if len(wrapped_lines) > 1: + total_height += (len(wrapped_lines) - 1) * self.text_padding + + width_padded = int(max_width + 2 * self.text_padding) + height_padded = int(total_height + 2 * self.text_padding) + + text_background_xyxy = resolve_text_background_xyxy( + center_coordinates=center_coordinates, + text_wh=(width_padded, height_padded), + position=self.text_anchor, + ) + + # Get the text origin offsets + text_left, text_top, _, _ = draw.textbbox((0, 0), "Tg", font=self.font) + + label_properties.append([*text_background_xyxy, text_left, text_top]) + + result: npt.NDArray[np.float32] = np.array( + label_properties, dtype=np.float32 + ).reshape(-1, 6) + return result + + def _draw_labels( + self, + draw: ImageDraw.ImageDraw, + labels: list[str], + label_properties: npt.NDArray[np.float32], + detections: Detections, + custom_color_lookup: npt.NDArray[np.int_] | None, + ) -> None: + assert len(labels) == len(label_properties) == len(detections), ( + f"Number of label properties ({len(label_properties)}), " + f"labels ({len(labels)}) and detections ({len(detections)}) " + "do not match." + ) + color_lookup = ( + custom_color_lookup + if custom_color_lookup is not None + else self.color_lookup + ) + + for idx, label_property in enumerate(label_properties): + background_color = resolve_color( + color=self.color, + detections=detections, + detection_idx=idx, + color_lookup=color_lookup, + ) + text_color = resolve_color( + color=self.text_color, + detections=detections, + detection_idx=idx, + color_lookup=color_lookup, + ) + + box_xyxy = label_property[:4].astype(int) + text_left = label_property[4] + text_top = label_property[5] + + # Draw the rounded rectangle background + draw.rounded_rectangle( + tuple(box_xyxy), + radius=self.border_radius, + fill=background_color.as_rgb(), + outline=None, + ) + + # Draw each line of text + wrapped_lines = wrap_text(labels[idx], self.max_line_length) + x_position = box_xyxy[0] + self.text_padding - text_left + y_position = box_xyxy[1] + self.text_padding - text_top + + for line in wrapped_lines: + draw.text( + xy=(x_position, y_position), + text=line, + font=self.font, + fill=text_color.as_rgb(), + ) + + # Move to the next line position + _left, top, _right, bottom = draw.textbbox((0, 0), line, font=self.font) + line_height = bottom - top + y_position += line_height + self.text_padding + + @staticmethod + def _load_font( + font_size: int, font_path: str | None + ) -> ImageFont.FreeTypeFont | ImageFont.ImageFont: + def load_default_font( + size: int, + ) -> ImageFont.FreeTypeFont | ImageFont.ImageFont: + try: + return ImageFont.load_default(size) + except TypeError: + return ImageFont.load_default() + + if font_path is None: + return load_default_font(font_size) + + try: + return ImageFont.truetype(font_path, font_size) + except OSError: + logger.warning( + "Font path '%s' not found. Using PIL's default font.", font_path + ) + return load_default_font(font_size) + + +class IconAnnotator(BaseAnnotator): + """ + A class for drawing an icon on an image, using provided detections. + """ + + def __init__( + self, + icon_resolution_wh: tuple[int, int] = (64, 64), + icon_position: Position = Position.TOP_CENTER, + offset_xy: tuple[int, int] = (0, 0), + ): + """ + Args: + icon_resolution_wh: The size of drawn icons. + All icons will be resized to this resolution, keeping the aspect ratio. + icon_position: The position of the icon. + offset_xy: The offset to apply to the icon position, + in pixels. Can be both positive and negative. + """ + self.icon_resolution_wh = icon_resolution_wh + self.position = icon_position + self.offset_xy = offset_xy + + @ensure_cv2_image_for_class_method + def annotate( + self, + scene: ImageType, + detections: Detections, + icon_path: str | list[str] = "", + ) -> ImageType: + """ + Annotates the given scene with given icons. + + Args: + scene: The image where labels will be drawn. + `ImageType` is a flexible type, accepting either `numpy.ndarray` + or `PIL.Image.Image`. + detections: Object detections to annotate. + icon_path: The path to the PNG image to use as an + icon. Must be a single path or a list of paths, one for each detection. + Pass an empty string `""` to draw nothing. + + Returns: + The annotated image, matching the type of `scene` (`numpy.ndarray` + or `PIL.Image.Image`) + + Example: + ```python + import supervision as sv + + image = ... + detections = sv.Detections(...) + + available_icons = ["roboflow.png", "lenny.png"] + icon_paths = [np.random.choice(available_icons) for _ in detections] + + icon_annotator = sv.IconAnnotator() + annotated_frame = icon_annotator.annotate( + scene=image.copy(), + detections=detections, + icon_path=icon_paths + ) + ``` + + ![icon-annotator-example](https://media.roboflow.com/ + supervision-annotator-examples/icon-annotator-example.png) + """ + if not isinstance(scene, np.ndarray): + return scene + if isinstance(icon_path, list) and len(icon_path) != len(detections): + raise ValueError( + f"The number of icon paths provided ({len(icon_path)}) does not match " + f"the number of detections ({len(detections)}). Either provide a single" + f" icon path or one for each detection." + ) + + xy: npt.NDArray[np.int32] = detections.get_anchors_coordinates( + anchor=self.position + ).astype(int) + + for detection_idx in range(len(detections)): + current_path = ( + icon_path if isinstance(icon_path, str) else icon_path[detection_idx] + ) + if current_path == "": + continue + icon = self._load_icon(current_path) + icon_h, icon_w = icon.shape[:2] + + x = int(xy[detection_idx, 0] - icon_w / 2 + self.offset_xy[0]) + y = int(xy[detection_idx, 1] - icon_h / 2 + self.offset_xy[1]) + + scene[:] = _overlay_image(scene, icon, (x, y)) + return scene + + def _load_icon(self, icon_path: str) -> npt.NDArray[np.uint8]: + """Load an icon through the module-level cache shared by annotators.""" + return _load_icon_from_path( + icon_path=icon_path, icon_resolution_wh=self.icon_resolution_wh + ) + + +class BlurAnnotator(BaseAnnotator): + """ + A class for blurring regions in an image using provided detections. + """ + + def __init__(self, kernel_size: int | None = None): + """ + Args: + kernel_size: The size of the average pooling kernel used for blurring. + If not set, a dynamic size is computed as one-third of the shorter + bounding-box dimension. Must be >= 1 when provided. + """ + if kernel_size is not None and kernel_size < 1: + raise ValueError(f"kernel_size must be >= 1, got {kernel_size}.") + self.kernel_size: int | None = kernel_size + + @ensure_cv2_image_for_class_method + def annotate( + self, + scene: ImageType, + detections: Detections, + ) -> ImageType: + """ + Annotates the given scene by blurring regions based on the provided detections. + + Args: + scene: The image where blurring will be applied. + `ImageType` is a flexible type, accepting either `numpy.ndarray` + or `PIL.Image.Image`. + detections: Object detections to annotate. + + Returns: + The annotated image, matching the type of `scene` (`numpy.ndarray` + or `PIL.Image.Image`) + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> image = np.zeros((100, 100, 3), dtype=np.uint8) + >>> detections = sv.Detections( + ... xyxy=np.array([[20, 20, 80, 80]]), + ... class_id=np.array([0]) + ... ) + >>> blur_annotator = sv.BlurAnnotator() + >>> annotated_frame = blur_annotator.annotate( + ... scene=image.copy(), + ... detections=detections + ... ) + + ``` + + ![blur-annotator-example](https://media.roboflow.com/ + supervision-annotator-examples/blur-annotator-example-purple.png) + """ + if not isinstance(scene, np.ndarray): + return scene + image_height, image_width = scene.shape[:2] + clipped_xyxy: npt.NDArray[np.int32] = clip_boxes( + xyxy=detections.xyxy, + resolution_wh=(image_width, image_height), + ).astype(int) + + for x1, y1, x2, y2 in clipped_xyxy: + if x2 <= x1 or y2 <= y1: + continue + roi = scene[y1:y2, x1:x2] + kernel_size = ( + self.kernel_size + if self.kernel_size is not None + else calculate_dynamic_kernel_size(x1, y1, x2, y2) + ) + roi = cast(npt.NDArray[np.uint8], cv2.blur(roi, (kernel_size, kernel_size))) + scene[y1:y2, x1:x2] = roi + + return scene + + +class TraceAnnotator(BaseAnnotator): + """ + A class for drawing trace paths on an image based on detection coordinates. + + !!! warning + + This annotator uses the `sv.Detections.tracker_id`. Read + [here](/latest/trackers/) to learn how to plug + tracking into your inference pipeline. + """ + + def __init__( + self, + color: Color | ColorPalette | str = ColorPalette.DEFAULT, + position: Position = Position.CENTER, + trace_length: int = 30, + thickness: int = 2, + smooth: bool = False, + color_lookup: ColorLookup = ColorLookup.CLASS, + ): + """ + Args: + color: The color to draw the trace, can be + a single color or a color palette. + position: The position of the trace. + Defaults to `CENTER`. + trace_length: The maximum length of the trace in terms of historical + points. Defaults to `30`. + thickness: The thickness of the trace lines. Defaults to `2`. + smooth: If `True`, applies spline smoothing to trace lines using + consecutive unique anchor points. Falls back to a raw polyline + when fewer than 4 unique points are available (e.g. when a + tracker is stationary). + color_lookup: Strategy for mapping colors to annotations. + Options are `INDEX`, `CLASS`, `TRACK`. + """ + self.color: Color | ColorPalette = _normalize_color_input(color) + self.trace = Trace(max_size=trace_length, anchor=position) + self.thickness = thickness + self.smooth = smooth + self.color_lookup: ColorLookup = color_lookup + + def reset(self) -> None: + """ + Clears the accumulated trace history so the annotator can be reused + across independent streams without carrying over points from a + previous stream. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> image = np.zeros((20, 20, 3), dtype=np.uint8) + >>> detections = sv.Detections( + ... xyxy=np.array([[1, 1, 10, 10]]), + ... class_id=np.array([0]), + ... tracker_id=np.array([1]) + ... ) + >>> trace_annotator = sv.TraceAnnotator() + >>> _ = trace_annotator.annotate(scene=image.copy(), detections=detections) + >>> trace_annotator.trace.xy.shape + (1, 2) + >>> trace_annotator.reset() + >>> trace_annotator.trace.current_frame_id + 0 + >>> trace_annotator.trace.xy.shape + (0, 2) + + ``` + """ + self.trace.reset() + + @ensure_cv2_image_for_class_method + def annotate( + self, + scene: ImageType, + detections: Detections, + custom_color_lookup: npt.NDArray[np.int_] | None = None, + ) -> ImageType: + """ + Draws trace paths on the frame based on the detection coordinates provided. + + Args: + scene: The image on which the traces will be drawn. + `ImageType` is a flexible type, accepting either `numpy.ndarray` + or `PIL.Image.Image`. + detections: The detections which include coordinates for + which the traces will be drawn. An empty `Detections` batch + is a no-op: `scene` is returned unmodified. + custom_color_lookup: Custom color lookup array. + Allows to override the default color mapping strategy. + + Returns: + The annotated image, matching the type of `scene` (`numpy.ndarray` + or `PIL.Image.Image`) + + Raises: + ValueError: If `detections` is non-empty and its `tracker_id` field is + missing. + + Examples: + ```python + import supervision as sv + from rfdetr import RFDETRMedium + + model = RFDETRMedium() + trace_annotator = sv.TraceAnnotator() + + video_info = sv.VideoInfo.from_video_path(video_path='...') + frames_generator = sv.get_video_frames_generator(source_path='...') + tracker = sv.ByteTrack() + + with sv.VideoSink(target_path='...', video_info=video_info) as sink: + for frame in frames_generator: + detections = model.predict(frame[:, :, ::-1]) + detections = tracker.update_with_detections(detections) + annotated_frame = trace_annotator.annotate( + scene=frame.copy(), + detections=detections) + sink.write_frame(frame=annotated_frame) + ``` + + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> image = np.zeros((100, 100, 3), dtype=np.uint8) + >>> trace_annotator = sv.TraceAnnotator() + >>> detections = sv.Detections( + ... xyxy=np.array([[10, 10, 30, 30]]), + ... class_id=np.array([0]), + ... tracker_id=np.array([1]), + ... ) + >>> _ = trace_annotator.annotate(scene=image.copy(), detections=detections) + >>> detections = sv.Detections( + ... xyxy=np.array([[70, 70, 90, 90]]), + ... class_id=np.array([0]), + ... tracker_id=np.array([1]), + ... ) + >>> annotated_frame = trace_annotator.annotate( + ... scene=image.copy(), + ... detections=detections + ... ) + >>> bool(annotated_frame.any()) + True + >>> annotated_frame = trace_annotator.annotate( + ... scene=image.copy(), + ... detections=sv.Detections.empty() + ... ) + >>> np.array_equal(annotated_frame, image) + True + + ``` + + ![trace-annotator-example](https://media.roboflow.com/ + supervision-annotator-examples/trace-annotator-example-purple.png) + """ + if not isinstance(scene, np.ndarray): + return scene + + # A frame in which nothing was detected carries no `tracker_id` and is + # not a missing-tracker mistake, so it must not raise. It still reaches + # the trace: advancing the frame counter there keeps `trace_length` a + # window over elapsed frames, so a track whose stored history had + # already filled that window is not joined to its pre-gap trail when it + # reappears after a longer gap. + if len(detections) == 0: + self.trace.put(detections) + return scene + + if detections.tracker_id is None: + raise ValueError( + "The `tracker_id` field is missing in the provided detections." + " See more: https://supervision.roboflow.com/latest/how_to/track_objects" + ) + is_confirmed = detections.tracker_id != PENDING_TRACK_ID + filtered_detections: Detections = detections[is_confirmed] # type: ignore + # Validate before filtering so an invalid lookup cannot happen to match only + # the confirmed tracks. The matching lookup then drops pending-track entries. + if custom_color_lookup is not None: + if len(custom_color_lookup) != len(detections): + raise ValueError( + f"Length of color lookup {len(custom_color_lookup)} " + f"does not match length of detections {len(detections)}" + ) + custom_color_lookup = custom_color_lookup[is_confirmed] + + self.trace.put(filtered_detections) + for detection_idx in range(len(filtered_detections)): + tracker_id_val = filtered_detections.tracker_id[detection_idx] # type: ignore + if tracker_id_val is None: + continue + tracker_id = int(tracker_id_val) + color = resolve_color( + color=self.color, + detections=filtered_detections, + detection_idx=detection_idx, + color_lookup=self.color_lookup + if custom_color_lookup is None + else custom_color_lookup, + ) + xy = self.trace.get(tracker_id=tracker_id) + spline_points: npt.NDArray[np.int32] = xy.astype(np.int32) + + if self.smooth: + unique_xy = xy[ + np.concatenate(([True], np.any(np.diff(xy, axis=0) != 0, axis=1))) + ] + if len(unique_xy) > 3: + try: + x, y = unique_xy[:, 0], unique_xy[:, 1] + tck, _u = splprep([x, y], s=20) + x_new, y_new = splev( + np.linspace(0, 1, 100), + cast( + tuple[ + npt.NDArray[np.float64], + npt.NDArray[np.float64], + int, + ], + tck, + ), + ) + spline_points = np.stack((x_new, y_new), axis=1).astype( + np.int32 + ) + except ValueError: + spline_points = unique_xy.astype(np.int32) + else: + spline_points = unique_xy.astype(np.int32) + + if len(xy) > 1: + cv2.polylines( + scene, + [spline_points], + False, + color=color.as_bgr(), + thickness=self.thickness, + ) + return scene + + +class HeatMapAnnotator(BaseAnnotator): + """ + A class for drawing heatmaps on an image based on provided detections. + Heat accumulates over time and is drawn as a semi-transparent overlay + of blurred circles. + """ + + def __init__( + self, + position: Position = Position.BOTTOM_CENTER, + opacity: float = 0.2, + radius: int = 40, + kernel_size: int | None = 25, + top_hue: int = 0, + low_hue: int = 125, + ): + """ + Args: + position: The position of the heatmap. Defaults to + `BOTTOM_CENTER`. + opacity: Opacity of the overlay mask. Must be between `0` and `1`. + radius: Radius of the heat circle. + kernel_size: Kernel size for blurring the heatmap. Pass `None` + to disable blurring entirely. + top_hue: Hue at the top of the heatmap. Defaults to 0 (red). + low_hue: Hue at the bottom of the heatmap. Defaults to 125 (blue). + """ + self.position = position + self.opacity = opacity + self.radius = radius + self.kernel_size = kernel_size + self.top_hue = top_hue + self.low_hue = low_hue + self.heat_mask: npt.NDArray[np.float32] | None = None + + def reset(self) -> None: + """ + Clears the accumulated heat so the annotator can be reused across + independent streams. `annotate` already reinitializes the heat mask + when the scene resolution changes; call this to discard heat from a + previous stream that shares the same resolution. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> image = np.zeros((40, 40, 3), dtype=np.uint8) + >>> detections = sv.Detections(xyxy=np.array([[10, 10, 20, 20]])) + >>> heat_map_annotator = sv.HeatMapAnnotator() + >>> _ = heat_map_annotator.annotate( + ... scene=image.copy(), + ... detections=detections + ... ) + >>> bool(heat_map_annotator.heat_mask.sum() > 0) + True + >>> heat_map_annotator.reset() + >>> heat_map_annotator.heat_mask is None + True + + ``` + """ + self.heat_mask = None + + @ensure_cv2_image_for_class_method + def annotate(self, scene: ImageType, detections: Detections) -> ImageType: + """ + Annotates the scene with a heatmap based on the provided detections. + + Args: + scene: The image where the heatmap will be drawn. + `ImageType` is a flexible type, accepting either `numpy.ndarray` + or `PIL.Image.Image`. + detections: Object detections to annotate. + + Returns: + The annotated image, matching the type of `scene` (`numpy.ndarray` + or `PIL.Image.Image`) + + Note: + When `detections` is empty or no heat has accumulated yet, the + scene is returned unchanged without raising a ``RuntimeWarning``. + + Examples: + ```python + import supervision as sv + from rfdetr import RFDETRMedium + + model = RFDETRMedium() + + heat_map_annotator = sv.HeatMapAnnotator() + + video_info = sv.VideoInfo.from_video_path(video_path='...') + frames_generator = sv.get_video_frames_generator(source_path='...') + + with sv.VideoSink(target_path='...', video_info=video_info) as sink: + for frame in frames_generator: + detections = model.predict(frame[:, :, ::-1]) + annotated_frame = heat_map_annotator.annotate( + scene=frame.copy(), + detections=detections) + sink.write_frame(frame=annotated_frame) + ``` + + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> image = np.zeros((100, 100, 3), dtype=np.uint8) + >>> detections = sv.Detections( + ... xyxy=np.array([[20, 20, 80, 80]]), + ... class_id=np.array([0]), + ... ) + >>> heat_map_annotator = sv.HeatMapAnnotator() + >>> annotated_frame = heat_map_annotator.annotate( + ... scene=image.copy(), + ... detections=detections + ... ) + >>> bool(heat_map_annotator.heat_mask.sum() > 0) + True + + ``` + + ![heatmap-annotator-example](https://media.roboflow.com/ + supervision-annotator-examples/heat-map-annotator-example-purple.png) + """ + if not isinstance(scene, np.ndarray): + return scene + if self.heat_mask is None or self.heat_mask.shape != scene.shape[:2]: + self.heat_mask = np.zeros(scene.shape[:2], dtype=np.float32) + + mask: npt.NDArray[np.float32] = np.zeros(scene.shape[:2], dtype=np.float32) + for xy in detections.get_anchors_coordinates(self.position): + x, y = int(xy[0]), int(xy[1]) + cv2.circle( + img=mask, + center=(x, y), + radius=self.radius, + color=(1,), + thickness=-1, # fill + ) + self.heat_mask = mask + self.heat_mask + heat_mask = self.heat_mask + heat_values = heat_mask.copy() + max_val = heat_values.max() + if max_val > 0: + heat_values = self.low_hue - heat_values / max_val * ( + self.low_hue - self.top_hue + ) + heat_hue = heat_values.astype(np.uint8) + if self.kernel_size is not None: + heat_hue = cast( + npt.NDArray[np.uint8], + cv2.blur(heat_hue, (self.kernel_size, self.kernel_size)), + ) + hsv = np.full(scene.shape, 255, dtype=np.uint8) + hsv[..., 0] = heat_hue + heat_bgr = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR) + mask2d = heat_mask > 0 + blended = cv2.addWeighted(heat_bgr, self.opacity, scene, 1 - self.opacity, 0) + scene[mask2d] = blended[mask2d] + return scene + + +class PixelateAnnotator(BaseAnnotator): + """ + A class for pixelating regions in an image using provided detections. + """ + + def __init__(self, pixel_size: int | None = None): + """ + Args: + pixel_size: The size of the pixelation. If not set, a dynamic size is + computed as one-half of the shorter bounding-box dimension. When set + and the detection area is smaller than `pixel_size`, the region is + filled with its average colour instead to avoid an OpenCV crash. + Must be >= 1 when provided. + """ + if pixel_size is not None and pixel_size < 1: + raise ValueError(f"pixel_size must be >= 1, got {pixel_size}.") + self.pixel_size: int | None = pixel_size + + @ensure_cv2_image_for_class_method + def annotate( + self, + scene: ImageType, + detections: Detections, + ) -> ImageType: + """ + Annotates the given scene by pixelating regions based on the provided + detections. + + Args: + scene: The image where pixelating will be applied. + `ImageType` is a flexible type, accepting either `numpy.ndarray` + or `PIL.Image.Image`. + detections: Object detections to annotate. + + Returns: + The annotated image, matching the type of `scene` (`numpy.ndarray` + or `PIL.Image.Image`) + + Example: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> image = np.zeros((100, 100, 3), dtype=np.uint8) + >>> detections = sv.Detections( + ... xyxy=np.array([[20, 20, 80, 80]]), + ... class_id=np.array([0]), + ... ) + >>> pixelate_annotator = sv.PixelateAnnotator() + >>> annotated_frame = pixelate_annotator.annotate( + ... scene=image.copy(), + ... detections=detections + ... ) + + ``` + + ![pixelate-annotator-example](https://media.roboflow.com/ + supervision-annotator-examples/pixelate-annotator-example-10.png) + """ + if not isinstance(scene, np.ndarray): + return scene + image_height, image_width = scene.shape[:2] + clipped_xyxy: npt.NDArray[np.int32] = clip_boxes( + xyxy=detections.xyxy, + resolution_wh=(image_width, image_height), + ).astype(int) + + for x1, y1, x2, y2 in clipped_xyxy: + if x2 <= x1 or y2 <= y1: + continue + roi = scene[y1:y2, x1:x2] + + pixel_size = ( + self.pixel_size + if self.pixel_size is not None + else calculate_dynamic_pixel_size(x1, y1, x2, y2) + ) + if min(y2 - y1, x2 - x1) < pixel_size: + if roi.ndim == 2 or (roi.ndim == 3 and roi.shape[2] == 1): + scene[y1:y2, x1:x2] = cv2.mean(roi)[0] + else: + num_channels = scene.shape[2] + scene[y1:y2, x1:x2] = cv2.mean(roi)[:num_channels] + continue + + scaled_up_roi = cv2.resize( + src=roi, dsize=None, fx=1 / pixel_size, fy=1 / pixel_size + ) + scaled_down_roi = cv2.resize( + src=scaled_up_roi, + dsize=(roi.shape[1], roi.shape[0]), + interpolation=cv2.INTER_NEAREST, + ) + + scene[y1:y2, x1:x2] = scaled_down_roi + + return scene + + +class TriangleAnnotator(BaseAnnotator): + """ + A class for drawing triangle markers on an image at specific coordinates based on + provided detections. + """ + + def __init__( + self, + color: Color | ColorPalette | str = ColorPalette.DEFAULT, + base: int = 10, + height: int = 10, + position: Position = Position.TOP_CENTER, + color_lookup: ColorLookup = ColorLookup.CLASS, + outline_thickness: int = 0, + outline_color: Color | ColorPalette | str = Color.BLACK, + ): + """ + Args: + color: The color or color palette to use for + annotating detections. + base: The base width of the triangle. + height: The height of the triangle. + position: The anchor position for placing the triangle. + color_lookup: Strategy for mapping colors to annotations. + Options are `INDEX`, `CLASS`, `TRACK`. + outline_thickness: Thickness of the outline of the triangle. + outline_color: The color or color palette to + use for outline. It is activated by setting outline_thickness to a value + greater than 0. + """ + self.color: Color | ColorPalette = _normalize_color_input(color) + self.base: int = base + self.height: int = height + self.position: Position = position + self.color_lookup: ColorLookup = color_lookup + self.outline_thickness: int = outline_thickness + self.outline_color: Color | ColorPalette = _normalize_color_input(outline_color) + + @ensure_cv2_image_for_class_method + def annotate( + self, + scene: ImageType, + detections: Detections, + custom_color_lookup: npt.NDArray[np.int_] | None = None, + ) -> ImageType: + """ + Annotates the given scene with triangles based on the provided detections. + + Args: + scene: The image where triangles will be drawn. + `ImageType` is a flexible type, accepting either `numpy.ndarray` + or `PIL.Image.Image`. + detections: Object detections to annotate. + custom_color_lookup: Custom color lookup array. + Allows to override the default color mapping strategy. + + Returns: + The annotated image, matching the type of `scene` (`numpy.ndarray` + or `PIL.Image.Image`) + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> image = np.zeros((100, 100, 3), dtype=np.uint8) + >>> detections = sv.Detections( + ... xyxy=np.array([[20, 20, 80, 80]]), + ... class_id=np.array([0]) + ... ) + >>> triangle_annotator = sv.TriangleAnnotator() + >>> annotated_frame = triangle_annotator.annotate( + ... scene=image.copy(), + ... detections=detections + ... ) + + ``` + + ![triangle-annotator-example](https://media.roboflow.com/ + supervision-annotator-examples/triangle-annotator-example.png) + """ + if not isinstance(scene, np.ndarray): + return scene + xy = detections.get_anchors_coordinates(anchor=self.position) + for detection_idx in range(len(detections)): + color = resolve_color( + color=self.color, + detections=detections, + detection_idx=detection_idx, + color_lookup=self.color_lookup + if custom_color_lookup is None + else custom_color_lookup, + ) + tip_x, tip_y = int(xy[detection_idx, 0]), int(xy[detection_idx, 1]) + vertices = np.array( + [ + [tip_x - self.base // 2, tip_y - self.height], + [tip_x + self.base // 2, tip_y - self.height], + [tip_x, tip_y], + ], + np.int32, + ) + + cv2.fillPoly(scene, [vertices], color.as_bgr()) + if self.outline_thickness: + outline_color = resolve_color( + color=self.outline_color, + detections=detections, + detection_idx=detection_idx, + color_lookup=self.color_lookup + if custom_color_lookup is None + else custom_color_lookup, + ) + cv2.polylines( + scene, + [vertices], + True, + outline_color.as_bgr(), + thickness=self.outline_thickness, + ) + return scene + + +class RoundBoxAnnotator(BaseAnnotator): + """ + A class for drawing bounding boxes with round edges on an image + using provided detections. + """ + + def __init__( + self, + color: Color | ColorPalette | str = ColorPalette.DEFAULT, + thickness: int = 2, + color_lookup: ColorLookup = ColorLookup.CLASS, + roundness: float = 0.6, + ): + """ + Args: + color: The color or color palette to use for + annotating detections. + thickness: Thickness of the bounding box lines. + color_lookup: Strategy for mapping colors to annotations. + Options are `INDEX`, `CLASS`, `TRACK`. + roundness: Percent of roundness for edges of bounding box. + Value must be float 0 < roundness <= 1.0 + By default roundness percent is calculated based on smaller side + length (width or height). + """ + self.color: Color | ColorPalette = _normalize_color_input(color) + self.thickness: int = thickness + self.color_lookup: ColorLookup = color_lookup + if not 0 < roundness <= 1.0: + raise ValueError("roundness attribute must be float between (0, 1.0]") + self.roundness: float = roundness + + @ensure_cv2_image_for_class_method + def annotate( + self, + scene: ImageType, + detections: Detections, + custom_color_lookup: npt.NDArray[np.int_] | None = None, + ) -> ImageType: + """ + Annotates the given scene with bounding boxes with rounded edges + based on the provided detections. + + Args: + scene: The image where rounded bounding boxes will be drawn. + `ImageType` is a flexible type, accepting either `numpy.ndarray` + or `PIL.Image.Image`. + detections: Object detections to annotate. + custom_color_lookup: Custom color lookup array. + Allows to override the default color mapping strategy. + + Returns: + The annotated image, matching the type of `scene` (`numpy.ndarray` + or `PIL.Image.Image`) + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> image = np.zeros((100, 100, 3), dtype=np.uint8) + >>> detections = sv.Detections( + ... xyxy=np.array([[20, 20, 80, 80]]), + ... class_id=np.array([0]) + ... ) + >>> round_box_annotator = sv.RoundBoxAnnotator() + >>> annotated_frame = round_box_annotator.annotate( + ... scene=image.copy(), + ... detections=detections + ... ) + + ``` + + ![round-box-annotator-example](https://media.roboflow.com/ + supervision-annotator-examples/round-box-annotator-example-purple.png) + """ + if not isinstance(scene, np.ndarray): + return scene + for detection_idx in range(len(detections)): + x1, y1, x2, y2 = detections.xyxy[detection_idx].astype(int) + color = resolve_color( + color=self.color, + detections=detections, + detection_idx=detection_idx, + color_lookup=self.color_lookup + if custom_color_lookup is None + else custom_color_lookup, + ) + + radius = ( + int((x2 - x1) // 2 * self.roundness) + if abs(x1 - x2) < abs(y1 - y2) + else int((y2 - y1) // 2 * self.roundness) + ) + + circle_coordinates = [ + ((x1 + radius), (y1 + radius)), + ((x2 - radius), (y1 + radius)), + ((x2 - radius), (y2 - radius)), + ((x1 + radius), (y2 - radius)), + ] + + line_coordinates = [ + ((x1 + radius, y1), (x2 - radius, y1)), + ((x2, y1 + radius), (x2, y2 - radius)), + ((x1 + radius, y2), (x2 - radius, y2)), + ((x1, y1 + radius), (x1, y2 - radius)), + ] + + start_angles = (180, 270, 0, 90) + end_angles = (270, 360, 90, 180) + + for center_coordinates, line, start_angle, end_angle in zip( + circle_coordinates, line_coordinates, start_angles, end_angles + ): + cv2.ellipse( + img=scene, + center=center_coordinates, + axes=(radius, radius), + angle=0, + startAngle=start_angle, + endAngle=end_angle, + color=color.as_bgr(), + thickness=self.thickness, + ) + + cv2.line( + img=scene, + pt1=line[0], + pt2=line[1], + color=color.as_bgr(), + thickness=self.thickness, + ) + + return scene + + +class PercentageBarAnnotator(BaseAnnotator): + """ + A class for drawing percentage bars on an image using provided detections. + """ + + def __init__( + self, + height: int = 16, + width: int = 80, + color: Color | ColorPalette | str = ColorPalette.DEFAULT, + border_color: Color | str = Color.BLACK, + position: Position = Position.TOP_CENTER, + color_lookup: ColorLookup = ColorLookup.CLASS, + border_thickness: int | None = None, + ): + """ + Args: + height: The height in pixels of the percentage bar. + width: The width in pixels of the percentage bar. + color: The color or color palette to use for + annotating detections. + border_color: The color of the border lines. + position: The anchor position of drawing the percentage bar. + color_lookup: Strategy for mapping colors to annotations. + Options are `INDEX`, `CLASS`, `TRACK`. + border_thickness: The thickness of the border lines. + """ + self.height: int = height + self.width: int = width + self.color: Color | ColorPalette = _normalize_color_input(color) + self.border_color = cast(Color, _normalize_color_input(border_color)) + self.position: Position = position + self.color_lookup: ColorLookup = color_lookup + + self.border_thickness = ( + border_thickness + if border_thickness is not None + else int(0.15 * self.height) + ) + + @ensure_cv2_image_for_class_method + def annotate( + self, + scene: ImageType, + detections: Detections, + custom_color_lookup: npt.NDArray[np.int_] | None = None, + custom_values: npt.NDArray[np.float64] | None = None, + ) -> ImageType: + """ + Annotates the given scene with percentage bars based on the provided + detections. The percentage bars visually represent the confidence or custom + values associated with each detection. + + Args: + scene: The image where percentage bars will be drawn. + `ImageType` is a flexible type, accepting either `numpy.ndarray` + or `PIL.Image.Image`. + detections: Object detections to annotate. + custom_color_lookup: Custom color lookup array. + Allows to override the default color mapping strategy. + custom_values: Custom values array to use instead + of the default detection confidences. This array should have the + same length as the number of detections and contain a value between + 0 and 1 (inclusive) for each detection, representing the percentage + to be displayed. + + Returns: + The annotated image, matching the type of `scene` (`numpy.ndarray` + or `PIL.Image.Image`) + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> image = np.zeros((100, 100, 3), dtype=np.uint8) + >>> detections = sv.Detections( + ... xyxy=np.array([[20, 20, 80, 80]]), + ... confidence=np.array([0.9]), + ... class_id=np.array([0]) + ... ) + >>> percentage_bar_annotator = sv.PercentageBarAnnotator() + >>> annotated_frame = percentage_bar_annotator.annotate( + ... scene=image.copy(), + ... detections=detections + ... ) + + ``` + + ![percentage-bar-example](https://media.roboflow.com/ + supervision-annotator-examples/percentage-bar-annotator-example-purple.png) + """ + if not isinstance(scene, np.ndarray): + return scene + self._validate_custom_values(custom_values=custom_values, detections=detections) + + anchors = detections.get_anchors_coordinates(anchor=self.position) + for detection_idx in range(len(detections)): + anchor = anchors[detection_idx] + border_coordinates = self.calculate_border_coordinates( + anchor_xy=(int(anchor[0]), int(anchor[1])), + border_wh=(self.width, self.height), + position=self.position, + ) + border_width = border_coordinates[1][0] - border_coordinates[0][0] + + if custom_values is not None: + value = custom_values[detection_idx] + else: + assert detections.confidence is not None # MyPy type hint + value = detections.confidence[detection_idx] + + color = resolve_color( + color=self.color, + detections=detections, + detection_idx=detection_idx, + color_lookup=self.color_lookup + if custom_color_lookup is None + else custom_color_lookup, + ) + cv2.rectangle( + img=scene, + pt1=border_coordinates[0], + pt2=( + border_coordinates[0][0] + int(border_width * value), + border_coordinates[1][1], + ), + color=color.as_bgr(), + thickness=-1, + ) + cv2.rectangle( + img=scene, + pt1=border_coordinates[0], + pt2=border_coordinates[1], + color=self.border_color.as_bgr(), + thickness=self.border_thickness, + ) + return scene + + @staticmethod + def calculate_border_coordinates( + anchor_xy: tuple[int, int], border_wh: tuple[int, int], position: Position + ) -> tuple[tuple[int, int], tuple[int, int]]: + """Compute the border corner coordinates for a given anchor position.""" + cx, cy = anchor_xy + width, height = border_wh + + if position == Position.TOP_LEFT: + return (cx - width, cy - height), (cx, cy) + elif position == Position.TOP_CENTER: + return (cx - width // 2, cy), (cx + width // 2, cy - height) + elif position == Position.TOP_RIGHT: + return (cx, cy), (cx + width, cy - height) + elif position == Position.CENTER_LEFT: + return (cx - width, cy - height // 2), (cx, cy + height // 2) + elif position == Position.CENTER or position == Position.CENTER_OF_MASS: + return ( + (cx - width // 2, cy - height // 2), + (cx + width // 2, cy + height // 2), + ) + elif position == Position.CENTER_RIGHT: + return (cx, cy - height // 2), (cx + width, cy + height // 2) + elif position == Position.BOTTOM_LEFT: + return (cx - width, cy), (cx, cy + height) + elif position == Position.BOTTOM_CENTER: + return (cx - width // 2, cy), (cx + width // 2, cy + height) + elif position == Position.BOTTOM_RIGHT: + return (cx, cy), (cx + width, cy + height) + raise ValueError(f"Unsupported position: {position}") + + @staticmethod + def _validate_custom_values( + custom_values: npt.NDArray[np.float64] | list[float] | None, + detections: Detections, + ) -> None: + if custom_values is None: + if detections.confidence is None: + raise ValueError( + "The provided detections do not contain confidence values. " + "Please provide `custom_values` or ensure that the detections " + "contain confidence values (e.g. by using a different model)." + ) + + else: + if not isinstance(custom_values, (np.ndarray, list)): + raise TypeError( + "custom_values must be either a numpy array or a list of floats." + ) + + if len(custom_values) != len(detections): + raise ValueError( + "The length of custom_values must match the number of detections." + ) + + if not all(0 <= value <= 1 for value in custom_values): + raise ValueError("All values in custom_values must be between 0 and 1.") + + @staticmethod + @deprecated( # type: ignore[untyped-decorator] + target=_validate_custom_values.__func__, # type: ignore[attr-defined] + deprecated_in="0.29.0", + remove_in="0.32.0", + ) + def validate_custom_values( + custom_values: npt.NDArray[np.float64] | list[float] | None, + detections: Detections, + ) -> None: + void(custom_values, detections) + + +class CropAnnotator(BaseAnnotator): + """ + A class for drawing scaled up crops of detections on the scene. + """ + + def __init__( + self, + position: Position = Position.TOP_CENTER, + scale_factor: float = 2.0, + border_color: Color | ColorPalette | str = ColorPalette.DEFAULT, + border_thickness: int = 2, + border_color_lookup: ColorLookup = ColorLookup.CLASS, + ): + """ + Args: + position: The anchor position for placing the cropped and scaled + part of the detection in the scene. + scale_factor: The factor by which to scale the cropped image part. A + factor of 2, for example, would double the size of the cropped area, + allowing for a closer view of the detection. + border_color: The color or color palette to + use for annotating border around the cropped area. + border_thickness: The thickness of the border around the cropped area. + border_color_lookup: Strategy for mapping colors to + annotations. Options are `INDEX`, `CLASS`, `TRACK`. + """ + self.position: Position = position + self.scale_factor: float = scale_factor + self.border_color: Color | ColorPalette = _normalize_color_input(border_color) + self.border_thickness: int = border_thickness + self.border_color_lookup: ColorLookup = border_color_lookup + + @ensure_cv2_image_for_class_method + def annotate( + self, + scene: ImageType, + detections: Detections, + custom_color_lookup: npt.NDArray[np.int_] | None = None, + ) -> ImageType: + """ + Annotates the provided scene with scaled and cropped parts of the image based + on the provided detections. Each detection is cropped from the original scene + and scaled according to the annotator's scale factor before being placed back + onto the scene at the specified position. + + + Args: + scene: The image where cropped detection will be placed. + `ImageType` is a flexible type, accepting either `numpy.ndarray` + or `PIL.Image.Image`. + detections: Object detections to annotate. + custom_color_lookup: Custom color lookup array. + Allows to override the default color mapping strategy. + + Returns: + The annotated image. + + Note: + Detections whose bounding boxes extend partially outside `scene` are + clipped to scene bounds before cropping. Detections fully outside the + scene collapse to zero area after clipping and are skipped without + raising an error. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> image = np.zeros((100, 100, 3), dtype=np.uint8) + >>> detections = sv.Detections( + ... xyxy=np.array([[20, 20, 80, 80]]), + ... class_id=np.array([0]) + ... ) + >>> crop_annotator = sv.CropAnnotator() + >>> annotated_frame = crop_annotator.annotate( + ... scene=image.copy(), + ... detections=detections + ... ) + + ``` + + ![crop-annotator-example](https://media.roboflow.com/ + supervision-annotator-examples/crop-annotator-example.png) + """ + if not isinstance(scene, np.ndarray): + return scene + image_height, image_width = scene.shape[:2] + clipped_xyxy: npt.NDArray[np.int32] = clip_boxes( + xyxy=detections.xyxy, + resolution_wh=(image_width, image_height), + ).astype(np.int32) + anchors: npt.NDArray[np.int32] = detections.get_anchors_coordinates( + anchor=self.position + ).astype(np.int32) + # Snapshot before the loop so later crops are taken from the original image, + # not a scene already annotated by earlier iterations (overlapping-box case). + source_scene = scene.copy() + + for idx, (xyxy, anchor) in enumerate(zip(clipped_xyxy, anchors)): + crop_x1, crop_y1, crop_x2, crop_y2 = xyxy + if crop_x2 <= crop_x1 or crop_y2 <= crop_y1: + continue + crop = crop_image(image=source_scene, xyxy=xyxy) + resized_crop = scale_image(image=crop, scale_factor=self.scale_factor) + crop_wh = resized_crop.shape[1], resized_crop.shape[0] + (x1, y1), (x2, y2) = self.calculate_crop_coordinates( + anchor=anchor, crop_wh=crop_wh, position=self.position + ) + scene = _overlay_image(image=scene, overlay=resized_crop, anchor=(x1, y1)) + color = resolve_color( + color=self.border_color, + detections=detections, + detection_idx=idx, + color_lookup=self.border_color_lookup + if custom_color_lookup is None + else custom_color_lookup, + ) + cv2.rectangle( + img=scene, + pt1=(x1, y1), + pt2=(x2, y2), + color=color.as_bgr(), + thickness=self.border_thickness, + ) + + return scene + + @staticmethod + def calculate_crop_coordinates( + anchor: tuple[int, int], crop_wh: tuple[int, int], position: Position + ) -> tuple[tuple[int, int], tuple[int, int]]: + """Compute the crop coordinates for a given anchor position.""" + anchor_x, anchor_y = anchor + width, height = crop_wh + + if position == Position.TOP_LEFT: + return (anchor_x - width, anchor_y - height), (anchor_x, anchor_y) + elif position == Position.TOP_CENTER: + return ( + (anchor_x - width // 2, anchor_y - height), + (anchor_x + width // 2, anchor_y), + ) + elif position == Position.TOP_RIGHT: + return (anchor_x, anchor_y - height), (anchor_x + width, anchor_y) + elif position == Position.CENTER_LEFT: + return ( + (anchor_x - width, anchor_y - height // 2), + (anchor_x, anchor_y + height // 2), + ) + elif position == Position.CENTER or position == Position.CENTER_OF_MASS: + return ( + (anchor_x - width // 2, anchor_y - height // 2), + (anchor_x + width // 2, anchor_y + height // 2), + ) + elif position == Position.CENTER_RIGHT: + return ( + (anchor_x, anchor_y - height // 2), + (anchor_x + width, anchor_y + height // 2), + ) + elif position == Position.BOTTOM_LEFT: + return (anchor_x - width, anchor_y), (anchor_x, anchor_y + height) + elif position == Position.BOTTOM_CENTER: + return ( + (anchor_x - width // 2, anchor_y), + (anchor_x + width // 2, anchor_y + height), + ) + elif position == Position.BOTTOM_RIGHT: + return (anchor_x, anchor_y), (anchor_x + width, anchor_y + height) + raise ValueError(f"Unsupported position: {position}") + + +class BackgroundOverlayAnnotator(BaseAnnotator): + """ + A class for drawing a colored overlay on the background of an image outside + the region of detections. + + If masks are provided, the background is colored outside the masks. + If masks are not provided, the background is colored outside the bounding boxes. + + You can use the `force_box` parameter to force the annotator to use bounding boxes. + + !!! warning + + This annotator uses `sv.Detections.mask`. + """ + + def __init__( + self, + color: Color = Color.BLACK, + opacity: float = 0.5, + force_box: bool = False, + ): + """ + Args: + color: The color to use for annotating detections. + opacity: Opacity of the overlay mask. Must be between `0` and `1`. + force_box: If `True`, forces the annotator to use bounding boxes when + masks are provided in the supplied sv.Detections. + """ + self.color: Color = color + self.opacity = opacity + self.force_box = force_box + + @ensure_cv2_image_for_class_method + def annotate(self, scene: ImageType, detections: Detections) -> ImageType: + """ + Applies a colored overlay to the scene outside of the detected regions. + + Args: + scene: The image where masks will be drawn. + `ImageType` is a flexible type, accepting either `numpy.ndarray` + or `PIL.Image.Image`. + detections: Object detections to annotate. + + Returns: + The annotated image, matching the type of `scene` (`numpy.ndarray` + or `PIL.Image.Image`) + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> image = np.zeros((100, 100, 3), dtype=np.uint8) + >>> detections = sv.Detections( + ... xyxy=np.array([[20, 20, 80, 80]]), + ... class_id=np.array([0]) + ... ) + >>> background_overlay_annotator = sv.BackgroundOverlayAnnotator() + >>> annotated_frame = background_overlay_annotator.annotate( + ... scene=image.copy(), + ... detections=detections + ... ) + + ``` + + ![background-overlay-annotator-example](https://media.roboflow.com/ + supervision-annotator-examples/background-color-annotator-example-purple.png) + """ + if not isinstance(scene, np.ndarray): + return scene + colored_mask = np.full_like(scene, self.color.as_bgr(), dtype=np.uint8) + + cv2.addWeighted( + scene, 1 - self.opacity, colored_mask, self.opacity, 0, dst=colored_mask + ) + + if detections.mask is None or self.force_box: + image_height, image_width = scene.shape[:2] + clipped_xyxy: npt.NDArray[np.int32] = clip_boxes( + xyxy=detections.xyxy, + resolution_wh=(image_width, image_height), + ).astype(np.int32) + for x1, y1, x2, y2 in clipped_xyxy: + colored_mask[y1:y2, x1:x2] = scene[y1:y2, x1:x2] + else: + for mask in detections.mask: + mask_bool = np.asarray(mask, dtype=bool) + colored_mask[mask_bool] = scene[mask_bool] + + np.copyto(scene, colored_mask) + return scene + + +class ComparisonAnnotator: + """ + Highlights the differences between two sets of detections. + Useful for comparing results from two different models, or the difference + between a ground truth and a prediction. + + If present, uses the oriented bounding box data. + Otherwise, if present, uses a mask. + Otherwise, uses the bounding box data. + """ + + # Not a BaseAnnotator subclass — duck-typing callers can still check requires_mask + requires_mask: ClassVar[bool] = False + + def __init__( + self, + color_1: Color = Color.RED, + color_2: Color = Color.GREEN, + color_overlap: Color = Color.BLUE, + *, + opacity: float = 0.75, + label_1: str = "", + label_2: str = "", + label_overlap: str = "", + label_scale: float = 1.0, + ): + """ + Args: + color_1: Color of areas only present in the first set of + detections. + color_2: Color of areas only present in the second set of + detections. + color_overlap: Color of areas present in both sets of detections. + opacity: Opacity of the overlay mask. Must be between `0` and `1`. + label_1: Label for the first set of detections. + label_2: Label for the second set of detections. + label_overlap: Label for areas present in both sets of detections. + label_scale: Controls how large the labels are. + """ + + self.color_1 = color_1 + self.color_2 = color_2 + self.color_overlap = color_overlap + + self.opacity = opacity + self.label_1 = label_1 + self.label_2 = label_2 + self.label_overlap = label_overlap + self.label_scale = label_scale + self.text_thickness = int(self.label_scale + 1.2) + + @ensure_cv2_image_for_class_method + def annotate( + self, scene: ImageType, detections_1: Detections, detections_2: Detections + ) -> ImageType: + """ + Highlights the differences between two sets of detections. + + Args: + scene: The image where detections will be drawn. + `ImageType` is a flexible type, accepting either `numpy.ndarray` + or `PIL.Image.Image`. + detections_1: The first set of detections or predictions. + detections_2: The second set of detections to compare or + ground truth. + + Returns: + The annotated image. + + Example: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> image = np.zeros((100, 100, 3), dtype=np.uint8) + >>> detections_1 = sv.Detections( + ... xyxy=np.array([[10, 10, 50, 50]]), + ... class_id=np.array([0]), + ... ) + >>> detections_2 = sv.Detections( + ... xyxy=np.array([[40, 40, 90, 90]]), + ... class_id=np.array([0]), + ... ) + >>> comparison_annotator = sv.ComparisonAnnotator() + >>> annotated_frame = comparison_annotator.annotate( + ... scene=image.copy(), + ... detections_1=detections_1, + ... detections_2=detections_2 + ... ) + + ``` + + ![comparison-annotator-example](https://media.roboflow.com/ + supervision-annotator-examples/comparison-annotator-example.png) + """ + if not isinstance(scene, np.ndarray): + return scene + if detections_1.is_empty() and detections_2.is_empty(): + return scene + + use_obb = self._use_obb(detections_1, detections_2) + use_mask = self._use_mask(detections_1, detections_2) + + if use_obb: + mask_1 = self._mask_from_obb(scene, detections_1) + mask_2 = self._mask_from_obb(scene, detections_2) + + elif use_mask: + mask_1 = self._mask_from_mask(scene, detections_1) + mask_2 = self._mask_from_mask(scene, detections_2) + + else: + mask_1 = self._mask_from_xyxy(scene, detections_1) + mask_2 = self._mask_from_xyxy(scene, detections_2) + + mask_overlap = mask_1 & mask_2 + mask_1 = mask_1 & ~mask_overlap + mask_2 = mask_2 & ~mask_overlap + + color_layer = np.zeros_like(scene, dtype=np.uint8) + color_layer[mask_overlap] = self.color_overlap.as_bgr() + color_layer[mask_1] = self.color_1.as_bgr() + color_layer[mask_2] = self.color_2.as_bgr() + + scene[mask_overlap] = (1 - self.opacity) * scene[ + mask_overlap + ] + self.opacity * color_layer[mask_overlap] + scene[mask_1] = (1 - self.opacity) * scene[mask_1] + self.opacity * color_layer[ + mask_1 + ] + scene[mask_2] = (1 - self.opacity) * scene[mask_2] + self.opacity * color_layer[ + mask_2 + ] + + self._draw_labels(scene) + + return scene + + @staticmethod + def _use_obb(detections_1: Detections, detections_2: Detections) -> bool: + assert not detections_1.is_empty() or not detections_2.is_empty() + is_obb_1 = ORIENTED_BOX_COORDINATES in detections_1.data + is_obb_2 = ORIENTED_BOX_COORDINATES in detections_2.data + return ( + (is_obb_1 and is_obb_2) + or (is_obb_1 and detections_2.is_empty()) + or (detections_1.is_empty() and is_obb_2) + ) + + @staticmethod + def _use_mask(detections_1: Detections, detections_2: Detections) -> bool: + assert not detections_1.is_empty() or not detections_2.is_empty() + is_mask_1 = detections_1.mask is not None + is_mask_2 = detections_2.mask is not None + return ( + (is_mask_1 and is_mask_2) + or (is_mask_1 and detections_2.is_empty()) + or (detections_1.is_empty() and is_mask_2) + ) + + @staticmethod + def _mask_from_xyxy( + scene: npt.NDArray[np.uint8], detections: Detections + ) -> npt.NDArray[np.bool_]: + mask = np.zeros(scene.shape[:2], dtype=np.bool_) + if detections.is_empty(): + return mask + + resolution_wh = scene.shape[1], scene.shape[0] + polygons = xyxy_to_polygons(detections.xyxy) + + for polygon in polygons: + polygon_mask = polygon_to_mask(polygon, resolution_wh=resolution_wh) + mask |= polygon_mask.astype(np.bool_) + return mask + + @staticmethod + def _mask_from_obb( + scene: npt.NDArray[np.uint8], detections: Detections + ) -> npt.NDArray[np.bool_]: + mask = np.zeros(scene.shape[:2], dtype=np.bool_) + if detections.is_empty(): + return mask + + resolution_wh = scene.shape[1], scene.shape[0] + + for polygon in detections.data[ORIENTED_BOX_COORDINATES]: + polygon_mask = polygon_to_mask(polygon, resolution_wh=resolution_wh) + mask |= polygon_mask.astype(np.bool_) + return mask + + @staticmethod + def _mask_from_mask( + scene: npt.NDArray[np.uint8], detections: Detections + ) -> npt.NDArray[np.bool_]: + mask = np.zeros(scene.shape[:2], dtype=np.bool_) + if detections.is_empty(): + return mask + assert detections.mask is not None + + for detections_mask in detections.mask: + mask |= detections_mask.astype(np.bool_) + return mask + + def _draw_labels(self, scene: npt.NDArray[np.uint8]) -> None: + """ + Draw the labels, explaining what each color represents, with automatically + computed positions. + + Args: + scene: The image where the labels will be drawn. + """ + margin = int(50 * self.label_scale) + gap = int(40 * self.label_scale) + y0 = int(50 * self.label_scale) + height = int(50 * self.label_scale) + + marker_size = int(20 * self.label_scale) + padding = int(10 * self.label_scale) + text_box_corner_radius = int(10 * self.label_scale) + marker_corner_radius = int(4 * self.label_scale) + text_scale = self.label_scale + + label_color_pairs = [ + (self.label_1, self.color_1), + (self.label_2, self.color_2), + (self.label_overlap, self.color_overlap), + ] + + x0 = margin + for text, color in label_color_pairs: + if not text: + continue + + (text_w, _) = cv2.getTextSize( + text=text, + fontFace=CV2_FONT, + fontScale=self.label_scale, + thickness=self.text_thickness, + )[0] + + width = text_w + marker_size + padding * 4 + center_x = x0 + width // 2 + center_y = y0 + height // 2 + + draw_rounded_rectangle( + scene=scene, + rect=Rect(x=x0, y=y0, width=width, height=height), + color=Color.WHITE, + border_radius=text_box_corner_radius, + ) + + draw_rounded_rectangle( + scene=scene, + rect=Rect( + x=x0 + padding, + y=center_y - marker_size / 2, + width=marker_size, + height=marker_size, + ), + color=color, + border_radius=marker_corner_radius, + ) + + draw_text( + scene, + text, + text_anchor=Point(x=center_x + marker_size, y=center_y), + text_scale=text_scale, + text_thickness=self.text_thickness, + ) + + x0 += width + gap diff --git a/.venv/lib/python3.12/site-packages/supervision/annotators/utils.py b/.venv/lib/python3.12/site-packages/supervision/annotators/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..54058f39f4050e8d9b476ef6f46a4b3f66704c99 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/annotators/utils.py @@ -0,0 +1,576 @@ +import re +import textwrap +from enum import Enum +from typing import Any, cast + +import numpy as np +import numpy.typing as npt +from deprecate import deprecated, void + +from supervision.config import CLASS_NAME_DATA_FIELD +from supervision.detection.core import Detections +from supervision.draw.color import Color, ColorPalette +from supervision.geometry.core import Position + +PENDING_TRACK_COLOR = Color.GREY +PENDING_TRACK_ID = -1 + + +class ColorLookup(Enum): + """ + Enumeration class to define strategies for mapping colors to annotations. + + This enum supports three different lookup strategies: + - `INDEX`: Colors are determined by the index of the detection within the scene. + - `CLASS`: Colors are determined by the class label of the detected object. + - `TRACK`: Colors are determined by the tracking identifier of the object. + """ + + INDEX = "index" + CLASS = "class" + TRACK = "track" + + @classmethod + def list(cls) -> list[str]: + return list(map(lambda c: c.value, cls)) + + +def resolve_color_idx( + detections: Detections, + detection_idx: int, + color_lookup: ColorLookup | npt.NDArray[np.int_] = ColorLookup.CLASS, +) -> int: + if detection_idx >= len(detections): + raise ValueError( + f"Detection index {detection_idx} " + f"is out of bounds for detections of length {len(detections)}" + ) + + if isinstance(color_lookup, np.ndarray): + if len(color_lookup) != len(detections): + raise ValueError( + f"Length of color lookup {len(color_lookup)} " + f"does not match length of detections {len(detections)}" + ) + return int(color_lookup[detection_idx]) + elif color_lookup == ColorLookup.INDEX: + return detection_idx + elif color_lookup == ColorLookup.CLASS: + if detections.class_id is None: + raise ValueError( + "Could not resolve color by class because " + "Detections do not have class_id. If using an annotator, " + "try setting color_lookup to sv.ColorLookup.INDEX or " + "sv.ColorLookup.TRACK." + ) + return int(detections.class_id[detection_idx]) + elif color_lookup == ColorLookup.TRACK: + if detections.tracker_id is None: + raise ValueError( + "Could not resolve color by track because " + "Detections do not have tracker_id. Did you call " + "tracker.update_with_detections(...) before annotating?" + ) + return int(detections.tracker_id[detection_idx]) + raise ValueError(f"Unsupported color lookup strategy: {color_lookup}") + + +def resolve_text_background_xyxy( + center_coordinates: tuple[int, int], + text_wh: tuple[int, int], + position: Position, +) -> tuple[int, int, int, int]: + """Compute the background box for text anchored at `position`.""" + center_x, center_y = center_coordinates + text_w, text_h = text_wh + + if position == Position.TOP_LEFT: + return center_x, center_y - text_h, center_x + text_w, center_y + elif position == Position.TOP_RIGHT: + return center_x - text_w, center_y - text_h, center_x, center_y + elif position == Position.TOP_CENTER: + return ( + center_x - text_w // 2, + center_y - text_h, + center_x + text_w // 2, + center_y, + ) + elif position == Position.CENTER or position == Position.CENTER_OF_MASS: + return ( + center_x - text_w // 2, + center_y - text_h // 2, + center_x + text_w // 2, + center_y + text_h // 2, + ) + elif position == Position.BOTTOM_LEFT: + return center_x, center_y, center_x + text_w, center_y + text_h + elif position == Position.BOTTOM_RIGHT: + return center_x - text_w, center_y, center_x, center_y + text_h + elif position == Position.BOTTOM_CENTER: + return ( + center_x - text_w // 2, + center_y, + center_x + text_w // 2, + center_y + text_h, + ) + elif position == Position.CENTER_LEFT: + return ( + center_x - text_w, + center_y - text_h // 2, + center_x, + center_y + text_h // 2, + ) + elif position == Position.CENTER_RIGHT: + return ( + center_x, + center_y - text_h // 2, + center_x + text_w, + center_y + text_h // 2, + ) + raise ValueError(f"Unsupported position: {position}") + + +def get_color_by_index(color: Color | ColorPalette, idx: int) -> Color: + """Resolve a color-like object to a concrete `Color` for an index.""" + color_like = cast(Any, color) + # Accept ColorPalette-like objects without depending on their exact concrete class. + if callable(getattr(color_like, "by_idx", None)): + color_like = color_like.by_idx(idx) + if isinstance(color_like, Color): + return color_like + return Color( + r=int(color_like.r), + g=int(color_like.g), + b=int(color_like.b), + a=int(getattr(color_like, "a", 255)), + ) + + +def resolve_color( + color: Color | ColorPalette, + detections: Detections, + detection_idx: int, + color_lookup: ColorLookup | npt.NDArray[np.int_] = ColorLookup.CLASS, +) -> Color: + idx = resolve_color_idx( + detections=detections, + detection_idx=detection_idx, + color_lookup=color_lookup, + ) + if ( + isinstance(color_lookup, ColorLookup) + and color_lookup == ColorLookup.TRACK + and idx == PENDING_TRACK_ID + ): + return PENDING_TRACK_COLOR + return get_color_by_index(color=color, idx=idx) + + +def wrap_text(text: object, max_line_length: int | None = None) -> list[str]: + """ + Wrap `text` to the specified maximum line length, respecting existing + newlines. Falls back to str() if `text` is not already a string. + + Args: + text: The text (or object) to wrap. + max_line_length: Maximum width for each wrapped line. + + Returns: + Wrapped lines. + """ + + if not text: + return [""] + + if not isinstance(text, str): + text = str(text) + + if max_line_length is None: + return text.splitlines() or [""] + + if max_line_length <= 0: + raise ValueError("max_line_length must be a positive integer") + + paragraphs = text.split("\n") + all_lines: list[str] = [] + + for paragraph in paragraphs: + if paragraph == "": + all_lines.append("") + continue + + wrapped = textwrap.wrap( + paragraph, + width=max_line_length, + break_long_words=True, + replace_whitespace=False, + drop_whitespace=True, + ) + + all_lines.extend(wrapped or [""]) + + return all_lines or [""] + + +def _validate_labels(labels: list[str] | None, detections: Detections) -> None: + """ + Validates that the number of provided labels matches the number of detections. + + Args: + labels: A list of labels, one for each detection. Can + be None. + detections: The detections to be labeled. + + Raises: + ValueError: If `labels` is not None and its length does not match the number + of detections. + """ + if labels is not None and len(labels) != len(detections): + raise ValueError( + f"The number of labels ({len(labels)}) does not match the " + f"number of detections ({len(detections)}). Each detection " + f"should have exactly 1 label." + ) + + +@deprecated( # type: ignore[untyped-decorator] + target=_validate_labels, + deprecated_in="0.29.0", + remove_in="0.32.0", +) +def validate_labels(labels: list[str] | None, detections: Detections) -> None: + void(labels, detections) + + +def get_labels_text( + detections: Detections, custom_labels: list[str] | None +) -> list[str]: + """ + Retrieves the text labels for the detections. + + If `custom_labels` are provided, they are used. Otherwise, the labels are + extracted from the `detections` object, prioritizing the 'class_name' field, + then the `class_id`, and finally using the detection index as a string. + + Args: + detections: The detections to get labels for. + custom_labels: An optional list of custom labels. + + Returns: + A list of text labels for each detection. + + Raises: + ValueError: If `class_name` or `class_id` is present but its length + does not match the number of detections (e.g. `detections.data` + was mutated directly, bypassing `Detections` alignment checks). + """ + if custom_labels is not None: + return custom_labels + + if CLASS_NAME_DATA_FIELD in detections.data: + class_names = detections.data[CLASS_NAME_DATA_FIELD] + # `Detections.data` is normally kept aligned with `xyxy` by the + # dataclass's own validation, but a caller can bypass it by mutating + # `detections.data` directly. Fail loudly rather than silently + # dropping or duplicating labels. + if len(class_names) != len(detections): + raise ValueError( + f"'{CLASS_NAME_DATA_FIELD}' has {len(class_names)} entries " + f"but detections has {len(detections)} - the two must stay " + "aligned." + ) + return [str(v) for v in class_names] + if detections.class_id is not None: + if len(detections.class_id) != len(detections): + raise ValueError( + f"'class_id' has {len(detections.class_id)} entries but " + f"detections has {len(detections)} - the two must stay " + "aligned." + ) + return [str(v) for v in detections.class_id] + return [str(i) for i in range(len(detections))] + + +def snap_boxes( + xyxy: npt.NDArray[np.float32], + resolution_wh: tuple[int, int], +) -> npt.NDArray[np.float32]: + """ + Shifts `label` bounding boxes into the frame so that they are fully contained + within the given resolution, prioritizing the top/left edge. + Unlike `clip_boxes`, this function does not crop boxes. + It moves them entirely if they exceed the frame boundaries. + + Args: + xyxy: A numpy array of shape `(N, 4)` where each + row corresponds to a bounding box in the format + `(x_min, y_min, x_max, y_max)`. + resolution_wh: A tuple `(width, height)` + representing the resolution of the frame. + + Returns: + A numpy array of shape `(N, 4)` with boxes shifted into frame. + + Examples: + ```pycon + >>> import numpy as np + >>> from supervision.annotators.utils import snap_boxes + >>> xyxy = np.array([ + ... [-10, 10, 30, 50], # Off left edge + ... [310, 200, 350, 250], # Off right edge + ... [100, -20, 150, 30], # Off top edge + ... [200, 220, 250, 270], # Off bottom edge + ... [-20, 10, 350, 50], # Wider than frame (370 vs 320) + ... [10, -20, 30, 260] # Taller than frame (280 vs 240) + ... ]) + >>> resolution_wh = (320, 240) + >>> snapped_boxes = snap_boxes(xyxy=xyxy, resolution_wh=resolution_wh) + >>> snapped_boxes + array([[ 0., 10., 40., 50.], + [280., 190., 320., 240.], + [100., 0., 150., 50.], + [200., 190., 250., 240.], + [ 0., 10., 370., 50.], + [ 10., 0., 30., 280.]], dtype=float32) + + ``` + """ + result: npt.NDArray[np.float32] = np.array(xyxy, dtype=np.float32, copy=True) + width, height = resolution_wh + + # X-axis (prioritize left edge) + left_overflow = result[:, 0] < 0 + result[left_overflow, 0:3:2] -= result[left_overflow, 0:1] + + right_overflow = (~left_overflow) & (result[:, 2] > width) + right_shift = width - result[right_overflow, 2] + result[right_overflow, 0:3:2] += right_shift[:, np.newaxis] + + # Y-axis (prioritize top edge) + top_overflow = result[:, 1] < 0 + result[top_overflow, 1:4:2] -= result[top_overflow, 1:2] + + bottom_overflow = (~top_overflow) & (result[:, 3] > height) + bottom_shift = height - result[bottom_overflow, 3] + result[bottom_overflow, 1:4:2] += bottom_shift[:, np.newaxis] + + return cast(npt.NDArray[np.float32], result.astype(np.float32, copy=False)) + + +class Trace: + def __init__( + self, + max_size: int | None = None, + start_frame_id: int = 0, + anchor: Position = Position.CENTER, + ) -> None: + self.current_frame_id = start_frame_id + self.max_size = max_size + self.anchor = anchor + + self.frame_id: npt.NDArray[np.int_] = np.array([], dtype=int) + self.xy: npt.NDArray[np.float32] = np.empty((0, 2), dtype=np.float32) + self.tracker_id: npt.NDArray[np.int_] = np.array([], dtype=int) + + def put(self, detections: Detections) -> None: + """Append a frame of detections to the trace history. + + A frame that detected nothing contributes no points but still advances + the frame counter, keeping `max_size` a window over elapsed frames + rather than over populated ones. An empty frame has no anchors and no + `tracker_id`, so only frames that carry detections require one. + + Pruning runs on the next frame that does carry detections, measures + the window from the advanced counter, and only fires once the distinct + frames held in the history — counting the frame that triggers it — + outnumber `max_size`. A track that had filled the window before a long + gap therefore starts a fresh trail, while a track whose stored history + stayed shorter than the window is still joined to its pre-gap points. + + History is normalised on the way in: anchor points are stored as + `float32` and tracker ids are cast to NumPy's default integer dtype + (`np.int_`), so tracker ids outside that dtype's range are unsupported. + """ + if len(detections) == 0: + xy: npt.NDArray[np.float32] = np.empty((0, 2), dtype=np.float32) + tracker_id: npt.NDArray[np.int_] = np.array([], dtype=int) + else: + if detections.tracker_id is None: + raise ValueError( + "Could not put detections into Trace because " + "Detections do not have tracker_id." + ) + xy = np.asarray( + detections.get_anchors_coordinates(self.anchor), dtype=np.float32 + ) + tracker_id = np.asarray(detections.tracker_id, dtype=int) + + frame_id: npt.NDArray[np.int_] = np.full( + len(detections), self.current_frame_id, dtype=int + ) + self.frame_id = np.concatenate([self.frame_id, frame_id]) + self.xy = np.concatenate([self.xy, xy]) + self.tracker_id = np.concatenate([self.tracker_id, tracker_id]) + + unique_frame_id = np.unique(self.frame_id) + + if self.max_size is not None and 0 < self.max_size < len(unique_frame_id): + max_allowed_frame_id = self.current_frame_id - self.max_size + 1 + filtering_mask = self.frame_id >= max_allowed_frame_id + self.frame_id = self.frame_id[filtering_mask] + self.xy = self.xy[filtering_mask] + self.tracker_id = self.tracker_id[filtering_mask] + + self.current_frame_id += 1 + + def get(self, tracker_id: int) -> npt.NDArray[np.float32]: + xy: npt.NDArray[np.float32] = np.asarray( + self.xy[self.tracker_id == tracker_id], dtype=np.float32 + ) + return xy + + def reset(self) -> None: + """Restore the trace buffers to their initial empty state. + + Clears the accumulated `frame_id`, `xy`, and `tracker_id` history and + rewinds `current_frame_id` to `0`, so the trace can be reused across + independent streams without carrying over points from a previous run. + """ + self.current_frame_id = 0 + self.frame_id = np.array([], dtype=int) + self.xy = np.empty((0, 2), dtype=np.float32) + self.tracker_id = np.array([], dtype=int) + + +def hex_to_rgba(hex_color: str) -> tuple[int, int, int, int]: + """ + Converts a hex color string (e.g. "#FF00FF" or "#FF00FF80") to an RGBA tuple. + + Args: + hex_color: A hex color string. + + Returns: + RGBA values in range 0-255. + + Raises: + ValueError: If the format is invalid. + + Examples: + ```pycon + >>> from supervision.annotators.utils import hex_to_rgba + >>> hex_to_rgba("#FF00FF") + (255, 0, 255, 255) + >>> hex_to_rgba("#FF00FF80") + (255, 0, 255, 128) + + ``` + """ + hex_color = hex_color.strip().removeprefix("#") + if len(hex_color) == 6: + hex_color += "FF" # default full opacity + if len(hex_color) != 8: + raise ValueError(f"Invalid hex color format: {hex_color}") + try: + r = int(hex_color[0:2], 16) + g = int(hex_color[2:4], 16) + b = int(hex_color[4:6], 16) + a = int(hex_color[6:8], 16) + except ValueError as exc: + raise ValueError(f"Invalid hex digits in {hex_color}") from exc + return (r, g, b, a) + + +def rgba_to_hex(rgba: tuple[int, int, int, int]) -> str: + """ + Converts an RGBA tuple (0-255 each) to a hex color string. + + Args: + rgba: RGBA values in range 0-255. + + Returns: + Hex color string in the format "#RRGGBBAA". + + Raises: + ValueError: If `rgba` is not a 4-tuple or contains values outside 0-255. + + Examples: + ```pycon + >>> from supervision.annotators.utils import rgba_to_hex + >>> rgba_to_hex((255, 0, 255, 128)) + '#FF00FF80' + + ``` + """ + if len(rgba) != 4 or not all(0 <= c <= 255 for c in rgba): + raise ValueError("RGBA must be a 4-tuple with values between 0-255.") + return "#{:02X}{:02X}{:02X}{:02X}".format(*rgba) + + +def is_valid_hex(hex_color: str) -> bool: + """ + Checks if a given string is a valid hex color. + + Args: + hex_color: A hex color string with an optional leading "#". Supports + 6-digit (RGB) or 8-digit (RGBA) formats. + + Returns: + True if the string is a valid 6- or 8-digit hex color, otherwise False. + + Examples: + ```pycon + >>> from supervision.annotators.utils import is_valid_hex + >>> is_valid_hex("#FF00FF") + True + >>> is_valid_hex("not-a-color") + False + + ``` + """ + return bool(re.fullmatch(r"#?[0-9A-Fa-f]{6}([0-9A-Fa-f]{2})?", hex_color.strip())) + + +def calculate_dynamic_kernel_size(x1: int, y1: int, x2: int, y2: int) -> int: + """ + Computes a blur kernel size proportional to the shorter side of a bounding box. + + Args: + x1: Left edge of the bounding box. + y1: Top edge of the bounding box. + x2: Right edge of the bounding box. + y2: Bottom edge of the bounding box. + + Returns: + Kernel size as one-third of the shorter dimension, minimum 1. + + Examples: + ```pycon + >>> calculate_dynamic_kernel_size(0, 0, 90, 60) + 20 + + ``` + """ + return max(1, min(y2 - y1, x2 - x1) // 3) + + +def calculate_dynamic_pixel_size(x1: int, y1: int, x2: int, y2: int) -> int: + """ + Computes a pixelation size proportional to the shorter side of a bounding box. + + Args: + x1: Left edge of the bounding box. + y1: Top edge of the bounding box. + x2: Right edge of the bounding box. + y2: Bottom edge of the bounding box. + + Returns: + Pixel size as one-half of the shorter dimension, minimum 1. + + Examples: + ```pycon + >>> calculate_dynamic_pixel_size(0, 0, 90, 60) + 30 + + ``` + """ + return max(1, min(y2 - y1, x2 - x1) // 2) diff --git a/.venv/lib/python3.12/site-packages/supervision/assets/__init__.py b/.venv/lib/python3.12/site-packages/supervision/assets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3ed213f58a8443824e88e1a2a9050bebee064109 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/assets/__init__.py @@ -0,0 +1,4 @@ +from supervision.assets.downloader import download_assets +from supervision.assets.list import ImageAssets, VideoAssets + +__all__ = ["ImageAssets", "VideoAssets", "download_assets"] diff --git a/.venv/lib/python3.12/site-packages/supervision/assets/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/assets/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36a02f5efb25088f52043cdbb9e88316d0e5a558 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/assets/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/assets/__pycache__/downloader.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/assets/__pycache__/downloader.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea1a6a2a47831fa964252d7bd2e28d990cb6dc6b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/assets/__pycache__/downloader.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/assets/__pycache__/list.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/assets/__pycache__/list.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..452c5f81ac302a511704162cf680b89e7d945a8d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/assets/__pycache__/list.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/assets/downloader.py b/.venv/lib/python3.12/site-packages/supervision/assets/downloader.py new file mode 100644 index 0000000000000000000000000000000000000000..bd0ab9653293097bb339a4efc5c53f907d427b2a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/assets/downloader.py @@ -0,0 +1,141 @@ +import os +from hashlib import md5 +from pathlib import Path + +from supervision.assets.list import MEDIA_ASSETS, Assets +from supervision.utils.file import _download_to_file +from supervision.utils.logger import _get_logger + +logger = _get_logger(__name__) + + +def is_md5_hash_matching(filename: str | Path, original_md5_hash: str) -> bool: + """ + Check if the MD5 hash of a file matches the original hash. + + Note: MD5 is used here for file integrity checking (detecting corruption), + not for cryptographic security purposes. + + Args: + filename: The path to the file to be checked. + original_md5_hash: The original MD5 hash to compare against. + + Returns: + True if the hashes match, False otherwise. + """ + if not os.path.exists(filename): + return False + + with open(filename, "rb") as file: + file_contents = file.read() + computed_md5_hash = md5(file_contents, usedforsecurity=False) + + return computed_md5_hash.hexdigest() == original_md5_hash + + +def _download_asset(filename: str, destination: Path) -> None: + """ + Download asset bytes to the target destination via a temporary file. + """ + _download_to_file(MEDIA_ASSETS[filename][0], destination, timeout=30.0, stream=True) + + +def _download_verified_asset( + filename: str, + original_md5_hash: str, + destination: Path, + check_target: str | Path, + retry_on_mismatch: bool = True, +) -> None: + """ + Download an asset and reject payloads whose MD5 does not match the catalog. + """ + _download_asset(filename, destination) + + if is_md5_hash_matching(check_target, original_md5_hash): + return + + logger.warning("File corrupted. Re-downloading...") + os.remove(check_target) + + if retry_on_mismatch: + _download_verified_asset( + filename=filename, + original_md5_hash=original_md5_hash, + destination=destination, + check_target=check_target, + retry_on_mismatch=False, + ) + return + + raise ValueError(f"Downloaded asset {filename!r} failed MD5 verification.") + + +def download_assets( + asset_name: Assets | str, + directory: str | Path | None = None, +) -> str: + """ + Download a specified asset if it doesn't already exist or is corrupted. + + Args: + asset_name: The name or type of the asset to be downloaded. + directory: Optional output directory. Defaults to the current working + directory for backward compatibility. + + Returns: + The downloaded asset path. When `directory` is omitted, this preserves + the historical filename-only return value. + + Example: + ```pycon + >>> from supervision.assets import download_assets, ImageAssets, VideoAssets + >>> download_assets(VideoAssets.VEHICLES) # doctest: +SKIP + 'vehicles.mp4' + + >>> download_assets(ImageAssets.PEOPLE_WALKING) # doctest: +SKIP + 'people-walking.jpg' + + ``` + """ + + filename = asset_name.filename if isinstance(asset_name, Assets) else asset_name + if directory is None: + destination = Path.cwd() / filename + check_target: str | Path = filename + return_value = filename + else: + destination_directory = Path(directory).expanduser().resolve() + destination = destination_directory / filename + check_target = str(destination) + return_value = str(destination) + + if filename in MEDIA_ASSETS: + original_md5_hash = MEDIA_ASSETS[filename][1] + if not Path(check_target).exists(): + logger.info("Downloading %s assets", filename) + _download_verified_asset( + filename=filename, + original_md5_hash=original_md5_hash, + destination=destination, + check_target=check_target, + ) + else: + if not is_md5_hash_matching(check_target, original_md5_hash): + logger.warning("File corrupted. Re-downloading...") + os.remove(check_target) + _download_verified_asset( + filename=filename, + original_md5_hash=original_md5_hash, + destination=destination, + check_target=check_target, + ) + + logger.info("%s asset download complete.", filename) + else: + valid_assets = ", ".join(filename for filename in MEDIA_ASSETS.keys()) + raise ValueError( + f"Invalid asset. It should be one of the following: {valid_assets}." + ) + + return return_value diff --git a/.venv/lib/python3.12/site-packages/supervision/assets/list.py b/.venv/lib/python3.12/site-packages/supervision/assets/list.py new file mode 100644 index 0000000000000000000000000000000000000000..9b2a2ba4814d90e1abf922e64981d7f809ad1cca --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/assets/list.py @@ -0,0 +1,84 @@ +from __future__ import annotations + +from enum import Enum + +BASE_VIDEO_URL = "https://media.roboflow.com/supervision/video-examples/" +BASE_IMAGE_URL = "https://media.roboflow.com/supervision/image-examples/" + + +class Assets(Enum): + filename: str + md5_hash: str + + def __new__(cls, filename: str, md5_hash: str) -> Assets: + obj = object.__new__(cls) + obj._value_ = filename + obj.filename = filename + obj.md5_hash = md5_hash + return obj + + @classmethod + def list(cls) -> list[str]: + return [asset.filename for asset in cls] + + +class VideoAssets(Assets): + """ + Each member of this class represents a video asset. The value associated with each + member has a filename and hash of the video. File names and links can be seen below. + + | Asset | Video Filename | Video URL | + |------------------------|----------------------------|---------------------------------------------------------------------------------------| + | `VEHICLES` | `vehicles.mp4` | [Link](https://media.roboflow.com/supervision/video-examples/vehicles.mp4) | + | `MILK_BOTTLING_PLANT` | `milk-bottling-plant.mp4` | [Link](https://media.roboflow.com/supervision/video-examples/milk-bottling-plant.mp4) | + | `VEHICLES_2` | `vehicles-2.mp4` | [Link](https://media.roboflow.com/supervision/video-examples/vehicles-2.mp4) | + | `GROCERY_STORE` | `grocery-store.mp4` | [Link](https://media.roboflow.com/supervision/video-examples/grocery-store.mp4) | + | `SUBWAY` | `subway.mp4` | [Link](https://media.roboflow.com/supervision/video-examples/subway.mp4) | + | `MARKET_SQUARE` | `market-square.mp4` | [Link](https://media.roboflow.com/supervision/video-examples/market-square.mp4) | + | `PEOPLE_WALKING` | `people-walking.mp4` | [Link](https://media.roboflow.com/supervision/video-examples/people-walking.mp4) | + | `BEACH` | `beach-1.mp4` | [Link](https://media.roboflow.com/supervision/video-examples/beach-1.mp4) | + | `BASKETBALL` | `basketball-1.mp4` | [Link](https://media.roboflow.com/supervision/video-examples/basketball-1.mp4) | + | `SKIING` | `skiing.mp4` | [Link](https://media.roboflow.com/supervision/video-examples/skiing.mp4) | + """ # noqa: E501 // docs + + VEHICLES = ("vehicles.mp4", "8155ff4e4de08cfa25f39de96483f918") + MILK_BOTTLING_PLANT = ( + "milk-bottling-plant.mp4", + "9e8fb6e883f842a38b3d34267290bdc7", + ) + VEHICLES_2 = ("vehicles-2.mp4", "830af6fba21ffbf14867a7fea595937b") + GROCERY_STORE = ("grocery-store.mp4", "48608fb4a8981f1c2469fa492adeec9c") + SUBWAY = ("subway.mp4", "453475750691fb23c56a0cffef089194") + MARKET_SQUARE = ("market-square.mp4", "859179bf4a21f80a8baabfdb2ed716dc") + PEOPLE_WALKING = ("people-walking.mp4", "0574c053c8686c3f1dc0aa3743e45cb9") + BEACH = ("beach-1.mp4", "4175d42fec4d450ed081523fd39e0cf8") + BASKETBALL = ("basketball-1.mp4", "60d94a3c7c47d16f09d342b088012ecc") + SKIING = ("skiing.mp4", "d30987cbab1bbc5934199cdd1b293119") + + +class ImageAssets(Assets): + """ + Each member of this enum represents a image asset. The value associated with each + member is the filename of the image. + + | Asset | Image Filename | Video URL | + |--------------------|------------------------|---------------------------------------------------------------------------------------| + | `PEOPLE_WALKING` | `people-walking.jpg` | [Link](https://media.roboflow.com/supervision/image-examples/people-walking.jpg) | + | `SOCCER` | `soccer.jpg` | [Link](https://media.roboflow.com/supervision/image-examples/soccer.jpg) | + + """ # noqa: E501 // docs + + PEOPLE_WALKING = ("people-walking.jpg", "e6bda00b47f2908eeae7df86ef995dcd") + SOCCER = ("soccer.jpg", "0f5a4b98abf3e3973faf9e9260a7d876") + + +MEDIA_ASSETS: dict[str, tuple[str, str]] = { + **{ + asset.filename: (f"{BASE_VIDEO_URL}{asset.filename}", asset.md5_hash) + for asset in VideoAssets + }, + **{ + asset.filename: (f"{BASE_IMAGE_URL}{asset.filename}", asset.md5_hash) + for asset in ImageAssets + }, +} diff --git a/.venv/lib/python3.12/site-packages/supervision/classification/__init__.py b/.venv/lib/python3.12/site-packages/supervision/classification/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/supervision/classification/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/classification/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..361d58fa11185d0009706e384d2deb8c45e8d943 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/classification/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/classification/__pycache__/core.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/classification/__pycache__/core.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32113ec389eb5c565006d483779a1da8d336d0c1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/classification/__pycache__/core.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/classification/core.py b/.venv/lib/python3.12/site-packages/supervision/classification/core.py new file mode 100644 index 0000000000000000000000000000000000000000..82a110f153e8c03ceec10e4664568c1eaf4a0c81 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/classification/core.py @@ -0,0 +1,216 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any + +import numpy as np +import numpy.typing as npt + +if TYPE_CHECKING: + import torch # type: ignore[import-not-found, unused-ignore] + + +def _validate_class_ids(class_id: Any, n: int) -> None: + """ + Ensure that class_id is a 1d np.ndarray with (n, ) shape. + """ + is_valid = isinstance(class_id, np.ndarray) and class_id.shape == (n,) + if not is_valid: + raise ValueError("class_id must be 1d np.ndarray with (n, ) shape") + + +def _validate_confidence(confidence: Any, n: int) -> None: + """ + Ensure that confidence is a 1d np.ndarray with (n, ) shape. + """ + if confidence is not None: + is_valid = isinstance(confidence, np.ndarray) and confidence.shape == (n,) + if not is_valid: + raise ValueError("confidence must be 1d np.ndarray with (n, ) shape") + + +@dataclass +class Classifications: + class_id: npt.NDArray[np.int_] + confidence: npt.NDArray[np.floating] | None = None + + def __post_init__(self) -> None: + """ + Validate the classification inputs. + """ + n = len(self.class_id) + + _validate_class_ids(self.class_id, n) + _validate_confidence(self.confidence, n) + + def __eq__(self, other: object) -> bool: + """ + Compare classifications by value across numpy-backed fields. + """ + if not isinstance(other, Classifications): + return NotImplemented + if not np.array_equal(self.class_id, other.class_id): + return False + if self.confidence is None or other.confidence is None: + return self.confidence is other.confidence + return bool(np.array_equal(self.confidence, other.confidence)) + + def __len__(self) -> int: + """ + Returns the number of classifications. + """ + return len(self.class_id) + + @classmethod + def from_clip(cls, clip_results: torch.Tensor) -> Classifications: + """ + Creates a Classifications instance from a + [clip](https://github.com/openai/clip) inference result. + + Args: + clip_results: The inference result from clip model. + + Returns: + A new Classifications object. + + Example: + ```python + from PIL import Image + import clip + import supervision as sv + + model, preprocess = clip.load('ViT-B/32') + + image = cv2.imread(SOURCE_IMAGE_PATH) + image = preprocess(image).unsqueeze(0) + + text = clip.tokenize(["a diagram", "a dog", "a cat"]) + output, _ = model(image, text) + classifications = sv.Classifications.from_clip(output) + ``` + """ + + confidence = clip_results.softmax(dim=-1).cpu().detach().numpy()[0] + + if len(confidence) == 0: + return cls( + class_id=np.array([], dtype=np.int_), + confidence=np.array([], dtype=np.float32), + ) + + class_ids = np.arange(len(confidence)) + return cls(class_id=class_ids, confidence=confidence) + + @classmethod + def from_ultralytics(cls, ultralytics_results: Any) -> Classifications: + """ + Creates a Classifications instance from a + [ultralytics](https://github.com/ultralytics/ultralytics) inference result. + + Args: + ultralytics_results: The inference result from ultralytics model. + + Returns: + A new Classifications object. + + Example: + ```python + from supervision import _cv2 as cv2 + from ultralytics import YOLO + import supervision as sv + + image = cv2.imread(SOURCE_IMAGE_PATH) + model = YOLO('yolov8n-cls.pt') + + output = model(image)[0] + classifications = sv.Classifications.from_ultralytics(output) + ``` + """ + confidence = ultralytics_results.probs.data.cpu().numpy() + return cls(class_id=np.arange(confidence.shape[0]), confidence=confidence) + + @classmethod + def from_timm(cls, timm_results: Any) -> Classifications: + """ + Creates a Classifications instance from a + [timm](https://huggingface.co/docs/hub/timm) inference result. + + Note: + Returned confidences are softmax-normalized probabilities, so + thresholds calibrated against raw logits may need recalibration. + + Args: + timm_results: The inference result from timm model. + + Returns: + A new Classifications object. + + Example: + ```python + from PIL import Image + import timm + from timm.data import resolve_data_config, create_transform + import supervision as sv + + model = timm.create_model( + model_name='hf-hub:nateraw/resnet50-oxford-iiit-pet', + pretrained=True + ).eval() + + config = resolve_data_config({}, model=model) + transform = create_transform(**config) + + image = Image.open(SOURCE_IMAGE_PATH).convert('RGB') + x = transform(image).unsqueeze(0) + + output = model(x) + + classifications = sv.Classifications.from_timm(output) + ``` + """ + confidence = timm_results.softmax(dim=-1).cpu().detach().numpy()[0] + + if len(confidence) == 0: + return cls( + class_id=np.array([], dtype=np.int_), + confidence=np.array([], dtype=np.float32), + ) + + class_id = np.arange(len(confidence)) + return cls(class_id=class_id, confidence=confidence) + + def get_top_k( + self, k: int + ) -> tuple[npt.NDArray[np.int_], npt.NDArray[np.floating]]: + """ + Retrieve the top k class IDs and confidences, + ordered in descending order by confidence. + + Args: + k: The number of top class IDs and confidences to retrieve. + + Returns: + A tuple containing the top k class IDs and confidences. + + Example: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> classifications = sv.Classifications( + ... class_id=np.array([0, 1, 2]), + ... confidence=np.array([0.3, 0.9, 0.5]) + ... ) + >>> classifications.get_top_k(1) + (array([1]), array([0.9])) + + ``` + """ + if self.confidence is None: + raise ValueError("top_k could not be calculated, confidence is None") + + order = np.argsort(self.confidence)[::-1] + top_k_order = order[:k] + top_k_class_id = self.class_id[top_k_order] + top_k_confidence = self.confidence[top_k_order] + + return top_k_class_id, top_k_confidence diff --git a/.venv/lib/python3.12/site-packages/supervision/config.py b/.venv/lib/python3.12/site-packages/supervision/config.py new file mode 100644 index 0000000000000000000000000000000000000000..37cdc75c4635d4acda1ae269ecdf91fc3613cda0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/config.py @@ -0,0 +1,26 @@ +CLASS_NAME_DATA_FIELD: str = "class_name" +COCO_RAW_SEGMENTATION: str = "coco_raw_segmentation" +#: Key for per-detection area metadata in ``Detections.data``. +AREA_DATA_FIELD: str = "area" +#: Key for the source image in ``Detections.metadata``. +#: +#: An RF-DETR / ``inference``-package convention rather than a field supervision +#: itself populates: model connectors from those packages attach the image the +#: predictions were produced from under this key. +#: :class:`~supervision.detection.tools.inference_slicer.InferenceSlicer` drops it +#: while merging slices (each slice carries a different tile) and restores the full +#: input image afterwards. +#: The stored value is a reference to the caller's image, not a copy — mutating +#: ``metadata[SOURCE_IMAGE_METADATA_FIELD]`` mutates the original array. +SOURCE_IMAGE_METADATA_FIELD: str = "source_image" +#: Key for oriented bounding-box corner coordinates in ``Detections.data``. +#: +#: Value layout: ``np.ndarray`` of shape ``(N, 4, 2)``, dtype ``float32``, pixel +#: coordinates ordered as ``[[x1, y1], [x2, y2], [x3, y3], [x4, y4]]`` per +#: detection where the four points are the corners of the oriented box. +#: Used by :func:`~supervision.dataset.formats.yolo.detections_to_yolo_annotations` +#: (``is_obb=True``) and +#: :func:`~supervision.dataset.formats.yolo.yolo_annotations_to_detections` +#: (``is_obb=True``). +#: Also triggers sequential mode in ``InferenceSlicer`` when present. +ORIENTED_BOX_COORDINATES: str = "xyxyxyxy" diff --git a/.venv/lib/python3.12/site-packages/supervision/dataset/__init__.py b/.venv/lib/python3.12/site-packages/supervision/dataset/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/supervision/dataset/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/dataset/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d3b596682fdca96b887ee23595d9f2e730e1a6b0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/dataset/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/dataset/__pycache__/core.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/dataset/__pycache__/core.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e48ce267670b4ae8f09e4746de13e1acc2e8f32a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/dataset/__pycache__/core.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/dataset/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/dataset/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..115d3f3b519a664e008f79dc35e33bffb0d88f97 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/dataset/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/dataset/core.py b/.venv/lib/python3.12/site-packages/supervision/dataset/core.py new file mode 100644 index 0000000000000000000000000000000000000000..d75243571610218c736f506e1c88e10e6f24d049 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/dataset/core.py @@ -0,0 +1,1341 @@ +from __future__ import annotations + +import contextlib +import os +import shutil +from abc import ABC, abstractmethod +from collections.abc import Iterator +from copy import deepcopy +from dataclasses import dataclass +from itertools import chain +from pathlib import Path +from typing import cast + +import numpy as np +import numpy.typing as npt +from tqdm.auto import tqdm + +from supervision import _cv2 as cv2 +from supervision.classification.core import Classifications +from supervision.config import CLASS_NAME_DATA_FIELD +from supervision.dataset.formats.coco import ( + load_coco_annotations, + save_coco_annotations, +) +from supervision.dataset.formats.createml import ( + load_createml_annotations, + save_createml_annotations, +) +from supervision.dataset.formats.labelme import ( + load_labelme_annotations, + save_labelme_annotations, +) +from supervision.dataset.formats.pascal_voc import ( + load_pascal_voc_annotations, + save_pascal_voc_annotations, +) +from supervision.dataset.formats.yolo import ( + load_yolo_annotations, + save_data_yaml, + save_yolo_annotations, +) +from supervision.dataset.utils import ( + build_class_index_mapping, + check_no_basename_collisions, + map_detections_class_id, + merge_class_lists, + save_dataset_images, + train_test_split, +) +from supervision.detection.core import Detections +from supervision.utils.internal import warn_deprecated +from supervision.utils.iterables import find_duplicates + +_IMAGE_FILE_EXTENSIONS = frozenset( + {".bmp", ".jpeg", ".jpg", ".png", ".tif", ".tiff", ".webp"} +) + + +class BaseDataset(ABC): + @abstractmethod + def __len__(self) -> int: + pass + + @abstractmethod + def split( + self, + split_ratio: float = 0.8, + random_state: int | None = None, + shuffle: bool = True, + ) -> tuple[BaseDataset, BaseDataset]: + pass + + +class DetectionDataset(BaseDataset): + """ + Contains information about a detection dataset. Handles lazy image loading + and annotation retrieval, dataset splitting, conversions into multiple + formats. + + Attributes: + classes: List containing dataset class names. + images: + Accepts a list of image paths. Passing a dict + (``Dict[str, np.ndarray]``) is deprecated in ``0.30.0`` and will + be removed in ``0.33.0``; use a list of paths instead. + When a list of paths is provided, images are loaded lazily on + demand, which is more memory-efficient. + annotations: Dictionary mapping + image path to annotations. The dictionary keys match + match the keys in `images` or entries in the list of + image paths. + """ + + def __init__( + self, + classes: list[str], + images: list[str] | dict[str, npt.NDArray[np.uint8]], + annotations: dict[str, Detections], + ) -> None: + self.classes = classes + + if set(images) != set(annotations): + raise ValueError( + "The keys of the images and annotations dictionaries must match." + ) + self.annotations = { + image_path: deepcopy(annotation) + for image_path, annotation in annotations.items() + } + + np_classes = np.array(self.classes) + for image_path, annotation in self.annotations.items(): + class_ids = annotation.class_id + if class_ids is None: + continue + if not np.issubdtype(class_ids.dtype, np.integer): + raise ValueError( + f"Detection annotation for image {image_path!r} contains " + f"non-integer class_id values with dtype {class_ids.dtype}." + ) + + invalid_class_ids = class_ids[ + (class_ids < 0) | (class_ids >= len(self.classes)) + ] + if len(invalid_class_ids) > 0: + valid_range = ( + "empty" + if len(self.classes) == 0 + else f"[0, {len(self.classes) - 1}]" + ) + raise ValueError( + f"Detection annotation for image {image_path!r} contains " + f"class_id {int(invalid_class_ids[0])}, outside the valid " + f"range {valid_range} for {len(self.classes)} classes." + ) + + annotation.data[CLASS_NAME_DATA_FIELD] = np_classes[class_ids] + + # Eliminate duplicates while preserving order + self.image_paths = list(dict.fromkeys(images)) + + self._images_in_memory: dict[str, npt.NDArray[np.uint8]] = {} + if isinstance(images, dict): + self._images_in_memory = images + warn_deprecated( + "Passing a `Dict[str, np.ndarray]` into `DetectionDataset` is " + "deprecated in `0.30.0` and will be removed in `0.33.0`. Use " + "a list of paths `List[str]` instead." + ) + + def _get_image(self, image_path: str) -> npt.NDArray[np.uint8]: + """Assumes that image is in dataset.""" + if self._images_in_memory: + return self._images_in_memory[image_path] + image = cv2.imread(image_path) + if image is None: + raise ValueError(f"Could not read image from path: {image_path}") + return cast(npt.NDArray[np.uint8], image) + + def __len__(self) -> int: + return len(self._images_in_memory) or len(self.image_paths) + + def __getitem__(self, i: int) -> tuple[str, npt.NDArray[np.uint8], Detections]: + """ + Returns: + The image path, image data, + and its corresponding annotation at index i. + """ + image_path = self.image_paths[i] + image = self._get_image(image_path) + annotation = self.annotations[image_path] + return image_path, image, annotation + + def __iter__(self) -> Iterator[tuple[str, npt.NDArray[np.uint8], Detections]]: + """ + Iterate over the images and annotations in the dataset. + + Yields: + Tuples containing the image path, image data, and its annotation. + """ + for i in range(len(self)): + image_path, image, annotation = self[i] + yield image_path, image, annotation + + def __eq__(self, other: object) -> bool: + if not isinstance(other, DetectionDataset): + return False + + if self.classes != other.classes: + return False + + if self.image_paths != other.image_paths: + return False + + if self._images_in_memory or other._images_in_memory: + if not np.array_equal( + list(self._images_in_memory.values()), + list(other._images_in_memory.values()), + ): + return False + + if self.annotations != other.annotations: + return False + + return True + + def split( + self, + split_ratio: float = 0.8, + random_state: int | None = None, + shuffle: bool = True, + ) -> tuple[DetectionDataset, DetectionDataset]: + """ + Splits the dataset into two parts (training and testing) + using the provided split_ratio. The input dataset is not mutated. + + Args: + split_ratio: The ratio of the training + set to the entire dataset. + random_state: The seed for the random number generator. + This is used for reproducibility. + shuffle: Whether to shuffle the data before splitting. + + Returns: + A tuple containing + the training and testing datasets. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> ds = sv.DetectionDataset( + ... classes=['dog', 'person'], + ... images={ + ... 'img1.jpg': np.zeros((100, 100, 3), dtype=np.uint8), + ... 'img2.jpg': np.zeros((100, 100, 3), dtype=np.uint8), + ... }, + ... annotations={ + ... 'img1.jpg': sv.Detections(xyxy=np.array([[10, 10, 20, 20]])), + ... 'img2.jpg': sv.Detections(xyxy=np.array([[30, 30, 40, 40]])), + ... } + ... ) + >>> train_ds, test_ds = ds.split(split_ratio=0.5, random_state=42) + >>> len(train_ds), len(test_ds) + (1, 1) + + ``` + """ + + train_paths, test_paths = train_test_split( + data=self.image_paths, + train_ratio=split_ratio, + random_state=random_state, + shuffle=shuffle, + ) + + train_annotations = {path: self.annotations[path] for path in train_paths} + test_annotations = {path: self.annotations[path] for path in test_paths} + + train_dataset = DetectionDataset( + classes=self.classes, + images=train_paths, + annotations=train_annotations, + ) + test_dataset = DetectionDataset( + classes=self.classes, + images=test_paths, + annotations=test_annotations, + ) + if self._images_in_memory: + train_dataset._images_in_memory = { + path: self._images_in_memory[path] for path in train_paths + } + test_dataset._images_in_memory = { + path: self._images_in_memory[path] for path in test_paths + } + return train_dataset, test_dataset + + @classmethod + def merge(cls, dataset_list: list[DetectionDataset]) -> DetectionDataset: + """ + Merge a list of `DetectionDataset` objects into a single + `DetectionDataset` object. + + This method takes a list of `DetectionDataset` objects and combines + their respective fields (`classes`, `images`, + `annotations`) into a single `DetectionDataset` object. + + Args: + dataset_list: A list of `DetectionDataset` + objects to merge. + + Returns: + A single `DetectionDataset` object containing + the merged data from the input list. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> ds_1 = sv.DetectionDataset( + ... classes=['dog', 'person'], + ... images={'img1.jpg': np.zeros((100, 100, 3), dtype=np.uint8)}, + ... annotations={'img1.jpg': sv.Detections.empty()} + ... ) + >>> len(ds_1) + 1 + >>> ds_1.classes + ['dog', 'person'] + >>> ds_2 = sv.DetectionDataset( + ... classes=['cat'], + ... images={'img2.jpg': np.zeros((100, 100, 3), dtype=np.uint8)}, + ... annotations={'img2.jpg': sv.Detections.empty()} + ... ) + >>> len(ds_2) + 1 + >>> ds_2.classes + ['cat'] + >>> ds_merged = sv.DetectionDataset.merge([ds_1, ds_2]) + >>> len(ds_merged) + 2 + >>> ds_merged.classes + ['cat', 'dog', 'person'] + + ``` + """ + + def is_in_memory(dataset: DetectionDataset) -> bool: + return len(dataset._images_in_memory) > 0 or len(dataset.image_paths) == 0 + + def is_lazy(dataset: DetectionDataset) -> bool: + return len(dataset._images_in_memory) == 0 + + all_in_memory = all([is_in_memory(dataset) for dataset in dataset_list]) + all_lazy = all([is_lazy(dataset) for dataset in dataset_list]) + if not all_in_memory and not all_lazy: + raise ValueError( + "Merging lazy and in-memory DetectionDatasets is not supported." + ) + + images_in_memory = {} + for dataset in dataset_list: + images_in_memory.update(dataset._images_in_memory) + + image_paths = list( + chain.from_iterable(dataset.image_paths for dataset in dataset_list) + ) + image_paths_unique = list(dict.fromkeys(image_paths)) + if len(image_paths) != len(image_paths_unique): + duplicates = find_duplicates(image_paths) + raise ValueError( + f"Image paths {duplicates} are not unique across datasets." + ) + image_paths = image_paths_unique + + classes = merge_class_lists( + class_lists=[dataset.classes for dataset in dataset_list] + ) + + annotations = {} + for dataset in dataset_list: + annotations.update(dataset.annotations) + for dataset in dataset_list: + class_index_mapping = build_class_index_mapping( + source_classes=dataset.classes, target_classes=classes + ) + for image_path in dataset.image_paths: + annotations[image_path] = map_detections_class_id( + source_to_target_mapping=class_index_mapping, + detections=annotations[image_path], + ) + + merged_dataset = cls( + classes=classes, + images=image_paths, + annotations=annotations, + ) + if all_in_memory: + merged_dataset._images_in_memory = images_in_memory + return merged_dataset + + def as_pascal_voc( + self, + images_directory_path: str | None = None, + annotations_directory_path: str | None = None, + min_image_area_percentage: float = 0.0, + max_image_area_percentage: float = 1.0, + approximation_percentage: float = 0.0, + show_progress: bool = False, + ) -> None: + """ + Exports the dataset to PASCAL VOC format. This method saves the images + and their corresponding annotations in PASCAL VOC format. Both output + layouts are preflighted before any files are written so a collision in + either target fails without partial output. + + Args: + images_directory_path: The path to the directory + where the images should be saved. + If not provided, images will not be saved. + annotations_directory_path: The path to + the directory where the annotations in PASCAL VOC format should be + saved. If not provided, annotations will not be saved. + min_image_area_percentage: The minimum percentage of + detection area relative to + the image area for a detection to be included. + Argument is used only for segmentation datasets. + max_image_area_percentage: The maximum percentage + of detection area relative to + the image area for a detection to be included. + Argument is used only for segmentation datasets. + approximation_percentage: The percentage of + polygon points to be removed from the input polygon, + in the range [0, 1). Argument is used only for segmentation datasets. + show_progress: If True, display a progress bar during saving. + + Raises: + ValueError: If two image paths share the same basename (when + images_directory_path is set) or the same stem (when + annotations_directory_path is set), which would cause one + output file to overwrite another. Rename images to ensure + unique basenames before exporting a merged dataset. + """ + if images_directory_path: + check_no_basename_collisions( + image_paths=self.image_paths, + key=lambda image_path: Path(image_path).name, + output_kind="image", + ) + if annotations_directory_path: + check_no_basename_collisions( + image_paths=self.image_paths, + key=lambda image_path: f"{Path(image_path).stem}.xml", + output_kind="Pascal VOC annotation", + ) + + if images_directory_path: + save_dataset_images( + dataset=self, + images_directory_path=images_directory_path, + show_progress=show_progress, + ) + if annotations_directory_path: + save_pascal_voc_annotations( + dataset=self, + annotations_directory_path=annotations_directory_path, + min_image_area_percentage=min_image_area_percentage, + max_image_area_percentage=max_image_area_percentage, + approximation_percentage=approximation_percentage, + show_progress=show_progress, + ) + + @classmethod + def from_pascal_voc( + cls, + images_directory_path: str, + annotations_directory_path: str, + force_masks: bool = False, + show_progress: bool = False, + ) -> DetectionDataset: + """ + Creates a Dataset instance from PASCAL VOC formatted data. + + Args: + images_directory_path: Path to the directory containing the images. + annotations_directory_path: Path to the directory + containing the PASCAL VOC XML annotations. + force_masks: If True, forces masks to + be loaded for all annotations, regardless of whether they are present. + show_progress: If True, display a progress bar during loading. + + Returns: + A DetectionDataset instance containing + the loaded images and annotations. + + Examples: + ```python + import roboflow + from roboflow import Roboflow + import supervision as sv + + roboflow.login() + + rf = Roboflow() + + project = rf.workspace(WORKSPACE_ID).project(PROJECT_ID) + dataset = project.version(PROJECT_VERSION).download("voc") + + ds = sv.DetectionDataset.from_pascal_voc( + images_directory_path=f"{dataset.location}/train/images", + annotations_directory_path=f"{dataset.location}/train/labels", + # pass show_progress=True to enable a tqdm progress bar + ) + + ds.classes + # ['dog', 'person'] + ``` + """ + + classes, image_paths, annotations = load_pascal_voc_annotations( + images_directory_path=images_directory_path, + annotations_directory_path=annotations_directory_path, + force_masks=force_masks, + show_progress=show_progress, + ) + + return DetectionDataset( + classes=classes, images=image_paths, annotations=annotations + ) + + @classmethod + def from_yolo( + cls, + images_directory_path: str, + annotations_directory_path: str, + data_yaml_path: str, + force_masks: bool = False, + is_obb: bool = False, + show_progress: bool = False, + ) -> DetectionDataset: + """ + Creates a Dataset instance from YOLO formatted data. + + Args: + images_directory_path: The path to the + directory containing the images. + annotations_directory_path: The path to the directory + containing the YOLO annotation files. + data_yaml_path: The path to the data + YAML file containing class information. + force_masks: If True, forces + masks to be loaded for all annotations, + regardless of whether they are present. + is_obb: If True, loads the annotations in OBB format. + OBB annotations are defined as `[class_id, x, y, x, y, x, y, x, y]`, + where pairs of [x, y] are box corners. + show_progress: If True, display a progress bar during loading. + + Returns: + A DetectionDataset instance + containing the loaded images and annotations. + + Examples: + ```python + import roboflow + from roboflow import Roboflow + import supervision as sv + + roboflow.login() + rf = Roboflow() + + project = rf.workspace(WORKSPACE_ID).project(PROJECT_ID) + dataset = project.version(PROJECT_VERSION).download("yolov5") + + ds = sv.DetectionDataset.from_yolo( + images_directory_path=f"{dataset.location}/train/images", + annotations_directory_path=f"{dataset.location}/train/labels", + data_yaml_path=f"{dataset.location}/data.yaml", + # pass show_progress=True to enable a tqdm progress bar + ) + + ds.classes + # ['dog', 'person'] + ``` + """ + classes, image_paths, annotations = load_yolo_annotations( + images_directory_path=images_directory_path, + annotations_directory_path=annotations_directory_path, + data_yaml_path=data_yaml_path, + force_masks=force_masks, + is_obb=is_obb, + show_progress=show_progress, + ) + return DetectionDataset( + classes=classes, images=image_paths, annotations=annotations + ) + + def as_yolo( + self, + images_directory_path: str | None = None, + annotations_directory_path: str | None = None, + data_yaml_path: str | None = None, + min_image_area_percentage: float = 0.0, + max_image_area_percentage: float = 1.0, + approximation_percentage: float = 0.0, + is_obb: bool = False, + show_progress: bool = False, + ) -> None: + """ + Exports the dataset to YOLO format. This method saves the + images and their corresponding annotations in YOLO format. + + Args: + images_directory_path: The path to the + directory where the images should be saved. + If not provided, images will not be saved. + annotations_directory_path: The path to the + directory where the annotations in + YOLO format should be saved. If not provided, + annotations will not be saved. + data_yaml_path: The path where the data.yaml + file should be saved. + If not provided, the file will not be saved. + min_image_area_percentage: The minimum percentage of + detection area relative to + the image area for a detection to be included. + Argument is used only for segmentation datasets. + max_image_area_percentage: The maximum percentage + of detection area relative to + the image area for a detection to be included. + Argument is used only for segmentation datasets. + approximation_percentage: The percentage of polygon points to + be removed from the input polygon, in the range [0, 1). + This is useful for simplifying the annotations. + Argument is used only for segmentation datasets. + is_obb: If True, exports annotations in OBB format + (`class_id x1 y1 x2 y2 x3 y3 x4 y4`) using the oriented + corners stored in `detections.data["xyxyxyxy"]`. Mirrors + `from_yolo(..., is_obb=True)`. Masks are ignored when + `is_obb=True`. + show_progress: If True, display a progress bar during saving. + + Raises: + ValueError: If two image paths share the same basename (when + images_directory_path is set) or the same annotation + file name (when annotations_directory_path is set), + which would cause one output file to overwrite another. + """ + if is_obb and ( + min_image_area_percentage != 0.0 + or max_image_area_percentage != 1.0 + or approximation_percentage != 0.0 + ): + import warnings + + warnings.warn( + "`min_image_area_percentage`, `max_image_area_percentage`, and " + "`approximation_percentage` have no effect when `is_obb=True`; " + "OBB annotations use corner coordinates directly.", + UserWarning, + stacklevel=2, + ) + # Pre-flight: validate output uniqueness before writing any file + if images_directory_path: + check_no_basename_collisions( + image_paths=self.image_paths, + key=lambda image_path: Path(image_path).name, + output_kind="image", + ) + if annotations_directory_path: + check_no_basename_collisions( + image_paths=self.image_paths, + key=lambda image_path: Path(image_path).stem + ".txt", + output_kind="YOLO annotation", + ) + + if images_directory_path is not None: + save_dataset_images( + dataset=self, + images_directory_path=images_directory_path, + show_progress=show_progress, + ) + if annotations_directory_path is not None: + save_yolo_annotations( + dataset=self, + annotations_directory_path=annotations_directory_path, + min_image_area_percentage=min_image_area_percentage, + max_image_area_percentage=max_image_area_percentage, + approximation_percentage=approximation_percentage, + show_progress=show_progress, + is_obb=is_obb, + ) + if data_yaml_path is not None: + save_data_yaml(data_yaml_path=data_yaml_path, classes=self.classes) + + @classmethod + def from_labelme( + cls, + images_directory_path: str, + annotations_directory_path: str, + force_masks: bool = False, + ) -> DetectionDataset: + """ + Creates a Dataset instance from LabelMe formatted data. + + LabelMe stores one JSON file per image, each containing a list of + ``shapes``. ``rectangle`` shapes are loaded as bounding boxes and + ``polygon`` shapes as masks (with their bounding boxes); other shape + types are skipped. Class names are inferred from the labels present in + the files. When an image file contains a ``polygon`` shape, or when + ``force_masks=True`` is set, both ``rectangle`` and ``polygon`` shapes + produce masks: rectangles via a four-corner polygon fill. + + Args: + images_directory_path: The path to the + directory containing the images. + annotations_directory_path: The path to the directory + containing the LabelMe ``.json`` annotation files. + force_masks: If True, forces masks to be loaded for all + annotations, regardless of whether polygon shapes are present. + Requires ``imageWidth`` and ``imageHeight`` in every JSON file. + + Returns: + A DetectionDataset instance containing + the loaded images and annotations. + + Raises: + ValueError: If an annotation is malformed - for example + ``imagePath`` is empty or resolves to ``..``, a shape is + missing its ``label`` or ``points``, or a mask is required but + ``imageWidth`` / ``imageHeight`` are missing or zero. + + Examples: + ```python + import supervision as sv + + ds = sv.DetectionDataset.from_labelme( + images_directory_path="", + annotations_directory_path="", + ) + + ds.classes + # ['dog', 'person'] + ``` + """ + classes, image_paths, annotations = load_labelme_annotations( + images_directory_path=images_directory_path, + annotations_directory_path=annotations_directory_path, + force_masks=force_masks, + ) + return DetectionDataset( + classes=classes, images=image_paths, annotations=annotations + ) + + def as_labelme( + self, + images_directory_path: str | None = None, + annotations_directory_path: str | None = None, + ) -> None: + """ + Exports the dataset to LabelMe format. This method saves the images and + their corresponding annotations as per-image LabelMe ``.json`` files. + Masked detections are written as ``polygon`` shapes whose vertices + approximate the mask contour, so masks are not bit-exact on round-trip. + Because the bounding box is recomputed from the quantized polygon contour + on re-import, bounding boxes for masked detections may also shift by + approximately one pixel after a save-load cycle. + + Args: + images_directory_path: The path to the directory + where the images should be saved. + If not provided, images will not be saved. + annotations_directory_path: The path to the directory where the + LabelMe ``.json`` files should be saved. + If not provided, annotations will not be saved. + + Examples: + ```python + import supervision as sv + + ds = sv.DetectionDataset(...) + + ds.as_labelme( + images_directory_path="", + annotations_directory_path="", + ) + ``` + """ + if images_directory_path is not None: + save_dataset_images( + dataset=self, images_directory_path=images_directory_path + ) + if annotations_directory_path is not None: + save_labelme_annotations( + dataset=self, + annotations_directory_path=annotations_directory_path, + ) + + @classmethod + def from_createml( + cls, + images_directory_path: str, + annotations_path: str, + show_progress: bool = False, + ) -> DetectionDataset: + """ + Creates a Dataset instance from CreateML formatted data. + + CreateML stores object-detection annotations in a single JSON file as a + list of per-image entries, with each box expressed as a pixel-space + centre point plus width and height. Class names are inferred from the + labels present in the file. + + Args: + images_directory_path: The path to the directory containing the + images. + annotations_path: The path to the CreateML json annotation file. + show_progress: If True, display a progress bar during loading. + + Returns: + A DetectionDataset instance containing the loaded images and + annotations. + + Examples: + ```python + import roboflow + from roboflow import Roboflow + import supervision as sv + + roboflow.login() + rf = Roboflow() + + project = rf.workspace(WORKSPACE_ID).project(PROJECT_ID) + dataset = project.version(PROJECT_VERSION).download("createml") + + ds = sv.DetectionDataset.from_createml( + images_directory_path=f"{dataset.location}/train", + annotations_path=f"{dataset.location}/train/_annotations.createml.json", + ) + + ds.classes + # ['dog', 'person'] + ``` + """ + classes, image_paths, annotations = load_createml_annotations( + images_directory_path=images_directory_path, + annotations_path=annotations_path, + show_progress=show_progress, + ) + return DetectionDataset( + classes=classes, images=image_paths, annotations=annotations + ) + + def as_createml( + self, + images_directory_path: str | None = None, + annotations_path: str | None = None, + show_progress: bool = False, + ) -> None: + """ + Exports the dataset to CreateML format. This method saves the + images and their corresponding annotations in CreateML format. + + Args: + images_directory_path: The path to the directory where the images + should be saved. If not provided, images will not be saved. + annotations_path: The path to the CreateML json annotation file. + If not provided, the annotations will not be saved. + show_progress: If True, display a progress bar while saving images. + + Returns: + None. Side-effects only: writes images and/or annotation file. + + Examples: + ```python + import supervision as sv + + ds = sv.DetectionDataset(classes=["dog"], images=[], annotations={}) + ds.as_createml( + images_directory_path="/tmp/images", + annotations_path="/tmp/annotations.json", + ) + ``` + """ + if images_directory_path is not None: + save_dataset_images( + dataset=self, + images_directory_path=images_directory_path, + show_progress=show_progress, + ) + if annotations_path is not None: + save_createml_annotations( + dataset=self, + annotations_path=annotations_path, + ) + + @classmethod + def from_coco( + cls, + images_directory_path: str, + annotations_path: str, + force_masks: bool = False, + show_progress: bool = False, + *, + use_iscrowd: bool = True, + ) -> DetectionDataset: + """ + Creates a Dataset instance from COCO formatted data. + + Args: + images_directory_path: The path to the + directory containing the images. + annotations_path: The path to the json annotation files. + force_masks: If True, + forces masks to be loaded for all annotations, + regardless of whether they are present. + show_progress: If True, display a progress bar during loading. + use_iscrowd: If True, includes COCO ``iscrowd`` and ``area`` + annotation fields in ``Detections.data``. + Returns: + A DetectionDataset instance containing + the loaded images and annotations. + + Examples: + ```python + import roboflow + from roboflow import Roboflow + import supervision as sv + + roboflow.login() + rf = Roboflow() + + project = rf.workspace(WORKSPACE_ID).project(PROJECT_ID) + dataset = project.version(PROJECT_VERSION).download("coco") + + ds = sv.DetectionDataset.from_coco( + images_directory_path=f"{dataset.location}/train", + annotations_path=f"{dataset.location}/train/_annotations.coco.json", + # pass show_progress=True to enable a tqdm progress bar + ) + + ds.classes + # ['dog', 'person'] + ``` + """ + classes, images, annotations = load_coco_annotations( + images_directory_path=images_directory_path, + annotations_path=annotations_path, + force_masks=force_masks, + use_iscrowd=use_iscrowd, + show_progress=show_progress, + ) + return DetectionDataset(classes=classes, images=images, annotations=annotations) + + def as_coco( + self, + images_directory_path: str | None = None, + annotations_path: str | None = None, + min_image_area_percentage: float = 0.0, + max_image_area_percentage: float = 1.0, + approximation_percentage: float = 0.0, + starting_image_id: int = 1, + starting_annotation_id: int = 1, + show_progress: bool = False, + ) -> tuple[int, int]: + """ + Exports the dataset to COCO format. This method saves the + images and their corresponding annotations in COCO format. + + !!! tip + + The format of the mask is determined automatically based on its structure: + + - If a mask contains multiple disconnected components or holes, it will be + saved using the Run-Length Encoding (RLE) format for efficient storage and + processing. + - If a mask consists of a single, contiguous region without any holes, it + will be encoded as a polygon, preserving the outline of the object. + + This automatic selection ensures that the masks are stored in the most + appropriate and space-efficient format, complying with COCO dataset + standards. + + Args: + images_directory_path: The path to the directory + where the images should be saved. + If not provided, images will not be saved. + annotations_path: The path to COCO annotation file. + min_image_area_percentage: The minimum percentage of + detection area relative to + the image area for a detection to be included. + Argument is used only for segmentation datasets. + max_image_area_percentage: The maximum percentage of + detection area relative to + the image area for a detection to be included. + Argument is used only for segmentation datasets. + approximation_percentage: The percentage of polygon points + to be removed from the input polygon, + in the range [0, 1). This is useful for simplifying the annotations. + Argument is used only for segmentation datasets. + starting_image_id: First image id to assign in the exported file. + Defaults to ``1``. Override when exporting multiple splits into + a coordinated COCO collection so ids remain unique across the + set (see example below). + starting_annotation_id: First annotation id to assign in the + exported file. Defaults to ``1``. Override for the same + multi-split reason as ``starting_image_id``. + show_progress: If True, display a progress bar during saving. + + Returns: + A ``(next_image_id, next_annotation_id)`` tuple containing the + first unused ids after this export. Feed them straight back into + ``starting_image_id`` and ``starting_annotation_id`` on the next + split so ids stay globally unique. When ``annotations_path`` is + ``None`` (images-only export) the starting ids are returned + unchanged so chaining still composes. + + Example: + ```python + # Exporting train, valid, and test splits with non-colliding ids + # so the three annotation files can later be merged into one COCO. + next_image_id, next_annotation_id = train_ds.as_coco( + images_directory_path="out/train/images", + annotations_path="out/train/annotations.json", + ) + next_image_id, next_annotation_id = valid_ds.as_coco( + images_directory_path="out/valid/images", + annotations_path="out/valid/annotations.json", + starting_image_id=next_image_id, + starting_annotation_id=next_annotation_id, + ) + _, _ = test_ds.as_coco( + images_directory_path="out/test/images", + annotations_path="out/test/annotations.json", + starting_image_id=next_image_id, + starting_annotation_id=next_annotation_id, + ) # return value not needed — no further split + ``` + """ + if images_directory_path is not None: + save_dataset_images( + dataset=self, + images_directory_path=images_directory_path, + show_progress=show_progress, + ) + if annotations_path is not None: + return save_coco_annotations( + dataset=self, + annotation_path=annotations_path, + min_image_area_percentage=min_image_area_percentage, + max_image_area_percentage=max_image_area_percentage, + approximation_percentage=approximation_percentage, + starting_image_id=starting_image_id, + starting_annotation_id=starting_annotation_id, + show_progress=show_progress, + ) + return starting_image_id, starting_annotation_id + + +@dataclass +class ClassificationDataset(BaseDataset): + """ + Contains information about a classification dataset, handles lazy image + loading, dataset splitting. + + Attributes: + classes: List containing dataset class names. + images: + List of image paths or dictionary mapping image name to image data. + annotations: Dictionary mapping + image name to annotations. + """ + + def __init__( + self, + classes: list[str], + images: list[str] | dict[str, npt.NDArray[np.uint8]], + annotations: dict[str, Classifications], + ) -> None: + self.classes = classes + + if set(images) != set(annotations): + raise ValueError( + "The keys of the images and annotations dictionaries must match." + ) + self.annotations = annotations + + # Eliminate duplicates while preserving order + self.image_paths = list(dict.fromkeys(images)) + + self._images_in_memory: dict[str, npt.NDArray[np.uint8]] = {} + if isinstance(images, dict): + self._images_in_memory = images + warn_deprecated( + "Passing a `Dict[str, np.ndarray]` into `ClassificationDataset` is " + "deprecated and will be removed in a future release. Use " + "a list of paths `List[str]` instead." + ) + + def _get_image(self, image_path: str) -> npt.NDArray[np.uint8]: + """Assumes that image is in dataset.""" + if self._images_in_memory: + return self._images_in_memory[image_path] + image = cv2.imread(image_path) + if image is None: + raise ValueError(f"Could not read image from path: {image_path}") + return cast(npt.NDArray[np.uint8], image) + + def __len__(self) -> int: + return len(self._images_in_memory) or len(self.image_paths) + + def __getitem__(self, i: int) -> tuple[str, npt.NDArray[np.uint8], Classifications]: + """ + Returns: + The image path, image data, + and its corresponding annotation at index i. + """ + image_path = self.image_paths[i] + image = self._get_image(image_path) + annotation = self.annotations[image_path] + return image_path, image, annotation + + def __iter__( + self, + ) -> Iterator[tuple[str, npt.NDArray[np.uint8], Classifications]]: + """ + Iterate over the images and annotations in the dataset. + + Yields: + Tuples containing the image path, image data, and its annotation. + """ + for i in range(len(self)): + image_path, image, annotation = self[i] + yield image_path, image, annotation + + def __eq__(self, other: object) -> bool: + if not isinstance(other, ClassificationDataset): + return False + + if self.classes != other.classes: + return False + + if self.image_paths != other.image_paths: + return False + + if self._images_in_memory or other._images_in_memory: + if not np.array_equal( + list(self._images_in_memory.values()), + list(other._images_in_memory.values()), + ): + return False + + if self.annotations != other.annotations: + return False + + return True + + def split( + self, + split_ratio: float = 0.8, + random_state: int | None = None, + shuffle: bool = True, + ) -> tuple[ClassificationDataset, ClassificationDataset]: + """ + Splits the dataset into two parts (training and testing) + using the provided split_ratio. + + Args: + split_ratio: The ratio of the training + set to the entire dataset. + random_state: The seed for the + random number generator. This is used for reproducibility. + shuffle: Whether to shuffle the data before splitting. + + Returns: + A tuple containing + the training and testing datasets. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> cd = sv.ClassificationDataset( + ... classes=['cat', 'dog'], + ... images={ + ... 'img1.jpg': np.zeros((100, 100, 3), dtype=np.uint8), + ... 'img2.jpg': np.zeros((100, 100, 3), dtype=np.uint8), + ... }, + ... annotations={ + ... 'img1.jpg': sv.Classifications(class_id=np.array([0])), + ... 'img2.jpg': sv.Classifications(class_id=np.array([1])), + ... } + ... ) + >>> train_cd, test_cd = cd.split(split_ratio=0.5, random_state=42) + >>> len(train_cd), len(test_cd) + (1, 1) + + ``` + """ + train_paths, test_paths = train_test_split( + data=self.image_paths, + train_ratio=split_ratio, + random_state=random_state, + shuffle=shuffle, + ) + + train_input: list[str] | dict[str, npt.NDArray[np.uint8]] + test_input: list[str] | dict[str, npt.NDArray[np.uint8]] + if self._images_in_memory: + train_input = {path: self._images_in_memory[path] for path in train_paths} + test_input = {path: self._images_in_memory[path] for path in test_paths} + else: + train_input = train_paths + test_input = test_paths + train_annotations = {path: self.annotations[path] for path in train_paths} + test_annotations = {path: self.annotations[path] for path in test_paths} + + train_dataset = ClassificationDataset( + classes=self.classes, + images=train_input, + annotations=train_annotations, + ) + test_dataset = ClassificationDataset( + classes=self.classes, + images=test_input, + annotations=test_annotations, + ) + + return train_dataset, test_dataset + + def as_folder_structure( + self, root_directory_path: str, show_progress: bool = False + ) -> None: + """ + Saves the dataset as a multi-class folder structure. + + Images assigned to the same class must have unique basenames + (case-insensitive). Conflicts are rejected before any files are written. + Image files are copied unchanged; images held in memory are encoded to the + format their name's extension selects. + + Args: + root_directory_path: The path to the directory + where the dataset will be saved. + show_progress: If True, display a progress bar during saving. + + Raises: + ValueError: If two images would be saved to the same output path. + """ + output_paths = {} + for image_path in self.image_paths: + annotation = self.annotations[image_path] + class_id = ( + annotation.class_id[0] + if annotation.confidence is None + else annotation.get_top_k(1)[0][0] + ) + output_paths[image_path] = os.path.join( + self.classes[class_id], Path(image_path).name + ) + + check_no_basename_collisions( + image_paths=self.image_paths, + key=lambda path: output_paths[path], + output_kind="classification image", + ) + os.makedirs(root_directory_path, exist_ok=True) + + for class_name in self.classes: + os.makedirs(os.path.join(root_directory_path, class_name), exist_ok=True) + + for image_path in tqdm( + self.image_paths, + desc="Saving classification images", + disable=not show_progress, + ): + image_save_path = os.path.join( + root_directory_path, output_paths[image_path] + ) + if image_path in self._images_in_memory: + cv2.imwrite(image_save_path, self._images_in_memory[image_path]) + continue + # Copy the file as `save_dataset_images` does: decoding and re-encoding it + # would drop alpha and bit depth and recompress lossy formats. Exporting + # into the folder the image was loaded from leaves it where it is. + with contextlib.suppress(shutil.SameFileError): + shutil.copyfile(image_path, image_save_path) + + @classmethod + def from_folder_structure( + cls, root_directory_path: str, show_progress: bool = False + ) -> ClassificationDataset: + """ + Load data from a multiclass folder structure into a ClassificationDataset. + + Args: + root_directory_path: The path to the dataset directory. Hidden + entries, root-level files, nested directories, and files whose + suffix is not a supported image extension are ignored. + show_progress: If True, display a progress bar during loading. + + Returns: + The dataset. + + Examples: + ```python + import roboflow + from roboflow import Roboflow + import supervision as sv + + roboflow.login() + rf = Roboflow() + + project = rf.workspace(WORKSPACE_ID).project(PROJECT_ID) + dataset = project.version(PROJECT_VERSION).download("folder") + + cd = sv.ClassificationDataset.from_folder_structure( + root_directory_path=f"{dataset.location}/train" + # pass show_progress=True to enable a tqdm progress bar + ) + ``` + """ + root_directory = Path(root_directory_path) + classes = sorted( + { + entry.name + for entry in root_directory.iterdir() + if entry.is_dir() and not entry.name.startswith(".") + } + ) + + image_paths = [] + annotations = {} + + for class_id, class_name in enumerate( + tqdm( + classes, + total=len(classes), + desc="Loading classification dataset", + disable=not show_progress, + ) + ): + class_directory = root_directory / class_name + + for image_path in sorted( + class_directory.iterdir(), key=lambda path: path.name + ): + if image_path.name.startswith(".") or not image_path.is_file(): + continue + if image_path.suffix.lower() not in _IMAGE_FILE_EXTENSIONS: + continue + image_paths.append(str(image_path)) + annotations[str(image_path)] = Classifications( + class_id=np.array([class_id]), + ) + + return cls( + classes=classes, + images=image_paths, + annotations=annotations, + ) diff --git a/.venv/lib/python3.12/site-packages/supervision/dataset/formats/__init__.py b/.venv/lib/python3.12/site-packages/supervision/dataset/formats/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/supervision/dataset/formats/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/dataset/formats/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..543a7e1eab50e3ebd40618986d7d75733b20702f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/dataset/formats/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/dataset/formats/__pycache__/coco.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/dataset/formats/__pycache__/coco.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8a92a857e1bac5f01abcd417a2d55df3518b085 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/dataset/formats/__pycache__/coco.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/dataset/formats/__pycache__/createml.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/dataset/formats/__pycache__/createml.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e88b0dc5072f90413076c1d443fcf552f25712bc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/dataset/formats/__pycache__/createml.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/dataset/formats/__pycache__/labelme.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/dataset/formats/__pycache__/labelme.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b5c9ae35b7801445e9b9d02c8aedd69a3285dca Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/dataset/formats/__pycache__/labelme.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/dataset/formats/__pycache__/pascal_voc.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/dataset/formats/__pycache__/pascal_voc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..000daaa5a21a75c6ef794ca2bcec2d7c8f469ce4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/dataset/formats/__pycache__/pascal_voc.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/dataset/formats/__pycache__/yolo.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/dataset/formats/__pycache__/yolo.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b987b530e5812373c553173df799d2525c92c1d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/dataset/formats/__pycache__/yolo.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/dataset/formats/coco.py b/.venv/lib/python3.12/site-packages/supervision/dataset/formats/coco.py new file mode 100644 index 0000000000000000000000000000000000000000..0b2cde5837346a5b73fd50a873b92afd5618a748 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/dataset/formats/coco.py @@ -0,0 +1,738 @@ +from __future__ import annotations + +import warnings +from datetime import datetime +from pathlib import Path +from typing import TYPE_CHECKING, Any, cast + +import numpy as np +import numpy.typing as npt +from tqdm.auto import tqdm + +from supervision.config import AREA_DATA_FIELD, COCO_RAW_SEGMENTATION +from supervision.dataset.utils import ( + _image_file_resolution_wh, + approximate_mask_with_polygons, + check_no_basename_collisions, + map_detections_class_id, +) +from supervision.detection.core import Detections +from supervision.detection.utils.converters import ( + mask_to_rle, + polygon_to_mask, + rle_to_mask, +) +from supervision.detection.utils.masks import contains_holes, contains_multiple_segments +from supervision.utils.file import read_json_file, save_json_file + +if TYPE_CHECKING: + from supervision.dataset.core import DetectionDataset + +CocoDict = dict[str, Any] + + +def coco_categories_to_classes(coco_categories: list[CocoDict]) -> list[str]: + return [ + category["name"] + for category in sorted(coco_categories, key=lambda category: category["id"]) + ] + + +def build_coco_class_index_mapping( + coco_categories: list[CocoDict], target_classes: list[str] +) -> dict[int, int]: + source_class_to_index = { + category["name"]: category["id"] for category in coco_categories + } + return { + source_class_to_index[target_class_name]: target_class_index + for target_class_index, target_class_name in enumerate(target_classes) + } + + +def classes_to_coco_categories(classes: list[str]) -> list[CocoDict]: + """Convert a list of class names to COCO ``categories`` entries. + + Category ids are emitted 1-indexed to comply with the COCO specification + and tools such as CVAT, which require ``category_id`` values to start at + ``1``. The id assigned to the class at position ``class_index`` is + ``class_index + 1``, keeping it consistent with the ``category_id`` written + by [`detections_to_coco_annotations`](#detections_to_coco_annotations). + + Args: + classes: Class names ordered by their internal (0-indexed) class id. + + Returns: + A list of COCO category dictionaries with 1-indexed ``id`` values. + + Example: + ```pycon + >>> from supervision.dataset.formats.coco import classes_to_coco_categories + >>> classes_to_coco_categories(classes=["cat", "dog"]) + [{'id': 1, 'name': 'cat', 'supercategory': 'common-objects'}, + {'id': 2, 'name': 'dog', 'supercategory': 'common-objects'}] + + ``` + """ + return [ + { + "id": class_index + 1, + "name": class_name, + "supercategory": "common-objects", + } + for class_index, class_name in enumerate(classes) + ] + + +def group_coco_annotations_by_image_id( + coco_annotations: list[CocoDict], +) -> dict[int, list[CocoDict]]: + annotations: dict[int, list[CocoDict]] = {} + for annotation in coco_annotations: + image_id = annotation["image_id"] + if image_id not in annotations: + annotations[image_id] = [] + annotations[image_id].append(annotation) + return annotations + + +def coco_annotations_to_masks( + image_annotations: list[CocoDict], resolution_wh: tuple[int, int] +) -> npt.NDArray[np.bool_]: + """Rasterise each annotation's RLE or polygon segmentation into one bool mask.""" + height, width = resolution_wh[1], resolution_wh[0] + empty_mask: npt.NDArray[np.bool_] = np.zeros((height, width), dtype=bool) + masks = [] + + for image_annotation in image_annotations: + segmentation = image_annotation.get("segmentation") + if not segmentation: + # `force_masks=True` may request masks even for bbox-only annotations. + # Keep detection count aligned by emitting an empty mask for that object. + masks.append(empty_mask.copy()) + continue + + if isinstance(segmentation, dict): + if "counts" not in segmentation: + warnings.warn( + "Skipping annotation " + f"{image_annotation.get('id', '?')}: segmentation is a dict but " + "missing 'counts' key (expected RLE format)", + stacklevel=2, + ) + masks.append(empty_mask.copy()) + continue + masks.append( + rle_to_mask(rle=segmentation["counts"], resolution_wh=resolution_wh) + ) + continue + + if not isinstance(segmentation, list): + masks.append(empty_mask.copy()) + continue + polygons = segmentation if isinstance(segmentation[0], list) else [segmentation] + + object_mask = empty_mask.copy() + for polygon in polygons: + vertices = np.reshape(np.asarray(polygon, dtype=np.float64), (-1, 2)) + if vertices.size == 0: + warnings.warn( + "Skipping empty polygon while loading COCO segmentation for " + f"annotation id={image_annotation.get('id')}.", + stacklevel=2, + ) + continue + if not np.isfinite(vertices).all(): + raise ValueError( + "COCO polygon segmentation for annotation " + f"id={image_annotation.get('id')} has a vertex that is not a " + "finite number." + ) + # COCO vertices are sub-pixel floats. Round them to the nearest pixel, as + # the YOLO, LabelMe and Pascal VOC loaders do; casting straight to int + # truncates and shifts the mask up and to the left. + polygon_array: npt.NDArray[np.int32] = np.round(vertices).astype(np.int32) + # COCO polygon segmentation can contain multiple disjoint parts. + # Merge all parts into a single per-object mask. + object_mask |= polygon_to_mask( + polygon=polygon_array, resolution_wh=resolution_wh + ).astype(bool) + + masks.append(object_mask) + + return np.asarray(masks, dtype=bool) + + +def coco_annotations_to_detections( + image_annotations: list[CocoDict], + resolution_wh: tuple[int, int], + with_masks: bool, + use_iscrowd: bool = True, +) -> Detections: + """Convert COCO annotation dicts for a single image into a `Detections` object. + + .. warning:: + The returned ``Detections.class_id`` contains **raw COCO** ``category_id`` + values, not the final 0-indexed internal class ids. Callers **must** pass + the result through :func:`map_detections_class_id` with the appropriate + ``source_to_target_mapping`` (built by + :func:`build_coco_class_index_mapping`) before the ``class_id`` values are + meaningful. Skipping the remap step yields 1-based ids in a field that the + rest of supervision treats as 0-based. + + Args: + image_annotations: List of COCO annotation dicts for one image. + resolution_wh: ``(width, height)`` of the image, used for mask decoding. + with_masks: Whether to decode segmentation fields into binary masks. + use_iscrowd: When ``True``, store ``iscrowd`` and ``area`` in + ``Detections.data``. + + Returns: + Detections with ``class_id`` set to raw COCO ``category_id`` values. + Call :func:`map_detections_class_id` on the result before use. + When ``with_masks=False``, ``detections.data[COCO_RAW_SEGMENTATION]`` is + populated as an object array (shape ``(N,)``) holding the raw polygon list or + RLE dict per annotation; consumed by :func:`detections_to_coco_annotations` + for a coordinate-preserving round-trip. + """ + if not image_annotations: + return Detections.empty() + + class_ids = [ + image_annotation["category_id"] for image_annotation in image_annotations + ] + xyxy_list = [image_annotation["bbox"] for image_annotation in image_annotations] + xyxy: npt.NDArray[np.float32] = np.asarray(xyxy_list, dtype=np.float32) + xyxy[:, 2:4] += xyxy[:, 0:2] + + data: dict[str, npt.NDArray[np.generic] | list[Any]] = {} + if use_iscrowd: + iscrowd = [ + image_annotation.get("iscrowd", 0) for image_annotation in image_annotations + ] + area = [] + for image_annotation in image_annotations: + if "area" in image_annotation: + area.append(image_annotation["area"]) + elif with_masks and _with_seg_mask(image_annotation): + area.append(np.nan) + else: + area.append(image_annotation["bbox"][2] * image_annotation["bbox"][3]) + data = dict( + iscrowd=np.asarray(iscrowd, dtype=int), area=np.asarray(area, dtype=float) + ) + + if with_masks: + mask = coco_annotations_to_masks( + image_annotations=image_annotations, resolution_wh=resolution_wh + ) + else: + mask = None + # Preserve raw polygon/RLE data so as_coco() can round-trip without + # binary-mask encoding. Stored as an object array (one entry per detection). + raw_segs: npt.NDArray[np.object_] = np.empty( + len(image_annotations), dtype=object + ) + for k, _ann in enumerate(image_annotations): + raw_segs[k] = _ann.get("segmentation", []) + data[COCO_RAW_SEGMENTATION] = raw_segs + + return Detections( + class_id=np.asarray(class_ids, dtype=int), xyxy=xyxy, mask=mask, data=data + ) + + +def detections_to_coco_annotations( + detections: Detections, + image_id: int, + annotation_id: int, + min_image_area_percentage: float = 0.0, + max_image_area_percentage: float = 1.0, + approximation_percentage: float = 0.75, +) -> tuple[list[CocoDict], int]: + """Convert `Detections` to COCO ``annotations`` entries. + + The internal 0-indexed ``Detections.class_id`` is serialized as a 1-indexed + COCO ``category_id`` (``category_id = class_id + 1``). This complies with the + COCO specification and tools such as CVAT, and stays consistent with the ids + emitted by [`classes_to_coco_categories`](#classes_to_coco_categories), so a + detection with internal ``class_id=k`` maps to ``category_id=k + 1``. + + Args: + detections: The detections to convert. ``class_id`` must not be ``None``. + image_id: COCO ``image_id`` shared by every produced annotation. + annotation_id: First annotation id to assign; incremented per detection. + min_image_area_percentage: Lower bound on detection area / image area, + used only when approximating masks with polygons. + max_image_area_percentage: Upper bound on detection area / image area, + used only when approximating masks with polygons. + approximation_percentage: Polygon-simplification ratio in ``[0, 1)``. + + Returns: + A ``(coco_annotations, next_annotation_id)`` tuple, where + ``next_annotation_id`` is one greater than the last id assigned. + + Raises: + ValueError: If any detection has ``class_id`` equal to ``None``. + + Note: + For ``iscrowd=0`` annotations, ``segmentation`` is a + ``list[list[float]]`` where each inner list encodes one polygon + part as flat ``[x1, y1, x2, y2, ...]`` coordinates. A single + object with *N* disjoint parts produces *N* inner lists. + + When ``iscrowd`` is not in ``detections.data``, masks with holes + or multiple disjoint segments are auto-encoded as RLE + (``iscrowd=1``); simple single-region masks use polygon format + (``iscrowd=0``). Supply ``data={"iscrowd": np.array([0])}`` to + force polygon output regardless of mask topology. + + Example: + ```pycon + >>> import numpy as np + >>> from supervision import Detections + >>> from supervision.dataset.formats.coco import ( + ... detections_to_coco_annotations, + ... ) + >>> detections = Detections( + ... xyxy=np.array([[0, 0, 10, 10]], dtype=np.float32), + ... class_id=np.array([0], dtype=int), + ... ) + >>> annotations, next_id = detections_to_coco_annotations( + ... detections=detections, image_id=1, annotation_id=1 + ... ) + >>> annotations[0]["category_id"] + 1 + >>> next_id + 2 + + ``` + """ + coco_annotations: list[CocoDict] = [] + for xyxy, mask, _, class_id, _, data in detections: + if class_id is None: + raise ValueError("Detections must include class_id for COCO export.") + box_width, box_height = xyxy[2] - xyxy[0], xyxy[3] - xyxy[1] + segmentation: list[list[float]] | dict[str, list[int]] = [] + if mask is not None: + mask_bool = mask + if "iscrowd" in data: + iscrowd = int(np.asarray(data["iscrowd"]).item()) + else: + iscrowd = int( + contains_holes(mask=mask_bool) + or contains_multiple_segments(mask=mask_bool) + ) + + if iscrowd: + segmentation = { + "counts": cast( + list[int], mask_to_rle(mask=mask_bool, compressed=False) + ), + "size": list(mask.shape[:2]), + } + else: + polygons = approximate_mask_with_polygons( + mask=mask_bool, + min_image_area_percentage=min_image_area_percentage, + max_image_area_percentage=max_image_area_percentage, + approximation_percentage=approximation_percentage, + ) + # Small/noisy masks can be filtered out by approximation settings. + # Guard against empty output and keep a valid COCO annotation record. + if polygons: + # Export ALL polygons so disjoint mask components are preserved. + segmentation = [list(p.flatten()) for p in polygons] + else: + warnings.warn( + "Skipping COCO polygon segmentation for annotation " + f"id={annotation_id} because mask approximation " + "returned no polygons.", + stacklevel=2, + ) + else: + iscrowd = int(np.asarray(data.get("iscrowd", 0)).item()) + # When masks were not decoded during loading, fall back to the raw + # polygon/RLE stored in data["segmentation"] for a lossless round-trip. + raw_seg = data.get(COCO_RAW_SEGMENTATION) + if raw_seg is not None and bool(raw_seg): + if isinstance(raw_seg, dict): + # RLE format — pass through unchanged + segmentation = raw_seg + elif ( + isinstance(raw_seg, list) + and raw_seg + and not isinstance(raw_seg[0], (list, tuple)) + ): + # Flat list shorthand [x1,y1,...] — wrap to list-of-lists + segmentation = [list(raw_seg)] + else: + segmentation = list(raw_seg) + + stored_area = None + if AREA_DATA_FIELD in data: + stored_area = float(np.asarray(data[AREA_DATA_FIELD]).item()) + + if stored_area is not None and np.isfinite(stored_area): + area = stored_area + elif mask is not None: + area = float(np.count_nonzero(mask)) + else: + area = float(box_width * box_height) + coco_annotation = { + "id": annotation_id, + "image_id": image_id, + "category_id": int(class_id) + 1, + "bbox": [xyxy[0], xyxy[1], box_width, box_height], + "area": area, + "segmentation": segmentation, + "iscrowd": iscrowd, + } + coco_annotations.append(coco_annotation) + annotation_id += 1 + return coco_annotations, annotation_id + + +def get_coco_class_index_mapping(annotations_path: str) -> dict[int, int]: + """ + Generates a mapping from sequential class indices to original COCO class ids. + + This function is essential when working with models that expect class ids to be + zero-indexed and sequential (0 to 79), as opposed to the original COCO + dataset where category ids are non-contiguous ranging from 1 to 90 but skipping some + ids. + + Use Cases: + - Evaluating models trained with COCO-style annotations where class ids + are sequential ranging from 0 to 79. + - Ensuring consistent class indexing across training, inference and evaluation, + when using different tools or datasets with COCO format. + - Reproducing results from models that assume sequential class ids (0 to 79). + + How it Works: + - Reads the COCO annotation file in its original format (`annotations_path`). + - Extracts and sorts all class names by their original COCO id (1 to 90). + - Builds a mapping from COCO class ids (not sequential with skipped ids) to + new class ids (sequential ranging from 0 to 79). + - Returns a dictionary mapping: `{new_class_id: original_COCO_class_id}`. + + Args: + annotations_path: Path to COCO JSON annotations file + (e.g., `instances_val2017.json`). + + Returns: + A mapping from new class id (sequential ranging from 0 to 79) + to original COCO class id (1 to 90 with skipped ids). + + Examples: + ```pycon + >>> import json + >>> import os + >>> import tempfile + >>> from supervision.dataset.formats.coco import get_coco_class_index_mapping + >>> coco_data = { + ... "categories": [ + ... {"id": 1, "name": "person"}, + ... {"id": 3, "name": "car"}, + ... ], + ... "images": [], + ... "annotations": [], + ... } + >>> annotations_path = None + >>> try: + ... with tempfile.NamedTemporaryFile( + ... mode="w", suffix=".json", delete=False + ... ) as f: + ... annotations_path = f.name + ... json.dump(coco_data, f) + ... mapping = get_coco_class_index_mapping(annotations_path) + ... print(mapping) + ... finally: + ... if annotations_path is not None: + ... os.remove(annotations_path) + {0: 1, 1: 3} + >>> os.path.exists(annotations_path) + False + + ``` + """ + coco_data = read_json_file(annotations_path) + classes = coco_categories_to_classes(coco_categories=coco_data["categories"]) + class_mapping = build_coco_class_index_mapping( + coco_categories=coco_data["categories"], target_classes=classes + ) + return {v: k for k, v in class_mapping.items()} + + +def load_coco_annotations( + images_directory_path: str, + annotations_path: str, + force_masks: bool = False, + use_iscrowd: bool = True, + show_progress: bool = False, +) -> tuple[list[str], list[str], dict[str, Detections]]: + """ + Load COCO annotations and convert them to `Detections`. + + If `force_masks` is `False`, masks are still loaded for images whose annotations + include a `segmentation` field. This keeps mask handling consistent with other + dataset loaders that infer masks from annotation content. + + Args: + images_directory_path: Path to the image directory. + annotations_path: Path to COCO JSON annotations. + force_masks: If `True`, always attempt to load masks. + use_iscrowd: If `True`, include `iscrowd` and `area` in detection data. + show_progress: If `True`, display a progress bar during loading. + + Returns: + A tuple of `(classes, image_paths, annotations)` where image paths are + canonicalized resolved paths inside ``images_directory_path``. + + Raises: + ValueError: If any annotation's ``file_name`` resolves to the images + directory itself, to a path outside the images directory (e.g. via + ``../`` traversal or an absolute path), or to a subdirectory instead + of a regular image file. + ValueError: If two image entries resolve to the same canonical path. + + Note: + Each annotation's ``file_name`` is validated against + ``images_directory_path`` before loading. Annotations that reference + paths outside the directory are rejected to prevent path-traversal + attacks when loading user-supplied annotation files. Symlinked images + pointing outside the resolved images directory are also rejected. + """ + coco_data = read_json_file(file_path=annotations_path) + classes = coco_categories_to_classes(coco_categories=coco_data["categories"]) + + class_index_mapping = build_coco_class_index_mapping( + coco_categories=coco_data["categories"], target_classes=classes + ) + + coco_images = coco_data["images"] + coco_annotations_groups = group_coco_annotations_by_image_id( + coco_annotations=coco_data["annotations"] + ) + + images = [] + annotations = {} + images_directory_resolved = Path(images_directory_path).resolve() + + for coco_image in tqdm( + coco_images, + total=len(coco_images), + desc="Loading COCO annotations", + disable=not show_progress, + ): + image_name, image_width, image_height = ( + coco_image["file_name"], + coco_image["width"], + coco_image["height"], + ) + image_annotations = coco_annotations_groups.get(coco_image["id"], []) + image_path = str(Path(images_directory_path) / Path(image_name)) + try: + resolved_image_path = Path(image_path).resolve() + except (OSError, ValueError) as exc: + raise ValueError( + f"COCO annotation refers to image {image_name!r}, which " + f"produces an invalid path: {exc}" + ) from exc + if resolved_image_path == images_directory_resolved: + raise ValueError( + f"COCO annotation refers to image {image_name!r}, which " + f"resolves to the images directory itself " + f"({images_directory_resolved}). Expected a path to an " + "image file." + ) + if images_directory_resolved not in resolved_image_path.parents: + raise ValueError( + f"COCO annotation refers to image {image_name!r}, which " + f"resolves to {resolved_image_path} — outside the images " + f"directory {images_directory_resolved}." + ) + if resolved_image_path.is_dir(): + raise ValueError( + f"COCO annotation refers to image {image_name!r}, which " + f"resolves to directory {resolved_image_path}. Expected a " + "path to an image file." + ) + image_path = str(resolved_image_path) + if image_path in annotations: + raise ValueError( + f"COCO annotation file contains duplicate entries for image " + f"{image_name!r}. Each image must appear at most once." + ) + + with_masks = force_masks or any( + _with_seg_mask(annotation) for annotation in image_annotations + ) + annotation = coco_annotations_to_detections( + image_annotations=image_annotations, + resolution_wh=(image_width, image_height), + with_masks=with_masks, + use_iscrowd=use_iscrowd, + ) + + annotation = map_detections_class_id( + source_to_target_mapping=class_index_mapping, + detections=annotation, + ) + + images.append(image_path) + annotations[image_path] = annotation + + return classes, images, annotations + + +def _with_seg_mask(annotation: dict[str, Any]) -> bool: + return bool(annotation.get("segmentation")) + + +def _image_resolution_hw(dataset: DetectionDataset, image_path: str) -> tuple[int, int]: + """Return ``(height, width)`` for ``image_path`` without decoding pixels. + + Uses the in-memory array when the dataset holds one; otherwise reads the size from + the file header, following its EXIF orientation the way loading the image does — the + same optimization the YOLO loader uses (#1636). + """ + if dataset._images_in_memory: + image_height, image_width = dataset._images_in_memory[image_path].shape[:2] + return image_height, image_width + image_width, image_height = _image_file_resolution_wh(image_path) + return image_height, image_width + + +def save_coco_annotations( + dataset: DetectionDataset, + annotation_path: str, + min_image_area_percentage: float = 0.0, + max_image_area_percentage: float = 1.0, + approximation_percentage: float = 0.0, + starting_image_id: int = 1, + starting_annotation_id: int = 1, + show_progress: bool = False, +) -> tuple[int, int]: + """Save a DetectionDataset to a COCO-format ``annotations.json`` file. + + Args: + dataset: The DetectionDataset to write. + annotation_path: Output path for the COCO ``annotations.json``. + min_image_area_percentage: Lower bound on detection area / image area; + used only for segmentation datasets. + max_image_area_percentage: Upper bound on detection area / image area; + used only for segmentation datasets. + approximation_percentage: Polygon-simplification ratio in ``[0, 1)``; + used only for segmentation datasets. + starting_image_id: First image id to assign in the exported file. + Defaults to ``1``. Override when exporting multiple splits into + a coordinated COCO collection so ids remain unique across the set. + starting_annotation_id: First annotation id to assign in the exported + file. Defaults to ``1``. Override for the same multi-split reason + as ``starting_image_id``. + show_progress: If ``True``, display a progress bar during saving. + + Returns: + A ``(next_image_id, next_annotation_id)`` tuple. The returned values + are one greater than the highest ids written, so they can be fed + directly back into ``starting_image_id`` and ``starting_annotation_id`` + when exporting another split into a coordinated COCO collection + (see ``DetectionDataset.as_coco`` for the chaining pattern). When the + dataset is empty the starting ids are returned unchanged. + + .. note:: + This function ensures globally unique integer ``id`` values across + splits. It rejects duplicate image basenames before writing because + ``file_name`` is set to the bare image basename, so two input paths + that differ only by directory would otherwise collapse to the same + COCO image record. + + Raises: + ValueError: If two image paths share the same basename and would map to + the same COCO ``file_name``. + + Example: + ```python + import supervision as sv + from supervision.dataset.formats.coco import save_coco_annotations + + ds = sv.DetectionDataset.from_yolo( + images_directory_path="train/images", + annotations_directory_path="train/labels", + data_yaml_path="data.yaml", + ) + next_img_id, next_ann_id = save_coco_annotations( + dataset=ds, annotation_path="out/train/annotations.json" + ) + # next_img_id and next_ann_id are the first unused ids — pass them + # to the next split to keep ids globally unique across files. + ``` + """ + if starting_image_id < 1 or starting_annotation_id < 1: + raise ValueError( + "starting_image_id and starting_annotation_id must be >= 1 " + "(COCO spec requires 1-indexed ids); " + f"got {starting_image_id=}, {starting_annotation_id=}" + ) + check_no_basename_collisions( + image_paths=dataset.image_paths, + key=lambda image_path: Path(image_path).name, + output_kind="COCO image", + ) + Path(annotation_path).parent.mkdir(parents=True, exist_ok=True) + licenses = [ + { + "id": 1, + "url": "https://creativecommons.org/licenses/by/4.0/", + "name": "CC BY 4.0", + } + ] + + coco_annotations = [] + coco_images = [] + coco_categories = classes_to_coco_categories(classes=dataset.classes) + + image_id, annotation_id = starting_image_id, starting_annotation_id + for image_path in tqdm( + dataset.image_paths, + desc="Saving COCO annotations", + disable=not show_progress, + ): + annotation = dataset.annotations[image_path] + # Only the image size is needed here, so read it from the file header + # (or the in-memory array) instead of iterating the dataset, which + # would fully decode every image just to inspect its shape. + image_height, image_width = _image_resolution_hw(dataset, image_path) + image_name = f"{Path(image_path).stem}{Path(image_path).suffix}" + coco_image = { + "id": image_id, + "license": 1, + "file_name": image_name, + "height": image_height, + "width": image_width, + "date_captured": datetime.now().strftime("%m/%d/%Y,%H:%M:%S"), + } + + coco_images.append(coco_image) + coco_annotation, annotation_id = detections_to_coco_annotations( + detections=annotation, + image_id=image_id, + annotation_id=annotation_id, + min_image_area_percentage=min_image_area_percentage, + max_image_area_percentage=max_image_area_percentage, + approximation_percentage=approximation_percentage, + ) + + coco_annotations.extend(coco_annotation) + image_id += 1 + + annotation_dict = { + "info": {}, + "licenses": licenses, + "categories": coco_categories, + "images": coco_images, + "annotations": coco_annotations, + } + save_json_file(annotation_dict, file_path=annotation_path) + return image_id, annotation_id diff --git a/.venv/lib/python3.12/site-packages/supervision/dataset/formats/createml.py b/.venv/lib/python3.12/site-packages/supervision/dataset/formats/createml.py new file mode 100644 index 0000000000000000000000000000000000000000..4bcfac2f98b0b4e9f43e585921beb4d4ffeaec87 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/dataset/formats/createml.py @@ -0,0 +1,334 @@ +from __future__ import annotations + +from pathlib import Path +from typing import TYPE_CHECKING, Any, cast + +import numpy as np +from tqdm.auto import tqdm + +from supervision.dataset.utils import check_no_basename_collisions +from supervision.detection.core import Detections +from supervision.utils.file import read_json_file, save_json_file + +if TYPE_CHECKING: + from supervision.dataset.core import DetectionDataset + +CreateMLDict = dict[str, Any] + + +def _resolve_image_path(images_directory_path: str, image_name: str) -> str: + """Resolve and validate an image path against the images directory. + + Rejects annotations whose ``image`` field escapes ``images_directory_path`` + (via ``..`` traversal, an absolute path, or a symlink pointing outside), + mirroring the protection used by the COCO loader. Returns the canonical + resolved path so aliases collapse to a single dataset entry. + """ + images_directory_resolved = Path(images_directory_path).resolve() + image_path = Path(images_directory_path) / Path(image_name) + try: + resolved_image_path = image_path.resolve() + except (OSError, ValueError) as exc: + raise ValueError( + f"CreateML annotation refers to image {image_name!r}, which " + f"produces an invalid path: {exc}" + ) from exc + if resolved_image_path == images_directory_resolved: + raise ValueError( + f"CreateML annotation refers to image {image_name!r}, which " + f"resolves to the images directory itself " + f"({images_directory_resolved}). Expected a path to an image file." + ) + if images_directory_resolved not in resolved_image_path.parents: + raise ValueError( + f"CreateML annotation refers to image {image_name!r}, which " + f"resolves to {resolved_image_path} — outside the images " + f"directory {images_directory_resolved}." + ) + if resolved_image_path.is_dir(): + raise ValueError( + f"CreateML annotation refers to image {image_name!r}, which " + f"resolves to directory {resolved_image_path}. Expected a path " + "to an image file." + ) + return str(resolved_image_path) + + +def createml_annotations_to_detections( + image_annotations: list[CreateMLDict], class_to_index: dict[str, int] +) -> Detections: + """Convert a single image's CreateML annotations into ``Detections``. + + CreateML stores each box as a pixel-space centre point plus width/height + (``{"x", "y", "width", "height"}``); they are converted to ``xyxy`` corners. + + Args: + image_annotations: List of annotation dicts for one image, each containing + a ``"label"`` key and a ``"coordinates"`` dict with ``"x"``, ``"y"``, + ``"width"``, and ``"height"`` keys. + class_to_index: Mapping from class name to zero-based integer id. + + Returns: + A ``Detections`` instance with ``xyxy`` boxes and ``class_id`` set. + Returns ``Detections.empty()`` when ``image_annotations`` is empty. + + Raises: + ValueError: If an annotation is missing required keys (``"coordinates"``, + ``"label"``, or any coordinate sub-key), or if a coordinate value + cannot be converted to float. + + Example: + ```pycon + >>> from supervision.dataset.formats.createml import ( + ... createml_annotations_to_detections, + ... ) + >>> annotations = [ + ... { + ... "label": "dog", + ... "coordinates": {"x": 50, "y": 50, "width": 20, "height": 20}, + ... } + ... ] + >>> detections = createml_annotations_to_detections(annotations, {"dog": 0}) + >>> detections.xyxy + array([[40., 40., 60., 60.]], dtype=float32) + >>> detections.class_id + array([0]) + + ``` + """ + if not image_annotations: + return Detections.empty() + + xyxy = [] + class_ids = [] + for annotation in image_annotations: + try: + coordinates = annotation["coordinates"] + x_center = float(coordinates["x"]) + y_center = float(coordinates["y"]) + width = float(coordinates["width"]) + height = float(coordinates["height"]) + label = annotation["label"] + except (KeyError, TypeError) as exc: + raise ValueError( + f"Malformed CreateML annotation entry {annotation!r}: {exc}" + ) from exc + xyxy.append( + [ + x_center - width / 2, + y_center - height / 2, + x_center + width / 2, + y_center + height / 2, + ] + ) + class_ids.append(class_to_index[label]) + + return Detections( + xyxy=np.array(xyxy, dtype=np.float32), + class_id=np.array(class_ids, dtype=int), + ) + + +def load_createml_annotations( + images_directory_path: str, + annotations_path: str, + show_progress: bool = False, +) -> tuple[list[str], list[str], dict[str, Detections]]: + """Load CreateML object-detection annotations and convert them to ``Detections``. + + CreateML uses a single JSON file containing a list of per-image entries, each + holding axis-aligned bounding boxes. Class names are inferred from the labels + present in the file and assigned stable, sorted, zero-based ids. Because the + format has no explicit category list, a class with no boxes anywhere in the + file will not appear in the returned ``classes``. + + Args: + images_directory_path: Path to the directory containing the images. + annotations_path: Path to the CreateML JSON annotation file. + show_progress: If ``True``, display a tqdm progress bar while loading + annotations. + + Returns: + A tuple of three elements: + + - ``classes`` (``list[str]``): globally sorted class names inferred from + all labels present in the file. + - ``image_paths`` (``list[str]``): canonical resolved path for every + entry in the JSON, in file order. + - ``annotations`` (``dict[str, Detections]``): mapping from canonical + resolved image path to its ``Detections``. + + Raises: + ValueError: If the JSON root is not a list. + ValueError: If an entry is missing the required ``"image"`` key. + ValueError: If an annotation is missing required coordinate or label keys. + ValueError: If two entries resolve to the same image path. + ValueError: If an annotation's ``image`` field resolves to the images + directory itself or to a path outside it (e.g. via ``..`` traversal + or an absolute path). + """ + createml_data = cast( + "list[CreateMLDict]", read_json_file(file_path=annotations_path) + ) + if not isinstance(createml_data, list): + raise ValueError( + f"CreateML annotation file must contain a JSON list at the root, " + f"got {type(createml_data).__name__}." + ) + + try: + classes = sorted( + { + annotation["label"] + for entry in createml_data + for annotation in (entry.get("annotations") or []) + } + ) + except (KeyError, TypeError) as exc: + raise ValueError( + f"Malformed CreateML annotation entry " + f"(missing or non-string 'label'): {exc}" + ) from exc + class_to_index = {class_name: index for index, class_name in enumerate(classes)} + + image_paths: list[str] = [] + annotations: dict[str, Detections] = {} + for entry in tqdm( + createml_data, + desc="Loading CreateML annotations", + disable=not show_progress, + ): + image_name = entry.get("image") + if image_name is None: + raise ValueError( + f"CreateML annotation entry is missing the required 'image' key: " + f"{entry!r}" + ) + image_path = _resolve_image_path( + images_directory_path=images_directory_path, image_name=image_name + ) + if image_path in annotations: + raise ValueError( + f"CreateML annotation file contains duplicate entries for image " + f"{image_name!r}. Each image must appear at most once." + ) + annotations[image_path] = createml_annotations_to_detections( + image_annotations=entry.get("annotations") or [], + class_to_index=class_to_index, + ) + image_paths.append(image_path) + + return classes, image_paths, annotations + + +def detections_to_createml_annotations( + detections: Detections, classes: list[str] +) -> list[CreateMLDict]: + """Convert ``Detections`` into a list of CreateML annotation dicts. + + Each bounding box is stored as a pixel-space centre point plus width and + height, which is the CreateML object-detection convention. + + Args: + detections: The detections to convert. ``class_id`` must not be ``None``. + classes: Ordered list of class names; ``detections.class_id`` values are + used as indices into this list. + + Returns: + A list of dicts, each with a ``"label"`` key (class name) and a + ``"coordinates"`` dict containing ``"x"``, ``"y"``, ``"width"``, and + ``"height"`` in pixel space. + + Raises: + ValueError: If ``detections.class_id`` is ``None``. + + Example: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> from supervision.dataset.formats.createml import ( + ... detections_to_createml_annotations, + ... ) + >>> detections = sv.Detections( + ... xyxy=np.array([[40, 40, 60, 60]], dtype=np.float32), + ... class_id=np.array([0], dtype=int), + ... ) + >>> detections_to_createml_annotations(detections, classes=["dog"]) + [{'label': 'dog', 'coordinates': + {'x': 50.0, 'y': 50.0, 'width': 20.0, 'height': 20.0}}] + + ``` + """ + class_ids = detections.class_id + if class_ids is None: + raise ValueError( + "class_id is required for CreateML export, but the provided " + "Detections has class_id=None." + ) + annotations: list[CreateMLDict] = [] + for xyxy, class_id in zip(detections.xyxy, class_ids): + x_min, y_min, x_max, y_max = (float(value) for value in xyxy) + annotations.append( + { + "label": classes[int(class_id)], + "coordinates": { + "x": (x_min + x_max) / 2, + "y": (y_min + y_max) / 2, + "width": x_max - x_min, + "height": y_max - y_min, + }, + } + ) + return annotations + + +def save_createml_annotations( + dataset: DetectionDataset, + annotations_path: str, +) -> None: + """Export a ``DetectionDataset`` to a CreateML object-detection JSON file. + + Only the filename component of each image path is stored in the JSON (e.g. + ``"img.jpg"`` rather than ``"/data/train/img.jpg"``). This matches CreateML + convention and means the loader reconstructs paths relative to + ``images_directory_path``. As a consequence, two images with the same + basename from different directories would collapse to the same ``"image"`` + key, so the exporter rejects that case before writing. + + Args: + dataset: The ``DetectionDataset`` to write. + annotations_path: Output path for the CreateML JSON file. Parent + directories are created if they do not already exist. + + Raises: + ValueError: If two image paths share the same basename and would map to + the same CreateML ``image`` entry. + + Example: + ```python + import supervision as sv + from supervision.dataset.formats.createml import save_createml_annotations + + dataset = sv.DetectionDataset(classes=["dog"], images=[], annotations={}) + save_createml_annotations(dataset, "/tmp/annotations.json") + ``` + """ + check_no_basename_collisions( + image_paths=dataset.image_paths, + key=lambda image_path: Path(image_path).name, + output_kind="CreateML image", + ) + Path(annotations_path).parent.mkdir(parents=True, exist_ok=True) + createml_data: list[CreateMLDict] = [ + { + "image": Path(image_path).name, + "annotations": detections_to_createml_annotations( + detections=dataset.annotations[image_path], classes=dataset.classes + ), + } + for image_path in dataset.image_paths + ] + save_json_file( + data=createml_data, # type: ignore[arg-type] # save_json_file accepts list at runtime + file_path=annotations_path, + ) diff --git a/.venv/lib/python3.12/site-packages/supervision/dataset/formats/labelme.py b/.venv/lib/python3.12/site-packages/supervision/dataset/formats/labelme.py new file mode 100644 index 0000000000000000000000000000000000000000..d5c033d186c16d986697cd6ff550d0840a011270 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/dataset/formats/labelme.py @@ -0,0 +1,408 @@ +from __future__ import annotations + +import warnings +from pathlib import Path, PureWindowsPath +from typing import TYPE_CHECKING, Any + +import numpy as np +import numpy.typing as npt + +from supervision.dataset.utils import check_no_basename_collisions +from supervision.detection.core import Detections +from supervision.detection.utils.converters import ( + mask_to_polygons, + polygon_to_mask, + polygon_to_xyxy, +) +from supervision.utils.file import ( + list_files_with_extensions, + read_json_file, + save_json_file, +) + +if TYPE_CHECKING: + from supervision.dataset.core import DetectionDataset + +LabelMeDict = dict[str, Any] +# Written to every exported JSON; never read back on import. +_LABELME_EXPORT_VERSION = "5.5.0" +SUPPORTED_SHAPE_TYPES = ("rectangle", "polygon") + +__all__ = [ + "detections_to_labelme_shapes", + "labelme_shapes_to_detections", + "load_labelme_annotations", + "save_labelme_annotations", +] + + +def _rectangle_to_xyxy(points: npt.NDArray[np.float32]) -> npt.NDArray[np.float32]: + x_coordinates = points[:, 0] + y_coordinates = points[:, 1] + return np.array( + [ + float(x_coordinates.min()), + float(y_coordinates.min()), + float(x_coordinates.max()), + float(y_coordinates.max()), + ], + dtype=np.float32, + ) + + +def _xyxy_to_polygon(xyxy: npt.NDArray[np.float32]) -> npt.NDArray[np.float32]: + x_min, y_min, x_max, y_max = (float(value) for value in xyxy) + return np.array( + [[x_min, y_min], [x_max, y_min], [x_max, y_max], [x_min, y_max]], + dtype=np.float32, + ) + + +def labelme_shapes_to_detections( + shapes: list[LabelMeDict], + class_to_index: dict[str, int], + resolution_wh: tuple[int, int], + with_masks: bool, +) -> Detections: + """Convert a single image's LabelMe shapes into ``Detections``. + + Only ``rectangle`` and ``polygon`` shapes are imported; other shape types + (``circle``, ``line``, ``point``, ``linestrip``) are skipped with a warning. + When ``with_masks`` is ``True``, both ``rectangle`` and ``polygon`` shapes + produce masks: rectangles via a four-corner polygon fill. + + Args: + shapes: List of LabelMe shape dicts for one image. + class_to_index: Mapping from class name to integer class ID. + resolution_wh: Image ``(width, height)`` used to rasterise masks. + with_masks: If ``True``, produce a binary mask for every detection. + + Returns: + A :class:`Detections` instance with ``xyxy``, ``class_id``, and + optionally ``mask`` populated. + + Raises: + ValueError: If a shape is missing its ``label`` or ``points`` field, + if a ``polygon`` has fewer than 3 points, or a ``rectangle`` has + fewer than 2 points. + + Warns: + UserWarning: When unsupported shape types are encountered and skipped. + """ + xyxy_list: list[npt.NDArray[np.float32]] = [] + class_ids: list[int] = [] + polygons: list[npt.NDArray[np.float32]] = [] + skipped_types: set[str] = set() + + for shape in shapes: + shape_type = shape.get("shape_type") + if shape_type not in SUPPORTED_SHAPE_TYPES: + skipped_types.add(str(shape_type)) + continue + label = shape.get("label") + points_raw = shape.get("points") + if label is None or points_raw is None: + missing = "label" if label is None else "points" + raise ValueError( + f"LabelMe shape of type {shape_type!r} is missing the " + f"required {missing!r} field." + ) + points = np.array(points_raw, dtype=np.float32) + if points.ndim != 2 or points.shape[1] != 2: + raise ValueError( + f"LabelMe shape of type {shape_type!r} (label={label!r}) has " + f"malformed points: expected an (N, 2) array, got shape " + f"{points.shape}." + ) + if shape_type == "rectangle": + if len(points) < 2: + raise ValueError( + f"LabelMe rectangle shape (label={label!r}) has " + f"{len(points)} point(s); expected at least 2." + ) + xyxy = _rectangle_to_xyxy(points) + polygon = _xyxy_to_polygon(xyxy) + else: + if len(points) < 3: + raise ValueError( + f"LabelMe polygon shape (label={label!r}) has " + f"{len(points)} point(s); expected at least 3." + ) + xyxy = polygon_to_xyxy(polygon=points).astype(np.float32) + polygon = points + xyxy_list.append(xyxy) + class_ids.append(class_to_index[label]) + if with_masks: + polygons.append(polygon) + + if skipped_types: + warnings.warn( + f"Skipped unsupported LabelMe shape type(s) {sorted(skipped_types)}; " + f"only {list(SUPPORTED_SHAPE_TYPES)} are imported.", + UserWarning, + stacklevel=2, + ) + + if not xyxy_list: + return Detections.empty() + + xyxy = np.array(xyxy_list, dtype=np.float32) + class_id = np.array(class_ids, dtype=int) + if not with_masks: + return Detections(xyxy=xyxy, class_id=class_id) + + mask = np.array( + [ + polygon_to_mask( + polygon=np.round(polygon).astype(np.int32), + resolution_wh=resolution_wh, + ) + for polygon in polygons + ], + dtype=bool, + ) + return Detections(xyxy=xyxy, class_id=class_id, mask=mask) + + +def load_labelme_annotations( + images_directory_path: str, + annotations_directory_path: str, + force_masks: bool = False, +) -> tuple[list[str], list[str], dict[str, Detections]]: + """Load LabelMe annotations and convert them to ``Detections``. + + LabelMe stores one JSON file per image, each containing a list of ``shapes``. + ``rectangle`` shapes become bounding boxes; ``polygon`` shapes become masks + (and their bounding boxes); other shape types are skipped with a warning. + When any polygon is present in a file or when ``force_masks`` is ``True``, + both ``rectangle`` and ``polygon`` shapes produce masks: rectangles via a + four-corner polygon fill. Class names are inferred from the labels present + across all files and assigned sorted, zero-based ids. + + Each image is located by the basename of the JSON's ``imagePath`` joined to + ``images_directory_path``; the directory portion of ``imagePath`` (which + LabelMe stores relative to the JSON file) is ignored, so annotation-supplied + path traversal cannot escape ``images_directory_path``. + + Args: + images_directory_path: Path to the directory containing the images. + annotations_directory_path: Path to the directory containing the LabelMe + ``.json`` files. + force_masks: If ``True``, load masks for every image regardless of + whether it contains polygon shapes. + + Returns: + A tuple of ``(classes, image_paths, annotations)``. + + Raises: + ValueError: If an annotation's ``imagePath`` is missing, empty, or + resolves to ``..`` or ``.``; if two annotation files reference the + same image basename; or if a polygon mask is requested for a file + missing ``imageWidth`` / ``imageHeight``. + + Examples: + ```python + from supervision.dataset.formats.labelme import load_labelme_annotations + + classes, image_paths, annotations = load_labelme_annotations( + images_directory_path="", + annotations_directory_path="", + ) + + classes + # ['dog', 'person'] + ``` + """ + annotation_paths = sorted( + str(path) + for path in list_files_with_extensions( + directory=annotations_directory_path, extensions=["json"] + ) + ) + + # Two-pass design (collect all class labels first, then assign IDs) requires + # materialising all annotation dicts upfront. + entries: list[LabelMeDict] = [ + read_json_file(file_path=annotation_path) + for annotation_path in annotation_paths + ] + + classes = sorted( + { + shape.get("label") + for entry in entries + for shape in entry.get("shapes", []) + if shape.get("shape_type") in SUPPORTED_SHAPE_TYPES + } + - {None} + ) + class_to_index = {class_name: index for index, class_name in enumerate(classes)} + + image_paths: list[str] = [] + annotations: dict[str, Detections] = {} + for entry in entries: + shapes = entry.get("shapes", []) + raw_image_path = entry.get("imagePath") + if not raw_image_path: + raise ValueError( + "A LabelMe annotation file is missing the required " + "'imagePath' field or it is empty." + ) + # ponytail: basename-only, no symlink resolution — images_directory_path + # is trusted; annotation-driven traversal is neutralised by .name. + # See createml._resolve_image_path for the full .resolve()+parents pattern. + # LabelMe writes imagePath with the separator of the OS that saved the file, + # so files saved on Windows hold backslashes. PureWindowsPath splits on both + # separators on every OS, as LabelMe does when it reads its own files. + image_name = PureWindowsPath(raw_image_path).name + if not image_name or image_name in ("..", "."): + raise ValueError( + f"LabelMe annotation has an invalid 'imagePath' {raw_image_path!r}." + ) + image_path = str(Path(images_directory_path) / image_name) + if image_path in annotations: + raise ValueError( + f"Duplicate image basename {image_name!r} resolved from multiple " + "annotation files. All annotation files must reference unique " + "image basenames." + ) + with_masks = force_masks or any( + shape.get("shape_type") == "polygon" for shape in shapes + ) + if with_masks and not (entry.get("imageWidth") and entry.get("imageHeight")): + raise ValueError( + f"LabelMe annotation for {image_name!r} requires " + "'imageWidth' and 'imageHeight' to build masks, but they are " + "missing or zero." + ) + resolution_wh = ( + int(entry.get("imageWidth", 0)), + int(entry.get("imageHeight", 0)), + ) + annotations[image_path] = labelme_shapes_to_detections( + shapes=shapes, + class_to_index=class_to_index, + resolution_wh=resolution_wh, + with_masks=with_masks, + ) + image_paths.append(image_path) + + return classes, image_paths, annotations + + +def _build_shape(label: str, points: list[list[float]], shape_type: str) -> LabelMeDict: + return { + "label": label, + "points": points, + "group_id": None, + "description": "", + "shape_type": shape_type, + "flags": {}, + } + + +def detections_to_labelme_shapes( + detections: Detections, classes: list[str] +) -> list[LabelMeDict]: + """Convert ``Detections`` into a list of LabelMe shape dicts. + + Masked detections are exported as ``polygon`` shapes (one per connected + component); box-only detections — and masked detections whose mask yields no + polygon contour (e.g. an empty or sub-pixel mask) — are exported as + ``rectangle`` shapes, so no detection is silently dropped. + + Args: + detections: The detections to export. + classes: List of class names indexed by ``class_id``. + + Returns: + A list of LabelMe shape dicts ready to embed in a ``.json`` annotation. + + Raises: + ValueError: If ``detections.class_id`` is ``None`` or if any + ``class_id`` value is out of range for ``classes``. + """ + class_ids = detections.class_id + if class_ids is None: + raise ValueError( + "class_id is required for LabelMe export, but the provided " + "Detections has class_id=None." + ) + masks = detections.mask + shapes: list[LabelMeDict] = [] + for index in range(len(detections)): + class_index = int(class_ids[index]) + if class_index < 0 or class_index >= len(classes): + raise ValueError( + f"class_id {class_index} at detection index {index} is out of " + f"range for classes list of length {len(classes)}." + ) + label = classes[class_index] + if masks is not None: + mask_arr = np.asarray(masks[index], dtype=np.bool_) + polygons = mask_to_polygons(mask_arr) + else: + polygons = [] + if polygons: + for polygon in polygons: + points = [[float(x), float(y)] for x, y in polygon] + shapes.append(_build_shape(label, points, "polygon")) + else: + x_min, y_min, x_max, y_max = ( + float(value) for value in detections.xyxy[index] + ) + points = [[x_min, y_min], [x_max, y_max]] + shapes.append(_build_shape(label, points, "rectangle")) + return shapes + + +def save_labelme_annotations( + dataset: DetectionDataset, + annotations_directory_path: str, +) -> None: + """Export a ``DetectionDataset`` to per-image LabelMe ``.json`` files. + + Args: + dataset: The ``DetectionDataset`` to write. + annotations_directory_path: Directory where the LabelMe ``.json`` files + are written (created if it does not exist). + + Raises: + ValueError: If two image paths map to the same output .json stem, + which would cause one annotation file to overwrite another. + + Examples: + ```python + import supervision as sv + from supervision.dataset.formats.labelme import save_labelme_annotations + + dataset = sv.DetectionDataset(classes=["dog"], images=[], annotations={}) + save_labelme_annotations( + dataset=dataset, + annotations_directory_path="", + ) + ``` + """ + check_no_basename_collisions( + image_paths=dataset.image_paths, + key=lambda image_path: f"{Path(image_path).stem}.json", + output_kind="LabelMe annotation", + ) + Path(annotations_directory_path).mkdir(parents=True, exist_ok=True) + for image_path, image, detections in dataset: + image_height, image_width, _ = image.shape + labelme_dict: LabelMeDict = { + "version": _LABELME_EXPORT_VERSION, + "flags": {}, + "shapes": detections_to_labelme_shapes( + detections=detections, classes=dataset.classes + ), + "imagePath": Path(image_path).name, + "imageData": None, + "imageHeight": int(image_height), + "imageWidth": int(image_width), + } + annotation_path = ( + Path(annotations_directory_path) / f"{Path(image_path).stem}.json" + ) + save_json_file(data=labelme_dict, file_path=str(annotation_path)) diff --git a/.venv/lib/python3.12/site-packages/supervision/dataset/formats/pascal_voc.py b/.venv/lib/python3.12/site-packages/supervision/dataset/formats/pascal_voc.py new file mode 100644 index 0000000000000000000000000000000000000000..80a86bc0b8e203cf93c1c59b86a23dcce9800f31 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/dataset/formats/pascal_voc.py @@ -0,0 +1,501 @@ +import math +import os +from pathlib import Path +from typing import TYPE_CHECKING +from xml.etree.ElementTree import Element, SubElement + +if TYPE_CHECKING: + from supervision.dataset.core import DetectionDataset + +import numpy as np +import numpy.typing as npt +from defusedxml.ElementTree import parse, tostring +from defusedxml.minidom import parseString +from tqdm.auto import tqdm + +from supervision import _cv2 as cv2 +from supervision.dataset.utils import ( + approximate_mask_with_polygons, + check_no_basename_collisions, +) +from supervision.detection.core import Detections +from supervision.detection.utils.converters import polygon_to_mask, polygon_to_xyxy +from supervision.utils.file import list_files_with_extensions + + +def object_to_pascal_voc( + xyxy: npt.NDArray[np.number], + name: str, + polygon: npt.NDArray[np.number] | None = None, +) -> Element: + """Build a Pascal VOC ```` XML element for one detection. + + Coordinates are converted to 1-indexed Pascal VOC convention before writing. + The input arrays are never mutated; new arrays are allocated for the offset. + + Args: + xyxy: Bounding box in zero-indexed pixel coordinates ``[x1, y1, x2, y2]``. + Shape ``(4,)``. + name: Class label string written to the ```` child element. + polygon: Optional segmentation polygon in zero-indexed pixel coordinates. + Shape ``(N, 2)``. + + Returns: + An XML ``Element`` rooted at ```` containing ````, + ````, and optionally ```` children. + + Examples: + ```pycon + >>> import numpy as np + >>> from supervision.dataset.formats.pascal_voc import object_to_pascal_voc + >>> elem = object_to_pascal_voc(np.array([0, 0, 9, 9]), name="cat") + >>> elem.find("bndbox/xmin").text + '1' + >>> elem.find("bndbox/xmax").text + '10' + + ``` + """ + root = Element("object") + + object_name = SubElement(root, "name") + object_name.text = name + + # Pascal VOC coordinates are 1-indexed (https://github.com/roboflow/supervision/issues/144). + # Rebind to a new array instead of `+= 1`: `xyxy` is a view into the source + # `Detections.xyxy` (yielded by `Detections.__iter__`), so an in-place add + # would corrupt the caller's detections by +1 on every export. + xyxy = xyxy + 1 + + bndbox = SubElement(root, "bndbox") + xmin = SubElement(bndbox, "xmin") + xmin.text = str(int(xyxy[0])) + ymin = SubElement(bndbox, "ymin") + ymin.text = str(int(xyxy[1])) + xmax = SubElement(bndbox, "xmax") + xmax.text = str(int(xyxy[2])) + ymax = SubElement(bndbox, "ymax") + ymax.text = str(int(xyxy[3])) + + if polygon is not None: + # 1-indexed, rebound to avoid mutating the caller's array (see above). + polygon = polygon + 1 + object_polygon = SubElement(root, "polygon") + for index, point in enumerate(polygon, start=1): + x_coordinate, y_coordinate = point + x = SubElement(object_polygon, f"x{index}") + x.text = str(x_coordinate) + y = SubElement(object_polygon, f"y{index}") + y.text = str(y_coordinate) + + return root + + +def detections_to_pascal_voc( + detections: Detections, + classes: list[str], + filename: str, + image_shape: tuple[int, int, int], + min_image_area_percentage: float = 0.0, + max_image_area_percentage: float = 1.0, + approximation_percentage: float = 0.75, +) -> str: + """ + Converts Detections object to Pascal VOC XML format. + + Args: + detections: A Detections object containing bounding boxes, + class ids, and other relevant information. + classes: A list of class names corresponding to the + class ids in the Detections object. + filename: The name of the image file associated with the detections. + image_shape: The shape of the image + file associated with the detections. + min_image_area_percentage: Minimum detection area + relative to area of image associated with it. + max_image_area_percentage: Maximum detection area + relative to area of image associated with it. + approximation_percentage: The percentage of + polygon points to be removed from the input polygon, in the range [0, 1). + Returns: + An XML string in Pascal VOC format representing the detections. + + Note: + ``detections`` is never mutated by this function; the source ``xyxy`` + array is unchanged after the call. The function is therefore safe to + call multiple times on the same ``Detections`` object. + """ + height, width, depth = image_shape + + # Create root element + annotation = Element("annotation") + + # Add folder element + folder = SubElement(annotation, "folder") + folder.text = "VOC" + + # Add filename element + file_name = SubElement(annotation, "filename") + file_name.text = filename + + # Add source element + source = SubElement(annotation, "source") + database = SubElement(source, "database") + database.text = "roboflow.ai" + + # Add size element + size = SubElement(annotation, "size") + w = SubElement(size, "width") + w.text = str(width) + h = SubElement(size, "height") + h.text = str(height) + d = SubElement(size, "depth") + d.text = str(depth) + + # Add segmented element + segmented = SubElement(annotation, "segmented") + segmented.text = "0" + + # Add object elements + for xyxy, mask, _, class_id, _, _ in detections: + if class_id is None: + raise ValueError("Detections must include class_id for Pascal VOC export.") + if not isinstance(class_id, (int, np.integer)): + raise ValueError( + f"Detections class_id must be an integer for Pascal VOC export, " + f"got {type(class_id)!r}." + ) + name = classes[class_id] + if mask is not None: + polygons = approximate_mask_with_polygons( + mask=mask, + min_image_area_percentage=min_image_area_percentage, + max_image_area_percentage=max_image_area_percentage, + approximation_percentage=approximation_percentage, + ) + for polygon in polygons: + xyxy = polygon_to_xyxy(polygon=polygon) + next_object = object_to_pascal_voc( + xyxy=xyxy, name=name, polygon=polygon + ) + annotation.append(next_object) + else: + next_object = object_to_pascal_voc(xyxy=xyxy, name=name) + annotation.append(next_object) + + # Generate XML string + xml_string = str( + parseString(tostring(annotation).decode("utf-8")).toprettyxml(indent=" ") + ) + return xml_string + + +def load_pascal_voc_annotations( + images_directory_path: str, + annotations_directory_path: str, + force_masks: bool = False, + show_progress: bool = False, +) -> tuple[list[str], list[str], dict[str, Detections]]: + """ + Load Pascal VOC XML annotations in sorted image-path order. + + Args: + images_directory_path: The path to the directory containing the images. + Files with a ``.bmp``, ``.jpeg``, ``.jpg``, ``.png``, ``.tif``, + ``.tiff`` or ``.webp`` extension are loaded. + annotations_directory_path: The path to the directory containing the + PASCAL VOC annotation files. + force_masks: If True, forces masks to be loaded for all + annotations, regardless of whether they are present. + show_progress: If True, display a progress bar during loading. + + Returns: + A tuple with a list of class names, a sorted list of paths to images, + and a dictionary with image paths as keys and corresponding + Detections instances as values. + """ + + image_paths = sorted( + str(path) + for path in list_files_with_extensions( + directory=images_directory_path, + extensions=["bmp", "jpeg", "jpg", "png", "tif", "tiff", "webp"], + ) + ) + + classes: list[str] = [] + annotations = {} + + for image_path in tqdm( + image_paths, + total=len(image_paths), + desc="Loading Pascal VOC annotations", + disable=not show_progress, + ): + image_stem = Path(image_path).stem + annotation_path = os.path.join(annotations_directory_path, f"{image_stem}.xml") + if not os.path.exists(annotation_path): + annotations[image_path] = Detections.empty() + continue + + tree = parse(annotation_path) + root = tree.getroot() + if root is None: + raise ValueError(f"Failed to parse XML root from {annotation_path}") + + image = cv2.imread(image_path) + if image is None: + raise ValueError(f"Could not read image from path: {image_path}") + resolution_wh = (image.shape[1], image.shape[0]) + annotation, classes = detections_from_xml_obj( + root, classes, resolution_wh, force_masks + ) + annotations[image_path] = annotation + + return classes, image_paths, annotations + + +def detections_from_xml_obj( + root: Element, + classes: list[str], + resolution_wh: tuple[int, int], + force_masks: bool = False, +) -> tuple[Detections, list[str]]: + """ + Converts an XML object in Pascal VOC format to a Detections object. + Expected XML format: + + ... + + dog + + 48 + 240 + 195 + 371 + + + 48 + 240 + 195 + 240 + 195 + 371 + 48 + 371 + + + + + Args: + root: Parsed Pascal VOC ```` XML element. + classes: Existing class names used to assign stable class ids. + resolution_wh: Image resolution as ``(width, height)`` for mask + rasterization. + force_masks: If True, returns a mask array for every object even when + no ```` element is present. + + Returns: + A tuple containing a Detections object and an + updated list of class names, extended with the class names + from the XML object. The Detections ``class_id`` is always an + integer-dtype array, including the zero-```` (background) + case where it is empty. + """ + xyxy: list[list[float]] = [] + class_names: list[str] = [] + masks: list[npt.NDArray[np.bool_]] = [] + with_masks = force_masks or any( + _with_poly_mask(obj) for obj in root.findall("object") + ) + extended_classes = classes[:] + for obj in root.findall("object"): + class_name = _get_required_text(obj, "name") + class_names.append(class_name) + + bbox = obj.find("bndbox") + if bbox is None: + raise ValueError("Missing bndbox in Pascal VOC annotation.") + x1 = _parse_coordinate(_get_required_text(bbox, "xmin"), "xmin") + y1 = _parse_coordinate(_get_required_text(bbox, "ymin"), "ymin") + x2 = _parse_coordinate(_get_required_text(bbox, "xmax"), "xmax") + y2 = _parse_coordinate(_get_required_text(bbox, "ymax"), "ymax") + + xyxy.append([x1, y1, x2, y2]) + + object_mask: npt.NDArray[np.bool_] = np.zeros( + (resolution_wh[1], resolution_wh[0]), dtype=bool + ) + for polygon_element in obj.findall("polygon"): + polygon = parse_polygon_points(polygon_element) + # https://github.com/roboflow/supervision/issues/144 + polygon -= 1 + + # Round only after the 1-index offset, as the YOLO and LabelMe loaders + # round zero-indexed vertices; rounding first would move `.5` values. + mask_from_polygon = polygon_to_mask( + polygon=np.round(polygon).astype(np.int32), + resolution_wh=resolution_wh, + ) + object_mask |= mask_from_polygon.astype(bool) + + if with_masks: + masks.append(object_mask) + + xyxy_arr: npt.NDArray[np.float32] + if xyxy: + xyxy_arr = np.array(xyxy, dtype=np.float32) + else: + xyxy_arr = np.empty((0, 4), dtype=np.float32) + + # https://github.com/roboflow/supervision/issues/144 + xyxy_arr -= 1 + + for k in sorted(set(class_names)): + if k not in extended_classes: + extended_classes.append(k) + # dtype=int forced: on a background image class_names is empty, so + # np.array([]) would default to float64 and fail Detections' integer + # class_id validation. Redundant on the non-empty path (ints already). + class_id = np.array( + [extended_classes.index(class_name) for class_name in class_names], + dtype=int, + ) + + mask_arr: npt.NDArray[np.bool_] | None + if not with_masks: + mask_arr = None + elif masks: + mask_arr = np.array(masks, dtype=bool) + else: + # Background image with force_masks=True: masks is empty, and + # np.array([]) would collapse to shape (0,). Detections requires a 3D + # (0, H, W) mask, so build the empty stack explicitly. + mask_arr = np.empty((0, resolution_wh[1], resolution_wh[0]), dtype=bool) + + annotation = Detections( + xyxy=xyxy_arr, + mask=mask_arr, + class_id=class_id, + ) + + return annotation, extended_classes + + +def _with_poly_mask(obj: Element) -> bool: + return obj.find("polygon") is not None + + +def _parse_coordinate(text: str, tag: str) -> float: + """Parse one Pascal VOC coordinate written as an integer or a decimal. + + Exporters that keep sub-pixel boxes write values such as ``48.5`` or ``48.0``, + which ``int()`` rejects. Anything that is not a finite number still raises. + """ + try: + value = float(text) + except ValueError: + value = math.nan + if not math.isfinite(value): + raise ValueError(f"Invalid '{tag}' value {text!r} in Pascal VOC annotation.") + return value + + +def parse_polygon_points(polygon: Element) -> npt.NDArray[np.float64]: + """Parse ```` vertices, keeping decimal values as written. + + Vertices stay floats so the caller can apply the 1-index offset before rounding them + to pixels for rasterisation. + """ + coordinates: list[float] = [] + for coord in polygon.findall(".//*"): + if coord.text is None: + raise ValueError("Missing polygon coordinate value in Pascal VOC.") + coordinates.append(_parse_coordinate(coord.text, coord.tag)) + return np.array( + [(coordinates[i], coordinates[i + 1]) for i in range(0, len(coordinates), 2)], + dtype=np.float64, + ) + + +def _get_required_text(element: Element, tag: str) -> str: + child = element.find(tag) + if child is None or child.text is None: + raise ValueError(f"Missing '{tag}' in Pascal VOC annotation.") + return child.text + + +def save_pascal_voc_annotations( + dataset: "DetectionDataset", + annotations_directory_path: str, + min_image_area_percentage: float = 0.0, + max_image_area_percentage: float = 1.0, + approximation_percentage: float = 0.75, + show_progress: bool = False, +) -> None: + """Write Pascal VOC XML annotation files for every image in *dataset*. + + Files are written as UTF-8, whatever the platform's default encoding is. + + Args: + dataset: Dataset whose annotations are saved. + annotations_directory_path: Destination directory for ``.xml`` files; + created automatically if it does not exist. + min_image_area_percentage: Minimum detection area as a fraction of the + image area. Detections below this threshold are omitted. Must be in + ``[0, 1]``. Default ``0.0`` keeps all detections. + max_image_area_percentage: Maximum detection area as a fraction of the + image area. Detections above this threshold are omitted. Must be in + ``[0, 1]``. Default ``1.0`` keeps all detections. + approximation_percentage: Fraction of polygon vertices to remove when + approximating instance masks as polygons. Range ``[0, 1)``. Default + ``0.75`` applies aggressive simplification. + show_progress: If ``True``, display a tqdm progress bar while writing + annotation files. Default ``False``. + + Raises: + ValueError: If two image paths map to the same ``.xml`` output name. + + Examples: + ```pycon + >>> import tempfile + >>> from supervision.dataset.core import DetectionDataset + >>> from supervision.dataset.formats.pascal_voc import ( + ... save_pascal_voc_annotations, + ... ) + >>> dataset = DetectionDataset(classes=[], images={}, annotations={}) + >>> with tempfile.TemporaryDirectory() as tmpdir: + ... save_pascal_voc_annotations(dataset, tmpdir) + + ``` + """ + + check_no_basename_collisions( + image_paths=dataset.image_paths, + key=lambda image_path: f"{Path(image_path).stem}.xml", + output_kind="Pascal VOC annotation", + ) + Path(annotations_directory_path).mkdir(parents=True, exist_ok=True) + for image_path, image, annotations in tqdm( + dataset, + total=len(dataset), + desc="Saving Pascal VOC annotations", + disable=not show_progress, + ): + annotation_name = Path(image_path).stem + annotations_path = os.path.join( + annotations_directory_path, f"{annotation_name}.xml" + ) + image_name = Path(image_path).name + pascal_voc_xml = detections_to_pascal_voc( + detections=annotations, + classes=dataset.classes, + filename=image_name, + image_shape=(image.shape[0], image.shape[1], image.shape[2]), + min_image_area_percentage=min_image_area_percentage, + max_image_area_percentage=max_image_area_percentage, + approximation_percentage=approximation_percentage, + ) + # The XML declaration names no encoding, so readers decode it as UTF-8. + with open(annotations_path, "w", encoding="utf-8") as f: + f.write(pascal_voc_xml) diff --git a/.venv/lib/python3.12/site-packages/supervision/dataset/formats/yolo.py b/.venv/lib/python3.12/site-packages/supervision/dataset/formats/yolo.py new file mode 100644 index 0000000000000000000000000000000000000000..9c280ae2fe974733dc5b9d9a8fd037f66f9f8191 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/dataset/formats/yolo.py @@ -0,0 +1,531 @@ +from __future__ import annotations + +import os +import warnings +from collections.abc import Sequence +from decimal import Decimal, InvalidOperation +from pathlib import Path +from typing import TYPE_CHECKING, Any, cast + +import numpy as np +import numpy.typing as npt +from tqdm.auto import tqdm + +from supervision.config import ORIENTED_BOX_COORDINATES +from supervision.dataset.utils import ( + _image_file_resolution_wh, + approximate_mask_with_polygons, + check_no_basename_collisions, +) +from supervision.detection.core import Detections +from supervision.detection.utils._typing import _DetectionDataType +from supervision.detection.utils.converters import polygon_to_mask, polygon_to_xyxy +from supervision.utils.file import ( + list_files_with_extensions, + read_txt_file, + read_yaml_file, + save_text_file, + save_yaml_file, +) + +if TYPE_CHECKING: + from supervision.dataset.core import DetectionDataset + + +def _parse_box(values: list[str]) -> npt.NDArray[np.float32]: + x_center, y_center, width, height = values + return np.array( + [ + float(x_center) - float(width) / 2, + float(y_center) - float(height) / 2, + float(x_center) + float(width) / 2, + float(y_center) + float(height) / 2, + ], + dtype=np.float32, + ) + + +def _box_to_polygon(box: npt.NDArray[np.float32]) -> npt.NDArray[np.float32]: + return np.array( + [[box[0], box[1]], [box[2], box[1]], [box[2], box[3]], [box[0], box[3]]], + dtype=np.float32, + ) + + +def _parse_polygon(values: list[str]) -> npt.NDArray[np.float32]: + return np.array(values, dtype=np.float32).reshape(-1, 2) + + +def _polygons_to_masks( + polygons: Sequence[npt.NDArray[np.number]], resolution_wh: tuple[int, int] +) -> npt.NDArray[np.bool_]: + return np.array( + [ + polygon_to_mask( + polygon=np.round(polygon).astype(np.int32), + resolution_wh=resolution_wh, + ) + for polygon in polygons + ], + dtype=bool, + ) + + +def _with_seg_mask(lines: list[str]) -> bool: + return any([len(line.split()) > 5 for line in lines]) + + +def _extract_class_names(file_path: str) -> list[str]: + """Return class names from a YOLO data.yaml file ordered by class index. + + Supports list and dict forms of the ``names`` field. Dict keys that are + all int-like (plain ints or digit strings) are sorted numerically so + class index 10 follows index 9. All-non-numeric keys are sorted + lexicographically. Mixed numeric/non-numeric keys raise ``ValueError``. + Boolean YAML keys (``true``/``false``) are excluded from numeric sorting + because ``bool`` is a subclass of ``int`` in Python. + + Args: + file_path: Path to the data.yaml file. + + Returns: + Class names in class-index order. + + Raises: + ValueError: If the YAML root is not a mapping, if ``names`` is + neither a list nor a dict, or if the dict has mixed key types. + """ + data: dict[str, Any] = read_yaml_file(file_path=file_path) + if not isinstance(data, dict): + raise ValueError( + f"Expected mapping in data.yaml at '{file_path}'," + f" got {type(data).__name__}." + ) + names = data.get("names") + if isinstance(names, dict): + keys = list(names.keys()) + + def _is_int_like(key: Any) -> bool: + # bool subclasses int; YAML `true`/`false` must not become class indices + if isinstance(key, bool): + return False + if isinstance(key, int): + return True + if isinstance(key, str): + stripped = key.strip() + return stripped.isdigit() + return False + + int_like = [_is_int_like(k) for k in keys] + if any(int_like) and not all(int_like): + mixed_numeric = [k for k, il in zip(keys, int_like) if il][:3] + mixed_other = [k for k, il in zip(keys, int_like) if not il][:3] + raise ValueError( + f"Expected 'names' dict in data.yaml at '{file_path}' to have either " + f"all numeric or all non-numeric keys, got a mix: " + f"numeric {mixed_numeric} and non-numeric {mixed_other} keys." + ) + if all(int_like): + sorted_keys = sorted(keys, key=lambda k: int(k)) + else: + sorted_keys = sorted(keys, key=str) + return [str(names[key]) for key in sorted_keys] + if isinstance(names, list): + return [str(name) for name in names] + raise ValueError( + "Expected 'names' to be a list or dict in data.yaml at " + f"'{file_path}', got {type(names).__name__}." + ) + + +def _image_name_to_annotation_name(image_name: str) -> str: + base_name, _ = os.path.splitext(image_name) + return base_name + ".txt" + + +def _parse_class_id(value: str) -> int: + """Parse a YOLO class id written as an integer or as a whole decimal number. + + Label files saved with ``np.savetxt`` write every column as a float, such as + ``1.000000000000000000e+00``, and Ultralytics reads the class column as a float, so + such datasets train there. Values that are not finite whole numbers still raise. + """ + try: + return int(value) + except ValueError: + pass + try: + class_id = Decimal(value) + except InvalidOperation: + raise ValueError( + f"Invalid class id {value!r} in YOLO annotation; expected a whole number." + ) from None + if not class_id.is_finite() or class_id != class_id.to_integral_value(): + raise ValueError( + f"Invalid class id {value!r} in YOLO annotation; expected a whole number." + ) + return int(class_id) + + +def yolo_annotations_to_detections( + lines: list[str], + resolution_wh: tuple[int, int], + with_masks: bool, + is_obb: bool = False, +) -> Detections: + if len(lines) == 0: + return Detections.empty() + + class_id_list: list[int] = [] + relative_xyxy_list: list[npt.NDArray[np.number]] = [] + relative_polygon_list: list[npt.NDArray[np.float32]] = [] + relative_xyxyxyxy_list: list[npt.NDArray[np.float32]] = [] + w, h = resolution_wh + for line in lines: + values = line.split() + class_id_list.append(_parse_class_id(values[0])) + if len(values) == 5: + box = _parse_box(values=values[1:]) + relative_xyxy_list.append(box) + if with_masks: + relative_polygon_list.append(_box_to_polygon(box=box)) + elif len(values) > 5: + polygon = _parse_polygon(values=values[1:]) + relative_xyxy_list.append(polygon_to_xyxy(polygon=polygon)) + if is_obb: + relative_xyxyxyxy_list.append(np.array(values[1:], dtype=np.float32)) + if with_masks: + relative_polygon_list.append(polygon) + + class_id = np.array(class_id_list, dtype=int) + relative_xyxy = np.array(relative_xyxy_list, dtype=np.float32) + xyxy = relative_xyxy * np.array([w, h, w, h], dtype=np.float32) + data: _DetectionDataType = {} + + if is_obb: + relative_xyxyxyxy = np.array(relative_xyxyxyxy_list, dtype=np.float32) + xyxyxyxy = relative_xyxyxyxy.reshape(-1, 4, 2) + xyxyxyxy *= np.array([w, h], dtype=np.float32) + data[ORIENTED_BOX_COORDINATES] = cast(npt.NDArray[np.generic], xyxyxyxy) + + if not with_masks: + return Detections(class_id=class_id, xyxy=xyxy, data=data) + + polygons = [ + polygon * np.array(resolution_wh, dtype=np.float32) + for polygon in relative_polygon_list + ] + mask = _polygons_to_masks(polygons=polygons, resolution_wh=resolution_wh) + return Detections(class_id=class_id, xyxy=xyxy, data=data, mask=mask) + + +def load_yolo_annotations( + images_directory_path: str, + annotations_directory_path: str, + data_yaml_path: str, + force_masks: bool = False, + is_obb: bool = False, + show_progress: bool = False, +) -> tuple[list[str], list[str], dict[str, Detections]]: + """ + Loads YOLO annotations and returns class names, images, + and their corresponding detections. + + Args: + images_directory_path: The path to the directory containing the images. + annotations_directory_path: The path to the directory + containing the YOLO annotation files. + data_yaml_path: The path to the data + YAML file containing class information. + force_masks: If True, forces masks to be loaded + for all annotations, regardless of whether they are present. + This parameter has no effect when `is_obb=True`; mask generation + is always disabled for OBB annotations. + is_obb: If True, loads the annotations in OBB format. + OBB annotations are defined as `[class_id, x, y, x, y, x, y, x, y]`, + where pairs of [x, y] are box corners. + show_progress: If True, display a progress bar during loading. + + Returns: + A tuple containing a list of class names, a dictionary with + image names as keys and images as values, and a dictionary + with image names as keys and corresponding Detections instances as values. + """ + if is_obb and force_masks: + warnings.warn( + "`force_masks=True` has no effect when `is_obb=True`; " + "mask generation is always disabled for OBB annotations.", + UserWarning, + stacklevel=2, + ) + image_paths = [ + str(path) + for path in list_files_with_extensions( + directory=images_directory_path, + extensions=[ + "bmp", + "dng", + "jpg", + "jpeg", + "mpo", + "png", + "tif", + "tiff", + "webp", + ], + ) + ] + + classes = _extract_class_names(file_path=data_yaml_path) + annotations = {} + + for image_path in tqdm( + image_paths, + total=len(image_paths), + desc="Loading YOLO annotations", + disable=not show_progress, + ): + image_stem = Path(image_path).stem + annotation_path = os.path.join(annotations_directory_path, f"{image_stem}.txt") + if not os.path.exists(annotation_path): + annotations[image_path] = Detections.empty() + continue + + w, h = _image_file_resolution_wh(image_path) + lines = read_txt_file(file_path=annotation_path, skip_empty=True) + resolution_wh = (w, h) + + with_masks = not is_obb and (force_masks or _with_seg_mask(lines=lines)) + annotation = yolo_annotations_to_detections( + lines=lines, + resolution_wh=resolution_wh, + with_masks=with_masks, + is_obb=is_obb, + ) + annotations[image_path] = annotation + return classes, image_paths, annotations + + +def object_to_yolo( + xyxy: npt.NDArray[np.number], + class_id: int, + image_shape: tuple[int, int, int], + polygon: npt.NDArray[np.number] | None = None, +) -> str: + h, w, _ = image_shape + if polygon is None: + xyxy_relative = xyxy / np.array([w, h, w, h], dtype=np.float32) + x_min, y_min, x_max, y_max = xyxy_relative + x_center = (x_min + x_max) / 2 + y_center = (y_min + y_max) / 2 + width = x_max - x_min + height = y_max - y_min + return f"{int(class_id)} {x_center:.5f} {y_center:.5f} {width:.5f} {height:.5f}" + else: + polygon_relative = polygon / np.array([w, h], dtype=np.float32) + polygon_relative = polygon_relative.reshape(-1) + polygon_parsed = " ".join([f"{value:.5f}" for value in polygon_relative]) + return f"{int(class_id)} {polygon_parsed}" + + +def detections_to_yolo_annotations( + detections: Detections, + image_shape: tuple[int, int, int], + min_image_area_percentage: float = 0.0, + max_image_area_percentage: float = 1.0, + approximation_percentage: float = 0.75, + is_obb: bool = False, +) -> list[str]: + """Convert detections to YOLO annotation lines. + + Args: + detections: The detections to serialize. Each detection must have a + valid integer ``class_id``. When ``is_obb=True``, each non-empty + detection must also carry ``detections.data['xyxyxyxy']`` with + shape ``(N, 4, 2)``. + image_shape: The ``(height, width, channels)`` shape of the source + image, used to normalize coordinates to ``[0, 1]``. + min_image_area_percentage: Minimum detection area as a fraction of the + image area; smaller detections are omitted. Ignored when + ``is_obb=True``. + max_image_area_percentage: Maximum detection area as a fraction of the + image area; larger detections are omitted. Ignored when + ``is_obb=True``. + approximation_percentage: Fraction of polygon points removed during + contour approximation when saving mask annotations. Ignored when + ``is_obb=True``. + is_obb: If ``True``, serializes oriented bounding-box corners from + ``detections.data['xyxyxyxy']`` as a 9-token YOLO OBB line + ``class_id x1 y1 x2 y2 x3 y3 x4 y4``. Mask data is ignored. + + Returns: + A list of YOLO annotation strings, one per detection (or one per + polygon for instance-segmentation annotations). + + Raises: + ValueError: If any detection has ``class_id=None`` or a non-integer + ``class_id``. + ValueError: If ``is_obb=True`` and any non-empty detection is missing + ``'xyxyxyxy'`` in ``detections.data``. + + Examples: + ```pycon + >>> import numpy as np + >>> from supervision.detection.core import Detections + >>> from supervision.dataset.formats.yolo import detections_to_yolo_annotations + >>> detections = Detections( + ... xyxy=np.array([[10, 10, 90, 90]], dtype=np.float32), + ... class_id=np.array([0]), + ... ) + >>> detections_to_yolo_annotations(detections, image_shape=(100, 100, 3)) + ['0 0.50000 0.50000 0.80000 0.80000'] + + ``` + """ + if ( + is_obb + and len(detections) > 0 + and ORIENTED_BOX_COORDINATES not in detections.data + ): + raise ValueError( + f"`is_obb=True` requires `'{ORIENTED_BOX_COORDINATES}'` in " + "`detections.data` with shape (N, 4, 2). Load OBB datasets via " + "`DetectionDataset.from_yolo(..., is_obb=True)` or set " + f"`detections.data['{ORIENTED_BOX_COORDINATES}']` " + "(shape (N, 4, 2)) before exporting." + ) + + if is_obb and detections.mask is not None: + warnings.warn( + "`detections.mask` is ignored when `is_obb=True`; " + "OBB annotations use corner coordinates from " + f"`detections.data['{ORIENTED_BOX_COORDINATES}']`.", + UserWarning, + stacklevel=2, + ) + + annotation: list[str] = [] + for xyxy, mask, _, class_id, _, data in detections: + if class_id is None: + raise ValueError("Class ID is required for YOLO annotations.") + if not isinstance(class_id, (int, np.integer)): + raise ValueError( + f"Detections class_id must be an integer for YOLO export, " + f"got {type(class_id)!r}." + ) + class_id_int = int(class_id) + + if is_obb: + corners = np.asarray(data[ORIENTED_BOX_COORDINATES], dtype=np.float32) + if corners.shape != (4, 2): + raise ValueError( + f"OBB data for each detection must have shape (4, 2), " + f"got {corners.shape}. Ensure " + f"`detections.data['{ORIENTED_BOX_COORDINATES}']` has " + "shape (N, 4, 2) before exporting." + ) + next_object = object_to_yolo( + xyxy=xyxy, + class_id=class_id_int, + image_shape=image_shape, + polygon=corners, + ) + annotation.append(next_object) + continue + + if mask is not None: + polygons = approximate_mask_with_polygons( + mask=mask, + min_image_area_percentage=min_image_area_percentage, + max_image_area_percentage=max_image_area_percentage, + approximation_percentage=approximation_percentage, + ) + for polygon in polygons: + xyxy = polygon_to_xyxy(polygon=polygon) + next_object = object_to_yolo( + xyxy=xyxy, + class_id=class_id_int, + image_shape=image_shape, + polygon=polygon, + ) + annotation.append(next_object) + else: + next_object = object_to_yolo( + xyxy=xyxy, class_id=class_id_int, image_shape=image_shape + ) + annotation.append(next_object) + return annotation + + +def save_yolo_annotations( + dataset: DetectionDataset, + annotations_directory_path: str, + min_image_area_percentage: float = 0.0, + max_image_area_percentage: float = 1.0, + approximation_percentage: float = 0.75, + is_obb: bool = False, + show_progress: bool = False, +) -> None: + """Save dataset annotations in YOLO format. + + Args: + dataset: The dataset whose annotations are saved. + annotations_directory_path: Path to the directory where annotation + ``.txt`` files are written; created automatically if absent. + min_image_area_percentage: Minimum detection area as a fraction of the + image area; smaller detections are omitted. Ignored when + ``is_obb=True``. + max_image_area_percentage: Maximum detection area as a fraction of the + image area; larger detections are omitted. Ignored when + ``is_obb=True``. + approximation_percentage: Fraction of polygon points removed during + contour approximation when saving mask annotations. Ignored when + ``is_obb=True``. + is_obb: If ``True``, writes oriented bounding-box annotations using + the 9-token format ``class_id x1 y1 x2 y2 x3 y3 x4 y4``. Each + non-empty detection must carry ``detections.data['xyxyxyxy']`` + with shape ``(N, 4, 2)``. + show_progress: If ``True``, display a tqdm progress bar while + saving annotations. + + Examples: + ```pycon + >>> from supervision.dataset.core import DetectionDataset + >>> from supervision.dataset.formats.yolo import save_yolo_annotations + >>> dataset = DetectionDataset(classes=["cat"], images={}, annotations={}) + >>> save_yolo_annotations(dataset, "/tmp/labels") + + ``` + """ + check_no_basename_collisions( + image_paths=dataset.image_paths, + key=lambda image_path: _image_name_to_annotation_name(Path(image_path).name), + output_kind="YOLO annotation", + ) + Path(annotations_directory_path).mkdir(parents=True, exist_ok=True) + for image_path, image, annotation in tqdm( + dataset, + total=len(dataset), + desc="Saving YOLO annotations", + disable=not show_progress, + ): + image_name = Path(image_path).name + yolo_annotations_name = _image_name_to_annotation_name(image_name=image_name) + yolo_annotations_path = os.path.join( + annotations_directory_path, yolo_annotations_name + ) + lines = detections_to_yolo_annotations( + detections=annotation, + image_shape=image.shape, + min_image_area_percentage=min_image_area_percentage, + max_image_area_percentage=max_image_area_percentage, + approximation_percentage=approximation_percentage, + is_obb=is_obb, + ) + save_text_file(lines=lines, file_path=yolo_annotations_path) + + +def save_data_yaml(data_yaml_path: str, classes: list[str]) -> None: + data = {"nc": len(classes), "names": classes} + Path(data_yaml_path).parent.mkdir(parents=True, exist_ok=True) + save_yaml_file(data=data, file_path=data_yaml_path) diff --git a/.venv/lib/python3.12/site-packages/supervision/dataset/utils.py b/.venv/lib/python3.12/site-packages/supervision/dataset/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c2965542449dedbc1b6116d5ba605e17da0c4cc3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/dataset/utils.py @@ -0,0 +1,293 @@ +from __future__ import annotations + +__all__ = ["check_no_basename_collisions", "train_test_split"] + +import copy +import os +import random +import shutil +from collections.abc import Callable +from pathlib import Path +from typing import TYPE_CHECKING, TypeVar, cast + +import numpy as np +import numpy.typing as npt +from deprecate import deprecated, void # type: ignore[import-untyped,unused-ignore] +from PIL import Image +from tqdm.auto import tqdm + +from supervision import _cv2 as cv2 +from supervision._cv2._image import _EXIF_ORIENTATION_TAG +from supervision.detection.core import Detections +from supervision.detection.utils.converters import mask_to_polygons +from supervision.detection.utils.converters import ( + mask_to_rle as _mask_to_rle, +) +from supervision.detection.utils.converters import ( + rle_to_mask as _rle_to_mask, +) +from supervision.detection.utils.polygons import ( + approximate_polygon, + filter_polygons_by_area, +) + +_QUARTER_TURN_EXIF_ORIENTATIONS = frozenset({5, 6, 7, 8}) + + +def _image_file_resolution_wh(image_path: str) -> tuple[int, int]: + """Return the `(width, height)` at which `cv2.imread` loads an image file. + + Only the file header is read, which is much faster than decoding the image (#1554). + Loading applies the EXIF orientation tag, and orientations 5 to 8 turn the image a + quarter turn, so for those the header's width and height are swapped. + """ + with Image.open(image_path) as image: + width, height = image.size + orientation = image.getexif().get(_EXIF_ORIENTATION_TAG) + if orientation in _QUARTER_TURN_EXIF_ORIENTATIONS: + return height, width + return width, height + + +@deprecated(target=_mask_to_rle, deprecated_in="0.28.0", remove_in="0.31.0") # type: ignore[untyped-decorator] +def mask_to_rle( + mask: npt.NDArray[np.bool_], compressed: bool = False +) -> list[int] | str: + """Deprecated since 0.28.0. + + Use `supervision.detection.utils.converters.mask_to_rle`. + """ + return cast(list[int] | str, void(mask, compressed)) + + +@deprecated(target=_rle_to_mask, deprecated_in="0.28.0", remove_in="0.31.0") # type: ignore[untyped-decorator] +def rle_to_mask( + rle: npt.NDArray[np.integer] | list[int] | str | bytes, + resolution_wh: tuple[int, int], +) -> npt.NDArray[np.bool_]: + """Deprecated since 0.28.0. + + Use `supervision.detection.utils.converters.rle_to_mask`. + """ + return cast(npt.NDArray[np.bool_], void(rle, resolution_wh)) + + +if TYPE_CHECKING: + from supervision.dataset.core import DetectionDataset + +T = TypeVar("T") + + +def approximate_mask_with_polygons( + mask: npt.NDArray[np.bool_], + min_image_area_percentage: float = 0.0, + max_image_area_percentage: float = 1.0, + approximation_percentage: float = 0.0, +) -> list[npt.NDArray[np.number]]: + """Filter mask polygons by area and optionally simplify them. + + The default `approximation_percentage=0.0` preserves the original contour + unless callers explicitly ask for simplification. + """ + height, width = mask.shape + image_area = height * width + minimum_detection_area = min_image_area_percentage * image_area + maximum_detection_area = max_image_area_percentage * image_area + + polygons = cast(list[npt.NDArray[np.number]], mask_to_polygons(mask=mask)) + if len(polygons) == 1: + polygons = filter_polygons_by_area( + polygons=polygons, min_area=None, max_area=maximum_detection_area + ) + else: + polygons = filter_polygons_by_area( + polygons=polygons, + min_area=minimum_detection_area, + max_area=maximum_detection_area, + ) + return [ + approximate_polygon(polygon=polygon, percentage=approximation_percentage) + for polygon in polygons + ] + + +def merge_class_lists(class_lists: list[list[str]]) -> list[str]: + unique_classes = set() + + for class_list in class_lists: + for class_name in class_list: + unique_classes.add(class_name) + + return sorted(list(unique_classes)) + + +def build_class_index_mapping( + source_classes: list[str], target_classes: list[str] +) -> dict[int, int]: + """Returns the index map of source classes -> target classes.""" + index_mapping = {} + + for i, class_name in enumerate(source_classes): + if class_name not in target_classes: + raise ValueError( + f"Class {class_name} not found in target classes. " + "source_classes must be a subset of target_classes." + ) + corresponding_index = target_classes.index(class_name) + index_mapping[i] = corresponding_index + + return index_mapping + + +def map_detections_class_id( + source_to_target_mapping: dict[int, int], detections: Detections +) -> Detections: + if detections.class_id is None: + raise ValueError("Detections must have class_id attribute.") + if set(np.unique(detections.class_id)) - set(source_to_target_mapping.keys()): + raise ValueError( + "Detections class_id must be a subset of source_to_target_mapping keys." + ) + + detections_copy = copy.deepcopy(detections) + + if len(detections) > 0: + detections_copy.class_id = np.vectorize(source_to_target_mapping.get)( + detections_copy.class_id + ) + + return detections_copy + + +def check_no_basename_collisions( + image_paths: list[str], + key: Callable[[str], str], + output_kind: str, +) -> None: + """Raise if two image paths would be written to the same output file. + + Dataset image paths may share a basename when they originate from different + directories (a legal, common state after :meth:`DetectionDataset.merge`). + Exporting them into a single flat output directory keyed on the basename or + stem would silently overwrite one file with another and mispair images with + their annotations. This guard detects such collisions before any file is + written and names the colliding source paths. + + Args: + image_paths: The dataset image paths about to be written. + key: Maps an image path to the output file name it would be written to. + output_kind: Human-readable description of the output (e.g. ``"image"`` + or ``"YOLO annotation"``) used in the error message. + + Raises: + ValueError: If two image paths map to the same output file name. + + Examples: + ```pycon + >>> from pathlib import Path + >>> from supervision.dataset.utils import check_no_basename_collisions + >>> check_no_basename_collisions( + ... ["a/img.jpg", "b/img.jpg"], lambda p: Path(p).name, "image" + ... ) + Traceback (most recent call last): + ... + ValueError: Cannot export dataset: image paths 'a/img.jpg' and ... + + ``` + """ + seen: dict[str, tuple[str, str]] = {} # casefold(key) → (original name, image_path) + for image_path in image_paths: + output_name = key(image_path) + case_key = output_name.casefold() + if case_key in seen: + first_name, first_path = seen[case_key] + raise ValueError( + f"Cannot export dataset: image paths {first_path!r} and " + f"{image_path!r} both map to {output_kind} file {first_name!r}. " + "Ensure all output paths are unique before exporting." + ) + seen[case_key] = (output_name, image_path) + + +def save_dataset_images( + dataset: DetectionDataset, + images_directory_path: str, + show_progress: bool = False, +) -> None: + """Save all images from a dataset to a directory. + + Images already in memory are written with ``cv2.imwrite``; images stored + only as file paths are copied with ``shutil.copyfile``. + + Args: + dataset: The dataset whose images are saved. + images_directory_path: Destination directory path; created + automatically if it does not exist. + show_progress: If ``True``, display a tqdm progress bar while + saving images. + + Examples: + ```pycon + >>> from supervision.dataset.core import DetectionDataset + >>> from supervision.dataset.utils import save_dataset_images + >>> dataset = DetectionDataset(classes=["cat"], images={}, annotations={}) + >>> save_dataset_images(dataset, "/tmp/images") + + ``` + """ + check_no_basename_collisions( + image_paths=dataset.image_paths, + key=lambda image_path: Path(image_path).name, + output_kind="image", + ) + Path(images_directory_path).mkdir(parents=True, exist_ok=True) + for image_path in tqdm( + dataset.image_paths, + desc="Saving images", + disable=not show_progress, + ): + final_path = os.path.join(images_directory_path, Path(image_path).name) + if image_path in dataset._images_in_memory: + image = dataset._images_in_memory[image_path] + cv2.imwrite(final_path, image) + else: + shutil.copyfile(image_path, final_path) + + +def train_test_split( + data: list[T], + train_ratio: float = 0.8, + random_state: int | None = None, + shuffle: bool = True, +) -> tuple[list[T], list[T]]: + """ + Splits the data into two parts using the provided train_ratio. + + Args: + data: The data to split. + train_ratio: The ratio of the training set to the entire dataset. + random_state: The seed for the random number generator. + shuffle: Whether to shuffle the data before splitting. + + Returns: + The split data. The input list is copied and never mutated. + + Examples: + ```pycon + >>> train, test = train_test_split( + ... [1, 2, 3, 4, 5], train_ratio=0.6, random_state=0 + ... ) + >>> len(train), len(test) + (3, 2) + + ``` + """ + rng = random.Random(random_state) # noqa: S311 — dataset split, not cryptographic + if shuffle: + data = list(data) + rng.shuffle(data) + else: + data = list(data) # copy to guarantee non-mutation + + split_index = int(len(data) * train_ratio) + return data[:split_index], data[split_index:] diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/__init__.py b/.venv/lib/python3.12/site-packages/supervision/detection/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/detection/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dfb26b3543d30103940933b4a1614ee7461027b8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/detection/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/__pycache__/_geometry_dispatch.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/detection/__pycache__/_geometry_dispatch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0169218a6a4be3061a91a550f9f1a81f301452e0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/detection/__pycache__/_geometry_dispatch.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/__pycache__/compact_mask.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/detection/__pycache__/compact_mask.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49dbba0cd2b3eeb251ec3d60877caa3149742c5a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/detection/__pycache__/compact_mask.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/__pycache__/core.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/detection/__pycache__/core.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13b3627f2bdbb4e6dea51d64efdda6bf4ee42bab --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/detection/__pycache__/core.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3d6508bdc0abaaef12f7ea181099dad43b2bc5425597883b56ccb7e23e8f5c90 +size 148947 diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/__pycache__/line_zone.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/detection/__pycache__/line_zone.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a10b5441edeb36a8ee56eb2a876f9579d4c7bf3c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/detection/__pycache__/line_zone.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/__pycache__/vlm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/detection/__pycache__/vlm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d63bd75bbb44dd22c66bcf6f9a7f0b692daf0d90 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/detection/__pycache__/vlm.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/_geometry_dispatch.py b/.venv/lib/python3.12/site-packages/supervision/detection/_geometry_dispatch.py new file mode 100644 index 0000000000000000000000000000000000000000..b44303b1edbfa5da4d70ad2f7f4b0c123db1a4eb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/detection/_geometry_dispatch.py @@ -0,0 +1,132 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, cast + +import numpy as np +import numpy.typing as npt + +from supervision.config import ORIENTED_BOX_COORDINATES +from supervision.detection.compact_mask import CompactMask +from supervision.detection.utils.boxes import obb_polygon_area +from supervision.detection.utils.iou_and_nms import ( + OverlapMetric, + box_iou_batch, + mask_iou_batch, + oriented_box_iou_batch, +) +from supervision.detection.utils.masks import count_mask_pixels + +if TYPE_CHECKING: + from supervision.detection.core import Detections + + +def detection_area(detections: Detections) -> npt.NDArray[np.generic]: + """ + Calculate detection areas using the richest geometry present. + + Selection order: + + 1. If ``mask`` is set, return the area of each mask. + 2. Else, if ``data[ORIENTED_BOX_COORDINATES]`` is set, return the area of + each oriented box. + 3. Otherwise, return the axis-aligned box area. + + Args: + detections: Detections whose geometry should be measured. + + Returns: + A 1-D array containing the area of each detection. + + Example: + ```pycon + >>> import numpy as np + >>> from supervision.detection.core import Detections + >>> detections = Detections( + ... xyxy=np.array([[0, 0, 2, 3]], dtype=np.float32) + ... ) + >>> detection_area(detections) # doctest: +ELLIPSIS + array([6.], dtype=float32) + + ``` + """ + if detections.mask is not None: + if isinstance(detections.mask, CompactMask): + return detections.mask.area + return count_mask_pixels(detections.mask) + if ORIENTED_BOX_COORDINATES in detections.data: + return obb_polygon_area( + cast(npt.NDArray[np.number], detections.data[ORIENTED_BOX_COORDINATES]) + ) + return detections.box_area + + +def detection_iou( + detections_a: Detections, + detections_b: Detections, + overlap_metric: OverlapMetric | str = OverlapMetric.IOU, +) -> npt.NDArray[np.floating]: + """ + Calculate pairwise IoU using the richest geometry both operands share. + + Selection order: + + 1. If both operands have masks, use mask IoU. + 2. Else, if both operands have oriented-box coordinates, use OBB IoU. + 3. Otherwise, use axis-aligned box IoU. + + This is a **shared**-geometry dispatch, unlike `detection_area`'s + per-operand dispatch: if the two operands carry different kinds of + richer geometry (e.g. one has only a mask, the other only oriented-box + coordinates), neither is used and the axis-aligned box IoU is computed + instead. + + Args: + detections_a: First set of detections. + detections_b: Second set of detections. + overlap_metric: Metric used to compute the degree of overlap. + + Returns: + A matrix of pairwise overlaps with shape + ``(len(detections_a), len(detections_b))``. + + Example: + ```pycon + >>> import numpy as np + >>> from supervision.detection.core import Detections + >>> detections = Detections( + ... xyxy=np.array([[0, 0, 2, 2]], dtype=np.float32) + ... ) + >>> detection_iou(detections, detections) # doctest: +ELLIPSIS + array([[1.]], dtype=float32) + + ``` + """ + overlap_metric = OverlapMetric.from_value(overlap_metric) + if detections_a.mask is not None and detections_b.mask is not None: + return mask_iou_batch( + detections_a.mask, + detections_b.mask, + overlap_metric=overlap_metric, + ) + + if ( + ORIENTED_BOX_COORDINATES in detections_a.data + and ORIENTED_BOX_COORDINATES in detections_b.data + ): + return oriented_box_iou_batch( + cast( + npt.NDArray[np.number], + detections_a.data[ORIENTED_BOX_COORDINATES], + ), + cast( + npt.NDArray[np.number], + detections_b.data[ORIENTED_BOX_COORDINATES], + ), + overlap_metric=overlap_metric, + ) + + return box_iou_batch( + detections_a.xyxy, + detections_b.xyxy, + overlap_metric=overlap_metric, + ) diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/compact_mask.py b/.venv/lib/python3.12/site-packages/supervision/detection/compact_mask.py new file mode 100644 index 0000000000000000000000000000000000000000..38f916f3f35918ab6cec3311419be91a2f6a62dc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/detection/compact_mask.py @@ -0,0 +1,1706 @@ +"""Crop-RLE compact mask storage for memory-efficient instance segmentation. + +Dense ``(N, H, W)`` boolean masks use O(N·H·W) memory, which becomes +prohibitive for aerial imagery (e.g. 1000 objects x 4K image ~ 8.3 GB). +:class:`CompactMask` stores each mask as a run-length encoding of its +bounding-box crop, reducing typical usage to tens of MB. + +The bounding boxes (``xyxy``) already present in ``Detections`` serve as the +crop boundaries, so no extra metadata is required from the caller. + +CompactMask reduces memory footprint but does not improve computational +speed. The ingestion path (base48 decode, column split, RLE trim) is +Python-level and is typically slower than the dense NumPy path. The primary +benefit is memory savings for large images with many sparse masks. +""" + +from __future__ import annotations + +import os +from collections.abc import Iterator, Mapping, Sequence +from typing import Any, cast, overload + +import numpy as np +import numpy.typing as npt + +# _base48_decode and _delta_decode are private to the COCO RLE codec. They +# live in converters.py and are shared by public conversion helpers here and +# in that module. +from supervision.detection.utils.converters import ( + _base48_decode, + _delta_decode, + _mask_to_rle_counts, + _rle_counts_to_mask, +) + + +def _rle_area(rle: npt.NDArray[np.int32]) -> int: + """Return the number of ``True`` pixels in a run-length encoded mask. + + Args: + rle: int32 array of run lengths as produced by :func:`_mask_to_rle_counts`. + + Returns: + Total number of ``True`` pixels. + + Examples: + ```pycon + >>> import numpy as np + >>> from supervision.detection.compact_mask import _rle_area + >>> rle = np.array([1, 2, 1, 1, 1], dtype=np.int32) + >>> _rle_area(rle) + 3 + + ``` + """ + return int(np.sum(rle[1::2])) + + +def _rle_split_cols( + rle: npt.NDArray[np.int32], + crop_h: int, + crop_w: int, + x_start: int = 0, + x_stop: int | None = None, +) -> list[list[int]]: + """Split a flat F-order RLE into per-column run lists. + + With F-order (column-major) RLE the flat pixel sequence visits all rows + of column 0, then all rows of column 1, etc. Each column therefore + contains ``crop_h`` contiguous pixels. + + Runs that cross column boundaries are split at the boundary. Each + returned list starts with a ``False``-run count (possibly 0), matching + the convention of :func:`_mask_to_rle_counts`. + + When ``x_start`` and ``x_stop`` are provided, only columns in the closed + range ``[x_start, x_stop]`` are collected. Pixels in skipped columns + are consumed without being stored, which avoids O(W) allocation when + only a small crop of a wide image is needed. + + Note: + ``x_start`` uses ``np.cumsum`` + ``np.searchsorted`` to jump directly + to the first relevant run in O(log R) time, avoiding the O(pixel_prefix) + walk that previously made right-edge crops on wide images expensive. + + Args: + rle: int32 run-length array as produced by + :func:`~supervision.detection.utils.converters._mask_to_rle_counts`. + crop_h: Number of rows (pixels per column). + crop_w: Number of columns. + x_start: First column to collect (0-indexed, inclusive). Columns + before ``x_start`` are skipped. Defaults to ``0``. + x_stop: Last column to collect (0-indexed, inclusive). Processing + stops after column ``x_stop`` is complete. Defaults to + ``crop_w - 1`` (collect all columns). + + Returns: + List of ``x_stop - x_start + 1`` run lists. Index ``i`` in the + returned list corresponds to column ``x_start + i``. Each list + sums to ``crop_h``. + + Examples: + ```pycon + >>> import numpy as np + >>> from supervision.detection.compact_mask import _rle_split_cols + >>> from supervision.detection.utils.converters import _mask_to_rle_counts + >>> mask = np.array([[True, False], [True, True]], dtype=bool) + >>> rle = _mask_to_rle_counts(mask) + >>> rle.tolist() + [0, 2, 1, 1] + >>> _rle_split_cols(rle, 2, 2) + [[0, 2], [1, 1]] + >>> _rle_split_cols(rle, 2, 2, x_start=1) + [[1, 1]] + + ``` + """ + if x_stop is None: + x_stop = crop_w - 1 + + # Convert numpy int32 array to Python ints to avoid scalar boxing overhead + # in the inner loop (np.int32 boxing/unboxing slows pure-Python loops). + rle_list: list[int] = rle.tolist() + + n_cols = x_stop - x_start + 1 + per_col: list[list[int]] = [[] for _ in range(n_cols)] + + # Fast-forward to the first run that overlaps column x_start using O(log R) + # searchsorted instead of an O(pixel_prefix) sequential walk. + start_pixel = x_start * crop_h + if start_pixel > 0 and len(rle_list) > 0: + cumsum_ends = np.cumsum(rle, dtype=np.int64) + first_run = int(np.searchsorted(cumsum_ends, start_pixel, side="right")) + if first_run >= len(rle_list): + for c in range(n_cols): + per_col[c] = [crop_h] + return per_col + prefix = int(cumsum_ends[first_run - 1]) if first_run > 0 else 0 + else: + first_run = 0 + prefix = 0 + + col = prefix // crop_h + row = prefix % crop_h + + for run_idx in range(first_run, len(rle_list)): + run_len = rle_list[run_idx] + is_true = run_idx % 2 == 1 + remaining = run_len + while remaining > 0: + # Past the requested range — stop early. + if col > x_stop: + remaining = 0 + break + space_in_col = crop_h - row + take = min(remaining, space_in_col) + if col >= x_start: + local_col = col - x_start + if len(per_col[local_col]) == 0: + if is_true: + per_col[local_col].append(0) # leading False count = 0 + # Check if last run has same parity (True/False) as current chunk. + # Last element's parity: index (len-1) odd → True, even → False. + elif is_true == ((len(per_col[local_col]) - 1) % 2 == 1): + per_col[local_col][-1] += take + remaining -= take + row += take + if row >= crop_h: + row = 0 + col += 1 + continue + per_col[local_col].append(take) + remaining -= take + row += take + if row >= crop_h: + row = 0 + col += 1 + if col > x_stop: + break + + # Fill any empty columns (all-False). + for c in range(n_cols): + if not per_col[c]: + per_col[c] = [crop_h] + + return per_col + + +def _rle_scale_col( + col_runs: list[int], + src_h: int, + row_map: npt.NDArray[np.int32], +) -> list[int]: + """Scale one column's run list to a new height using a precomputed row map. + + Each output row is mapped to a source row via ``row_map``, which + implements nearest-neighbour resampling in the vertical direction. + + Args: + col_runs: Per-column run list starting with a ``False``-run count. + src_h: Height of the source column (sum of ``col_runs``). + row_map: int32 array of length ``new_crop_h``; ``row_map[r']`` is the + source row index for output row ``r'``. Use + ``(np.arange(new_crop_h) * src_h // new_crop_h)`` for + ``cv2.INTER_NEAREST``-compatible mapping. + + Returns: + Scaled run list of total length ``len(row_map)``, always starting + with a ``False``-run count. + + Examples: + ```pycon + >>> import numpy as np + >>> from supervision.detection.compact_mask import _rle_scale_col + >>> col_runs = [0, 2, 2] # F=0, T=2, F=2 → [T, T, F, F] + >>> row_map = np.array([0, 1, 2, 3, 0, 1, 2, 3], dtype=np.int32) + >>> _rle_scale_col(col_runs, 4, row_map) + [0, 2, 2, 2, 2] + + ``` + """ + new_crop_h = len(row_map) + if new_crop_h == 0: + return [0] + + # Reconstruct per-source-row boolean values from run list. + src_values: npt.NDArray[np.bool_] = np.empty(src_h, dtype=np.bool_) + pos = 0 + for ri, rl in enumerate(col_runs): + src_values[pos : pos + rl] = ri % 2 == 1 # odd index → True + pos += rl + if pos < src_h: + src_values[pos:] = False # pad truncated RLE + + # Map output rows to source values. + out_values = src_values[row_map] + + # RLE-encode the output column; vectorised via np.diff on bool view. + out_uint8 = out_values.view(np.uint8) + boundaries = np.flatnonzero(np.diff(out_uint8)) + run_starts: npt.NDArray[np.int64] = np.empty(len(boundaries) + 1, dtype=np.int64) + run_ends: npt.NDArray[np.int64] = np.empty(len(boundaries) + 1, dtype=np.int64) + run_starts[0] = 0 + run_starts[1:] = boundaries + 1 + run_ends[:-1] = boundaries + 1 + run_ends[-1] = new_crop_h + result_runs: list[int] = (run_ends - run_starts).tolist() + # RLE starts with a False count; prepend 0 if output begins with True. + if bool(out_values[0]): + result_runs.insert(0, 0) + return result_runs + + +def _rle_join_cols( + scaled_cols: list[list[int]], + new_total: int, +) -> npt.NDArray[np.int32]: + """Concatenate per-column run lists into a flat RLE, merging junctions. + + Each column run list starts with a ``False``-run count. Two junction types + can be merged across column boundaries: + + * ``False``/``False``: the trailing False run merges with the leading False + run of the next column (leading count may be zero). + * ``True``/``True``: when the accumulated output ends on a True run and the + next column's leading False count is zero (column starts with True), the + two True runs are merged to avoid inserting a zero-length False run that + would inflate ``len(rle)`` and skew the density metric in + :func:`_resize_crop`. + + Args: + scaled_cols: List of per-column run lists, each starting with a + ``False``-run count. + new_total: Total pixel count of the output (fallback for empty input). + + Returns: + Flat int32 RLE array starting with a ``False``-run count. + + Examples: + ```pycon + >>> import numpy as np + >>> from supervision.detection.compact_mask import _rle_join_cols + >>> cols = [[1, 2], [1, 2]] # each col: F=1, T=2 + >>> _rle_join_cols(cols, 6).tolist() + [1, 2, 1, 2] + + ``` + """ + output_runs: list[int] = [] + for col_runs in scaled_cols: + if not output_runs: + output_runs.extend(col_runs) + else: + last_is_true = (len(output_runs) - 1) % 2 == 1 + # col_runs always starts with a False count → first_is_true=False + if not last_is_true: # last == False == first → merge + output_runs[-1] += col_runs[0] + output_runs.extend(col_runs[1:]) + elif col_runs[0] == 0 and len(col_runs) > 1: + # last run = True; column also starts True (leading False = 0) + # → merge to avoid a zero-length False run at the junction. + output_runs[-1] += col_runs[1] + output_runs.extend(col_runs[2:]) + else: + output_runs.extend(col_runs) + + return np.array(output_runs if output_runs else [new_total], dtype=np.int32) + + +def _rle_trim_col_runs(col_runs: Sequence[int], y1: int, y2: int) -> list[int]: + """Restrict one full-height column RLE to inclusive rows ``[y1, y2]``. + + Args: + col_runs: Run lengths for one full-height column, starting with a + ``False`` run. + y1: Inclusive top row of the crop. + y2: Inclusive bottom row of the crop. + + Returns: + Run lengths for the cropped column, also starting with a ``False`` run. + + Examples: + ```pycon + >>> from supervision.detection.compact_mask import _rle_trim_col_runs + >>> # Full column F=2, T=2, F=2 (height 6); crop to rows 1..4 inclusive + >>> # yields rows [F, T, T, F] → F=1, T=2, F=1. + >>> _rle_trim_col_runs([2, 2, 2], y1=1, y2=4) + [1, 2, 1] + + ``` + """ + target_height = y2 - y1 + 1 + # Sum invariant: returned list sums to target_height. Correctness depends + # on the caller (from_coco_rle) having already validated that counts sum + # equals img_h * img_w; no re-validation here. + collected: list[tuple[bool, int]] = [] + row = 0 + for run_idx, run_len in enumerate(col_runs): + is_true = run_idx % 2 == 1 + start = row + end = row + int(run_len) + row = end + + crop_start = max(start, y1) + crop_end = min(end, y2 + 1) + if crop_end > crop_start: + collected.append((is_true, crop_end - crop_start)) + if row > y2: + break + + if not collected: + return [target_height] + + result: list[int] = [] + if collected[0][0]: + result.append(0) + for is_true, length in collected: + last_is_true = bool(result) and (len(result) - 1) % 2 == 1 + if result and last_is_true == is_true: + result[-1] += length + else: + result.append(length) + return result + + +def _coco_rle_counts_to_array(counts: Any) -> npt.NDArray[np.int32]: + """Decode COCO RLE counts into absolute F-order run lengths. + + Args: + counts: COCO compressed counts (``str`` or ``bytes``), or uncompressed + integer run lengths. + + Returns: + One-dimensional ``int32`` run-length array. + + Raises: + ValueError: If counts cannot be decoded into non-negative run lengths. + + Examples: + ```pycon + >>> from supervision.detection.compact_mask import _coco_rle_counts_to_array + >>> _coco_rle_counts_to_array([0, 2, 2, 2, 10]) + array([ 0, 2, 2, 2, 10], dtype=int32) + + ``` + """ + try: + if isinstance(counts, bytes): + counts = counts.decode("utf-8") + if isinstance(counts, str): + decoded_counts = _delta_decode(_base48_decode(counts)) + counts_arr = np.array(decoded_counts, dtype=np.int32) + else: + # Convert to int64 first, then range-check against int32 bounds before + # narrowing. A direct int32 cast wraps silently on some numpy versions + # and raises on others; this makes overflow detection deterministic. + counts_arr64 = np.asarray(counts, dtype=np.int64) + int32_info = np.iinfo(np.int32) + if counts_arr64.size and ( + counts_arr64.max() > int32_info.max + or counts_arr64.min() < int32_info.min + ): + raise ValueError("COCO RLE counts exceed int32 range.") + counts_arr = counts_arr64.astype(np.int32) + except (TypeError, ValueError, OverflowError) as exc: + raise ValueError("Invalid COCO RLE counts.") from exc + + if counts_arr.ndim != 1: + raise ValueError("COCO RLE counts must be one-dimensional.") + if counts_arr.size == 0: + raise ValueError("COCO RLE counts cannot be empty.") + if np.any(counts_arr < 0): + raise ValueError("COCO RLE counts must be non-negative.") + return counts_arr + + +def _rle_resize( + rle: npt.NDArray[np.int32], + crop_h: int, + crop_w: int, + new_crop_h: int, + new_crop_w: int, +) -> npt.NDArray[np.int32]: + """Resize an F-order RLE-encoded crop via nearest-neighbour resampling. + + Manipulates run lengths directly without decoding to a full 2D boolean + array. Delegates to :func:`_rle_split_cols`, :func:`_rle_scale_col`, + and :func:`_rle_join_cols`. + + The nearest-neighbour mapping ``src = floor(dst * src_size / dst_size)`` + is bit-exact with ``cv2.INTER_NEAREST``. + + Args: + rle: int32 array of F-order run lengths as produced by + :func:`~supervision.detection.utils.converters._mask_to_rle_counts`. + Starts with a ``False``-run count (may be 0). + crop_h: Height of the original crop. + crop_w: Width of the original crop. + new_crop_h: Height of the resized crop. + new_crop_w: Width of the resized crop. + + Returns: + int32 array of F-order run lengths for the resized crop, starting + with the ``False``-run count. + + Examples: + Upscale a 3x3 mask with a diagonal True stripe to 6x6: + + ```pycon + >>> import numpy as np + >>> from supervision.detection.compact_mask import _rle_resize + >>> from supervision.detection.utils.converters import ( + ... _mask_to_rle_counts, _rle_counts_to_mask, + ... ) + >>> mask = np.array([ + ... [True, False, False], + ... [False, True, False], + ... [False, False, True ], + ... ], dtype=bool) + >>> rle = _mask_to_rle_counts(mask) + >>> resized_rle = _rle_resize(rle, 3, 3, 6, 6) + >>> result = _rle_counts_to_mask(resized_rle, 6, 6) + >>> result.astype(int) + array([[1, 1, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0], + [0, 0, 1, 1, 0, 0], + [0, 0, 1, 1, 0, 0], + [0, 0, 0, 0, 1, 1], + [0, 0, 0, 0, 1, 1]]) + + ``` + """ + new_total = new_crop_h * new_crop_w + + if crop_h * crop_w == 0 or new_total == 0: + return np.array([0], dtype=np.int32) + if len(rle) == 1 or int(np.sum(rle[1::2])) == 0: + return np.array([new_total], dtype=np.int32) + if len(rle) == 2 and rle[0] == 0: + return np.array([0, new_total], dtype=np.int32) + + per_col = _rle_split_cols(rle, crop_h, crop_w) + + # cv2.INTER_NEAREST column mapping: src = floor(dst * src_w / dst_w) + col_map = (np.arange(new_crop_w) * crop_w // new_crop_w).astype(np.int32) + + # cv2.INTER_NEAREST row mapping: src = floor(dst * src_h / dst_h) + row_map = (np.arange(new_crop_h) * crop_h // new_crop_h).astype(np.int32) + + # Scale each unique source column once; reuse via cache for repeated cols. + col_cache: dict[int, list[int]] = {} + scaled_cols = [] + for src_c in col_map: + src_col = int(src_c) + if src_col not in col_cache: + col_cache[src_col] = _rle_scale_col(per_col[src_col], crop_h, row_map) + scaled_cols.append(col_cache[src_col]) + + return _rle_join_cols(scaled_cols, new_total) + + +# Fraction of (run_count / pixel_count) below which _rle_resize is used +# instead of the decode → cv2 → re-encode path. Sparse masks have few long +# runs; dense/complex masks approach 1 run per 2 pixels. +_L3_DENSITY_THRESHOLD: float = 0.25 +# Thread overhead outweighs gains below this mask count. +_PARALLEL_THRESHOLD: int = 8 +# Hard ceiling on each image dimension accepted by from_coco_rle, guarding +# against crafted payloads that allocate O(H x W) column lists. +_MAX_IMAGE_DIMENSION: int = 32768 +# Images at or below this pixel count use a fully-vectorised numpy dense-decode +# path inside from_coco_rle instead of the pure-Python column-split loop. +# Crossover measured at ~8-16 K px (128x128); threshold set at 128x128 = 16 384. +_SMALL_IMAGE_DENSE_THRESHOLD: int = 128 * 128 + + +def _resize_crop( + rle: npt.NDArray[np.int32], + orig_h: int, + orig_w: int, + new_h: int, + new_w: int, +) -> npt.NDArray[np.int32]: + """Resize one RLE crop to ``(new_h, new_w)``, choosing the fastest path. + + Dispatch order: + + 1. **All-False fast path** — returns a single False run; no decode. + 2. **L3 direct RLE path** — used when run density is below + :data:`_L3_DENSITY_THRESHOLD`; manipulates run lengths without + allocating a 2D array. + 3. **cv2 fallback** — decodes to ``uint8``, calls + ``cv2.resize(INTER_NEAREST)``, re-encodes; used for dense masks. + + Args: + rle: int32 run-length array for the source crop. + orig_h: Height of the source crop. + orig_w: Width of the source crop. + new_h: Target height. + new_w: Target width. + + Returns: + int32 RLE array for the resized crop. + """ + from supervision import _cv2 as cv2 + + # All-False: skip decode entirely. + if _rle_area(rle) == 0: + return np.array([new_h * new_w], dtype=np.int32) + + # L3: direct RLE arithmetic for sparse masks. + if len(rle) / max(1, orig_h * orig_w) < _L3_DENSITY_THRESHOLD: + return _rle_resize(rle, orig_h, orig_w, new_h, new_w) + + # cv2 fallback for dense masks. + crop = _rle_counts_to_mask(rle, orig_h, orig_w) + resized = cv2.resize( + crop.view(np.uint8), + (new_w, new_h), + interpolation=cv2.INTER_NEAREST, + ).astype(bool) + return _mask_to_rle_counts(resized) + + +class CompactMask: + """Memory-efficient crop-RLE mask storage for instance segmentation. + + Instead of storing N full ``(H, W)`` boolean arrays, :class:`CompactMask` + encodes each mask as a run-length sequence of its bounding-box crop. This + reduces memory from O(N·H·W) to roughly O(N·bbox_area), which is orders of + magnitude smaller for sparse masks on high-resolution images. + + The class exposes a duck-typed interface compatible with ``np.ndarray`` + masks used elsewhere in ``supervision``: + + * ``mask[int]`` → dense ``(H, W)`` bool array (annotators, converters). + * ``mask[slice | list | ndarray]`` → new :class:`CompactMask` (filtering). + * ``np.asarray(mask)`` → dense ``(N, H, W)`` bool array (numpy interop). + * ``mask.shape``, ``mask.dtype``, ``mask.area`` — match the dense API. + + :class:`CompactMask` is **not** a drop-in ``np.ndarray`` replacement. + When you need to call arbitrary ndarray methods (``astype``, ``reshape``, + ``ravel``, ``any``, ``all``, …) call :meth:`to_dense` first: + ``cm.to_dense().astype(np.uint8)``. :meth:`to_dense` is the single + explicit materialisation boundary. + + .. note:: **RLE encoding — COCO / pycocotools pixel-scan order** + + :class:`CompactMask` uses **column-major (Fortran-order, F-order)** + run-lengths scoped to each mask's bounding-box crop, matching the + pixel-scan order used by the COCO API (pycocotools). The crop scope + still differs from the full-image scope used by pycocotools, so a + :class:`CompactMask` RLE cannot be passed directly to + ``maskUtils.iou()`` or ``maskUtils.decode()`` without re-scoping to + the full canvas. Use :meth:`to_dense` to obtain a standard boolean + array for pycocotools interop. + + This scan order is part of CompactMask's internal RLE representation. + Switching from row-major (C-order) to column-major (F-order) is a + backward-incompatible format change for any persisted or serialized + :class:`CompactMask` state, including pickled objects and any + external storage of ``._rles``. Older stored RLE arrays will decode + incorrectly under the new convention. + + Migration note: load or decode legacy masks with the older version, + materialize them to dense boolean arrays, and then re-encode them + with the current version (for example via :meth:`to_dense` followed + by :meth:`from_dense`) before persisting them again. + + Args: + rles: List of N int32 run-length arrays. + crop_shapes: Array of shape ``(N, 2)`` — ``(crop_h, crop_w)`` per mask. + offsets: Array of shape ``(N, 2)`` — ``(x1, y1)`` bounding-box origins. + image_shape: ``(H, W)`` of the full image. + + Examples: + ```pycon + >>> import numpy as np + >>> from supervision.detection.compact_mask import CompactMask + >>> masks = np.zeros((2, 100, 100), dtype=bool) + >>> masks[0, 10:20, 10:20] = True + >>> masks[1, 50:70, 50:80] = True + >>> xyxy = np.array([[10, 10, 19, 19], [50, 50, 79, 69]], dtype=np.float32) + >>> cm = CompactMask.from_dense(masks, xyxy, image_shape=(100, 100)) + >>> len(cm) + 2 + >>> cm.shape + (2, 100, 100) + + ``` + """ + + __slots__ = ("_crop_shapes", "_image_shape", "_offsets", "_rles") + + def __init__( + self, + rles: list[npt.NDArray[np.int32]], + crop_shapes: npt.NDArray[np.int32], + offsets: npt.NDArray[np.int32], + image_shape: tuple[int, int], + ) -> None: + self._rles: list[npt.NDArray[np.int32]] = rles + self._crop_shapes: npt.NDArray[np.int32] = crop_shapes # (N,2): (h,w) + self._offsets: npt.NDArray[np.int32] = offsets # (N,2): (x1,y1) + self._image_shape: tuple[int, int] = image_shape # (H, W) + + # ------------------------------------------------------------------ + # Construction + # ------------------------------------------------------------------ + + @classmethod + def from_dense( + cls, + masks: npt.NDArray[np.bool_], + xyxy: npt.NDArray[np.number], + image_shape: tuple[int, int], + ) -> CompactMask: + """Create a :class:`CompactMask` from a dense ``(N, H, W)`` bool array. + + Bounding boxes are clipped to image bounds and interpreted in the + supervision ``xyxy`` convention (inclusive max coordinates). A + box with invalid ordering (``x2 < x1`` or ``y2 < y1``) is replaced by + a ``1x1`` all-False crop to avoid degenerate RLE. + + Args: + masks: Dense boolean mask array of shape ``(N, H, W)``. + xyxy: Bounding boxes of shape ``(N, 4)`` in ``[x1, y1, x2, y2]`` + format. + image_shape: ``(H, W)`` of the full image. + + Returns: + A new :class:`CompactMask` instance. + + Examples: + ```pycon + >>> import numpy as np + >>> from supervision.detection.compact_mask import CompactMask + >>> masks = np.zeros((1, 100, 100), dtype=bool) + >>> masks[0, 10:20, 10:20] = True + >>> xyxy = np.array([[10, 10, 19, 19]], dtype=np.float32) + >>> cm = CompactMask.from_dense(masks, xyxy, image_shape=(100, 100)) + >>> cm.shape + (1, 100, 100) + + ``` + """ + img_h, img_w = image_shape + num_masks = len(masks) + + if num_masks == 0: + return cls( + [], + np.empty((0, 2), dtype=np.int32), + np.empty((0, 2), dtype=np.int32), + image_shape, + ) + + rles: list[npt.NDArray[np.int32]] = [] + crop_shapes_list: list[tuple[int, int]] = [] + offsets_list: list[tuple[int, int]] = [] + + for mask_idx in range(num_masks): + x1, y1, x2, y2 = xyxy[mask_idx] + x1i, y1i, x2i, y2i = int(x1), int(y1), int(x2), int(y2) + x1c = int(max(0, min(x1i, img_w - 1))) + y1c = int(max(0, min(y1i, img_h - 1))) + crop: npt.NDArray[np.bool_] + + # supervision xyxy uses inclusive max coords, so slicing must add +1. + if ( + x2i < x1i + or y2i < y1i + or x2i < 0 + or y2i < 0 + or x1i >= img_w + or y1i >= img_h + ): + crop = np.zeros((1, 1), dtype=bool) + crop_h = 1 + crop_w = 1 + else: + x2c = int(max(0, min(x2i, img_w - 1))) + y2c = int(max(0, min(y2i, img_h - 1))) + crop = masks[mask_idx, y1c : y2c + 1, x1c : x2c + 1] + crop_h = y2c - y1c + 1 + crop_w = x2c - x1c + 1 + rles.append(_mask_to_rle_counts(crop)) + crop_shapes_list.append((crop_h, crop_w)) + offsets_list.append((x1c, y1c)) + + crop_shapes = np.array(crop_shapes_list, dtype=np.int32) + offsets = np.array(offsets_list, dtype=np.int32) + return cls(rles, crop_shapes, offsets, image_shape) + + @classmethod + def from_coco_rle( + cls, + rles: Sequence[Mapping[str, Any]], + xyxy: npt.NDArray[np.floating], + image_shape: tuple[int, int], + ) -> CompactMask: + """Create a :class:`CompactMask` from full-frame COCO RLE masks. + + Transcodes full-image COCO RLE payloads into the crop-scoped RLE format + used by :class:`CompactMask`. The conversion uses run-length arithmetic + scoped by ``xyxy`` boxes and does not materialise a dense ``(N, H, W)`` + mask stack. + + Args: + rles: Sequence of COCO RLE dictionaries. Each dictionary must contain + ``"size"`` as ``[height, width]`` and ``"counts"`` as compressed + counts (``str`` or ``bytes``) or uncompressed integer run lengths. + xyxy: Bounding boxes of shape ``(N, 4)`` in ``[x1, y1, x2, y2]`` + format. Max coordinates follow supervision's inclusive convention. + image_shape: ``(H, W)`` of the full image. This must match every RLE + ``"size"`` value. + + Returns: + A new :class:`CompactMask` instance. + + Raises: + ValueError: If the RLE payloads are malformed, are not aligned with + ``xyxy``, or their sizes/counts do not match ``image_shape``. + + Examples: + ```pycon + >>> import numpy as np + >>> from supervision.detection.compact_mask import CompactMask + >>> # 4x4 image with a 2x2 True block at the top-left corner. + >>> # Uncompressed F-order COCO counts: F=0, T=2, F=2, T=2, F=10 + >>> # (column-major: col0=[T,T,F,F], col1=[T,T,F,F], cols2-3 all F). + >>> rles = [{"size": [4, 4], "counts": [0, 2, 2, 2, 10]}] + >>> xyxy = np.array([[0, 0, 3, 3]], dtype=np.float32) + >>> cm = CompactMask.from_coco_rle(rles, xyxy, image_shape=(4, 4)) + >>> cm.shape + (1, 4, 4) + >>> cm.area.tolist() + [4] + + ``` + """ + img_h, img_w = (int(image_shape[0]), int(image_shape[1])) + if img_h <= 0 or img_w <= 0: + raise ValueError("image_shape must contain positive height and width.") + if img_h > _MAX_IMAGE_DIMENSION or img_w > _MAX_IMAGE_DIMENSION: + raise ValueError( + f"image_shape {(img_h, img_w)} exceeds the maximum allowed dimension " + f"of {_MAX_IMAGE_DIMENSION} pixels per side." + ) + + xyxy_arr = np.asarray(xyxy) + if xyxy_arr.shape != (len(rles), 4): + raise ValueError( + "xyxy must have shape (N, 4), where N matches the number of RLEs." + ) + + if len(rles) == 0: + return cls( + [], + np.empty((0, 2), dtype=np.int32), + np.empty((0, 2), dtype=np.int32), + (img_h, img_w), + ) + + crop_rles: list[npt.NDArray[np.int32]] = [] + crop_shapes_list: list[tuple[int, int]] = [] + offsets_list: list[tuple[int, int]] = [] + + for mask_idx, rle in enumerate(rles): + if not isinstance(rle, Mapping): + raise ValueError("Each RLE payload must be a mapping.") + if "size" not in rle or "counts" not in rle: + raise ValueError("Each RLE payload must contain 'size' and 'counts'.") + + try: + # COCO standard: size=[height, width] (h,w order per pycocotools spec) + rle_h, rle_w = rle["size"] + rle_h = int(rle_h) + rle_w = int(rle_w) + except (TypeError, ValueError) as exc: + raise ValueError("RLE size must be [height, width].") from exc + + if (rle_h, rle_w) != (img_h, img_w): + raise ValueError( + f"RLE size {(rle_h, rle_w)} must match image_shape " + f"{(img_h, img_w)}." + ) + + counts = _coco_rle_counts_to_array(rle["counts"]) + if int(np.sum(counts, dtype=np.int64)) != img_h * img_w: + raise ValueError( + "The sum of COCO RLE counts must match the image area." + ) + + x1, y1, x2, y2 = xyxy_arr[mask_idx] + x1i, y1i, x2i, y2i = int(x1), int(y1), int(x2), int(y2) + x1c = max(0, min(x1i, img_w - 1)) + y1c = max(0, min(y1i, img_h - 1)) + + if ( + x2i < x1i + or y2i < y1i + or x2i < 0 + or y2i < 0 + or x1i >= img_w + or y1i >= img_h + ): + crop_rles.append(np.array([1], dtype=np.int32)) + crop_shapes_list.append((1, 1)) + offsets_list.append((x1c, y1c)) + continue + + x2c = max(0, min(x2i, img_w - 1)) + y2c = max(0, min(y2i, img_h - 1)) + crop_h = y2c - y1c + 1 + crop_w = x2c - x1c + 1 + + if img_h * img_w <= _SMALL_IMAGE_DENSE_THRESHOLD: + # Small image: vectorised numpy decode avoids the O(img_w)-column + # Python loop. Decode RLE to flat F-order bool, extract crop, and + # re-encode directly. + ends = np.cumsum(counts, dtype=np.int64) + starts = ends - counts.astype(np.int64) + # Mark True runs (odd-indexed) via difference-array decode (O(R)). + true_starts = starts[1::2] + true_ends = ends[1::2] + if true_starts.size > 0: + indicator = np.zeros(img_h * img_w + 1, dtype=np.int32) + np.add.at(indicator, true_starts, 1) + np.add.at(indicator, true_ends, -1) + # cumsum in int32 avoids int8 overflow; cast to uint8 (0/1). + flat = np.cumsum(indicator[:-1], dtype=np.int32).astype(np.uint8) + else: + flat = np.zeros(img_h * img_w, dtype=np.uint8) + # Extract crop: reshape to (img_w, img_h) F-order view, slice. + flat_crop = flat.reshape(img_w, img_h)[ + x1c : x2c + 1, y1c : y2c + 1 + ].ravel() + # RLE-encode the flat crop: find value-change positions. + change_pos = np.where(np.diff(flat_crop.view(np.int8)))[0] + 1 + boundaries = np.concatenate([[0], change_pos, [len(flat_crop)]]) + run_lens = np.diff(boundaries) + if flat_crop[0]: + run_lens = np.concatenate([[0], run_lens]) + crop_rle_arr = run_lens.astype(np.int32) + else: + cols = _rle_split_cols(counts, img_h, img_w, x_start=x1c, x_stop=x2c) + selected_columns = [_rle_trim_col_runs(col, y1c, y2c) for col in cols] + crop_rle_arr = _rle_join_cols(selected_columns, crop_h * crop_w) + + crop_rles.append(crop_rle_arr) + crop_shapes_list.append((crop_h, crop_w)) + offsets_list.append((x1c, y1c)) + + crop_shapes = np.array(crop_shapes_list, dtype=np.int32) + offsets = np.array(offsets_list, dtype=np.int32) + return cls(crop_rles, crop_shapes, offsets, (img_h, img_w)) + + # ------------------------------------------------------------------ + # Materialisation + # ------------------------------------------------------------------ + + def to_dense(self) -> npt.NDArray[np.bool_]: + """Materialise all masks as a dense ``(N, H, W)`` boolean array. + + Returns: + Boolean array of shape ``(N, H, W)``. + + Examples: + ```pycon + >>> import numpy as np + >>> from supervision.detection.compact_mask import CompactMask + >>> masks = np.zeros((1, 50, 50), dtype=bool) + >>> masks[0, 10:20, 10:30] = True + >>> xyxy = np.array([[10, 10, 29, 19]], dtype=np.float32) + >>> cm = CompactMask.from_dense(masks, xyxy, image_shape=(50, 50)) + >>> cm.to_dense().shape + (1, 50, 50) + + ``` + """ + num_masks = len(self._rles) + img_h, img_w = self._image_shape + result: npt.NDArray[np.bool_] = np.zeros((num_masks, img_h, img_w), dtype=bool) + for mask_idx in range(num_masks): + crop_h, crop_w = ( + int(self._crop_shapes[mask_idx, 0]), + int(self._crop_shapes[mask_idx, 1]), + ) + x1, y1 = int(self._offsets[mask_idx, 0]), int(self._offsets[mask_idx, 1]) + crop = _rle_counts_to_mask(self._rles[mask_idx], crop_h, crop_w) + result[mask_idx, y1 : y1 + crop_h, x1 : x1 + crop_w] = crop + return result + + def crop(self, index: int) -> npt.NDArray[np.bool_]: + """Decode a single mask crop without allocating the full image array. + + This is an O(crop_area) operation — ideal for annotators that only + need the cropped region. + + Args: + index: Index of the mask to decode. + + Returns: + Boolean array of shape ``(crop_h, crop_w)``. + + Examples: + ```pycon + >>> import numpy as np + >>> from supervision.detection.compact_mask import CompactMask + >>> masks = np.zeros((1, 100, 100), dtype=bool) + >>> masks[0, 20:30, 10:40] = True + >>> xyxy = np.array([[10, 20, 39, 29]], dtype=np.float32) + >>> cm = CompactMask.from_dense(masks, xyxy, image_shape=(100, 100)) + >>> cm.crop(0).shape + (10, 30) + + ``` + """ + crop_h = int(self._crop_shapes[index, 0]) + crop_w = int(self._crop_shapes[index, 1]) + return _rle_counts_to_mask(self._rles[index], crop_h, crop_w) + + # ------------------------------------------------------------------ + # Sequence / array protocol + # ------------------------------------------------------------------ + + def __len__(self) -> int: + """Return the number of masks. + + Returns: + Number of masks N. + + Examples: + ```pycon + >>> from supervision.detection.compact_mask import CompactMask + >>> import numpy as np + >>> cm = CompactMask( + ... [], np.empty((0, 2), dtype=np.int32), + ... np.empty((0, 2), dtype=np.int32), (100, 100)) + >>> len(cm) + 0 + + ``` + """ + return len(self._rles) + + def __iter__(self) -> Iterator[npt.NDArray[np.bool_]]: + """Iterate over masks as dense ``(H, W)`` boolean arrays.""" + for mask_idx in range(len(self)): + yield self[mask_idx] + + @property + def shape(self) -> tuple[int, int, int]: + """Return ``(N, H, W)`` matching the dense mask convention. + + Returns: + Tuple ``(N, H, W)``. + + Examples: + ```pycon + >>> from supervision.detection.compact_mask import CompactMask + >>> import numpy as np + >>> cm = CompactMask( + ... [], np.empty((0, 2), dtype=np.int32), + ... np.empty((0, 2), dtype=np.int32), (480, 640)) + >>> cm.shape + (0, 480, 640) + + ``` + """ + img_h, img_w = self._image_shape + return (len(self), img_h, img_w) + + @property + def image_shape(self) -> tuple[int, int]: + """Return ``(H, W)`` of the full image this mask is scoped to. + + Returns: + Tuple ``(H, W)``. + + Examples: + ```pycon + >>> from supervision.detection.compact_mask import CompactMask + >>> import numpy as np + >>> cm = CompactMask( + ... [], np.empty((0, 2), dtype=np.int32), + ... np.empty((0, 2), dtype=np.int32), (480, 640)) + >>> cm.image_shape + (480, 640) + + ``` + """ + return self._image_shape + + @property + def offsets(self) -> npt.NDArray[np.int32]: + """Return per-mask crop origins as ``(x1, y1)`` integer offsets. + + Returns: + Array of shape ``(N, 2)`` with ``int32`` offsets. + + Examples: + ```pycon + >>> import numpy as np + >>> from supervision.detection.compact_mask import CompactMask + >>> masks = np.zeros((1, 10, 10), dtype=bool) + >>> masks[0, 2:4, 3:5] = True + >>> xyxy = np.array([[3, 2, 4, 3]], dtype=np.float32) + >>> cm = CompactMask.from_dense(masks, xyxy, image_shape=(10, 10)) + >>> cm.offsets.tolist() + [[3, 2]] + + ``` + """ + return self._offsets + + @property + def bbox_xyxy(self) -> npt.NDArray[np.int32]: + """Return per-mask inclusive bounding boxes in ``xyxy`` format. + + Boxes are derived from crop metadata: + ``x2 = x1 + crop_w - 1``, ``y2 = y1 + crop_h - 1``. + + Returns: + Array of shape ``(N, 4)`` with ``int32`` boxes + ``[x1, y1, x2, y2]``. + + Examples: + ```pycon + >>> import numpy as np + >>> from supervision.detection.compact_mask import CompactMask + >>> masks = np.zeros((1, 10, 10), dtype=bool) + >>> masks[0, 2:5, 3:7] = True + >>> xyxy = np.array([[3, 2, 6, 4]], dtype=np.float32) + >>> cm = CompactMask.from_dense(masks, xyxy, image_shape=(10, 10)) + >>> cm.bbox_xyxy.tolist() + [[3, 2, 6, 4]] + + ``` + """ + if len(self) == 0: + return np.empty((0, 4), dtype=np.int32) + + x1: npt.NDArray[np.int32] = self._offsets[:, 0] + y1: npt.NDArray[np.int32] = self._offsets[:, 1] + x2: npt.NDArray[np.int32] = x1 + self._crop_shapes[:, 1] - 1 + y2: npt.NDArray[np.int32] = y1 + self._crop_shapes[:, 0] - 1 + return np.column_stack((x1, y1, x2, y2)).astype(np.int32, copy=False) + + @property + def dtype(self) -> np.dtype[np.bool_]: + """Return ``np.dtype(bool)`` — always. + + Returns: + ``np.dtype(bool)``. + + Examples: + ```pycon + >>> from supervision.detection.compact_mask import CompactMask + >>> import numpy as np + >>> cm = CompactMask( + ... [], np.empty((0, 2), dtype=np.int32), + ... np.empty((0, 2), dtype=np.int32), (100, 100)) + >>> cm.dtype + dtype('bool') + + ``` + """ + return np.dtype(bool) + + @property + def area(self) -> npt.NDArray[np.int64]: + """Compute the area (``True`` pixel count) of each mask. + + Note: + The implementation iterates over the N individual RLE arrays in a + Python loop (one :func:`_rle_area` call per mask). This is negligible + for typical N, but callers processing thousands of detections per + frame should be aware of the per-mask Python-level overhead. + + Returns: + int64 array of shape ``(N,)`` with per-mask pixel counts. + + Examples: + ```pycon + >>> import numpy as np + >>> from supervision.detection.compact_mask import CompactMask + >>> masks = np.zeros((2, 100, 100), dtype=bool) + >>> masks[0, 0:10, 0:10] = True # 100 pixels + >>> masks[1, 0:5, 0:5] = True # 25 pixels + >>> xyxy = np.array([[0, 0, 9, 9], [0, 0, 4, 4]], dtype=np.float32) + >>> cm = CompactMask.from_dense(masks, xyxy, image_shape=(100, 100)) + >>> cm.area.tolist() + [100, 25] + + ``` + """ + return np.array([_rle_area(rle) for rle in self._rles], dtype=np.int64) + + def sum( + self, axis: int | tuple[int, ...] | None = None + ) -> npt.NDArray[np.int64] | np.int64: + """NumPy-compatible sum with a fast path for per-mask area. + + When ``axis=(1, 2)``, returns the per-mask True-pixel count via + :attr:`area` without materialising the full dense array. + + Args: + axis: Axis or axes to sum over. + + Returns: + Sum result matching NumPy semantics. + + Examples: + ```pycon + >>> import numpy as np + >>> from supervision.detection.compact_mask import CompactMask + >>> masks = np.zeros((1, 10, 10), dtype=bool) + >>> masks[0, 0:3, 0:3] = True + >>> xyxy = np.array([[0, 0, 2, 2]], dtype=np.float32) + >>> cm = CompactMask.from_dense(masks, xyxy, image_shape=(10, 10)) + >>> cm.sum(axis=(1, 2)).tolist() + [9] + + ``` + """ + if axis == (1, 2): + return self.area + return cast(npt.NDArray[np.int64] | np.int64, self.to_dense().sum(axis=axis)) + + @overload + def __getitem__(self, index: int | np.integer) -> npt.NDArray[np.bool_]: ... + + @overload + def __getitem__( + self, + index: slice + | list[int] + | list[bool] + | npt.NDArray[np.int_] + | npt.NDArray[np.bool_], + ) -> CompactMask: ... + + def __getitem__( + self, + index: ( + int + | np.integer + | slice + | list[int] + | list[bool] + | npt.NDArray[np.int_] + | npt.NDArray[np.bool_] + ), + ) -> npt.NDArray[np.bool_] | CompactMask: + """Index into the mask collection. + + * ``int`` → dense ``(H, W)`` bool array (for annotators, iterators). + * ``slice | list | ndarray`` → new :class:`CompactMask` (for filtering). + + Args: + index: An integer returns a dense ``(H, W)`` mask. Any other + supported index type returns a new :class:`CompactMask`. + + Returns: + Dense ``(H, W)`` ``np.ndarray`` for integer index, or a new + :class:`CompactMask` for all other index types. + + Examples: + ```pycon + >>> import numpy as np + >>> from supervision.detection.compact_mask import CompactMask + >>> masks = np.zeros((3, 20, 20), dtype=bool) + >>> xyxy = np.array( + ... [[0,0,5,5],[5,5,10,10],[10,10,15,15]], dtype=np.float32) + >>> cm = CompactMask.from_dense(masks, xyxy, image_shape=(20, 20)) + >>> cm[0].shape # int → dense (H, W) + (20, 20) + >>> len(cm[[0, 2]]) # list → CompactMask + 2 + + ``` + """ + if isinstance(index, (int, np.integer)): + idx = int(index) + img_h, img_w = self._image_shape + result: npt.NDArray[np.bool_] = np.zeros((img_h, img_w), dtype=bool) + crop_h = int(self._crop_shapes[idx, 0]) + crop_w = int(self._crop_shapes[idx, 1]) + x1 = int(self._offsets[idx, 0]) + y1 = int(self._offsets[idx, 1]) + crop = _rle_counts_to_mask(self._rles[idx], crop_h, crop_w) + result[y1 : y1 + crop_h, x1 : x1 + crop_w] = crop + return result + + if isinstance(index, slice): + selected_rles = [rle.copy() for rle in self._rles[index]] + return CompactMask( + selected_rles, + self._crop_shapes[index].copy(), + self._offsets[index].copy(), + self._image_shape, + ) + + # Boolean selectors and fancy index → convert to integer positions first. + if isinstance(index, np.ndarray) and index.dtype == bool: + idx_arr = np.where(index)[0] + elif isinstance(index, list) and all( + isinstance(item, (bool, np.bool_)) for item in index + ): + idx_arr = np.flatnonzero(np.asarray(index, dtype=bool)) + else: + idx_arr = np.asarray(list(index), dtype=np.intp) + + new_rles = [self._rles[int(mask_idx)].copy() for mask_idx in idx_arr] + new_crop_shapes: npt.NDArray[np.int32] = self._crop_shapes[idx_arr].copy() + new_offsets: npt.NDArray[np.int32] = self._offsets[idx_arr].copy() + return CompactMask(new_rles, new_crop_shapes, new_offsets, self._image_shape) + + def __array__( + self, dtype: np.dtype[np.generic] | None = None + ) -> npt.NDArray[np.generic]: + """NumPy interop: materialise as a dense ``(N, H, W)`` array. + + Called by ``np.asarray(compact_mask)`` and similar NumPy functions. + + Args: + dtype: Optional dtype to cast the result to. + + Returns: + Dense boolean array of shape ``(N, H, W)``. + + Examples: + ```pycon + >>> import numpy as np + >>> from supervision.detection.compact_mask import CompactMask + >>> masks = np.zeros((1, 10, 10), dtype=bool) + >>> xyxy = np.array([[0, 0, 5, 5]], dtype=np.float32) + >>> cm = CompactMask.from_dense(masks, xyxy, image_shape=(10, 10)) + >>> np.asarray(cm).shape + (1, 10, 10) + + ``` + """ + result = self.to_dense() + if dtype is not None: + return result.astype(dtype) + return result + + def __eq__(self, other: object) -> bool: + """Element-wise equality with another :class:`CompactMask` or ndarray. + + Args: + other: Another :class:`CompactMask` or ``np.ndarray``. + + Returns: + ``True`` if all masks are pixel-identical. + + Examples: + ```pycon + >>> import numpy as np + >>> from supervision.detection.compact_mask import CompactMask + >>> masks = np.zeros((1, 10, 10), dtype=bool) + >>> xyxy = np.array([[0, 0, 5, 5]], dtype=np.float32) + >>> cm1 = CompactMask.from_dense(masks, xyxy, image_shape=(10, 10)) + >>> cm2 = CompactMask.from_dense(masks, xyxy, image_shape=(10, 10)) + >>> cm1 == cm2 + True + + ``` + """ + if isinstance(other, CompactMask): + return bool(np.array_equal(self.to_dense(), other.to_dense())) + if isinstance(other, np.ndarray): + return bool(np.array_equal(self.to_dense(), other)) + return NotImplemented + + # ------------------------------------------------------------------ + # Collection utilities + # ------------------------------------------------------------------ + + @staticmethod + def merge(masks_list: list[CompactMask]) -> CompactMask: + """Concatenate multiple :class:`CompactMask` objects into one. + + All inputs must have the same ``image_shape``. + + Args: + masks_list: Non-empty list of :class:`CompactMask` objects. + + Returns: + A new :class:`CompactMask` containing every mask from the inputs, + in order. + + Raises: + ValueError: If ``masks_list`` is empty or image shapes differ. + + Examples: + ```pycon + >>> import numpy as np + >>> from supervision.detection.compact_mask import CompactMask + >>> masks1 = np.zeros((2, 50, 50), dtype=bool) + >>> masks2 = np.zeros((3, 50, 50), dtype=bool) + >>> xyxy1 = np.array([[0,0,10,10],[10,10,20,20]], dtype=np.float32) + >>> xyxy2 = np.array( + ... [[0,0,5,5],[5,5,10,10],[10,10,15,15]], dtype=np.float32) + >>> cm1 = CompactMask.from_dense(masks1, xyxy1, image_shape=(50, 50)) + >>> cm2 = CompactMask.from_dense(masks2, xyxy2, image_shape=(50, 50)) + >>> len(CompactMask.merge([cm1, cm2])) + 5 + + ``` + """ + if not masks_list: + raise ValueError("Cannot merge an empty list of CompactMask objects.") + + image_shape = masks_list[0]._image_shape + for cm in masks_list[1:]: + if cm._image_shape != image_shape: + raise ValueError( + f"Cannot merge CompactMask objects with different image shapes: " + f"{image_shape} vs {cm._image_shape}" + ) + + # list.extend is a C-level call and avoids the per-element Python + # bytecode overhead of a flat list comprehension. This matters under + # GIL contention when multiple threads call merge concurrently. + new_rles: list[npt.NDArray[np.int32]] = [] + for cm in masks_list: + new_rles.extend(cm._rles) + + # np.concatenate handles (0, 2) arrays correctly. + # No .astype() needed — _crop_shapes and _offsets are already int32. + new_crop_shapes: npt.NDArray[np.int32] = np.concatenate( + [cm._crop_shapes for cm in masks_list], axis=0 + ) + new_offsets: npt.NDArray[np.int32] = np.concatenate( + [cm._offsets for cm in masks_list], axis=0 + ) + + return CompactMask(new_rles, new_crop_shapes, new_offsets, image_shape) + + def repack(self) -> CompactMask: + """Re-encode all masks using tight bounding boxes. + + When the original ``xyxy`` boxes are padded or loose — common with + object-detector outputs and full-image boxes used in tests — each RLE + crop encodes more background (``False``) pixels than necessary. This + method decodes every crop, trims it to the minimal rectangle that + contains all ``True`` pixels, and re-encodes. All-``False`` masks are + normalised to a ``1x1`` all-``False`` crop. + + The call is O(sum of crop areas) — suitable as a one-time cleanup + after accumulating many merges (e.g. after + :class:`~supervision.detection.tools.inference_slicer.InferenceSlicer` + tiles are merged). + + Returns: + A new :class:`CompactMask` with minimal-area crops and updated + offsets. + + Examples: + ```pycon + >>> import numpy as np + >>> from supervision.detection.compact_mask import CompactMask + >>> masks = np.zeros((1, 10, 10), dtype=bool) + >>> masks[0, 3:7, 3:7] = True + >>> # Deliberately loose bbox: covers the full image. + >>> xyxy = np.array([[0, 0, 9, 9]], dtype=np.float32) + >>> cm = CompactMask.from_dense(masks, xyxy, image_shape=(10, 10)) + >>> repacked = cm.repack() + >>> repacked.offsets.tolist() # tight origin: x1=3, y1=3 + [[3, 3]] + + ``` + """ + num_masks = len(self._rles) + if num_masks == 0: + return CompactMask( + [], + np.empty((0, 2), dtype=np.int32), + np.empty((0, 2), dtype=np.int32), + self._image_shape, + ) + + new_rles: list[npt.NDArray[np.int32]] = [] + new_crop_shapes_list: list[tuple[int, int]] = [] + new_offsets_list: list[tuple[int, int]] = [] + + for mask_idx in range(num_masks): + crop = self.crop(mask_idx) + x1_off = int(self._offsets[mask_idx, 0]) + y1_off = int(self._offsets[mask_idx, 1]) + + rows_any = np.any(crop, axis=1) + cols_any = np.any(crop, axis=0) + + if not rows_any.any(): + # All-False: normalise to 1x1 to avoid zero-sized arrays. + new_rles.append(_mask_to_rle_counts(np.zeros((1, 1), dtype=bool))) + new_crop_shapes_list.append((1, 1)) + new_offsets_list.append((x1_off, y1_off)) + continue + + y_indices = np.where(rows_any)[0] + x_indices = np.where(cols_any)[0] + y_min, y_max = int(y_indices[0]), int(y_indices[-1]) + x_min, x_max = int(x_indices[0]), int(x_indices[-1]) + + tight = crop[y_min : y_max + 1, x_min : x_max + 1] + new_rles.append(_mask_to_rle_counts(tight)) + new_crop_shapes_list.append((y_max - y_min + 1, x_max - x_min + 1)) + new_offsets_list.append((x1_off + x_min, y1_off + y_min)) + + return CompactMask( + new_rles, + np.array(new_crop_shapes_list, dtype=np.int32), + np.array(new_offsets_list, dtype=np.int32), + self._image_shape, + ) + + # ------------------------------------------------------------------ + # Slicer support + # ------------------------------------------------------------------ + + def with_offset( + self, + dx: int, + dy: int, + new_image_shape: tuple[int, int], + ) -> CompactMask: + """Return a new :class:`CompactMask` with adjusted offsets and image shape. + + Used by :class:`~supervision.detection.tools.inference_slicer.InferenceSlicer` + to relocate tile-local masks into full-image coordinates without + materialising the dense ``(N, H, W)`` array. + + Args: + dx: Pixels to add to every mask's ``x1`` offset. + dy: Pixels to add to every mask's ``y1`` offset. + new_image_shape: ``(H, W)`` of the full (destination) image. + + Returns: + New :class:`CompactMask` with updated offsets and image shape. + Crops are clipped to stay inside ``new_image_shape``; masks fully + outside are represented as ``1x1`` all-False crops. + + Examples: + ```pycon + >>> import numpy as np + >>> from supervision.detection.compact_mask import CompactMask + >>> masks = np.zeros((1, 20, 20), dtype=bool) + >>> xyxy = np.array([[5, 5, 15, 15]], dtype=np.float32) + >>> cm = CompactMask.from_dense(masks, xyxy, image_shape=(20, 20)) + >>> cm2 = cm.with_offset(100, 200, new_image_shape=(400, 400)) + >>> cm2.offsets[0].tolist() + [105, 205] + + ``` + """ + new_h, new_w = new_image_shape + if new_h <= 0 or new_w <= 0: + raise ValueError("new_image_shape must contain positive dimensions") + + num_masks = len(self) + if num_masks == 0: + return CompactMask( + [], + np.empty((0, 2), dtype=np.int32), + np.empty((0, 2), dtype=np.int32), + new_image_shape, + ) + + # Vectorised bounds check: compute every new [x1,y1,x2,y2] at once. + # For the common case (InferenceSlicer tiles that fit fully inside the + # new canvas) this catches the "no clipping needed" path in O(N) numpy + # without touching any RLE data. + new_offsets: npt.NDArray[np.int32] = self._offsets + np.array( + [dx, dy], dtype=np.int32 + ) + x1s = new_offsets[:, 0] + y1s = new_offsets[:, 1] + x2s = x1s + self._crop_shapes[:, 1] - 1 + y2s = y1s + self._crop_shapes[:, 0] - 1 + + needs_clip: npt.NDArray[np.bool_] = ( + (x1s < 0) | (y1s < 0) | (x2s >= new_w) | (y2s >= new_h) + ) + + if not needs_clip.any(): + # Fast path: pure offset arithmetic, no decode/re-encode needed. + return CompactMask( + list(self._rles), + self._crop_shapes.copy(), + new_offsets, + new_image_shape, + ) + + # Slow path: only decode+clip+re-encode the masks that actually overflow. + out_rles: list[npt.NDArray[np.int32]] = [] + out_crop_shapes: list[tuple[int, int]] = [] + out_offsets_list: list[tuple[int, int]] = [] + + for mask_idx in range(num_masks): + x1 = int(x1s[mask_idx]) + y1 = int(y1s[mask_idx]) + x2 = int(x2s[mask_idx]) + y2 = int(y2s[mask_idx]) + + if not needs_clip[mask_idx]: + out_rles.append(self._rles[mask_idx]) + out_crop_shapes.append( + ( + int(self._crop_shapes[mask_idx, 0]), + int(self._crop_shapes[mask_idx, 1]), + ) + ) + out_offsets_list.append((x1, y1)) + continue + + ix1 = max(0, x1) + iy1 = max(0, y1) + ix2 = min(new_w - 1, x2) + iy2 = min(new_h - 1, y2) + + if ix1 > ix2 or iy1 > iy2: + anchor_x = min(max(x1, 0), new_w - 1) + anchor_y = min(max(y1, 0), new_h - 1) + out_rles.append(_mask_to_rle_counts(np.zeros((1, 1), dtype=bool))) + out_crop_shapes.append((1, 1)) + out_offsets_list.append((anchor_x, anchor_y)) + continue + + crop = self.crop(mask_idx) + clipped = crop[iy1 - y1 : iy2 - y1 + 1, ix1 - x1 : ix2 - x1 + 1] + out_rles.append(_mask_to_rle_counts(clipped)) + out_crop_shapes.append((iy2 - iy1 + 1, ix2 - ix1 + 1)) + out_offsets_list.append((ix1, iy1)) + + return CompactMask( + out_rles, + np.array(out_crop_shapes, dtype=np.int32), + np.array(out_offsets_list, dtype=np.int32), + new_image_shape, + ) + + # ------------------------------------------------------------------ + # Resize + # ------------------------------------------------------------------ + + def resize(self, new_image_shape: tuple[int, int]) -> CompactMask: + """Return a new CompactMask scaled to a different image resolution. + + Each crop mask is resized with nearest-neighbour interpolation. + Sparse masks use direct RLE arithmetic (:func:`_rle_resize`); dense + masks fall back to ``cv2.resize(INTER_NEAREST)``. Offsets and crop + dimensions are scaled proportionally to the new image size. + + Performance notes: + + * Coordinate arithmetic is fully vectorised (no Python loop over N). + * All-``False`` crops skip decode/resize entirely. + * For N >= 8, resize runs in a thread pool — NumPy and OpenCV + release the GIL so crops execute in parallel on multi-core CPUs. + + Args: + new_image_shape: ``(H, W)`` of the target image. + + Returns: + New :class:`CompactMask` with updated ``image_shape``, scaled + offsets, scaled crop shapes, and re-encoded RLE crops. + + Raises: + ValueError: If any dimension in *new_image_shape* is ``<= 0``. + + Examples: + ```pycon + >>> import numpy as np + >>> from supervision.detection.compact_mask import CompactMask + >>> masks = np.zeros((1, 100, 100), dtype=bool) + >>> masks[0, 20:40, 30:60] = True + >>> xyxy = np.array([[30, 20, 59, 39]], dtype=np.float32) + >>> cm = CompactMask.from_dense(masks, xyxy, image_shape=(100, 100)) + >>> small = cm.resize((50, 50)) + >>> small.shape + (1, 50, 50) + >>> small.offsets[0].tolist() + [15, 10] + + ``` + """ + from concurrent.futures import ThreadPoolExecutor + + new_h, new_w = new_image_shape + if new_h <= 0 or new_w <= 0: + raise ValueError("new_image_shape must contain positive dimensions") + + # fast path — identity resize; list() creates a new container but the + # individual RLE numpy arrays are shared (shallow copy). Callers must + # not mutate returned RLE arrays in-place. + if (new_h, new_w) == self._image_shape: + return CompactMask( + list(self._rles), + self._crop_shapes.copy(), + self._offsets.copy(), + new_image_shape, + ) + + # empty guard + if len(self) == 0: + return CompactMask( + [], + np.empty((0, 2), dtype=np.int32), + np.empty((0, 2), dtype=np.int32), + new_image_shape, + ) + + img_h, img_w = self._image_shape + sx = new_w / img_w + sy = new_h / img_h + + # L1 — vectorised coordinate arithmetic; no Python loop over N masks. + x1s = self._offsets[:, 0].astype(np.float64) + y1s = self._offsets[:, 1].astype(np.float64) + x2s = x1s + self._crop_shapes[:, 1] - 1 # inclusive right edge + y2s = y1s + self._crop_shapes[:, 0] - 1 # inclusive bottom edge + + new_x1s = np.clip(np.round(x1s * sx), 0, new_w - 1).astype(np.int32) + new_y1s = np.clip(np.round(y1s * sy), 0, new_h - 1).astype(np.int32) + new_x2s = np.clip(np.round(x2s * sx), 0, new_w - 1).astype(np.int32) + new_y2s = np.clip(np.round(y2s * sy), 0, new_h - 1).astype(np.int32) + new_crop_ws: npt.NDArray[np.int32] = np.maximum( + 1, new_x2s - new_x1s + 1 + ).astype(np.int32) + new_crop_hs: npt.NDArray[np.int32] = np.maximum( + 1, new_y2s - new_y1s + 1 + ).astype(np.int32) + + # L2b — parallel per-crop resize; NumPy and OpenCV release the GIL. + orig_crop_hs = self._crop_shapes[:, 0] + orig_crop_ws = self._crop_shapes[:, 1] + + args = [ + ( + self._rles[i], + int(orig_crop_hs[i]), + int(orig_crop_ws[i]), + int(new_crop_hs[i]), + int(new_crop_ws[i]), + ) + for i in range(len(self)) + ] + + n = len(self) + if n >= _PARALLEL_THRESHOLD: + with ThreadPoolExecutor(max_workers=min(n, os.cpu_count() or 4)) as pool: + new_rles: list[npt.NDArray[np.int32]] = list( + pool.map(lambda a: _resize_crop(*a), args) + ) + else: + new_rles = [_resize_crop(*a) for a in args] + + new_crop_shapes = np.column_stack((new_crop_hs, new_crop_ws)).astype(np.int32) + new_offsets = np.column_stack((new_x1s, new_y1s)).astype(np.int32) + return CompactMask(new_rles, new_crop_shapes, new_offsets, new_image_shape) diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/core.py b/.venv/lib/python3.12/site-packages/supervision/detection/core.py new file mode 100644 index 0000000000000000000000000000000000000000..a38bae76cc3123f5802972f319eb359b0e1dc512 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/detection/core.py @@ -0,0 +1,3604 @@ +from __future__ import annotations + +import warnings +from collections.abc import Iterator +from dataclasses import dataclass, field +from functools import reduce +from typing import Any, cast + +import numpy as np +import numpy.typing as npt +from deprecate import deprecated, void + +from supervision.config import ( + CLASS_NAME_DATA_FIELD, + ORIENTED_BOX_COORDINATES, +) +from supervision.detection._geometry_dispatch import detection_area, detection_iou +from supervision.detection.compact_mask import CompactMask +from supervision.detection.tools.transformers import ( + process_transformers_detection_result, + process_transformers_v4_segmentation_result, + process_transformers_v5_segmentation_result, +) +from supervision.detection.utils._typing import ( + _DetectionDataType, + _DetectionDataValueType, + _MetadataType, +) +from supervision.detection.utils.boxes import ( + _oriented_box_anchors, + _sort_box_corners, + xyxyxyxy_to_xyxy, +) +from supervision.detection.utils.converters import ( + mask_to_xyxy, + polygon_to_mask, + rle_to_mask, + xywh_to_xyxy, +) +from supervision.detection.utils.internal import ( + extract_ultralytics_masks, + get_data_item, + is_data_equal, + is_metadata_equal, + merge_data, + merge_metadata, + process_roboflow_result, +) +from supervision.detection.utils.iou_and_nms import ( + OverlapMetric, + box_non_max_merge, + box_non_max_suppression, + box_soft_non_max_suppression, + mask_non_max_merge, + mask_non_max_suppression, + mask_soft_non_max_suppression, + oriented_box_non_max_merge, + oriented_box_non_max_suppression, +) +from supervision.detection.utils.masks import ( + calculate_masks_centroids, +) +from supervision.detection.vlm import ( + LMM, + VLM, + _validate_vlm_parameters, + from_deepseek_vl_2, + from_florence_2, + from_google_gemini_2_0, + from_google_gemini_2_5, + from_google_gemini_3_5, + from_moondream, + from_paligemma, + from_qwen_2_5_vl, + from_qwen_3_vl, +) +from supervision.geometry.core import Position +from supervision.utils.internal import ( + SupervisionWarnings, + get_instance_variables, + warn_deprecated, +) +from supervision.validators import ( + _validate_data, + _validate_detections_fields, + _validate_resolution, +) + + +@dataclass +class Detections: + """ + The `sv.Detections` class in the Supervision library standardizes results from + various object detection and segmentation models into a consistent format. This + class simplifies data manipulation and filtering, providing a uniform API for + integration with Supervision [trackers](/trackers/), [annotators](/latest/detection/annotators/), and [tools](/detection/tools/line_zone/). + + === "RF-DETR" + + [RF-DETR](https://github.com/roboflow/rf-detr)'s `predict` method returns a + `sv.Detections` object directly, so no conversion step is needed. + + ```python + from supervision import _cv2 as cv2 + import supervision as sv + from rfdetr import RFDETRMedium + + model = RFDETRMedium() + image = cv2.imread("") + detections = model.predict(image[:, :, ::-1]) + ``` + + === "Inference" + + Use [`sv.Detections.from_inference`](/detection/core/#supervision.detection.core.Detections.from_inference) + method, which accepts model results from both detection and segmentation models. + + ```python + from supervision import _cv2 as cv2 + import supervision as sv + from inference import get_model + + model = get_model(model_id="rfdetr-small") + image = cv2.imread("") + results = model.infer(image)[0] + detections = sv.Detections.from_inference(results) + ``` + + === "Ultralytics" + + Use [`sv.Detections.from_ultralytics`](/detection/core/#supervision.detection.core.Detections.from_ultralytics) + method, which accepts model results from both detection and segmentation models. + + ```python + from supervision import _cv2 as cv2 + import supervision as sv + from ultralytics import YOLO + + model = YOLO("yolov8n.pt") + image = cv2.imread("") + results = model(image)[0] + detections = sv.Detections.from_ultralytics(results) + ``` + + === "Transformers" + + Use [`sv.Detections.from_transformers`](/detection/core/#supervision.detection.core.Detections.from_transformers) + method, which accepts model results from both detection and segmentation models. + + ```python + import torch + import supervision as sv + from PIL import Image + from transformers import DetrImageProcessor, DetrForObjectDetection + + processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50") + model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50") + + image = Image.open("") + inputs = processor(images=image, return_tensors="pt") + + with torch.no_grad(): + outputs = model(**inputs) + + width, height = image.size + target_size = torch.tensor([[height, width]]) + results = processor.post_process_object_detection( + outputs=outputs, target_sizes=target_size)[0] + detections = sv.Detections.from_transformers( + transformers_results=results, + id2label=model.config.id2label) + ``` + + Attributes: + xyxy: An array of shape `(n, 4)` containing + the bounding boxes coordinates in format `[x1, y1, x2, y2]` + mask: An array of shape `(n, H, W)` containing the segmentation masks + (`bool` data type), or `None` when masks are not available, or as + :class:`~supervision.detection.compact_mask.CompactMask`. + confidence: An array of shape `(n,)` containing the confidence scores + of the detections, or `None` when confidence values are not available. + class_id: An array of shape `(n,)` containing the class ids of the + detections, or `None` when class ids are not available. + tracker_id: An array of shape `(n,)` containing the tracker ids of the + detections, or `None` when tracker ids are not available. + data: A dictionary containing additional + data where each key is a string representing the data type, and the value + is either a NumPy array or a list of corresponding data. + metadata: A dictionary containing collection-level metadata + that applies to the entire set of detections. This may include information such + as the video name, camera parameters, timestamp, or other global metadata. + """ # noqa: E501 // docs + + xyxy: npt.NDArray[np.number] + mask: npt.NDArray[np.bool_] | CompactMask | None = None + confidence: npt.NDArray[np.floating] | None = None + class_id: npt.NDArray[np.integer] | None = None + tracker_id: npt.NDArray[np.integer] | None = None + data: _DetectionDataType = field(default_factory=dict) + metadata: _MetadataType = field(default_factory=dict) + + def __post_init__(self) -> None: + _validate_detections_fields( + xyxy=self.xyxy, + mask=self.mask, + confidence=self.confidence, + class_id=self.class_id, + tracker_id=self.tracker_id, + data=self.data, + ) + + def __len__(self) -> int: + """ + Returns the number of detections in the Detections object. + """ + return len(self.xyxy) + + def __iter__( + self, + ) -> Iterator[ + tuple[ + npt.NDArray[np.number], + npt.NDArray[np.bool_] | None, + np.generic | None, + np.generic | None, + np.generic | None, + _DetectionDataType, + ] + ]: + """ + Iterates over the Detections object and yield a tuple of + `(xyxy, mask, confidence, class_id, tracker_id, data)` for each detection. + """ + for i in range(len(self.xyxy)): + yield ( + self.xyxy[i], + self.mask[i] if self.mask is not None else None, + self.confidence[i] if self.confidence is not None else None, + self.class_id[i] if self.class_id is not None else None, + self.tracker_id[i] if self.tracker_id is not None else None, + get_data_item(self.data, i), + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Detections): + return NotImplemented + + def array_equal_or_none( + a: npt.NDArray[np.generic] | None, + b: npt.NDArray[np.generic] | None, + ) -> bool: + if a is None or b is None: + return a is b + return bool(np.array_equal(a, b)) + + def mask_equal( + a: npt.NDArray[np.generic] | CompactMask | None, + b: npt.NDArray[np.generic] | CompactMask | None, + ) -> bool: + if a is None or b is None: + return a is b + if isinstance(a, CompactMask): + return bool(a == b) + if isinstance(b, CompactMask): + return bool(b == a) + return bool(np.array_equal(a, b)) + + return all( + [ + np.array_equal(self.xyxy, other.xyxy), + mask_equal(self.mask, other.mask), + array_equal_or_none(self.class_id, other.class_id), + array_equal_or_none(self.confidence, other.confidence), + array_equal_or_none(self.tracker_id, other.tracker_id), + is_data_equal(self.data, other.data), + is_metadata_equal(self.metadata, other.metadata), + ] + ) + + @classmethod + def from_yolov5(cls, yolov5_results: Any) -> Detections: + """ + Creates a Detections instance from a + [YOLOv5](https://github.com/ultralytics/yolov5) inference result. + + Args: + yolov5_results: The output Detections instance from YOLOv5. + + Returns: + A new Detections object. + + Example: + ```python + from supervision import _cv2 as cv2 + import torch + import supervision as sv + + image = cv2.imread("") + model = torch.hub.load('ultralytics/yolov5', 'yolov5s') + result = model(image) + detections = sv.Detections.from_yolov5(result) + ``` + """ + yolov5_detections_predictions = yolov5_results.pred[0].cpu().cpu().numpy() + + return cls( + xyxy=yolov5_detections_predictions[:, :4], + confidence=yolov5_detections_predictions[:, 4], + class_id=yolov5_detections_predictions[:, 5].astype(int), + ) + + @classmethod + def from_ultralytics(cls, ultralytics_results: Any) -> Detections: + """ + Creates a `sv.Detections` instance from a + [YOLOv8](https://github.com/ultralytics/ultralytics) inference result. + + !!! Note + + `from_ultralytics` is compatible with + [detection](https://docs.ultralytics.com/tasks/detect/), + [segmentation](https://docs.ultralytics.com/tasks/segment/), and + [OBB](https://docs.ultralytics.com/tasks/obb/) models. + + Args: + ultralytics_results: The output Results instance from Ultralytics. + + Returns: + A new Detections object. + + Example: + ```python + from supervision import _cv2 as cv2 + import supervision as sv + from ultralytics import YOLO + + image = cv2.imread("") + model = YOLO('yolov8s.pt') + results = model(image)[0] + detections = sv.Detections.from_ultralytics(results) + ``` + """ + + if hasattr(ultralytics_results, "obb") and ultralytics_results.obb is not None: + class_id = ultralytics_results.obb.cls.cpu().numpy().astype(int) + class_names = np.array([ultralytics_results.names[i] for i in class_id]) + oriented_box_coordinates = ultralytics_results.obb.xyxyxyxy.cpu().numpy() + return cls( + xyxy=ultralytics_results.obb.xyxy.cpu().numpy(), + confidence=ultralytics_results.obb.conf.cpu().numpy(), + class_id=class_id, + tracker_id=( + ultralytics_results.obb.id.int().cpu().numpy() + if ultralytics_results.obb.id is not None + else None + ), + data={ + ORIENTED_BOX_COORDINATES: oriented_box_coordinates, + CLASS_NAME_DATA_FIELD: class_names, + }, + ) + + if hasattr(ultralytics_results, "boxes") and ultralytics_results.boxes is None: + masks = extract_ultralytics_masks(ultralytics_results) + if masks is None: + empty = cls.empty() + empty.data = {CLASS_NAME_DATA_FIELD: np.empty(0, dtype=str)} + return empty + return cls( + xyxy=mask_to_xyxy(masks), + mask=masks, + class_id=np.zeros(len(masks), dtype=int), + ) + + if ( + hasattr(ultralytics_results, "boxes") + and ultralytics_results.boxes is not None + ): + class_id = ultralytics_results.boxes.cls.cpu().numpy().astype(int) + class_names = np.array([ultralytics_results.names[i] for i in class_id]) + return cls( + xyxy=ultralytics_results.boxes.xyxy.cpu().numpy(), + confidence=ultralytics_results.boxes.conf.cpu().numpy(), + class_id=class_id, + mask=extract_ultralytics_masks(ultralytics_results), + tracker_id=( + ultralytics_results.boxes.id.int().cpu().numpy() + if ultralytics_results.boxes.id is not None + else None + ), + data={CLASS_NAME_DATA_FIELD: class_names}, + ) + + empty = cls.empty() + empty.data = {CLASS_NAME_DATA_FIELD: np.empty(0, dtype=str)} + return empty + + @classmethod + def from_yolo_nas(cls, yolo_nas_results: Any) -> Detections: + """ + Creates a Detections instance from a + [YOLO-NAS](https://github.com/Deci-AI/super-gradients/blob/master/YOLONAS.md) + inference result. + + Args: + yolo_nas_results: The output Results instance from YOLO-NAS. + ImageDetectionPrediction is coming from + 'super_gradients.training.models.prediction_results'. + + Returns: + A new Detections object. + + Example: + ```python + from supervision import _cv2 as cv2 + from super_gradients.training import models + import supervision as sv + + image = cv2.imread("") + model = models.get('yolo_nas_l', pretrained_weights="coco") + + result = list(model.predict(image, conf=0.35))[0] + detections = sv.Detections.from_yolo_nas(result) + ``` + """ + if np.asarray(yolo_nas_results.prediction.bboxes_xyxy).shape[0] == 0: + return cls.empty() + + return cls( + xyxy=yolo_nas_results.prediction.bboxes_xyxy, + confidence=yolo_nas_results.prediction.confidence, + class_id=yolo_nas_results.prediction.labels.astype(int), + ) + + @classmethod + def from_tensorflow( + cls, tensorflow_results: dict[str, Any], resolution_wh: tuple[int, int] + ) -> Detections: + """ + Creates a Detections instance from a + [Tensorflow Hub](https://www.tensorflow.org/hub/tutorials/tf2_object_detection) + inference result. + + Args: + tensorflow_results: Raw output dict from a TensorFlow Hub + object-detection model. Must contain: + ``"detection_boxes"`` (shape ``[1, N, 4]``, normalized + ``[ymin, xmin, ymax, xmax]``), ``"detection_scores"`` + (shape ``[1, N]``), and ``"detection_classes"`` + (shape ``[1, N]``). + resolution_wh: The input image resolution as `(width, height)`. + Bounding boxes from Tensorflow are normalized and are scaled + to absolute coordinates using this resolution. + + Returns: + A new Detections object. + + Note: + TensorFlow Hub object-detection models return bounding boxes + normalized as ``[ymin, xmin, ymax, xmax]``. This method rescales + them to absolute pixel coordinates and reorders them to ``xyxy`` + (``[xmin, ymin, xmax, ymax]``) before constructing the + :class:`Detections` object. + + Example: + ```python + import tensorflow as tf + import tensorflow_hub as hub + import numpy as np + from supervision import _cv2 as cv2 + + module_handle = "https://tfhub.dev/tensorflow/centernet/hourglass_512x512_kpts/1" + model = hub.load(module_handle) + img = np.array(cv2.imread("")) + result = model(img) + detections = sv.Detections.from_tensorflow( + result, resolution_wh=(img.shape[1], img.shape[0]) + ) + ``` + """ + + # Tensorflow returns normalized boxes as [ymin, xmin, ymax, xmax], so the + # y coordinates (cols 0, 2) scale by height and x (cols 1, 3) by width. + # `.numpy()` may share memory with the source tensor, so copy before the + # in-place scaling to avoid mutating the caller's result / double-scaling. + boxes = tensorflow_results["detection_boxes"][0].numpy().copy() + boxes[:, [0, 2]] *= resolution_wh[1] + boxes[:, [1, 3]] *= resolution_wh[0] + boxes = boxes[:, [1, 0, 3, 2]] + return cls( + xyxy=boxes, + confidence=tensorflow_results["detection_scores"][0].numpy(), + class_id=tensorflow_results["detection_classes"][0].numpy().astype(int), + ) + + @classmethod + def from_deepsparse(cls, deepsparse_results: Any) -> Detections: + """ + Creates a Detections instance from a + [DeepSparse](https://github.com/neuralmagic/deepsparse) + inference result. + + Args: + deepsparse_results: The output Results instance from DeepSparse. + + Returns: + A new Detections object. + + Example: + ```python + import supervision as sv + from deepsparse import Pipeline + + yolo_pipeline = Pipeline.create( + task="yolo", + model_path = "zoo:cv/detection/yolov5-l/pytorch/ultralytics/coco/pruned80_quant-none" + ) + result = yolo_pipeline() + detections = sv.Detections.from_deepsparse(result) + ``` + """ # noqa: E501 // docs + + if np.asarray(deepsparse_results.boxes[0]).shape[0] == 0: + return cls.empty() + + return cls( + xyxy=np.array(deepsparse_results.boxes[0]), + confidence=np.array(deepsparse_results.scores[0]), + class_id=np.array(deepsparse_results.labels[0]).astype(float).astype(int), + ) + + @classmethod + def from_mmdetection(cls, mmdet_results: Any) -> Detections: + """ + Creates a Detections instance from a + [mmdetection](https://github.com/open-mmlab/mmdetection) and + [mmyolo](https://github.com/open-mmlab/mmyolo) inference result. + + Args: + mmdet_results: The output Results instance from MMDetection. + + Returns: + A new Detections object. + + Example: + ```python + from supervision import _cv2 as cv2 + import supervision as sv + from mmdet.apis import init_detector, inference_detector + + image = cv2.imread("") + model = init_detector("", "", device="") + + result = inference_detector(model, image) + detections = sv.Detections.from_mmdetection(result) + ``` + """ + + return cls( + xyxy=mmdet_results.pred_instances.bboxes.cpu().numpy(), + confidence=mmdet_results.pred_instances.scores.cpu().numpy(), + class_id=mmdet_results.pred_instances.labels.cpu().numpy().astype(int), + mask=( + mmdet_results.pred_instances.masks.cpu().numpy() + if "masks" in mmdet_results.pred_instances + else None + ), + ) + + @classmethod + def from_transformers( + cls, + transformers_results: dict[str, Any], + id2label: dict[int, str] | None = None, + ) -> Detections: + """ + Creates a Detections instance from object detection or panoptic, semantic + and instance segmentation + [Transformer](https://github.com/huggingface/transformers) inference result. + + Args: + transformers_results: Inference results from your Transformers model. + This can be either a dictionary containing valuable outputs like + `scores`, `labels`, `boxes`, `masks`, `segments_info`, and + `segmentation`, or a `torch.Tensor` holding a segmentation map + where values represent class IDs. + id2label: A dictionary mapping class IDs to labels, typically part of + the `transformers` model configuration. If provided, the resulting + dictionary will include class names. + + Returns: + A new Detections object. + + Example: + ```python + import torch + import supervision as sv + from PIL import Image + from transformers import DetrImageProcessor, DetrForObjectDetection + + processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50") + model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50") + + image = Image.open("") + inputs = processor(images=image, return_tensors="pt") + + with torch.no_grad(): + outputs = model(**inputs) + + width, height = image.size + target_size = torch.tensor([[height, width]]) + results = processor.post_process_object_detection( + outputs=outputs, target_sizes=target_size)[0] + + detections = sv.Detections.from_transformers( + transformers_results=results, + id2label=model.config.id2label + ) + ``` + """ + + if ( + transformers_results.__class__.__name__ == "Tensor" + or "segmentation" in transformers_results + ): + return cls( + **process_transformers_v5_segmentation_result( + transformers_results, id2label + ) + ) + + if "masks" in transformers_results or "png_string" in transformers_results: + return cls( + **process_transformers_v4_segmentation_result( + transformers_results, id2label + ) + ) + + if "boxes" in transformers_results: + return cls( + **process_transformers_detection_result(transformers_results, id2label) + ) + + else: + raise ValueError( + "The provided Transformers results do not contain any valid fields." + " Expected fields are 'boxes', 'masks', 'segments_info' or" + " 'segmentation'." + ) + + @classmethod + def from_detectron2(cls, detectron2_results: Any) -> Detections: + """ + Create a Detections object from the + [Detectron2](https://github.com/facebookresearch/detectron2) inference result. + + Args: + detectron2_results: The output of a + Detectron2 model containing instances with prediction data. + + Returns: + A Detections object containing the bounding boxes, + class IDs, and confidences of the predictions. + + Example: + ```python + from supervision import _cv2 as cv2 + import supervision as sv + from detectron2.engine import DefaultPredictor + from detectron2.config import get_cfg + + + image = cv2.imread("") + cfg = get_cfg() + cfg.merge_from_file("") + cfg.MODEL.WEIGHTS = "" + predictor = DefaultPredictor(cfg) + + result = predictor(image) + detections = sv.Detections.from_detectron2(result) + ``` + """ + + return cls( + xyxy=detectron2_results["instances"].pred_boxes.tensor.cpu().numpy(), + confidence=detectron2_results["instances"].scores.cpu().numpy(), + mask=( + detectron2_results["instances"].pred_masks.cpu().numpy() + if hasattr(detectron2_results["instances"], "pred_masks") + else None + ), + class_id=detectron2_results["instances"] + .pred_classes.cpu() + .numpy() + .astype(int), + ) + + @classmethod + def from_inference( + cls, + roboflow_result: dict[str, Any] | Any, + *, + compact_masks: bool = False, + ) -> Detections: + """ + Create a `sv.Detections` object from the [Roboflow](https://roboflow.com/) + API inference result or the [Inference](https://inference.roboflow.com/) + package results. This method extracts bounding boxes, class IDs, + confidences, and class names from the Roboflow API result and encapsulates + them into a Detections object. + + Args: + roboflow_result: The result from the + Roboflow API or Inference package containing predictions. + compact_masks: When `True`, return segmentation masks as + :class:`~supervision.detection.compact_mask.CompactMask`. + The default `False` preserves the existing dense NumPy mask + representation. + + Warning: + When `compact_masks=True`, the crop policy depends on how + each prediction encodes its mask: + + - Native size-matched COCO-RLE (the RLE `size` equals the + image size) is **cropped to the detector bounding box** + (`xyxy`). For instance-segmentation models the detector + box may not tightly bound the mask, so pixels beyond the + box boundary are silently dropped. + - Polygon-derived masks (`points`) and size-mismatched + COCO-RLE masks (decoded, then resized to the image) are + retained **full-frame** and lose no pixels. + + Because only the box-cropped path is lossy, + `from_inference(r)` and + `from_inference(r, compact_masks=True)` can return masks + with different areas and IoU **only** for native + size-matched COCO-RLE predictions. Use `compact_masks=True` + only when the memory savings outweigh the boundary loss on + that path. + + Returns: + A Detections object containing the bounding boxes, class IDs, + and confidences of the predictions. + `detections.data["class_name"]` is always present as a + string-dtype NumPy array aligned with the detections; it is + empty (shape `(0,)`, dtype str) when `predictions` is empty + or absent. `detections.tracker_id` is `None` when no + predictions carry a tracker ID, or when only a subset do + (mixed batch) — in that case all tracker IDs are dropped to + preserve alignment with the bounding boxes. Similarly, + `detections.mask` is `None` when no predictions include mask + data, or when only a subset carry masks — all masks are dropped + to preserve xyxy alignment. + When `compact_masks=True` and all predictions carry mask data, + `detections.mask` is a + :class:`~supervision.detection.compact_mask.CompactMask` rather + than a dense boolean array. + + Example: + ```python + from supervision import _cv2 as cv2 + import supervision as sv + from inference import get_model + + image = cv2.imread("") + model = get_model(model_id="yolov8s-640") + + result = model.infer(image)[0] + detections = sv.Detections.from_inference(result) + compact_detections = sv.Detections.from_inference( + result, compact_masks=True + ) + ``` + """ + if hasattr(roboflow_result, "dict"): + roboflow_result = roboflow_result.dict(exclude_none=True, by_alias=True) + elif hasattr(roboflow_result, "json"): + roboflow_result = roboflow_result.json() + masks: npt.NDArray[np.bool_] | CompactMask | None + # Design note (ADR): the `compact_masks` flag changes the runtime type of + # `detections.mask` from `NDArray[bool_]` to `CompactMask`, so every mask + # consumer must branch on `isinstance(detections.mask, CompactMask)`. A + # typed factory / `mask_format=` enum would be cleaner but would require a + # deprecation cycle if introduced later. + if compact_masks: + xyxy, confidence, class_id, masks, trackers, data = process_roboflow_result( + roboflow_result=roboflow_result, compact_masks=True + ) + else: + xyxy, confidence, class_id, masks, trackers, data = process_roboflow_result( + roboflow_result=roboflow_result + ) + + if np.asarray(xyxy).shape[0] == 0: + empty_detection = cls.empty() + empty_detection.data = data + return empty_detection + + return cls( + xyxy=xyxy, + confidence=confidence, + class_id=class_id, + mask=masks, + tracker_id=trackers, + data=data, + ) + + @classmethod + def from_sam(cls, sam_result: list[dict[str, Any]]) -> Detections: + """ + Creates a Detections instance from + [Segment Anything Model](https://github.com/facebookresearch/segment-anything) + inference result. + + Args: + sam_result: The output Results instance from SAM. + + Returns: + A new Detections object. + + Example: + ```python + import supervision as sv + from segment_anything import ( + sam_model_registry, + SamAutomaticMaskGenerator + ) + + sam_model_reg = sam_model_registry[MODEL_TYPE] + sam = sam_model_reg(checkpoint=CHECKPOINT_PATH).to(device=DEVICE) + mask_generator = SamAutomaticMaskGenerator(sam) + sam_result = mask_generator.generate(IMAGE) + detections = sv.Detections.from_sam(sam_result=sam_result) + ``` + """ + + sorted_generated_masks = sorted( + sam_result, key=lambda x: x["area"], reverse=True + ) + if len(sorted_generated_masks) == 0: + return cls.empty() + + xywh = np.array([mask["bbox"] for mask in sorted_generated_masks]) + segmentations = [mask["segmentation"] for mask in sorted_generated_masks] + first_segmentation = segmentations[0] + + if all(isinstance(segmentation, np.ndarray) for segmentation in segmentations): + mask = np.stack(segmentations, axis=0) + elif all(isinstance(segmentation, dict) for segmentation in segmentations): + image_height, image_width = cast( + tuple[int, int], tuple(int(v) for v in first_segmentation["size"]) + ) + mask = np.stack( + [ + rle_to_mask( + segmentation["counts"], + (image_width, image_height), + ) + for segmentation in segmentations + ], + axis=0, + ) + else: + raise ValueError( + "SAM segmentations must all be dense arrays or COCO RLE dictionaries." + ) + + xyxy = xywh_to_xyxy(xywh=xywh) + return cls(xyxy=xyxy, mask=mask) + + @classmethod + def from_sam3( + cls, sam3_result: dict[str, Any] | Any, resolution_wh: tuple[int, int] + ) -> Detections: + """ + Creates a Detections instance from + [SAM 3](https://github.com/facebookresearch/sam3) inference result. + Supports both PVS and PCS SAM3 segmentation formats. + + Args: + sam3_result: The output result from SAM 3 inference, either + Sam3PromptResult from inference package or dict containing + prompt_results with polygon predictions. + resolution_wh: The width and height of the image used for mask + generation. + + Returns: + A new Detections object. The `class_id` field contains the prompt + index for each polygon. + + Example: + ```python + from supervision import _cv2 as cv2 + import supervision as sv + from inference.models.sam3 import SegmentAnything3 + from inference.core.entities.requests.sam3 import Sam3Prompt + + image = cv2.imread("") + model = SegmentAnything3( + model_id="sam3/sam3_final", + api_key="" + ) + + prompts = [ + Sam3Prompt(type="text", text="car"), + Sam3Prompt(type="text", text="tire"), + ] + + result = model.segment_image( + image=image, + prompts=prompts, + output_prob_thresh=0.5, + format="polygon" + ) + + height, width = image.shape[:2] + detections = sv.Detections.from_sam3( + sam3_result=result, + resolution_wh=(width, height) + ) + ``` + """ + width, height = _validate_resolution(resolution_wh) + + masks = [] + confidences = [] + class_ids = [] + + if isinstance(sam3_result, dict): + prompt_results = sam3_result.get("prompt_results", []) + if not prompt_results and "predictions" in sam3_result: + prompt_results = [ + {"predictions": sam3_result["predictions"], "prompt_index": 0} + ] + else: + prompt_results = getattr(sam3_result, "prompt_results", []) + if not prompt_results and hasattr(sam3_result, "predictions"): + prompt_results = [ + { + "predictions": getattr(sam3_result, "predictions"), + "prompt_index": 0, + } + ] + + for i, prompt_result in enumerate(prompt_results): + if isinstance(prompt_result, dict): + predictions = prompt_result.get("predictions", []) + prompt_index = prompt_result.get("prompt_index", i) + else: + predictions = getattr(prompt_result, "predictions", []) + prompt_index = getattr(prompt_result, "prompt_index", i) + + for prediction in predictions: + if isinstance(prediction, dict): + prediction_format = prediction.get("format") + if prediction_format and prediction_format != "polygon": + continue + pred_masks = prediction.get("masks", []) + confidence = prediction.get("confidence", 1.0) + else: + prediction_format = getattr(prediction, "format", None) + if prediction_format and prediction_format != "polygon": + continue + pred_masks = getattr(prediction, "masks", []) + confidence = getattr(prediction, "confidence", 1.0) + + if not pred_masks: + continue + + full_mask: npt.NDArray[np.bool_] = np.zeros((height, width), dtype=bool) + for poly in pred_masks: + polygon = np.array(poly, dtype=np.int32) + mask = polygon_to_mask( + polygon=polygon, resolution_wh=(width, height) + ) + mask = mask.astype(bool, copy=False) + np.logical_or(full_mask, mask, out=full_mask) + + masks.append(full_mask) + confidences.append(confidence) + class_ids.append(prompt_index) + + if not masks: + return cls.empty() + + masks_np = np.stack(masks, axis=0) + xyxy = mask_to_xyxy(masks_np) + + return cls( + xyxy=xyxy.astype(np.float32), + mask=masks_np, + confidence=np.array(confidences, dtype=np.float32), + class_id=np.array(class_ids, dtype=int), + ) + + @classmethod + def from_azure_analyze_image( + cls, azure_result: dict[str, Any], class_map: dict[int, str] | None = None + ) -> Detections: + """ + Creates a Detections instance from [Azure Image Analysis 4.0]( + https://learn.microsoft.com/en-us/azure/ai-services/computer-vision/ + concept-object-detection-40). + + Args: + azure_result: The result from Azure Image Analysis. It should + contain detected objects and their bounding box coordinates. + class_map: A mapping of class IDs to class names. If None, a new + mapping is created dynamically. + + Returns: + A new Detections object. + + Example: + ```python + import requests + import supervision as sv + + image = open(input, "rb").read() + + endpoint = "https://.cognitiveservices.azure.com/" + subscription_key = "" + + headers = { + "Content-Type": "application/octet-stream", + "Ocp-Apim-Subscription-Key": subscription_key + } + + response = requests.post(endpoint, + headers=self.headers, + data=image + ).json() + + detections = sv.Detections.from_azure_analyze_image(response) + ``` + """ + if "error" in azure_result: + raise ValueError( + f"Azure API returned an error {azure_result['error']['message']}" + ) + + xyxy, confidences, class_ids = [], [], [] + + is_dynamic_mapping = class_map is None + if class_map is None: + class_map = {} + + inverted_map: dict[str, int] = {value: key for key, value in class_map.items()} + + for detection in azure_result["objectsResult"]["values"]: + bbox = detection["boundingBox"] + + tags = detection["tags"] + + x0 = bbox["x"] + y0 = bbox["y"] + x1 = x0 + bbox["w"] + y1 = y0 + bbox["h"] + + selected_tag: dict[str, Any] | None = None + selected_class_id: int | None = None + for tag in sorted( + tags, key=lambda candidate: candidate["confidence"], reverse=True + ): + class_name = tag["name"] + class_id_val = inverted_map.get(class_name, None) + + if is_dynamic_mapping and class_id_val is None: + class_id_val = len(inverted_map) + inverted_map[class_name] = class_id_val + + if class_id_val is not None: + selected_tag = tag + selected_class_id = class_id_val + break + + if selected_tag is None: + if tags: + warnings.warn( + "Azure detection skipped because none of its tags matched " + "the provided class_map.", + category=SupervisionWarnings, + stacklevel=2, + ) + continue + + xyxy.append([x0, y0, x1, y1]) + confidences.append(selected_tag["confidence"]) + class_ids.append(cast(int, selected_class_id)) + + if len(xyxy) == 0: + return Detections.empty() + + return cls( + xyxy=np.array(xyxy), + class_id=np.array(class_ids), + confidence=np.array(confidences), + ) + + @classmethod + def from_paddledet(cls, paddledet_result: Any) -> Detections: + """ + Creates a Detections instance from + [PaddleDetection](https://github.com/PaddlePaddle/PaddleDetection) + inference result. + + Args: + paddledet_result: The output Results instance from PaddleDet. + + Returns: + A new Detections object. + + Example: + ```python + import supervision as sv + import paddle + from ppdet.engine import Trainer + from ppdet.core.workspace import load_config + + weights = () + config = () + + cfg = load_config(config) + trainer = Trainer(cfg, mode='test') + trainer.load_weights(weights) + + paddledet_result = trainer.predict([images])[0] + + detections = sv.Detections.from_paddledet(paddledet_result) + ``` + """ + + if np.asarray(paddledet_result["bbox"][:, 2:6]).shape[0] == 0: + return cls.empty() + + return cls( + xyxy=paddledet_result["bbox"][:, 2:6], + confidence=paddledet_result["bbox"][:, 1], + class_id=paddledet_result["bbox"][:, 0].astype(int), + ) + + @classmethod + def from_lmm( + cls, lmm: LMM | str, result: str | dict[str, Any], **kwargs: Any + ) -> Detections: + """ + !!! deprecated "Deprecated" + `Detections.from_lmm` is **deprecated** and will be removed in `supervision-0.31.0`. + Please use `Detections.from_vlm` instead. + + Creates a Detections object from the given result string based on the specified + Large Multimodal Model (LMM). + + | Name | Enum (sv.LMM) | Tasks | Required parameters | Optional parameters | + |---------------------|----------------------|-------------------------|-----------------------------|---------------------| + | PaliGemma | `PALIGEMMA` | detection | `resolution_wh` | `classes` | + | PaliGemma 2 | `PALIGEMMA` | detection | `resolution_wh` | `classes` | + | Qwen2.5-VL | `QWEN_2_5_VL` | detection | `resolution_wh`, `input_wh` | `classes` | + | Qwen3-VL | `QWEN_3_VL` | detection | `resolution_wh` | `classes` | + | Google Gemini 2.0 | `GOOGLE_GEMINI_2_0` | detection | `resolution_wh` | `classes` | + | Google Gemini 2.5 | `GOOGLE_GEMINI_2_5` | detection, segmentation | `resolution_wh` | `classes` | + | Google Gemini 3.5 | `GOOGLE_GEMINI_3_5` | detection, segmentation | `resolution_wh` | `classes` | + | Moondream | `MOONDREAM` | detection | `resolution_wh` | | + | DeepSeek-VL2 | `DEEPSEEK_VL_2` | detection | `resolution_wh` | `classes` | + | Qwen3-VL | `QWEN_3_VL` | detection | `resolution_wh` | `classes` | + + Args: + lmm: The type of LMM (Large Multimodal Model) to use. + result: The result string containing the detection data. + **kwargs: Additional keyword arguments required by the specified LMM. + + Returns: + A new Detections object. + + Raises: + ValueError: If the LMM is invalid, required arguments are missing, or + disallowed arguments are provided. + ValueError: If the specified LMM is not supported. + + !!! example "PaliGemma" + ```python + + import supervision as sv + + paligemma_result = " cat" + detections = sv.Detections.from_lmm( + sv.LMM.PALIGEMMA, + paligemma_result, + resolution_wh=(1000, 1000), + classes=['cat', 'dog'] + ) + detections.xyxy + # array([[250., 250., 750., 750.]]) + + detections.class_id + # array([0]) + + detections.data + # {'class_name': array(['cat'], dtype='" + } + }, + { + "text": "Detect all the cats and dogs in the image..." + } + ] + } + ] + } + ``` + To get the best results from Google Gemini 2.0, use the following prompt. + + ``` + Detect all the cats and dogs in the image. The box_2d should be + [ymin, xmin, ymax, xmax] normalized to 0-1000. + ``` + + ```python + import supervision as sv + + gemini_response_text = \"\"\"```json + [ + {"box_2d": [543, 40, 728, 200], "label": "cat", "id": 1}, + {"box_2d": [653, 352, 820, 522], "label": "dog", "id": 2} + ] + ```\"\"\" + + detections = sv.Detections.from_lmm( + sv.LMM.GOOGLE_GEMINI_2_0, + gemini_response_text, + resolution_wh=(1000, 1000), + classes=['cat', 'dog'], + ) + + detections.xyxy + # array([[543., 40., 728., 200.], [653., 352., 820., 522.]]) + + detections.data + # {'class_name': array(['cat', 'dog'], dtype='\\n<|ref|>The giraffe at the front<|/ref|> + ``` + + **For visual grounding, use the following user prompt:** + + ``` + \\n<|grounding|>Detect the giraffes + ``` + + ```python + from PIL import Image + import supervision as sv + + deepseek_vl2_result = "<|ref|>The giraffe at the back<|/ref|><|det|>[[580, 270, 999, 904]]<|/det|><|ref|>The giraffe at the front<|/ref|><|det|>[[26, 31, 632, 998]]<|/det|><|end▁of▁sentence|>" + + detections = sv.Detections.from_vlm( + vlm=sv.VLM.DEEPSEEK_VL_2, result=deepseek_vl2_result, resolution_wh=image.size + ) + + detections.xyxy + # array([[ 420, 293, 724, 982], + # [ 18, 33, 458, 1084]]) + + detections.class_id + # array([0, 1]) + + detections.data + # {'class_name': array(['The giraffe at the back', 'The giraffe at the front'], dtype=' Detections: + """ + + Creates a Detections object from the given result string based on the specified + Vision Language Model (VLM). + + | Name | Enum (sv.VLM) | Tasks | Required parameters | Optional parameters | + |---------------------|----------------------|-------------------------|-----------------------------|---------------------| + | PaliGemma | `PALIGEMMA` | detection | `resolution_wh` | `classes` | + | PaliGemma 2 | `PALIGEMMA` | detection | `resolution_wh` | `classes` | + | Qwen2.5-VL | `QWEN_2_5_VL` | detection | `resolution_wh`, `input_wh` | `classes` | + | Qwen3-VL | `QWEN_3_VL` | detection | `resolution_wh` | `classes` | + | Google Gemini 2.0 | `GOOGLE_GEMINI_2_0` | detection | `resolution_wh` | `classes` | + | Google Gemini 2.5 | `GOOGLE_GEMINI_2_5` | detection, segmentation | `resolution_wh` | `classes` | + | Google Gemini 3.5 | `GOOGLE_GEMINI_3_5` | detection, segmentation | `resolution_wh` | `classes` | + | Moondream | `MOONDREAM` | detection | `resolution_wh` | | + | DeepSeek-VL2 | `DEEPSEEK_VL_2` | detection | `resolution_wh` | `classes` | + + Args: + vlm: The type of VLM (Vision Language Model) to use. + result: The result string containing the detection data. + **kwargs: Additional keyword arguments required by the specified VLM. + + Returns: + A new Detections object. + + Raises: + ValueError: If the VLM is invalid, required arguments are missing, or + disallowed arguments are provided. + ValueError: If the specified VLM is not supported. + + !!! example "PaliGemma" + ```pycon + >>> import supervision as sv + + >>> paligemma_result = " cat" + >>> detections = sv.Detections.from_vlm( + ... sv.VLM.PALIGEMMA, + ... paligemma_result, + ... resolution_wh=(1000, 1000), + ... classes=['cat', 'dog'] + ... ) + >>> detections.xyxy + array([[250., 250., 750., 750.]]) + >>> detections.class_id + array([0]) + >>> detections.data + {'class_name': array(['cat'], dtype='>> import supervision as sv + + >>> qwen_2_5_vl_result = \"\"\"```json + ... [ + ... {"bbox_2d": [139, 768, 315, 954], "label": "cat"}, + ... {"bbox_2d": [366, 679, 536, 849], "label": "dog"} + ... ] + ... ```\"\"\" + >>> detections = sv.Detections.from_vlm( + ... sv.VLM.QWEN_2_5_VL, + ... qwen_2_5_vl_result, + ... input_wh=(1000, 1000), + ... resolution_wh=(1000, 1000), + ... classes=['cat', 'dog'], + ... ) + >>> detections.xyxy + array([[139., 768., 315., 954.], + [366., 679., 536., 849.]]) + >>> detections.class_id + array([0, 1]) + >>> detections.data + {'class_name': array(['cat', 'dog'], dtype='>> import supervision as sv + + >>> qwen_3_vl_result = \"\"\"```json + ... [ + ... {"bbox_2d": [139, 768, 315, 954], "label": "cat"}, + ... {"bbox_2d": [366, 679, 536, 849], "label": "dog"} + ... ] + ... ```\"\"\" + >>> detections = sv.Detections.from_vlm( + ... sv.VLM.QWEN_3_VL, + ... qwen_3_vl_result, + ... resolution_wh=(1000, 1000), + ... classes=['cat', 'dog'], + ... ) + >>> detections.xyxy + array([[139., 768., 315., 954.], + [366., 679., 536., 849.]]) + >>> detections.class_id + array([0, 1]) + >>> detections.data + {'class_name': array(['cat', 'dog'], dtype='>> import supervision as sv + + >>> gemini_response_text = \"\"\"```json + ... [ + ... {"box_2d": [543, 40, 728, 200], "label": "cat", "id": 1}, + ... {"box_2d": [653, 352, 820, 522], "label": "dog", "id": 2} + ... ] + ... ```\"\"\" + + >>> detections = sv.Detections.from_vlm( + ... sv.VLM.GOOGLE_GEMINI_2_0, + ... gemini_response_text, + ... resolution_wh=(1000, 1000), + ... classes=['cat', 'dog'], + ... ) + >>> detections.xyxy + array([[ 40., 543., 200., 728.], + [352., 653., 522., 820.]]) + >>> detections.data + {'class_name': array(['cat', 'dog'], dtype='>> detections.class_id + array([0, 1]) + + ``` + + !!! example "Gemini 2.5" + + ??? tip "Prompt engineering" + + To get the best results from Google Gemini 2.5, use the following prompt. + + This prompt is designed to detect all visible objects in the image, + including small, distant, or partially visible ones, and to return + tight bounding boxes. + + According to the [Gemini API documentation on image prompts]( + https://ai.google.dev/gemini-api/docs/vision?hl=en), + when using a single image with text, place the text prompt after the image + part in the `contents` array. For example, with the `google-genai` client: + + ```python + response = model.generate_content( + [ + { + "role": "user", + "parts": [ + types.Part.from_bytes(image_bytes, mime_type="image/png"), + types.Part.from_text(prompt), + ], + } + ] + ) + ``` + + This ordering has been shown to produce significantly better results in practice. + + ``` + Carefully examine this image and detect ALL visible objects, including + small, distant, or partially visible ones. + + IMPORTANT: Focus on finding as many objects as possible, even if you are + only moderately confident. + + Make sure each bounding box is as tight as possible. + + Valid object classes: {class_list} + + For each detected object, provide: + - "label": the exact class name from the list above + - "confidence": your certainty (between 0.0 and 1.0) + - "box_2d": the bounding box [ymin, xmin, ymax, xmax] normalized to 0-1000 + - "mask": the binary mask of the object as a base64-encoded string + + Detect everything that matches the valid classes. Do not be + conservative; include objects even with moderate confidence. + + Return a JSON array, for example: + [ + { + "label": "person", + "confidence": 0.95, + "box_2d": [100, 200, 300, 400], + "mask": "..." + }, + { + "label": "kite", + "confidence": 0.80, + "box_2d": [50, 150, 250, 350], + "mask": "..." + } + ] + ``` + + When using the google-genai library, it is recommended to set + thinking_budget=0 in thinking_config for more direct and faster responses. + + ```python + from google.generativeai import types + + model.generate_content( + ..., + generation_config=generation_config, + safety_settings=safety_settings, + thinking_config=types.ThinkingConfig( + thinking_budget=0 + ) + ) + ``` + + For a shorter prompt focused only on segmentation masks, you can use: + + ``` + Return a JSON list of segmentation masks. Each entry should include the + 2D bounding box in the "box_2d" key, the segmentation mask in the "mask" + key, and the text label in the "label" key. Use descriptive labels. + ``` + + ```pycon + >>> import supervision as sv + + >>> gemini_response_text = \"\"\"```json + ... [ + ... {"box_2d": [543, 40, 728, 200], "label": "cat", "id": 1}, + ... {"box_2d": [653, 352, 820, 522], "label": "dog", "id": 2} + ... ] + ... ```\"\"\" + + >>> detections = sv.Detections.from_vlm( + ... sv.VLM.GOOGLE_GEMINI_2_5, + ... gemini_response_text, + ... resolution_wh=(1000, 1000), + ... classes=['cat', 'dog'], + ... ) + >>> detections.xyxy + array([[ 40., 543., 200., 728.], + [352., 653., 522., 820.]]) + >>> detections.data + {'class_name': array(['cat', 'dog'], dtype='>> detections.class_id + array([0, 1]) + + ``` + + !!! example "Moondream" + + + ??? tip "Prompt engineering" + + To get the best results from Moondream, use optimized prompts that leverage + its object detection capabilities effectively. + + **For general object detection, use this simple prompt:** + + ``` + objects + ``` + + This single-word prompt instructs Moondream to detect all visible objects + and return them in the proper JSON format with normalized coordinates. + + + ```pycon + >>> import supervision as sv + + >>> moondream_result = { + ... 'objects': [ + ... { + ... 'x_min': 0.5704046934843063, + ... 'y_min': 0.20069346576929092, + ... 'x_max': 0.7049859315156937, + ... 'y_max': 0.3012596592307091 + ... }, + ... { + ... 'x_min': 0.6210969910025597, + ... 'y_min': 0.3300672620534897, + ... 'x_max': 0.8417936339974403, + ... 'y_max': 0.4961046129465103 + ... } + ... ] + ... } + + >>> detections = sv.Detections.from_vlm( + ... sv.VLM.MOONDREAM, + ... moondream_result, + ... resolution_wh=(1000, 1000), + ... ) + >>> detections.xyxy # doctest: +ELLIPSIS + array([[570.404..., 200.693..., 704.985..., 301.259...], + [621.096..., 330.067..., 841.793..., 496.104...]]) + + ``` + + !!! example "DeepSeek-VL2" + + + ??? tip "Prompt engineering" + + To get the best results from DeepSeek-VL2, use optimized prompts that leverage + its object detection and visual grounding capabilities effectively. + + **For general object detection, use the following user prompt:** + + ``` + \\n<|ref|>The giraffe at the front<|/ref|> + ``` + + **For visual grounding, use the following user prompt:** + + ``` + \\n<|grounding|>Detect the giraffes + ``` + + ```pycon + >>> import supervision as sv + + >>> deepseek_vl2_result = "<|ref|>The giraffe at the back<|/ref|><|det|>[[580, 270, 999, 904]]<|/det|><|ref|>The giraffe at the front<|/ref|><|det|>[[26, 31, 632, 998]]<|/det|><|end▁of▁sentence|>" + + >>> detections = sv.Detections.from_vlm( + ... vlm=sv.VLM.DEEPSEEK_VL_2, + ... result=deepseek_vl2_result, + ... resolution_wh=(1000, 1000), + ... ) + >>> detections.xyxy + array([[ 580.58057 , 270.27026 , 1000. , 904.9049 ], + [ 26.026026, 31.03103 , 632.6326 , 998.999 ]], + dtype=float32) + >>> detections.class_id + array([0, 1]) + >>> detections.data + {'class_name': array(['The giraffe at the back', 'The giraffe at the front'], + dtype=' Detections: + """ + Create a Detections object from the + [EasyOCR](https://github.com/JaidedAI/EasyOCR) result. + + Results are placed in the `data` field with the key `"class_name"`. + When EasyOCR returns quadrilateral corners, the original corners are + preserved in ``ORIENTED_BOX_COORDINATES``. Call EasyOCR with + ``detail=1`` so bounding boxes are available; ``detail=0`` returns text + strings only and cannot be converted into detections. + + Args: + easyocr_results: The output Results instance from EasyOCR. + + Returns: + A new Detections object. + + Example: + ```python + import supervision as sv + import easyocr + + reader = easyocr.Reader(['en']) + results = reader.readtext("") + detections = sv.Detections.from_easyocr(results) + detected_text = detections["class_name"] + ``` + """ + if len(easyocr_results) == 0: + return cls.empty() + + if isinstance(easyocr_results[0], str): + raise ValueError( + "EasyOCR results produced with detail=0 do not include bounding " + "boxes. Call reader.readtext(..., detail=1) instead." + ) + + bbox = np.array([result[0] for result in easyocr_results], dtype=np.float32) + if bbox.ndim != 3 or bbox.shape[1:] != (4, 2): + raise ValueError( + "EasyOCR results must contain four corner points per detection." + ) + xyxy = np.hstack((np.min(bbox, axis=1), np.max(bbox, axis=1))) + confidence = np.array( + [ + result[2] if len(result) > 2 and result[2] else 0 + for result in easyocr_results + ] + ) + ocr_text = np.array([result[1] for result in easyocr_results]) + + data: _DetectionDataType = { + CLASS_NAME_DATA_FIELD: ocr_text, + ORIENTED_BOX_COORDINATES: bbox, + } + return cls( + xyxy=xyxy.astype(np.float32), + confidence=confidence.astype(np.float32), + data=data, + ) + + @classmethod + def from_ncnn(cls, ncnn_results: Any) -> Detections: + """ + Creates a Detections instance from the + [ncnn](https://github.com/Tencent/ncnn) inference result. + Supports object detection models. + + Args: + ncnn_results: The output Results instance from ncnn. + + Returns: + A new Detections object. + + Example: + ```python + from supervision import _cv2 as cv2 + from ncnn.model_zoo import get_model + import supervision as sv + + image = cv2.imread("") + model = get_model( + "yolov8s", + target_size=640 + prob_threshold=0.5, + nms_threshold=0.45, + num_threads=4, + use_gpu=True, + ) + result = model(image) + detections = sv.Detections.from_ncnn(result) + ``` + """ + + xywh, confidences, class_ids = [], [], [] + + if len(ncnn_results) == 0: + return cls.empty() + + for ncnn_result in ncnn_results: + rect = ncnn_result.rect + xywh.append( + [ + rect.x.astype(np.float32), + rect.y.astype(np.float32), + rect.w.astype(np.float32), + rect.h.astype(np.float32), + ] + ) + + confidences.append(ncnn_result.prob) + class_ids.append(ncnn_result.label) + + return cls( + xyxy=xywh_to_xyxy(np.array(xywh, dtype=np.float32)), + confidence=np.array(confidences, dtype=np.float32), + class_id=np.array(class_ids, dtype=int), + ) + + @classmethod + def empty(cls) -> Detections: + """ + Create an empty Detections object with no bounding boxes, + confidences, or class IDs. + + Returns: + An empty Detections object. + + Example: + ```pycon + >>> from supervision import Detections + >>> empty_detections = Detections.empty() + >>> empty_detections.xyxy.shape + (0, 4) + + ``` + """ + return cls( + xyxy=np.empty((0, 4), dtype=np.float32), + confidence=np.array([], dtype=np.float32), + class_id=np.array([], dtype=int), + ) + + def is_empty(self) -> bool: + """ + Check whether the `Detections` object has zero bounding boxes. + + Returns: + `True` if there are no detections, `False` otherwise. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> detections = sv.Detections( + ... xyxy=np.array([[10, 20, 110, 120]]), + ... class_id=np.array([1]), + ... tracker_id=np.array([1]), + ... ) + >>> filtered = detections[detections.class_id == 99] + >>> filtered.is_empty() + True + + ``` + """ + return len(self.xyxy) == 0 + + @classmethod + def merge(cls, detections_list: list[Detections]) -> Detections: + """ + Merge a list of Detections objects into a single Detections object. + + This method takes a list of Detections objects and combines their + respective fields (`xyxy`, `mask`, `confidence`, `class_id`, and `tracker_id`) + into a single Detections object. + + For example, if merging Detections with 3 and 4 detected objects, this method + will return a Detections with 7 objects (7 entries in `xyxy`, `mask`, etc). + + !!! Note + + When merging, empty `Detections` objects are ignored. + + !!! Note + + **Mask merge policy** — the output mask type follows these rules: + + * All inputs carry + [`CompactMask`][supervision.detection.compact_mask.CompactMask] + → result mask is `CompactMask`. + * Mixed dense `ndarray` + `CompactMask` inputs → dense masks are converted + to `CompactMask` via + [`CompactMask.from_dense`][supervision.detection.compact_mask.CompactMask.from_dense]; + result is `CompactMask`. No full `(N, H, W)` stack is allocated. + + !!! warning "Lossy conversion" + + `from_dense` crops each dense mask to its detection bounding box + (`xyxy`). **True pixels outside the bounding box are silently + discarded.** This matches the behaviour of + `Detections.from_inference(compact_masks=True)`. If pixel-perfect + preservation is required, ensure all inputs are already `CompactMask` + or use the all-dense path (no `CompactMask` inputs). + + * All inputs carry dense `ndarray` → result is `ndarray` (backward + compatible). + * The pairwise merge path used by + [`with_nms`][supervision.detection.core.Detections.with_nms] / + [`with_nmm`][supervision.detection.core.Detections.with_nmm] + (`merge_inner_detection_object_pair`) does **not** preserve `CompactMask` + — mixed inputs materialise to a dense `ndarray` on that path. + + Args: + detections_list: A list of Detections objects to merge. + + Returns: + A single Detections object containing the merged data from the input list. + + Raises: + ValueError: If some `Detections` have a `mask` and others do not. + ValueError: If `CompactMask` inputs have different `image_shape` values. + ValueError: If a dense mask `(H, W)` shape differs from the `CompactMask` + `image_shape` when mixing mask types. + + Example: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> detections_1 = sv.Detections( + ... xyxy=np.array([[15, 15, 100, 100], [200, 200, 300, 300]]), + ... class_id=np.array([1, 2]), + ... data={'feature_vector': np.array([0.1, 0.2])} + ... ) + >>> detections_2 = sv.Detections( + ... xyxy=np.array([[30, 30, 120, 120]]), + ... class_id=np.array([1]), + ... data={'feature_vector': np.array([0.3])} + ... ) + >>> merged_detections = sv.Detections.merge([detections_1, detections_2]) + >>> merged_detections.xyxy + array([[ 15, 15, 100, 100], + [200, 200, 300, 300], + [ 30, 30, 120, 120]]) + >>> merged_detections.class_id + array([1, 2, 1]) + >>> merged_detections.data['feature_vector'] + array([0.1, 0.2, 0.3]) + + ``` + + Compact mask merge example: + + ```python + import numpy as np + import supervision as sv + from supervision.detection.compact_mask import CompactMask + + H, W = 720, 1280 + masks_a = np.zeros((2, H, W), dtype=bool) + masks_a[0, 100:200, 100:300] = True + xyxy_a = np.array([[100., 100., 299., 199.], [400., 300., 600., 500.]]) + cm_a = CompactMask.from_dense(masks_a, xyxy_a, image_shape=(H, W)) + + det_compact = sv.Detections( + xyxy=xyxy_a, mask=cm_a, class_id=np.array([0, 1]) + ) + + masks_b = np.zeros((1, H, W), dtype=bool) + masks_b[0, 50:100, 50:150] = True + xyxy_b = np.array([[50., 50., 149., 99.]]) + det_dense = sv.Detections(xyxy=xyxy_b, mask=masks_b, class_id=np.array([2])) + + # Dense mask is converted to CompactMask; no (N, H, W) stack allocated. + merged = sv.Detections.merge([det_compact, det_dense]) + assert isinstance(merged.mask, CompactMask) + assert len(merged) == 3 + ``` + """ + detections_list = [ + detections for detections in detections_list if not detections.is_empty() + ] + + if len(detections_list) == 0: + return Detections.empty() + + for detections in detections_list: + _validate_detections_fields( + xyxy=detections.xyxy, + mask=detections.mask, + confidence=detections.confidence, + class_id=detections.class_id, + tracker_id=detections.tracker_id, + data=detections.data, + ) + + xyxy = np.vstack([d.xyxy for d in detections_list]) + + def stack_mask_or_none() -> npt.NDArray[np.generic] | CompactMask | None: + masks = [d.mask for d in detections_list] + if all(m is None for m in masks): + return None + if any(m is None for m in masks): + raise ValueError("All or none of the 'mask' fields must be None") + if all(isinstance(m, CompactMask) for m in masks): + return CompactMask.merge(cast(list[CompactMask], masks)) + if all(not isinstance(m, CompactMask) for m in masks): + # All-dense: preserve backward-compatible dense stacking. + return cast( + npt.NDArray[np.generic], np.vstack([np.asarray(m) for m in masks]) + ) + # Mixed dense and CompactMask: convert dense masks to CompactMask to + # avoid materialising a full (N, H, W) stack. + compact_image_shapes = { + m.image_shape for m in masks if isinstance(m, CompactMask) + } + if len(compact_image_shapes) != 1: + raise ValueError( + "Cannot merge CompactMask objects with different image shapes: " + f"{sorted(compact_image_shapes)}" + ) + image_shape: tuple[int, int] = next(iter(compact_image_shapes)) + compact_list: list[CompactMask] = [] + for d, m in zip(detections_list, masks): + if isinstance(m, CompactMask): + compact_list.append(m) + else: + dense = np.asarray(m, dtype=bool) + if dense.shape[1:] != image_shape: + raise ValueError( + f"Dense mask shape {dense.shape[1:]} does not match " + f"CompactMask image_shape {image_shape}." + ) + compact_list.append( + CompactMask.from_dense(dense, d.xyxy, image_shape) + ) + return CompactMask.merge(compact_list) + + def stack_or_none(name: str) -> npt.NDArray[np.generic] | None: + values = [getattr(d, name) for d in detections_list] + if all(v is None for v in values): + return None + if any(v is None for v in values): + raise ValueError(f"All or none of the '{name}' fields must be None") + return cast(npt.NDArray[np.generic], np.hstack(values)) + + mask = cast(npt.NDArray[np.bool_] | CompactMask | None, stack_mask_or_none()) + confidence = cast(npt.NDArray[np.floating] | None, stack_or_none("confidence")) + class_id = cast(npt.NDArray[np.integer] | None, stack_or_none("class_id")) + tracker_id = cast(npt.NDArray[np.integer] | None, stack_or_none("tracker_id")) + + data = merge_data([d.data for d in detections_list]) + + metadata_list = [detections.metadata for detections in detections_list] + metadata = merge_metadata(metadata_list) + + return cls( + xyxy=xyxy, + mask=mask, + confidence=confidence, + class_id=class_id, + tracker_id=tracker_id, + data=data, + metadata=metadata, + ) + + def get_anchors_coordinates(self, anchor: Position) -> npt.NDArray[np.generic]: + """Compute anchor-point coordinates for each detection. + + The anchor can be any position in the `Position` enum, such as + `CENTER`, `CENTER_LEFT`, `BOTTOM_RIGHT`, etc. + + Selection order: + + 1. If ``data[ORIENTED_BOX_COORDINATES]`` is set and ``anchor`` is not + ``Position.CENTER_OF_MASS``, coordinates are computed from the + oriented bounding box corners (result lies on the actual rotated + body). + 2. If ``anchor`` is ``Position.CENTER_OF_MASS``, the detection mask + centroid is returned regardless of OBB data presence. + 3. Otherwise, the anchor is derived from the axis-aligned envelope + (``xyxy``). + + Args: + anchor: Anchor position to compute. Supported positions are + defined in the `Position` enum. + + Returns: + Array of shape `(n, 2)` where each row is the `[x, y]` anchor + coordinate for the corresponding detection. + + Raises: + ValueError: If the provided `anchor` is not supported. + + Examples: + Axis-aligned detection: + + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> detections = sv.Detections( + ... xyxy=np.array([[0.0, 0.0, 10.0, 4.0]]) + ... ) + >>> detections.get_anchors_coordinates(sv.Position.BOTTOM_CENTER) + array([[5., 4.]]) + + ``` + + Oriented (rotated) detection — anchor lies on the rotated body, + not the axis-aligned envelope: + + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> corners = np.array( + ... [[[0.0, 0.0], [10.0, 0.0], [10.0, 4.0], [0.0, 4.0]]] + ... ) + >>> detections = sv.Detections( + ... xyxy=np.array([[0.0, 0.0, 10.0, 4.0]]), + ... data={"xyxyxyxy": corners}, + ... ) + >>> detections.get_anchors_coordinates(sv.Position.BOTTOM_CENTER) + array([[5., 4.]]) + + ``` + """ + if ORIENTED_BOX_COORDINATES in self.data and anchor != Position.CENTER_OF_MASS: + return cast( + npt.NDArray[np.generic], + _oriented_box_anchors( + np.asarray(self.data[ORIENTED_BOX_COORDINATES]), anchor + ), + ) + + xyxy = self.xyxy + + def coordinates( + x: npt.NDArray[np.number], y: npt.NDArray[np.number] + ) -> npt.NDArray[np.generic]: + return cast(npt.NDArray[np.generic], np.array([x, y]).transpose()) + + if anchor == Position.CENTER: + return coordinates( + (xyxy[:, 0] + xyxy[:, 2]) / 2, + (xyxy[:, 1] + xyxy[:, 3]) / 2, + ) + elif anchor == Position.CENTER_OF_MASS: + if self.mask is None: + raise ValueError( + "Cannot use `Position.CENTER_OF_MASS` without a detection mask." + ) + return calculate_masks_centroids(masks=self.mask) + elif anchor == Position.CENTER_LEFT: + return coordinates(xyxy[:, 0], (xyxy[:, 1] + xyxy[:, 3]) / 2) + elif anchor == Position.CENTER_RIGHT: + return coordinates(xyxy[:, 2], (xyxy[:, 1] + xyxy[:, 3]) / 2) + elif anchor == Position.BOTTOM_CENTER: + return coordinates((xyxy[:, 0] + xyxy[:, 2]) / 2, xyxy[:, 3]) + elif anchor == Position.BOTTOM_LEFT: + return coordinates(xyxy[:, 0], xyxy[:, 3]) + elif anchor == Position.BOTTOM_RIGHT: + return coordinates(xyxy[:, 2], xyxy[:, 3]) + elif anchor == Position.TOP_CENTER: + return coordinates((xyxy[:, 0] + xyxy[:, 2]) / 2, xyxy[:, 1]) + elif anchor == Position.TOP_LEFT: + return coordinates(xyxy[:, 0], xyxy[:, 1]) + elif anchor == Position.TOP_RIGHT: + return coordinates(xyxy[:, 2], xyxy[:, 1]) + + raise ValueError(f"{anchor} is not supported.") + + def get_data(self, key: str) -> _DetectionDataValueType | None: + """Get a value from the detection data dictionary. + + Args: + key: Data field name. + + Returns: + The stored data value, or `None` when the key is absent. + + Example: + ```pycon + >>> import numpy as np + >>> from supervision import Detections + >>> detections = Detections( + ... xyxy=np.array([[0, 0, 1, 1]]), + ... data={"class_name": np.array(["cat"])}, + ... ) + >>> detections.get_data("class_name").tolist() + ['cat'] + + ``` + """ + return self.data.get(key) + + def select( + self, + index: int | np.integer[Any] | slice | list[int] | npt.NDArray[np.generic], + ) -> Detections: + """Get a subset of the Detections object. + + Args: + index: Row index, indices, slice, or boolean mask selecting detections. + + Returns: + A new `Detections` instance containing the selected rows. Always returns + a fresh copy — arrays and metadata are never shared with the original, + even when the selection is empty or the input has zero detections. + + Example: + ```pycon + >>> import numpy as np + >>> from supervision import Detections + >>> detections = Detections(xyxy=np.array([[0, 0, 1, 1], [1, 1, 2, 2]])) + >>> detections.select([1]).xyxy.tolist() + [[1, 1, 2, 2]] + + ``` + """ + mask: npt.NDArray[np.bool_] | CompactMask | None + if len(self) == 0: + if isinstance(self.mask, CompactMask): + mask = self.mask[:0] + elif self.mask is not None: + mask = self.mask[:0].copy() + else: + mask = None + data = { + key: value.copy() if isinstance(value, np.ndarray) else list(value) + for key, value in self.data.items() + } + return Detections( + xyxy=self.xyxy.copy(), + mask=mask, + confidence=( + self.confidence.copy() if self.confidence is not None else None + ), + class_id=self.class_id.copy() if self.class_id is not None else None, + tracker_id=( + self.tracker_id.copy() if self.tracker_id is not None else None + ), + data=data, + metadata=dict(self.metadata), + ) + if isinstance(index, (int, np.integer)): + index = [int(index)] + array_index = cast( + slice | list[int] | npt.NDArray[np.integer | np.bool_], index + ) + data = { + key: value.copy() if isinstance(value, np.ndarray) else list(value) + for key, value in get_data_item(self.data, array_index).items() + } + if isinstance(self.mask, CompactMask): + mask = self.mask[cast(Any, array_index)] + elif self.mask is not None: + mask = self.mask[cast(Any, array_index)].copy() + else: + mask = None + return Detections( + xyxy=self.xyxy[array_index].copy(), + mask=mask, + confidence=( + self.confidence[array_index].copy() + if self.confidence is not None + else None + ), + class_id=( + self.class_id[array_index].copy() if self.class_id is not None else None + ), + tracker_id=( + self.tracker_id[array_index].copy() + if self.tracker_id is not None + else None + ), + data=data, + metadata=dict(self.metadata), + ) + + def __getitem__( + self, + index: int + | np.integer[Any] + | slice + | list[int] + | npt.NDArray[np.generic] + | str, + ) -> Detections | list[Any] | npt.NDArray[np.generic] | None: + """ + Get a subset of the Detections object or access an item from its data field. + + When provided with an integer, slice, list of integers, or a numpy array, this + method returns a new Detections object that represents a subset of the original + detections. When provided with a string, it accesses the corresponding item in + the data dictionary. + + Args: + index: The index, indices, or key to access a subset of the Detections + or an item from the data. + + Returns: + A subset of the Detections object or an item from the data field. + + Example: + ```python + import supervision as sv + + detections = sv.Detections() + + first_detection = detections[0] + first_10_detections = detections[0:10] + some_detections = detections[[0, 2, 4]] + class_0_detections = detections[detections.class_id == 0] + high_confidence_detections = detections[detections.confidence > 0.5] + + feature_vector = detections['feature_vector'] + ``` + """ + if isinstance(index, str): + return self.get_data(index) + return self.select(index) + + def __setitem__(self, key: str, value: npt.NDArray[np.generic] | list[Any]) -> None: + """ + Set a value in the data dictionary of the Detections object. + + Args: + key: The key in the data dictionary to set. + value: The value to set for the key. + + Example: + ```python + from supervision import _cv2 as cv2 + import supervision as sv + from ultralytics import YOLO + + image = cv2.imread("") + model = YOLO('yolov8s.pt') + + result = model(image)[0] + detections = sv.Detections.from_ultralytics(result) + + detections['names'] = [ + model.model.names[class_id] + for class_id + in detections.class_id + ] + ``` + + Raises: + TypeError: If `value` is not a `np.ndarray` or `list`. + ValueError: If `value` has a length or shape incompatible with + the detection count. + """ + if not isinstance(value, (np.ndarray, list)): + raise TypeError("Value must be a np.ndarray or a list") + + if isinstance(value, list): + value = np.array(value) + + _validate_data({key: value}, len(self)) + self.data[key] = value + + @property + def area(self) -> npt.NDArray[np.generic]: + """ + Calculate the area of each detection in the set of object detections. + + Selection order: + + 1. If ``mask`` is set, return the area of each mask. + 2. Else, if ``data[ORIENTED_BOX_COORDINATES]`` is set, return the area of + the rotated body (shoelace formula on the four corners). + 3. Otherwise, return the axis-aligned box area (``box_area``). + + **OBB dispatch contract**: presence of ``data[ORIENTED_BOX_COORDINATES]`` + with shape ``(N, 4, 2)`` is the canonical signal that a detection carries + oriented bounding box geometry. The same presence-of-key check governs + ``with_nms``, ``with_nmm``, and this property — always store OBB corners + under ``config.ORIENTED_BOX_COORDINATES`` with that shape. + + **Return dtype**: ``float64`` (OBB branch and integer AABB fallback), + floating input dtype (floating AABB fallback), ``int64`` (mask branch). + + Returns: + An array containing the area of each detection + in the format of `(area_1, area_2, ..., area_n)`, + where n is the number of detections. + + Example: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> corners = np.array( + ... [[[0, 5], [5, 10], [10, 5], [5, 0]]], dtype=np.float32 + ... ) + >>> detections = sv.Detections( + ... xyxy=np.array([[0, 0, 10, 10]], dtype=np.float32), + ... class_id=np.array([0]), + ... data={"xyxyxyxy": corners}, + ... ) + >>> detections.area + array([50.]) + + Mask branch returns ``int64`` pixel counts: + + >>> mask = np.zeros((2, 10, 10), dtype=bool) + >>> mask[0, :3, :3] = True # 9 pixels + >>> mask[1, :5, :5] = True # 25 pixels + >>> detections = sv.Detections( + ... xyxy=np.array( + ... [[0, 0, 10, 10], [0, 0, 10, 10]], dtype=np.float32 + ... ), + ... mask=mask, + ... ) + >>> detections.area + array([ 9, 25]) + + ``` + """ + return detection_area(self) + + @property + def box_area(self) -> npt.NDArray[np.generic]: + """ + Calculate the area of each bounding box in the set of object detections. + + Returns: + An array of floats containing the area of each bounding + box in the format of `(area_1, area_2, ..., area_n)`, + where n is the number of detections. Integer coordinates + produce ``float64``; floating coordinates preserve their dtype. + """ + xyxy = self.xyxy + if np.issubdtype(xyxy.dtype, np.integer): + # Subtract as Python integers first: converting corners to float64 + # would collapse adjacent 64-bit coordinates above 2**53, while + # native integer subtraction can overflow across the dtype range. + integer_coordinates = xyxy.astype(object) + widths = integer_coordinates[:, 2] - integer_coordinates[:, 0] + heights = integer_coordinates[:, 3] - integer_coordinates[:, 1] + return np.asarray(widths, dtype=np.float64) * np.asarray( + heights, dtype=np.float64 + ) + + widths = xyxy[:, 2] - xyxy[:, 0] + heights = xyxy[:, 3] - xyxy[:, 1] + return widths * heights + + @property + def box_aspect_ratio(self) -> npt.NDArray[np.generic]: + """ + Compute the aspect ratio (width divided by height) for each bounding box. + + Returns: + Array of shape `(N,)` containing aspect ratios, where `N` is the + number of boxes (width / height for each box). + + Examples: + ```python + import numpy as np + import supervision as sv + + xyxy = np.array([ + [10, 10, 50, 50], + [60, 10, 180, 50], + [10, 60, 50, 180], + ]) + + detections = sv.Detections(xyxy=xyxy) + + detections.box_aspect_ratio + # array([1.0, 3.0, 0.33333333]) + + ar = detections.box_aspect_ratio + detections[(ar < 2.0) & (ar > 0.5)].xyxy + # array([[10., 10., 50., 50.]]) + ``` + """ + widths = self.xyxy[:, 2] - self.xyxy[:, 0] + heights = self.xyxy[:, 3] - self.xyxy[:, 1] + + aspect_ratios = np.full_like(widths, np.nan, dtype=np.float64) + np.divide(widths, heights, out=aspect_ratios, where=heights != 0) + return aspect_ratios + + def to_compact_masks(self) -> Detections: + """Return a copy of this Detections with masks converted to CompactMask. + + The dense :attr:`mask` field (``NDArray[np.bool_]``) is converted to a + :class:`~supervision.detection.compact_mask.CompactMask` without changing + mask pixels. When :attr:`mask` is already a + :class:`~supervision.detection.compact_mask.CompactMask` or is ``None``, + the instance is returned unchanged. + + Note: + The crop boundaries are set to the **full image dimensions**, not the + detector bounding box. No bbox-crop memory savings apply: the RLE + sparsity still reduces storage versus a dense array, but the + ``O(bbox_area)`` savings available from + ``from_inference(..., compact_masks=True)`` are absent here because + every crop spans the whole frame. Call + :meth:`~supervision.detection.compact_mask.CompactMask.repack` on the + resulting mask to tighten crops to their bounding boxes, at the cost + of potential pixel loss outside those boxes. + + Returns: + A new :class:`Detections` instance with ``mask`` set to a + :class:`~supervision.detection.compact_mask.CompactMask`, or ``self`` + when conversion is not needed. + + Example: + ```python + import numpy as np + import supervision as sv + detections = sv.Detections( + xyxy=np.array([[0, 0, 10, 10]]), + mask=np.ones((1, 20, 20), dtype=bool), + ) + compact = detections.to_compact_masks() + ``` + """ + from supervision.detection.compact_mask import CompactMask + + if self.mask is None or isinstance(self.mask, CompactMask): + return self + image_shape = (int(self.mask.shape[1]), int(self.mask.shape[2])) + full_image_xyxy = np.tile( + np.array( + [[0, 0, image_shape[1] - 1, image_shape[0] - 1]], dtype=np.float64 + ), + (len(self), 1), + ) + new = self.__class__( + xyxy=self.xyxy, + mask=CompactMask.from_dense( + masks=self.mask, + xyxy=full_image_xyxy, + image_shape=image_shape, + ), + confidence=self.confidence, + class_id=self.class_id, + tracker_id=self.tracker_id, + data=self.data, + metadata=dict(self.metadata), + ) + return new + + def _build_nms_predictions( + self, class_agnostic: bool, operation_name: str + ) -> npt.NDArray[np.floating]: + """Stack xyxy + confidence (+ class_id) for NMS/NMM/Soft-NMS dispatch. + + Callers must already have verified `self.confidence is not None`. + """ + if class_agnostic: + return cast( + npt.NDArray[np.floating], + np.hstack( + (self.xyxy, cast(np.ndarray, self.confidence).reshape(-1, 1)) + ), + ) + if self.class_id is None: + raise ValueError( + f"Detections class_id must be given for {operation_name} to be " + f"executed. If you intended to perform class agnostic " + f"{operation_name} set class_agnostic=True." + ) + return cast( + npt.NDArray[np.floating], + np.hstack( + ( + self.xyxy, + cast(np.ndarray, self.confidence).reshape(-1, 1), + self.class_id.reshape(-1, 1), + ) + ), + ) + + def with_nms( + self, + threshold: float = 0.5, + class_agnostic: bool = False, + overlap_metric: OverlapMetric = OverlapMetric.IOU, + ) -> Detections: + """ + Performs non-max suppression on detection set. Dispatch order: (1) if mask + data present, IoU mask is used; (2) else if oriented-box coordinates + (``data[ORIENTED_BOX_COORDINATES]``) present, oriented-box IoU is used; (3) + otherwise, axis-aligned box IoU is used. + + Args: + threshold: The intersection-over-union threshold + to use for non-maximum suppression. The lower the value the more + restrictive the NMS becomes. Defaults to 0.5. + class_agnostic: Whether to perform class-agnostic + non-maximum suppression. If True, the class_id of each detection + will be ignored. Defaults to False. + overlap_metric: Metric used to compute the degree of + overlap between pairs of masks or boxes (e.g., IoU, IoS). + + Returns: + A new Detections object containing the subset of detections + after non-maximum suppression. + + Raises: + ValueError: If `confidence` is None and class_agnostic is False. + If `class_id` is None and class_agnostic is False. + """ + if len(self) == 0: + return self + + if self.confidence is None: + raise ValueError( + "Detections confidence must be given for NMS to be executed." + ) + + predictions = self._build_nms_predictions(class_agnostic, "NMS") + + if self.mask is not None: + indices = mask_non_max_suppression( + predictions=predictions, + masks=self.mask, + iou_threshold=threshold, + overlap_metric=overlap_metric, + ) + elif ORIENTED_BOX_COORDINATES in self.data: + indices = oriented_box_non_max_suppression( + predictions=predictions, + oriented_boxes=np.asarray(self.data[ORIENTED_BOX_COORDINATES]), + iou_threshold=threshold, + overlap_metric=overlap_metric, + ) + else: + indices = box_non_max_suppression( + predictions=predictions, + iou_threshold=threshold, + overlap_metric=overlap_metric, + ) + + return self.select(indices) + + def with_soft_nms( + self, + sigma: float = 0.5, + class_agnostic: bool = False, + score_threshold: float | None = None, + ) -> Detections: + """ + Performs Gaussian Soft Non-Maximum Suppression on detection set. Dispatch + order: (1) if mask data present, IoU mask is used; (2) otherwise, + axis-aligned box IoU is used. Oriented-box detections are not given + dedicated OBB-IoU treatment and fall back to their axis-aligned `xyxy`. + + Unlike `with_nms`, which discards overlapping detections outright, + Soft-NMS keeps every detection and instead rescales its confidence by + `score *= exp(-iou**2 / sigma)` for each higher-scoring, same-category + overlap. By default (`score_threshold=None`) nothing is dropped — the + method only rescales confidence, despite the "suppression" name; pass + `score_threshold` to additionally filter the decayed scores into a real + subset, matching `with_nms`'s return contract. + + Args: + sigma: Controls the strength of the confidence decay; must be + greater than `0`. The lower the value the stronger the decay. + No value of `sigma` reproduces `with_nms`'s hard cutoff — + Soft-NMS never drops detections on its own. + class_agnostic: Whether to perform class-agnostic Soft-NMS. If + True, the class_id of each detection will be ignored. + Defaults to False. + score_threshold: If given, detections whose decayed confidence is + at or below this value are dropped, producing a real subset + (like `with_nms`). If `None` (default), all detections are + kept, with their confidence rescaled in place on the returned + copy. + + Returns: + A new Detections object with decayed confidence scores and, + if `score_threshold` is given, filtered to a real subset. + The original `Detections` instance is never modified. + + Raises: + ValueError: If `confidence` is None. + If `class_id` is None and class_agnostic is False. + If `sigma` is not greater than `0`. + """ + if len(self) == 0: + return self + + if self.confidence is None: + raise ValueError( + "Detections confidence must be given for Soft-NMS to be executed." + ) + + predictions = self._build_nms_predictions(class_agnostic, "Soft-NMS") + + if self.mask is not None: + decayed_confidence = mask_soft_non_max_suppression( + predictions=predictions, + masks=self.mask, + sigma=sigma, + ) + else: + decayed_confidence = box_soft_non_max_suppression( + predictions=predictions, + sigma=sigma, + ) + + result = self.select(np.arange(len(self))) + result.confidence = decayed_confidence + + if score_threshold is None: + return result + return result.select(decayed_confidence > score_threshold) + + def with_nmm( + self, + threshold: float = 0.5, + class_agnostic: bool = False, + overlap_metric: OverlapMetric = OverlapMetric.IOU, + ) -> Detections: + """ + Perform non-maximum merging on the current set of object detections. + Dispatch order: (1) if mask data present, IoU mask is used; (2) else if + oriented-box coordinates (``data[ORIENTED_BOX_COORDINATES]``) present, + oriented-box IoU is used; (3) otherwise, axis-aligned box IoU is used. + + Args: + threshold: The intersection-over-union threshold + to use for non-maximum merging. Defaults to 0.5. + class_agnostic: Whether to perform class-agnostic + non-maximum merging. If True, the class_id of each detection + will be ignored. Defaults to False. + overlap_metric: Metric used to compute the degree of + overlap between pairs of masks or boxes (e.g., IoU, IoS). + + Returns: + A new Detections object containing the subset of detections + after non-maximum merging. + + Note: + For detections carrying oriented bounding box data + (``data[ORIENTED_BOX_COORDINATES]``), each merge group's output OBB + is the tightest rectangle at the winner's orientation enclosing all + corners contributed by every detection in the group. The winner is + the highest-confidence detection in the group. The axis-aligned + ``xyxy`` field is updated to the tight bounding box of that rect. + For zero-rotation OBBs this equals the axis-aligned union exactly; + for rotated OBBs the merged rect inherits the winner's rotation angle. + Groups of size 1 keep the original OBB unchanged. + + Raises: + ValueError: If `confidence` is None or `class_id` is None and + class_agnostic is False. + + ![non-max-merging](https://media.roboflow.com/supervision-docs/non-max-merging.png){ align=center width="800" } + """ # noqa: E501 // docs + if len(self) == 0: + return self + + if self.confidence is None: + raise ValueError( + "Detections confidence must be given for NMM to be executed." + ) + + predictions = self._build_nms_predictions(class_agnostic, "NMM") + + if self.mask is not None: + merge_groups = mask_non_max_merge( + predictions=predictions, + masks=self.mask, + iou_threshold=threshold, + overlap_metric=overlap_metric, + ) + elif ORIENTED_BOX_COORDINATES in self.data: + merge_groups = oriented_box_non_max_merge( + predictions=predictions, + oriented_boxes=np.asarray(self.data[ORIENTED_BOX_COORDINATES]), + iou_threshold=threshold, + overlap_metric=overlap_metric, + ) + else: + merge_groups = box_non_max_merge( + predictions=predictions, + iou_threshold=threshold, + overlap_metric=overlap_metric, + ) + + result: list[Detections] = [] + for merge_group in merge_groups: + group = [self.select(i) for i in merge_group] + result.append(_merge_detection_group(group)) + + return Detections.merge(result) + + +def _merge_obb_corners( + corners_list: list[npt.NDArray[np.number]], +) -> npt.NDArray[np.floating]: + """Merge multiple OBB corner arrays using winner-angle projection. + + The first entry in *corners_list* is the winner. Its orientation angle + (derived from its first edge) defines the local frame in which the + tightest enclosing axis-aligned rectangle is computed. That rectangle is + then rotated back to produce the merged OBB. + + Args: + corners_list: List of (4, 2) corner arrays. First is the winner. + + Returns: + Merged OBB corners as a (4, 2) floating-point array. Its dtype matches + floating inputs and is float64 for integer inputs. + """ + input_dtype = np.result_type(*[corners.dtype for corners in corners_list]) + output_dtype = ( + input_dtype if np.issubdtype(input_dtype, np.floating) else np.float64 + ) + origin = corners_list[0][0] + stacked = np.concatenate(corners_list, axis=0) + # Translate to the winner's first corner before any float math so large + # integer coordinates (e.g. geospatial or stitched frames) are reduced to + # local extents. Object arithmetic keeps those integer differences exact + # and avoids unsigned wrap-around for corners lying below the origin. + if np.issubdtype(input_dtype, np.integer): + all_corners = np.asarray( + stacked.astype(object) - origin.astype(object), dtype=np.float64 + ) + else: + all_corners = stacked.astype(np.float64, copy=False) - origin.astype( + np.float64, copy=False + ) + # Use winner's first edge to derive orientation angle -- avoids + # cv2.minAreaRect surprises (e.g. 90-degree flip for wide rects). Read it + # off the translated corners so it inherits the same wrap-safety. + winner_edge = all_corners[1] - all_corners[0] + angle = float(np.arctan2(float(winner_edge[1]), float(winner_edge[0]))) + cos, sin = float(np.cos(angle)), float(np.sin(angle)) + + # De-rotate all corners into the winner's local frame + to_local = np.array([[cos, -sin], [sin, cos]], dtype=np.float64) + local_corners = all_corners @ to_local + x_min = float(local_corners[:, 0].min()) + x_max = float(local_corners[:, 0].max()) + y_min = float(local_corners[:, 1].min()) + y_max = float(local_corners[:, 1].max()) + + # Rotate the enclosing AABB back to world frame + to_world = np.array([[cos, sin], [-sin, cos]], dtype=np.float64) + merged: npt.NDArray[np.floating] = ( + np.array( + [[x_min, y_min], [x_max, y_min], [x_max, y_max], [x_min, y_max]], + dtype=np.float64, + ) + @ to_world + ) + return cast(npt.NDArray[np.floating], (merged + origin).astype(output_dtype)) + + +def _merge_detection_group(detections: list[Detections]) -> Detections: + """Merge a group of single-object Detections into one merged detection. + + Used internally by :meth:`Detections.with_nmm` to combine each merge group + into a single output detection. The highest-confidence detection is the + "winner" whose class_id, tracker_id, and data fields are preserved. + + Args: + detections: List of Detections, each containing exactly one object. + + Returns: + A single merged Detections object of length 1. + """ + if len(detections) == 1: + return detections[0] + + confidences = np.array( + [d.confidence[0] if d.confidence is not None else 0.0 for d in detections], + dtype=np.float64, + ) + winner_idx = int(np.argmax(confidences)) + winner = detections[winner_idx] + + # Area-weighted confidence: each box contributes proportionally to its + # footprint so large overlapping boxes dominate over small slivers. + all_xyxy = np.array([d.xyxy[0] for d in detections]) + widths = all_xyxy[:, 2] - all_xyxy[:, 0] + heights = all_xyxy[:, 3] - all_xyxy[:, 1] + areas = widths.astype(np.float64, copy=False) * heights.astype( + np.float64, copy=False + ) + + confidence: npt.NDArray[np.floating] | None + if winner.confidence is not None: + total_area = float(areas.sum()) + if total_area > 0: + confidence = np.array( + [float(np.dot(areas, confidences) / total_area)], + dtype=np.float32, + ) + else: + confidence = winner.confidence + else: + confidence = None + + # OBB path: merge corners via winner-angle projection, then derive xyxy + # from the merged OBB so both stay consistent. + has_obb = ORIENTED_BOX_COORDINATES in winner.data + if has_obb: + corners_list = [] + for det in detections: + c = np.asarray(det.data[ORIENTED_BOX_COORDINATES]) + if c.ndim != 3 or c.shape[1:] != (4, 2): + raise ValueError(f"corners must have shape (N, 4, 2); got {c.shape}") + corners_list.append(c[0].reshape(4, 2)) + merged_corners = _merge_obb_corners(corners_list) + xyxy = xyxyxyxy_to_xyxy(merged_corners[np.newaxis]) + data = {**winner.data, ORIENTED_BOX_COORDINATES: merged_corners[np.newaxis]} + else: + # AABB path: union bounding box across all group members + xyxy = np.array( + [ + [ + all_xyxy[:, 0].min(), + all_xyxy[:, 1].min(), + all_xyxy[:, 2].max(), + all_xyxy[:, 3].max(), + ] + ], + dtype=np.float32, + ) + data = winner.data + + # Mask union via logical OR. Preserve CompactMask outputs without re-cropping + # to the merged box, because source masks may legitimately extend outside it. + masks = [d.mask for d in detections if d.mask is not None] + if masks: + if all(isinstance(m, CompactMask) for m in masks): + compact_masks = cast(list[CompactMask], masks) + image_shape = compact_masks[0].image_shape + if any(m.image_shape != image_shape for m in compact_masks): + raise ValueError( + "Cannot merge CompactMask objects with different image shapes." + ) + union_mask = np.zeros(image_shape, dtype=bool) + for compact_mask in compact_masks: + union_mask |= compact_mask.to_dense()[0] + union_xyxy = mask_to_xyxy(union_mask[np.newaxis]).astype(np.float32) + mask = CompactMask.from_dense( + masks=union_mask[np.newaxis], + xyxy=union_xyxy, + image_shape=image_shape, + ) + else: + dense_masks = [ + m.to_dense() if isinstance(m, CompactMask) else m for m in masks + ] + mask = np.logical_or.reduce(np.concatenate(dense_masks, axis=0))[np.newaxis] + else: + mask = None + + metadata = merge_metadata([d.metadata for d in detections]) + + return Detections( + xyxy=xyxy, + mask=mask, + confidence=confidence, + class_id=winner.class_id, + tracker_id=winner.tracker_id, + data=data, + metadata=metadata, + ) + + +@deprecated(deprecated_in="0.29.0", remove_in="0.32.0") # type: ignore[untyped-decorator] +def merge_inner_detection_object_pair( + detections_1: Detections, detections_2: Detections +) -> Detections: + """ + Merges two Detections objects into a single Detections object. + Assumes each Detections contains exactly one object. + + A `winning` detection is determined based on the confidence score of the two + input detections. This winning detection is then used to specify which + `class_id`, `tracker_id`, and `data` to include in the merged Detections object. + + The resulting `confidence` of the merged object is calculated by the weighted + contribution of each detection to the merged object. + The bounding boxes and masks of the two input detections are merged into a + single bounding box and mask, respectively. + + Args: + detections_1: The first Detections object. + detections_2: The second Detections object. + + Returns: + A new Detections object, with merged attributes. + + Raises: + ValueError: If the input Detections objects do not have exactly 1 detected + object. + + Example: + ```python + from supervision import _cv2 as cv2 + import supervision as sv + from inference import get_model + + image = cv2.imread("") + model = get_model(model_id="yolov8s-640") + + result = model.infer(image)[0] + detections = sv.Detections.from_inference(result) + + merged_detections = merge_object_detection_pair( + detections[0], detections[1]) + ``` + """ + if len(detections_1) != 1 or len(detections_2) != 1: + raise ValueError("Both Detections should have exactly 1 detected object.") + + _validate_fields_both_defined_or_none(detections_1, detections_2) + + xyxy_1 = detections_1.xyxy[0] + xyxy_2 = detections_2.xyxy[0] + if detections_1.confidence is None and detections_2.confidence is None: + merged_confidence = None + else: + assert detections_1.confidence is not None + assert detections_2.confidence is not None + detection_1_area = (xyxy_1[2] - xyxy_1[0]) * (xyxy_1[3] - xyxy_1[1]) + detections_2_area = (xyxy_2[2] - xyxy_2[0]) * (xyxy_2[3] - xyxy_2[1]) + merged_confidence = ( + detection_1_area * detections_1.confidence[0] + + detections_2_area * detections_2.confidence[0] + ) / (detection_1_area + detections_2_area) + merged_confidence = np.array([merged_confidence]) + + merged_x1, merged_y1 = np.minimum(xyxy_1[:2], xyxy_2[:2]) + merged_x2, merged_y2 = np.maximum(xyxy_1[2:], xyxy_2[2:]) + merged_xyxy = np.array([[merged_x1, merged_y1, merged_x2, merged_y2]]) + + if detections_1.mask is None and detections_2.mask is None: + merged_mask = None + else: + merged_mask = np.logical_or( + cast(npt.NDArray[Any], detections_1.mask), + cast(npt.NDArray[Any], detections_2.mask), + ) + + if detections_1.confidence is None or detections_2.confidence is None: + winning_detection = detections_1 + elif detections_1.confidence[0] >= detections_2.confidence[0]: + winning_detection = detections_1 + else: + winning_detection = detections_2 + + metadata = merge_metadata([detections_1.metadata, detections_2.metadata]) + + return Detections( + xyxy=merged_xyxy, + mask=merged_mask, + confidence=merged_confidence, + class_id=winning_detection.class_id, + tracker_id=winning_detection.tracker_id, + data=winning_detection.data, + metadata=metadata, + ) + + +@deprecated(deprecated_in="0.29.0", remove_in="0.32.0") # type: ignore[untyped-decorator] +def merge_inner_detections_objects( + detections: list[Detections], + threshold: float = 0.5, + overlap_metric: OverlapMetric = OverlapMetric.IOU, +) -> Detections: + """ + Given N detections each of length 1 (exactly one object inside), combine them into a + single detection object of length 1. The contained inner object will be the merged + result of all the input detections. + + For example, this lets you merge N boxes into one big box, N masks into one mask, + etc. + """ + detections_1 = detections[0] + for detections_2 in detections[1:]: + iou = detection_iou(detections_1, detections_2, overlap_metric)[0] + if iou < threshold: + break + detections_1 = merge_inner_detection_object_pair(detections_1, detections_2) + return detections_1 + + +@deprecated(deprecated_in="0.29.0", remove_in="0.32.0") # type: ignore[untyped-decorator] +def merge_inner_detections_objects_without_iou( + detections: list[Detections], +) -> Detections: + """ + Given N detections each of length 1 (exactly one object inside), combine them into a + single detection object of length 1. The contained inner object will be the merged + result of all the input detections. + + For example, this lets you merge N boxes into one big box, N masks into one mask, + etc. + """ + return reduce(merge_inner_detection_object_pair, detections) + + +def _validate_fields_both_defined_or_none( + detections_1: Detections, detections_2: Detections +) -> None: + """ + Verify that for each optional field in the Detections, both instances either have + the field set to None or both have it set to non-None values. + + `data` field is ignored. + + Raises: + ValueError: If one field is None and the other is not, for any of the fields. + """ + attributes = get_instance_variables(detections_1) + for attribute in attributes: + value_1 = getattr(detections_1, attribute) + value_2 = getattr(detections_2, attribute) + + if (value_1 is None) != (value_2 is None): + raise ValueError( + f"Field '{attribute}' should be consistently None or not None in both " + "Detections." + ) + + +@deprecated( # type: ignore[untyped-decorator] + target=_validate_fields_both_defined_or_none, + deprecated_in="0.29.0", + remove_in="0.32.0", +) +def validate_fields_both_defined_or_none( + detections_1: Detections, detections_2: Detections +) -> None: + void(detections_1, detections_2) diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/line_zone.py b/.venv/lib/python3.12/site-packages/supervision/detection/line_zone.py new file mode 100644 index 0000000000000000000000000000000000000000..5f1c5a63bb2d9b397ce4ed7eac999dbe23e49777 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/detection/line_zone.py @@ -0,0 +1,955 @@ +import math +import warnings +from collections import Counter, defaultdict, deque +from collections.abc import Iterable +from functools import lru_cache +from itertools import islice +from typing import Literal + +import numpy as np +import numpy.typing as npt + +from supervision import _cv2 as cv2 +from supervision.config import CLASS_NAME_DATA_FIELD +from supervision.detection.core import Detections +from supervision.detection.utils.internal import cross_product +from supervision.draw.color import Color +from supervision.draw.utils import draw_rectangle, draw_text +from supervision.geometry.core import Point, Position, Rect, Vector +from supervision.utils.image import _overlay_image +from supervision.utils.internal import SupervisionWarnings + +TEXT_MARGIN = 10 + + +class LineZone: + """ + This class is responsible for counting the number of objects that cross a + predefined line. + + + + !!! warning + + LineZone uses the `tracker_id`. Read + [here](/latest/trackers/) to learn how to plug + tracking into your inference pipeline. + + Attributes: + in_count: The number of objects that have crossed the line from outside + to inside. + out_count: The number of objects that have crossed the line from inside + to outside. + in_count_per_class: Number of objects of each class that have + crossed the line from outside to inside, keyed by `class_id` + (`int` for classified detections, `None` for unclassified ones). + out_count_per_class: Number of objects of each class that have + crossed the line from inside to outside, keyed by `class_id` + (`int` for classified detections, `None` for unclassified ones). + + Example: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> def frames_generator(): + ... yield np.zeros((1080, 1920, 3), dtype=np.uint8) + ... + >>> start = sv.Point(x=0, y=100) + >>> end = sv.Point(x=200, y=100) + >>> line_zone = sv.LineZone(start=start, end=end) + >>> for frame in frames_generator(): + ... detections = sv.Detections( + ... xyxy=np.array([[10, 110, 20, 150]]), + ... tracker_id=np.array([1]) + ... ) + ... crossed_in, crossed_out = line_zone.trigger( + ... detections + ... ) + ... + >>> line_zone.in_count, line_zone.out_count + (0, 0) + >>> for frame in frames_generator(): + ... detections = sv.Detections( + ... xyxy=np.array([[10, 50, 20, 90]]), + ... tracker_id=np.array([1]) + ... ) + ... crossed_in, crossed_out = line_zone.trigger( + ... detections + ... ) + ... + >>> line_zone.in_count, line_zone.out_count + (1, 0) + + ``` + """ + + def __init__( + self, + start: Point, + end: Point, + triggering_anchors: Iterable[Position] = ( + Position.TOP_LEFT, + Position.TOP_RIGHT, + Position.BOTTOM_LEFT, + Position.BOTTOM_RIGHT, + ), + minimum_crossing_threshold: int = 1, + ) -> None: + """ + Args: + start: The starting point of the line. + end: The ending point of the line. + triggering_anchors: Any iterable of positions specifying which anchors + of the detections bounding box to consider when deciding on whether + the detection has passed the line counter or not. By default, + this contains the four corners of the detection's bounding box. + minimum_crossing_threshold: Detection needs to be seen on the other + side of the line for this many consecutive observations to be + considered as having crossed the line. Only frames that place the + detection on one side of the line count: a frame in which it is + temporarily missing, falls outside the line's limits, or straddles + the line is skipped, and neither extends the run nor resets it. + This is useful when dealing with unstable bounding boxes or when + detections may linger on the line. Excursions shorter than this + are treated as noise: they neither count as a crossing nor as a + return crossing once the detection settles back on the side it + started from. This holds only for excursions from a side the + detection is already established on — the first side it is seen + on, at the start of its life and again after it has been absent + long enough for its state to be dropped, becomes its reference + immediately, with no confirmation. + """ + self.vector = Vector(start=start, end=end) + self.limits = self._calculate_region_of_interest_limits(vector=self.vector) + self.crossing_history_length = max(2, minimum_crossing_threshold + 1) + self.crossing_state_history: dict[int, deque[bool]] = defaultdict( + lambda: deque(maxlen=self.crossing_history_length) + ) + # Last side of the line a tracker was *confirmed* on. Crossings are counted + # against this rather than against the oldest history entry, so a + # sub-threshold excursion never becomes the reference side once a reference + # exists, and cannot be mistaken for a crossing back to the side the tracker + # never left. The reference itself is seeded by the first observation with no + # confirmation, so a noisy first frame — at the start of a tracker's life or + # on its first frame back after eviction — still decides where it starts. + self._confirmed_crossing_side: dict[int, bool] = {} + # Tracks consecutive frames a tracker key has been absent; eviction + # requires crossing_history_length absent frames so that ByteTrack + # coasting gaps (single-frame detection drops) don't reset mid-crossing + # state prematurely. + self._tracker_frames_absent: dict[int, int] = {} + self._in_count_per_class: Counter[int | None] = Counter() + self._out_count_per_class: Counter[int | None] = Counter() + # Materialize once so we can safely accept generators without exhausting them. + self.triggering_anchors = list(triggering_anchors) + if not self.triggering_anchors: + raise ValueError("Triggering anchors cannot be empty.") + self.class_id_to_name: dict[int, str] = {} + + @property + def in_count(self) -> int: + return sum(self._in_count_per_class.values()) + + @property + def out_count(self) -> int: + return sum(self._out_count_per_class.values()) + + @property + def in_count_per_class(self) -> dict[int | None, int]: + return dict(self._in_count_per_class) + + @property + def out_count_per_class(self) -> dict[int | None, int]: + return dict(self._out_count_per_class) + + def trigger( + self, detections: Detections + ) -> tuple[npt.NDArray[np.bool_], npt.NDArray[np.bool_]]: + """ + Update the `in_count` and `out_count` based on the objects that cross the line. + + Args: + detections: A Detections object for which to update the counts. + + Returns: + A tuple of two boolean NumPy arrays. The first array indicates which + detections have crossed the line from outside to inside. The second + array indicates which detections have crossed the line from inside to + outside. + """ + crossed_in = np.full(len(detections), False) + crossed_out = np.full(len(detections), False) + + if len(detections) == 0: + self._evict_stale_crossing_history(set()) + return crossed_in, crossed_out + + if detections.tracker_id is None: + warnings.warn( + "Line zone counting skipped. LineZone requires tracker_id. Refer to " + "https://supervision.roboflow.com/latest/trackers for more " + "information.", + category=SupervisionWarnings, + ) + return crossed_in, crossed_out + + class_ids: list[int | None] = ( + list(detections.class_id) + if detections.class_id is not None + else [None] * len(detections) + ) + current_keys = {int(tracker_id) for tracker_id in detections.tracker_id} + self._evict_stale_crossing_history(current_keys) + self._update_class_id_to_name(detections) + + in_limits, has_any_left_trigger, has_any_right_trigger = ( + self._compute_anchor_sides(detections) + ) + + for i, (class_id, tracker_id) in enumerate( + zip(class_ids, detections.tracker_id) + ): + if not in_limits[i]: + continue + + if has_any_left_trigger[i] and has_any_right_trigger[i]: + continue + + tracker_state = bool(has_any_left_trigger[i]) + key = int(tracker_id) + crossing_history = self.crossing_state_history[key] + crossing_history.append(tracker_state) + # The first observed side seeds the reference; there is nothing to have + # crossed from before it. + confirmed_side = self._confirmed_crossing_side.setdefault( + key, tracker_state + ) + + # Subsumed by the confirmed-side check that follows, but not removable: + # this is what guarantees the deque is full — exactly + # crossing_history_length entries — by the time the sustained-run check + # below reads it. Without it a partial window would satisfy that check + # after a single frame on the new side. + if len(crossing_history) < self.crossing_history_length: + continue + + if tracker_state == confirmed_side: + continue + + # Only promote the new side once it has been held for the full threshold, + # so a flicker that reverts before the threshold elapses is discarded. + # The gate above leaves exactly crossing_history_length entries, so + # skipping the oldest one leaves precisely the minimum_crossing_threshold + # frames that must all be on the new side. + sustained_run = islice(crossing_history, 1, None) + if any(state != tracker_state for state in sustained_run): + continue + + self._confirmed_crossing_side[key] = tracker_state + + if tracker_state: + self._in_count_per_class[class_id] += 1 + crossed_in[i] = True + else: + self._out_count_per_class[class_id] += 1 + crossed_out[i] = True + + return crossed_in, crossed_out + + def _evict_stale_crossing_history(self, current_keys: set[int]) -> None: + for key in list(self.crossing_state_history): + if key in current_keys: + self._tracker_frames_absent.pop(key, None) + else: + absent = self._tracker_frames_absent.get(key, 0) + 1 + if absent >= self.crossing_history_length: + del self.crossing_state_history[key] + self._confirmed_crossing_side.pop(key, None) + self._tracker_frames_absent.pop(key, None) + else: + self._tracker_frames_absent[key] = absent + + @staticmethod + def _calculate_region_of_interest_limits(vector: Vector) -> tuple[Vector, Vector]: + magnitude = vector.magnitude + + if magnitude == 0: + raise ValueError("The magnitude of the vector cannot be zero.") + + delta_x = vector.end.x - vector.start.x + delta_y = vector.end.y - vector.start.y + + unit_vector_x = delta_x / magnitude + unit_vector_y = delta_y / magnitude + + perpendicular_vector_x = -unit_vector_y + perpendicular_vector_y = unit_vector_x + + start_region_limit = Vector( + start=vector.start, + end=Point( + x=vector.start.x + perpendicular_vector_x, + y=vector.start.y + perpendicular_vector_y, + ), + ) + end_region_limit = Vector( + start=vector.end, + end=Point( + x=vector.end.x - perpendicular_vector_x, + y=vector.end.y - perpendicular_vector_y, + ), + ) + return start_region_limit, end_region_limit + + def _compute_anchor_sides( + self, detections: Detections + ) -> tuple[npt.NDArray[np.bool_], npt.NDArray[np.bool_], npt.NDArray[np.bool_]]: + """ + Find if detections' anchors are within the limit of the line + zone and which anchors are on its left and right side. + + Assumes: + * At least 1 detection is provided + * Detections have `tracker_id` + + The limit is defined as the region between the two lines, + perpendicular to the line zone, and passing through its start + and end points, as shown below: + + Limits: + ``` + | IN ↑ + | | + OUT o---LINE---o OUT + | | + ↓ IN | + ``` + + Args: + detections: The detections to check. + + Returns: + All 3 arrays are boolean arrays of shape (N, ) where N is the + number of detections. The first array, `in_limits`, indicates + if the detection's anchor is within the line zone limits. + The second array, `has_any_left_trigger`, indicates if the + detection's anchor is on the left side of the line zone. + The third array, `has_any_right_trigger`, indicates if the + detection's anchor is on the right side of the line zone. + """ + assert len(detections) > 0 + assert detections.tracker_id is not None + + all_anchors = np.array( + [ + detections.get_anchors_coordinates(anchor) + for anchor in self.triggering_anchors + ] + ) + + cross_products_1 = cross_product(all_anchors, self.limits[0]) + cross_products_2 = cross_product(all_anchors, self.limits[1]) + + # Works because limit vectors are pointing in opposite directions + in_limits = (cross_products_1 > 0) == (cross_products_2 > 0) + in_limits = np.all(in_limits, axis=0) + + triggers = cross_product(all_anchors, self.vector) < 0 + has_any_left_trigger = np.any(triggers, axis=0) + has_any_right_trigger = np.any(~triggers, axis=0) + + return in_limits, has_any_left_trigger, has_any_right_trigger + + def _update_class_id_to_name(self, detections: Detections) -> None: + """ + Update the attribute keeping track of which class + IDs correspond to which class names. + + Assumes that class_names are only provided when class_ids are. + """ + class_names = detections.data.get(CLASS_NAME_DATA_FIELD) + assert class_names is None or detections.class_id is not None + + if detections.class_id is None: + return + + if class_names is None: + new_names = {class_id: str(class_id) for class_id in detections.class_id} + else: + new_names = { + class_id: class_name + for class_id, class_name in zip(detections.class_id, class_names) + } + self.class_id_to_name.update(new_names) + + +class LineZoneAnnotator: + """ + Draw a `LineZone` and its in/out counts on a video frame. + + Use this annotator after calling `LineZone.trigger` so the rendered counts + reflect the latest tracked detections. + """ + + def __init__( + self, + thickness: int = 2, + color: Color = Color.WHITE, + text_thickness: int = 2, + text_color: Color = Color.BLACK, + text_scale: float = 0.5, + text_offset: float = 1.5, + text_padding: int = 10, + custom_in_text: str | None = None, + custom_out_text: str | None = None, + display_in_count: bool = True, + display_out_count: bool = True, + display_text_box: bool = True, + text_orient_to_line: bool = False, + text_centered: bool = True, + ) -> None: + """ + A class for drawing the `LineZone` and its detected object count + on an image. + + Args: + thickness: Line thickness. + color: Line color. + text_thickness: Text thickness. + text_color: Text color. + text_scale: Text scale. + text_offset: How far the text will be from the line. + text_padding: The empty space in the text box, surrounding the text. + custom_in_text: Write something else instead of "in". + custom_out_text: Write something else instead of "out". + display_in_count: Pass `False` to hide the "in" count. + display_out_count: Pass `False` to hide the "out" count. + display_text_box: Pass `False` to hide the text background box. + text_orient_to_line: Match text orientation to the line. + Recommended to set to `True`. + text_centered: Pass `False` to disable text centering. Useful + when the label overlaps something important. + + """ + self.thickness: int = thickness + self.color: Color = color + self.text_thickness: int = text_thickness + self.text_color: Color = text_color + self.text_scale: float = text_scale + self.text_offset: float = text_offset + self.text_padding: int = text_padding + self.in_text: str = custom_in_text if custom_in_text else "in" + self.out_text: str = custom_out_text if custom_out_text else "out" + self.display_in_count: bool = display_in_count + self.display_out_count: bool = display_out_count + self.display_text_box: bool = display_text_box + self.text_orient_to_line: bool = text_orient_to_line + self.text_centered: bool = text_centered + + def annotate( + self, frame: npt.NDArray[np.uint8], line_counter: LineZone + ) -> npt.NDArray[np.uint8]: + """ + Draws the line on the frame using the line zone provided. + + Args: + frame: The image on which the line will be drawn. + line_counter: The line zone that will be used to draw the line. + + Returns: + The image with the line drawn on it. + + """ + line_start = line_counter.vector.start.as_xy_int_tuple() + line_end = line_counter.vector.end.as_xy_int_tuple() + cv2.line( + frame, + line_start, + line_end, + self.color.as_bgr(), + self.thickness, + lineType=cv2.LINE_AA, + shift=0, + ) + cv2.circle( + frame, + line_start, + radius=5, + color=self.text_color.as_bgr(), + thickness=-1, + lineType=cv2.LINE_AA, + ) + cv2.circle( + frame, + line_end, + radius=5, + color=self.text_color.as_bgr(), + thickness=-1, + lineType=cv2.LINE_AA, + ) + + in_text = f"{self.in_text}: {line_counter.in_count}" + out_text = f"{self.out_text}: {line_counter.out_count}" + line_angle_degrees = self._get_line_angle(line_counter) + + for text, is_shown, is_in_count in [ + (in_text, self.display_in_count, True), + (out_text, self.display_out_count, False), + ]: + if not is_shown: + continue + + if line_angle_degrees == 0 or not self.text_orient_to_line: + self._draw_basic_label( + frame=frame, + line_center=line_counter.vector.center, + text=text, + is_in_count=is_in_count, + ) + else: + self._draw_oriented_label( + frame=frame, + line_zone=line_counter, + text=text, + is_in_count=is_in_count, + ) + + return frame + + def _get_line_angle(self, line_zone: LineZone) -> float: + """ + Calculate the line counter angle (in degrees). + + Args: + line_zone: The line zone object. + + Returns: + Line counter angle, in degrees. + """ + start_point = line_zone.vector.start.as_xy_int_tuple() + end_point = line_zone.vector.end.as_xy_int_tuple() + + delta_x = end_point[0] - start_point[0] + delta_y = end_point[1] - start_point[1] + + if delta_x == 0: + line_angle = 90.0 + line_angle += 180 if delta_y < 0 else 0 + else: + line_angle = math.degrees(math.atan(delta_y / delta_x)) + line_angle += 180 if delta_x < 0 else 0 + + return line_angle + + def _calculate_anchor_in_frame( + self, + line_zone: LineZone, + text_width: int, + text_height: int, + is_in_count: bool, + label_dimension: int, + ) -> tuple[int, int]: + """ + Calculate insertion anchor in frame to position the center of the count image. + + Args: + line_zone: The line counter object used for counting. + text_width: Text width. + text_height: Text height. + is_in_count: Whether the count should be placed over or below line. + label_dimension: Size of the label image. Assumes the + label is rectangular. + + Returns: + xy, point in an image where the label will be placed. + """ + line_angle = self._get_line_angle(line_zone) + + if self.text_centered: + mid_point = Vector( + start=line_zone.vector.start, end=line_zone.vector.end + ).center.as_xy_int_tuple() + anchor = list(mid_point) + else: + end_point = line_zone.vector.end.as_xy_int_tuple() + anchor = list(end_point) + + move_along_x = int( + math.cos(math.radians(line_angle)) + * (text_width / 2 + self.text_padding) + ) + move_along_y = int( + math.sin(math.radians(line_angle)) + * (text_width / 2 + self.text_padding) + ) + + anchor[0] -= move_along_x + anchor[1] -= move_along_y + + move_perpendicular_x = int( + math.sin(math.radians(line_angle)) * (self.text_offset * text_height) + ) + move_perpendicular_y = int( + math.cos(math.radians(line_angle)) * (self.text_offset * text_height) + ) + + if is_in_count: + anchor[0] += move_perpendicular_x + anchor[1] -= move_perpendicular_y + else: + anchor[0] -= move_perpendicular_x + anchor[1] += move_perpendicular_y + + x1 = max(anchor[0] - label_dimension // 2, 0) + y1 = max(anchor[1] - label_dimension // 2, 0) + + return x1, y1 + + def _draw_basic_label( + self, + frame: npt.NDArray[np.uint8], + line_center: Point, + text: str, + is_in_count: bool, + ) -> npt.NDArray[np.uint8]: + """ + Draw the count label on the frame. For example: "out: 7". + The label contains horizontal text and is not rotated. + + Args: + frame: The entire scene, on which the label will be placed. + line_center: The center of the line zone. + text: The text that will be drawn. + is_in_count: Whether to display the in count (above line) + or out count (below line). + + Returns: + The scene with the label drawn on it. + """ + _, text_height = cv2.getTextSize( + text, cv2.FONT_HERSHEY_SIMPLEX, self.text_scale, self.text_thickness + )[0] + + if is_in_count: + line_center.y -= int(self.text_offset * text_height) + else: + line_center.y += int(self.text_offset * text_height) + + draw_text( + scene=frame, + text=text, + text_anchor=line_center, + text_color=self.text_color, + text_scale=self.text_scale, + text_thickness=self.text_thickness, + text_padding=self.text_padding, + background_color=self.color if self.display_text_box else None, + ) + + return frame + + def _draw_oriented_label( + self, + frame: npt.NDArray[np.uint8], + line_zone: LineZone, + text: str, + is_in_count: bool, + ) -> npt.NDArray[np.uint8]: + """ + Draw the count label on the frame. For example: "out: 7". + The label is oriented to match the line angle. + + Args: + frame: The entire scene, on which the label will be placed. + line_zone: The line zone responsible for counting objects crossing it. + text: The text that will be drawn. + is_in_count: Whether to display the in count (above line) + or out count (below line). + + Returns: + The scene with the label drawn on it. + """ + + line_angle_degrees = self._get_line_angle(line_zone) + label_image = self._make_label_image( + text, + text_scale=self.text_scale, + text_thickness=self.text_thickness, + text_padding=self.text_padding, + text_color=self.text_color, + text_box_show=self.display_text_box, + text_box_color=self.color, + line_angle_degrees=line_angle_degrees, + ) + assert label_image.shape[0] == label_image.shape[1] + + text_width, text_height = cv2.getTextSize( + text, cv2.FONT_HERSHEY_SIMPLEX, self.text_scale, self.text_thickness + )[0] + + label_anchor = self._calculate_anchor_in_frame( + line_zone=line_zone, + text_width=text_width, + text_height=text_height, + is_in_count=is_in_count, + label_dimension=label_image.shape[0], + ) + + frame = _overlay_image(frame, label_image, label_anchor) + + return frame + + @staticmethod + @lru_cache(maxsize=32) + def _make_label_image( + text: str, + *, + text_scale: float, + text_thickness: int, + text_padding: int, + text_color: Color, + text_box_show: bool, + text_box_color: Color, + line_angle_degrees: float, + ) -> npt.NDArray[np.uint8]: + """ + Create the small text box displaying line zone count. E.g. "out: 7". + + Args: + text: The text to display. + text_scale: The scale of the text. + text_thickness: The thickness of the text. + text_padding: The padding around the text. + text_color: The color of the text. + text_box_show: Whether to display the text box. + text_box_color: The color of the text box. + line_angle_degrees: The angle of the line in degrees. + + Returns: + The label of shape (H, W, 4), in BGRA format. + """ + text_width, text_height = cv2.getTextSize( + text, cv2.FONT_HERSHEY_SIMPLEX, text_scale, text_thickness + )[0] + + annotation_dim = int((max(text_width, text_height) + text_padding * 2) * 1.5) + annotation_shape = (annotation_dim, annotation_dim) + annotation_center = Point(annotation_dim // 2, annotation_dim // 2) + + annotation: npt.NDArray[np.uint8] = np.zeros( + (*annotation_shape, 3), dtype=np.uint8 + ) + annotation_alpha: npt.NDArray[np.uint8] = np.zeros( + (*annotation_shape, 1), dtype=np.uint8 + ) + draw_text( + scene=annotation, + text=text, + text_anchor=annotation_center, + text_scale=text_scale, + text_thickness=text_thickness, + text_padding=text_padding, + text_color=text_color, + background_color=text_box_color if text_box_show else None, + ) + draw_text( + scene=annotation_alpha, + text=text, + text_anchor=annotation_center, + text_scale=text_scale, + text_thickness=text_thickness, + text_padding=text_padding, + text_color=Color.WHITE, + background_color=Color.WHITE if text_box_show else None, + ) + annotation = np.dstack((annotation, annotation_alpha)).astype(np.uint8) + + # Make sure text is displayed upright + if 90 < line_angle_degrees % 360 < 270: + annotation = cv2.flip(annotation, flipCode=-1).astype(np.uint8) + + from PIL import Image + + annotation = np.asarray( + Image.fromarray(annotation).rotate( + -line_angle_degrees, + resample=Image.Resampling.BILINEAR, + center=annotation_center.as_xy_float_tuple(), + ) + ).astype(np.uint8) + + return annotation + + +class LineZoneAnnotatorMulticlass: + """ + Draw per-class crossing counts for one or more `LineZone` instances. + + The annotator renders a table with one row per line zone and one column per + class observed by the zones. + """ + + def __init__( + self, + *, + table_position: Literal[ + Position.TOP_LEFT, + Position.TOP_RIGHT, + Position.BOTTOM_LEFT, + Position.BOTTOM_RIGHT, + ] = Position.TOP_RIGHT, + table_color: Color = Color.WHITE, + table_margin: int = 10, + table_padding: int = 10, + table_max_width: int = 400, + text_color: Color = Color.BLACK, + text_scale: float = 0.75, + text_thickness: int = 1, + force_draw_class_ids: bool = False, + ) -> None: + """ + Draw a table showing how many items of each class crossed each line. + + Args: + table_position: The position of the table. + table_color: The color of the table. + table_margin: The margin of the table from the image border. + table_padding: The padding of the table. + table_max_width: The maximum width of the table. + text_color: The color of the text. + text_scale: The scale of the text. + text_thickness: The thickness of the text. + force_draw_class_ids: Instead of writing the class names, + on the table, write the class IDs. E.g. instead of `person: 6`, + write `0: 6`. + """ + if table_position not in { + Position.TOP_LEFT, + Position.TOP_RIGHT, + Position.BOTTOM_LEFT, + Position.BOTTOM_RIGHT, + }: + raise ValueError( + "Invalid table position. Supported values are:" + " TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT." + ) + + self.table_position = table_position + self.table_color = table_color + self.table_margin = table_margin + self.table_padding = table_padding + self.table_max_width = table_max_width + self.text_color = text_color + self.text_scale = text_scale + self.text_thickness = text_thickness + self.force_draw_class_ids = force_draw_class_ids + + def annotate( + self, + frame: npt.NDArray[np.uint8], + line_zones: list[LineZone], + line_zone_labels: list[str] | None = None, + ) -> npt.NDArray[np.uint8]: + """ + Draws a table with the number of objects of each class that crossed each line. + + Args: + frame: The image on which the table will be drawn. + line_zones: The line zones to be annotated. + line_zone_labels: The labels, one for each line zone. If not + provided, the default labels will be used. + + Returns: + The image with the table drawn on it. + + """ + if line_zone_labels is None: + line_zone_labels = [f"Line {i + 1}:" for i in range(len(line_zones))] + if len(line_zones) != len(line_zone_labels): + raise ValueError("The number of line zones and their labels must match.") + + text_lines = ["Line Crossings:"] + for line_zone, line_zone_label in zip(line_zones, line_zone_labels): + text_lines.append(line_zone_label) + class_id_to_name = line_zone.class_id_to_name + + for direction, count_per_class in [ + ("In", line_zone.in_count_per_class), + ("Out", line_zone.out_count_per_class), + ]: + if not count_per_class: + continue + + text_lines.append(f" {direction}:") + for class_id, count in count_per_class.items(): + if self.force_draw_class_ids: + class_name = str(class_id) + elif class_id is None: + class_name = "None" + else: + class_name = class_id_to_name.get(class_id, str(class_id)) + text_lines.append(f" {class_name}: {count}") + + table_width, table_height = 0, 0 + for line in text_lines: + text_width, text_height = cv2.getTextSize( + line, cv2.FONT_HERSHEY_SIMPLEX, self.text_scale, self.text_thickness + )[0] + text_height += TEXT_MARGIN + table_width = max(table_width, text_width) + table_height += text_height + + table_width += 2 * self.table_padding + table_height += 2 * self.table_padding + table_max_height = frame.shape[0] - 2 * self.table_margin + table_height = min(table_height, table_max_height) + table_width = min(table_width, self.table_max_width) + + position_map = { + Position.TOP_LEFT: (self.table_margin, self.table_margin), + Position.TOP_RIGHT: ( + frame.shape[1] - table_width - self.table_margin, + self.table_margin, + ), + Position.BOTTOM_LEFT: ( + self.table_margin, + frame.shape[0] - table_height - self.table_margin, + ), + Position.BOTTOM_RIGHT: ( + frame.shape[1] - table_width - self.table_margin, + frame.shape[0] - table_height - self.table_margin, + ), + } + table_x1, table_y1 = position_map[self.table_position] + + table_rect = Rect( + x=table_x1, y=table_y1, width=table_width, height=table_height + ) + frame = draw_rectangle( + scene=frame, rect=table_rect, color=self.table_color, thickness=-1 + ) + + for i, line in enumerate(text_lines): + _, text_height = cv2.getTextSize( + line, cv2.FONT_HERSHEY_SIMPLEX, self.text_scale, self.text_thickness + )[0] + text_height += TEXT_MARGIN + anchor_x = table_x1 + self.table_padding + anchor_y = table_y1 + self.table_padding + (i + 1) * text_height + + cv2.putText( + img=frame, + text=line, + org=(anchor_x, anchor_y), + fontFace=cv2.FONT_HERSHEY_SIMPLEX, + fontScale=self.text_scale, + color=self.text_color.as_bgr(), + thickness=self.text_thickness, + lineType=cv2.LINE_AA, + ) + + return frame diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/tools/__init__.py b/.venv/lib/python3.12/site-packages/supervision/detection/tools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/tools/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/detection/tools/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c22684a92f586de43b912aab0bedba9b9ea4cea Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/detection/tools/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/tools/__pycache__/csv_sink.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/detection/tools/__pycache__/csv_sink.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7cdf0a2002a84f91d82c2543adbb9fde426d81d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/detection/tools/__pycache__/csv_sink.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/tools/__pycache__/inference_slicer.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/detection/tools/__pycache__/inference_slicer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8186ffb866e155beeb6b6ca0e0d86c58d28abdc3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/detection/tools/__pycache__/inference_slicer.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/tools/__pycache__/json_sink.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/detection/tools/__pycache__/json_sink.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a3e1bf62462209e5e314df28851774e4a277648 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/detection/tools/__pycache__/json_sink.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/tools/__pycache__/polygon_zone.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/detection/tools/__pycache__/polygon_zone.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1527e2b6c9f541e4fdfb8054cd2ef4e198a05a2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/detection/tools/__pycache__/polygon_zone.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/tools/__pycache__/smoother.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/detection/tools/__pycache__/smoother.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6cb38816ce7ed82323818986958ceba91ef9c858 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/detection/tools/__pycache__/smoother.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/tools/__pycache__/transformers.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/detection/tools/__pycache__/transformers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32de3b43c4c085b64021e9bc19b3acad642a0133 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/detection/tools/__pycache__/transformers.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/tools/csv_sink.py b/.venv/lib/python3.12/site-packages/supervision/detection/tools/csv_sink.py new file mode 100644 index 0000000000000000000000000000000000000000..b954adf896fdde4f4776aac9be19fbe7a7ba4769 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/detection/tools/csv_sink.py @@ -0,0 +1,280 @@ +from __future__ import annotations + +import csv +import io +import os +from collections.abc import Iterable +from typing import Any, Protocol + +import numpy as np + +from supervision.detection.core import Detections +from supervision.utils.logger import _get_logger + +logger = _get_logger(__name__) + +BASE_HEADER = [ + "x_min", + "y_min", + "x_max", + "y_max", + "class_id", + "confidence", + "tracker_id", +] + + +class WriterProtocol(Protocol): + def writerow(self, row: Iterable[Any]) -> Any: ... + + +class CSVSink: + """ + A utility class for saving detection data to a CSV file. This class is designed to + efficiently serialize detection objects into a CSV format, allowing for the + inclusion of bounding box coordinates and additional attributes like `confidence`, + `class_id`, and `tracker_id`. + + !!! tip + + CSVSink allows passing custom data alongside detection fields, providing + flexibility for logging various types of information. + When a NumPy array, list, or tuple value in custom_data (or + detections.data) has the same length as the detection count, each + element is written to the corresponding detection row; any other value + is broadcast to all rows. + + Args: + file_name: The name of the CSV file where the detections will be stored. + Defaults to 'output.csv'. + + Example: + ```pycon + >>> import supervision as sv + >>> import numpy as np + >>> import tempfile + >>> import os + >>> # Create synthetic detections + >>> detections = sv.Detections( + ... xyxy=np.array([[10, 20, 30, 40], [50, 60, 70, 80]]), + ... confidence=np.array([0.9, 0.8]), + ... class_id=np.array([0, 1]) + ... ) + >>> # Use temporary file + >>> temp_file = tempfile.NamedTemporaryFile( + ... mode='w', suffix='.csv', delete=False + ... ) + >>> temp_file.close() + >>> csv_sink = sv.CSVSink(temp_file.name) + >>> with csv_sink as sink: + ... sink.append(detections, custom_data={'frame': 0}) + >>> os.unlink(temp_file.name) # Clean up + + ``` + """ + + def __init__(self, file_name: str = "output.csv") -> None: + """ + Initialize the CSVSink instance. + + Args: + file_name: The name of the CSV file. + """ + self.file_name = file_name + self.file: io.TextIOWrapper | None = None + self.writer: WriterProtocol | None = None + self.header_written = False + self.field_names: list[str] = [] + self.deferred_field_names: list[str] = [] + + def __enter__(self) -> CSVSink: + self.open() + return self + + def __exit__( + self, + exc_type: type | None, + exc_val: Exception | None, + exc_tb: Any | None, + ) -> None: + self.close() + + def open(self) -> None: + """ + Open the CSV file for writing. + """ + parent_directory = os.path.dirname(self.file_name) + if parent_directory and not os.path.exists(parent_directory): + os.makedirs(parent_directory) + + self.file = open(self.file_name, "w", newline="") + self.writer = csv.writer(self.file) + self.header_written = False + self.field_names = [] + self.deferred_field_names = [] + + def close(self) -> None: + """ + Close the CSV file. + + When every appended batch was empty no header has been written yet, so + the schema remembered from the first such batch is emitted here. This + keeps a run that never detected anything readable as an empty table + rather than as a zero-byte file. + """ + if self.file is None or self.file.closed: + return + + # close() also runs from __exit__, so a writer raising here would both leak + # the file handle and replace the with-body's own exception. Closing in a + # finally keeps the handle released and lets the original error surface. + try: + if not self.header_written and self.deferred_field_names and self.writer: + self.field_names = self.deferred_field_names + self.writer.writerow(self.field_names) + self.header_written = True + finally: + self.file.close() + + @staticmethod + def _slice_value(value: Any, i: int, n: int) -> Any: + """ + Return the i-th element when the value stores per-detection data. + + Dispatch rules: + - np.ndarray with ndim == 0: return as-is for broadcasting + - np.ndarray with len equal to n: return value[i] + - list or tuple with len equal to n: return value[i] + - any other type: return as-is for broadcasting + + Args: + value: Custom-data field value. + i: Zero-based detection index. + n: Total number of detections. + + Returns: + Element at position i if value is a per-detection sequence, + otherwise value unchanged. + """ + if isinstance(value, np.ndarray): + return value[i] if value.ndim > 0 and len(value) == n else value + if isinstance(value, (list, tuple)) and len(value) == n: + return value[i] + return value + + @staticmethod + def parse_detection_data( + detections: Detections, custom_data: dict[str, Any] | None = None + ) -> list[dict[str, Any]]: + """ + Convert detections and optional custom data into per-detection rows. + + Builds one dictionary per detection containing bounding box coordinates, + detection attributes, and any values from ``detections.data`` or + ``custom_data``. NumPy array, list, and tuple values in + ``custom_data`` with length equal to ``len(detections.xyxy)`` are + sliced one element per row; all other values are broadcast to every row. + + Args: + detections: Detection data to serialize into row dictionaries. + custom_data: Optional extra fields to include in each row. + + Returns: + A list of dictionaries, one per detection, containing ``xyxy`` + coordinates, ``class_id``, ``confidence``, ``tracker_id``, and any + values from ``detections.data`` or ``custom_data``. + """ + parsed_rows = [] + n = len(detections.xyxy) + for i in range(n): + row = { + "x_min": detections.xyxy[i][0], + "y_min": detections.xyxy[i][1], + "x_max": detections.xyxy[i][2], + "y_max": detections.xyxy[i][3], + "class_id": "" + if detections.class_id is None + else str(detections.class_id[i]), + "confidence": "" + if detections.confidence is None + else str(detections.confidence[i]), + "tracker_id": "" + if detections.tracker_id is None + else str(detections.tracker_id[i]), + } + + if hasattr(detections, "data"): + for key, value in detections.data.items(): + row[key] = CSVSink._slice_value(value, i, n) + + if custom_data: + for key, value in custom_data.items(): + row[key] = CSVSink._slice_value(value, i, n) + + parsed_rows.append(row) + return parsed_rows + + def append( + self, detections: Detections, custom_data: dict[str, Any] | None = None + ) -> None: + """ + Append detection data to the CSV file. + + The CSV header is fixed by the first batch that actually contains + detections; batches with no detections write nothing and leave the + header undecided, so an empty first frame does not strip the columns + of the frames that follow. While no populated batch has appeared, the + schema of the first empty batch is the one ``close()`` falls back to. + + Args: + detections: The detection data. + custom_data: Custom data to include. Scalars, dictionaries, and + other non-sequence values are broadcast to every detection in + this batch. NumPy arrays, lists, and tuples with length equal + to ``len(detections)`` are sliced per detection; other lists + and tuples are broadcast unchanged. + """ + if not self.writer: + raise Exception( + f"Cannot append to CSV: The file '{self.file_name}' is not open." + ) + field_names = CSVSink.parse_field_names(detections, custom_data) + + # An empty batch produces no rows, so letting it fix the header would + # pin the file to a schema no detection ever contributed to and drop + # every extra column of the batches that follow. Remember the first + # such schema for close() instead, in case no batch ever carries + # detections; later empty batches must not redefine it, mirroring the + # first-populated-batch rule for the header itself. + if len(detections) == 0: + if not self.header_written and not self.deferred_field_names: + self.deferred_field_names = field_names + return + + if not self.header_written: + self.field_names = field_names + self.writer.writerow(field_names) + self.header_written = True + + if field_names != self.field_names: + logger.warning( + "Field names do not match the header. Expected: %s, given: %s", + self.field_names, + field_names, + ) + + parsed_rows = CSVSink.parse_detection_data(detections, custom_data) + for row in parsed_rows: + self.writer.writerow( + [row.get(field_name, "") for field_name in self.field_names] + ) + + @staticmethod + def parse_field_names( + detections: Detections, custom_data: dict[str, Any] | None = None + ) -> list[str]: + custom_keys = set(custom_data.keys()) if custom_data else set() + dynamic_header = sorted( + custom_keys | set(getattr(detections, "data", {}).keys()) + ) + return BASE_HEADER + dynamic_header diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/tools/inference_slicer.py b/.venv/lib/python3.12/site-packages/supervision/detection/tools/inference_slicer.py new file mode 100644 index 0000000000000000000000000000000000000000..5aeb279afa0cd09c55ab617bc5235da3e6af2bc8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/detection/tools/inference_slicer.py @@ -0,0 +1,897 @@ +from __future__ import annotations + +import threading +import warnings +from collections.abc import Callable +from concurrent.futures import ThreadPoolExecutor +from functools import partial +from typing import TYPE_CHECKING, Any, Protocol, cast, runtime_checkable + +if TYPE_CHECKING: + from typing import TypeGuard + +import numpy as np +import numpy.typing as npt + +from supervision.config import ORIENTED_BOX_COORDINATES, SOURCE_IMAGE_METADATA_FIELD +from supervision.detection.compact_mask import CompactMask +from supervision.detection.core import Detections +from supervision.detection.utils.boxes import move_boxes, move_oriented_boxes +from supervision.detection.utils.internal import merge_metadata_lenient +from supervision.detection.utils.iou_and_nms import OverlapFilter, OverlapMetric +from supervision.detection.utils.masks import move_masks +from supervision.draw.base import ImageType +from supervision.utils.image import crop_image, get_image_resolution_wh +from supervision.utils.internal import SupervisionWarnings +from supervision.utils.iterables import create_batches + + +@runtime_checkable +class WindowedRasterDataset(Protocol): + """Structural type for a rasterio-style dataset read window-by-window. + + Matched structurally by `_is_windowed_raster` rather than by import so + `rasterio` stays an optional dependency — any object exposing these members + works. `rasterio.io.DatasetReader` satisfies this protocol. + """ + + width: int + height: int + crs: object | None + + def read(self, window: Any) -> npt.NDArray[Any]: ... + + +def _is_windowed_raster(image: object) -> TypeGuard[WindowedRasterDataset]: + """Duck-type check for a rasterio-style dataset that supports windowed reads. + + Avoids importing rasterio so it remains an optional dependency. numpy arrays + and PIL images do not expose this combination of attributes. + """ + return ( + callable(getattr(image, "read", None)) + and hasattr(image, "crs") + and hasattr(image, "width") + and hasattr(image, "height") + ) + + +def move_detections( + detections: Detections, + offset: npt.NDArray[Any], + resolution_wh: tuple[int, int] | None = None, +) -> Detections: + """Translate detections by a pixel offset, repositioning boxes and masks. + + Args: + detections: Detections object to be moved. The input is left unchanged; + a fresh copy is returned. + offset: An array of shape `(2,)` containing offset values in the + format `[dx, dy]`. + resolution_wh: The width and height of the desired mask + resolution. Required for segmentation detections. + + Returns: + Repositioned Detections object. + """ + detections = detections.select(slice(None)) + detections.xyxy = move_boxes(xyxy=detections.xyxy, offset=offset) + if ORIENTED_BOX_COORDINATES in detections.data: + detections.data[ORIENTED_BOX_COORDINATES] = move_oriented_boxes( + xyxyxyxy=cast( + npt.NDArray[np.number], detections.data[ORIENTED_BOX_COORDINATES] + ), + offset=offset, + ) + if detections.mask is not None: + if resolution_wh is None: + raise ValueError( + "Resolution width and height are required for moving segmentation " + "detections. This should be the same as (width, height) of image shape." + ) + if isinstance(detections.mask, CompactMask): + # Preserve move_masks clipping semantics without dense materialisation. + detections.mask = detections.mask.with_offset( + dx=int(offset[0]), + dy=int(offset[1]), + new_image_shape=(resolution_wh[1], resolution_wh[0]), + ) + else: + detections.mask = move_masks( + masks=detections.mask, offset=offset, resolution_wh=resolution_wh + ) + return detections + + +class InferenceSlicer: + """ + Perform tiled inference on large images by slicing them into overlapping patches. + + This class divides an input image into overlapping slices of configurable size + and overlap, runs inference on each slice through a user-provided callback, and + merges the resulting detections. The slicing process allows efficient processing + of large images with limited resources while preserving detection accuracy via + configurable overlap and post-processing of overlaps. Uses multi-threading for + parallel slice inference. + + Args: + callback: Inference function called for each slice (or batch of slices). + + When ``batch_size=1`` (default) the function receives a single + ``np.ndarray`` and must return a single + :class:`~supervision.detection.core.Detections` — the original + single-image contract, fully backward-compatible. + + When ``batch_size > 1`` the function receives + ``list[np.ndarray]`` (one array per slice) and must return + ``list[Detections]`` of the **same length** in the same order. + A length mismatch or non-list return raises :exc:`ValueError`. + + The two signatures are **not interchangeable**: a callback written + for ``batch_size=1`` will fail when ``batch_size > 1``, and vice + versa. + slice_wh: Size of each slice `(width, height)`. If int, both width and + height are set to this value. + overlap_wh: Overlap size `(width, height)` between slices. If int, both + width and height are set to this value. + overlap_filter: Strategy to merge overlapping detections + (`NON_MAX_SUPPRESSION`, `NON_MAX_MERGE`, or `NONE`). + iou_threshold: IOU threshold used in merging overlap filtering. + overlap_metric: Metric to compute overlap (`IOU` or `IOS`). + thread_workers: Number of threads for concurrent slice inference. + Must be a positive integer. When the first slice returns oriented + bounding boxes (OBB), Supervision probes additional slices until a + non-empty result is found, then falls back to sequential processing + for all remaining slices to avoid thread-safety issues in common OBB + inference backends. When passing a rasterio-style dataset, tile reads + are serialized via an internal lock regardless of this setting — + model inference runs in parallel, but ``raster.read()`` is protected. + Note: the first slice always runs synchronously + regardless of this setting, so for grids with few slices + (e.g. two-slice images) effective parallelism is reduced. + compact_masks: If ``True``, dense ``(N, H, W)`` boolean mask + arrays returned by the callback are immediately converted to a + :class:`~supervision.detection.compact_mask.CompactMask`. This + keeps masks in run-length-encoded form for the entire pipeline — + merge, NMS, and annotation — avoiding the large ``(N, H, W)`` + allocations that cause OOM on high-resolution images with many + objects. IoU and NMS are computed directly on the RLE crops + without ever materialising a full ``(N, H, W)`` array. + Defaults to ``False`` for backward compatibility. + + When ``compact_masks=True``, each detection's CompactMask crop spans + the entire slice tile bbox (not the tight detection bbox). Call + :meth:`~supervision.detection.compact_mask.CompactMask.repack` on the + merged result to tighten crops to the detection bounding boxes. + batch_size: Number of slices passed to the callback per call. + Defaults to ``1``, which uses the single-image callback contract + (``np.ndarray`` → :class:`~supervision.detection.core.Detections`). + Set to ``> 1`` to enable the batch callback contract + (``list[np.ndarray]`` → ``list[Detections]``). + + For GPU-backed models, prefer ``batch_size > 1`` with + ``thread_workers=1``. A single batched forward pass is faster than + concurrent single-image calls that compete for the same CUDA device, + and avoids multiplying peak VRAM by ``thread_workers * batch_size``. + Must be a positive integer. + + Raises: + ValueError: If ``slice_wh``, ``overlap_wh``, or ``thread_workers`` are + invalid or inconsistent. + ValueError: If ``batch_size < 1``. + ValueError: If the callback returns a non-list when ``batch_size > 1``. + ValueError: If the callback returns a list whose length differs from the + number of slices passed when ``batch_size > 1``. + + Example: + ```python + from supervision import _cv2 as cv2 + import supervision as sv + from rfdetr import RFDETRMedium + + model = RFDETRMedium() + + def callback(tile): + return model.predict(tile) + + slicer = sv.InferenceSlicer(callback, slice_wh=640, overlap_wh=100) + + image = cv2.imread("example.png") + detections = slicer(image) + ``` + + ```python + import supervision as sv + from PIL import Image + from ultralytics import YOLO + + model = YOLO("yolo11m.pt") + + def callback(tile): + results = model(tile)[0] + return sv.Detections.from_ultralytics(results) + + slicer = sv.InferenceSlicer(callback, slice_wh=640, overlap_wh=100) + + image = Image.open("example.png") + detections = slicer(image) + ``` + + ```python + import rasterio + import supervision as sv + + def callback(tile): # tile is (H, W, C); select/convert bands as needed + ... + + slicer = sv.InferenceSlicer(callback, slice_wh=640, overlap_wh=100) + + with rasterio.open("large_orthomosaic.tif") as dataset: + detections = slicer(dataset) + ``` + + Passing an open rasterio dataset reads each tile lazily via a windowed + read, so multi-GB GeoTIFFs never need to be loaded into memory at once. + `rasterio` is an optional dependency installable via + `pip install "supervision[geotiff]"`. + + Batch inference — pass multiple slices per callback call for GPU models + that benefit from batched forward passes: + + ```python + from supervision import _cv2 as cv2 + import numpy as np + import supervision as sv + + # Batch callback: receives list[np.ndarray], returns list[Detections] + def batch_callback(tiles: list[np.ndarray]) -> list[sv.Detections]: + # Run your model on the batch; return one Detections per tile. + return [sv.Detections.empty() for _ in tiles] + + slicer = sv.InferenceSlicer( + callback=batch_callback, + slice_wh=640, + overlap_wh=100, + batch_size=8, + thread_workers=1, # recommended for GPU: batch not threads + ) + + image = cv2.imread("example.png") + detections = slicer(image) + ``` + """ + + def __init__( + self, + callback: ( + Callable[[ImageType], Detections] + | Callable[[list[npt.NDArray[Any]]], list[Detections]] + ), + slice_wh: int | tuple[int, int] = 640, + overlap_wh: int | tuple[int, int] = 100, + overlap_filter: OverlapFilter | str = OverlapFilter.NON_MAX_SUPPRESSION, + iou_threshold: float = 0.5, + overlap_metric: OverlapMetric | str = OverlapMetric.IOU, + thread_workers: int = 1, + compact_masks: bool = False, + batch_size: int = 1, + ): + slice_wh_norm = self._normalize_slice_wh(slice_wh) + overlap_wh_norm = self._normalize_overlap_wh(overlap_wh) + + self._validate_overlap(slice_wh=slice_wh_norm, overlap_wh=overlap_wh_norm) + + if thread_workers < 1: + raise ValueError( + "`thread_workers` must be a positive integer. " + f"Received: {thread_workers}" + ) + if batch_size < 1: + raise ValueError( + f"`batch_size` must be a positive integer. Received: {batch_size}" + ) + + self.slice_wh = slice_wh_norm + self.overlap_wh = overlap_wh_norm + self.iou_threshold = iou_threshold + self.overlap_metric = OverlapMetric.from_value(overlap_metric) + self.overlap_filter = OverlapFilter.from_value(overlap_filter) + # Stored as single-image type; batch path calls with list[ndarray] via + # _run_callback_batch which suppresses the arg-type mismatch there. + self.callback: Callable[[npt.NDArray[Any]], Detections] = callback # type: ignore[assignment] + self.thread_workers = thread_workers + self.compact_masks = compact_masks + self.batch_size = batch_size + self._out_of_slice_bounds_warned: bool = False + self._out_of_slice_bounds_lock = threading.Lock() + self._obb_thread_workers_warned: bool = False + self._obb_thread_workers_lock = threading.Lock() + self._dropped_metadata_warned: bool = False + self._dropped_metadata_lock = threading.Lock() + self._raster_read_lock = threading.Lock() + + def __call__(self, image: ImageType | WindowedRasterDataset) -> Detections: + """ + Perform tiled inference on the full image and return merged detections. + + The first slice always runs synchronously so the output type can be + inspected before committing to a threading strategy. Detections are + merged in a deterministic order: the first slice is always at index 0, + followed by any probe slices, then the remaining slices in source order. + If oriented bounding boxes are detected, all remaining slices are + processed sequentially and a ``SupervisionWarnings`` warning is emitted + once per slicer instance. + + Per-slice ``metadata`` is merged leniently: a key survives only when + every slice carries it with an equal value; otherwise it is dropped and + a ``SupervisionWarnings`` warning is emitted once per slicer instance, + naming the dropped keys — a key meant to be global (``video_name``, + ``camera_id``, …) would otherwise vanish silently. The merged + ``metadata`` dict returned is always freshly built, never the same + dict object as any slice's own metadata. + + ``source_image`` is the one metadata key handled specially: it is + removed from every slice before the lenient merge, then reattached + afterward as a reference to ``image`` itself — not a copy, and not the + per-slice tile — for in-memory input (array or PIL image); a windowed + raster dataset has no full in-memory image to give back, so its result + carries no ``source_image``. Because the stored value is a reference, + mutating the returned ``metadata["source_image"]`` mutates the caller's + own ``image``, and every ``Detections`` derived from the result via + ``select()``, ``__getitem__``, or ``with_nms()`` shares that same + reference — a long-lived derived result (e.g. held across a video + processing loop) keeps the full input frame alive. + + Args: + image: The full image to run inference on. In addition to in-memory + images (NumPy arrays or PIL images), this also accepts an open + rasterio-style dataset. When a dataset is provided, each tile is + read lazily via a windowed read instead of loading the whole image + into memory, enabling tiled inference on multi-GB GeoTIFFs. Tiles + read from a dataset preserve the source dtype (e.g. ``uint16`` for + 16-bit sensors) and keep every band; convert or select bands to + the dtype/channels your model expects inside the callback. + + Returns: + Merged detections across all slices. + + Raises: + ValueError: If ``image`` is a rasterio-style dataset whose CRS is + geographic (non-projected). Reproject to a projected CRS + (e.g. with ``gdalwarp``) before calling. + """ + detections_list: list[Detections] = [] + resolution_wh = self._get_resolution_wh(image) + + offsets = self._generate_offset( + resolution_wh=resolution_wh, + slice_wh=self.slice_wh, + overlap_wh=self.overlap_wh, + ) + + if self.batch_size > 1: + batched = list(create_batches(offsets, self.batch_size)) + # Run first batch synchronously: fail-fast type validation + OBB probe. + first_batch_results = self._run_callback_batch(image, batched[0]) + detections_list.extend(first_batch_results) + obb_detected = any( + ORIENTED_BOX_COORDINATES in det.data for det in first_batch_results + ) + if obb_detected and self.thread_workers > 1: + with self._obb_thread_workers_lock: + if not self._obb_thread_workers_warned: + self._obb_thread_workers_warned = True + warnings.warn( + "InferenceSlicer detected oriented bounding boxes while " + "`thread_workers > 1`. Remaining batches will be processed " + "sequentially because many OBB inference backends are not " + "thread-safe and can crash when shared across threads.", + category=SupervisionWarnings, + stacklevel=2, + ) + remaining_batches = batched[1:] + if self.thread_workers == 1 or obb_detected: + for offset_batch in remaining_batches: + detections_list.extend( + self._run_callback_batch(image, offset_batch) + ) + else: + with ThreadPoolExecutor(max_workers=self.thread_workers) as executor: + # `Executor.map` yields in submission order, so batches merge in + # source order no matter which thread finishes first. + for batch_detections in executor.map( + partial(self._run_callback_batch, image), remaining_batches + ): + detections_list.extend(batch_detections) + + return self._merge_and_filter(detections_list, image) + + first_offset = offsets[0] + first_detections = self._run_callback(image, first_offset) + detections_list.append(first_detections) + + remaining_offsets = offsets[1:] + obb_detected = ORIENTED_BOX_COORDINATES in first_detections.data + should_run_sequentially = self.thread_workers <= 1 or obb_detected + + probe_index = 0 + if not should_run_sequentially and len(first_detections) == 0: + while probe_index < len(remaining_offsets): + probe_offset = remaining_offsets[probe_index] + probe_detections = self._run_callback(image, probe_offset) + detections_list.append(probe_detections) + probe_index += 1 + + if ORIENTED_BOX_COORDINATES in probe_detections.data: + obb_detected = True + should_run_sequentially = True + break + + if len(probe_detections) > 0: + break + + remaining_offsets = remaining_offsets[probe_index:] + + if should_run_sequentially: + if self.thread_workers > 1 and obb_detected: + with self._obb_thread_workers_lock: + if not self._obb_thread_workers_warned: + self._obb_thread_workers_warned = True + warnings.warn( + "InferenceSlicer detected oriented bounding boxes while " + "`thread_workers > 1`. Remaining slices will be processed " + "sequentially because many OBB inference backends are not " + "thread-safe and can crash when shared across threads.", + category=SupervisionWarnings, + stacklevel=2, + ) + for offset in remaining_offsets: + detections_list.append(self._run_callback(image, offset)) + else: + with ThreadPoolExecutor(max_workers=self.thread_workers) as executor: + # `Executor.map` yields in submission order, so slices merge in + # source order no matter which thread finishes first. + detections_list.extend( + executor.map(partial(self._run_callback, image), remaining_offsets) + ) + + return self._merge_and_filter(detections_list, image) + + def _merge_and_filter( + self, + detections_list: list[Detections], + image: ImageType | WindowedRasterDataset, + ) -> Detections: + """Merge per-slice detections, apply the overlap filter, restore the source. + + The source image is attached only after filtering. Overlap filters propagate + ``metadata`` forward untouched, so the output is identical either way — but + ``NON_MAX_MERGE`` compares metadata values per merge group, and a whole + ``(H, W, C)`` array compared once per group dominates the filter's runtime. + + Args: + detections_list: Per-slice detections in full-image coordinates. + image: The full image the slices were cut from. + + Returns: + The merged, overlap-filtered detections. + """ + merged, had_source_image = self._merge_slice_detections(detections_list, image) + filtered = self._apply_overlap_filter(merged) + if had_source_image: + filtered.metadata[SOURCE_IMAGE_METADATA_FIELD] = image + return filtered + + def _merge_slice_detections( + self, + detections_list: list[Detections], + image: ImageType | WindowedRasterDataset, + ) -> tuple[Detections, bool]: + """Merge per-slice detections, reconciling their metadata leniently. + + Metadata keys that disagree across slices, or that only some slices carry, + are dropped rather than raising — slices legitimately differ in per-tile + metadata. The source image is the one such key worth recovering: when any + slice carried it, the caller restores the full input image — array or PIL + alike, but not a windowed raster, which has no full in-memory image to hand + back. Any other key lost this way is reported once per slicer instance, + since a key the user meant to be global (``video_name``, ``camera_id``, …) + would otherwise vanish silently. + + Because the source image is restored wholesale, it is removed from every + slice up front: leaving it in would make the lenient merge — and every + downstream merge group of ``NON_MAX_MERGE`` — compare whole image arrays + only to overwrite the result afterwards. Slices of a windowed raster keep + the key, since nothing restores it for them. + + Args: + detections_list: Per-slice detections in full-image coordinates. + image: The full image the slices were cut from. + + Returns: + The merged detections before overlap filtering, and whether any slice + carried a source image that the caller should restore. + """ + non_empty = [d for d in detections_list if not d.is_empty()] + + restorable = not _is_windowed_raster(image) + had_source_image = False + if restorable: + for d in non_empty: + if SOURCE_IMAGE_METADATA_FIELD in d.metadata: + del d.metadata[SOURCE_IMAGE_METADATA_FIELD] + had_source_image = True + + merged_metadata, dropped_keys = merge_metadata_lenient( + [d.metadata for d in non_empty] + ) + + # `Detections.merge` would re-compare the same metadata and raise on the + # conflicts just resolved, so hand it empty dicts and attach the result. + for d in non_empty: + d.metadata = {} + merged = Detections.merge(detections_list=detections_list) + merged.metadata = merged_metadata + + self._warn_dropped_metadata(dropped_keys) + + return merged, had_source_image + + def _warn_dropped_metadata(self, dropped_keys: set[str]) -> None: + """Warn once per slicer instance about metadata keys lost while merging.""" + if not dropped_keys or self._dropped_metadata_warned: + return + with self._dropped_metadata_lock: + # Re-check under the lock so concurrent calls warn exactly once. + if self._dropped_metadata_warned: + return + self._dropped_metadata_warned = True + keys = ", ".join(sorted(dropped_keys)) + warnings.warn( + "InferenceSlicer dropped metadata keys that were not identical " + f"across all slices: {keys}. Metadata must agree on every slice to " + "survive merging. If the value is genuinely per-detection, store it " + "in `Detections.data` instead, which is merged per detection.", + category=SupervisionWarnings, + stacklevel=2, + ) + + def _get_resolution_wh( + self, image: ImageType | WindowedRasterDataset + ) -> tuple[int, int]: + """Return ``(width, height)`` for the image, validating CRS for rasters.""" + if _is_windowed_raster(image): + crs = image.crs + if crs is not None and not getattr(crs, "is_projected", True): + raise ValueError( + "InferenceSlicer requires a projected coordinate reference " + "system for pixel-space tiled inference on a raster dataset. " + f"The provided dataset uses a geographic CRS ({crs}). Reproject " + "it to a projected CRS (e.g. with `gdalwarp`) before slicing." + ) + return (image.width, image.height) + return get_image_resolution_wh(image) + + def _apply_overlap_filter(self, merged: Detections) -> Detections: + """Apply the configured overlap filter strategy to merged detections.""" + if self.overlap_filter == OverlapFilter.NONE: + return merged + if self.overlap_filter == OverlapFilter.NON_MAX_SUPPRESSION: + return merged.with_nms( + threshold=self.iou_threshold, + overlap_metric=self.overlap_metric, + ) + if self.overlap_filter == OverlapFilter.NON_MAX_MERGE: + return merged.with_nmm( + threshold=self.iou_threshold, + overlap_metric=self.overlap_metric, + ) + warnings.warn( + f"Invalid overlap filter strategy: {self.overlap_filter}", + category=SupervisionWarnings, + ) + return merged + + def _run_callback( + self, image: ImageType | WindowedRasterDataset, offset: npt.NDArray[Any] + ) -> Detections: + """ + Run detection callback on a sliced portion of the image and adjust coordinates. + + Args: + image: The full image. + offset: Coordinates `(x_min, y_min, x_max, y_max)` defining + the slice region. + + Returns: + Detections adjusted to the full image coordinate system. + """ + if _is_windowed_raster(image): + x_min, y_min, x_max, y_max = (int(v) for v in offset) + # rasterio tuple window: ((row_start, row_stop), (col_start, col_stop)) + window = ((y_min, y_max), (x_min, x_max)) + with self._raster_read_lock: + bands = image.read(window=window) # shape (channels, height, width) + image_slice = np.ascontiguousarray( + np.transpose(bands, (1, 2, 0)) + ) # -> (H, W, C) + resolution_wh = (image.width, image.height) + else: + image_slice = crop_image(image=image, xyxy=offset) + resolution_wh = get_image_resolution_wh(image) + + detections = self.callback(image_slice) + + if ( + self.compact_masks + and detections.mask is not None + and isinstance(detections.mask, np.ndarray) + ): + slice_w, slice_h = get_image_resolution_wh(image_slice) + full_slice_xyxy = np.tile( + np.array([[0, 0, slice_w - 1, slice_h - 1]], dtype=np.float64), + (len(detections), 1), + ) + detections.mask = CompactMask.from_dense( + detections.mask, + full_slice_xyxy, + image_shape=(slice_h, slice_w), + ) + + # Fast-path: skip locking and bounds checking when the warning has already + # been emitted or when there are no detections to inspect. + needs_warning_check = ( + not self._out_of_slice_bounds_warned and len(detections) > 0 + ) + + if needs_warning_check: + with self._out_of_slice_bounds_lock: + # Re-check under the lock to ensure correctness with multiple threads. + if not self._out_of_slice_bounds_warned and len(detections) > 0: + slice_width = offset[2] - offset[0] + slice_height = offset[3] - offset[1] + x_exceeds = np.any(detections.xyxy[:, [0, 2]] > slice_width) + y_exceeds = np.any(detections.xyxy[:, [1, 3]] > slice_height) + x_negative = np.any(detections.xyxy[:, [0, 2]] < 0) + y_negative = np.any(detections.xyxy[:, [1, 3]] < 0) + if x_exceeds or y_exceeds or x_negative or y_negative: + self._out_of_slice_bounds_warned = True + msg = ( + "Detections returned by the callback have coordinates " + "outside the slice bounds. This may be caused by the " + "callback running inference on the full image instead of " + "the provided image slice. Ensure your callback uses the " + "input slice for inference, not the original " + "full-resolution image." + ) + warnings.warn(msg, category=SupervisionWarnings, stacklevel=2) + detections = move_detections( + detections=detections, + offset=offset[:2], + resolution_wh=resolution_wh, + ) + return detections + + def _run_callback_batch( + self, + image: ImageType | WindowedRasterDataset, + offsets: list[npt.NDArray[Any]], + ) -> list[Detections]: + """Run batch inference callback on multiple slices. + + Args: + image: The full image or rasterio dataset. + offsets: List of slice coordinates `(x_min, y_min, x_max, y_max)`. + + Returns: + Detections adjusted to full-image coordinates, one per offset. + """ + if _is_windowed_raster(image): + slices = [] + for offset in offsets: + x_min, y_min, x_max, y_max = (int(v) for v in offset) + window = ((y_min, y_max), (x_min, x_max)) + with self._raster_read_lock: + bands = image.read(window=window) + slices.append(np.ascontiguousarray(np.transpose(bands, (1, 2, 0)))) + resolution_wh = (image.width, image.height) + else: + slices = [crop_image(image=image, xyxy=offset) for offset in offsets] + resolution_wh = get_image_resolution_wh(image) + + batch_callback = cast( + Callable[[list[npt.NDArray[Any]]], list[Detections]], self.callback + ) + detections_in_slices = batch_callback(slices) + if not isinstance(detections_in_slices, list): + raise ValueError( + "Callback must return `list[Detections]` when `batch_size > 1`. " + f"Got: {type(detections_in_slices)}" + ) + if len(detections_in_slices) != len(offsets): + raise ValueError( + f"Callback returned {len(detections_in_slices)} Detections " + f"for {len(offsets)} slices. Lengths must match." + ) + + if self.compact_masks: + for det, image_slice in zip(detections_in_slices, slices): + if det.mask is not None and isinstance(det.mask, np.ndarray): + slice_w, slice_h = get_image_resolution_wh(image_slice) + full_slice_xyxy = np.tile( + np.array([[0, 0, slice_w - 1, slice_h - 1]], dtype=np.float64), + (len(det), 1), + ) + det.mask = CompactMask.from_dense( + det.mask, + full_slice_xyxy, + image_shape=(slice_h, slice_w), + ) + + if not self._out_of_slice_bounds_warned: + for det, offset in zip(detections_in_slices, offsets): + if self._out_of_slice_bounds_warned or len(det) == 0: + continue + with self._out_of_slice_bounds_lock: + if not self._out_of_slice_bounds_warned and len(det) > 0: + slice_width = offset[2] - offset[0] + slice_height = offset[3] - offset[1] + x_exceeds = np.any(det.xyxy[:, [0, 2]] > slice_width) + y_exceeds = np.any(det.xyxy[:, [1, 3]] > slice_height) + x_negative = np.any(det.xyxy[:, [0, 2]] < 0) + y_negative = np.any(det.xyxy[:, [1, 3]] < 0) + if x_exceeds or y_exceeds or x_negative or y_negative: + self._out_of_slice_bounds_warned = True + warnings.warn( + "Detections returned by the callback have coordinates " + "outside the slice bounds. This may be caused by the " + "callback running inference on the full image instead " + "of the provided image slice. Ensure your callback " + "uses the input slice for inference, not the original " + "full-resolution image.", + category=SupervisionWarnings, + stacklevel=2, + ) + + return [ + move_detections( + detections=det, offset=offset[:2], resolution_wh=resolution_wh + ) + for det, offset in zip(detections_in_slices, offsets) + ] + + @staticmethod + def _normalize_slice_wh( + slice_wh: int | tuple[int, int], + ) -> tuple[int, int]: + if isinstance(slice_wh, int): + if slice_wh <= 0: + raise ValueError( + f"`slice_wh` must be a positive integer. Received: {slice_wh}" + ) + return slice_wh, slice_wh + + if isinstance(slice_wh, tuple) and len(slice_wh) == 2: + width, height = slice_wh + if width <= 0 or height <= 0: + raise ValueError( + f"`slice_wh` values must be positive. Received: {slice_wh}" + ) + return width, height + + raise ValueError( + "`slice_wh` must be an int or a tuple of two positive integers " + "(slice_w, slice_h). " + f"Received: {slice_wh}" + ) + + @staticmethod + def _normalize_overlap_wh( + overlap_wh: int | tuple[int, int], + ) -> tuple[int, int]: + if isinstance(overlap_wh, int): + if overlap_wh < 0: + raise ValueError( + "`overlap_wh` must be a non negative integer. " + f"Received: {overlap_wh}" + ) + return overlap_wh, overlap_wh + + if isinstance(overlap_wh, tuple) and len(overlap_wh) == 2: + overlap_w, overlap_h = overlap_wh + if overlap_w < 0 or overlap_h < 0: + raise ValueError( + f"`overlap_wh` values must be non negative. Received: {overlap_wh}" + ) + return overlap_w, overlap_h + + raise ValueError( + "`overlap_wh` must be an int or a tuple of two non negative integers " + "(overlap_w, overlap_h). " + f"Received: {overlap_wh}" + ) + + @staticmethod + def _generate_offset( + resolution_wh: tuple[int, int], + slice_wh: tuple[int, int], + overlap_wh: tuple[int, int], + ) -> npt.NDArray[Any]: + """ + Generate bounding boxes defining the coordinates of image slices with overlap. + + Args: + resolution_wh: Image resolution `(width, height)`. + slice_wh: Size of each slice `(width, height)`. + overlap_wh: Overlap size between slices `(width, height)`. + + Returns: + Array of shape `(num_slices, 4)` with each row as + `(x_min, y_min, x_max, y_max)` coordinates for a slice. + """ + slice_width, slice_height = slice_wh + image_width, image_height = resolution_wh + overlap_width, overlap_height = overlap_wh + + stride_x = slice_width - overlap_width + stride_y = slice_height - overlap_height + + def _compute_axis_starts( + image_size: int, + slice_size: int, + stride: int, + ) -> list[int]: + if image_size <= slice_size: + return [0] + + if stride == slice_size: + return list(np.arange(0, image_size, stride).tolist()) + + last_start = image_size - slice_size + starts: list[int] = list(np.arange(0, last_start, stride).tolist()) + if not starts or starts[-1] != last_start: + starts.append(last_start) + return starts + + x_starts = _compute_axis_starts( + image_size=image_width, + slice_size=slice_width, + stride=stride_x, + ) + y_starts = _compute_axis_starts( + image_size=image_height, + slice_size=slice_height, + stride=stride_y, + ) + + x_min, y_min = np.meshgrid(x_starts, y_starts) + x_max = np.clip(x_min + slice_width, 0, image_width) + y_max = np.clip(y_min + slice_height, 0, image_height) + + offsets: npt.NDArray[Any] = np.stack( + [x_min, y_min, x_max, y_max], + axis=-1, + ).reshape(-1, 4) + + return offsets + + @staticmethod + def _validate_overlap( + slice_wh: tuple[int, int], + overlap_wh: tuple[int, int], + ) -> None: + overlap_w, overlap_h = overlap_wh + slice_w, slice_h = slice_wh + + if overlap_w < 0 or overlap_h < 0: + raise ValueError( + "Overlap values must be greater than or equal to 0. " + f"Received: {overlap_wh}" + ) + + if overlap_w >= slice_w or overlap_h >= slice_h: + raise ValueError( + "`overlap_wh` must be smaller than `slice_wh` in both dimensions " + f"to keep a positive stride. Received overlap_wh={overlap_wh}, " + f"slice_wh={slice_wh}." + ) diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/tools/json_sink.py b/.venv/lib/python3.12/site-packages/supervision/detection/tools/json_sink.py new file mode 100644 index 0000000000000000000000000000000000000000..1e1ffda4feb361527e256cbfbba75d8bd89909fa --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/detection/tools/json_sink.py @@ -0,0 +1,215 @@ +from __future__ import annotations + +import io +import json +import os +from typing import Any + +import numpy as np + +from supervision.detection.core import Detections + + +class JSONSink: + """ + A utility class for saving detection data to a JSON file. This class is designed to + efficiently serialize detection objects into a JSON format, allowing for the + inclusion of bounding box coordinates and additional attributes like `confidence`, + `class_id`, and `tracker_id`. + + !!! tip + + JSONSink allows passing custom data alongside detection fields, providing + flexibility for logging various types of information. + When a NumPy array, list, or tuple value in custom_data (or + detections.data) has the same length as the detection count, each + element is written to the corresponding detection row; any other value + is broadcast to all rows. + NumPy scalars (e.g. ``np.int64``, ``np.float32``) are serialized as + JSON numbers; NumPy arrays are serialized as JSON arrays. + + Args: + file_name: The name of the JSON file where the detections will be stored. + Defaults to 'output.json'. + + Example: + ```python + import supervision as sv + from rfdetr import RFDETRMedium + + model = RFDETRMedium() + json_sink = sv.JSONSink() + frames_generator = sv.get_video_frames_generator("") + + with json_sink as sink: + for frame in frames_generator: + detections = model.predict(frame[:, :, ::-1]) + sink.append(detections, custom_data={"":""}) + ``` + """ + + def __init__(self, file_name: str = "output.json") -> None: + """ + Initialize the JSONSink instance. + + Args: + file_name: The name of the JSON file. + """ + self.file_name = file_name + self.file: io.TextIOWrapper | None = None + self.data: list[dict[str, Any]] = [] + + def __enter__(self) -> JSONSink: + self.open() + return self + + def __exit__( + self, + exc_type: type | None, + exc_val: Exception | None, + exc_tb: Any | None, + ) -> None: + self.write_and_close() + + def open(self) -> None: + """ + Open the JSON file for writing. + """ + parent_directory = os.path.dirname(self.file_name) + if parent_directory and not os.path.exists(parent_directory): + os.makedirs(parent_directory) + + self.file = open(self.file_name, "w") + self.data = [] + + @staticmethod + def _json_default(value: Any) -> Any: + """Return a JSON-serializable equivalent of a NumPy scalar or array. + + Called as the ``default`` hook by :func:`json.dump`. Converts + :class:`numpy.generic` scalars via ``.item()`` and + :class:`numpy.ndarray` instances via ``.tolist()``. + + Args: + value: Object the standard JSON encoder could not serialize. + + Returns: + A Python scalar or nested list equivalent of ``value``. + + Raises: + TypeError: If ``value`` is neither a NumPy scalar nor an ndarray. + """ + if isinstance(value, np.generic): + return value.item() + if isinstance(value, np.ndarray): + return value.tolist() + raise TypeError( + f"Object of type {type(value).__name__} is not JSON serializable" + ) + + def write_and_close(self) -> None: + """ + Write and close the JSON file. + """ + if self.file: + try: + json.dump( + self.data, self.file, indent=4, default=JSONSink._json_default + ) + finally: + self.file.close() + + @staticmethod + def _slice_value(value: Any, i: int, n: int) -> Any: + """ + Return the i-th element when the value stores per-detection data. + + Dispatch rules: + - np.ndarray with ndim == 0: return as-is for broadcasting + - np.ndarray with len equal to n: return value[i] + - list or tuple with len equal to n: return value[i] + - any other type: return as-is for broadcasting + + Args: + value: Custom-data field value. + i: Zero-based detection index. + n: Total number of detections. + + Returns: + Element at position i if value is a per-detection sequence, + otherwise value unchanged. + """ + if isinstance(value, np.ndarray): + return value[i] if value.ndim > 0 and len(value) == n else value + if isinstance(value, (list, tuple)) and len(value) == n: + return value[i] + return value + + @staticmethod + def parse_detection_data( + detections: Detections, custom_data: dict[str, Any] | None = None + ) -> list[dict[str, Any]]: + """ + Convert detections and optional custom data into per-detection rows. + + Builds one dictionary per detection containing bounding box coordinates, + detection attributes, and any values from ``detections.data`` or + ``custom_data``. NumPy array, list, and tuple values in + ``custom_data`` with length equal to ``len(detections.xyxy)`` are + sliced one element per row; all other values are broadcast to every row. + + Args: + detections: Detection data to serialize into row dictionaries. + custom_data: Optional extra fields to include in each row. + + Returns: + A list of dictionaries, one per detection, containing ``xyxy`` + coordinates, ``class_id``, ``confidence``, ``tracker_id``, and any + values from ``detections.data`` or ``custom_data``. + """ + parsed_rows = [] + n = len(detections.xyxy) + for i in range(n): + row = { + "x_min": float(detections.xyxy[i][0]), + "y_min": float(detections.xyxy[i][1]), + "x_max": float(detections.xyxy[i][2]), + "y_max": float(detections.xyxy[i][3]), + "class_id": "" + if detections.class_id is None + else int(detections.class_id[i]), + "confidence": "" + if detections.confidence is None + else float(detections.confidence[i]), + "tracker_id": "" + if detections.tracker_id is None + else int(detections.tracker_id[i]), + } + + if hasattr(detections, "data"): + for key, value in detections.data.items(): + row[key] = JSONSink._slice_value(value, i, n) + + if custom_data: + for key, value in custom_data.items(): + row[key] = JSONSink._slice_value(value, i, n) + + parsed_rows.append(row) + return parsed_rows + + def append( + self, detections: Detections, custom_data: dict[str, Any] | None = None + ) -> None: + """ + Append detection data to the JSON file. + + Args: + detections: The detection data. + custom_data: Custom data to include. Scalars, dictionaries, and + other non-sequence values are broadcast to every detection in + this batch. NumPy arrays, lists, and tuples with length equal + to ``len(detections)`` are sliced per detection; other lists + and tuples are broadcast unchanged. + """ + parsed_rows = JSONSink.parse_detection_data(detections, custom_data) + self.data.extend(parsed_rows) diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/tools/polygon_zone.py b/.venv/lib/python3.12/site-packages/supervision/detection/tools/polygon_zone.py new file mode 100644 index 0000000000000000000000000000000000000000..62e378964c39d4269765bc3d4cd1e2e0eb83a37c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/detection/tools/polygon_zone.py @@ -0,0 +1,272 @@ +from collections.abc import Iterable +from typing import Any, cast + +import numpy as np +import numpy.typing as npt + +from supervision import Detections +from supervision import _cv2 as cv2 +from supervision.detection.utils.converters import ( + MIN_POLYGON_POINT_COUNT, + polygon_to_mask, +) +from supervision.draw.color import Color +from supervision.draw.utils import draw_filled_polygon, draw_polygon, draw_text +from supervision.geometry.core import Position +from supervision.geometry.utils import get_polygon_center + + +class PolygonZone: + """ + A class for defining a polygon-shaped zone within a frame for detecting objects. + + !!! warning + + PolygonZone uses the `tracker_id`. Read + [here](/latest/trackers/) to learn how to plug + tracking into your inference pipeline. + + Attributes: + polygon: A polygon represented by a numpy array of shape + `(N, 2)`, containing the `x`, `y` coordinates of the points. + triggering_anchors: Any iterable of positions specifying + which anchors of the detections bounding box to consider when deciding on + whether the detection fits within the PolygonZone + (default: (sv.Position.BOTTOM_CENTER,)). + require_all_anchors: If `True` (default), a detection is considered inside + the zone only when *every* anchor in `triggering_anchors` is inside. + If `False`, the detection triggers as soon as *any* anchor is inside. + Has no effect when `triggering_anchors` has a single entry. + This is anchor-based, not a true geometric box/polygon intersection + test: it fires only when a listed anchor point lands inside the mask. + Use mask/IoU-based approaches instead when full-overlap semantics are + required. + current_count: The current count of detected objects within the zone + mask: The 2D bool mask for the polygon zone + + Example: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> polygon = np.array([[100, 200], [200, 100], [300, 200], [200, 300]]) + >>> polygon_zone = sv.PolygonZone(polygon=polygon) + >>> detections = sv.Detections( + ... xyxy=np.array([[180, 100, 220, 200], [400, 400, 450, 500]]) + ... ) + >>> is_detections_in_zone = polygon_zone.trigger(detections) + >>> is_detections_in_zone + array([ True, False]) + >>> polygon_zone.current_count + 1 + + ``` + + ```pycon + >>> polygon = np.array([[0, 0], [100, 0], [100, 100], [0, 100]]) + >>> polygon_zone = sv.PolygonZone( + ... polygon=polygon, + ... triggering_anchors=[sv.Position.TOP_LEFT, sv.Position.BOTTOM_RIGHT], + ... require_all_anchors=False, + ... ) + >>> detections = sv.Detections(xyxy=np.array([[80, 80, 120, 120]])) + >>> polygon_zone.trigger(detections) + array([ True]) + + ``` + """ + + def __init__( + self, + polygon: npt.NDArray[np.int64], + triggering_anchors: Iterable[Position] = (Position.BOTTOM_CENTER,), + require_all_anchors: bool = True, + ) -> None: + """Build a zone from a polygon. + + Args: + polygon: Zone boundary of shape `(N, 2)` holding the `x`, `y` + coordinates of its vertices. + triggering_anchors: Which anchors of a detection's bounding box + decide whether it falls inside the zone. + require_all_anchors: Whether every triggering anchor must be inside + for the detection to count, rather than any one of them. + + Raises: + ValueError: If `polygon` is not of shape `(N, 2)`, has fewer than + `MIN_POLYGON_POINT_COUNT` vertices, or `triggering_anchors` is + empty. + """ + polygon = np.asarray(polygon) + if polygon.ndim != 2 or polygon.shape[-1] != 2: + raise ValueError(f"Polygon must have shape (N, 2); got {polygon.shape}.") + # Fewer than three vertices enclose no area, so the mask below comes out + # empty or a bare line and the zone silently never triggers. Reject it + # here rather than let a zone that can never count look like a zone that + # simply saw nothing. Zero vertices additionally breaks `np.max`. + if len(polygon) < MIN_POLYGON_POINT_COUNT: + raise ValueError( + f"Polygon must have at least {MIN_POLYGON_POINT_COUNT} vertices " + f"to enclose an area; got {len(polygon)}." + ) + + self.polygon = polygon.astype(int) + # Materialize once so we can safely accept generators without exhausting them. + self.triggering_anchors = list(triggering_anchors) + if not self.triggering_anchors: + raise ValueError("Triggering anchors cannot be empty.") + self.require_all_anchors = require_all_anchors + + self.current_count = 0 + + x_max, y_max = np.max(polygon, axis=0) + self.mask = polygon_to_mask( + polygon=polygon, resolution_wh=(x_max + 2, y_max + 2) + ) + + def trigger(self, detections: Detections) -> npt.NDArray[np.bool_]: + """ + Determines if the detections are within the polygon zone. + + Anchor points are calculated from original (unclipped) detection boxes to + avoid per-zone clipping shifting anchor positions. This prevents a single + detection from being counted in multiple non-overlapping zones due to + clipping artifacts, although overlapping zones may still legitimately + contain the same detection. + + Args: + detections: The detections to be checked against the polygon zone + + Returns: + A boolean numpy array indicating + if each detection is within the polygon zone + """ + if len(detections) == 0: + self.current_count = 0 + return cast(npt.NDArray[np.bool_], np.array([], dtype=bool)) + + all_anchors = np.array( + [ + np.rint(detections.get_anchors_coordinates(anchors)).astype(int) + for anchors in self.triggering_anchors + ] + ) + + mask_h, mask_w = self.mask.shape + x, y = all_anchors[:, :, 0], all_anchors[:, :, 1] + in_bounds = (x >= 0) & (y >= 0) & (x < mask_w) & (y < mask_h) + x_safe = np.clip(x, 0, mask_w - 1) + y_safe = np.clip(y, 0, mask_h - 1) + anchor_hits = in_bounds & self.mask[y_safe, x_safe] + reduce = np.all if self.require_all_anchors else np.any + is_in_zone = reduce(anchor_hits, axis=0) + self.current_count = int(np.sum(is_in_zone)) + return cast(npt.NDArray[np.bool_], is_in_zone.astype(bool)) + + +class PolygonZoneAnnotator: + """ + A class for annotating a polygon-shaped zone within a frame with a count of + detected objects. + + Attributes: + zone: The polygon zone to be annotated + color: The color to draw the polygon lines, default is white + thickness: The thickness of the polygon lines, default is 2 + text_color: The color of the text on the polygon, default is black + text_scale: The scale of the text on the polygon, default is 0.5 + text_thickness: The thickness of the text on the polygon, default is 1 + text_padding: The padding around the text on the polygon, default is 10 + font: The font type for the text on the polygon, + default is cv2.FONT_HERSHEY_SIMPLEX + center: The center of the polygon for text placement + display_in_zone_count: Show the label of the zone or not. Default is True + opacity: The opacity of zone filling when drawn on the scene. Default is 0 + + Example: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> polygon = np.array([[100, 200], [200, 100], [300, 200], [200, 300]]) + >>> polygon_zone = sv.PolygonZone(polygon=polygon) + >>> zone_annotator = sv.PolygonZoneAnnotator(zone=polygon_zone, thickness=2) + >>> scene = np.zeros((400, 400, 3), dtype=np.uint8) + >>> annotated_scene = zone_annotator.annotate(scene=scene) + >>> annotated_scene.shape + (400, 400, 3) + + ``` + """ + + def __init__( + self, + zone: PolygonZone, + color: Color = Color.WHITE, + thickness: int = 2, + text_color: Color = Color.BLACK, + text_scale: float = 0.5, + text_thickness: int = 1, + text_padding: int = 10, + display_in_zone_count: bool = True, + opacity: float = 0, + ) -> None: + self.zone = zone + self.color = color + self.thickness = thickness + self.text_color = text_color + self.text_scale = text_scale + self.text_thickness = text_thickness + self.text_padding = text_padding + self.font = cv2.FONT_HERSHEY_SIMPLEX + self.center = get_polygon_center(polygon=zone.polygon) + self.display_in_zone_count = display_in_zone_count + self.opacity = opacity + + def annotate( + self, scene: npt.NDArray[Any], label: str | None = None + ) -> npt.NDArray[Any]: + """ + Annotates the polygon zone within a frame with a count of detected objects. + + Args: + scene: The image on which the polygon zone will be annotated + label: A label for the count of detected objects + within the polygon zone (default: None) + + Returns: + The image with the polygon zone and count of detected objects + """ + if self.opacity == 0: + annotated_frame = draw_polygon( + scene=scene, + polygon=self.zone.polygon, + color=self.color, + thickness=self.thickness, + ) + else: + annotated_frame = draw_filled_polygon( + scene=scene.copy(), + polygon=self.zone.polygon, + color=self.color, + opacity=self.opacity, + ) + annotated_frame = draw_polygon( + scene=annotated_frame, + polygon=self.zone.polygon, + color=self.color, + thickness=self.thickness, + ) + + if self.display_in_zone_count: + annotated_frame = draw_text( + scene=annotated_frame, + text=str(self.zone.current_count) if label is None else label, + text_anchor=self.center, + background_color=self.color, + text_color=self.text_color, + text_scale=self.text_scale, + text_thickness=self.text_thickness, + text_padding=self.text_padding, + text_font=self.font, + ) + + return cast(npt.NDArray[Any], annotated_frame) diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/tools/smoother.py b/.venv/lib/python3.12/site-packages/supervision/detection/tools/smoother.py new file mode 100644 index 0000000000000000000000000000000000000000..7b5612b1542a2e9c5689164c140b376f7704f5fa --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/detection/tools/smoother.py @@ -0,0 +1,255 @@ +import warnings +from collections import defaultdict, deque +from copy import deepcopy + +import numpy as np + +from supervision.config import ORIENTED_BOX_COORDINATES +from supervision.detection.core import Detections +from supervision.detection.utils.boxes import xyxyxyxy_to_xyxy +from supervision.utils.internal import SupervisionWarnings + + +def _align_oriented_corners(corners: np.ndarray, reference: np.ndarray) -> np.ndarray: + """Align OBB corner starts and winding with a reference representation.""" + variants = [corners, corners[:, ::-1]] + candidates = np.stack( + [ + np.roll(candidate, shift, axis=1) + for candidate in variants + for shift in range(4) + ] + ) + distances = np.sum((candidates - reference[None, ...]) ** 2, axis=(-2, -1)) + best = np.argmin(distances, axis=0) + return np.asarray(candidates[best, np.arange(corners.shape[0])]) + + +class DetectionsSmoother: + """ + A utility class for smoothing detections over multiple frames in video tracking. + It maintains a history of detections for each track and provides smoothed + predictions based on these histories. + + + + !!! warning + + - `DetectionsSmoother` requires the `tracker_id` for each detection. Refer to + [Roboflow Trackers](/latest/trackers/) for + information on integrating tracking into your inference pipeline. + - This class is not compatible with segmentation models. + - When detections in a frame disagree on confidence presence — some tracks + carry confidence scores and others do not — `confidence` is set to `None` + for all smoothed detections in that frame. + + Example: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> smoother = sv.DetectionsSmoother(length=3) + >>> detections_1 = sv.Detections( + ... xyxy=np.array([[0, 0, 10, 10]]), + ... confidence=np.array([0.5]), + ... tracker_id=np.array([1]) + ... ) + >>> detections_2 = sv.Detections( + ... xyxy=np.array([[2, 2, 12, 12]]), + ... confidence=np.array([0.7]), + ... tracker_id=np.array([1]) + ... ) + >>> smoothed = smoother.update_with_detections(detections_1) + >>> smoothed.xyxy + array([[ 0., 0., 10., 10.]]) + >>> smoothed = smoother.update_with_detections(detections_2) + >>> smoothed.xyxy + array([[ 1., 1., 11., 11.]]) + >>> smoothed.confidence + array([0.6]) + + ``` + + + ```python + import supervision as sv + + from rfdetr import RFDETRMedium + + video_info = sv.VideoInfo.from_video_path(video_path="") + frame_generator = sv.get_video_frames_generator( + source_path="") + + model = RFDETRMedium() + tracker = sv.ByteTrack(frame_rate=video_info.fps) + smoother = sv.DetectionsSmoother() + + box_annotator = sv.BoxAnnotator() + + with sv.VideoSink("", video_info=video_info) as sink: + for frame in frame_generator: + detections = model.predict(frame[:, :, ::-1]) + detections = tracker.update_with_detections(detections) + detections = smoother.update_with_detections(detections) + + annotated_frame = box_annotator.annotate(frame.copy(), detections) + sink.write_frame(annotated_frame) + ``` + """ + + def __init__(self, length: int = 5) -> None: + """ + Args: + length: The maximum number of frames to consider for smoothing + detections. Defaults to 5. + """ + self.tracks: defaultdict[int, deque[Detections | None]] = defaultdict( + lambda: deque(maxlen=length) + ) + + def reset(self) -> None: + """ + Clears the per-track detection history so the smoother can be reused + across independent streams without carrying over frames from a + previous stream. The configured window `length` is preserved. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> smoother = sv.DetectionsSmoother() + >>> detections = sv.Detections( + ... xyxy=np.array([[0, 0, 10, 10]]), + ... confidence=np.array([0.5]), + ... tracker_id=np.array([1]) + ... ) + >>> _ = smoother.update_with_detections(detections) + >>> len(smoother.tracks) + 1 + >>> smoother.reset() + >>> len(smoother.tracks) + 0 + + ``` + """ + self.tracks.clear() + + def update_with_detections(self, detections: Detections) -> Detections: + """ + Updates the smoother with a new set of detections from a frame. + + Args: + detections: The detections to add to the smoother. + """ + + if detections.tracker_id is None: + warnings.warn( + "Smoothing skipped. DetectionsSmoother requires tracker_id. Refer to " + "https://supervision.roboflow.com/latest/trackers for more " + "information.", + category=SupervisionWarnings, + ) + return detections + + for detection_idx in range(len(detections)): + tracker_id_value = detections.tracker_id[detection_idx] + tracker_id = int(tracker_id_value) + + self.tracks[tracker_id].append(detections.select(detection_idx)) + + active_ids = set(detections.tracker_id.tolist()) + + for track_id in self.tracks.keys(): + if track_id not in active_ids: + self.tracks[track_id].append(None) + + for track_id in list(self.tracks.keys()): + if all(d is None for d in self.tracks[track_id]): + del self.tracks[track_id] + + current_track_ids = active_ids + return self.get_smoothed_detections(track_ids=current_track_ids) + + def get_track(self, track_id: int) -> Detections | None: + """Return the smoothed `Detections` for a single track. + + Averages `xyxy` over all valid (non-`None`) frames in the track window. + `confidence` is averaged only over frames that carry it; frames with + `confidence=None` are excluded. When every valid frame carries compatible + oriented-box corners, those corners are aligned and averaged too, and + `xyxy` is derived from their resulting envelope. Mixed or incompatible + oriented-box metadata is dropped to keep the returned geometry consistent. + Returns `None` when the track is unknown or its entire window is empty. + + Args: + track_id: The tracker ID whose smoothed detection to retrieve. + + Returns: + Smoothed `Detections` for the track, or `None` if the track is + unknown or all frames in its window are empty. + """ + track = self.tracks.get(track_id, None) + if track is None: + return None + + valid: list[Detections] = [d for d in track if d is not None] + if len(valid) == 0: + return None + + ret = deepcopy(valid[0]) + ret.xyxy = np.mean(np.stack([d.xyxy for d in valid], axis=0), axis=0) + # Average confidence only over frames that carry it; frames with + # confidence=None contribute nothing to the mean. Retain None when + # no frame in the window carries confidence. + confidences = [d.confidence for d in valid if d.confidence is not None] + ret.confidence = np.mean(np.array(confidences), axis=0) if confidences else None + + corner_sets = [ + np.asarray(d.data[ORIENTED_BOX_COORDINATES]) + for d in valid + if ORIENTED_BOX_COORDINATES in d.data + ] + if len(corner_sets) == len(valid) and len({c.shape for c in corner_sets}) == 1: + reference = corner_sets[0] + aligned = [ + _align_oriented_corners(corners, reference) for corners in corner_sets + ] + smoothed_corners = np.mean(np.stack(aligned, axis=0), axis=0) + ret.data[ORIENTED_BOX_COORDINATES] = smoothed_corners + ret.xyxy = xyxyxyxy_to_xyxy(smoothed_corners) + else: + ret.data.pop(ORIENTED_BOX_COORDINATES, None) + + return ret + + def get_smoothed_detections(self, track_ids: set[int] | None = None) -> Detections: + """Return the smoothed detections for the requested active tracks. + + Args: + track_ids: Optional set of track IDs to include in the output. When + provided, tracks absent from the current frame are excluded from the + emitted detections but their history stays cached. + """ + tracked_detections = [] + for track_id in self.tracks: + if track_ids is not None and track_id not in track_ids: + continue + track = self.get_track(track_id) + if track is not None: + tracked_detections.append(track) + + # Detections.merge requires all-or-none for optional fields. + # When tracks disagree on confidence presence, drop it from all to + # prevent ValueError inside Detections.merge (stack_or_none invariant). + if tracked_detections and any(d.confidence is None for d in tracked_detections): + for d in tracked_detections: + d.confidence = None + + detections = Detections.merge(tracked_detections) + if len(detections) == 0: + detections.tracker_id = np.array([], dtype=int) + + return detections diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/tools/transformers.py b/.venv/lib/python3.12/site-packages/supervision/detection/tools/transformers.py new file mode 100644 index 0000000000000000000000000000000000000000..7f03f2d4440c1b91e22c03361434e88a3ba7fbd2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/detection/tools/transformers.py @@ -0,0 +1,279 @@ +from __future__ import annotations + +import io +from typing import Any, cast + +import numpy as np +import numpy.typing as npt +from PIL import Image + +from supervision.config import CLASS_NAME_DATA_FIELD +from supervision.detection.utils.converters import mask_to_xyxy + + +def process_transformers_detection_result( + detection_result: dict[str, Any], id2label: dict[int, str] | None +) -> dict[str, Any]: + """ + Process the result of Transformers object detection functions such as + `post_process` (v4) and `post_process_detection` (v5). + + Args: + detection_result: Dictionary containing detection results with keys + 'boxes', 'labels', and 'scores'. + id2label: A dictionary mapping class IDs to labels, + typically part of the `transformers` model configuration. If provided, the + resulting dictionary will include class names. + + Returns: + Processed detection result including bounding boxes, confidence scores, + class IDs, and data. + """ + class_ids = detection_result["labels"].cpu().detach().numpy().astype(int) + data = append_class_names_to_data(class_ids, id2label, {}) + + return dict( + xyxy=detection_result["boxes"].cpu().detach().numpy(), + confidence=detection_result["scores"].cpu().detach().numpy(), + class_id=class_ids, + data=data, + ) + + +def process_transformers_v4_segmentation_result( + segmentation_result: dict[str, Any], id2label: dict[int, str] | None +) -> dict[str, Any]: + """ + Process the result of Transformers segmentation functions such as + `post_process_panoptic`, `post_process_segmentation`, and `post_process_instance` + (v4). + + Args: + segmentation_result: Dictionary containing segmentation results with keys + 'masks', 'labels', and 'scores'. + id2label: A dictionary mapping class IDs to labels, + typically part of the `transformers` model configuration. If provided, the + resulting dictionary will include class names. + + Returns: + Processed segmentation result including bounding boxes, masks, confidence + scores, class IDs, and data. + """ + if "png_string" in segmentation_result: + return process_transformers_v4_panoptic_segmentation_result( + segmentation_result, id2label + ) + else: + boxes = None + if "boxes" in segmentation_result: + boxes = segmentation_result["boxes"].cpu().detach().numpy() + masks = segmentation_result["masks"].cpu().detach().numpy().astype(bool) + class_ids = segmentation_result["labels"].cpu().detach().numpy().astype(int) + + return dict( + xyxy=boxes if boxes is not None else mask_to_xyxy(masks), + mask=np.squeeze(masks, axis=1) if boxes is not None else masks, + confidence=segmentation_result["scores"].cpu().detach().numpy(), + class_id=class_ids, + data=append_class_names_to_data(class_ids, id2label, {}), + ) + + +def process_transformers_v5_segmentation_result( + segmentation_result: Any, id2label: dict[int, str] | None +) -> dict[str, Any]: + """ + Process the result of Transformers segmentation functions such as + `post_process_semantic_segmentation`, `post_process_instance_segmentation`, and + `post_process_panoptic_segmentation` (v5). + + Args: + segmentation_result: Either a dictionary containing segmentation results + (`segments_info` and `segmentation`) or a tensor object + representing a semantic segmentation map. + id2label: A dictionary mapping class IDs to labels, + typically part of the `transformers` model configuration. If provided, the + resulting dictionary will include class names. + + Returns: + Processed segmentation result including bounding boxes, masks, confidence + scores, class IDs, and data. + """ + if segmentation_result.__class__.__name__ == "Tensor": + segmentation_array = segmentation_result.cpu().detach().numpy() + return process_transformers_v5_panoptic_segmentation_result( + segmentation_array, id2label + ) + return process_transformers_v5_semantic_or_instance_segmentation_result( + cast(dict[str, Any], segmentation_result), id2label + ) + + +def process_transformers_v5_semantic_or_instance_segmentation_result( + segmentation_result: dict[str, Any], id2label: dict[int, str] | None +) -> dict[str, Any]: + """ + Process the result of Transformers segmentation functions such as + `post_process_semantic_segmentation` and `post_process_instance_segmentation` (v5). + + Args: + segmentation_result: Dictionary containing segmentation results with keys + `segments_info` and `segmentation`. `segmentation` is either a + `(height, width)` map of segment ids or, for + `post_process_instance_segmentation(return_binary_maps=True)`, a + `(num_segments, height, width)` stack of binary maps. + id2label: A dictionary mapping class IDs to labels, + typically part of the `transformers` model configuration. If provided, the + resulting dictionary will include class names. + + Returns: + Processed segmentation result including bounding boxes, masks, confidence + scores, class IDs, and data. + """ + segments_info = segmentation_result["segments_info"] + segmentation_array = segmentation_result["segmentation"].cpu().detach().numpy() + scores = np.array([segment["score"] for segment in segments_info], dtype=float) + class_ids = np.array([segment["label_id"] for segment in segments_info], dtype=int) + if len(segments_info) == 0: + masks = np.empty((0, *segmentation_array.shape), dtype=bool) + elif segmentation_array.ndim == 3: + # Binary maps are stacked in the order segment ids were assigned, so each + # segment's `id` indexes its own map. Reading the maps directly also keeps + # pixels shared by overlapping instances, which a segment-id map drops. + segment_ids = [segment["id"] for segment in segments_info] + masks = segmentation_array[segment_ids].astype(bool) + else: + masks = np.array( + [segmentation_array == segment["id"] for segment in segments_info] + ).astype(bool) + data = append_class_names_to_data(class_ids, id2label, {}) + + return dict( + xyxy=mask_to_xyxy(masks), + mask=masks, + confidence=scores, + class_id=class_ids, + data=data, + ) + + +def process_transformers_v4_panoptic_segmentation_result( + segmentation_result: dict[str, Any], id2label: dict[int, str] | None +) -> dict[str, Any]: + """ + Process the result of the Transformers function `post_process_panoptic` (v4). + + Args: + segmentation_result: Dictionary containing segmentation results with keys + such as 'png_string' and 'segments_info'. + id2label: A dictionary mapping class IDs to labels, + typically part of the `transformers` model configuration. If provided, the + resulting dictionary will include class names. + + Returns: + Processed segmentation result including bounding boxes, masks, + class IDs, and data. + """ + segments_info = segmentation_result["segments_info"] + png_string = segmentation_result["png_string"] + class_ids = np.array( + [segment["category_id"] for segment in segments_info], dtype=int + ) + segmentation_array = png_string_to_segmentation_array(png_string=png_string) + if len(segments_info) == 0: + masks = np.empty((0, *segmentation_array.shape), dtype=bool) + else: + masks = np.array( + [segmentation_array == segment["id"] for segment in segments_info] + ).astype(bool) + data = append_class_names_to_data(class_ids, id2label, {}) + + return dict( + xyxy=mask_to_xyxy(masks), + mask=masks, + class_id=class_ids, + data=data, + ) + + +def process_transformers_v5_panoptic_segmentation_result( + segmentation_array: npt.NDArray[Any], id2label: dict[int, str] | None +) -> dict[str, Any]: + """ + Process a v5 Transformers semantic segmentation tensor. + + Args: + segmentation_array: Segmentation array where unique values are class IDs. + id2label: A dictionary mapping class IDs to labels, + typically part of the `transformers` model configuration. If provided, the + resulting dictionary will include class names. + + Returns: + Processed segmentation result including bounding boxes, masks, + class IDs, and data. + """ + class_ids = np.unique(segmentation_array).astype(int) + if len(class_ids) == 0: + masks = np.empty((0, *segmentation_array.shape), dtype=bool) + else: + masks = np.stack( + [segmentation_array == class_id for class_id in class_ids], axis=0 + ).astype(bool) + data = append_class_names_to_data(class_ids, id2label, {}) + return dict(xyxy=mask_to_xyxy(masks), mask=masks, class_id=class_ids, data=data) + + +def png_string_to_segmentation_array(png_string: bytes) -> npt.NDArray[Any]: + """ + Convert a PNG byte string to a panoptic segmentation array. + + Args: + png_string: A byte string representing the PNG image. + + Returns: + A segmentation ID array with shape (H, W), where each unique value + represents a different object or category. RGB-encoded panoptic + PNGs are decoded as little-endian 24-bit integers; alpha is ignored. + """ + image = Image.open(io.BytesIO(png_string)) + mask = np.array(image, dtype=np.uint8) + if mask.ndim == 2: + return mask.astype(np.uint32) + if mask.shape[2] < 3: + raise ValueError("Panoptic PNG masks must have at least 3 channels.") + + segmentation = ( + mask[:, :, 0].astype(np.uint32) + + (mask[:, :, 1].astype(np.uint32) << 8) + + (mask[:, :, 2].astype(np.uint32) << 16) + ) + return cast(npt.NDArray[Any], segmentation) + + +def append_class_names_to_data( + class_ids: npt.NDArray[Any], + id2label: dict[int, str] | None, + data: dict[str, Any] | None = None, +) -> dict[str, Any]: + """ + Helper function to create or append to a data dictionary with class names if + available. + + Args: + class_ids: Array of class IDs. + id2label: A dictionary mapping class IDs to labels, + typically part of the `transformers` model configuration. If provided, the + resulting dictionary will include class names. + data: An existing data dictionary to append to. + + Returns: + Dictionary containing class names if id2label is provided. + """ + if data is None: + data = {} + + if id2label is not None: + class_names = np.array([id2label[class_id] for class_id in class_ids]) + data[CLASS_NAME_DATA_FIELD] = class_names + + return data diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/utils/__init__.py b/.venv/lib/python3.12/site-packages/supervision/detection/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/utils/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/detection/utils/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..253a503891017ef997cd43d495be9dec767b9667 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/detection/utils/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/utils/__pycache__/_typing.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/detection/utils/__pycache__/_typing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..503f150c4ed451d96ad21dbb720bdd500b5b8e4b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/detection/utils/__pycache__/_typing.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/utils/__pycache__/boxes.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/detection/utils/__pycache__/boxes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69a67aa8768af1ac49d1c29094c6497523165a4a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/detection/utils/__pycache__/boxes.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/utils/__pycache__/converters.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/detection/utils/__pycache__/converters.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d7d7091a9424561abe7b011cca5f4102186c41b7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/detection/utils/__pycache__/converters.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/utils/__pycache__/internal.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/detection/utils/__pycache__/internal.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7954129929a8fb7c077dc4bb52b9c4cf88c720fd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/detection/utils/__pycache__/internal.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/utils/__pycache__/iou_and_nms.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/detection/utils/__pycache__/iou_and_nms.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd7e113591982e54db3811f0ebffb5cf990e78ce Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/detection/utils/__pycache__/iou_and_nms.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/utils/__pycache__/masks.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/detection/utils/__pycache__/masks.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e7fe74d8633f4140c289eb0abd087a60854745f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/detection/utils/__pycache__/masks.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/utils/__pycache__/polygons.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/detection/utils/__pycache__/polygons.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a0bb62f7ebc12ad4603574dc509b938e4a49f5e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/detection/utils/__pycache__/polygons.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/utils/__pycache__/vlms.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/detection/utils/__pycache__/vlms.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a1b9c5588573b920b6916bcc873268a2d8bf01a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/detection/utils/__pycache__/vlms.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/utils/_typing.py b/.venv/lib/python3.12/site-packages/supervision/detection/utils/_typing.py new file mode 100644 index 0000000000000000000000000000000000000000..7b903ab367ddf05a963f8c1446908c5c8be34bac --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/detection/utils/_typing.py @@ -0,0 +1,8 @@ +from typing import Any, TypeAlias + +import numpy as np +import numpy.typing as npt + +_DetectionDataValueType: TypeAlias = npt.NDArray[np.generic] | list[Any] +_DetectionDataType: TypeAlias = dict[str, _DetectionDataValueType] +_MetadataType: TypeAlias = dict[str, Any] diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/utils/boxes.py b/.venv/lib/python3.12/site-packages/supervision/detection/utils/boxes.py new file mode 100644 index 0000000000000000000000000000000000000000..4b18f221b3920b218e66b28d614d3f9eb20f12d0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/detection/utils/boxes.py @@ -0,0 +1,638 @@ +from typing import Any, cast + +import numpy as np +import numpy.typing as npt +from deprecate import ( # type: ignore[import-untyped,unused-ignore] + TargetMode, + deprecated, +) + +from supervision.detection.utils.iou_and_nms import box_iou_batch +from supervision.geometry.core import Position + + +def clip_boxes( + xyxy: npt.NDArray[np.number], + resolution_wh: tuple[int, int], +) -> npt.NDArray[np.number]: + """ + Clips bounding boxes coordinates to fit within the frame resolution. + + Args: + xyxy: A numpy array of shape `(N, 4)` where each + row corresponds to a bounding box in + the format `(x_min, y_min, x_max, y_max)`. + resolution_wh: A tuple of the form + `(width, height)` representing the resolution of the frame. + + Returns: + A numpy array of shape `(N, 4)` where each row + corresponds to a bounding box with coordinates clipped to fit + within the frame resolution. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> xyxy = np.array([ + ... [10, 20, 300, 200], + ... [15, 25, 350, 450], + ... [-10, -20, 30, 40] + ... ]) + >>> sv.clip_boxes(xyxy=xyxy, resolution_wh=(320, 240)) + array([[ 10, 20, 300, 200], + [ 15, 25, 320, 240], + [ 0, 0, 30, 40]]) + + ``` + """ + result: npt.NDArray[np.number] = np.copy(xyxy) + width, height = resolution_wh + result[:, [0, 2]] = result[:, [0, 2]].clip(0, width) + result[:, [1, 3]] = result[:, [1, 3]].clip(0, height) + return result + + +def pad_boxes( + xyxy: npt.NDArray[np.number], + px: int, + py: int | None = None, +) -> npt.NDArray[np.number]: + """ + Pads bounding boxes coordinates with a constant padding. + + Args: + xyxy: A numpy array of shape `(N, 4)` where each + row corresponds to a bounding box in the format + `(x_min, y_min, x_max, y_max)`. + px: The padding value to be added to both the left and right sides of + each bounding box. + py: The padding value to be added to both the top and bottom + sides of each bounding box. If not provided, `px` will be used for both + dimensions. + + Returns: + A numpy array of shape `(N, 4)` where each row corresponds to a + bounding box with coordinates padded according to the provided padding + values. Integer inputs produce `int64` output, or `float64` if a padded + coordinate exceeds the `int64` range. Floating-point inputs preserve + their dtype. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> xyxy = np.array([ + ... [10, 20, 30, 40], + ... [15, 25, 35, 45] + ... ]) + >>> sv.pad_boxes(xyxy=xyxy, px=5, py=10) + array([[ 5, 10, 35, 50], + [10, 15, 40, 55]]) + + ``` + """ + if py is None: + py = px + + integer_input = np.issubdtype(xyxy.dtype, np.integer) + padding: list[int] | npt.NDArray[Any] = [px, py] + if integer_input: + px, py = int(px), int(py) + exact_integer_limit = np.iinfo(np.int64).max // 2 + is_safe_to_cast = max(abs(px), abs(py)) <= exact_integer_limit and np.all( + xyxy <= exact_integer_limit + if np.issubdtype(xyxy.dtype, np.unsignedinteger) + else (xyxy >= -exact_integer_limit) & (xyxy <= exact_integer_limit) + ) + # Use exact Python integers only when int64 intermediates could overflow. + result = xyxy.astype(np.int64 if is_safe_to_cast else object) + padding = np.asarray([px, py], dtype=result.dtype) + else: + result = cast(npt.NDArray[Any], xyxy.copy()) + result[:, [0, 1]] -= padding + result[:, [2, 3]] += padding + + if integer_input and result.dtype == object: + limits = np.iinfo(np.int64) + fits_int64 = np.all((result >= limits.min) & (result <= limits.max)) + return cast( + npt.NDArray[np.number], + np.asarray(result, dtype=np.int64 if fits_int64 else np.float64), + ) + return cast(npt.NDArray[np.number], result) + + +@deprecated( # type: ignore[untyped-decorator] + target=TargetMode.ARGS_REMAP, + deprecated_in="0.27.0", + remove_in="0.31.0", + args_mapping={"normalized_xyxy": "xyxy"}, +) +def denormalize_boxes( + xyxy: npt.NDArray[np.number], + resolution_wh: tuple[int, int], + normalization_factor: float = 1.0, + normalized_xyxy: npt.NDArray[np.number] | None = None, +) -> npt.NDArray[np.number]: + """ + Convert normalized bounding box coordinates to absolute pixel coordinates. + + Multiplies each bounding box coordinate by image size and divides by + `normalization_factor`, mapping values from normalized `[0, normalization_factor]` + to absolute pixel values for a given resolution. + + Args: + xyxy: Normalized bounding boxes of shape `(N, 4)`, + where each row is `(x_min, y_min, x_max, y_max)`, values in + `[0, normalization_factor]`. + resolution_wh: Target image resolution as `(width, height)`. + normalization_factor: Maximum value of input coordinate range. + Defaults to `1.0`. + + Returns: + Array of shape `(N, 4)` with absolute coordinates in + `(x_min, y_min, x_max, y_max)` format. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> xyxy = np.array([ + ... [0.1, 0.2, 0.5, 0.6], + ... [0.3, 0.4, 0.7, 0.8], + ... [0.2, 0.1, 0.6, 0.5] + ... ]) + >>> sv.denormalize_boxes(xyxy, (1280, 720)) + array([[128., 144., 640., 432.], + [384., 288., 896., 576.], + [256., 72., 768., 360.]]) + + ``` + + ```pycon + >>> xyxy = np.array([ + ... [256., 128., 768., 640.] + ... ]) + >>> sv.denormalize_boxes(xyxy, (1280, 720), normalization_factor=1024.0) + array([[320., 90., 960., 450.]]) + + ``` + """ + width, height = resolution_wh + + # Preserve floating caller dtypes; integer inputs need float64 to retain + # fractional pixel coordinates rather than silently truncating them. + scale_dtype = ( + xyxy.dtype if np.issubdtype(xyxy.dtype, np.inexact) else np.dtype(np.float64) + ) + scale = np.array([width, height, width, height], dtype=scale_dtype) + scale /= normalization_factor + + return xyxy * scale + + +def _sort_box_corners( + xyxy: npt.NDArray[np.number], +) -> npt.NDArray[np.number]: + """Order each box's corners so that `x_min <= x_max` and `y_min <= y_max`. + + `Detections.xyxy` is defined as `(x_min, y_min, x_max, y_max)`, and every + box operation in the library relies on that ordering: `box_iou_batch` + clamps its intersection widths at zero, so a box whose corners arrive + swapped scores an IoU of `0` even against itself. `box_area` hides the + problem rather than surfacing it, because negating both sides leaves their + product positive. Sorting the corner pairs restores the invariant without + moving the region a box describes; a correctly ordered box is unchanged. + + Args: + xyxy: Boxes of shape `(N, 4)`, each row `(x_min, y_min, x_max, y_max)`, + possibly with either corner pair transposed. + + Returns: + Boxes of shape `(N, 4)` with both corner pairs in ascending order. + + Examples: + ```pycon + >>> import numpy as np + >>> from supervision.detection.utils.boxes import _sort_box_corners + >>> _sort_box_corners(np.array([[300.0, 320.0, 200.0, 80.0]])) + array([[200., 80., 300., 320.]]) + + ``` + """ + xyxy = np.asarray(xyxy) + if xyxy.size == 0: + return xyxy + x_min = np.minimum(xyxy[:, 0], xyxy[:, 2]) + x_max = np.maximum(xyxy[:, 0], xyxy[:, 2]) + y_min = np.minimum(xyxy[:, 1], xyxy[:, 3]) + y_max = np.maximum(xyxy[:, 1], xyxy[:, 3]) + return cast(npt.NDArray[np.number], np.stack([x_min, y_min, x_max, y_max], axis=-1)) + + +def move_boxes( + xyxy: npt.NDArray[np.number], offset: npt.NDArray[np.integer] +) -> npt.NDArray[np.number]: + """ + Args: + xyxy: An array of shape `(n, 4)` containing the + bounding boxes coordinates in format `[x1, y1, x2, y2]` + offset: An array of shape `(2,)` containing offset values in format + is `[dx, dy]`. + + Returns: + Repositioned bounding boxes. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> xyxy = np.array([ + ... [10, 10, 20, 20], + ... [30, 30, 40, 40] + ... ]) + >>> offset = np.array([5, 5]) + >>> sv.move_boxes(xyxy=xyxy, offset=offset) + array([[15, 15, 25, 25], + [35, 35, 45, 45]]) + + ``` + """ + return xyxy + np.hstack([offset, offset]) + + +def move_oriented_boxes( + xyxyxyxy: npt.NDArray[np.number], offset: npt.NDArray[np.integer] +) -> npt.NDArray[np.number]: + """ + Args: + xyxyxyxy: An array of shape `(n, 4, 2)` containing the + oriented bounding boxes coordinates in format + `[[x1, y1], [x2, y2], [x3, y3], [x3, y3]]` + offset: An array of shape `(2,)` containing offset values in format + is `[dx, dy]`. + + Returns: + Repositioned bounding boxes. + + Examples: + ```pycon + >>> import numpy as np + >>> from supervision.detection.utils.boxes import move_oriented_boxes + >>> xyxyxyxy = np.array([ + ... [ + ... [20, 10], + ... [10, 20], + ... [20, 30], + ... [30, 20] + ... ], + ... [ + ... [30, 30], + ... [20, 40], + ... [30, 50], + ... [40, 40] + ... ] + ... ]) + >>> offset = np.array([5, 5]) + >>> move_oriented_boxes(xyxyxyxy=xyxyxyxy, offset=offset) + array([[[25, 15], + [15, 25], + [25, 35], + [35, 25]], + + [[35, 35], + [25, 45], + [35, 55], + [45, 45]]]) + + ``` + """ + return xyxyxyxy + offset + + +def obb_polygon_area(corners: npt.NDArray[np.number]) -> npt.NDArray[np.float64]: + """Compute the area of N oriented bounding boxes using the shoelace formula. + + Args: + corners: OBB corner coordinates with shape `(N, 4, 2)`. + + Returns: + Area of each box as a 1-D float64 array of shape `(N,)`. + + Raises: + ValueError: If `corners` does not have shape `(N, 4, 2)`. + + Examples: + ```pycon + >>> import numpy as np + >>> from supervision.detection.utils.boxes import obb_polygon_area + >>> corners = np.array([[[0, 5], [5, 10], [10, 5], [5, 0]]], dtype=np.float32) + >>> obb_polygon_area(corners) + array([50.]) + + ``` + """ + corners = cast(npt.NDArray[np.number], np.asarray(corners)) + if corners.ndim != 3 or corners.shape[-2:] != (4, 2): + raise ValueError(f"corners must have shape (N, 4, 2); got {corners.shape}") + # Translate each box before the shoelace products so representable integer + # coordinates with large origins (e.g. geospatial or stitched frames) are + # reduced to local extents before conversion to float64. Float inputs that + # were already quantized retain their input precision. + origin = corners[:, 0:1, :] + if np.issubdtype(corners.dtype, np.integer): + # Object arithmetic avoids unsigned underflow and signed overflow before + # the exact integer differences are converted to float64. + translated = np.asarray( + corners.astype(object) - origin.astype(object), dtype=np.float64 + ) + else: + translated = corners.astype(np.float64, copy=False) - origin.astype( + np.float64, copy=False + ) + x = translated[..., 0] + y = translated[..., 1] + cross = x * np.roll(y, -1, axis=-1) - y * np.roll(x, -1, axis=-1) + return cast(npt.NDArray[np.float64], 0.5 * np.abs(np.sum(cross, axis=-1))) + + +def xyxyxyxy_to_xyxy( + xyxyxyxy: npt.NDArray[np.number], +) -> npt.NDArray[np.number]: + """Convert oriented bounding box corners to axis-aligned bounding boxes. + + Args: + xyxyxyxy: OBB corner coordinates with shape `(N, 4, 2)` where each + box is represented as `[[x1, y1], [x2, y2], [x3, y3], [x4, y4]]`. + + Returns: + Axis-aligned bounding boxes as an array of shape `(N, 4)` + in `(x_min, y_min, x_max, y_max)` format. + + Raises: + ValueError: If `xyxyxyxy` does not have shape `(N, 4, 2)`. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> corners = np.array([ + ... [[0, 0], [10, 0], [10, 5], [0, 5]], + ... [[5, 5], [15, 5], [15, 10], [5, 10]], + ... ], dtype=np.float32) + >>> sv.xyxyxyxy_to_xyxy(corners) + array([[ 0., 0., 10., 5.], + [ 5., 5., 15., 10.]], dtype=float32) + + ``` + """ + xyxyxyxy = cast(npt.NDArray[np.number], np.asarray(xyxyxyxy)) + if xyxyxyxy.ndim != 3 or xyxyxyxy.shape[-2:] != (4, 2): + raise ValueError(f"xyxyxyxy must have shape (N, 4, 2); got {xyxyxyxy.shape}") + x_min = xyxyxyxy[..., 0].min(axis=-1) + y_min = xyxyxyxy[..., 1].min(axis=-1) + x_max = xyxyxyxy[..., 0].max(axis=-1) + y_max = xyxyxyxy[..., 1].max(axis=-1) + return cast(npt.NDArray[np.number], np.stack([x_min, y_min, x_max, y_max], axis=-1)) + + +# Anchor position -> (sx, sy) offset from the box center, in units of the box +# half-width and half-height. Image coordinates, so +y points down. +_ANCHOR_OFFSETS: dict[Position, tuple[float, float]] = { + Position.CENTER: (0.0, 0.0), + Position.CENTER_LEFT: (-1.0, 0.0), + Position.CENTER_RIGHT: (1.0, 0.0), + Position.TOP_CENTER: (0.0, -1.0), + Position.BOTTOM_CENTER: (0.0, 1.0), + Position.TOP_LEFT: (-1.0, -1.0), + Position.TOP_RIGHT: (1.0, -1.0), + Position.BOTTOM_LEFT: (-1.0, 1.0), + Position.BOTTOM_RIGHT: (1.0, 1.0), +} + + +def _oriented_box_anchors( + xyxyxyxy: npt.NDArray[np.number], anchor: Position +) -> npt.NDArray[np.float64]: + """Locate an anchor point on each oriented bounding box. + + The returned point always lies on the oriented rectangle itself: corners map + to corners, side anchors to side midpoints, and `CENTER` to the box center. + For an axis-aligned box the result matches the anchor derived from the + envelope, so this is a drop-in replacement that stops the anchor from drifting + off a rotated body. + + Args: + xyxyxyxy: OBB corner coordinates with shape `(N, 4, 2)` in winding order, + each box as `[[x1, y1], [x2, y2], [x3, y3], [x4, y4]]`. + anchor: The anchor position to locate. `Position.CENTER_OF_MASS` is not + supported here, as it is defined on a mask rather than a box. + + Returns: + Anchor coordinates as an array of shape `(N, 2)`. + + Raises: + ValueError: If `xyxyxyxy` does not have shape `(N, 4, 2)`, or the anchor + is not supported. + + Note: + Corners must be in consecutive winding order (clockwise or + counter-clockwise). Non-sequential ordering (e.g. diagonal pairs) + silently produces incorrect results. + + Width and height are determined by x-axis projection of each half-side + vector. When a box rotates past ``arctan(w/h)`` (approx. 68 deg for a + 10 x 4 box) the assigned *width* side flips discontinuously, producing + a jump in anchor position (~``|w - h|`` pixels for ``BOTTOM_CENTER``). + The anchor always lies on the box; the effect is cosmetic for static + images but visible on rotating objects in video. + + Examples: + ```pycon + >>> import numpy as np + >>> from supervision.detection.utils.boxes import _oriented_box_anchors + >>> from supervision.geometry.core import Position + >>> corners = np.array( + ... [[[0, 0], [10, 0], [10, 4], [0, 4]]], dtype=np.float32 + ... ) + >>> _oriented_box_anchors(corners, Position.BOTTOM_CENTER) + array([[5., 4.]]) + + ``` + """ + corners = np.asarray(xyxyxyxy, dtype=np.float64) + if corners.ndim != 3 or corners.shape[-2:] != (4, 2): + raise ValueError(f"xyxyxyxy must have shape (N, 4, 2); got {corners.shape}") + if anchor not in _ANCHOR_OFFSETS: + raise ValueError(f"{anchor} is not supported.") + sx, sy = _ANCHOR_OFFSETS[anchor] + + center = corners.mean(axis=1) + # Two perpendicular half-side vectors per box. + half_side_a = (corners[:, 1] - corners[:, 0]) / 2 + half_side_b = (corners[:, 2] - corners[:, 1]) / 2 + + # Map each box's own sides onto the image axes: the side more aligned with + # the x-axis plays the role of width, the other of height. This makes the + # offsets collapse to the axis-aligned frame when the box is not rotated. + is_width = np.abs(half_side_a[:, 0]) >= np.abs(half_side_b[:, 0]) + width = np.where(is_width[:, None], half_side_a, half_side_b) + height = np.where(is_width[:, None], half_side_b, half_side_a) + # Point width toward +x and height toward +y so the offset signs are stable. + width = np.where((width[:, 0] < 0)[:, None], -width, width) + height = np.where((height[:, 1] < 0)[:, None], -height, height) + + return cast(npt.NDArray[np.float64], center + sx * width + sy * height) + + +def scale_boxes( + xyxy: npt.NDArray[np.number], factor: float +) -> npt.NDArray[np.floating]: + """ + Scale the dimensions of bounding boxes. + + Args: + xyxy: An integer or floating-point array of shape `(n, 4)` containing + bounding box coordinates in format `[x1, y1, x2, y2]`. + factor: A float value representing the factor by which the box + dimensions are scaled. A factor greater than 1 enlarges the boxes, while a + factor less than 1 shrinks them. + + Returns: + Scaled bounding boxes. Integer input arrays produce `float64` output; + floating-point inputs preserve their existing dtype. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> xyxy = np.array([ + ... [10, 10, 20, 20], + ... [30, 30, 40, 40] + ... ]) + >>> sv.scale_boxes(xyxy=xyxy, factor=1.5) + array([[ 7.5, 7.5, 22.5, 22.5], + [27.5, 27.5, 42.5, 42.5]]) + + ``` + """ + if np.issubdtype(xyxy.dtype, np.integer): + exact_integer_limit = 2**52 + is_safe_to_cast = np.all( + xyxy <= exact_integer_limit + if np.issubdtype(xyxy.dtype, np.unsignedinteger) + else (xyxy >= -exact_integer_limit) & (xyxy <= exact_integer_limit) + ) + if is_safe_to_cast: + xyxy = xyxy.astype(np.float64) + elif np.isfinite(factor): + # Preserve 64-bit integer precision through both final-corner + # expressions. Converting the center first can change the final + # float64 rounding near 2**53. + factor_numerator, factor_denominator = factor.as_integer_ratio() + integer_coordinates = xyxy.astype(object) + coordinate_sum = integer_coordinates[:, :2] + integer_coordinates[:, 2:] + coordinate_size = integer_coordinates[:, 2:] - integer_coordinates[:, :2] + denominator = 2 * factor_denominator + lower = np.asarray( + ( + coordinate_sum * factor_denominator + - coordinate_size * factor_numerator + ) + / denominator, + dtype=np.float64, + ) + upper = np.asarray( + ( + coordinate_sum * factor_denominator + + coordinate_size * factor_numerator + ) + / denominator, + dtype=np.float64, + ) + return cast( + npt.NDArray[np.floating], np.concatenate((lower, upper), axis=1) + ) + else: + xyxy = xyxy.astype(np.float64) + + centers = cast(npt.NDArray[np.floating], (xyxy[:, :2] + xyxy[:, 2:]) / 2) + new_sizes = cast(npt.NDArray[np.floating], (xyxy[:, 2:] - xyxy[:, :2]) * factor) + return cast( + npt.NDArray[np.floating], + np.concatenate((centers - new_sizes / 2, centers + new_sizes / 2), axis=1), + ) + + +def spread_out_boxes( + xyxy: npt.NDArray[np.number], + max_iterations: int = 100, +) -> npt.NDArray[np.number]: + """ + Spread out boxes that overlap with each other. + + Args: + xyxy: Numpy array of shape (N, 4) where N is the number of boxes. + max_iterations: Maximum number of iterations to run the algorithm for. + + Example: + ```pycon + >>> import numpy as np + >>> from supervision.detection.utils.boxes import spread_out_boxes + >>> xyxy = np.array([ + ... [10, 10, 20, 20], + ... [12, 12, 22, 22] + ... ]) + >>> spread_out = spread_out_boxes(xyxy=xyxy, max_iterations=10) + >>> # The boxes should be moved apart + >>> bool(spread_out[0, 0] < 10 and spread_out[0, 1] < 10) + True + >>> bool(spread_out[1, 0] > 12 and spread_out[1, 1] > 12) + True + + ``` + """ + if len(xyxy) == 0: + return xyxy + + xyxy_padded = cast(npt.NDArray[Any], pad_boxes(xyxy, px=1)) + for _ in range(max_iterations): + # NxN + iou = box_iou_batch(xyxy_padded, xyxy_padded) + np.fill_diagonal(iou, 0) + if np.all(iou == 0): + break + + overlap_mask = iou > 0 + + # Nx2 + centers = (xyxy_padded[:, :2] + xyxy_padded[:, 2:]) / 2 + + # NxNx2 + delta_centers = centers[:, np.newaxis, :] - centers[np.newaxis, :, :] + delta_centers *= overlap_mask[:, :, np.newaxis] + + # Nx2 + delta_sum = np.sum(delta_centers, axis=1) + delta_magnitude = np.linalg.norm(delta_sum, axis=1, keepdims=True) + direction_vectors = np.divide( + delta_sum, + delta_magnitude, + out=np.zeros_like(delta_sum), + where=delta_magnitude != 0, + ) + + force_vectors = np.sum(iou, axis=1) + force_vectors = force_vectors[:, np.newaxis] * direction_vectors + + force_vectors *= 10 + force_vectors[(force_vectors > 0) & (force_vectors < 2)] = 2 + force_vectors[(force_vectors < 0) & (force_vectors > -2)] = -2 + + force_vectors = force_vectors.astype(int) + + xyxy_padded[:, [0, 1]] += force_vectors + xyxy_padded[:, [2, 3]] += force_vectors + + return pad_boxes(xyxy_padded, px=-1) diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/utils/converters.py b/.venv/lib/python3.12/site-packages/supervision/detection/utils/converters.py new file mode 100644 index 0000000000000000000000000000000000000000..f327e94dbddf927dee6992de5f9d8807e01c4efd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/detection/utils/converters.py @@ -0,0 +1,837 @@ +from __future__ import annotations + +from typing import Any, Literal, cast + +import numpy as np +import numpy.typing as npt + +from supervision import _cv2 as cv2 + +MIN_POLYGON_POINT_COUNT = 3 +CoordinateConvention = Literal["inclusive", "exclusive"] + + +def xyxy_to_polygons(box: npt.NDArray[np.number]) -> npt.NDArray[np.number]: + """ + Convert an array of boxes to an array of polygons. + Retains the input datatype. + + Args: + box: An array of boxes (N, 4), where each box is represented as a + list of four coordinates in the format `(x_min, y_min, x_max, y_max)`. + + Returns: + An array of polygons (N, 4, 2), where each polygon is + represented as a list of four coordinates in the format `(x, y)`. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> box = np.array([[10, 20, 30, 40]]) + >>> sv.xyxy_to_polygons(box) + array([[[10, 20], + [30, 20], + [30, 40], + [10, 40]]]) + + ``` + """ + polygon = np.zeros((box.shape[0], 4, 2), dtype=box.dtype) + polygon[:, :, 0] = box[:, [0, 2, 2, 0]] + polygon[:, :, 1] = box[:, [1, 1, 3, 3]] + return polygon + + +def polygon_to_mask( + polygon: npt.NDArray[np.number], + resolution_wh: tuple[int, int], +) -> npt.NDArray[np.uint8]: + """Generate a mask from a polygon. + + Args: + polygon: The polygon for which the mask should be generated, + given as a list of vertices. + resolution_wh: The width and height of the desired resolution. + + Returns: + The generated 2D mask, where the polygon is marked with + `1`s and the rest is filled with `0`s. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> polygon = np.array([[2, 2], [6, 2], [6, 6], [2, 6]]) + >>> mask = sv.polygon_to_mask(polygon, resolution_wh=(10, 10)) + >>> int(mask.sum()) + 25 + + ``` + """ + width, height = map(int, resolution_wh) + mask = np.zeros((height, width), dtype=np.uint8) + cv2.fillPoly(mask, [polygon.astype(np.int32)], color=(1,)) + return mask + + +def xywh_to_xyxy(xywh: npt.NDArray[np.number]) -> npt.NDArray[np.number]: + """ + Converts bounding box coordinates from `(x, y, width, height)` + format to `(x_min, y_min, x_max, y_max)` format. + + Args: + xywh: A numpy array of shape `(N, 4)` where each row + corresponds to a bounding box in the format `(x, y, width, height)`. + + Returns: + A numpy array of shape `(N, 4)` where each row corresponds + to a bounding box in the format `(x_min, y_min, x_max, y_max)`. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> xywh = np.array([ + ... [10, 20, 30, 40], + ... [15, 25, 35, 45] + ... ]) + >>> sv.xywh_to_xyxy(xywh=xywh) + array([[10, 20, 40, 60], + [15, 25, 50, 70]]) + + ``` + """ + xyxy = xywh.copy() + xyxy[:, 2] = xywh[:, 0] + xywh[:, 2] + xyxy[:, 3] = xywh[:, 1] + xywh[:, 3] + return cast(npt.NDArray[np.number], np.asarray(xyxy)) + + +def xyxy_to_xywh(xyxy: npt.NDArray[np.number]) -> npt.NDArray[np.number]: + """ + Converts bounding box coordinates from `(x_min, y_min, x_max, y_max)` + format to `(x, y, width, height)` format. + + Args: + xyxy: A numpy array of shape `(N, 4)` where each row + corresponds to a bounding box in the format `(x_min, y_min, x_max, + y_max)`. + + Returns: + A numpy array of shape `(N, 4)` where each row corresponds + to a bounding box in the format `(x, y, width, height)`. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> xyxy = np.array([ + ... [10, 20, 40, 60], + ... [15, 25, 50, 70] + ... ]) + >>> sv.xyxy_to_xywh(xyxy=xyxy) + array([[10, 20, 30, 40], + [15, 25, 35, 45]]) + + ``` + """ + xywh = xyxy.copy() + xywh[:, 2] = xyxy[:, 2] - xyxy[:, 0] + xywh[:, 3] = xyxy[:, 3] - xyxy[:, 1] + return cast(npt.NDArray[np.number], np.asarray(xywh)) + + +def xcycwh_to_xyxy(xcycwh: npt.NDArray[np.number]) -> npt.NDArray[np.number]: + """ + Converts bounding box coordinates from `(center_x, center_y, width, height)` + format to `(x_min, y_min, x_max, y_max)` format. + + Args: + xcycwh: A numpy array of shape `(N, 4)` where each row + corresponds to a bounding box in the format `(center_x, center_y, width, + height)`. + + Returns: + A numpy array of shape `(N, 4)` where each row corresponds + to a bounding box in the format `(x_min, y_min, x_max, y_max)`. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> xcycwh = np.array([ + ... [50.0, 50.0, 20.0, 30.0], + ... [30.0, 40.0, 10.0, 15.0] + ... ]) + >>> sv.xcycwh_to_xyxy(xcycwh=xcycwh) + array([[40. , 35. , 60. , 65. ], + [25. , 32.5, 35. , 47.5]]) + + ``` + """ + # Build the result from the half-extent arithmetic instead of writing into a + # copy of the input. Half of an odd width or height is fractional, so an + # integer input array would silently truncate those coordinates; letting the + # division set the output dtype keeps them exact. + center_x = xcycwh[:, 0] + center_y = xcycwh[:, 1] + half_width = xcycwh[:, 2] / 2 + half_height = xcycwh[:, 3] / 2 + xyxy = np.column_stack( + ( + center_x - half_width, + center_y - half_height, + center_x + half_width, + center_y + half_height, + ) + ) + return cast(npt.NDArray[np.number], xyxy) + + +def xyxy_to_xcycarh(xyxy: npt.NDArray[np.number]) -> npt.NDArray[np.floating]: + """ + Converts bounding box coordinates from `(x_min, y_min, x_max, y_max)` + into measurement space to format `(center x, center y, aspect ratio, height)`, + where the aspect ratio is `width / height`. + + Args: + xyxy: Bounding box in format `(x1, y1, x2, y2)`. + Expected shape is `(N, 4)`. + Returns: + Bounding box in format + `(center x, center y, aspect ratio, height)`. Shape `(N, 4)`. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> xyxy = np.array([ + ... [10, 20, 40, 60], + ... [15, 25, 50, 70] + ... ]) + >>> sv.xyxy_to_xcycarh(xyxy=xyxy) # doctest: +ELLIPSIS + array([[25. , 40. , 0.75 , 40. ], + [32.5 , 47.5 , 0.77..., 45. ]]) + + ``` + + """ + if xyxy.size == 0: + return np.empty((0, 4), dtype=float) + + x1, y1, x2, y2 = xyxy.T + width = x2 - x1 + height = y2 - y1 + center_x = x1 + width / 2 + center_y = y1 + height / 2 + + aspect_ratio = np.divide( + width, + height, + out=np.zeros_like(width, dtype=float), + where=height != 0, + ) + result = np.column_stack((center_x, center_y, aspect_ratio, height)) + return result.astype(float) + + +def mask_to_xyxy( + masks: npt.NDArray[np.bool_], + coordinate_convention: CoordinateConvention = "inclusive", +) -> npt.NDArray[np.int_]: + """ + Converts a 3D `np.array` of 2D bool masks into a 2D `np.array` of bounding boxes. + + Args: + masks: A 3D `np.array` of shape `(N, H, W)` containing 2D bool masks. + coordinate_convention: How to interpret the returned max corner. + Use `"inclusive"` to preserve the legacy Supervision behavior, + where `x_max` and `y_max` are the last covered pixel. Use + `"exclusive"` for half-open boxes that match area and IoU arithmetic. + + Returns: + A 2D `np.array` of shape `(N, 4)` containing the bounding boxes + `(x_min, y_min, x_max, y_max)` for each mask. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> masks = np.array([ + ... [[False, False, False], + ... [False, True, True], + ... [False, True, True]], + ... ]) + >>> sv.mask_to_xyxy(masks) + array([[1, 1, 2, 2]]) + + ``` + """ + n, height, width = masks.shape + if masks.size == 0: + return np.zeros((n, 4), dtype=int) + + # Reduce the mask stack to per-row / per-column occupancy, then read the + # tight bounds straight off those 1D profiles instead of scanning every + # pixel of every mask with `np.where`. + rows_any = cast(npt.NDArray[np.bool_], masks.any(axis=2)) # (N, H) + cols_any = cast(npt.NDArray[np.bool_], masks.any(axis=1)) # (N, W) + + x_min = cols_any.argmax(axis=1) + y_min = rows_any.argmax(axis=1) + + if coordinate_convention == "inclusive": + x_max = width - 1 - cols_any[:, ::-1].argmax(axis=1) + y_max = height - 1 - rows_any[:, ::-1].argmax(axis=1) + elif coordinate_convention == "exclusive": + x_max = width - cols_any[:, ::-1].argmax(axis=1) + y_max = height - rows_any[:, ::-1].argmax(axis=1) + else: + raise ValueError( + "coordinate_convention must be 'inclusive' or 'exclusive', " + f"got {coordinate_convention!r}." + ) + + xyxy = np.stack((x_min, y_min, x_max, y_max), axis=1).astype(int) + # Empty masks have no bounds; keep the original all-zeros box for them. + xyxy[~rows_any.any(axis=1)] = 0 + return xyxy + + +def xyxy_to_mask( + boxes: npt.NDArray[np.number], + resolution_wh: tuple[int, int], + coordinate_convention: CoordinateConvention = "inclusive", +) -> npt.NDArray[np.bool_]: + """ + Converts a 2D `np.ndarray` of bounding boxes into a 3D `np.ndarray` of bool masks. + + Args: + boxes: A 2D `np.ndarray` of shape `(N, 4)` containing bounding boxes + `(x_min, y_min, x_max, y_max)`. + resolution_wh: A tuple `(width, height)` specifying the resolution of + the output masks. + coordinate_convention: How to interpret `x_max` and `y_max`. + Use `"inclusive"` for closed boxes with the legacy Supervision + convention. Use `"exclusive"` for half-open boxes that align with + box area and IoU calculations. + + Returns: + A 3D `np.ndarray` of shape `(N, height, width)` containing 2D bool masks + for each bounding box. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> boxes = np.array([[0, 0, 2, 2]]) + >>> sv.xyxy_to_mask(boxes, (5, 5)) + array([[[ True, True, True, False, False], + [ True, True, True, False, False], + [ True, True, True, False, False], + [False, False, False, False, False], + [False, False, False, False, False]]]) + >>> boxes = np.array([[0, 0, 1, 1], [3, 3, 4, 4]]) + >>> sv.xyxy_to_mask(boxes, (5, 5)) + array([[[ True, True, False, False, False], + [ True, True, False, False, False], + [False, False, False, False, False], + [False, False, False, False, False], + [False, False, False, False, False]], + + [[False, False, False, False, False], + [False, False, False, False, False], + [False, False, False, False, False], + [False, False, False, True, True], + [False, False, False, True, True]]]) + + ``` + """ + width, height = resolution_wh + n = boxes.shape[0] + masks = np.zeros((n, height, width), dtype=bool) + + for i, (x_min, y_min, x_max, y_max) in enumerate(boxes): + x_min = max(0, int(x_min)) + y_min = max(0, int(y_min)) + if coordinate_convention == "inclusive": + x_max = min(width - 1, int(x_max)) + y_max = min(height - 1, int(y_max)) + if x_max >= x_min and y_max >= y_min: + masks[i, y_min : y_max + 1, x_min : x_max + 1] = True + elif coordinate_convention == "exclusive": + x_max = min(width, int(x_max)) + y_max = min(height, int(y_max)) + if x_max > x_min and y_max > y_min: + masks[i, y_min:y_max, x_min:x_max] = True + else: + raise ValueError( + "coordinate_convention must be 'inclusive' or 'exclusive', " + f"got {coordinate_convention!r}." + ) + + return masks + + +def mask_to_polygons(mask: npt.NDArray[np.bool_]) -> list[npt.NDArray[np.int32]]: + """ + Converts a binary mask to a list of polygons. + + Args: + mask: A binary mask represented as a 2D NumPy array of shape `(H, W)`, + where H and W are the height and width of the mask, respectively. + + Returns: + A list of polygons, where each polygon is represented by a NumPy array + of shape `(N, 2)`, containing the `x`, `y` coordinates of the + points. Polygons with fewer points than `MIN_POLYGON_POINT_COUNT = 3` + are excluded from the output. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> mask = np.zeros((10, 10), dtype=bool) + >>> mask[2:6, 2:6] = True + >>> sv.mask_to_polygons(mask) + [array([[2, 2], + [2, 5], + [5, 5], + [5, 2]], dtype=int32)] + + ``` + """ + + contours = cv2.find_contours(mask.astype(np.uint8)) + return [ + np.squeeze(contour, axis=1) + for contour in contours + if contour.shape[0] >= MIN_POLYGON_POINT_COUNT + ] + + +def _base48_decode(s: str) -> list[int]: + """Decode a COCO base-48 string to raw (delta-encoded) integers. + + Implements the variable-length base-48 codec from the COCO API + (pycocotools). Each integer is encoded across one or more 6-bit + characters: bits 0-4 carry data; bit 5 signals continuation; bit 4 + of the final character signals a negative value. + + This is the pure codec layer — call :func:`_delta_decode` on the + result to obtain absolute run-length counts. + + Args: + s: COCO compressed RLE string. + + Returns: + Raw delta-encoded integers, one per run. + + Raises: + ValueError: If the string is truncated mid-integer. + + Examples: + ```pycon + >>> from supervision.detection.utils.converters import _base48_decode + >>> _base48_decode("52203") + [5, 2, 2, 0, 3] + + ``` + """ + values: list[int] = [] + i = 0 + while i < len(s): + x = 0 + k = 0 + more = True + while more: + if i >= len(s): + raise ValueError( + f"Malformed compressed RLE string: unexpected end at position {i}" + ) + c = ord(s[i]) - 48 + x |= (c & 0x1F) << (5 * k) + more = bool(c & 0x20) + i += 1 + k += 1 + if not more and (c & 0x10): + x |= ~0 << (5 * k) + values.append(x) + return values + + +def _base48_encode(values: list[int]) -> str: + """Encode raw (delta-encoded) integers to a COCO base-48 string. + + The inverse of :func:`_base48_decode`. Applies the same variable-length + base-48 codec used by pycocotools. + + Apply :func:`_delta_encode` to absolute run-length counts before calling + this function to produce a valid COCO compressed RLE string. + + Args: + values: Raw (delta-encoded) integers to encode. + + Returns: + COCO base-48 encoded string. + + Examples: + ```pycon + >>> from supervision.detection.utils.converters import _base48_encode + >>> _base48_encode([5, 2, 2, 0, 3]) + '52203' + + ``` + """ + chars: list[str] = [] + for x in values: + more = True + while more: + c = x & 0x1F + x >>= 5 + more = (x != -1) if (c & 0x10) else (x != 0) + if more: + c |= 0x20 + chars.append(chr(c + 48)) + return "".join(chars) + + +def _delta_decode(values: list[int]) -> list[int]: + """Undo COCO delta encoding: ``counts[i] += counts[i - 2]`` for ``i > 2``. + + The COCO compressed RLE format stores run lengths as deltas relative to + the count two positions earlier (starting at index 3). This function + converts those relative values back to absolute run lengths. + + Args: + values: Raw delta-encoded integers from :func:`_base48_decode`. + + Returns: + Absolute run-length counts (alternating background / foreground). + + Examples: + ```pycon + >>> from supervision.detection.utils.converters import _delta_decode + >>> _delta_decode([5, 2, 2, 0, 3]) + [5, 2, 2, 2, 5] + + ``` + """ + # The recurrence ``counts[i] += counts[i - 2]`` for ``i >= 3`` decomposes + # into two independent stride-2 chains: the odd indices (1, 3, 5, ...) and + # the even indices from 2 onward (2, 4, 6, ...). A cumulative sum over each + # chain recovers the absolute counts. Index 0 is absolute and untouched. + # int64 accumulation avoids overflow; ``tolist`` returns native Python ints. + counts = np.asarray(values, dtype=np.int64) + counts[1::2] = np.cumsum(counts[1::2]) + counts[2::2] = np.cumsum(counts[2::2]) + return cast("list[int]", counts.tolist()) + + +def _delta_encode(counts: list[int]) -> list[int]: + """Apply COCO delta encoding: ``d[i] = counts[i] - counts[i - 2]`` for ``i > 2``. + + The inverse of :func:`_delta_decode`. Converts absolute run lengths to + the relative representation required by the COCO compressed RLE format. + + Args: + counts: Absolute run-length counts (alternating background / foreground). + + Returns: + Delta-encoded integers ready for :func:`_base48_encode`. + + Examples: + ```pycon + >>> from supervision.detection.utils.converters import _delta_encode + >>> _delta_encode([5, 2, 2, 2, 5]) + [5, 2, 2, 0, 3] + + ``` + """ + deltas = list(counts) + for i in range(3, len(deltas)): + deltas[i] = counts[i] - counts[i - 2] + return deltas + + +def is_compressed_rle(rle: object) -> bool: + """Return ``True`` if ``rle`` is a COCO compressed RLE (``str`` or ``bytes``). + + Use this to branch between the compressed-string pipeline + (:func:`_base48_decode` → :func:`_delta_decode`) and the uncompressed + integer-list / array pipeline before calling :func:`rle_to_mask`. + + Args: + rle: Candidate RLE value to inspect. + + Returns: + ``True`` for ``str`` or ``bytes`` inputs; ``False`` otherwise. + + Examples: + ```pycon + >>> from supervision.detection.utils.converters import is_compressed_rle + >>> is_compressed_rle("52203") + True + >>> is_compressed_rle([5, 2, 2, 2, 5]) + False + + ``` + """ + return isinstance(rle, (str, bytes)) + + +def _mask_to_rle_counts(mask_2d: npt.NDArray[Any]) -> npt.NDArray[np.int32]: + """Encode a 2D boolean mask as COCO F-order run lengths (int32 array). + + Pixels are scanned column-by-column (Fortran order), matching the COCO / + pycocotools RLE convention. The first value is always the count of leading + ``False`` pixels (may be 0 if the mask starts with ``True``). + + This is the shared low-level encoder used by both :func:`mask_to_rle` and + :class:`~supervision.detection.compact_mask.CompactMask`. + + Args: + mask_2d: 2D boolean array of shape ``(H, W)``. + + Returns: + int32 array of run lengths starting with the False count. + + Examples: + ```pycon + >>> import numpy as np + >>> from supervision.detection.utils.converters import _mask_to_rle_counts + >>> mask = np.array([[False, True], [True, False]]) + >>> _mask_to_rle_counts(mask).tolist() + [1, 2, 1] + + ``` + """ + flat = np.asarray(mask_2d, dtype=np.bool_).ravel(order="F") + if len(flat) == 0: + return np.array([0], dtype=np.int32) + + changes = np.diff(flat.view(np.uint8)) + boundaries = np.where(changes != 0)[0] + 1 + positions = np.concatenate(([0], boundaries, [len(flat)])) + run_lengths = np.diff(positions).astype(np.int32) + + if flat[0]: + run_lengths = np.concatenate(([np.int32(0)], run_lengths)) + + return run_lengths + + +def _rle_counts_to_mask( + rle: npt.NDArray[np.int32], height: int, width: int +) -> npt.NDArray[np.bool_]: + """Decode COCO F-order run lengths back to a 2D boolean mask. + + This is the shared low-level decoder used by both :func:`rle_to_mask` and + :class:`~supervision.detection.compact_mask.CompactMask`. + + Args: + rle: int32 array of run lengths as produced by :func:`_mask_to_rle_counts`. + height: Height of the output mask. + width: Width of the output mask. + + Returns: + 2D boolean array of shape ``(height, width)``. + + Examples: + ```pycon + >>> import numpy as np + >>> from supervision.detection.utils.converters import _rle_counts_to_mask + >>> rle = np.array([0, 1, 2, 1], dtype=np.int32) + >>> _rle_counts_to_mask(rle, 2, 2) + array([[ True, False], + [False, True]]) + + ``` + """ + is_true = np.arange(len(rle)) % 2 == 1 + flat: npt.NDArray[np.bool_] = np.repeat(is_true, rle) + num_pixels = height * width + if len(flat) < num_pixels: + flat = np.pad(flat, (0, num_pixels - len(flat))) + return cast( + npt.NDArray[np.bool_], flat[:num_pixels].reshape(height, width, order="F") + ) + + +def rle_to_mask( + rle: npt.NDArray[np.integer[Any]] | list[int] | str | bytes, + resolution_wh: tuple[int, int], +) -> npt.NDArray[np.bool_]: + """ + Converts a COCO run-length encoding (RLE) to a binary mask. + + Implements the COCO RLE format used by ``pycocotools``: pixels are counted + in **column-major (Fortran) order** — top-to-bottom within each column, + left-to-right across columns. This is the opposite of the row-major order + used by NumPy's default ``'C'`` layout. Passing RLE data produced by a + different row-major convention will yield an incorrect mask. + + Args: + rle: The COCO RLE data in one of the following formats: + + - A 1D array or list of integers (uncompressed COCO RLE, where + values at even indices are background run-lengths and values at + odd indices are foreground run-lengths, both counted column-major). + - A compressed COCO RLE string or bytes, as produced by + ``pycocotools.mask.encode``. + resolution_wh: The width (w) and height (h) + of the desired binary mask. + + Returns: + The generated 2D Boolean mask of shape `(h, w)`, where the foreground object is + marked with `True`'s and the rest is filled with `False`'s. + + Raises: + ValueError: If the sum of pixels encoded in RLE differs from the + number of pixels in the expected mask (computed based on resolution_wh). + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> mask = sv.rle_to_mask([5, 2, 2, 2, 5], (4, 4)) + >>> mask # doctest: +NORMALIZE_WHITESPACE + array([[False, False, False, False], + [False, True, True, False], + [False, True, True, False], + [False, False, False, False]]) + + >>> mask = sv.rle_to_mask("52203", (4, 4)) + >>> mask # doctest: +NORMALIZE_WHITESPACE + array([[False, False, False, False], + [False, True, True, False], + [False, True, True, False], + [False, False, False, False]]) + + ``` + """ + if isinstance(rle, bytes): + rle = rle.decode("utf-8") + if isinstance(rle, str): + counts: npt.NDArray[np.int32] = np.array( + _delta_decode(_base48_decode(rle)), dtype=np.int32 + ) + elif isinstance(rle, list): + counts = np.array(rle, dtype=np.int32) + else: + counts = np.asarray(rle, dtype=np.int32) + + width, height = resolution_wh + + if width * height != np.sum(counts): + raise ValueError( + "the sum of the number of pixels in the RLE must be the same " + "as the number of pixels in the expected mask" + ) + + return _rle_counts_to_mask(counts, height, width) + + +def mask_to_rle( + mask: npt.NDArray[np.bool_], compressed: bool = False +) -> list[int] | str: + """ + Converts a binary mask into a COCO run-length encoding (RLE). + + Produces RLE in the COCO format used by ``pycocotools``: pixels are counted + in **column-major (Fortran) order** — top-to-bottom within each column, + left-to-right across columns. The output is directly compatible with + ``pycocotools.mask.decode`` and COCO annotation JSON files. + + Args: + mask: 2D binary mask where `True` indicates foreground + object and `False` indicates background. + compressed: If ``True``, return a compressed COCO RLE string + compatible with ``pycocotools``. If ``False`` (default), + return a list of integers. + + Returns: + The COCO run-length encoded mask. When ``compressed`` is ``False``, + values of a list with even indices represent the number of pixels + assigned as background (`False`), values of a list with odd indices + represent the number of pixels assigned as foreground object (`True`), + both counted in column-major order. + When ``compressed`` is ``True``, a COCO compressed RLE string. + + Raises: + ValueError: If input mask is not 2D or is empty. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> mask = np.array([ + ... [True, True, True, True], + ... [True, True, True, True], + ... [True, True, True, True], + ... [True, True, True, True], + ... ]) + >>> rle = sv.mask_to_rle(mask) + >>> [int(x) for x in rle] + [0, 16] + + ``` + + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> mask = np.array([ + ... [False, False, False, False], + ... [False, True, True, False], + ... [False, True, True, False], + ... [False, False, False, False], + ... ]) + >>> rle = sv.mask_to_rle(mask) + >>> [int(x) for x in rle] + [5, 2, 2, 2, 5] + + >>> sv.mask_to_rle(mask, compressed=True) + '52203' + + ``` + + ![mask_to_rle](https://media.roboflow.com/supervision-docs/ + mask-to-rle.png){ align=center width="800" } + """ + if mask.ndim != 2: + raise ValueError("Input mask must be 2D") + if mask.size == 0: + raise ValueError("Input mask cannot be empty") + + counts: list[int] = cast(list[int], _mask_to_rle_counts(mask).tolist()) + if compressed: + return _base48_encode(_delta_encode(counts)) + return counts + + +def polygon_to_xyxy(polygon: npt.NDArray[np.number]) -> npt.NDArray[np.number]: + """ + Converts a polygon represented by a NumPy array into a bounding box. + + Args: + polygon: A polygon represented by a NumPy array of shape `(N, 2)`, + containing the `x`, `y` coordinates of the points. + + Returns: + A 1D NumPy array containing the bounding box + `(x_min, y_min, x_max, y_max)` of the input polygon. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> polygon = np.array([[10, 20], [30, 20], [30, 40], [10, 40]]) + >>> sv.polygon_to_xyxy(polygon) + array([10, 20, 30, 40]) + + ``` + """ + x_min, y_min = np.min(polygon, axis=0) + x_max, y_max = np.max(polygon, axis=0) + return np.array([x_min, y_min, x_max, y_max]) diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/utils/internal.py b/.venv/lib/python3.12/site-packages/supervision/detection/utils/internal.py new file mode 100644 index 0000000000000000000000000000000000000000..6c3dd7eb1d12daf23cd22a8cfb019188ac567609 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/detection/utils/internal.py @@ -0,0 +1,806 @@ +import logging +from itertools import chain +from typing import Any, Literal, cast, overload + +import numpy as np +import numpy.typing as npt + +from supervision import _cv2 as cv2 +from supervision.config import CLASS_NAME_DATA_FIELD +from supervision.detection.compact_mask import CompactMask +from supervision.detection.utils._typing import _DetectionDataType, _MetadataType +from supervision.detection.utils.converters import polygon_to_mask, rle_to_mask +from supervision.geometry.core import Vector + +logger = logging.getLogger(__name__) + + +def _full_image_xyxy( + count: int, + image_height: int, + image_width: int, + dtype: npt.DTypeLike = np.float64, +) -> npt.NDArray[Any]: + """Return full-frame inclusive boxes for lossless mask compaction.""" + return np.tile( + np.array([[0, 0, image_width - 1, image_height - 1]], dtype=dtype), + (count, 1), + ) + + +def _valid_rle_payload(prediction: dict[str, Any]) -> dict[str, Any] | None: + """Return the first valid RLE payload from ``rle`` then ``rle_mask``.""" + for key in ("rle", "rle_mask"): + rle_data = prediction.get(key) + if isinstance(rle_data, dict) and {"size", "counts"}.issubset(rle_data): + return rle_data + return None + + +def extract_ultralytics_masks(yolov8_results: Any) -> npt.NDArray[np.bool_] | None: + """Extract boolean masks from Ultralytics results, cropping letterbox padding. + + Handles the case where the inference resolution differs from the original image + shape by computing the letterbox padding offsets, cropping them out, and resizing + each proto mask back to `orig_shape`. Thresholds at 0.5 to match Ultralytics' + semantics and avoid dilating masks through float interpolation. + + Args: + yolov8_results: Ultralytics results object with `.masks` and `.orig_shape`. + + Returns: + Boolean array of shape `(N, H, W)` aligned with the detections, or `None` + when no masks are present. + """ + if not yolov8_results.masks: + return None + + orig_shape = yolov8_results.orig_shape + inference_shape = tuple(yolov8_results.masks.data.shape[1:]) + + pad = (0, 0) + + if inference_shape != orig_shape: + gain = min( + inference_shape[0] / orig_shape[0], + inference_shape[1] / orig_shape[1], + ) + pad = ( + (inference_shape[1] - orig_shape[1] * gain) / 2, + (inference_shape[0] - orig_shape[0] * gain) / 2, + ) + + top, left = int(pad[1]), int(pad[0]) + bottom, right = int(inference_shape[0] - pad[1]), int(inference_shape[1] - pad[0]) + + mask_maps = [] + masks = yolov8_results.masks.data.cpu().numpy() + for i in range(masks.shape[0]): + mask = masks[i] + mask = mask[top:bottom, left:right] + + if mask.shape != orig_shape: + # `cv2.resize` interpolates the float proto mask, so threshold at 0.5 + # (matching Ultralytics' own semantics) instead of casting every + # nonzero interpolated value to True, which would dilate the mask. + mask = cv2.resize(mask, (orig_shape[1], orig_shape[0])) > 0.5 + # else: slice-crop (no interpolation) preserves the binary 0/1 float values + # produced by Ultralytics; the final np.asarray(..., dtype=bool) is equivalent. + + mask_maps.append(mask) + + return cast(npt.NDArray[np.bool_], np.asarray(mask_maps, dtype=bool)) + + +def _resolve_rle_mask( + rle_data: dict[str, Any], + image_height: int, + image_width: int, + compact_masks: bool, +) -> tuple[npt.NDArray[np.bool_] | None, dict[str, Any] | None]: + """Decode one RLE prediction into (dense_mask, compact_pending). + + Returns ``(dense_mask, None)`` when ``compact_masks=False`` or when the + RLE size does not match the image size (fall back to dense decode). + Returns ``(None, rle_data)`` when ``compact_masks=True`` and the RLE size + matches, deferring the item to the post-loop batch call. + Returns ``(None, None)`` on decode failure (caller should skip mask). + + Args: + rle_data: Validated COCO RLE dict with ``"size"`` and ``"counts"`` keys. + image_height: Full-image height in pixels. + image_width: Full-image width in pixels. + compact_masks: Whether to return a deferred item for batch processing. + + Returns: + A 2-tuple ``(dense_mask, pending)`` where at most one element is + non-``None``. + """ + try: + h, w = rle_data["size"] + if compact_masks and (h, w) == (image_height, image_width): + # Sizes match; defer to the post-loop CompactMask.from_coco_rle call. + return None, rle_data + if compact_masks and (h, w) != (image_height, image_width): + logger.debug( + "compact_masks=True: RLE size %s does not match image " + "size (%d, %d); falling back to dense decode.", + (h, w), + image_height, + image_width, + ) + mask: npt.NDArray[np.bool_] = rle_to_mask(rle_data["counts"], (w, h)) + if (h, w) != (image_height, image_width): + mask = cv2.resize( + mask.astype(np.uint8), + (image_width, image_height), + interpolation=cv2.INTER_NEAREST, + ).astype(bool) + return mask, None + except (ValueError, AssertionError, KeyError, TypeError, OverflowError) as exc: + logger.warning( + "Failed to decode RLE mask payload; falling back to box-only " + "detection. Reason: %s", + exc, + ) + return None, None + + +def _all_present_or_none( + values: list[Any], + label: str, + dtype: npt.DTypeLike, +) -> npt.NDArray[Any] | None: + # Identity check (`v is None`) is required when values may contain numpy arrays: + # `None in values` triggers element-wise comparison and raises ValueError. + missing = sum(v is None for v in values) + if 0 < missing < len(values): + logger.warning( + "Partial %s in batch; dropping all to preserve alignment with xyxy.", label + ) + if not values or missing > 0: + return None + return np.array(values, dtype=dtype) + + +def _decode_compact_masks( + coco_rle_pending: list[tuple[int, Any, list[float]]], + polygon_compact_map: dict[int, CompactMask], + image_height: int, + image_width: int, + n_predictions: int, +) -> CompactMask | None: + """Decode deferred COCO-RLE entries and merge with polygon compact masks. + + Attempts a single batched ``CompactMask.from_coco_rle`` call for all pending + items to eliminate per-prediction call overhead on the happy path. On any + decode failure the call is retried per-prediction so that one malformed RLE + payload does not abort the entire batch. + + Isolation note: this function isolates the *decode* step only. If the + per-prediction fallback still leaves some predictions without masks, the + mixed-modality guard drops ALL masks to preserve alignment with ``xyxy``. + + Args: + coco_rle_pending: Deferred COCO-RLE items collected during the prediction + loop, each as ``(xyxy_idx, rle_dict, bbox)``. + polygon_compact_map: Already-decoded polygon masks keyed by ``xyxy_idx``. + image_height: Frame height in pixels. + image_width: Frame width in pixels. + n_predictions: Total number of accepted predictions; used by the + mixed-modality alignment guard. + + Returns: + A merged ``CompactMask`` when all predictions that carry masks decoded + successfully, or ``None`` when no masks are present or the + mixed-modality guard triggers. + + Examples: + ```pycon + >>> _decode_compact_masks([], {}, 1080, 1920, 5) is None + True + + ``` + """ + coco_compact_map: dict[int, CompactMask] = {} + if coco_rle_pending: + pending_indices = [t[0] for t in coco_rle_pending] + pending_rles = [t[1] for t in coco_rle_pending] + pending_xyxy = np.array([t[2] for t in coco_rle_pending], dtype=np.float64) + try: + batch_cm = CompactMask.from_coco_rle( + pending_rles, pending_xyxy, (image_height, image_width) + ) + for local_idx, global_idx in enumerate(pending_indices): + coco_compact_map[global_idx] = batch_cm[local_idx : local_idx + 1] + except (ValueError, AssertionError, KeyError, TypeError, OverflowError) as exc: + logger.warning( + "Batch compact RLE decode failed (%s); retrying " + "per-prediction for fault isolation.", + exc, + ) + for xyxy_idx, rle_dict, bbox in coco_rle_pending: + try: + single_cm = CompactMask.from_coco_rle( + [rle_dict], + np.array([bbox], dtype=np.float64), + (image_height, image_width), + ) + coco_compact_map[xyxy_idx] = single_cm[0:1] + except ( + ValueError, + AssertionError, + KeyError, + TypeError, + OverflowError, + ) as per_exc: + logger.warning( + "Compact RLE decode failed for prediction at index %d; " + "dropping that mask. Reason: %s", + xyxy_idx, + per_exc, + ) + all_compact = {**coco_compact_map, **polygon_compact_map} + compact_parts: list[CompactMask] = [ + all_compact[i] for i in sorted(all_compact.keys()) + ] + if 0 < len(compact_parts) < n_predictions: + logger.warning( + "Mixed-modality compact batch: %d of %d predictions carry masks; " + "dropping all masks to preserve alignment with xyxy.", + len(compact_parts), + n_predictions, + ) + compact_parts = [] + return CompactMask.merge(compact_parts) if compact_parts else None + + +@overload +def process_roboflow_result( + roboflow_result: dict[str, Any], + *, + compact_masks: Literal[False] = False, +) -> tuple[ + npt.NDArray[np.floating], + npt.NDArray[np.floating], + npt.NDArray[np.integer], + npt.NDArray[np.bool_] | None, + npt.NDArray[np.integer] | None, + _DetectionDataType, +]: ... + + +@overload +def process_roboflow_result( + roboflow_result: dict[str, Any], + *, + compact_masks: Literal[True], +) -> tuple[ + npt.NDArray[np.floating], + npt.NDArray[np.floating], + npt.NDArray[np.integer], + CompactMask | None, + npt.NDArray[np.integer] | None, + _DetectionDataType, +]: ... + + +def process_roboflow_result( + roboflow_result: dict[str, Any], + *, + compact_masks: bool = False, +) -> tuple[ + npt.NDArray[np.floating], + npt.NDArray[np.floating], + npt.NDArray[np.integer], + npt.NDArray[np.bool_] | CompactMask | None, + npt.NDArray[np.integer] | None, + _DetectionDataType, +]: + """Parse a Roboflow API or Inference package result into detection arrays. + + The returned ``data`` dict always contains ``CLASS_NAME_DATA_FIELD`` as a + string-dtype NumPy array. When ``predictions`` is empty, the array has + shape ``(0,)`` with ``dtype=str``, preserving dtype contracts for callers + that mix empty and non-empty results. + + Args: + roboflow_result: Raw dict from the Roboflow REST API or the Inference + package (after ``.dict()`` serialisation). + compact_masks: When ``True``, return segmentation masks as + :class:`~supervision.detection.compact_mask.CompactMask` instead of + a dense boolean array when mask data is present. + + Returns: + A 6-tuple of ``(xyxy, confidence, class_id, masks, tracker_ids, data)`` + where each array is aligned with the others. ``masks`` is ``None`` + when no predictions include mask data, or when only a subset do + (mixed-modality batch) — in that case all masks are dropped to preserve + alignment with ``xyxy``. Note: a single malformed polygon prediction + (fewer than 3 points) in an otherwise fully-segmented batch causes all + masks to be dropped from the result; the detection itself is kept as a + box-only entry with a ``logger.warning``. When ``compact_masks=True`` + and masks are + present, ``masks`` is a :class:`CompactMask`; otherwise it is a dense + boolean array. ``tracker_ids`` is ``None`` when no predictions carry a + tracker ID, or when only a subset do (mixed batch) — in that case all + tracker IDs are dropped to preserve alignment with ``xyxy``. + + Examples: + ```pycon + >>> from supervision.detection.utils.internal import process_roboflow_result + >>> result = {"predictions": [], "image": {"width": 100, "height": 100}} + >>> _, _, _, _, _, data = process_roboflow_result(result) + >>> data["class_name"].dtype.kind + 'U' + + ``` + """ + if not roboflow_result["predictions"]: + return ( + np.empty((0, 4), dtype=np.float64), + np.empty(0, dtype=np.float64), + np.empty(0, dtype=np.int64), + None, + None, + {CLASS_NAME_DATA_FIELD: np.empty(0, dtype=str)}, + ) + + xyxy: list[list[float]] = [] + confidence: list[float] = [] + class_id: list[int] = [] + class_name: list[str] = [] + masks: list[npt.NDArray[np.bool_] | None] = [] + # Deferred COCO-RLE processing: collect validated pairs here, then after the + # loop attempt a single batched from_coco_rle call (happy path). If that batch + # call fails, fall back to decoding each pending prediction individually for + # fault isolation. + _coco_rle_pending: list[tuple[int, Any, list[float]]] = [] # (xyxy_idx, rle, bbox) + _polygon_compact_map: dict[int, CompactMask] = {} # xyxy_idx → CompactMask + tracker_ids: list[int | None] = [] + + image_width = int(roboflow_result["image"]["width"]) + image_height = int(roboflow_result["image"]["height"]) + + for prediction in roboflow_result["predictions"]: + x = prediction["x"] + y = prediction["y"] + width = prediction["width"] + height = prediction["height"] + x_min = x - width / 2 + y_min = y - height / 2 + x_max = x_min + width + y_max = y_min + height + + rle_data = _valid_rle_payload(prediction) + mask: npt.NDArray[np.bool_] | None = None + compact_mask: CompactMask | None = None + if rle_data is not None: + _dense, _pending = _resolve_rle_mask( + rle_data, image_height, image_width, compact_masks + ) + if _dense is None and _pending is None: + # Decode failed; treat as no-mask prediction. + rle_data = None + elif _pending is None: + # Dense result: compact_masks=False, or size-mismatch fallback. + mask = _dense + if compact_masks and mask is not None: + compact_mask = CompactMask.from_dense( + masks=mask[np.newaxis, ...], + xyxy=_full_image_xyxy(1, image_height, image_width), + image_shape=(image_height, image_width), + ) + # else: _pending set → deferred to batch; mask and compact_mask stay None + if rle_data is not None: + xyxy_idx = len(xyxy) + xyxy.append([x_min, y_min, x_max, y_max]) + class_id.append(prediction["class_id"]) + class_name.append(prediction["class"]) + confidence.append(prediction["confidence"]) + if compact_masks: + if compact_mask is not None: + # Fallback dense path (size mismatch): compact_mask always set. + _polygon_compact_map[xyxy_idx] = compact_mask + else: + # Main COCO-RLE path: (h, w) == image size; defer to batch. + # Pass the detector bbox so _rle_split_cols only walks + # crop columns, not the full image width. + _coco_rle_pending.append( + ( + xyxy_idx, + rle_data, + [x_min, y_min, x_max, y_max], + ) + ) + elif mask is not None: + masks.append(mask) + tracker_ids.append(prediction.get("tracker_id")) + elif "points" not in prediction: + xyxy.append([x_min, y_min, x_max, y_max]) + class_id.append(prediction["class_id"]) + class_name.append(prediction["class"]) + confidence.append(prediction["confidence"]) + masks.append(None) + tracker_ids.append(prediction.get("tracker_id")) + elif len(prediction["points"]) >= 3: + polygon = np.array( + [[point["x"], point["y"]] for point in prediction["points"]], dtype=int + ) + mask = polygon_to_mask( + polygon, resolution_wh=(image_width, image_height) + ).astype(bool) + xyxy_idx = len(xyxy) + xyxy.append([x_min, y_min, x_max, y_max]) + class_id.append(prediction["class_id"]) + class_name.append(prediction["class"]) + confidence.append(prediction["confidence"]) + if compact_masks: + _polygon_compact_map[xyxy_idx] = CompactMask.from_dense( + masks=mask[np.newaxis, ...], + xyxy=_full_image_xyxy(1, image_height, image_width), + image_shape=(image_height, image_width), + ) + else: + masks.append(mask) + tracker_ids.append(prediction.get("tracker_id")) + else: + logger.warning( + "Invalid polygon prediction with fewer than 3 points; falling back " + "to box-only detection." + ) + xyxy.append([x_min, y_min, x_max, y_max]) + class_id.append(prediction["class_id"]) + class_name.append(prediction["class"]) + confidence.append(prediction["confidence"]) + masks.append(None) + tracker_ids.append(prediction.get("tracker_id")) + + xyxy_arr: npt.NDArray[np.floating] = ( + np.array(xyxy, dtype=np.float64) if len(xyxy) > 0 else np.empty((0, 4)) + ) + confidence_arr: npt.NDArray[np.floating] = ( + np.array(confidence, dtype=np.float64) if len(confidence) > 0 else np.empty(0) + ) + class_id_arr: npt.NDArray[np.integer] = ( + np.array(class_id, dtype=np.int64) + if len(class_id) > 0 + else np.empty(0, dtype=np.int64) + ) + class_name_arr: npt.NDArray[np.str_] = ( + np.array(class_name) if len(class_name) > 0 else np.empty(0, dtype=str) + ) + masks_arr: npt.NDArray[np.bool_] | CompactMask | None + if compact_masks: + masks_arr = _decode_compact_masks( + _coco_rle_pending, + _polygon_compact_map, + image_height, + image_width, + len(xyxy), + ) + else: + masks_arr = _all_present_or_none(masks, "mask", dtype=bool) + tracker_id_arr: npt.NDArray[np.integer] | None = _all_present_or_none( + tracker_ids, "tracker_id", dtype=np.int64 + ) + data: _DetectionDataType = {CLASS_NAME_DATA_FIELD: class_name_arr} + + return ( + xyxy_arr, + confidence_arr, + class_id_arr, + masks_arr, + tracker_id_arr, + data, + ) + + +def is_data_equal( + data_a: _DetectionDataType, + data_b: _DetectionDataType, +) -> bool: + """ + Compares the data payloads of two Detections instances. + + Args: + data_a, data_b: The data payloads of the instances. + + Returns: + True if the data payloads are equal, False otherwise. + """ + return set(data_a.keys()) == set(data_b.keys()) and all( + np.array_equal(data_a[key], data_b[key]) for key in data_a + ) + + +def is_metadata_equal(metadata_a: _MetadataType, metadata_b: _MetadataType) -> bool: + """ + Compares the metadata payloads of two Detections instances. + + Args: + metadata_a, metadata_b: The metadata payloads of the instances. + + Returns: + True if the metadata payloads are equal, False otherwise. + """ + return set(metadata_a.keys()) == set(metadata_b.keys()) and all( + metadata_values_equal(metadata_a[key], metadata_b[key]) for key in metadata_a + ) + + +def merge_data( + data_list: list[_DetectionDataType], +) -> _DetectionDataType: + """ + Merges the data payloads of a list of Detections instances. + + Warning: Assumes that empty detections were filtered-out before passing data to + this function. + + Args: + data_list: The data payloads of the Detections instances. Each data payload + is a dictionary with the same keys, and the values are either lists or + npt.NDArray[np.generic]. + + Returns: + A single data payload containing the merged data, preserving the original data + types (list or npt.NDArray[np.generic]). + + Raises: + ValueError: If data values within a single object have different lengths or if + dictionaries have different keys. + """ + if not data_list: + return {} + + all_keys_sets = [set(data.keys()) for data in data_list] + if not all(keys_set == all_keys_sets[0] for keys_set in all_keys_sets): + raise ValueError("All data dictionaries must have the same keys to merge.") + + for data in data_list: + lengths = [len(value) for value in data.values()] + if len(set(lengths)) > 1: + raise ValueError( + "All data values within a single object must have equal length." + ) + + merged_data: dict[str, Any] = {key: [] for key in all_keys_sets[0]} + for data in data_list: + for key in data: + merged_data[key].append(data[key]) + + for key in merged_data: + if all(isinstance(item, list) for item in merged_data[key]): + merged_data[key] = list(chain.from_iterable(merged_data[key])) + elif all(isinstance(item, np.ndarray) for item in merged_data[key]): + ndim = merged_data[key][0].ndim + if ndim == 1: + merged_data[key] = np.hstack(merged_data[key]) + elif ndim > 1: + merged_data[key] = np.vstack(merged_data[key]) + else: + raise ValueError(f"Unexpected array dimension for key '{key}'.") + else: + raise ValueError( + f"Inconsistent data types for key '{key}'. Only np.ndarray and list " + f"types are allowed." + ) + + return cast(_DetectionDataType, merged_data) + + +def metadata_values_equal(value_a: Any, value_b: Any) -> bool: + """Check whether two metadata values can merge into one. + + The predicate is total: any value type may be passed, and comparisons that a + type does not support resolve to `False` rather than propagating an exception. + + Args: + value_a, value_b: The metadata values to compare. + + Returns: + True if both values are considered equal, False otherwise. + """ + if isinstance(value_a, np.ndarray) and isinstance(value_b, np.ndarray): + # `equal_nan` makes an array holding NaN equal to itself, but NumPy rejects + # the argument for non-floating dtypes, so it is only passed when both + # operands are float arrays. + both_floating = np.issubdtype(value_a.dtype, np.floating) and np.issubdtype( + value_b.dtype, np.floating + ) + if both_floating: + return bool(np.array_equal(value_a, value_b, equal_nan=True)) + return bool(np.array_equal(value_a, value_b)) + if isinstance(value_a, np.ndarray) or isinstance(value_b, np.ndarray): + return False + try: + return bool(value_a == value_b) + except (ValueError, RuntimeError, TypeError): + # Containers of arrays (list/dict/tuple of ndarray) and tensor types return + # an elementwise result whose truth value is ambiguous; treat as unequal. + return False + + +def merge_metadata(metadata_list: list[_MetadataType]) -> _MetadataType: + """ + Merge metadata from a list of metadata dictionaries. + + This function combines the metadata dictionaries. If a key appears in more than one + dictionary, the values must be identical for the merge to succeed. + + Warning: Assumes that empty detections were filtered-out before passing metadata to + this function. + + Args: + metadata_list: A list of metadata dictionaries to merge. + + Returns: + A single merged metadata dictionary. + + Raises: + ValueError: If there are conflicting values for the same key or if + dictionaries have different keys. + """ + if not metadata_list: + return {} + + all_keys_sets = [set(metadata.keys()) for metadata in metadata_list] + if not all(keys_set == all_keys_sets[0] for keys_set in all_keys_sets): + raise ValueError("All metadata dictionaries must have the same keys to merge.") + + merged_metadata: _MetadataType = {} + for metadata in metadata_list: + for key, value in metadata.items(): + if key not in merged_metadata: + merged_metadata[key] = value + continue + + other_value = merged_metadata[key] + if not metadata_values_equal(value, other_value): + if isinstance(value, np.ndarray) or isinstance(other_value, np.ndarray): + raise ValueError( + f"Conflicting metadata for key: '{key}': " + f"{type(value)}, {type(other_value)}." + ) + raise ValueError(f"Conflicting metadata for key: '{key}'.") + + return merged_metadata + + +def merge_metadata_lenient( + metadata_list: list[_MetadataType], +) -> tuple[_MetadataType, set[str]]: + """Merge metadata dictionaries, dropping keys that cannot be reconciled. + + Unlike :func:`merge_metadata`, which raises on any disagreement, this variant + applies a lenient policy: a key survives only when every dictionary carries it + and all of its values compare equal under + :func:`metadata_values_equal`. Every other key is dropped and reported back so + the caller can react to the loss. + + A single traversal both detects conflicts and builds the merged dictionary; + the surviving value is the one from the first dictionary that carried the key. + + Warning: Assumes that empty detections were filtered-out before passing metadata + to this function. + + Args: + metadata_list: A list of metadata dictionaries to merge. + + Returns: + A 2-tuple of the merged metadata dictionary and the set of dropped keys. + + Examples: + ```pycon + >>> from supervision.detection.utils.internal import merge_metadata_lenient + >>> merge_metadata_lenient([{"a": 1, "b": 2}, {"a": 1, "b": 3}]) + ({'a': 1}, {'b'}) + + ``` + """ + merged_metadata: _MetadataType = {} + occurrences: dict[str, int] = {} + conflicting: set[str] = set() + + for metadata in metadata_list: + for key, value in metadata.items(): + occurrences[key] = occurrences.get(key, 0) + 1 + if key in conflicting: + continue + if key not in merged_metadata: + merged_metadata[key] = value + elif not metadata_values_equal(merged_metadata[key], value): + conflicting.add(key) + + dropped_keys = { + key + for key, count in occurrences.items() + if key in conflicting or count != len(metadata_list) + } + return { + key: value for key, value in merged_metadata.items() if key not in dropped_keys + }, dropped_keys + + +def get_data_item( + data: _DetectionDataType, + index: int | slice | list[int] | npt.NDArray[np.integer | np.bool_], +) -> _DetectionDataType: + """ + Retrieve a subset of the data dictionary based on the given index. + + Args: + data: The data dictionary of the Detections object. + index: The index or indices specifying the subset to retrieve. + + Returns: + A subset of the data dictionary corresponding to the specified index. + """ + subset_data: _DetectionDataType = {} + for key, value in data.items(): + if isinstance(value, np.ndarray): + subset_data[key] = value[index] + elif isinstance(value, list): + if isinstance(index, slice): + subset_data[key] = value[index] + elif isinstance(index, list): + subset_data[key] = [value[i] for i in index] + elif isinstance(index, np.ndarray): + if index.dtype == bool: + subset_data[key] = [ + value[i] for i, index_value in enumerate(index) if index_value + ] + else: + subset_data[key] = [value[i] for i in index] + elif isinstance(index, int): + subset_data[key] = [value[index]] + else: + raise TypeError(f"Unsupported index type: {type(index)}") + else: + raise TypeError(f"Unsupported data type for key '{key}': {type(value)}") + + return subset_data + + +def cross_product( + anchors: npt.NDArray[np.number], vector: Vector +) -> npt.NDArray[np.number]: + """Get signed z-component of cross product (2-D determinant) per anchor. + + Replaces the deprecated `np.cross` 2-D path (NumPy 2.0) with an explicit + determinant: ``a[..., 0] * b[..., 1] - a[..., 1] * b[..., 0]``. + + Args: + anchors: Array of anchors of shape (number of anchors, detections, 2). + vector: Vector to calculate cross product with. + + Returns: + Array of signed cross-product values, shape (number of anchors, + detections). Positive = anchor is to the left of the vector direction; + negative = to the right; zero = on the line. + + Examples: + ```pycon + >>> import numpy as np + >>> from supervision.geometry.core import Point, Vector + >>> anchors = np.array([[[10.0, 5.0]], [[20.0, 5.0]]]) + >>> vector = Vector(start=Point(0, 0), end=Point(1, 0)) + >>> cross_product(anchors, vector) + array([[5.], + [5.]]) + + ``` + """ + vector_at_zero = np.array( + [ + vector.end.x - vector.start.x, + vector.end.y - vector.start.y, + ] + ) + vector_start = np.array([vector.start.x, vector.start.y]) + diff = anchors - vector_start + return cast( + npt.NDArray[np.number], + vector_at_zero[0] * diff[..., 1] - vector_at_zero[1] * diff[..., 0], + ) diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/utils/iou_and_nms.py b/.venv/lib/python3.12/site-packages/supervision/detection/utils/iou_and_nms.py new file mode 100644 index 0000000000000000000000000000000000000000..6f378e481fe36665fdcb8337ed5d03a9406c6128 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/detection/utils/iou_and_nms.py @@ -0,0 +1,1851 @@ +from __future__ import annotations + +import warnings +from collections.abc import Callable, Sequence +from enum import Enum +from typing import Any, cast + +import numpy as np +import numpy.typing as npt + +from supervision import _cv2 as cv2 +from supervision.detection.compact_mask import CompactMask +from supervision.detection.utils.converters import mask_to_xyxy +from supervision.utils.internal import warn_deprecated + + +class OverlapFilter(Enum): + """ + Enum specifying the strategy for filtering overlapping detections. + + Attributes: + NONE: Do not filter detections based on overlap. + NON_MAX_SUPPRESSION: Filter detections using non-max suppression. This means, + detections that overlap by more than a set threshold will be discarded, + except for the one with the highest confidence. + NON_MAX_MERGE: Merge detections with non-max merging. This means, + detections that overlap by more than a set threshold will be merged + into a single detection. + """ + + NONE = "none" + NON_MAX_SUPPRESSION = "non_max_suppression" + NON_MAX_MERGE = "non_max_merge" + + @classmethod + def list(cls) -> list[str]: + return list(map(lambda member: member.value, cls)) + + @classmethod + def from_value(cls, value: OverlapFilter | str) -> OverlapFilter: + if isinstance(value, cls): + return value + if isinstance(value, str): + value = value.lower() + try: + return cls(value) + except ValueError: + raise ValueError(f"Invalid value: {value}. Must be one of {cls.list()}") + raise ValueError( + f"Invalid value type: {type(value)}. Must be an instance of " + f"{cls.__name__} or str." + ) + + +class OverlapMetric(Enum): + """ + Enum specifying the metric for measuring overlap between detections. + + Attributes: + IOU: Intersection over Union. A region-overlap metric that compares + two shapes (usually bounding boxes or masks) by normalising the + shared area with the area of their union. + IOS: Intersection over Smaller, a region-overlap metric that compares + two shapes (usually bounding boxes or masks) by normalising the + shared area with the smaller of the two shapes. + """ + + IOU = "IOU" + IOS = "IOS" + + @classmethod + def list(cls) -> list[str]: + return list(map(lambda member: member.value, cls)) + + @classmethod + def from_value(cls, value: OverlapMetric | str) -> OverlapMetric: + if isinstance(value, cls): + return value + if isinstance(value, str): + value = value.upper() + try: + return cls(value) + except ValueError: + raise ValueError(f"Invalid value: {value}. Must be one of {cls.list()}") + raise ValueError( + f"Invalid value type: {type(value)}. Must be an instance of " + f"{cls.__name__} or str." + ) + + +def _validate_iou_threshold(iou_threshold: float) -> None: + """Raise `ValueError` when an IoU threshold falls outside `[0, 1]`.""" + if not 0 <= iou_threshold <= 1: + raise ValueError( + "Value of `iou_threshold` must be in the closed range from 0 to 1, " + f"{iou_threshold} given." + ) + + +def _coordinate_difference(upper: np.number, lower: np.number) -> float: + """Subtract box coordinates without overflowing integer NumPy scalars.""" + return float(np.asarray(upper).item() - np.asarray(lower).item()) + + +def box_iou( + box_true: list[float] | npt.NDArray[np.number], + box_detection: list[float] | npt.NDArray[np.number], + overlap_metric: OverlapMetric | str = OverlapMetric.IOU, +) -> float: + """ + Compute overlap metric between two bounding boxes. + + Supports standard IOU (intersection-over-union) and IOS + (intersection-over-smaller-area) metrics. Returns the overlap value in range + `[0, 1]`. Integer coordinates are subtracted before conversion to floating + point so large origins remain precise while area products avoid integer overflow. + + Args: + box_true: Ground truth box in format + `(x_min, y_min, x_max, y_max)`. + box_detection: Detected box in format + `(x_min, y_min, x_max, y_max)`. + overlap_metric: Overlap type. + Use `OverlapMetric.IOU` for IOU or + `OverlapMetric.IOS` for IOS. Defaults to `OverlapMetric.IOU`. + + Returns: + Overlap value between boxes in `[0, 1]`. + + Raises: + TypeError: If either box contains complex coordinates. + ValueError: If `overlap_metric` is not IOU or IOS. + + Examples: + ```pycon + >>> import supervision as sv + >>> box_true = [100, 100, 200, 200] + >>> box_detection = [150, 150, 250, 250] + >>> sv.box_iou(box_true, box_detection, overlap_metric=sv.OverlapMetric.IOU) + 0.142857... + >>> sv.box_iou(box_true, box_detection, overlap_metric=sv.OverlapMetric.IOS) + 0.25 + + ``` + """ + overlap_metric = OverlapMetric.from_value(overlap_metric) + box_true_array = np.asarray(box_true) + box_detection_array = np.asarray(box_detection) + if np.iscomplexobj(box_true_array) or np.iscomplexobj(box_detection_array): + raise TypeError("box coordinates must be real-valued") + + x_min_true, y_min_true, x_max_true, y_max_true = box_true_array + x_min_det, y_min_det, x_max_det, y_max_det = box_detection_array + + x_min_inter = max(x_min_true, x_min_det) + y_min_inter = max(y_min_true, y_min_det) + x_max_inter = min(x_max_true, x_max_det) + y_max_inter = min(y_max_true, y_max_det) + + inter_w = max(0.0, _coordinate_difference(x_max_inter, x_min_inter)) + inter_h = max(0.0, _coordinate_difference(y_max_inter, y_min_inter)) + + area_inter = inter_w * inter_h + + area_true = _coordinate_difference(x_max_true, x_min_true) * _coordinate_difference( + y_max_true, y_min_true + ) + area_det = _coordinate_difference(x_max_det, x_min_det) * _coordinate_difference( + y_max_det, y_min_det + ) + + if overlap_metric == OverlapMetric.IOU: + area_norm = area_true + area_det - area_inter + elif overlap_metric == OverlapMetric.IOS: + area_norm = min(area_true, area_det) + else: + raise ValueError( + f"overlap_metric {overlap_metric} is not supported, " + "only 'IOU' and 'IOS' are supported" + ) + + if area_norm <= 0.0: + return 0.0 + + return float(area_inter / area_norm) + + +def box_iou_batch( + boxes_true: npt.NDArray[np.number], + boxes_detection: npt.NDArray[np.number], + overlap_metric: OverlapMetric | str = OverlapMetric.IOU, +) -> npt.NDArray[np.float32]: + """ + Compute pairwise overlap scores between batches of bounding boxes. + + Supports standard IOU (intersection-over-union) and IOS + (intersection-over-smaller-area) metrics for all `boxes_true` and + `boxes_detection` pairs. Returns a matrix of overlap values in range + `[0, 1]`, matching each box from the first batch to each from the second. + + Args: + boxes_true: Array of reference boxes in + shape `(N, 4)` as `(x_min, y_min, x_max, y_max)`. + boxes_detection: Array of detected boxes in + shape `(M, 4)` as `(x_min, y_min, x_max, y_max)`. + overlap_metric: Overlap type. + Use `OverlapMetric.IOU` for intersection-over-union, + `OverlapMetric.IOS` for intersection-over-smaller-area. + Defaults to `OverlapMetric.IOU`. + + Returns: + Overlap matrix of shape `(N, M)`, where entry + `[i, j]` is the overlap between `boxes_true[i]` and + `boxes_detection[j]`. + + Raises: + ValueError: If `overlap_metric` is not IOU or IOS. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> boxes_true = np.array([ + ... [100, 100, 200, 200], + ... [300, 300, 400, 400] + ... ]) + >>> boxes_detection = np.array([ + ... [150, 150, 250, 250], + ... [320, 320, 420, 420] + ... ]) + >>> sv.box_iou_batch( + ... boxes_true, boxes_detection, overlap_metric=sv.OverlapMetric.IOU + ... ) + array([[0.14285..., 0. ], + [0. , 0.47058...]], dtype=float32) + >>> sv.box_iou_batch( + ... boxes_true, boxes_detection, overlap_metric=sv.OverlapMetric.IOS + ... ) + array([[0.25, 0. ], + [0. , 0.64]], dtype=float32) + + ``` + """ + overlap_metric = OverlapMetric.from_value(overlap_metric) + # Upcast the corners to float64 right after unpacking so every subtraction + # and multiplication below runs in float64. This prevents integer-dtype + # overflow: an int32 box area such as 50000 * 50000 = 2.5e9 wraps to a + # negative value in int32 before any later cast could run, yielding wrong + # (often zero) IoU. Upcasting here also gives full float64 precision to + # float64/int64 callers. It does NOT recover precision already lost when a + # caller stores coordinates as float32 upstream, because that float32 + # rounding happens before this function is ever called. The final matrix is + # cast back to float32 to preserve the public return-type contract. + x_min_true, y_min_true, x_max_true, y_max_true = boxes_true.T.astype(np.float64) + x_min_det, y_min_det, x_max_det, y_max_det = boxes_detection.T.astype(np.float64) + count_true, count_det = boxes_true.shape[0], boxes_detection.shape[0] + + if count_true == 0 or count_det == 0: + return cast( + npt.NDArray[np.float32], np.empty((count_true, count_det), dtype=np.float32) + ) + + x_min_inter = np.empty((count_true, count_det), dtype=np.float64) + x_max_inter = np.empty_like(x_min_inter) + y_min_inter = np.empty_like(x_min_inter) + y_max_inter = np.empty_like(x_min_inter) + + np.maximum(x_min_true[:, None], x_min_det[None, :], out=x_min_inter) + np.minimum(x_max_true[:, None], x_max_det[None, :], out=x_max_inter) + np.maximum(y_min_true[:, None], y_min_det[None, :], out=y_min_inter) + np.minimum(y_max_true[:, None], y_max_det[None, :], out=y_max_inter) + + # we reuse x_max_inter and y_max_inter to store inter_w and inter_h + np.subtract(x_max_inter, x_min_inter, out=x_max_inter) # inter_w + np.subtract(y_max_inter, y_min_inter, out=y_max_inter) # inter_h + np.clip(x_max_inter, 0.0, None, out=x_max_inter) + np.clip(y_max_inter, 0.0, None, out=y_max_inter) + + area_inter = x_max_inter * y_max_inter # inter_w * inter_h + + area_true = (x_max_true - x_min_true) * (y_max_true - y_min_true) + area_det = (x_max_det - x_min_det) * (y_max_det - y_min_det) + + if overlap_metric == OverlapMetric.IOU: + area_norm = area_true[:, None] + area_det[None, :] - area_inter + elif overlap_metric == OverlapMetric.IOS: + area_norm = np.minimum(area_true[:, None], area_det[None, :]) + else: + raise ValueError( + f"overlap_metric {overlap_metric} is not supported, " + "only 'IOU' and 'IOS' are supported" + ) + + out: npt.NDArray[np.float32] = np.zeros_like(area_inter, dtype=np.float32) + np.divide(area_inter, area_norm, out=out, where=area_norm > 0) + return out + + +def box_iou_batch_with_jaccard( + boxes_true: Sequence[Sequence[float]], + boxes_detection: Sequence[Sequence[float]], + is_crowd: Sequence[bool], +) -> npt.NDArray[np.float64]: + """ + Calculate the intersection over union (IoU) between detection bounding boxes (dt) + and ground-truth bounding boxes (gt). + Reference: https://github.com/rafaelpadilla/review_object_detection_metrics + + Args: + boxes_true: Sequence of ground-truth bounding boxes in the + format [x, y, width, height]. + boxes_detection: Sequence of detection bounding boxes in the + format [x, y, width, height]. + is_crowd: Sequence indicating if each ground-truth bounding box + is a crowd region or not. + + Note: + This function expects bounding boxes in ``[x, y, width, height]`` format + (COCO convention). All other batch IoU functions in this module use + ``[x_min, y_min, x_max, y_max]``. + + NaN coordinates propagate silently: if any box value is ``NaN``, the + corresponding IoU values will be ``NaN``. + + Returns: + Array of IoU values of shape ``(len(boxes_detection), len(boxes_true))``, + where row ``i`` contains the IoU of detection ``i`` against all ground-truth + boxes, and column ``j`` contains the IoU of all detections against ground-truth + box ``j``. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> boxes_true = [ + ... [10, 20, 30, 40], # x, y, w, h + ... [15, 25, 35, 45] + ... ] + >>> boxes_detection = [ + ... [12, 22, 28, 38], + ... [16, 26, 36, 46] + ... ] + >>> is_crowd = [False, False] + >>> ious = sv.box_iou_batch_with_jaccard( + ... boxes_true=boxes_true, + ... boxes_detection=boxes_detection, + ... is_crowd=is_crowd + ... ) + >>> ious # doctest: +ELLIPSIS + array([[0.886..., 0.496...], + [0.4 ..., 0.862...]]) + + ``` + """ + if len(is_crowd) != len(boxes_true): + raise ValueError( + f"`is_crowd` length ({len(is_crowd)}) must match " + f"`boxes_true` length ({len(boxes_true)})." + ) + if len(boxes_detection) == 0 or len(boxes_true) == 0: + return np.empty((len(boxes_detection), len(boxes_true)), dtype=np.float64) + + # Smallest number to avoid division by zero. + eps = np.spacing(1) + gt = np.asarray(boxes_true, dtype=np.float64) + dt = np.asarray(boxes_detection, dtype=np.float64) + crowd = np.asarray(is_crowd, dtype=bool) + + # Boxes are [x, y, w, h]. Build the far corners as `x2 = x + w` (rather than + # reusing `w`) so that the area/intersection arithmetic is bit-identical to + # the per-pair reference it replaces. + gt_x2, gt_y2 = gt[:, 0] + gt[:, 2], gt[:, 1] + gt[:, 3] + dt_x2, dt_y2 = dt[:, 0] + dt[:, 2], dt[:, 1] + dt[:, 3] + + # Pairwise intersection: rows index detections, columns index ground truth. + inter_x1 = np.maximum(dt[:, 0][:, None], gt[:, 0][None, :]) + inter_y1 = np.maximum(dt[:, 1][:, None], gt[:, 1][None, :]) + inter_x2 = np.minimum(dt_x2[:, None], gt_x2[None, :]) + inter_y2 = np.minimum(dt_y2[:, None], gt_y2[None, :]) + area_inter = np.maximum(inter_x2 - inter_x1, 0.0) * np.maximum( + inter_y2 - inter_y1, 0.0 + ) + + area_det = np.maximum(dt_x2 - dt[:, 0], 0.0) * np.maximum(dt_y2 - dt[:, 1], 0.0) + area_gt = np.maximum(gt_x2 - gt[:, 0], 0.0) * np.maximum(gt_y2 - gt[:, 1], 0.0) + + # For a crowd ground truth a detection may match any subregion, so its union + # collapses to the detection area; otherwise use the standard box union. + iou: npt.NDArray[np.float64] = np.empty((len(dt), len(gt)), dtype=np.float64) + if not np.any(crowd): + area_norm = area_det[:, None] + area_gt[None, :] - area_inter + eps + else: + area_norm = np.where( + crowd[None, :], + area_det[:, None] + eps, + area_det[:, None] + area_gt[None, :] - area_inter + eps, + ) + np.divide(area_inter, area_norm, out=iou) + return iou + + +def _polygon_areas(polygons: npt.NDArray[np.number]) -> npt.NDArray[np.float64]: + """Compute the area of each oriented-box polygon using the shoelace formula. + + Each polygon is translated to its own first corner before the shoelace + products, keeping representable integer coordinates with large origins (e.g. + geospatial frames) local before conversion to float64. Float inputs that + were already quantized retain their input precision. + + Args: + polygons: ``(N, 4, 2)`` array of polygon corners. + + Returns: + ``(N,)`` array of polygon areas. + """ + origin = polygons[:, 0:1, :] + if np.issubdtype(polygons.dtype, np.integer): + translated = np.asarray( + polygons.astype(object) - origin.astype(object), dtype=np.float64 + ) + else: + polygons_float = polygons.astype(np.float64, copy=False) + translated = polygons_float - origin.astype(np.float64, copy=False) + x = translated[:, :, 0] + y = translated[:, :, 1] + cross = x * np.roll(y, -1, axis=1) - np.roll(x, -1, axis=1) * y + return cast(npt.NDArray[np.float64], 0.5 * np.abs(cross.sum(axis=1))) + + +def _aabb_envelopes(polygons: npt.NDArray[np.number]) -> npt.NDArray[np.number]: + """Compute the axis-aligned bounding envelope of each oriented box. + + Args: + polygons: ``(N, 4, 2)`` array of polygon corners. + + Returns: + ``(N, 4)`` array of ``(x_min, y_min, x_max, y_max)`` envelopes. + """ + xs = polygons[:, :, 0] + ys = polygons[:, :, 1] + return np.stack( + [xs.min(axis=1), ys.min(axis=1), xs.max(axis=1), ys.max(axis=1)], axis=1 + ) + + +def _overlapping_envelope_pairs( + envelopes_true: npt.NDArray[np.number], + envelopes_detection: npt.NDArray[np.number], +) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]: + """Return index pairs ``(i, j)`` whose axis-aligned envelopes overlap. + + Uses a fused boolean evaluation to halve peak transient memory compared to + named-intermediate form (4 separate NxM float64 arrays vs 1 boolean array). + + Note: + This gate is a correctness guarantee, not an approximation: if two + axis-aligned bounding boxes do not overlap, the convex polygons they + contain cannot overlap either. + + Args: + envelopes_true: ``(N, 4)`` array of ``(x_min, y_min, x_max, y_max)`` + envelopes for the ground-truth boxes. + envelopes_detection: ``(M, 4)`` array of ``(x_min, y_min, x_max, y_max)`` + envelopes for the detection boxes. + + Returns: + A pair of 1-D index arrays ``(rows, cols)`` identifying the overlapping + pairs. + """ + et = envelopes_true[:, None, :] + ed = envelopes_detection[None, :, :] + overlap = ( + np.minimum(et[..., 2], ed[..., 2]) > np.maximum(et[..., 0], ed[..., 0]) + ) & (np.minimum(et[..., 3], ed[..., 3]) > np.maximum(et[..., 1], ed[..., 1])) + return cast(tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], np.nonzero(overlap)) + + +def oriented_box_iou_batch( + boxes_true: npt.NDArray[np.number], + boxes_detection: npt.NDArray[np.number], + overlap_metric: OverlapMetric = OverlapMetric.IOU, +) -> npt.NDArray[np.floating]: + """ + Compute pairwise overlap scores between two sets of oriented bounding boxes + using the configured `overlap_metric`. + + Overlap areas are computed exactly via convex-polygon intersection, gated by + a cheap axis-aligned envelope pre-filter — no rasterization is involved, so + the result is exact (free of pixel-quantization error) and independent of the + coordinate magnitudes. + + `boxes_true` and `boxes_detection` are expected to be in + `((x1, y1), (x2, y2), (x3, y3), (x4, y4))` format. + + Note: + Inputs must be **convex** quads with finite coordinates. Self-intersecting + or non-convex polygons produce undefined results via + ``cv2.intersectConvexConvex``. NaN or Inf coordinates propagate silently + as ``0.0`` — validate inputs before calling if needed. + + When ``boxes_true is boxes_detection`` (the same Python object, not just + equal values), the function computes only the upper triangle of the + matrix and mirrors it. This optimization is used automatically by the + NMS/NMM callers that pass the same array twice. A defensive ``.copy()`` + at the call site would disable the optimization silently — see the + NMS caller comment for context. + + Args: + boxes_true: A `np.ndarray` representing ground-truth boxes. + `shape = (N, 4, 2)` where `N` is number of true objects. + Last axis convention: `[..., 0]` = x-coordinates, + `[..., 1]` = y-coordinates. + boxes_detection: A `np.ndarray` representing detection boxes. + `shape = (M, 4, 2)` where `M` is number of detected objects. + Last axis convention: `[..., 0]` = x-coordinates, + `[..., 1]` = y-coordinates. + overlap_metric: Metric used to compute the degree of overlap + between pairs of oriented boxes (e.g., IoU, IoS). + + Returns: + Overlap matrix of shape `(N, M)`, where entry `[i, j]` is the overlap + score between `boxes_true[i]` and `boxes_detection[j]`, in the range + `[0, 1]` under the configured :attr:`overlap_metric`. + + Raises: + ValueError: If ``boxes_true`` or ``boxes_detection`` is 3-D with inner + dimensions other than ``(4, 2)``. + ValueError: If ``boxes_true`` or ``boxes_detection`` is 2-D with a + column count other than 8. + ValueError: If ``boxes_true`` or ``boxes_detection`` is not 2-D or 3-D. + ValueError: If ``overlap_metric`` is not + :attr:`~supervision.config.OverlapMetric.IOU` or + :attr:`~supervision.config.OverlapMetric.IOS`. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> a = np.array([[[0, 0], [2, 0], [2, 2], [0, 2]]], dtype=np.float32) + >>> b = np.array([[[1, 0], [3, 0], [3, 2], [1, 2]]], dtype=np.float32) + >>> sv.oriented_box_iou_batch(a, b) # doctest: +ELLIPSIS + array([[0.333...]]) + + ``` + """ + + for name, arr in (("boxes_true", boxes_true), ("boxes_detection", boxes_detection)): + if arr.ndim == 3 and arr.shape[1:] != (4, 2): + raise ValueError( + f"`{name}` has shape {arr.shape}; expected (N, 4, 2) " + f"— each box must have exactly 4 corners with (x, y) coordinates." + ) + elif arr.ndim == 2 and arr.shape[1] != 8: + raise ValueError( + f"`{name}` has shape {arr.shape}; expected (N, 8) for flat " + f"YOLO format or (N, 4, 2) for corner format." + ) + elif arr.ndim not in (2, 3): + raise ValueError( + f"`{name}` must be 2-D (N, 8) or 3-D (N, 4, 2), got shape {arr.shape}." + ) + + if overlap_metric == OverlapMetric.IOU: + normalize_by_union = True + elif overlap_metric == OverlapMetric.IOS: + normalize_by_union = False + else: + raise ValueError( + f"overlap_metric {overlap_metric} is not supported, " + "only 'IOU' and 'IOS' are supported" + ) + + # Capture identity before reshape: NMS / NMM pass the same array twice, so + # the matrix is symmetric and we can compute only its upper triangle. + is_self_comparison = boxes_true is boxes_detection + boxes_true = boxes_true.reshape(-1, 4, 2) + boxes_detection = boxes_detection.reshape(-1, 4, 2) + + n, m = len(boxes_true), len(boxes_detection) + if n == 0 or m == 0: + return np.zeros((n, m), dtype=np.float64) + + areas_true = _polygon_areas(boxes_true) + areas_detection = _polygon_areas(boxes_detection) + + envelopes_true = _aabb_envelopes(boxes_true) + envelopes_detection = ( + envelopes_true if is_self_comparison else _aabb_envelopes(boxes_detection) + ) + rows, cols = _overlapping_envelope_pairs(envelopes_true, envelopes_detection) + if is_self_comparison: + upper = rows <= cols + rows, cols = rows[upper], cols[upper] + + ious: npt.NDArray[np.float64] = np.zeros((n, m), dtype=np.float64) + local_origins_true = envelopes_true[:, :2] + local_origins_detection = envelopes_detection[:, :2] + if np.issubdtype(boxes_true.dtype, np.integer): + local_polygons_true = np.asarray( + boxes_true.astype(object) - local_origins_true[:, None, :].astype(object), + dtype=np.float32, + ) + else: + local_polygons_true = (boxes_true - local_origins_true[:, None, :]).astype( + np.float32 + ) + if np.issubdtype(boxes_detection.dtype, np.integer): + local_polygons_detection = np.asarray( + boxes_detection.astype(object) + - local_origins_detection[:, None, :].astype(object), + dtype=np.float32, + ) + else: + local_polygons_detection = ( + boxes_detection - local_origins_detection[:, None, :] + ).astype(np.float32) + # Float32 inputs already have quantized origins, so their envelope minima + # can be reused without loss. Float64 inputs may retain unit differences at + # large origins; keep their pair offsets in float64 until each pair's local + # cast instead of rounding absolute minima to float32 up front. + origins_true_float32 = ( + local_origins_true if boxes_true.dtype == np.float32 else None + ) + origins_detection_float32 = ( + local_origins_detection if boxes_detection.dtype == np.float32 else None + ) + polygon_i_buffer = np.empty((4, 2), dtype=np.float32) + polygon_j_buffer = np.empty((4, 2), dtype=np.float32) + for i, j in zip(rows, cols): + # Rebase precomputed local polygons to the shared overlap origin. This + # preserves translation-invariant float32 geometry without repeating + # corner reductions and casts for every candidate pair. + if origins_true_float32 is not None and origins_detection_float32 is not None: + origin_i = origins_true_float32[i] + origin_j = origins_detection_float32[j] + else: + origin_i = local_origins_true[i] + origin_j = local_origins_detection[j] + pair_origin = np.minimum(origin_i, origin_j) + offset_i = (origin_i - pair_origin).astype(np.float32, copy=False) + offset_j = (origin_j - pair_origin).astype(np.float32, copy=False) + np.add(local_polygons_true[i], offset_i, out=polygon_i_buffer) + np.add(local_polygons_detection[j], offset_j, out=polygon_j_buffer) + intersection, _ = cv2.intersectConvexConvex(polygon_i_buffer, polygon_j_buffer) + if intersection <= 0: + continue + denominator = ( + areas_true[i] + areas_detection[j] - intersection + if normalize_by_union + else min(areas_true[i], areas_detection[j]) + ) + if denominator > 0: + score = intersection / denominator + ious[i, j] = score + if is_self_comparison: + ious[j, i] = score + + # DO NOT remove this clip. cv2.intersectConvexConvex computes in float32 + # internally while polygon areas are computed in float64; the intersection + # area can exceed the float64 area by ~25 ULP (~1e-7), producing raw IoU + # or IoS values microscopically above 1.0 for identical boxes. The clip is + # load-bearing, not defensive duplication. + return cast(npt.NDArray[np.floating], np.clip(ious, 0.0, 1.0)) + + +def compact_mask_iou_batch( + masks_true: Any, + masks_detection: Any, + overlap_metric: OverlapMetric = OverlapMetric.IOU, +) -> npt.NDArray[np.floating]: + """Compute pairwise overlap between two :class:`CompactMask` collections. + + Avoids materialising full ``(N, H, W)`` arrays by: + + 1. Vectorised bounding-box pre-filter — pairs whose boxes do not overlap + get IoU = 0 without any mask decoding. + 2. Sub-crop decoding — for overlapping pairs, only the intersection region + of each crop is decoded and compared. + 3. Crop caching — each individual crop is decoded at most once even when it + participates in many pairs. + + The result is numerically identical to running the dense + :func:`mask_iou_batch` on ``np.asarray(masks_true)`` / + ``np.asarray(masks_detection)``. + + Args: + masks_true: :class:`~supervision.detection.compact_mask.CompactMask` + holding the ground-truth masks. + masks_detection: :class:`~supervision.detection.compact_mask.CompactMask` + holding the detection masks. + overlap_metric: :class:`OverlapMetric` — ``IOU`` or ``IOS``. + + Returns: + Float array of shape ``(N1, N2)`` with pairwise overlap values. + """ + n1: int = len(masks_true) + n2: int = len(masks_detection) + result: npt.NDArray[np.floating] = np.zeros((n1, n2), dtype=float) + + if n1 == 0 or n2 == 0: + return result + + areas_a: npt.NDArray[np.int64] = masks_true.area + areas_b: npt.NDArray[np.int64] = masks_detection.area + + # Inclusive per-mask bounding boxes obtained from public accessors. + # bbox_xyxy: (N, 4) → (x1, y1, x2, y2) + bboxes_a: npt.NDArray[np.int32] = masks_true.bbox_xyxy.astype(np.int32) + x1a: npt.NDArray[np.int32] = bboxes_a[:, 0] + y1a: npt.NDArray[np.int32] = bboxes_a[:, 1] + x2a: npt.NDArray[np.int32] = bboxes_a[:, 2] + y2a: npt.NDArray[np.int32] = bboxes_a[:, 3] + + bboxes_b: npt.NDArray[np.int32] = masks_detection.bbox_xyxy.astype(np.int32) + x1b: npt.NDArray[np.int32] = bboxes_b[:, 0] + y1b: npt.NDArray[np.int32] = bboxes_b[:, 1] + x2b: npt.NDArray[np.int32] = bboxes_b[:, 2] + y2b: npt.NDArray[np.int32] = bboxes_b[:, 3] + + # Pairwise intersection bounding box — shape (N1, N2). + ix1: npt.NDArray[np.int32] = np.maximum(x1a[:, None], x1b[None, :]) + iy1: npt.NDArray[np.int32] = np.maximum(y1a[:, None], y1b[None, :]) + ix2: npt.NDArray[np.int32] = np.minimum(x2a[:, None], x2b[None, :]) + iy2: npt.NDArray[np.int32] = np.minimum(y2a[:, None], y2b[None, :]) + bbox_overlap: npt.NDArray[np.bool_] = (ix1 <= ix2) & (iy1 <= iy2) + + # Decode each crop at most once, even if it participates in many pairs. + crops_a: dict[int, npt.NDArray[np.bool_]] = {} + crops_b: dict[int, npt.NDArray[np.bool_]] = {} + + for idx_pair in np.argwhere(bbox_overlap): + idx_a, idx_b = int(idx_pair[0]), int(idx_pair[1]) + + if idx_a not in crops_a: + crops_a[idx_a] = masks_true.crop(idx_a) + if idx_b not in crops_b: + crops_b[idx_b] = masks_detection.crop(idx_b) + + lx1 = int(ix1[idx_a, idx_b]) + ly1 = int(iy1[idx_a, idx_b]) + lx2 = int(ix2[idx_a, idx_b]) + ly2 = int(iy2[idx_a, idx_b]) + + ox_a, oy_a = int(x1a[idx_a]), int(y1a[idx_a]) + sub_a = crops_a[idx_a][ly1 - oy_a : ly2 - oy_a + 1, lx1 - ox_a : lx2 - ox_a + 1] + + ox_b, oy_b = int(x1b[idx_b]), int(y1b[idx_b]) + sub_b = crops_b[idx_b][ly1 - oy_b : ly2 - oy_b + 1, lx1 - ox_b : lx2 - ox_b + 1] + + inter = int(np.logical_and(sub_a, sub_b).sum()) + area_a_i = int(areas_a[idx_a]) + area_b_j = int(areas_b[idx_b]) + + if overlap_metric == OverlapMetric.IOU: + union = area_a_i + area_b_j - inter + result[idx_a, idx_b] = inter / union if union > 0 else 0.0 + elif overlap_metric == OverlapMetric.IOS: + small = min(area_a_i, area_b_j) + result[idx_a, idx_b] = inter / small if small > 0 else 0.0 + else: + raise ValueError( + f"overlap_metric {overlap_metric} is not supported, " + "only 'IOU' and 'IOS' are supported" + ) + + return result + + +def _mask_iou_batch_split( + masks_true: npt.NDArray[Any], + masks_detection: npt.NDArray[Any], + overlap_metric: OverlapMetric = OverlapMetric.IOU, +) -> npt.NDArray[np.floating]: + """ + Internal function. + Compute Intersection over Union (IoU) of two sets of masks - + `masks_true` and `masks_detection`. + + Args: + masks_true: 3D `np.ndarray` representing ground-truth masks. + masks_detection: 3D `np.ndarray` representing detection masks. + overlap_metric: Metric used to compute the degree of overlap + between pairs of masks (e.g., IoU, IoS). + + Returns: + Pairwise IoU of masks from `masks_true` and `masks_detection`. + """ + # The overlap of two binary masks is the dot product of their flattened + # pixels, so the whole (N, M) intersection matrix is a single matmul. + # float32 counts pixels exactly up to 2**24; for larger masks (beyond + # ~4096x4096) we promote to float64 so the counts stay exact. + pixels = int(np.prod(masks_true.shape[1:])) + count_dtype = np.float32 if pixels <= 2**24 else np.float64 + true_flat = cast( + npt.NDArray[np.floating], + masks_true.reshape(masks_true.shape[0], pixels).astype(count_dtype, copy=False), + ) + detection_flat = cast( + npt.NDArray[np.floating], + masks_detection.reshape(masks_detection.shape[0], pixels).astype( + count_dtype, copy=False + ), + ) + with np.errstate(divide="ignore", over="ignore", invalid="ignore"): + intersection_area: npt.NDArray[np.floating[Any]] = true_flat @ detection_flat.T + + masks_true_area = true_flat.sum(axis=1) + masks_detection_area = detection_flat.sum(axis=1) + + if overlap_metric == OverlapMetric.IOU: + union_area = masks_true_area[:, None] + masks_detection_area - intersection_area + ious = np.divide( + intersection_area, + union_area, + out=np.zeros_like(intersection_area, dtype=float), + where=union_area != 0, + ) + elif overlap_metric == OverlapMetric.IOS: + # ios = intersection_area / min(area1, area2) + small_area = np.minimum(masks_true_area[:, None], masks_detection_area) + ious = np.divide( + intersection_area, + small_area, + out=np.zeros_like(intersection_area, dtype=float), + where=small_area != 0, + ) + else: + raise ValueError( + f"overlap_metric {overlap_metric} is not supported, " + "only 'IOU' and 'IOS' are supported" + ) + + ious = np.nan_to_num(ious) + return cast(npt.NDArray[np.floating], ious) + + +def mask_iou_batch( + masks_true: npt.NDArray[Any] | CompactMask, + masks_detection: npt.NDArray[Any] | CompactMask, + overlap_metric: OverlapMetric = OverlapMetric.IOU, + memory_limit: int = 1024 * 5, +) -> npt.NDArray[np.floating]: + """ + Compute Intersection over Union (IoU) of two sets of masks - + `masks_true` and `masks_detection`. + + Accepts both dense ``(N, H, W)`` boolean arrays and + :class:`~supervision.detection.compact_mask.CompactMask` objects. + When both inputs are :class:`~supervision.detection.compact_mask.CompactMask`, + the computation uses :func:`compact_mask_iou_batch` to avoid materialising + full ``(N, H, W)`` arrays. + + Args: + masks_true: 3D `np.ndarray` representing ground-truth masks. + masks_detection: 3D `np.ndarray` representing detection masks. + overlap_metric: Metric used to compute the degree of overlap + between pairs of masks (e.g., IoU, IoS). + memory_limit: Memory limit in MB, default is 1024 * 5 MB (5GB). + Controls chunking of ``masks_true`` so that flattened detection + masks plus each chunk's buffers stay within this limit. A + ``UserWarning`` is raised when ``masks_detection`` alone + exceeds the limit, as chunking cannot reduce peak memory + below that floor. Ignored when both inputs are + :class:`~supervision.detection.compact_mask.CompactMask`. + + Returns: + Pairwise IoU of masks from `masks_true` and `masks_detection`. + + Raises: + ValueError: If ``masks_true`` or ``masks_detection`` are not 3D + ``(N, H, W)`` arrays, or if they do not share the same + spatial dimensions ``(H, W)``. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> masks_true = np.zeros((1, 4, 4), dtype=bool) + >>> masks_true[:, :2, :2] = True + >>> masks_detection = np.zeros((1, 4, 4), dtype=bool) + >>> masks_detection[:, :3, :3] = True + >>> sv.mask_iou_batch(masks_true, masks_detection) + array([[0.44444445]]) + + ``` + """ + + if isinstance(masks_true, CompactMask) and isinstance(masks_detection, CompactMask): + return compact_mask_iou_batch(masks_true, masks_detection, overlap_metric) + + # Materialise any CompactMask that was passed alongside a dense array. + if isinstance(masks_true, CompactMask): + masks_true = np.asarray(masks_true) + if isinstance(masks_detection, CompactMask): + masks_detection = np.asarray(masks_detection) + + if masks_true.ndim != 3 or masks_detection.ndim != 3: + raise ValueError( + "masks_true and masks_detection must be 3D (N, H, W); got " + f"ndim={masks_true.ndim} and ndim={masks_detection.ndim}." + ) + if masks_true.shape[1:] != masks_detection.shape[1:]: + raise ValueError( + "masks_true and masks_detection must share the same (H, W); got " + f"{masks_true.shape[1:]} and {masks_detection.shape[1:]}." + ) + # A single pass already handles empty inputs and avoids np.vstack([]) below. + if masks_true.shape[0] == 0 or masks_detection.shape[0] == 0: + return _mask_iou_batch_split(masks_true, masks_detection, overlap_metric) + + # Peak memory of a single matmul pass: the flattened detection masks (shared + # across chunks) plus, per true-mask row, its flattened pixels and the three + # (N, M) matrices it touches (intersection, denominator and output). The + # previous (N, M, H, W) estimate overcounted by a factor of M and forced + # needless chunking now that the intersection is a matmul. + pixels = masks_true.shape[1] * masks_true.shape[2] + itemsize = 4 if pixels <= 2**24 else 8 + limit_bytes = memory_limit * 1024 * 1024 + detection_bytes = masks_detection.shape[0] * pixels * itemsize + per_true_row = pixels * itemsize + 3 * masks_detection.shape[0] * 8 + if detection_bytes > limit_bytes > 0: + warnings.warn( + f"detection masks ({detection_bytes // 1024 // 1024} MB) exceed " + f"memory_limit ({memory_limit} MB); chunking cannot reduce peak " + "memory below this floor.", + UserWarning, + stacklevel=2, + ) + if detection_bytes + masks_true.shape[0] * per_true_row <= limit_bytes: + return _mask_iou_batch_split(masks_true, masks_detection, overlap_metric) + + ious = [] + step = max((limit_bytes - detection_bytes) // per_true_row, 1) + for chunk_start in range(0, masks_true.shape[0], step): + ious.append( + _mask_iou_batch_split( + masks_true[chunk_start : chunk_start + step], + masks_detection, + overlap_metric, + ) + ) + + return cast(npt.NDArray[np.floating], np.vstack(ious)) + + +def mask_non_max_suppression( + predictions: npt.NDArray[np.floating], + masks: npt.NDArray[Any] | CompactMask, + iou_threshold: float = 0.5, + overlap_metric: OverlapMetric = OverlapMetric.IOU, + mask_dimension: int = 640, +) -> npt.NDArray[np.bool_]: + """ + Perform Non-Maximum Suppression (NMS) on segmentation predictions. + + IoU is computed exactly on the full-resolution masks for both dense and + :class:`~supervision.detection.compact_mask.CompactMask` inputs. The + ``mask_dimension`` parameter is kept for backward compatibility but is no + longer used — dense masks are **not** resized before IoU computation. + + Args: + predictions: A 2D array of object detection predictions in + the format of `(x_min, y_min, x_max, y_max, score)` + or `(x_min, y_min, x_max, y_max, score, class)`. Shape: `(N, 5)` or + `(N, 6)`, where N is the number of predictions. + masks: A 3D array of binary masks corresponding to the predictions. + Shape: `(N, H, W)`, where N is the number of predictions, and H, W are the + dimensions of each mask. + iou_threshold: The intersection-over-union threshold + to use for non-maximum suppression. + overlap_metric: Metric used to compute the degree of overlap + between pairs of masks (e.g., IoU, IoS). + mask_dimension: Deprecated, no longer used. Kept for backward + compatibility. + + Returns: + A boolean array indicating which predictions to keep after + non-maximum suppression. + + Raises: + ValueError: If `iou_threshold` is not within the closed range + from `0` to `1`. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> predictions = np.array([ + ... [0, 0, 4, 4, 0.9, 0], + ... [0, 0, 4, 4, 0.8, 0], + ... ]) + >>> masks = np.zeros((2, 4, 4), dtype=bool) + >>> masks[:, :2, :2] = True + >>> sv.mask_non_max_suppression(predictions, masks, iou_threshold=0.5) + array([ True, False]) + + ``` + """ + _validate_iou_threshold(iou_threshold) + rows, columns = predictions.shape + + if columns == 5: + predictions = np.c_[predictions, np.zeros(rows)] + + sort_index = predictions[:, 4].argsort()[::-1] + predictions = predictions[sort_index] + masks = masks[sort_index] + + ious = mask_iou_batch(masks, masks, overlap_metric) + categories = predictions[:, 5] + + keep = np.ones(rows, dtype=bool) + for row_idx in range(rows): + if keep[row_idx]: + condition = (ious[row_idx] > iou_threshold) & ( + categories[row_idx] == categories + ) + keep[row_idx + 1 :] = np.where( + condition[row_idx + 1 :], False, keep[row_idx + 1 :] + ) + + return cast(npt.NDArray[np.bool_], keep[sort_index.argsort()]) + + +def mask_soft_non_max_suppression( + predictions: npt.NDArray[np.floating], + masks: npt.NDArray[Any] | CompactMask, + sigma: float = 0.5, + overlap_metric: OverlapMetric = OverlapMetric.IOU, + mask_dimension: int = 640, +) -> npt.NDArray[np.floating]: + """ + Perform Soft Non-Maximum Suppression (Soft-NMS) on segmentation predictions. + + Unlike `mask_non_max_suppression`, which discards overlapping masks outright, + Soft-NMS keeps every detection and instead rescales its confidence by + `score *= exp(-iou**2 / sigma)` for each higher-scoring, same-category + overlap — the caller decides whether and where to threshold the result. + A smaller `sigma` produces a stronger decay. + + The 3rd positional parameter here is `sigma`, not `iou_threshold` as in + `mask_non_max_suppression` — Soft-NMS has no threshold to suppress at, only + a decay strength, so the two signatures intentionally diverge at that + position. + + IoU is computed exactly on the full-resolution masks for both dense and + :class:`~supervision.detection.compact_mask.CompactMask` inputs. The + `mask_dimension` parameter is kept for signature parity with + `mask_non_max_suppression` but is not used — dense masks are **not** resized + before IoU computation. + + Args: + predictions: A 2D array of object detection predictions in + the format of `(x_min, y_min, x_max, y_max, score)` + or `(x_min, y_min, x_max, y_max, score, class)`. Shape: `(N, 5)` or + `(N, 6)`, where N is the number of predictions. + masks: A 3D array of binary masks corresponding to the predictions. + Shape: `(N, H, W)`, where N is the number of predictions, and H, W are the + dimensions of each mask. + sigma: Controls the strength of the confidence decay; must be greater + than `0`. No value of `sigma` reproduces hard + `mask_non_max_suppression` output — Soft-NMS never drops masks, only + rescales confidence. + overlap_metric: Metric used to compute the degree of overlap + between pairs of masks (e.g., IoU, IoS). + mask_dimension: Deprecated, unused. Kept for signature parity with + `mask_non_max_suppression`. + + Returns: + An array containing the updated (decayed) confidence scores, in the + same order as the input `predictions`. + + Raises: + ValueError: If `sigma` is not greater than `0`. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> predictions = np.array([ + ... [0, 0, 4, 4, 0.9, 0], + ... [0, 0, 4, 4, 0.8, 0], + ... ]) + >>> masks = np.zeros((2, 4, 4), dtype=bool) + >>> masks[:, :2, :2] = True + >>> sv.mask_soft_non_max_suppression(predictions, masks, sigma=0.5) + array([0.9 , 0.10826823]) + + ``` + """ + _validate_sigma(sigma) + rows, columns = predictions.shape + + if columns == 5: + predictions = np.c_[predictions, np.zeros(rows)] + + sort_index = predictions[:, 4].argsort()[::-1] + predictions = predictions[sort_index] + masks = masks[sort_index] + + ious = mask_iou_batch(masks, masks, overlap_metric) + categories = predictions[:, 5] + + decayed = _soft_nms_decay_from_iou_matrix( + ious, categories, predictions[:, 4], sigma + ) + return decayed[sort_index.argsort()] + + +def _prepare_predictions_for_nms( + predictions: npt.NDArray[np.floating], +) -> tuple[npt.NDArray[np.int_], npt.NDArray[np.floating], npt.NDArray[np.floating]]: + """Add an agnostic class column when missing, sort by descending score. + + Returns the score-descending sort index, the reordered predictions, and the + category vector for the loop callers to consume. + """ + rows, columns = predictions.shape + if columns == 5: + predictions = np.c_[predictions, np.zeros(rows)] + sort_index = np.flip(predictions[:, 4].argsort()) + predictions = predictions[sort_index] + categories = predictions[:, 5] + return sort_index, predictions, categories + + +def _nms_loop_from_iou_matrix( + ious: npt.NDArray[np.floating], + categories: npt.NDArray[np.floating], + iou_threshold: float, +) -> npt.NDArray[np.bool_]: + """Greedy NMS suppression loop given a precomputed pairwise IoU matrix. + + Assumes `ious` is square with row/column order matching `categories`. + Detections sharing a category whose IoU exceeds `iou_threshold` are dropped + in favour of the higher-confidence entry. + """ + rows = len(ious) + ious = ious - np.eye(rows) + keep: npt.NDArray[np.bool_] = np.ones(rows, dtype=bool) + for index, (iou, category) in enumerate(zip(ious, categories)): + if not keep[index]: + continue + condition = (iou > iou_threshold) & (categories == category) + keep = keep & ~condition + return keep + + +def _validate_sigma(sigma: float) -> None: + """Raise `ValueError` when a Soft-NMS `sigma` is not strictly positive.""" + if not sigma > 0: + raise ValueError(f"Value of `sigma` must be greater than 0, {sigma} given.") + + +def _soft_nms_decay_from_iou_matrix( + ious: npt.NDArray[np.floating], + categories: npt.NDArray[np.floating], + scores: npt.NDArray[np.floating], + sigma: float, +) -> npt.NDArray[np.floating]: + """Vectorized Gaussian Soft-NMS confidence decay given a precomputed IoU matrix. + + Assumes `ious`, `categories`, and `scores` are all sorted by descending score + (as produced by `_prepare_predictions_for_nms`), and that `ious` is square with + row/column order matching `categories`. Each detection's score is decayed once + per higher-scoring, same-category detection that precedes it — equivalent to + the reference single-pass (no re-sort) Soft-NMS loop, computed as a single + vectorized closed form: `decayed[j] = scores[j] * exp(-sum_i(ious[i, j]**2) / + sigma)` summed over same-category `i < j`. + """ + rows = len(ious) + same_category = categories[:, None] == categories[None, :] + precedes = np.triu(np.ones((rows, rows), dtype=bool), k=1) + weighted_iou_sq = np.where(precedes & same_category, ious**2, 0.0) + decay_exponent = weighted_iou_sq.sum(axis=0) + return cast(npt.NDArray[np.floating], scores * np.exp(-decay_exponent / sigma)) + + +def box_non_max_suppression( + predictions: npt.NDArray[np.floating], + iou_threshold: float = 0.5, + overlap_metric: OverlapMetric = OverlapMetric.IOU, +) -> npt.NDArray[np.bool_]: + """ + Perform Non-Maximum Suppression (NMS) on object detection predictions. + + Args: + predictions: An array of object detection predictions in + the format of `(x_min, y_min, x_max, y_max, score)` + or `(x_min, y_min, x_max, y_max, score, class)`. + iou_threshold: The intersection-over-union threshold + to use for non-maximum suppression. + overlap_metric: Metric used to compute the degree of overlap + between pairs of boxes (e.g., IoU, IoS). + + Returns: + A boolean array indicating which predictions to keep after + non-maximum suppression. + + Raises: + ValueError: If `iou_threshold` is not within the closed range + from `0` to `1`. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> predictions = np.array([ + ... [0, 0, 4, 4, 0.9, 0], + ... [0, 0, 4, 4, 0.8, 0], + ... ]) + >>> sv.box_non_max_suppression(predictions, iou_threshold=0.5) + array([ True, False]) + + ``` + """ + _validate_iou_threshold(iou_threshold) + sort_index, predictions, categories = _prepare_predictions_for_nms(predictions) + ious = box_iou_batch(predictions[:, :4], predictions[:, :4], overlap_metric) + keep = _nms_loop_from_iou_matrix(ious, categories, iou_threshold) + result: npt.NDArray[np.bool_] = keep[sort_index.argsort()] + return result + + +def box_soft_non_max_suppression( + predictions: npt.NDArray[np.floating], + sigma: float = 0.5, + overlap_metric: OverlapMetric = OverlapMetric.IOU, +) -> npt.NDArray[np.floating]: + """ + Perform Soft Non-Maximum Suppression (Soft-NMS) on object detection predictions. + + Unlike `box_non_max_suppression`, which discards overlapping boxes outright, + Soft-NMS keeps every detection and instead rescales its confidence by + `score *= exp(-iou**2 / sigma)` for each higher-scoring, same-category + overlap — the caller decides whether and where to threshold the result. + A smaller `sigma` produces a stronger decay. + + Args: + predictions: An array of object detection predictions in + the format of `(x_min, y_min, x_max, y_max, score)` + or `(x_min, y_min, x_max, y_max, score, class)`. + sigma: Controls the strength of the confidence decay; must be greater + than `0`. No value of `sigma` reproduces hard + `box_non_max_suppression` output — Soft-NMS never drops boxes, only + rescales confidence. + overlap_metric: Metric used to compute the degree of overlap + between pairs of boxes (e.g., IoU, IoS). + + Returns: + An array containing the updated (decayed) confidence scores, in the + same order as the input `predictions`. + + Raises: + ValueError: If `sigma` is not greater than `0`. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> predictions = np.array([ + ... [0, 0, 4, 4, 0.9, 0], + ... [0, 0, 4, 4, 0.8, 0], + ... ]) + >>> sv.box_soft_non_max_suppression(predictions, sigma=0.5) + array([0.9 , 0.10826823]) + + ``` + """ + _validate_sigma(sigma) + sort_index, predictions, categories = _prepare_predictions_for_nms(predictions) + ious = box_iou_batch(predictions[:, :4], predictions[:, :4], overlap_metric) + decayed = _soft_nms_decay_from_iou_matrix( + ious, categories, predictions[:, 4], sigma + ) + result_scores: npt.NDArray[np.floating] = decayed[sort_index.argsort()] + return result_scores + + +def _group_overlapping_masks( + predictions: npt.NDArray[np.floating], + masks: npt.NDArray[np.bool_], + iou_threshold: float = 0.5, + overlap_metric: OverlapMetric = OverlapMetric.IOU, +) -> list[list[int]]: + """ + Apply greedy version of non-maximum merging to avoid detecting too many + + Args: + predictions: An array of shape `(n, 5)` containing + the bounding boxes coordinates in format `[x1, y1, x2, y2]` + and the confidence scores. + masks: A 3D array of binary masks corresponding to + the predictions. + iou_threshold: The intersection-over-union threshold + to use for non-maximum suppression. Defaults to 0.5. + overlap_metric: Metric used to compute the degree of overlap + between pairs of masks (e.g., IoU, IoS). + + Returns: + Groups of prediction indices to be merged. + Each group may have 1 or more elements. + """ + merge_groups: list[list[int]] = [] + + scores = predictions[:, 4] + order = scores.argsort() + + while len(order) > 0: + idx = int(order[-1]) + + order = order[:-1] + if len(order) == 0: + merge_groups.append([idx]) + break + + merge_candidate = masks[idx][None, ...] + candidate_groups = [idx] + while len(order) > 0: + ious = mask_iou_batch(masks[order], merge_candidate, overlap_metric) + above_threshold: npt.NDArray[np.bool_] = ious.flatten() >= iou_threshold + if not above_threshold.any(): + break + above_idx = order[above_threshold] + merge_candidate = np.logical_or.reduce( + np.concatenate([masks[above_idx], merge_candidate]), + axis=0, + keepdims=True, + ) + candidate_groups.extend(np.flip(above_idx).tolist()) + order = order[~above_threshold] + + merge_groups.append(candidate_groups) + return merge_groups + + +def mask_non_max_merge( + predictions: npt.NDArray[np.floating], + masks: npt.NDArray[Any] | CompactMask, + iou_threshold: float = 0.5, + *args: Any, + overlap_metric: OverlapMetric = OverlapMetric.IOU, + mask_dimension: int = 640, +) -> list[list[int]]: + """ + Perform Non-Maximum Merging (NMM) on segmentation predictions. + + Args: + predictions: A 2D array of object detection predictions in + the format of `(x_min, y_min, x_max, y_max, score)` + or `(x_min, y_min, x_max, y_max, score, class)`. Shape: `(N, 5)` or + `(N, 6)`, where N is the number of predictions. + masks: A 3D array of binary masks corresponding to the predictions. + Shape: `(N, H, W)`, where N is the number of predictions, and H, W are the + dimensions of each mask. + iou_threshold: The intersection-over-union threshold + to use for non-maximum merging. + overlap_metric: Metric used to compute the degree of overlap + between pairs of masks (e.g., IoU, IoS). + mask_dimension: Deprecated in `0.30.0`, removed in `0.33.0`. No longer + used; the parameter is silently ignored. Passing `mask_dimension` + positionally emits a deprecation warning. + + Returns: + A list of groups of prediction indices. Each inner list contains + the indices of predictions whose masks overlap above `iou_threshold` + according to the chosen `overlap_metric`, and should be merged or + kept together as a single detection by non-maximum merging. + + Raises: + ValueError: If `iou_threshold` is not within the closed range + from `0` to `1`. + TypeError: If more than five positional arguments are passed. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> predictions = np.array([ + ... [0, 0, 4, 4, 0.9, 0], + ... [0, 0, 4, 4, 0.8, 0], + ... ]) + >>> masks = np.zeros((2, 4, 4), dtype=bool) + >>> masks[:, :2, :2] = True + >>> sv.mask_non_max_merge(predictions, masks, iou_threshold=0.5) + [[0, 1]] + + ``` + """ + + _validate_iou_threshold(iou_threshold) + if len(args) > 2: + raise TypeError( + "mask_non_max_merge accepts at most five positional arguments. " + "Pass overlap_metric and mask_dimension by keyword." + ) + if args: + warn_deprecated( + "Passing `overlap_metric` or `mask_dimension` positionally to " + "`mask_non_max_merge` is deprecated in `0.30.0` and will be removed " + "in `0.33.0`. Pass them by keyword instead." + ) + first = args[0] + if isinstance(first, OverlapMetric): + overlap_metric = first + else: + mask_dimension = cast(int, first) + if len(args) == 2: + second = args[1] + if isinstance(first, OverlapMetric): + mask_dimension = cast(int, second) + else: + overlap_metric = cast(OverlapMetric, second) + + del mask_dimension + + def group_within(global_indices: npt.NDArray[np.int_]) -> list[list[int]]: + if isinstance(masks, CompactMask): + return _group_overlapping_masks_pairwise( + predictions[global_indices], + masks[global_indices], + iou_threshold, + overlap_metric, + ) + return _group_overlapping_masks( + predictions[global_indices], + masks[global_indices], + iou_threshold, + overlap_metric, + ) + + return _non_max_merge_per_category(predictions, group_within) + + +def _update_mask_candidate( + masks: npt.NDArray[Any] | CompactMask, + candidate: npt.NDArray[Any] | CompactMask, + above_idx: npt.NDArray[np.int_], +) -> npt.NDArray[Any] | CompactMask: + if isinstance(masks, CompactMask): + compact_candidate = cast(CompactMask, candidate) + union_mask = np.logical_or.reduce( + np.concatenate([masks[above_idx].to_dense(), compact_candidate.to_dense()]), + axis=0, + keepdims=True, + ) + return CompactMask.from_dense( + masks=union_mask, + xyxy=mask_to_xyxy(union_mask), + image_shape=masks.image_shape, + ) + dense_candidate = cast(npt.NDArray[Any], candidate) + dense_union: npt.NDArray[Any] = np.logical_or.reduce( + np.concatenate([masks[above_idx], dense_candidate]), + axis=0, + keepdims=True, + ) + return dense_union + + +def _greedy_nmm_via_mask_candidate( + predictions: npt.NDArray[np.floating], + masks: npt.NDArray[Any] | CompactMask, + iou_threshold: float = 0.5, + overlap_metric: OverlapMetric = OverlapMetric.IOU, +) -> list[list[int]]: + """Group masks by exact overlap while updating the merged candidate union.""" + merge_groups: list[list[int]] = [] + scores = predictions[:, 4] + order = scores.argsort() + while len(order) > 0: + idx = int(order[-1]) + order = order[:-1] + if len(order) == 0: + merge_groups.append([idx]) + break + candidate = masks[[idx]] + merge_group = [idx] + while len(order) > 0: + ious = mask_iou_batch(masks[order], candidate, overlap_metric).flatten() + above_threshold = ious >= iou_threshold + if not above_threshold.any(): + break + above_idx = order[above_threshold] + candidate = _update_mask_candidate(masks, candidate, above_idx) + merge_group.extend(np.flip(above_idx).tolist()) + order = order[~above_threshold] + merge_groups.append(merge_group) + return merge_groups + + +def _group_overlapping_masks_pairwise( + predictions: npt.NDArray[np.floating], + masks: npt.NDArray[Any] | CompactMask, + iou_threshold: float = 0.5, + overlap_metric: OverlapMetric = OverlapMetric.IOU, +) -> list[list[int]]: + return _greedy_nmm_via_mask_candidate( + predictions, masks, iou_threshold, overlap_metric + ) + + +def _non_max_merge_per_category( + predictions: npt.NDArray[np.floating], + group_within: Callable[[npt.NDArray[np.int_]], list[list[int]]], +) -> list[list[int]]: + """Dispatch NMM grouping per class, then translate local indices back to + the global row positions of ``predictions``. + + ``group_within(global_indices)`` must return merge groups expressed in + terms of *positions inside `global_indices`*, not absolute row positions. + When ``predictions`` has no class column, a single pass over all rows is + performed instead of per-category iteration. + """ + if predictions.shape[1] == 5: + global_indices = np.arange(len(predictions), dtype=int) + return [ + global_indices[group].tolist() for group in group_within(global_indices) + ] + + category_ids = predictions[:, 5] + merge_groups: list[list[int]] = [] + for category_id in np.unique(category_ids): + curr_indices = np.where(category_ids == category_id)[0] + for local_group in group_within(curr_indices): + merge_groups.append(curr_indices[local_group].tolist()) + + for merge_group in merge_groups: + if len(merge_group) == 0: + raise ValueError( + f"Empty group detected when non-max-merging detections: {merge_groups}" + ) + return merge_groups + + +def _group_overlapping_boxes( + predictions: npt.NDArray[np.floating], + iou_threshold: float = 0.5, + overlap_metric: OverlapMetric = OverlapMetric.IOU, +) -> list[list[int]]: + """ + Apply greedy version of non-maximum merging to avoid detecting too many + overlapping bounding boxes for a given object. + + Args: + predictions: An array of shape `(n, 5)` containing + the bounding boxes coordinates in format `[x1, y1, x2, y2]` + and the confidence scores. + iou_threshold: The intersection-over-union threshold + to use for non-maximum suppression. Defaults to 0.5. + overlap_metric: Metric used to compute the degree of overlap + between pairs of boxes (e.g., IoU, IoS). + + Returns: + Groups of prediction indices to be merged. + Each group may have 1 or more elements. + """ + merge_groups: list[list[int]] = [] + scores = predictions[:, 4] + order = scores.argsort() + while len(order) > 0: + idx = int(order[-1]) + order = order[:-1] + if len(order) == 0: + merge_groups.append([idx]) + break + ious = box_iou_batch( + predictions[order][:, :4], + predictions[idx : idx + 1, :4], + overlap_metric, + ).flatten() + above_threshold = ious >= iou_threshold + merge_group = [idx, *np.flip(order[above_threshold]).tolist()] + merge_groups.append(merge_group) + order = order[~above_threshold] + return merge_groups + + +def box_non_max_merge( + predictions: npt.NDArray[np.floating], + iou_threshold: float = 0.5, + overlap_metric: OverlapMetric = OverlapMetric.IOU, +) -> list[list[int]]: + """ + Apply greedy version of non-maximum merging per category to avoid detecting + too many overlapping bounding boxes for a given object. + + Args: + predictions: An array of shape `(n, 5)` or `(n, 6)` + containing the bounding boxes coordinates in format `[x1, y1, x2, y2]`, + the confidence scores and class_ids. Omit class_id column to allow + detections of different classes to be merged. + iou_threshold: The intersection-over-union threshold + to use for non-maximum suppression. Defaults to 0.5. + overlap_metric: Metric used to compute the degree of overlap + between pairs of boxes (e.g., IoU, IoS). + + Returns: + list[list[int]]: Groups of prediction indices be merged. + Each group may have 1 or more elements. + + Raises: + ValueError: If `iou_threshold` is not within the closed range + from `0` to `1`. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> predictions = np.array([ + ... [0, 0, 4, 4, 0.9, 0], + ... [0, 0, 4, 4, 0.8, 0], + ... ]) + >>> sv.box_non_max_merge(predictions, iou_threshold=0.5) + [[0, 1]] + + ``` + """ + _validate_iou_threshold(iou_threshold) + + def group_within(global_indices: npt.NDArray[np.int_]) -> list[list[int]]: + return _group_overlapping_boxes( + predictions[global_indices], iou_threshold, overlap_metric + ) + + return _non_max_merge_per_category(predictions, group_within) + + +def oriented_box_non_max_suppression( + predictions: npt.NDArray[np.floating], + oriented_boxes: npt.NDArray[np.floating], + iou_threshold: float = 0.5, + overlap_metric: OverlapMetric = OverlapMetric.IOU, +) -> npt.NDArray[np.bool_]: + """ + Perform Non-Maximum Suppression on oriented bounding box predictions. + + Overlap is computed via :func:`oriented_box_iou_batch` on the four + corners of each box, so detections whose axis-aligned bounding boxes + overlap heavily but whose oriented bodies do not are kept — unlike + :func:`box_non_max_suppression`, which would suppress them. + + Args: + predictions: An array of object detection predictions in the + format ``(x_min, y_min, x_max, y_max, score)`` or + ``(x_min, y_min, x_max, y_max, score, class)``. Shape ``(N, 5)`` + or ``(N, 6)``. Only the score (column 4) and optional class + (column 5) are read; the axis-aligned coordinates are not used. + oriented_boxes: Array of shape ``(N, 4, 2)`` containing the four + ``(x, y)`` corners of each oriented box, aligned with + ``predictions`` row-by-row. + iou_threshold: The intersection-over-union threshold to use for + non-maximum suppression. + overlap_metric: Metric used to compute the degree of overlap + between pairs of oriented boxes (e.g., IoU, IoS). + + Returns: + A boolean array of shape ``(N,)`` indicating which predictions + to keep after non-maximum suppression. + + Raises: + ValueError: If ``iou_threshold`` is not within the closed range + from 0 to 1. + ValueError: If ``predictions`` and ``oriented_boxes`` have + mismatched lengths or invalid shapes. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> oriented_boxes = np.array([ + ... [[10, 10], [50, 10], [50, 30], [10, 30]], + ... [[11, 11], [51, 11], [51, 31], [11, 31]], + ... ], dtype=np.float32) + >>> predictions = np.array([ + ... [10, 10, 50, 30, 0.9, 0], + ... [11, 11, 51, 31, 0.8, 0], + ... ], dtype=np.float32) + >>> keep = sv.oriented_box_non_max_suppression( + ... predictions=predictions, + ... oriented_boxes=oriented_boxes, + ... iou_threshold=0.5, + ... ) + >>> keep + array([ True, False]) + + ``` + """ + _validate_iou_threshold(iou_threshold) + for name, arr in (("predictions", predictions), ("oriented_boxes", oriented_boxes)): + if name == "predictions": + if arr.ndim != 2 or arr.shape[1] not in (5, 6): + raise ValueError( + f"`{name}` has shape {arr.shape}; expected (N, 5) or (N, 6)." + ) + continue + if arr.ndim == 3 and arr.shape[1:] != (4, 2): + raise ValueError( + f"`{name}` has shape {arr.shape}; expected (N, 4, 2) " + f"— each box must have exactly 4 corners with (x, y) coordinates." + ) + elif arr.ndim == 2 and arr.shape[1] != 8: + raise ValueError( + f"`{name}` has shape {arr.shape}; expected (N, 8) for flat " + f"YOLO format or (N, 4, 2) for corner format." + ) + elif arr.ndim not in (2, 3): + raise ValueError( + f"`{name}` must be 2-D (N, 8) or 3-D (N, 4, 2), got shape {arr.shape}." + ) + if len(predictions) != len(oriented_boxes): + raise ValueError( + f"`predictions` and `oriented_boxes` must have the same length, " + f"got {len(predictions)} and {len(oriented_boxes)}." + ) + sort_index, _, categories = _prepare_predictions_for_nms(predictions) + oriented_boxes = oriented_boxes[sort_index] + # same object intentional — triggers upper-triangle optimization + ious = oriented_box_iou_batch(oriented_boxes, oriented_boxes, overlap_metric) + keep = _nms_loop_from_iou_matrix(ious, categories, iou_threshold) + result: npt.NDArray[np.bool_] = keep[sort_index.argsort()] + return result + + +def _group_overlapping_oriented_boxes( + predictions: npt.NDArray[np.floating], + oriented_boxes: npt.NDArray[np.floating], + iou_threshold: float = 0.5, + overlap_metric: OverlapMetric = OverlapMetric.IOU, +) -> list[list[int]]: + """ + Greedy non-maximum merging on oriented boxes. Mirrors + :func:`_group_overlapping_boxes` but uses :func:`oriented_box_iou_batch`. + """ + merge_groups: list[list[int]] = [] + scores = predictions[:, 4] + order = scores.argsort() + while len(order) > 0: + idx = int(order[-1]) + order = order[:-1] + if len(order) == 0: + merge_groups.append([idx]) + break + ious = oriented_box_iou_batch( + oriented_boxes[order], + oriented_boxes[idx][None, ...], + overlap_metric, + ).flatten() + above_threshold = ious >= iou_threshold + merge_group = [idx, *np.flip(order[above_threshold]).tolist()] + merge_groups.append(merge_group) + order = order[~above_threshold] + return merge_groups + + +def oriented_box_non_max_merge( + predictions: npt.NDArray[np.floating], + oriented_boxes: npt.NDArray[np.floating], + iou_threshold: float = 0.5, + overlap_metric: OverlapMetric = OverlapMetric.IOU, +) -> list[list[int]]: + """ + Perform Non-Maximum Merging on oriented bounding box predictions, + grouped per category. + + Mirrors :func:`box_non_max_merge` but uses oriented-box IoU, so groups + of rotated detections sharing the same body — rather than the same + axis-aligned bounding box — are merged. + + Args: + predictions: An array of shape ``(n, 5)`` or ``(n, 6)`` containing + the axis-aligned coordinates ``[x1, y1, x2, y2]``, confidence + scores, and optionally class ids. Only the score and optional + class are used by the grouping logic; overlap is computed on + ``oriented_boxes``. + oriented_boxes: Array of shape ``(N, 4, 2)`` containing the four + ``(x, y)`` corners of each oriented box. + iou_threshold: The intersection-over-union threshold to use for + non-maximum merging. + overlap_metric: Metric used to compute the degree of overlap + between pairs of oriented boxes (e.g., IoU, IoS). + + Returns: + Groups of prediction indices to be merged. Each group may have 1 + or more elements. + + Raises: + ValueError: If ``iou_threshold`` is not within the closed range + from 0 to 1. + ValueError: If ``predictions`` and ``oriented_boxes`` have + mismatched lengths or invalid shapes. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> oriented_boxes = np.array([ + ... [[10, 10], [50, 10], [50, 30], [10, 30]], + ... [[11, 11], [51, 11], [51, 31], [11, 31]], + ... ], dtype=np.float32) + >>> predictions = np.array([ + ... [10, 10, 50, 30, 0.9, 0], + ... [11, 11, 51, 31, 0.8, 0], + ... ], dtype=np.float32) + >>> groups = sv.oriented_box_non_max_merge( + ... predictions=predictions, + ... oriented_boxes=oriented_boxes, + ... iou_threshold=0.5, + ... ) + >>> len(groups) + 1 + + ``` + """ + for name, arr in (("predictions", predictions), ("oriented_boxes", oriented_boxes)): + if name == "predictions": + if arr.ndim != 2 or arr.shape[1] not in (5, 6): + raise ValueError( + f"`{name}` has shape {arr.shape}; expected (N, 5) or (N, 6)." + ) + continue + if arr.ndim == 3 and arr.shape[1:] != (4, 2): + raise ValueError( + f"`{name}` has shape {arr.shape}; expected (N, 4, 2) " + f"— each box must have exactly 4 corners with (x, y) coordinates." + ) + elif arr.ndim == 2 and arr.shape[1] != 8: + raise ValueError( + f"`{name}` has shape {arr.shape}; expected (N, 8) for flat " + f"YOLO format or (N, 4, 2) for corner format." + ) + elif arr.ndim not in (2, 3): + raise ValueError( + f"`{name}` must be 2-D (N, 8) or 3-D (N, 4, 2), got shape {arr.shape}." + ) + if len(predictions) != len(oriented_boxes): + raise ValueError( + f"`predictions` and `oriented_boxes` must have the same length, " + f"got {len(predictions)} and {len(oriented_boxes)}." + ) + _validate_iou_threshold(iou_threshold) + + def group_within(global_indices: npt.NDArray[np.int_]) -> list[list[int]]: + return _group_overlapping_oriented_boxes( + predictions[global_indices], + oriented_boxes[global_indices], + iou_threshold, + overlap_metric, + ) + + return _non_max_merge_per_category(predictions, group_within) diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/utils/masks.py b/.venv/lib/python3.12/site-packages/supervision/detection/utils/masks.py new file mode 100644 index 0000000000000000000000000000000000000000..14a5b0b352ffa536f23c14b580a5fba3ec4bce67 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/detection/utils/masks.py @@ -0,0 +1,639 @@ +from typing import Any, Literal, cast + +import numpy as np +import numpy.typing as npt + +from supervision import _cv2 as cv2 +from supervision._cv2._components import _contains_holes +from supervision.detection.compact_mask import CompactMask + + +def count_mask_pixels(masks: npt.NDArray[np.bool_]) -> npt.NDArray[np.int64]: + """Count the number of True pixels in each mask. + + Uses ``np.count_nonzero`` (no axis), which dispatches to a SIMD popcount + over the raw bool buffer and is ~6x faster than ``np.sum(mask, axis=(1, 2))``. + + Args: + masks: Boolean mask array of shape ``(N, H, W)``. + + Returns: + Int64 array of shape ``(N,)`` with the True-pixel count per mask. + + Example: + ```pycon + >>> import numpy as np + >>> from supervision.detection.utils.masks import count_mask_pixels + >>> m = np.zeros((2, 4, 4), dtype=bool) + >>> m[0, :2, :2] = True # 4 pixels + >>> m[1, :3, :3] = True # 9 pixels + >>> count_mask_pixels(m) + array([4, 9]) + + ``` + """ + return np.fromiter( + (np.count_nonzero(m) for m in masks), dtype=np.int64, count=len(masks) + ) + + +def move_masks( + masks: npt.NDArray[np.bool_], + offset: npt.NDArray[np.integer], + resolution_wh: tuple[int, int], +) -> npt.NDArray[np.bool_]: + """ + Offset the masks in an array by the specified (x, y) amount. + + Args: + masks: A 3D array of binary masks corresponding to the + predictions. Shape: `(N, H, W)`, where N is the number of predictions, and + H, W are the dimensions of each mask. + offset: An array of shape `(2,)` containing int values + `[dx, dy]`. Supports both positive and negative values for bidirectional + movement. + resolution_wh: The width and height of the desired mask + resolution. + + Returns: + Repositioned masks, optionally padded to the specified shape. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> mask = np.array([[[False, False, False, False], + ... [False, True, True, False], + ... [False, True, True, False], + ... [False, False, False, False]]], dtype=bool) + >>> offset = np.array([1, 1]) + >>> sv.move_masks(mask, offset, resolution_wh=(4, 4)) + array([[[False, False, False, False], + [False, False, False, False], + [False, False, True, True], + [False, False, True, True]]]) + >>> offset = np.array([-2, 2]) + >>> sv.move_masks(mask, offset, resolution_wh=(4, 4)) + array([[[False, False, False, False], + [False, False, False, False], + [False, False, False, False], + [ True, False, False, False]]]) + + ``` + """ + mask_array = np.full((masks.shape[0], resolution_wh[1], resolution_wh[0]), False) + + if offset[0] < 0: + source_x_start = -offset[0] + source_x_end = min(masks.shape[2], resolution_wh[0] - offset[0]) + destination_x_start = 0 + destination_x_end = min(resolution_wh[0], masks.shape[2] + offset[0]) + else: + source_x_start = 0 + source_x_end = min(masks.shape[2], resolution_wh[0] - offset[0]) + destination_x_start = offset[0] + destination_x_end = offset[0] + source_x_end - source_x_start + + if offset[1] < 0: + source_y_start = -offset[1] + source_y_end = min(masks.shape[1], resolution_wh[1] - offset[1]) + destination_y_start = 0 + destination_y_end = min(resolution_wh[1], masks.shape[1] + offset[1]) + else: + source_y_start = 0 + source_y_end = min(masks.shape[1], resolution_wh[1] - offset[1]) + destination_y_start = offset[1] + destination_y_end = offset[1] + source_y_end - source_y_start + + if source_x_end > source_x_start and source_y_end > source_y_start: + mask_array[ + :, + destination_y_start:destination_y_end, + destination_x_start:destination_x_end, + ] = masks[:, source_y_start:source_y_end, source_x_start:source_x_end] + + return mask_array + + +def calculate_masks_centroids( + masks: npt.NDArray[np.bool_] | CompactMask, +) -> npt.NDArray[np.int_]: + """ + Calculate the centroids of binary masks in a tensor. + + Args: + masks: A 3D NumPy array of shape (num_masks, height, width). + Each 2D array in the tensor represents a binary mask. + Also accepts a :class:`~supervision.detection.compact_mask.CompactMask`. + + Returns: + A 2D NumPy array of shape (num_masks, 2), where each row contains the x and y + coordinates (in that order) of the centroid of the corresponding mask. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> masks = np.zeros((1, 10, 10), dtype=bool) + >>> masks[0, 2:6, 2:6] = True + >>> sv.calculate_masks_centroids(masks) + array([[4, 4]]) + + ``` + """ + if isinstance(masks, CompactMask): + # Compute centroids per-crop to avoid materialising the full (N, H, W) array. + n = len(masks) + if n == 0: + return cast(npt.NDArray[np.int_], np.empty((0, 2), dtype=int)) + + centroids: npt.NDArray[np.float64] = np.zeros((n, 2), dtype=np.float64) + for i in range(n): + crop = masks.crop(i) + crop_h, crop_w = crop.shape + x1 = int(masks.offsets[i, 0]) + y1 = int(masks.offsets[i, 1]) + total = int(crop.sum()) + if total == 0: + centroids[i] = [0.0, 0.0] + continue + # Match the +0.5 offset used by the dense implementation. + crop_rows, crop_cols = np.indices((crop_h, crop_w)) + cx = float(np.sum((crop_cols + 0.5)[crop])) / total + x1 + cy = float(np.sum((crop_rows + 0.5)[crop])) / total + y1 + centroids[i] = [cx, cy] + + return cast(npt.NDArray[np.int_], centroids.astype(int)) + + _num_masks, height, width = masks.shape + total_pixels: npt.NDArray[np.int64] = count_mask_pixels(masks) + + # offset for 1-based indexing + vertical_indices, horizontal_indices = np.indices((height, width)) + 0.5 + # avoid division by zero for empty masks + total_pixels[total_pixels == 0] = 1 + + def sum_over_mask( + indices: npt.NDArray[np.floating], axis: tuple[list[int], list[int]] + ) -> npt.NDArray[np.floating]: + return cast(npt.NDArray[np.floating], np.tensordot(masks, indices, axes=axis)) + + aggregation_axis: tuple[list[int], list[int]] = ([1, 2], [0, 1]) + centroid_x = sum_over_mask(horizontal_indices, aggregation_axis) / total_pixels + centroid_y = sum_over_mask(vertical_indices, aggregation_axis) / total_pixels + + return cast( + npt.NDArray[np.int_], np.column_stack((centroid_x, centroid_y)).astype(int) + ) + + +def contains_holes(mask: npt.NDArray[np.bool_]) -> bool: + """ + Checks if the binary mask contains holes (background pixels fully enclosed by + foreground pixels). + + Args: + mask: 2D binary mask where `True` indicates foreground + object and `False` indicates background. + + Returns: + True if holes are detected, False otherwise. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> mask = np.array([ + ... [0, 0, 0, 0, 0], + ... [0, 1, 1, 1, 0], + ... [0, 1, 0, 1, 0], + ... [0, 1, 1, 1, 0], + ... [0, 0, 0, 0, 0] + ... ]).astype(bool) + >>> sv.contains_holes(mask=mask) + True + >>> mask = np.array([ + ... [0, 0, 0, 0, 0], + ... [0, 1, 1, 1, 0], + ... [0, 1, 1, 1, 0], + ... [0, 1, 1, 1, 0], + ... [0, 0, 0, 0, 0] + ... ]).astype(bool) + >>> sv.contains_holes(mask=mask) + False + + ``` + + ![contains_holes](https://media.roboflow.com/supervision-docs/contains-holes.png){ align=center width="800" } + """ # noqa E501 // docs + return _contains_holes(mask) + + +def contains_multiple_segments( + mask: npt.NDArray[np.bool_], connectivity: int = 4 +) -> bool: + """ + Checks if the binary mask contains multiple unconnected foreground segments. + + Args: + mask: 2D binary mask where `True` indicates foreground + object and `False` indicates background. + connectivity: Default: 4 is 4-way connectivity, which means that + foreground pixels are the part of the same segment/component + if their edges touch. + Alternatively: 8 for 8-way connectivity, when foreground pixels are + connected by their edges or corners touch. + + Returns: + True when the mask contains multiple not connected components, False otherwise. + + Raises: + ValueError: If connectivity(int) parameter value is not 4 or 8. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> mask = np.array([ + ... [0, 0, 0, 0, 0, 0], + ... [0, 1, 1, 0, 1, 1], + ... [0, 1, 1, 0, 1, 1], + ... [0, 0, 0, 0, 0, 0], + ... [0, 1, 1, 1, 0, 0], + ... [0, 1, 1, 1, 0, 0] + ... ]).astype(bool) + >>> sv.contains_multiple_segments(mask=mask, connectivity=4) + True + >>> mask = np.array([ + ... [0, 0, 0, 0, 0, 0], + ... [0, 1, 1, 1, 1, 1], + ... [0, 1, 1, 1, 1, 1], + ... [0, 1, 1, 1, 1, 1], + ... [0, 1, 1, 1, 1, 1], + ... [0, 0, 0, 0, 0, 0] + ... ]).astype(bool) + >>> sv.contains_multiple_segments(mask=mask, connectivity=4) + False + + ``` + + ![contains_multiple_segments](https://media.roboflow.com/supervision-docs/contains-multiple-segments.png){ align=center width="800" } + """ # noqa E501 // docs + if connectivity != 4 and connectivity != 8: + raise ValueError( + "Incorrect connectivity value. Possible connectivity values: 4 or 8." + ) + mask_uint8 = mask.astype(np.uint8) + labels = np.zeros_like(mask_uint8, dtype=np.int32) + number_of_labels, _ = cv2.connectedComponents( + mask_uint8, labels, connectivity=connectivity + ) + return bool(number_of_labels > 2) + + +def resize_masks( + masks: npt.NDArray[np.bool_], max_dimension: int = 640 +) -> npt.NDArray[np.bool_]: + """ + Resize all masks in the array to have a maximum dimension of max_dimension, + maintaining aspect ratio. + + Args: + masks: 3D array of binary masks with shape (N, H, W). + max_dimension: The maximum dimension for the resized masks. + + Returns: + Array of resized masks. + """ + max_height: int = masks.shape[1] + max_width: int = masks.shape[2] + scale = min(1.0, max_dimension / max_height, max_dimension / max_width) + if scale == 1.0: + return masks + + new_height = int(scale * max_height) + new_width = int(scale * max_width) + + x = np.linspace(0, max_width - 1, new_width).astype(int) + y = np.linspace(0, max_height - 1, new_height).astype(int) + xv, yv = np.meshgrid(x, y) + + resized_masks = masks[:, yv, xv] + + return resized_masks.reshape(masks.shape[0], new_height, new_width) + + +def _chamfer_distances(main_mask: npt.NDArray[np.bool_]) -> npt.NDArray[np.int64]: + """Return OpenCV 3x3 L2 chamfer distances as fixed-point integers.""" + height, width = main_mask.shape + horizontal_vertical = 62587 + diagonal = 89738 + infinity = np.iinfo(np.int64).max // 4 + distances = np.where(main_mask, 0, infinity).astype(np.int64) + horizontal_costs = np.arange(width, dtype=np.int64) * horizontal_vertical + + for row in range(height): + current = distances[row] + if row: + previous = distances[row - 1] + upper_left = np.full(width, infinity, dtype=np.int64) + upper_right = np.full(width, infinity, dtype=np.int64) + upper_left[1:] = previous[:-1] + diagonal + upper_right[:-1] = previous[1:] + diagonal + current = np.minimum.reduce( + (current, previous + horizontal_vertical, upper_left, upper_right) + ) + distances[row] = ( + np.minimum.accumulate(current - horizontal_costs) + horizontal_costs + ) + + for row in range(height - 1, -1, -1): + current = distances[row] + if row + 1 < height: + following = distances[row + 1] + lower_left = np.full(width, infinity, dtype=np.int64) + lower_right = np.full(width, infinity, dtype=np.int64) + lower_left[1:] = following[:-1] + diagonal + lower_right[:-1] = following[1:] + diagonal + current = np.minimum.reduce( + (current, following + horizontal_vertical, lower_left, lower_right) + ) + reversed_current = current[::-1] + distances[row] = ( + np.minimum.accumulate(reversed_current - horizontal_costs) + + horizontal_costs + )[::-1] + + return distances + + +def filter_segments_by_distance( + mask: npt.NDArray[np.bool_], + absolute_distance: float | None = 100.0, + relative_distance: float | None = None, + connectivity: int = 8, + mode: Literal["edge", "centroid"] = "edge", +) -> npt.NDArray[np.bool_]: + """ + Keep the largest connected component and any other components within a distance + threshold. + + Distance can be absolute in pixels or relative to the image diagonal. + + Args: + mask: Boolean mask HxW. + absolute_distance: Max allowed distance in pixels to the main component. + Ignored if `relative_distance` is provided. + relative_distance: Fraction of the diagonal. If set, threshold = fraction * sqrt(H^2 + W^2). + connectivity: Defines which neighboring pixels are considered connected. + - 4-connectedness: Only orthogonal neighbors. + ``` + [ ][X][ ] + [X][O][X] + [ ][X][ ] + ``` + - 8-connectedness: Includes diagonal neighbors. + ``` + [X][X][X] + [X][O][X] + [X][X][X] + ``` + Default is 8. + mode: Defines how distance between components is measured. + - "edge": Uses distance between nearest edges (via distance transform). + - "centroid": Uses distance between component centroids. + + Returns: + Boolean mask after filtering. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> mask = np.array([ + ... [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ... [0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0], + ... [0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0], + ... [0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0], + ... [0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0], + ... [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ... [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ... [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ... [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0], + ... [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0], + ... [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ... [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ... ], dtype=bool) + >>> sv.filter_segments_by_distance( + ... mask, + ... absolute_distance=3, + ... mode="edge", + ... connectivity=8 + ... ).astype(int) + array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]) + + ``` + + The nearby 2x2 block at columns 6-7 is kept because its edge distance + is within 3 pixels. The distant block at columns 9-10 is removed. + """ # noqa E501 // docs + if mask.dtype != bool: + raise TypeError("mask must be boolean") + + height, width = mask.shape + if not np.any(mask): + return cast(npt.NDArray[np.bool_], mask.copy()) + + image = cast(npt.NDArray[np.uint8], mask.astype(np.uint8)) + components = cv2.connectedComponentsWithStats(image, connectivity=connectivity) + num_labels = int(components[0]) + labels = cast(npt.NDArray[np.int32], components[1]) + stats = cast(npt.NDArray[np.int32], components[2]) + centroids = cast(npt.NDArray[np.float64], components[3]) + + if num_labels <= 1: + return cast(npt.NDArray[np.bool_], mask.copy()) + + areas = stats[1:, cv2.CC_STAT_AREA] + max_area = int(areas.max()) + candidates = 1 + np.flatnonzero(areas == max_area) + # Use coordinates for equal-area ties so native and fallback labels agree. + main_label = min( + (int(label) for label in candidates), + key=lambda label: (int(stats[label, 0]), int(stats[label, 1]), label), + ) + + if relative_distance is not None: + diagonal = float(np.hypot(height, width)) + threshold = float(relative_distance) * diagonal + elif absolute_distance is not None: + threshold = float(absolute_distance) + else: + raise ValueError("Either absolute_distance or relative_distance must be set.") + + keep_labels: npt.NDArray[np.bool_] = np.zeros(num_labels, dtype=bool) + keep_labels[main_label] = True + + if mode == "centroid": + differences = centroids[1:] - centroids[main_label] + distances = np.sqrt(np.sum(differences**2, axis=1)) + nearby = 1 + np.where(distances <= threshold)[0] + keep_labels[nearby] = True + elif mode == "edge": + main_mask = labels == main_label + if np.isnan(threshold) or threshold < 0: + nearby_main = np.zeros_like(main_mask) + elif np.isposinf(threshold): + nearby_main = np.ones_like(main_mask) + else: + fixed_distances = _chamfer_distances(main_mask) + distances = fixed_distances.astype(np.float32) / 65536 + nearby_main = distances <= threshold + for label in range(1, num_labels): + if label == main_label: + continue + component = labels == label + if not np.any(component): + continue + if np.any(nearby_main & component): + keep_labels[label] = True + else: + raise ValueError("mode must be 'edge' or 'centroid'") + + return keep_labels[labels] + + +def mask_to_roi(mask: npt.NDArray[np.bool_]) -> tuple[int, int, int, int] | None: + """Return exclusive ``(x1, y1, x2, y2)`` bounds for true mask pixels. + + Use this helper when you need NumPy slice semantics. Unlike + :func:`~supervision.detection.utils.converters.mask_to_xyxy`, this + function uses exclusive upper bounds (``+1``) and returns ``None`` for + empty masks instead of zeros. The inclusive ``mask_to_xyxy`` convention + stays in place for compatibility with CompactMask and box-based adapters. + + Args: + mask: 2D boolean array of shape ``(H, W)``. + + Returns: + Exclusive ``(x1, y1, x2, y2)`` bounds, or ``None`` when the mask + has no true pixels. + + Examples: + ```pycon + >>> import numpy as np + >>> from supervision.detection.utils.masks import mask_to_roi + >>> mask = np.zeros((10, 10), dtype=bool) + >>> mask[2:5, 3:6] = True + >>> mask_to_roi(mask) + (3, 2, 6, 5) + + ``` + """ + rows = np.flatnonzero(np.any(mask, axis=1)) + if len(rows) == 0: + return None + cols = np.flatnonzero(np.any(mask, axis=0)) + return int(cols[0]), int(rows[0]), int(cols[-1]) + 1, int(rows[-1]) + 1 + + +_mask_to_roi = mask_to_roi + + +def _compact_masks_to_roi( + masks: CompactMask, + image_shape: tuple[int, int], +) -> tuple[int, int, int, int] | None: + """Return exclusive bounding-box union for compact masks. + + Uses crop metadata (offsets + shapes) — no RLE decode required. + + Args: + masks: Compact mask collection. + image_shape: Image dimensions as ``(height, width)``. + + Returns: + Exclusive ``(x1, y1, x2, y2)`` bounds, or ``None`` when empty. + """ + if len(masks) == 0: + return None + image_h, image_w = image_shape + bboxes = masks.bbox_xyxy # shape (N, 4), inclusive int32 + x_min = int(bboxes[:, 0].min()) + y_min = int(bboxes[:, 1].min()) + x_max = int(bboxes[:, 2].max()) + 1 # convert inclusive to exclusive + y_max = int(bboxes[:, 3].max()) + 1 + return ( + max(0, x_min), + max(0, y_min), + min(image_w, x_max), + min(image_h, y_max), + ) + + +def _masks_to_roi( + masks: CompactMask | npt.NDArray[Any], + image_shape: tuple[int, int], + xyxy: npt.NDArray[np.number] | None = None, +) -> tuple[int, int, int, int] | None: + """Return exclusive true-pixel bounds for dense or compact masks. + + Args: + masks: Dense boolean mask array of shape ``(N, H, W)`` or ``(H, W)``, + or a :class:`~supervision.detection.compact_mask.CompactMask`. + image_shape: Image dimensions as ``(height, width)``. + xyxy: Optional detection boxes of shape ``(N, 4)`` in + ``[x1, y1, x2, y2]`` format. When provided, the dense path + first checks whether all true pixels fall within the box union; + if so the box bounds are returned without a full pixel scan. + + Returns: + Exclusive ``(x1, y1, x2, y2)`` bounds, or ``None`` when no true + pixels exist. + """ + if isinstance(masks, CompactMask): + return _compact_masks_to_roi(masks=masks, image_shape=image_shape) + mask_array = np.asarray(masks, dtype=bool) + if mask_array.size == 0 or not mask_array.any(): + return None + # Fast path: union of detection boxes (O(N)) avoids a full N·H·W pixel scan + # when boxes are mask-derived. Guard it with an `any()` check over the ROI so + # loose boxes cannot clip true pixels that lie outside the box union. + if xyxy is not None and len(xyxy) > 0: + image_h, image_w = image_shape + box_roi = ( + max(0, int(np.floor(xyxy[:, 0].min()))), + max(0, int(np.floor(xyxy[:, 1].min()))), + min(image_w, int(np.floor(xyxy[:, 2].max())) + 1), + min(image_h, int(np.floor(xyxy[:, 3].max())) + 1), + ) + x1, y1, x2, y2 = box_roi + if x1 < x2 and y1 < y2: + union = mask_array if mask_array.ndim == 2 else np.any(mask_array, axis=0) + # Return box bounds only when all true pixels fall within the box. + # Slice-based checks avoid allocating a full-frame copy. + if ( + union[y1:y2, x1:x2].any() + and not union[:y1].any() + and not union[y2:].any() + and not union[y1:y2, :x1].any() + and not union[y1:y2, x2:].any() + ): + return box_roi + return mask_to_roi(union) + if mask_array.ndim == 2: + union = mask_array + else: + union = np.any(mask_array, axis=0) + return mask_to_roi(union) diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/utils/polygons.py b/.venv/lib/python3.12/site-packages/supervision/detection/utils/polygons.py new file mode 100644 index 0000000000000000000000000000000000000000..9810d0fb3fec7c1e11d3dfca44d91d04217e8ef4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/detection/utils/polygons.py @@ -0,0 +1,167 @@ +import numpy as np +import numpy.typing as npt + +from supervision import _cv2 as cv2 + + +def _to_local_cv2_polygon( + polygon: npt.NDArray[np.number], +) -> tuple[npt.NDArray[np.float32], npt.NDArray[np.number]]: + """Translate a polygon to a local float32 coordinate system for OpenCV. + + Integer subtraction uses object arithmetic so unsigned and signed inputs do + not wrap before conversion. Translating first preserves representable local + geometry when absolute coordinates exceed float32 precision. + """ + origin = polygon.min(axis=0) + if np.issubdtype(polygon.dtype, np.integer): + local_polygon = np.asarray( + polygon.astype(object) - origin.astype(object), dtype=np.float32 + ) + else: + local_polygon = ( + polygon.astype(np.float64, copy=False) + - origin.astype(np.float64, copy=False) + ).astype(np.float32) + return local_polygon, origin + + +def filter_polygons_by_area( + polygons: list[npt.NDArray[np.number]], + min_area: float | None = None, + max_area: float | None = None, +) -> list[npt.NDArray[np.number]]: + """ + Filters a list of polygons based on their area. + + Args: + polygons: A list of polygons, where each polygon is + represented by a NumPy array of shape `(N, 2)`, + containing the `x`, `y` coordinates of the points. + min_area: The minimum area threshold. + Only polygons with an area greater than or equal to this value + will be included in the output. If set to None, + no minimum area constraint will be applied. + max_area: The maximum area threshold. + Only polygons with an area less than or equal to this value + will be included in the output. If set to None, + no maximum area constraint will be applied. + + Returns: + A new list of polygons containing only those with + areas within the specified thresholds. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> small = np.array([[0, 0], [2, 0], [2, 2], [0, 2]]) + >>> big = np.array([[0, 0], [10, 0], [10, 10], [0, 10]]) + >>> sv.filter_polygons_by_area([small, big], min_area=50) + [array([[ 0, 0], + [10, 0], + [10, 10], + [ 0, 10]])] + + ``` + """ + if min_area is None and max_area is None: + return polygons + areas = [cv2.contourArea(_to_local_cv2_polygon(polygon)[0]) for polygon in polygons] + return [ + polygon + for polygon, area in zip(polygons, areas) + if (min_area is None or area >= min_area) + and (max_area is None or area <= max_area) + ] + + +def approximate_polygon( + polygon: npt.NDArray[np.number], percentage: float, epsilon_step: float = 0.05 +) -> npt.NDArray[np.number]: + """ + Approximates a given polygon by reducing a certain percentage of points. + + This function uses the Ramer-Douglas-Peucker algorithm to simplify the input + polygon by reducing the number of points while preserving the general shape. + + Args: + polygon: A 2D NumPy array of shape `(N, 2)` containing + the `x`, `y` coordinates of the input polygon's points. + percentage: The percentage of points to be removed from the + input polygon, in the range `[0, 1)`. + epsilon_step: Approximation accuracy step, must be positive. + Epsilon is the maximum distance between the original curve + and its approximation. + + Returns: + A new 2D NumPy array of shape `(M, 2)` containing the `x`, `y` + coordinates of the approximated polygon's points. `M` is at most + `floor(N * (1 - percentage))` (minimum 3). Because epsilon + advances in discrete `epsilon_step` increments, `M` may be + noticeably smaller than the budget when a single step crosses + the target band. At least 3 points are always kept; when further + simplification would collapse the polygon below 3 points the last + valid approximation is returned and `M` may exceed the budget. + + Raises: + ValueError: If `percentage` is outside the range `[0, 1)`. + ValueError: If `epsilon_step` is not positive. + + Examples: + Reduce a polygon to at most half its original point count: + + ```pycon + >>> import numpy as np + >>> polygon = np.array([[0, 0], [10, 0], [10, 10], [0, 10], + ... [5, 10], [5, 5], [3, 7], [1, 9]]) + >>> result = approximate_polygon(polygon, percentage=0.5) + >>> result.shape[1] + 2 + >>> len(result) <= max(int(len(polygon) * 0.5), 3) + True + + Polygon already at or below target — returned unchanged: + + >>> tiny = np.array([[0, 0], [5, 0], [2, 4]]) + >>> approximate_polygon(tiny, percentage=0.5) is tiny + True + + ``` + """ + + if percentage < 0 or percentage >= 1: + raise ValueError("Percentage must be in the range [0, 1).") + if epsilon_step <= 0: + raise ValueError("epsilon_step must be positive.") + + target_points = max(int(len(polygon) * (1 - percentage)), 3) + + if len(polygon) <= target_points: + return polygon + + original_dtype = polygon.dtype + cv_polygon, origin = _to_local_cv2_polygon(polygon) + + epsilon: float = 0 + approximated_points = polygon + while len(approximated_points) > target_points: + epsilon += epsilon_step + candidate = np.squeeze( + cv2.approxPolyDP(cv_polygon, epsilon, closed=True), axis=1 + ) + # Stop before the approximation collapses below a valid polygon; keep the + # last result with at least three points. + if len(candidate) < 3: + break + if np.issubdtype(original_dtype, np.integer): + approximated_points = np.asarray( + candidate.astype(original_dtype).astype(object) + origin.astype(object), + dtype=original_dtype, + ) + else: + approximated_points = ( + candidate.astype(np.float64) + origin.astype(np.float64) + ).astype(original_dtype) + + return approximated_points diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/utils/vlms.py b/.venv/lib/python3.12/site-packages/supervision/detection/utils/vlms.py new file mode 100644 index 0000000000000000000000000000000000000000..24a784e5442ed70c6d714d5a759cb4eccf80ef69 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/detection/utils/vlms.py @@ -0,0 +1,97 @@ +def edit_distance(string_1: str, string_2: str, case_sensitive: bool = True) -> int: + """ + Calculates the minimum number of single-character edits required + to transform one string into another. Allowed operations are insertion, + deletion, and substitution. + + Args: + string_1: The source string to be transformed. + string_2: The target string to transform into. + case_sensitive: Whether comparison should be case-sensitive. + Defaults to True. + + Returns: + The minimum number of edits required to convert `string_1` + into `string_2`. + + Examples: + ```pycon + >>> import supervision as sv + >>> sv.edit_distance("hello", "hello") + 0 + >>> sv.edit_distance("Test", "test", case_sensitive=True) + 1 + >>> sv.edit_distance("abc", "xyz") + 3 + >>> sv.edit_distance("hello", "") + 5 + >>> sv.edit_distance("", "") + 0 + >>> sv.edit_distance("hello world", "helloworld") + 1 + + ``` + """ + if not case_sensitive: + string_1 = string_1.lower() + string_2 = string_2.lower() + + if len(string_1) < len(string_2): + string_1, string_2 = string_2, string_1 + + prev_row = list(range(len(string_2) + 1)) + curr_row = [0] * (len(string_2) + 1) + + for i in range(1, len(string_1) + 1): + curr_row[0] = i + for j in range(1, len(string_2) + 1): + if string_1[i - 1] == string_2[j - 1]: + substitution_cost = 0 + else: + substitution_cost = 1 + curr_row[j] = min( + prev_row[j] + 1, + curr_row[j - 1] + 1, + prev_row[j - 1] + substitution_cost, + ) + prev_row, curr_row = curr_row, prev_row + + return prev_row[len(string_2)] + + +def fuzzy_match_index( + candidates: list[str], + query: str, + threshold: int, + case_sensitive: bool = True, +) -> int | None: + """ + Searches for the first string in `candidates` whose edit distance + to `query` is less than or equal to `threshold`. + + Args: + candidates: List of strings to search. + query: String to compare against the candidates. + threshold: Maximum allowed edit distance for a match. + case_sensitive: Whether matching should be case-sensitive. + + Returns: + Index of the first matching string in candidates, + or None if no match is found. + + Examples: + ```pycon + >>> from supervision.detection.utils.vlms import fuzzy_match_index + >>> fuzzy_match_index(["cat", "dog", "rat"], "dat", threshold=1) + 0 + >>> fuzzy_match_index(["alpha", "beta", "gamma"], "bata", threshold=1) + 1 + >>> fuzzy_match_index(["one", "two", "three"], "xyz", threshold=2) is None + True + + ``` + """ + for idx, candidate in enumerate(candidates): + if edit_distance(candidate, query, case_sensitive=case_sensitive) <= threshold: + return idx + return None diff --git a/.venv/lib/python3.12/site-packages/supervision/detection/vlm.py b/.venv/lib/python3.12/site-packages/supervision/detection/vlm.py new file mode 100644 index 0000000000000000000000000000000000000000..90c135eeba479cd5ce3bcabd13eef46533d7cf0d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/detection/vlm.py @@ -0,0 +1,999 @@ +from __future__ import annotations + +import ast +import base64 +import io +import json +import re +from enum import Enum +from typing import Any, cast + +import numpy as np +import numpy.typing as npt +from deprecate import deprecated, void +from PIL import Image + +from supervision.detection.utils.boxes import _sort_box_corners, denormalize_boxes +from supervision.detection.utils.converters import polygon_to_mask, polygon_to_xyxy +from supervision.utils.internal import warn_deprecated +from supervision.validators import _validate_resolution + + +class LMM(Enum): + """ + Enum specifying supported Large Multimodal Models (LMMs). + + !!! deprecated "Deprecated" + + `LMM` is deprecated and will be removed in `supervision-0.31.0`. + Use `VLM` instead. + + Attributes: + PALIGEMMA: Google's PaliGemma vision-language model. + FLORENCE_2: Microsoft's Florence-2 vision-language model. + QWEN_2_5_VL: Qwen2.5-VL open vision-language model from Alibaba.\ + QWEN_3_VL: Qwen3-VL open vision-language model from Alibaba. + GOOGLE_GEMINI_2_0: Google Gemini 2.0 vision-language model. + GOOGLE_GEMINI_2_5: Google Gemini 2.5 vision-language model. + MOONDREAM: The Moondream vision-language model. + """ + + PALIGEMMA = "paligemma" + FLORENCE_2 = "florence_2" + QWEN_2_5_VL = "qwen_2_5_vl" + QWEN_3_VL = "qwen_3_vl" + DEEPSEEK_VL_2 = "deepseek_vl_2" + GOOGLE_GEMINI_2_0 = "gemini_2_0" + GOOGLE_GEMINI_2_5 = "gemini_2_5" + MOONDREAM = "moondream" + + @classmethod + def list(cls) -> list[str]: + return [c.value for c in cls] + + @classmethod + def from_value(cls, value: LMM | str) -> LMM: + warn_deprecated( + "`LMM` is deprecated since `supervision-0.27.0` and will be removed in " + "`supervision-0.31.0`. Use `VLM` instead." + ) + if isinstance(value, cls): + return value + if isinstance(value, str): + value = value.lower() + try: + return cls(value) + except ValueError: + raise ValueError(f"Invalid value: {value}. Must be one of {cls.list()}") + raise ValueError( + f"Invalid value type: {type(value)}. Must be an instance of " + f"{cls.__name__} or str." + ) + + +class VLM(Enum): + """ + Enum specifying supported Vision-Language Models (VLMs). + + Attributes: + PALIGEMMA: Google's PaliGemma vision-language model. + FLORENCE_2: Microsoft's Florence-2 vision-language model. + QWEN_2_5_VL: Qwen2.5-VL open vision-language model from Alibaba. + QWEN_3_VL: Qwen3-VL open vision-language model from Alibaba. + GOOGLE_GEMINI_2_0: Google Gemini 2.0 vision-language model. + GOOGLE_GEMINI_2_5: Google Gemini 2.5 vision-language model. + GOOGLE_GEMINI_3_5: Google Gemini 3.5 vision-language model. + MOONDREAM: The Moondream vision-language model. + """ + + PALIGEMMA = "paligemma" + FLORENCE_2 = "florence_2" + QWEN_2_5_VL = "qwen_2_5_vl" + QWEN_3_VL = "qwen_3_vl" + DEEPSEEK_VL_2 = "deepseek_vl_2" + GOOGLE_GEMINI_2_0 = "gemini_2_0" + GOOGLE_GEMINI_2_5 = "gemini_2_5" + GOOGLE_GEMINI_3_5 = "gemini_3_5" + MOONDREAM = "moondream" + + @classmethod + def list(cls) -> list[str]: + return [c.value for c in cls] + + @classmethod + def from_value(cls, value: VLM | str) -> VLM: + if isinstance(value, cls): + return value + if isinstance(value, str): + value = value.lower() + try: + return cls(value) + except ValueError: + raise ValueError(f"Invalid value: {value}. Must be one of {cls.list()}") + raise ValueError( + f"Invalid value type: {type(value)}. Must be an instance of " + f"{cls.__name__} or str." + ) + + +RESULT_TYPES: dict[VLM, type] = { + VLM.PALIGEMMA: str, + VLM.FLORENCE_2: dict, + VLM.QWEN_2_5_VL: str, + VLM.QWEN_3_VL: str, + VLM.DEEPSEEK_VL_2: str, + VLM.GOOGLE_GEMINI_2_0: str, + VLM.GOOGLE_GEMINI_2_5: str, + VLM.GOOGLE_GEMINI_3_5: str, + VLM.MOONDREAM: dict, +} + +REQUIRED_ARGUMENTS: dict[VLM, list[str]] = { + VLM.PALIGEMMA: ["resolution_wh"], + VLM.FLORENCE_2: ["resolution_wh"], + VLM.QWEN_2_5_VL: ["input_wh", "resolution_wh"], + VLM.QWEN_3_VL: ["resolution_wh"], + VLM.DEEPSEEK_VL_2: ["resolution_wh"], + VLM.GOOGLE_GEMINI_2_0: ["resolution_wh"], + VLM.GOOGLE_GEMINI_2_5: ["resolution_wh"], + VLM.GOOGLE_GEMINI_3_5: ["resolution_wh"], + VLM.MOONDREAM: ["resolution_wh"], +} + +ALLOWED_ARGUMENTS: dict[VLM, list[str]] = { + VLM.PALIGEMMA: ["resolution_wh", "classes"], + VLM.FLORENCE_2: ["resolution_wh"], + VLM.QWEN_2_5_VL: ["input_wh", "resolution_wh", "classes"], + VLM.QWEN_3_VL: ["resolution_wh", "classes"], + VLM.DEEPSEEK_VL_2: ["resolution_wh", "classes"], + VLM.GOOGLE_GEMINI_2_0: ["resolution_wh", "classes"], + VLM.GOOGLE_GEMINI_2_5: ["resolution_wh", "classes"], + VLM.GOOGLE_GEMINI_3_5: ["resolution_wh", "classes"], + VLM.MOONDREAM: ["resolution_wh"], +} + +SUPPORTED_TASKS_FLORENCE_2 = [ + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", +] + + +def _validate_vlm_parameters( + vlm: VLM | str, result: Any, kwargs: dict[str, Any] +) -> VLM: + """ + Validates the parameters and result type for a given Vision-Language Model (VLM). + + Args: + vlm: The VLM enum or string specifying the model. + result: The result object to validate (type depends on VLM). + kwargs: Dictionary of arguments to validate against required/allowed lists. + + Returns: + The validated VLM enum value. + + Raises: + ValueError: If the VLM, result type, or arguments are invalid. + """ + if isinstance(vlm, str): + try: + vlm = VLM(vlm.lower()) + except ValueError: + raise ValueError( + f"Invalid vlm value: {vlm}. Must be one of {[e.value for e in VLM]}" + ) + + if not isinstance(result, RESULT_TYPES[vlm]): + raise ValueError( + f"Invalid VLM result type: {type(result)}. Must be {RESULT_TYPES[vlm]}" + ) + + required_args = REQUIRED_ARGUMENTS.get(vlm, []) + for arg in required_args: + if arg not in kwargs: + raise ValueError(f"Missing required argument: {arg}") + + allowed_args = ALLOWED_ARGUMENTS.get(vlm, []) + for arg in kwargs: + if arg not in allowed_args: + raise ValueError(f"Argument {arg} is not allowed for {vlm.name}") + + return vlm + + +@deprecated( # type: ignore[untyped-decorator] + target=_validate_vlm_parameters, + deprecated_in="0.29.0", + remove_in="0.32.0", +) +def validate_vlm_parameters(vlm: VLM | str, result: Any, kwargs: dict[str, Any]) -> VLM: + return void(vlm, result, kwargs) # type: ignore[no-any-return] + + +def from_paligemma( + result: str, resolution_wh: tuple[int, int], classes: list[str] | None = None +) -> tuple[npt.NDArray[Any], npt.NDArray[Any] | None, npt.NDArray[Any]]: + """ + Parse bounding boxes from paligemma-formatted text, scale them to the specified + resolution, and optionally filter by classes. + + Args: + result: String containing paligemma-formatted locations and labels. + resolution_wh: tuple (width, height) to which we scale the box coordinates. + classes: Optional list of valid class names. If provided, boxes and labels not + in this list are filtered out. + + Returns: + A tuple of `(xyxy, class_id, class_name)` where `xyxy` is an array of + shape `(n, 4)` in format `[x1, y1, x2, y2]`, `class_id` is an + optional array of shape `(n,)` with class indices, and `class_name` + is an array of shape `(n,)` with class labels. + """ + + w, h = _validate_resolution(resolution_wh) + + pattern = re.compile( + r"(?) ([\w\s\-]+)" + ) + matches = pattern.findall(result) + matches_arr: npt.NDArray[Any] = np.array(matches) if matches else np.empty((0, 5)) + + if matches_arr.shape[0] == 0: + return np.empty((0, 4)), np.empty((0,), dtype=int), np.empty(0, dtype=str) + + xyxy_arr = np.array(matches_arr[:, [1, 0, 3, 2]], dtype=float) + xyxy_arr = xyxy_arr.astype(int) / 1024 * np.array([w, h, w, h]) + class_name = np.char.strip(matches_arr[:, 4].astype(str)) + class_id: npt.NDArray[Any] | None = None + + if classes is not None: + mask = np.array([name in classes for name in class_name], dtype=bool) + xyxy_arr = xyxy_arr[mask] + class_name = class_name[mask] + class_id = np.array([classes.index(name) for name in class_name]) + + return xyxy_arr, class_id, class_name + + +def recover_truncated_qwen_2_5_vl_response(text: str) -> Any | None: + """ + Attempt to recover and parse a truncated or malformed JSON snippet from Qwen-2.5-VL + output. + + This utility extracts a JSON-like portion from a string that may be truncated or + malformed, cleans trailing commas, and attempts to parse it into a Python object. + + Args: + text: Raw text containing the JSON snippet possibly truncated or + incomplete. + + Returns: + Parsed Python object (usually list) if recovery and parsing succeed; + otherwise `None`. + """ + try: + first_bracket = text.find("[") + if first_bracket == -1: + return None + snippet = text[first_bracket:] + + last_brace = snippet.rfind("}") + if last_brace == -1: + return None + + snippet = snippet[: last_brace + 1] + + prefix_end = snippet.find("[") + if prefix_end == -1: + return None + + prefix = snippet[: prefix_end + 1] + body = snippet[prefix_end + 1 :].rstrip() + + if body.endswith(","): + body = body[:-1].rstrip() + + repaired = prefix + body + "]" + + return json.loads(repaired) + except Exception: + return None + + +def from_qwen_2_5_vl( + result: str, + input_wh: tuple[int, int], + resolution_wh: tuple[int, int], + classes: list[str] | None = None, +) -> tuple[npt.NDArray[Any], npt.NDArray[Any] | None, npt.NDArray[Any]]: + """ + Parse and rescale bounding boxes and class labels from Qwen-2.5-VL JSON output. + + The JSON is expected to be enclosed in triple backticks with the format: + ```json + [ + {"bbox_2d": [x1, y1, x2, y2], "label": "some class name"}, + ... + ] + ``` + + Args: + result: String containing Qwen-2.5-VL JSON bounding box and label data. + input_wh: Width and height of the coordinate space where boxes + are normalized. + resolution_wh: Target width and height to scale bounding boxes. + classes: Optional list of valid class names to filter results. If provided, + only boxes with labels in this list are returned. + + Returns: + A tuple of `(xyxy, class_id, class_name)` where `xyxy` is an array of + shape `(N, 4)` in `(x_min, y_min, x_max, y_max)` format, `class_id` + is an optional array of shape `(N,)` with class indices, and + `class_name` is an array of shape `(N,)` with class names. + """ + + in_w, in_h = _validate_resolution(input_wh) + out_w, out_h = _validate_resolution(resolution_wh) + + text = result.strip() + text = re.sub(r"^```(json)?", "", text, flags=re.IGNORECASE).strip() + text = re.sub(r"```$", "", text).strip() + + start = text.find("[") + end = text.rfind("]") + if start != -1 and end != -1 and end > start: + text = text[start : end + 1].strip() + + try: + data = json.loads(text) + except json.JSONDecodeError: + repaired = recover_truncated_qwen_2_5_vl_response(text) + if repaired is not None: + data = repaired + else: + try: + data = ast.literal_eval(text) + except (ValueError, SyntaxError, TypeError): + return ( + np.empty((0, 4)), + np.empty((0,), dtype=int), + np.empty((0,), dtype=str), + ) + + if not isinstance(data, list): + return (np.empty((0, 4)), np.empty((0,), dtype=int), np.empty((0,), dtype=str)) + + boxes_list = [] + labels_list = [] + + for item in data: + if not isinstance(item, dict) or "bbox_2d" not in item or "label" not in item: + continue + boxes_list.append(item["bbox_2d"]) + labels_list.append(item["label"]) + + if not boxes_list: + return (np.empty((0, 4)), np.empty((0,), dtype=int), np.empty((0,), dtype=str)) + + xyxy = np.array(boxes_list, dtype=float) + class_name = np.array(labels_list, dtype=str) + + xyxy = xyxy / [in_w, in_h, in_w, in_h] + xyxy = xyxy * [out_w, out_h, out_w, out_h] + + class_id = None + + if classes is not None: + mask = np.array([label in classes for label in class_name], dtype=bool) + xyxy = xyxy[mask] + class_name = class_name[mask] + class_id = np.array([classes.index(label) for label in class_name], dtype=int) + + return xyxy, class_id, class_name + + +def from_qwen_3_vl( + result: str, + resolution_wh: tuple[int, int], + classes: list[str] | None = None, +) -> tuple[npt.NDArray[Any], npt.NDArray[Any] | None, npt.NDArray[Any]]: + """ + Parse and scale bounding boxes from Qwen-3-VL style JSON output. + + Args: + result: String containing the Qwen-3-VL JSON output. + resolution_wh: Target resolution `(width, height)` to scale bounding boxes. + classes: Optional list of valid classes to filter results. + + Returns: + A tuple of `(xyxy, class_id, class_name)` where `xyxy` is an array of + shape `(N, 4)` in `(x_min, y_min, x_max, y_max)` format scaled to + `resolution_wh`, `class_id` is an optional array of class indices, + and `class_name` is an array of class names. + """ + return from_qwen_2_5_vl( + result=result, + input_wh=(1000, 1000), + resolution_wh=resolution_wh, + classes=classes, + ) + + +def from_deepseek_vl_2( + result: str, resolution_wh: tuple[int, int], classes: list[str] | None = None +) -> tuple[npt.NDArray[Any], npt.NDArray[Any] | None, npt.NDArray[Any]]: + """ + Parse bounding boxes from deepseek-vl2-formatted text, scale them to the specified + resolution, and optionally filter by classes. + + The DeepSeek-VL2 output typically contains pairs of <|ref|> ... <|/ref|> labels + and <|det|> ... <|/det|> bounding box definitions. Each <|det|> section may + contain one or more bounding boxes in the form [[x1, y1, x2, y2], [x1, y1, x2, y2], ...] + (scaled to 0..999). For example: + + ``` + <|ref|>The giraffe at the back<|/ref|><|det|>[[580, 270, 999, 904]]<|/det|><|ref|>The giraffe at the front<|/ref|><|det|>[[26, 31, 632, 998]]<|/det|><|end▁of▁sentence|> + ``` + + Args: + result: String containing deepseek-vl2-formatted locations and labels. + resolution_wh: Tuple (width, height) to which we scale the box coordinates. + classes: Optional list of valid class names. If provided, boxes and labels not + in this list are filtered out. + + Returns: + A tuple of `(xyxy, class_id, class_name)` where `xyxy` is an array of + shape `(n, 4)` in format `[x1, y1, x2, y2]`, `class_id` is an + optional array of shape `(n,)` with class indices, and `class_name` + is an array of shape `(n,)` with class labels. When the input + contains no detections (or all are filtered by `classes`), returns + `(np.empty((0, 4)), np.empty(0), np.empty(0))`. + """ # noqa: E501 + + width, height = resolution_wh + label_segments = re.findall(r"<\|ref\|>(.*?)<\|/ref\|>", result, flags=re.S) + detection_segments = re.findall(r"<\|det\|>(.*?)<\|/det\|>", result, flags=re.S) + + if len(label_segments) != len(detection_segments): + raise ValueError( + f"Number of ref tags ({len(label_segments)}) " + f"and det tags ({len(detection_segments)}) in the result must be equal." + ) + + xyxy_list: list[list[float]] = [] + class_name_list: list[str] = [] + for label, detection_blob in zip(label_segments, detection_segments): + current_class_name = label.strip() + for box in re.findall(r"\[(.*?)\]", detection_blob): + x1, y1, x2, y2 = map(float, box.strip("[]").split(",")) + xyxy_list.append( + [ + (x1 / 999 * width), + (y1 / 999 * height), + (x2 / 999 * width), + (y2 / 999 * height), + ] + ) + class_name_list.append(current_class_name) + + xyxy = ( + np.array(xyxy_list, dtype=np.float32) + if xyxy_list + else np.empty((0, 4), dtype=np.float32) + ) + class_name = ( + np.array(class_name_list) if class_name_list else np.array([], dtype=object) + ) + + if classes is not None: + mask = np.array([name in classes for name in class_name], dtype=bool) + xyxy = xyxy[mask] + class_name = class_name[mask] + class_id = np.array([classes.index(name) for name in class_name]) + else: + unique_classes = sorted(list(set(class_name))) + class_to_id = {name: i for i, name in enumerate(unique_classes)} + class_id = np.array([class_to_id[name] for name in class_name]) + + return xyxy, class_id, class_name + + +def from_florence_2( + result: dict[str, Any], resolution_wh: tuple[int, int] +) -> tuple[ + npt.NDArray[Any], + npt.NDArray[Any] | None, + npt.NDArray[Any] | None, + npt.NDArray[Any] | None, +]: + """ + Parse results from the Florence 2 multi-model model. + https://huggingface.co/microsoft/Florence-2-large + + Args: + result: dict containing the model output + resolution_wh: (output_width, output_height) to which we rescale the boxes. + + Returns: + A tuple of `(xyxy, labels, masks, obb_boxes)` where `xyxy` is an array + of shape `(n, 4)` in format `[x1, y1, x2, y2]`, `labels` is an + optional array of shape `(n,)` with class labels, `masks` is an + optional array of shape `(n, h, w)` with segmentation masks, and + `obb_boxes` is an optional array of shape `(n, 4, 2)` with oriented + bounding boxes. + + Raises: + ValueError: If the top-level Florence 2 payload has multiple tasks or + if a task payload is malformed. + """ + if len(result) != 1: + raise ValueError(f"Expected result with a single element. Got: {result}") + task = next(iter(result.keys())) + if task not in SUPPORTED_TASKS_FLORENCE_2: + raise ValueError( + f"{task} not supported. Supported tasks are: {SUPPORTED_TASKS_FLORENCE_2}" + ) + result = result[task] + + if task in ["", "", ""]: + xyxy = np.array(result["bboxes"], dtype=np.float32) + labels = np.array(result["labels"]) + return xyxy, labels, None, None + + if task == "": + xyxy = np.array(result["bboxes"], dtype=np.float32) + # provides labels, but they are ["", "", "", ...] + return xyxy, None, None, None + + if task == "": + xyxyxyxy = np.array(result["quad_boxes"], dtype=np.float32) + xyxyxyxy = xyxyxyxy.reshape(-1, 4, 2) + xyxy = np.array([polygon_to_xyxy(polygon) for polygon in xyxyxyxy]) + labels = np.array(result["labels"]) + return xyxy, labels, None, xyxyxyxy + + if task in ["", ""]: + xyxy_list: list[npt.NDArray[Any]] = [] + masks_list: list[npt.NDArray[Any]] = [] + for polygons_of_same_class in result["polygons"]: + for polygon in polygons_of_same_class: + polygon = np.reshape(polygon, (-1, 2)).astype(np.int32) + mask = polygon_to_mask(polygon, resolution_wh).astype(bool) + masks_list.append(mask) + xyxy_box = polygon_to_xyxy(polygon) + xyxy_list.append(xyxy_box) + # per-class labels also provided, but they are ["", "", "", ...] + # when we figure out how to set class names, we can do + # zip(result["labels"], result["polygons"]) + xyxy = np.array(xyxy_list, dtype=np.float32) + masks = np.array(masks_list) + return xyxy, None, masks, None + + if task == "": + xyxy = np.array(result["bboxes"], dtype=np.float32) + labels = np.array(result["bboxes_labels"]) + # Also has "polygons" and "polygons_labels", but they don't seem to be used + return xyxy, labels, None, None + + if task in ["", ""]: + if not isinstance(result, str): + raise ValueError(f"Expected string as {task} result, got {type(result)}") + + if result == "No object detected.": + return np.empty((0, 4), dtype=np.float32), np.array([]), None, None + + pattern = re.compile(r"") + match = pattern.search(result) + if match is None: + raise ValueError( + f"Expected string to end in location tags, but got {result}" + ) + + w, h = _validate_resolution(resolution_wh) + xyxy = np.array([match.groups()], dtype=np.float32) + xyxy *= np.array([w, h, w, h]) / 1000 + result_string = result[: match.start()] + labels = np.array([result_string]) + return xyxy, labels, None, None + + raise RuntimeError(f"Unimplemented task: {task}") + + +def _recover_gemini_json_objects(text: str) -> list[Any]: + """ + Salvage individual JSON objects from a malformed Gemini JSON array. + + Scans for balanced `{...}` spans and parses each independently, keeping the + ones that decode into a `dict` and skipping the rest. This recovers the valid + entries from an array that a single `json.loads` would reject wholesale, such + as one whose objects contain a mid-array syntax error or a missing key. + + Args: + text: The (fence-stripped) response text that failed `json.loads`. + + Returns: + The list of successfully parsed objects, which may be empty. + """ + objects: list[Any] = [] + depth = 0 + start = None + for index, char in enumerate(text): + if char == "{": + if depth == 0: + start = index + depth += 1 + elif char == "}" and depth > 0: + depth -= 1 + if depth == 0 and start is not None: + try: + parsed = json.loads(text[start : index + 1]) + except json.JSONDecodeError: + parsed = None + if isinstance(parsed, dict): + objects.append(parsed) + start = None + return objects + + +def from_google_gemini_2_0( + result: str, + resolution_wh: tuple[int, int], + classes: list[str] | None = None, +) -> tuple[npt.NDArray[Any], npt.NDArray[Any] | None, npt.NDArray[Any]]: + """ + Parse and scale bounding boxes from Google Gemini style + [JSON output](https://ai.google.dev/gemini-api/docs/vision?lang=python). + + The JSON is expected to be enclosed in triple backticks with the format: + ```json + [ + {"box_2d": [x1, y1, x2, y2], "label": "some class name"}, + ... + ] + ``` + + For example: + ```json + [ + {"box_2d": [10, 20, 110, 120], "label": "cat"}, + {"box_2d": [50, 100, 150, 200], "label": "dog"} + ] + ``` + + Args: + result: String containing the JSON snippet enclosed by triple backticks. + resolution_wh: (output_width, output_height) to which we rescale the boxes. + classes: Optional list of valid class names. If provided, returned boxes/labels + are filtered to only those classes found here. + + Returns: + A tuple of `(xyxy, class_id, class_name)` where `xyxy` is an array of + shape `(n, 4)` in format `[x1, y1, x2, y2]`, `class_id` is an + optional array of shape `(n,)` with class indices, and `class_name` + is an array of shape `(n,)` with class labels. + + """ + + w, h = _validate_resolution(resolution_wh) + + lines = result.splitlines() + for i, line in enumerate(lines): + if line == "```json": + result = "\n".join(lines[i + 1 :]) + result = result.split("```")[0] + break + + try: + data = json.loads(result) + except json.JSONDecodeError: + data = _recover_gemini_json_objects(result) + + if not isinstance(data, list): + return np.empty((0, 4)), np.empty((0,), dtype=int), np.empty((0,), dtype=str) + + labels = [] + xyxy = [] + + for item in data: + if not isinstance(item, dict) or "box_2d" not in item or "label" not in item: + continue + labels.append(item["label"]) + box = item["box_2d"] + # Gemini bbox order is [y_min, x_min, y_max, x_max] + xyxy.append([box[1], box[0], box[3], box[2]]) + + if len(xyxy) == 0: + return np.empty((0, 4)), np.empty((0,), dtype=int), np.empty((0,), dtype=str) + + xyxy = denormalize_boxes( + np.array(xyxy, dtype=np.float64), + resolution_wh=(w, h), + normalization_factor=1000, + ) + class_name = np.array(labels) + class_id = None + + if classes is not None: + mask = np.array([name in classes for name in class_name], dtype=bool) + xyxy = xyxy[mask] + class_name = class_name[mask] + class_id = np.array([classes.index(name) for name in class_name]) + + return xyxy, class_id, class_name + + +def from_google_gemini_2_5( + result: str, + resolution_wh: tuple[int, int], + classes: list[str] | None = None, +) -> tuple[ + npt.NDArray[Any], + npt.NDArray[Any] | None, + npt.NDArray[Any], + npt.NDArray[Any] | None, + npt.NDArray[Any] | None, +]: + """ + Parse and scale bounding boxes and masks from Google Gemini 2.5 style + [JSON output](https://ai.google.dev/gemini-api/docs/vision?lang=python). + + The JSON is expected to be enclosed in triple backticks with the format: + ```json + [ + { + "box_2d": [x1, y1, x2, y2], + "mask": "data:image/png;base64,...", + "label": "some class name", + "confidence": 0.95, + }, + ... + ] + ``` + + Args: + result: String containing the JSON snippet enclosed by triple backticks. + resolution_wh: (output_width, output_height) to which we rescale the boxes. + classes: Optional list of valid class names. If provided, returned boxes/labels + are filtered to only those classes found here. + + Returns: + A tuple of `(xyxy, class_id, class_name, confidence, masks)` where + `xyxy` is an array of shape `(n, 4)` in format `[x1, y1, x2, y2]`, + `class_id` is an array of shape `(n,)` with class indices, + `class_name` is an array of shape `(n,)` with class labels, + `confidence` is an optional array of shape `(n,)` with confidence + scores, and `masks` is an optional array of shape `(n, h, w)` with + segmentation masks. + """ + w, h = _validate_resolution(resolution_wh) + + lines = result.splitlines() + for i, line in enumerate(lines): + if line == "```json": + result = "\n".join(lines[i + 1 :]) + result = result.split("```")[0] + break + + try: + data = json.loads(result) + except json.JSONDecodeError: + data = _recover_gemini_json_objects(result) + + if not isinstance(data, list): + return ( + np.empty((0, 4)), + np.array([], dtype=int), + np.array([], dtype=str), + np.array([], dtype=float), + None, + ) + + boxes_list: list[Any] = [] + labels_list: list[str] = [] + confidence_list: list[float] | None = [] + masks_list: list[npt.NDArray[Any]] | None = [] + + for item in data: + if not isinstance(item, dict) or "box_2d" not in item or "label" not in item: + continue + labels_list.append(item["label"]) + box = item["box_2d"] + # Gemini bbox order is [y_min, x_min, y_max, x_max] + absolute_box = denormalize_boxes( + np.array([[box[1], box[0], box[3], box[2]]]).astype(np.float64), + resolution_wh=(w, h), + normalization_factor=1000, + ) + absolute_bbox = _sort_box_corners(absolute_box)[0] + boxes_list.append(absolute_bbox) + + if "mask" in item: + if masks_list is not None: + png_str = item["mask"] + if not isinstance(png_str, str) or not png_str.startswith( + "data:image/png;base64," + ): + # Malformed mask: keep an empty mask but still fall through to + # the confidence handling below, so the per-item arrays stay + # aligned (a `continue` here desynced confidence vs boxes). + masks_list.append(np.zeros((h, w), dtype=bool)) + else: + png_str = png_str.removeprefix("data:image/png;base64,") + try: + png_bytes = base64.b64decode(png_str) + mask_img = Image.open(io.BytesIO(png_bytes)).convert("L") + except Exception: + masks_list.append(np.zeros((h, w), dtype=bool)) + else: + y_min, y_max = int(absolute_bbox[1]), int(absolute_bbox[3]) + x_min, x_max = int(absolute_bbox[0]), int(absolute_bbox[2]) + + bbox_height = y_max - y_min + bbox_width = x_max - x_min + + if bbox_height > 0 and bbox_width > 0: + mask_img = mask_img.resize( + (bbox_width, bbox_height), + resample=Image.Resampling.BILINEAR, + ) + np_mask: npt.NDArray[np.bool_] = np.zeros( + (h, w), dtype=bool + ) + np_mask[y_min:y_max, x_min:x_max] = np.array(mask_img) > 0 + masks_list.append(np_mask) + else: + masks_list.append(np.zeros((h, w), dtype=bool)) + else: + masks_list = None + + if "confidence" in item: + if confidence_list is not None: + confidence_list.append(item["confidence"]) + else: + confidence_list = None + + if not boxes_list: + return ( + np.empty((0, 4)), + np.array([], dtype=int), + np.array([], dtype=str), + np.array([], dtype=float), + None, + ) + + xyxy = np.array(boxes_list, dtype=float) + class_name = np.array(labels_list) + class_id: npt.NDArray[Any] + + if classes is not None: + mask = np.array([name in classes for name in class_name], dtype=bool) + xyxy = xyxy[mask] + class_name = class_name[mask] + class_id = np.array([classes.index(name) for name in class_name]) + if masks_list is not None: + masks_list = [m for m, keep in zip(masks_list, mask) if keep] + + if confidence_list is not None: + confidence_list = [c for c, keep in zip(confidence_list, mask) if keep] + else: + unique_labels = sorted(list(set(class_name))) + label_to_id = {label: i for i, label in enumerate(unique_labels)} + class_id = np.array([label_to_id[name] for name in class_name]) + + confidence = ( + np.array(confidence_list, dtype=float) if confidence_list is not None else None + ) + masks = np.array(masks_list) if masks_list is not None else None + + return ( + xyxy, + class_id, + class_name, + confidence, + masks, + ) + + +def from_google_gemini_3_5( + result: str, + resolution_wh: tuple[int, int], + classes: list[str] | None = None, +) -> tuple[ + npt.NDArray[Any], + npt.NDArray[Any] | None, + npt.NDArray[Any], + npt.NDArray[Any] | None, + npt.NDArray[Any] | None, +]: + """ + Parse and scale bounding boxes and masks from Google Gemini 3.5 style JSON output. + + Gemini 3.5 emits the same detection JSON as Gemini 2.5 (`box_2d` in + `[y_min, x_min, y_max, x_max]` normalized to 0-1000, plus `label` and optional + `mask`/`confidence`), so parsing delegates to `from_google_gemini_2_5`. + + Args: + result: String containing the JSON snippet enclosed by triple backticks. + resolution_wh: (output_width, output_height) to which we rescale the boxes. + classes: Optional list of valid class names. If provided, returned boxes/labels + are filtered to only those classes found here. + + Returns: + A tuple of `(xyxy, class_id, class_name, confidence, masks)` matching the + `from_google_gemini_2_5` return contract. + """ + return from_google_gemini_2_5(result, resolution_wh, classes) + + +def from_moondream( + result: dict[str, Any], + resolution_wh: tuple[int, int], +) -> npt.NDArray[Any]: + """ + Parse and scale bounding boxes from moondream JSON output. + + The JSON is expected to have a key "objects" with a list of dictionaries: + { + "objects": [ + {"x_min": 0.1, "y_min": 0.2, "x_max": 0.3, "y_max": 0.4}, + ... + ] + } + + For Example: + { + "objects": [ + {"x_min": 0.1, "y_min": 0.2, "x_max": 0.3, "y_max": 0.4}, + {"x_min": 0.5, "y_min": 0.6, "x_max": 0.7, "y_max": 0.8} + ] + } + + Args: + result: Dictionary containing the JSON output from the model. + resolution_wh: (output_width, output_height) to which we rescale the boxes. + + Returns: + An array of shape `(n, 4)` containing the bounding boxes coordinates + in format `[x1, y1, x2, y2]`. + """ + + w, h = resolution_wh + if w <= 0 or h <= 0: + raise ValueError( + f"Both dimensions in resolution_wh must be positive. Got ({w}, {h})." + ) + + if "objects" not in result or not isinstance(result["objects"], list): + return np.empty((0, 4), dtype=float) + + xyxy = [] + + for item in result["objects"]: + if not all(k in item for k in ["x_min", "y_min", "x_max", "y_max"]): + continue + + x_min = item["x_min"] + y_min = item["y_min"] + x_max = item["x_max"] + y_max = item["y_max"] + + xyxy.append([x_min, y_min, x_max, y_max]) + + if len(xyxy) == 0: + return cast(npt.NDArray[Any], np.empty((0, 4))) + + return cast( + npt.NDArray[Any], + denormalize_boxes( + np.array(xyxy).astype(np.float64), + resolution_wh=(w, h), + ), + ) diff --git a/.venv/lib/python3.12/site-packages/supervision/draw/__init__.py b/.venv/lib/python3.12/site-packages/supervision/draw/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/supervision/draw/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/draw/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c71a42a4045876e8beff66d7357534e04c97a272 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/draw/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/draw/__pycache__/base.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/draw/__pycache__/base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9977f9ac08bdf594849d26a55067011534320d40 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/draw/__pycache__/base.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/draw/__pycache__/color.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/draw/__pycache__/color.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00f91b28bb9d26c1d9f96cc0c1bd1b89c39c2561 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/draw/__pycache__/color.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/draw/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/draw/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b67a1e12aa66d3750cd7dfa9737dbc2182f141a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/draw/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/draw/base.py b/.venv/lib/python3.12/site-packages/supervision/draw/base.py new file mode 100644 index 0000000000000000000000000000000000000000..0f3d50c6a3a3b08803226d115ddc9c93fa474828 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/draw/base.py @@ -0,0 +1,14 @@ +from typing import TypeVar + +import numpy as np +import numpy.typing as npt +from PIL import Image + +ImageType = TypeVar("ImageType", npt.NDArray[np.uint8], Image.Image) +""" +An image of type `np.ndarray` or `PIL.Image.Image`. + +Unlike a `Union`, ensures the type remains consistent. If a function +takes an `ImageType` argument and returns an `ImageType`, when you +pass an `np.ndarray`, you will get an `np.ndarray` back. +""" diff --git a/.venv/lib/python3.12/site-packages/supervision/draw/color.py b/.venv/lib/python3.12/site-packages/supervision/draw/color.py new file mode 100644 index 0000000000000000000000000000000000000000..c99f4ccafaabf1d9af038b3724b8ce2dc3c4f159 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/draw/color.py @@ -0,0 +1,598 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, cast + +from supervision.utils.internal import classproperty + +DEFAULT_COLOR_PALETTE = [ + "A351FB", + "FF4040", + "FFA1A0", + "FF7633", + "FFB633", + "D1D435", + "4CFB12", + "94CF1A", + "40DE8A", + "1B9640", + "00D6C1", + "2E9CAA", + "00C4FF", + "364797", + "6675FF", + "0019EF", + "863AFF", + "530087", + "CD3AFF", + "FF97CA", + "FF39C9", +] + +LEGACY_COLOR_PALETTE = [ + "#A351FB", + "#E6194B", + "#3CB44B", + "#FFE119", + "#0082C8", + "#F58231", + "#911EB4", + "#46F0F0", + "#F032E6", + "#D2F53C", + "#FABEBE", + "#008080", + "#E6BEFF", + "#AA6E28", + "#FFFAC8", + "#800000", + "#AAFFC3", +] + +ROBOFLOW_COLOR_PALETTE = ["C28DFC", "A351FB", "8315F9", "6706CE", "5905B3", "4D049A"] + + +def _validate_color_hex(color_hex: str) -> None: + color_hex = color_hex.lstrip("#") + if not all(c in "0123456789abcdefABCDEF" for c in color_hex): + raise ValueError("Invalid characters in color hash") + if len(color_hex) not in (3, 4, 6, 8): + raise ValueError("Invalid length of color hash") + + +@dataclass +class Color: + """ + Represents a color in RGBA format. + + This class provides methods to work with colors, including creating colors from hex + codes, converting colors to hex strings, RGB tuples, BGR tuples, RGBA tuples, + and BGRA tuples. + + Attributes: + r: Red channel value (0-255). + g: Green channel value (0-255). + b: Blue channel value (0-255). + a: Alpha channel value (0-255). Default is 255 (fully opaque). + + Example: + ```pycon + >>> import supervision as sv + >>> sv.Color.WHITE + Color(r=255, g=255, b=255) + + ``` + + | Constant | Hex Code | RGB | + |------------|------------|-------------------| + | `WHITE` | `#FFFFFF` | `(255, 255, 255)` | + | `BLACK` | `#000000` | `(0, 0, 0)` | + | `GREY` | `#808080` | `(128, 128, 128)` | + | `RED` | `#FF0000` | `(255, 0, 0)` | + | `GREEN` | `#00FF00` | `(0, 255, 0)` | + | `BLUE` | `#0000FF` | `(0, 0, 255)` | + | `YELLOW` | `#FFFF00` | `(255, 255, 0)` | + | `ROBOFLOW` | `#A351FB` | `(163, 81, 251)` | + """ + + r: int + g: int + b: int + a: int = 255 + + def __post_init__(self) -> None: + """Validate that direct Color construction uses byte-sized channels.""" + if not ( + 0 <= self.r <= 255 + and 0 <= self.g <= 255 + and 0 <= self.b <= 255 + and 0 <= self.a <= 255 + ): + raise ValueError( + "Color values must be in range 0-255, " + f"got ({self.r}, {self.g}, {self.b}, {self.a})" + ) + + @classmethod + def from_hex(cls, color_hex: str) -> Color: + """ + Create a Color instance from a hex string. + + Args: + color_hex: The hex string representing the color. This string can + start with '#' followed by 3, 4, 6, or 8 hexadecimal characters. + For 3- or 4-character codes, each character is doubled to form the + full hex code. + + Returns: + An instance representing the color. + + Example: + ```pycon + >>> import supervision as sv + >>> sv.Color.from_hex('#ff00ff') + Color(r=255, g=0, b=255) + >>> sv.Color.from_hex('#f0f') + Color(r=255, g=0, b=255) + + >>> sv.Color.from_hex('#ff00ff80') + Color(r=255, g=0, b=255, a=128) + >>> sv.Color.from_hex('#f0f8') + Color(r=255, g=0, b=255, a=136) + + ``` + """ + _validate_color_hex(color_hex) + color_hex = color_hex.lstrip("#") + if len(color_hex) == 3: + color_hex = "".join(c * 2 for c in color_hex) + elif len(color_hex) == 4: + color_hex = "".join(c * 2 for c in color_hex) + + if len(color_hex) == 6: + r, g, b = (int(color_hex[i : i + 2], 16) for i in range(0, 6, 2)) + return cls(r, g, b) + else: # len(color_hex) == 8 + r, g, b, a = (int(color_hex[i : i + 2], 16) for i in range(0, 8, 2)) + return cls(r, g, b, a) + + @classmethod + def from_rgb_tuple(cls, color_tuple: tuple[int, int, int]) -> Color: + """ + Create a Color instance from an RGB tuple. + + Args: + color_tuple: A tuple representing the color in RGB format, where each + element is an integer in the range 0-255. + + Returns: + An instance representing the color. + + Raises: + ValueError: If any RGB value is outside the range 0-255. + + Example: + ```pycon + >>> import supervision as sv + >>> sv.Color.from_rgb_tuple((255, 255, 0)) + Color(r=255, g=255, b=0) + + ``` + """ + r, g, b = color_tuple + if not (0 <= r <= 255 and 0 <= g <= 255 and 0 <= b <= 255): + raise ValueError(f"RGB values must be in range 0-255, got ({r}, {g}, {b})") + return cls(r=r, g=g, b=b) + + @classmethod + def from_bgr_tuple(cls, color_tuple: tuple[int, int, int]) -> Color: + """ + Create a Color instance from a BGR tuple. + + Args: + color_tuple: A tuple representing the color in BGR format, where each + element is an integer in the range 0-255. + + Returns: + An instance representing the color. + + Raises: + ValueError: If any BGR value is outside the range 0-255. + + Example: + ```pycon + >>> import supervision as sv + >>> sv.Color.from_bgr_tuple((0, 255, 255)) + Color(r=255, g=255, b=0) + + ``` + """ + b, g, r = color_tuple + if not (0 <= r <= 255 and 0 <= g <= 255 and 0 <= b <= 255): + raise ValueError(f"BGR values must be in range 0-255, got ({b}, {g}, {r})") + return cls(r=r, g=g, b=b) + + @classmethod + def from_rgba_tuple(cls, color_tuple: tuple[int, int, int, int]) -> Color: + """ + Create a Color instance from an RGBA tuple. + + Args: + color_tuple: A tuple representing the color in RGBA format, where each + element is an integer in the range 0-255. + + Returns: + An instance representing the color. + + Raises: + ValueError: If any RGBA value is outside the range 0-255. + + Example: + ```pycon + >>> import supervision as sv + >>> sv.Color.from_rgba_tuple((255, 255, 0, 128)) + Color(r=255, g=255, b=0, a=128) + + ``` + """ + r, g, b, a = color_tuple + if not (0 <= r <= 255 and 0 <= g <= 255 and 0 <= b <= 255 and 0 <= a <= 255): + raise ValueError( + f"RGBA values must be in range 0-255, got ({r}, {g}, {b}, {a})" + ) + return cls(r=r, g=g, b=b, a=a) + + @classmethod + def from_bgra_tuple(cls, color_tuple: tuple[int, int, int, int]) -> Color: + """ + Create a Color instance from a BGRA tuple. + + Args: + color_tuple: A tuple representing the color in BGRA format, where each + element is an integer in the range 0-255. + + Returns: + An instance representing the color. + + Raises: + ValueError: If any BGRA value is outside the range 0-255. + + Example: + ```pycon + >>> import supervision as sv + >>> sv.Color.from_bgra_tuple((0, 255, 255, 128)) + Color(r=255, g=255, b=0, a=128) + + ``` + """ + b, g, r, a = color_tuple + if not (0 <= r <= 255 and 0 <= g <= 255 and 0 <= b <= 255 and 0 <= a <= 255): + raise ValueError( + f"BGRA values must be in range 0-255, got ({b}, {g}, {r}, {a})" + ) + return cls(r=r, g=g, b=b, a=a) + + def as_hex(self) -> str: + """ + Converts the Color instance to a hex string. + + Returns: + The hexadecimal color string. Returns `#RRGGBBAA` if alpha is not 255, + otherwise returns `#RRGGBB`. + + Example: + ```pycon + >>> import supervision as sv + >>> sv.Color(r=255, g=255, b=0).as_hex() + '#ffff00' + + >>> sv.Color(r=255, g=0, b=255, a=128).as_hex() + '#ff00ff80' + + ``` + """ + if self.a != 255: + return f"#{self.r:02x}{self.g:02x}{self.b:02x}{self.a:02x}" + return f"#{self.r:02x}{self.g:02x}{self.b:02x}" + + def as_rgb(self) -> tuple[int, int, int]: + """ + Returns the color as an RGB tuple. + + Returns: + RGB tuple. + + Example: + ```pycon + >>> import supervision as sv + >>> sv.Color(r=255, g=255, b=0).as_rgb() + (255, 255, 0) + + ``` + """ + return self.r, self.g, self.b + + def as_bgr(self) -> tuple[int, int, int]: + """ + Returns the color as a BGR tuple. + + Returns: + BGR tuple. + + Example: + ```pycon + >>> import supervision as sv + >>> sv.Color(r=255, g=255, b=0).as_bgr() + (0, 255, 255) + + ``` + """ + return self.b, self.g, self.r + + def as_rgba(self) -> tuple[int, int, int, int]: + """ + Returns the color as an RGBA tuple. + + Returns: + RGBA tuple. + + Example: + ```pycon + >>> import supervision as sv + >>> sv.Color(r=255, g=255, b=0, a=128).as_rgba() + (255, 255, 0, 128) + + ``` + """ + return self.r, self.g, self.b, self.a + + def as_bgra(self) -> tuple[int, int, int, int]: + """ + Returns the color as a BGRA tuple. + + Returns: + BGRA tuple. + + Example: + ```pycon + >>> import supervision as sv + >>> sv.Color(r=255, g=255, b=0, a=128).as_bgra() + (0, 255, 255, 128) + + ``` + """ + return self.b, self.g, self.r, self.a + + @classproperty + def WHITE(cls) -> Color: + return Color.from_hex("#FFFFFF") + + @classproperty + def BLACK(cls) -> Color: + return Color.from_hex("#000000") + + @classproperty + def GREY(cls) -> Color: + return Color.from_hex("#808080") + + @classproperty + def RED(cls) -> Color: + return Color.from_hex("#FF0000") + + @classproperty + def GREEN(cls) -> Color: + return Color.from_hex("#00FF00") + + @classproperty + def BLUE(cls) -> Color: + return Color.from_hex("#0000FF") + + @classproperty + def YELLOW(cls) -> Color: + return Color.from_hex("#FFFF00") + + @classproperty + def ROBOFLOW(cls) -> Color: + return Color.from_hex("#A351FB") + + def __hash__(self) -> int: + return hash((self.r, self.g, self.b, self.a)) + + def __repr__(self) -> str: + if self.a == 255: + return f"Color(r={self.r}, g={self.g}, b={self.b})" + return f"Color(r={self.r}, g={self.g}, b={self.b}, a={self.a})" + + def __eq__(self, other: Any) -> bool: + return ( + isinstance(other, Color) + and self.r == other.r + and self.g == other.g + and self.b == other.b + and self.a == other.a + ) + + +@dataclass +class ColorPalette: + colors: list[Color] + + @classproperty + def DEFAULT(cls) -> ColorPalette: + """ + Returns a default color palette. + + Returns: + A ColorPalette instance with default colors. + + Example: + ```pycon + >>> import supervision as sv + >>> sv.ColorPalette.DEFAULT # doctest: +ELLIPSIS + ColorPalette(colors=[Color(r=163, g=81, b=251), Color(r=255, g=64, b=64), ...]) + + ``` + + ![default-color-palette](https://media.roboflow.com/ + supervision-annotator-examples/default-color-palette.png) + """ # noqa: E501 // docs + return ColorPalette.from_hex(color_hex_list=DEFAULT_COLOR_PALETTE) + + @classproperty + def ROBOFLOW(cls) -> ColorPalette: + """ + Returns a Roboflow color palette. + + Returns: + A ColorPalette instance with Roboflow colors. + + Example: + ```pycon + >>> import supervision as sv + >>> sv.ColorPalette.ROBOFLOW # doctest: +ELLIPSIS + ColorPalette(colors=[Color(r=194, g=141, b=252), Color(r=163, g=81, b=251), ...]) + + ``` + + ![roboflow-color-palette](https://media.roboflow.com/ + supervision-annotator-examples/roboflow-color-palette.png) + """ # noqa: E501 // docs + return ColorPalette.from_hex(color_hex_list=ROBOFLOW_COLOR_PALETTE) + + @classproperty + def LEGACY(cls) -> ColorPalette: + return ColorPalette.from_hex(color_hex_list=LEGACY_COLOR_PALETTE) + + @classmethod + def from_hex(cls, color_hex_list: list[str]) -> ColorPalette: + """ + Create a ColorPalette instance from a list of hex strings. + + Args: + color_hex_list: List of color hex strings. + + Returns: + A ColorPalette instance. + + Example: + ```pycon + >>> import supervision as sv + >>> colors = ['#ff0000', '#00ff00', '#0000ff'] + >>> sv.ColorPalette.from_hex(colors) # doctest: +ELLIPSIS + ColorPalette(colors=[Color(r=255, g=0, b=0), Color(r=0, g=255, b=0), ...]) + + ``` + """ + colors = [Color.from_hex(color_hex) for color_hex in color_hex_list] + return cls(colors) + + @classmethod + def from_matplotlib(cls, palette_name: str, color_count: int) -> ColorPalette: + """ + Create a ColorPalette instance from a Matplotlib color palette. + + Args: + palette_name: Name of the Matplotlib palette. + color_count: Number of colors to sample from the palette. + + Returns: + A ColorPalette instance. + + Example: + ```pycon + >>> import supervision as sv + >>> sv.ColorPalette.from_matplotlib('viridis', 5) # doctest: +ELLIPSIS + ColorPalette(colors=[Color(r=68, g=1, b=84), Color(r=58, g=82, b=139), ...]) + + ``` + + ![visualized_color_palette](https://media.roboflow.com/ + supervision-annotator-examples/visualized_color_palette.png) + """ + if color_count < 1: + raise ValueError("color_count must be greater than or equal to 1") + + # Keep pyplot lazy so importing color utilities does not import matplotlib. + import matplotlib.pyplot as plt + + mpl_palette = plt.get_cmap(palette_name) + if hasattr(mpl_palette, "resampled"): + mpl_palette = mpl_palette.resampled(color_count) + + if hasattr(mpl_palette, "colors"): + colors = mpl_palette.colors + else: + # A single color samples the palette start and avoids division by zero. + positions = ( + [0.0] + if color_count == 1 + else [i / (color_count - 1) for i in range(color_count)] + ) + colors = [mpl_palette(position) for position in positions] + + return cls( + [Color(int(r * 255), int(g * 255), int(b * 255)) for r, g, b, _ in colors] + ) + + def by_idx(self, idx: int) -> Color: + """ + Return the color at a given index in the palette. + + Args: + idx: Index of the color in the palette. + + Returns: + Color at the given index. + + Example: + ```pycon + >>> import supervision as sv + >>> colors = ['#ff0000', '#00ff00', '#0000ff'] + >>> color_palette = sv.ColorPalette.from_hex(colors) + >>> color_palette.by_idx(1) + Color(r=0, g=255, b=0) + + ``` + """ + if not self.colors: + raise ValueError("ColorPalette must contain at least one color") + # Modulo preserves Python-like wrapping for negative and oversized indexes. + idx = idx % len(self.colors) + return self.colors[idx] + + def __len__(self) -> int: + """ + Returns the number of colors in the palette. + + Returns: + The number of colors. + """ + return len(self.colors) + + +def unify_to_bgr(color: tuple[int, int, int] | Color) -> tuple[int, int, int]: + """ + Converts a color input in multiple formats to a standardized BGR format. + + Args: + color: The color input to be converted, + which can be either a tuple of BGR values or an instance of a Color class. + + Returns: + The color in BGR format as a tuple of three integers. + + Example: + ```pycon + >>> from supervision.draw.color import unify_to_bgr, Color + >>> unify_to_bgr(Color.WHITE) + (255, 255, 255) + >>> unify_to_bgr((0, 255, 255)) + (0, 255, 255) + + ``` + """ + if issubclass(type(color), Color): + color = cast(Color, color) + return color.as_bgr() + color = cast(tuple[int, int, int], color) + return color diff --git a/.venv/lib/python3.12/site-packages/supervision/draw/utils.py b/.venv/lib/python3.12/site-packages/supervision/draw/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4de1cf97c7a3600300e53052b23d86522be91b8e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/draw/utils.py @@ -0,0 +1,550 @@ +import os +from typing import cast + +import numpy as np +import numpy.typing as npt + +from supervision import _cv2 as cv2 +from supervision.draw.color import Color +from supervision.geometry.core import Point, Rect + + +def draw_line( + scene: npt.NDArray[np.uint8], + start: Point, + end: Point, + color: Color = Color.ROBOFLOW, + thickness: int = 2, +) -> npt.NDArray[np.uint8]: + """ + Draws a line on a given scene. + + Args: + scene: The scene on which the line will be drawn + start: The starting point of the line + end: The end point of the line + color: The color of the line, defaults to Color.ROBOFLOW + thickness: The thickness of the line + + Returns: + The scene with the line drawn on it + + Example: + ```pycon + >>> import numpy as np + >>> from supervision.draw.utils import draw_line + >>> from supervision.draw.color import Color + >>> from supervision.geometry.core import Point + >>> scene = np.zeros((100, 100, 3), dtype=np.uint8) + >>> scene = draw_line( + ... scene, start=Point(x=10, y=10), end=Point(x=90, y=90), color=Color.RED + ... ) + >>> scene.shape + (100, 100, 3) + + ``` + """ + cv2.line( + scene, + start.as_xy_int_tuple(), + end.as_xy_int_tuple(), + color.as_bgr(), + thickness=thickness, + ) + return scene + + +def draw_rectangle( + scene: npt.NDArray[np.uint8], + rect: Rect, + color: Color = Color.ROBOFLOW, + thickness: int = 2, +) -> npt.NDArray[np.uint8]: + """ + Draws a rectangle on an image. + + Args: + scene: The scene on which the rectangle will be drawn + rect: The rectangle to be drawn + color: The color of the rectangle + thickness: The thickness of the rectangle border + + Returns: + The scene with the rectangle drawn on it + + Example: + ```pycon + >>> import numpy as np + >>> from supervision.draw.utils import draw_rectangle + >>> from supervision.draw.color import Color + >>> from supervision.geometry.core import Rect + >>> scene = np.zeros((100, 100, 3), dtype=np.uint8) + >>> rect = Rect(x=10, y=10, width=50, height=30) + >>> scene = draw_rectangle(scene, rect, color=Color.RED) + >>> scene.shape + (100, 100, 3) + + ``` + """ + cv2.rectangle( + scene, + rect.top_left.as_xy_int_tuple(), + rect.bottom_right.as_xy_int_tuple(), + color.as_bgr(), + thickness=thickness, + ) + return scene + + +def draw_filled_rectangle( + scene: npt.NDArray[np.uint8], + rect: Rect, + color: Color = Color.ROBOFLOW, + opacity: float = 1, +) -> npt.NDArray[np.uint8]: + """ + Draws a filled rectangle on an image. + + Args: + scene: The scene on which the rectangle will be drawn + rect: The rectangle to be drawn + color: The color of the rectangle + opacity: The opacity of rectangle when drawn on the scene. + + Returns: + The scene with the rectangle drawn on it + + Example: + ```pycon + >>> import numpy as np + >>> from supervision.draw.utils import draw_filled_rectangle + >>> from supervision.draw.color import Color + >>> from supervision.geometry.core import Rect + >>> scene = np.zeros((100, 100, 3), dtype=np.uint8) + >>> rect = Rect(x=10, y=10, width=50, height=30) + >>> scene = draw_filled_rectangle(scene, rect, color=Color.RED, opacity=0.5) + >>> scene.shape + (100, 100, 3) + + ``` + """ + if opacity == 1: + cv2.rectangle( + scene, + rect.top_left.as_xy_int_tuple(), + rect.bottom_right.as_xy_int_tuple(), + color.as_bgr(), + -1, + ) + else: + scene_with_annotations = scene.copy() + cv2.rectangle( + scene_with_annotations, + rect.top_left.as_xy_int_tuple(), + rect.bottom_right.as_xy_int_tuple(), + color.as_bgr(), + -1, + ) + cv2.addWeighted( + scene_with_annotations, opacity, scene, 1 - opacity, gamma=0, dst=scene + ) + + return scene + + +def draw_rounded_rectangle( + scene: npt.NDArray[np.uint8], + rect: Rect, + color: Color, + border_radius: int, +) -> npt.NDArray[np.uint8]: + """ + Draws a rounded rectangle on an image. + + Args: + scene: The image on which the rounded rectangle will be drawn. + rect: The rectangle to be drawn. + color: The color of the rounded rectangle. + border_radius: The radius of the corner rounding in pixels. Values <= 0 + (or values clamped to 0 when the rectangle is too small) draw a + plain filled rectangle with square corners. Note: previously, + a negative value that remained negative after clamping would raise + ``cv2.error``; it now draws square corners silently. + + Returns: + The image with the rounded rectangle drawn on it. + + Example: + ```pycon + >>> import numpy as np + >>> from supervision.draw.utils import draw_rounded_rectangle + >>> from supervision.draw.color import Color + >>> from supervision.geometry.core import Rect + >>> scene = np.zeros((200, 300, 3), dtype=np.uint8) + >>> rect = Rect(x=20, y=30, width=120, height=80) + >>> scene = draw_rounded_rectangle(scene, rect, Color.RED, border_radius=0) + >>> scene.shape + (200, 300, 3) + + ``` + """ + x1, y1, x2, y2 = rect.as_xyxy_int_tuple() + width, height = x2 - x1, y2 - y1 + border_radius = min(border_radius, min(width, height) // 2) + + if border_radius <= 0: + # square corners: a single fill rectangle (the common default), rather + # than two rectangles plus four zero-radius corner circles + cv2.rectangle( + img=scene, + pt1=(x1, y1), + pt2=(x2, y2), + color=color.as_bgr(), + thickness=-1, + ) + return scene + + rectangle_coordinates = [ + ((x1 + border_radius, y1), (x2 - border_radius, y2)), + ((x1, y1 + border_radius), (x2, y2 - border_radius)), + ] + circle_centers = [ + (x1 + border_radius, y1 + border_radius), + (x2 - border_radius, y1 + border_radius), + (x1 + border_radius, y2 - border_radius), + (x2 - border_radius, y2 - border_radius), + ] + + for coordinates in rectangle_coordinates: + cv2.rectangle( + img=scene, + pt1=coordinates[0], + pt2=coordinates[1], + color=color.as_bgr(), + thickness=-1, + ) + for center in circle_centers: + cv2.circle( + img=scene, + center=center, + radius=border_radius, + color=color.as_bgr(), + thickness=-1, + ) + return scene + + +def draw_polygon( + scene: npt.NDArray[np.uint8], + polygon: npt.NDArray[np.int_], + color: Color = Color.ROBOFLOW, + thickness: int = 2, +) -> npt.NDArray[np.uint8]: + """Draw a polygon on a scene. + + Args: + scene: The scene to draw the polygon on. + polygon: The polygon to be drawn, given as a list of vertices. + color: The color of the polygon. Defaults to Color.ROBOFLOW. + thickness: The thickness of the polygon lines, by default 2. + + Returns: + The scene with the polygon drawn on it. + + Example: + ```pycon + >>> import numpy as np + >>> from supervision.draw.utils import draw_polygon + >>> from supervision.draw.color import Color + >>> scene = np.zeros((100, 100, 3), dtype=np.uint8) + >>> polygon = np.array([[10, 10], [90, 10], [90, 90], [10, 90]]) + >>> scene = draw_polygon(scene, polygon, color=Color.RED) + >>> scene.shape + (100, 100, 3) + + ``` + """ + cv2.polylines( + scene, [polygon], isClosed=True, color=color.as_bgr(), thickness=thickness + ) + return scene + + +def draw_filled_polygon( + scene: npt.NDArray[np.uint8], + polygon: npt.NDArray[np.int_], + color: Color = Color.ROBOFLOW, + opacity: float = 1, +) -> npt.NDArray[np.uint8]: + """Draw a filled polygon on a scene. + + Args: + scene: The scene to draw the polygon on. + polygon: The polygon to be drawn, given as a list of vertices. + color: The color of the polygon. Defaults to Color.ROBOFLOW. + opacity: The opacity of polygon when drawn on the scene. + + Returns: + The scene with the polygon drawn on it. + + Example: + ```pycon + >>> import numpy as np + >>> from supervision.draw.utils import draw_filled_polygon + >>> from supervision.draw.color import Color + >>> scene = np.zeros((100, 100, 3), dtype=np.uint8) + >>> polygon = np.array([[10, 10], [90, 10], [90, 90], [10, 90]]) + >>> scene = draw_filled_polygon(scene, polygon, color=Color.RED, opacity=0.5) + >>> scene.shape + (100, 100, 3) + + ``` + """ + if opacity == 1: + cv2.fillPoly(scene, [polygon], color=color.as_bgr()) + else: + scene_with_annotations = scene.copy() + cv2.fillPoly(scene_with_annotations, [polygon], color=color.as_bgr()) + cv2.addWeighted( + scene_with_annotations, opacity, scene, 1 - opacity, gamma=0, dst=scene + ) + + return scene + + +def draw_text( + scene: npt.NDArray[np.uint8], + text: str, + text_anchor: Point, + text_color: Color = Color.BLACK, + text_scale: float = 0.5, + text_thickness: int = 1, + text_padding: int = 10, + text_font: int = cv2.FONT_HERSHEY_SIMPLEX, + background_color: Color | None = None, +) -> npt.NDArray[np.uint8]: + """ + Draw text with background on a scene. + + Args: + scene: A numpy ndarray representing the image, typically of shape + (H, W, 3) for a color BGR image or (H, W) for grayscale, + with dtype uint8. + text: The text to be drawn. + text_anchor: The anchor point for the text, represented as a + Point object with x and y attributes. + text_color: The color of the text. Defaults to black. + text_scale: The scale of the text. Defaults to 0.5. + text_thickness: The thickness of the text. Defaults to 1. + text_padding: The amount of padding to add around the text + when drawing a rectangle in the background. Defaults to 10. + text_font: The font to use for the text. + Defaults to cv2.FONT_HERSHEY_SIMPLEX. + background_color: The color of the background rectangle, + if one is to be drawn. Defaults to None. + + Returns: + The input scene with the text drawn on it. + + Examples: + ```pycon + >>> import numpy as np + >>> from supervision.geometry.core import Point + >>> from supervision.draw.utils import draw_text + >>> scene = np.zeros((100, 100, 3), dtype=np.uint8) + >>> text_anchor = Point(x=50, y=50) + >>> scene = draw_text( + ... scene=scene, text="Hello, world!", text_anchor=text_anchor + ... ) + >>> scene.shape + (100, 100, 3) + + ``` + """ + text_width, text_height = cv2.getTextSize( + text=text, + fontFace=text_font, + fontScale=text_scale, + thickness=text_thickness, + )[0] + + text_anchor_x, text_anchor_y = text_anchor.as_xy_int_tuple() + + text_rect = Rect( + x=text_anchor_x - text_width // 2, + y=text_anchor_y - text_height // 2, + width=text_width, + height=text_height, + ).pad(text_padding) + + if background_color is not None: + scene = draw_filled_rectangle( + scene=scene, rect=text_rect, color=background_color + ) + + cv2.putText( + img=scene, + text=text, + org=(text_anchor_x - text_width // 2, text_anchor_y + text_height // 2), + fontFace=text_font, + fontScale=text_scale, + color=text_color.as_bgr(), + thickness=text_thickness, + lineType=cv2.LINE_AA, + ) + return scene + + +def draw_image( + scene: npt.NDArray[np.uint8], + image: str | npt.NDArray[np.uint8], + opacity: float, + rect: Rect, +) -> npt.NDArray[np.uint8]: + """ + Draws an image onto a given scene with specified opacity and dimensions. + + Args: + scene: Background image where the new image will be drawn. + image: Image to draw, either a file path or an already-loaded image array. + A 2-D grayscale image is not accepted, whether it is passed as an array + or read from a path; convert it to BGR first, for example with + `cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)`. A 16-bit image read from a + path is scaled down to the 8 bits of the scene. + opacity: Opacity of the image to be drawn. + rect: Rectangle specifying where to draw the image. + + Returns: + The updated scene. + + Raises: + FileNotFoundError: If the image path does not exist. + OSError: If the image path exists but cannot be decoded. + ValueError: If the image is not 3-D with 3 (BGR) or 4 (BGRA) channels, or + for invalid opacity or rectangle dimensions. + + Example: + ```pycon + >>> import numpy as np + >>> from supervision.draw.utils import draw_image + >>> from supervision.geometry.core import Rect + >>> scene = np.zeros((100, 100, 3), dtype=np.uint8) + >>> image = np.full((40, 40, 3), 255, dtype=np.uint8) + >>> rect = Rect(x=10, y=10, width=40, height=40) + >>> scene = draw_image(scene, image, opacity=0.8, rect=rect) + >>> scene.shape + (100, 100, 3) + + ``` + """ + + # Validate and load image + if isinstance(image, str): + if not os.path.exists(image): + raise FileNotFoundError(f"Image path ('{image}') does not exist.") + loaded_image = cv2.imread(image, cv2.IMREAD_UNCHANGED) + if loaded_image is None: + raise OSError(f"Could not decode image path ('{image}').") + if loaded_image.dtype == np.uint16: + # IMREAD_UNCHANGED keeps a 16-bit PNG at 16 bits, which the blend into + # the 8-bit scene saturates to 255; keep the high byte instead. + loaded_image = np.clip(np.rint(loaded_image / 256), 0, 255).astype(np.uint8) + image_np = cast(npt.NDArray[np.uint8], loaded_image) + else: + image_np = image + + if image_np.ndim != 3 or image_np.shape[2] not in (3, 4): + raise ValueError("Image must have 3 or 4 channels.") + + # Validate opacity + if not 0.0 <= opacity <= 1.0: + raise ValueError("Opacity must be between 0.0 and 1.0.") + + rect_x = int(rect.x) + rect_y = int(rect.y) + rect_width = int(rect.width) + rect_height = int(rect.height) + # Validate rectangle dimensions + if ( + rect_x < 0 + or rect_y < 0 + or rect_x + rect_width > scene.shape[1] + or rect_y + rect_height > scene.shape[0] + ): + raise ValueError("Invalid rectangle dimensions.") + + # Resize and isolate alpha channel + image_np = cast( + npt.NDArray[np.uint8], cv2.resize(image_np, (rect_width, rect_height)) + ) + alpha_channel = ( + image_np[:, :, 3] + if image_np.shape[2] == 4 + else np.ones((rect_height, rect_width), dtype=image_np.dtype) * 255 + ) + alpha_scaled = cv2.convertScaleAbs(alpha_channel * opacity) + + # Perform blending + scene_roi = scene[rect_y : rect_y + rect_height, rect_x : rect_x + rect_width] + alpha_float = alpha_scaled.astype(np.float32) / 255.0 + blended_roi = cv2.convertScaleAbs( + (1 - alpha_float[..., np.newaxis]) * scene_roi + + alpha_float[..., np.newaxis] * image_np[:, :, :3] + ) + + # Update the scene + scene[rect_y : rect_y + rect_height, rect_x : rect_x + rect_width] = blended_roi + + return scene + + +def calculate_optimal_text_scale(resolution_wh: tuple[int, int]) -> float: + """ + Calculate optimal font scale based on image resolution. Adjusts font scale + proportionally to the smallest dimension of the given image resolution for + consistent readability. + + Args: + resolution_wh: A tuple of `(width, height)` of the image in pixels. + + Returns: + Recommended font scale factor. + + Examples: + ```pycon + >>> import supervision as sv + >>> sv.calculate_optimal_text_scale((1920, 1080)) + 1.08 + >>> sv.calculate_optimal_text_scale((640, 480)) + 0.48 + + ``` + """ + return min(resolution_wh) * 1e-3 + + +def calculate_optimal_line_thickness(resolution_wh: tuple[int, int]) -> int: + """ + Calculate optimal line thickness based on image resolution. Adjusts the line + thickness for readability depending on the smallest dimension of the provided + image resolution. + + Args: + resolution_wh: A tuple of `(width, height)` of the image in pixels. + + Returns: + Recommended line thickness in pixels. + + Examples: + ```pycon + >>> import supervision as sv + >>> sv.calculate_optimal_line_thickness((1920, 1080)) + 4 + >>> sv.calculate_optimal_line_thickness((640, 480)) + 2 + + ``` + """ + if min(resolution_wh) < 1080: + return 2 + return 4 diff --git a/.venv/lib/python3.12/site-packages/supervision/geometry/__init__.py b/.venv/lib/python3.12/site-packages/supervision/geometry/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/supervision/geometry/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/geometry/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e20a06665e0c83af82484379835147420fa7f248 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/geometry/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/geometry/__pycache__/core.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/geometry/__pycache__/core.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..67439fe955c88aa1e84c40cc45a409362653eb3d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/geometry/__pycache__/core.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/geometry/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/geometry/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..81f0d5bed84fee2592e6853108e48626afc52c42 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/geometry/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/geometry/core.py b/.venv/lib/python3.12/site-packages/supervision/geometry/core.py new file mode 100644 index 0000000000000000000000000000000000000000..5f41e9bc30f3743fe5fe635d9428233a98f52a11 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/geometry/core.py @@ -0,0 +1,208 @@ +from __future__ import annotations + +from dataclasses import dataclass +from enum import Enum +from math import sqrt + + +class Position(Enum): + """ + Enum representing the position of an anchor point. + """ + + CENTER = "CENTER" + CENTER_LEFT = "CENTER_LEFT" + CENTER_RIGHT = "CENTER_RIGHT" + TOP_CENTER = "TOP_CENTER" + TOP_LEFT = "TOP_LEFT" + TOP_RIGHT = "TOP_RIGHT" + BOTTOM_LEFT = "BOTTOM_LEFT" + BOTTOM_CENTER = "BOTTOM_CENTER" + BOTTOM_RIGHT = "BOTTOM_RIGHT" + CENTER_OF_MASS = "CENTER_OF_MASS" + + @classmethod + def list(cls) -> list[str]: + """Return all position values in their definition order.""" + return [position.value for position in cls] + + +@dataclass +class Point: + """ + Represents a point in 2D space. + + Attributes: + x: The x-coordinate of the point. + y: The y-coordinate of the point. + + Example: + ```pycon + >>> from supervision.geometry.core import Point + >>> point = Point(x=10.0, y=20.0) + >>> point.as_xy_int_tuple() + (10, 20) + >>> point.as_xy_float_tuple() + (10.0, 20.0) + + ``` + """ + + x: float + y: float + + def as_xy_int_tuple(self) -> tuple[int, int]: + """ + Returns the point as a tuple of integers. + + Returns: + The point as (x, y) integers. + """ + return int(self.x), int(self.y) + + def as_xy_float_tuple(self) -> tuple[float, float]: + """ + Returns the point as a tuple of floats. + + Returns: + The point as (x, y) floats. + """ + return self.x, self.y + + +@dataclass +class Vector: + """ + Represents a vector in 2D space, defined by a start and an end point. + + Attributes: + start: The starting point of the vector. + end: The end point of the vector. + + Example: + ```pycon + >>> from supervision.geometry.core import Point, Vector + >>> start_point = Point(x=0.0, y=0.0) + >>> end_point = Point(x=3.0, y=4.0) + >>> vector = Vector(start=start_point, end=end_point) + >>> vector.magnitude + 5.0 + >>> vector.center + Point(x=1.5, y=2.0) + + ``` + """ + + start: Point + end: Point + + @property + def magnitude(self) -> float: + """ + Calculate the magnitude (length) of the vector. + + Returns: + The magnitude of the vector. + """ + dx = self.end.x - self.start.x + dy = self.end.y - self.start.y + return sqrt(dx**2 + dy**2) + + @property + def center(self) -> Point: + """ + Calculate the center point of the vector. + + Returns: + The center point of the vector. + """ + return Point( + x=(self.start.x + self.end.x) / 2, + y=(self.start.y + self.end.y) / 2, + ) + + def cross_product(self, point: Point) -> float: + """ + Calculate the 2D cross product (also known as the vector product or outer + product) of the vector and a point, treated as vectors in 2D space. + + Args: + point: The point to be evaluated, treated as the endpoint of a + vector originating from the 'start' of the main vector. + + Returns: + The scalar value of the cross product. It is positive if 'point' + lies to the left of the vector (when moving from 'start' to 'end'), + negative if it lies to the right, and 0 if it is collinear with the + vector. + """ + dx_vector = self.end.x - self.start.x + dy_vector = self.end.y - self.start.y + dx_point = point.x - self.start.x + dy_point = point.y - self.start.y + return (dx_vector * dy_point) - (dy_vector * dx_point) + + +@dataclass +class Rect: + """ + Represents a rectangle in 2D space. + + Attributes: + x: The x-coordinate of the top-left corner of the rectangle. + y: The y-coordinate of the top-left corner of the rectangle. + width: The width of the rectangle. + height: The height of the rectangle. + + Example: + ```pycon + >>> from supervision.geometry.core import Rect + >>> rect = Rect(x=10.0, y=20.0, width=30.0, height=40.0) + >>> rect.top_left + Point(x=10.0, y=20.0) + >>> rect.bottom_right + Point(x=40.0, y=60.0) + >>> rect.as_xyxy_int_tuple() + (10, 20, 40, 60) + + ``` + """ + + x: float + y: float + width: float + height: float + + @classmethod + def from_xyxy(cls, xyxy: tuple[float, float, float, float]) -> Rect: + """Create a rectangle from `(x_min, y_min, x_max, y_max)` coordinates.""" + x1, y1, x2, y2 = xyxy + return cls(x=x1, y=y1, width=x2 - x1, height=y2 - y1) + + @property + def top_left(self) -> Point: + """Return the top-left corner as a `Point`.""" + return Point(x=self.x, y=self.y) + + @property + def bottom_right(self) -> Point: + """Return the bottom-right corner as a `Point`.""" + return Point(x=self.x + self.width, y=self.y + self.height) + + def pad(self, padding: int) -> Rect: + """Return a rectangle expanded by `padding` pixels on every side.""" + return Rect( + x=self.x - padding, + y=self.y - padding, + width=self.width + 2 * padding, + height=self.height + 2 * padding, + ) + + def as_xyxy_int_tuple(self) -> tuple[int, int, int, int]: + """Return `(x_min, y_min, x_max, y_max)` coordinates as integers.""" + return ( + int(self.x), + int(self.y), + int(self.x + self.width), + int(self.y + self.height), + ) diff --git a/.venv/lib/python3.12/site-packages/supervision/geometry/utils.py b/.venv/lib/python3.12/site-packages/supervision/geometry/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7a6db11efd0396989ba363cc3e4ff2eb24567701 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/geometry/utils.py @@ -0,0 +1,56 @@ +import numpy as np +import numpy.typing as npt + +from supervision.geometry.core import Point + + +def get_polygon_center(polygon: npt.NDArray[np.number]) -> Point: + """ + Calculate the center of a polygon. The center is calculated as the center + of the solid figure formed by the points of the polygon + + Args: + polygon: A 2-dimensional numpy ndarray representing the vertices of the + polygon. + + Returns: + The center of the polygon, represented as a Point object with x and y + attributes. + + Raises: + ValueError: If the polygon has no vertices. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> polygon = np.array([[0, 0], [0, 2], [2, 2], [2, 0]]) + >>> center = sv.get_polygon_center(polygon=polygon) + >>> float(center.x) + 1.0 + >>> float(center.y) + 1.0 + + ``` + """ + + # This is one of the 3 candidate algorithms considered for centroid calculation. + # For a more detailed discussion, see PR #1084 and commit eb33176 + + if len(polygon) == 0: + raise ValueError("Polygon must have at least one vertex.") + + origin = polygon[0].astype(np.float64, copy=False) + polygon = polygon.astype(np.float64, copy=False) - origin + shift_polygon = np.roll(polygon, -1, axis=0) + signed_areas = ( + polygon[..., 0] * shift_polygon[..., 1] + - polygon[..., 1] * shift_polygon[..., 0] + ) / 2 + if signed_areas.sum() == 0: + center = (np.mean(polygon, axis=0) + origin).round() + return Point(x=center[0], y=center[1]) + centroids = (polygon + shift_polygon) / 3.0 + center = (np.average(centroids, axis=0, weights=signed_areas) + origin).round() + + return Point(x=center[0], y=center[1]) diff --git a/.venv/lib/python3.12/site-packages/supervision/key_points/__init__.py b/.venv/lib/python3.12/site-packages/supervision/key_points/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/supervision/key_points/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/key_points/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..535df136293d660fd48cb8039534d17fb87cfba4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/key_points/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/key_points/__pycache__/annotators.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/key_points/__pycache__/annotators.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e96d7ae1d1b74e9d597027981d4e8a92beb69989 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/key_points/__pycache__/annotators.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/key_points/__pycache__/core.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/key_points/__pycache__/core.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d5100cc1b50df867c72d17ff0c7dd39303ce8442 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/key_points/__pycache__/core.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/key_points/__pycache__/skeletons.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/key_points/__pycache__/skeletons.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..197d70585240ab1490fee77fb4fb6c6461ec96e3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/key_points/__pycache__/skeletons.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/key_points/annotators.py b/.venv/lib/python3.12/site-packages/supervision/key_points/annotators.py new file mode 100644 index 0000000000000000000000000000000000000000..b61e87212d908005ed5066599ca1c640cb3db44b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/key_points/annotators.py @@ -0,0 +1,1016 @@ +from abc import ABC, abstractmethod +from collections.abc import Sequence +from typing import cast + +import numpy as np +import numpy.typing as npt + +from supervision import _cv2 as cv2 +from supervision.detection.utils.boxes import pad_boxes, spread_out_boxes +from supervision.draw.base import ImageType +from supervision.draw.color import Color +from supervision.draw.utils import draw_rounded_rectangle +from supervision.geometry.core import Rect +from supervision.key_points.core import KeyPoints +from supervision.key_points.skeletons import SKELETONS_BY_VERTEX_COUNT +from supervision.utils.conversion import ensure_cv2_image_for_class_method +from supervision.utils.logger import _get_logger + +logger = _get_logger(__name__) + + +def _validate_edge_indices(edge: tuple[int, int], vertex_count: int) -> tuple[int, int]: + """Validate 1-based skeleton edges and return zero-based vertex indexes.""" + vertex_a, vertex_b = edge + if not (1 <= vertex_a <= vertex_count and 1 <= vertex_b <= vertex_count): + raise ValueError( + "Edge indices must use the 1-based convention and be within the " + f"available keypoint range [1, {vertex_count}], got {edge}." + ) + # Public skeleton definitions are 1-based; keypoint arrays are zero-based. + return vertex_a - 1, vertex_b - 1 + + +def _has_finite_coordinates(point: npt.ArrayLike) -> bool: + """Report whether a keypoint carries coordinates that can be rasterized. + + Pose estimators mark an undetected or occluded keypoint with `NaN` rather than + dropping it, and `KeyPoints` accepts those values, so annotators receive them + routinely. Every drawing helper below converts a coordinate to `int`, which + raises on `NaN` and on an infinity, and `np.allclose(point, 0)` does not catch + either. `KeyPoints.as_detections` already excludes non-finite coordinates; this + keeps the annotators on the same rule instead of aborting the whole frame. + """ + return bool(np.isfinite(point).all()) + + +class BaseKeyPointAnnotator(ABC): + @abstractmethod + def annotate(self, scene: ImageType, key_points: KeyPoints) -> ImageType: + pass + + +class VertexAnnotator(BaseKeyPointAnnotator): + """ + A class that specializes in drawing skeleton vertices on images. It uses + specified key points to determine the locations where the vertices should be + drawn. + """ + + def __init__( + self, + color: Color = Color.ROBOFLOW, + radius: int = 4, + ) -> None: + """ + Args: + color: The color to use for annotating key points. + radius: The radius of the circles used to represent the key points. + """ + self.color = color + self.radius = radius + + @ensure_cv2_image_for_class_method + def annotate(self, scene: ImageType, key_points: KeyPoints) -> ImageType: + """Annotates the given scene with skeleton vertices based on the provided key + points. It draws circles at each key point location. Anchors marked as not + visible via ``key_points.visible``, and anchors whose coordinates are not + finite, are skipped. + + Args: + scene: The image where skeleton vertices will be drawn. `ImageType` is a + flexible type, accepting either `numpy.ndarray` or `PIL.Image.Image`. + key_points: A collection of key points where each key point consists of x + and y coordinates. + + Returns: + The annotated image, matching the type of `scene` (`numpy.ndarray` + or `PIL.Image.Image`) + + Raises: + TypeError: If `scene` is not a `numpy.ndarray` or `PIL.Image.Image`. + + Example: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> image = np.zeros((800, 800, 3), dtype=np.uint8) + >>> key_points = sv.KeyPoints( + ... xy=np.array( + ... [[[400, 200], [300, 500], [500, 500]]], + ... dtype=np.float32, + ... ), + ... class_id=np.array([0]), + ... visible=np.array([[True, True, True]]), + ... ) + >>> annotator = sv.VertexAnnotator( + ... color=sv.Color.ROBOFLOW, radius=10 + ... ) + >>> result = annotator.annotate(image.copy(), key_points) + + ``` + """ + if len(key_points) == 0: + return scene + + for detection_index, xy in enumerate(key_points.xy): + for point_index, (x, y) in enumerate(xy): + if np.allclose((x, y), 0) or not _has_finite_coordinates((x, y)): + continue + if ( + key_points.visible is not None + and not key_points.visible[detection_index, point_index] + ): + continue + cv2.circle( + img=scene, + center=(int(x), int(y)), + radius=self.radius, + color=self.color.as_bgr(), + thickness=-1, + ) + + return scene + + +class EdgeAnnotator(BaseKeyPointAnnotator): + """ + A class that specializes in drawing skeleton edges on images using specified key + points. It connects key points with lines to form the skeleton structure. + """ + + def __init__( + self, + color: Color = Color.ROBOFLOW, + thickness: int = 2, + edges: ( + Sequence[tuple[int, int]] | dict[int, Sequence[tuple[int, int]]] | None + ) = None, + ) -> None: + """ + Args: + color: The color to use for the edges. + thickness: The thickness of the edges. + edges: The edges to draw. If set to ``None``, will attempt to + auto-detect the skeleton by vertex count. A + ``Sequence[tuple[int, int]]`` applies a single skeleton to + every instance. A ``dict[int, Sequence[tuple[int, int]]]`` + maps ``class_id`` to skeleton edges, enabling correct + rendering for datasets with multiple skeleton types. + """ + self.color = color + self.thickness = thickness + self.edges = edges + + @ensure_cv2_image_for_class_method + def annotate(self, scene: ImageType, key_points: KeyPoints) -> ImageType: + """Annotates the given scene by drawing lines between specified key points to + form edges. Edges where either endpoint is marked as not visible via + ``key_points.visible``, or where either endpoint has a non-finite coordinate, + are skipped. + + Args: + scene: The image where skeleton edges will be drawn. `ImageType` is a + flexible type, accepting either `numpy.ndarray` or `PIL.Image.Image`. + key_points: A collection of key points where each key point consists of x + and y coordinates. + + Returns: + The annotated image, matching the type of `scene` (`numpy.ndarray` + or `PIL.Image.Image`) + + Raises: + TypeError: If `scene` is not a `numpy.ndarray` or `PIL.Image.Image`. + + Example: + Single-skeleton example: + + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> image = np.zeros((800, 800, 3), dtype=np.uint8) + >>> key_points = sv.KeyPoints( + ... xy=np.array( + ... [[[400, 200], [300, 500], [500, 500]]], + ... dtype=np.float32, + ... ), + ... class_id=np.array([0]), + ... visible=np.array([[True, True, True]]), + ... ) + >>> annotator = sv.EdgeAnnotator( + ... color=sv.Color.ROBOFLOW, + ... thickness=3, + ... edges=[(1, 2), (1, 3)], + ... ) + >>> result = annotator.annotate(image.copy(), key_points) + + ``` + + Multi-skeleton example with per-class edges: + + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> image = np.zeros((800, 800, 3), dtype=np.uint8) + >>> key_points = sv.KeyPoints( + ... xy=np.array( + ... [[[400, 200], [300, 500], [500, 500]], + ... [[700, 300], [650, 500], [0, 0]]], + ... dtype=np.float32, + ... ), + ... class_id=np.array([0, 1]), + ... visible=np.array( + ... [[True, True, True], + ... [True, True, False]], + ... ), + ... ) + >>> annotator = sv.EdgeAnnotator( + ... color=sv.Color.ROBOFLOW, + ... thickness=3, + ... edges={0: [(1, 2), (1, 3)], 1: [(1, 2)]}, + ... ) + >>> result = annotator.annotate(image.copy(), key_points) + + ``` + """ + if len(key_points) == 0: + return scene + + for detection_index, xy in enumerate(key_points.xy): + if isinstance(self.edges, dict): + class_id = ( + int(key_points.class_id[detection_index]) + if key_points.class_id is not None + else None + ) + if class_id is None: + raise ValueError( + "edges is a dict but class_id is None; " + "KeyPoints must have class_id set." + ) + if class_id not in self.edges: + raise ValueError(f"No edges defined for class_id={class_id}.") + edges = self.edges[class_id] + elif self.edges: + edges = self.edges + else: + _looked_up = SKELETONS_BY_VERTEX_COUNT.get(len(xy)) + if not _looked_up: + logger.warning("No skeleton found with %d vertices", len(xy)) + continue + edges = _looked_up + + for edge in edges: + idx_a, idx_b = _validate_edge_indices(edge=edge, vertex_count=len(xy)) + xy_a = xy[idx_a] + xy_b = xy[idx_b] + if np.allclose(xy_a, 0) or np.allclose(xy_b, 0): + continue + if not _has_finite_coordinates(xy_a) or not _has_finite_coordinates( + xy_b + ): + continue + if key_points.visible is not None: + if ( + not key_points.visible[detection_index, idx_a] + or not key_points.visible[detection_index, idx_b] + ): + continue + + cv2.line( + img=scene, + pt1=(int(xy_a[0]), int(xy_a[1])), + pt2=(int(xy_b[0]), int(xy_b[1])), + color=self.color.as_bgr(), + thickness=self.thickness, + ) + + return scene + + +class _BaseVertexEllipseAnnotator(BaseKeyPointAnnotator): + """Private base for ellipse-based keypoint annotators. + + Handles sigma/color validation, sorting, covariance extraction and + eigendecomposition shared by all VertexEllipse* variants. + """ + + def __init__( + self, + sigma: float | Sequence[float] = (1.0, 2.0, 3.0), + color: Color | Sequence[Color] = (Color.GREEN, Color.YELLOW, Color.RED), + max_axis: float | None = None, + ) -> None: + sigma_seq: Sequence[float] = ( + (sigma,) if isinstance(sigma, (int, float)) else sigma + ) + color_seq: Sequence[Color] = (color,) if isinstance(color, Color) else color + + if len(sigma_seq) == 0: + raise ValueError("sigma must contain at least one value") + if any(s <= 0 for s in sigma_seq): + raise ValueError("All sigma values must be positive") + if max_axis is not None and max_axis <= 0: + raise ValueError("max_axis must be positive when provided") + if len(color_seq) != len(sigma_seq): + raise ValueError( + f"color length ({len(color_seq)}) must match " + f"sigma length ({len(sigma_seq)})" + ) + + sorted_indices = sorted( + range(len(sigma_seq)), key=lambda i: sigma_seq[i], reverse=True + ) + self.sigma = [sigma_seq[i] for i in sorted_indices] + self.color = [color_seq[i] for i in sorted_indices] + self.max_axis = max_axis + + def _get_covariances(self, key_points: KeyPoints) -> npt.NDArray[np.float32]: + covariances = key_points.data.get("covariance") + if covariances is None: + raise ValueError( + "key_points.data must contain 'covariance' with shape (N, K, 2, 2)." + ) + covariances_array = cast( + npt.NDArray[np.float32], np.asarray(covariances, dtype=np.float32) + ) + expected_shape = (*key_points.xy.shape[:2], 2, 2) + if covariances_array.shape != expected_shape: + raise ValueError( + f"Expected covariance shape {expected_shape}, " + f"got {covariances_array.shape}." + ) + return covariances_array + + def _decompose_covariance( + self, covariance: npt.NDArray[np.float32] + ) -> tuple[npt.NDArray[np.float64], npt.NDArray[np.float64]] | None: + """Eigendecompose a 2x2 covariance, returning sorted (eigenvalues, vectors).""" + if not np.isfinite(covariance).all(): + return None + try: + eigenvalues, eigenvectors = np.linalg.eigh(covariance.astype(np.float64)) + except np.linalg.LinAlgError: + return None + if not np.isfinite(eigenvalues).all() or np.any(eigenvalues <= 0): + return None + order = np.argsort(eigenvalues)[::-1] + return eigenvalues[order], eigenvectors[:, order] + + def _iter_ellipse_params( + self, key_points: KeyPoints + ) -> list[list[tuple[tuple[int, int], tuple[int, int], float, float, Color]]]: + """Return ellipse params grouped by sigma level (outermost first).""" + covariances = self._get_covariances(key_points) + levels: list[ + list[tuple[tuple[int, int], tuple[int, int], float, float, Color]] + ] = [[] for _ in self.sigma] + for detection_index, xy in enumerate(key_points.xy): + for point_index, (x, y) in enumerate(xy): + if np.allclose((x, y), 0) or not _has_finite_coordinates((x, y)): + continue + if ( + key_points.visible is not None + and not key_points.visible[detection_index, point_index] + ): + continue + covariance = covariances[detection_index, point_index] + decomposition = self._decompose_covariance(covariance) + if decomposition is None: + continue + eigenvalues, eigenvectors = decomposition + angle = float( + np.degrees(np.arctan2(eigenvectors[1, 0], eigenvectors[0, 0])) + ) + center = (round(x), round(y)) + for level_idx, (sigma, color) in enumerate(zip(self.sigma, self.color)): + axes = sigma * np.sqrt(eigenvalues) + if self.max_axis is not None: + axes = np.minimum(axes, self.max_axis) + axis_lengths = ( + max(1, round(axes[0])), + max(1, round(axes[1])), + ) + levels[level_idx].append( + (center, axis_lengths, angle, sigma, color) + ) + return levels + + +class VertexEllipseAreaAnnotator(_BaseVertexEllipseAnnotator): + """ + Draws filled semi-transparent covariance ellipses at multiple sigma levels + around each keypoint, each ring in a different color. This produces a + bullseye-like uncertainty visualization where inner rings represent higher + probability density. + + !!! warning + + This annotator uses `key_points.data["covariance"]` with shape + `(N, K, 2, 2)` in pixel coordinates. + """ + + def __init__( + self, + sigma: float | Sequence[float] = (1.0, 2.0, 3.0), + color: Color | Sequence[Color] = (Color.GREEN, Color.YELLOW, Color.RED), + opacity: float = 0.4, + max_axis: float | None = None, + ) -> None: + """ + Args: + sigma: Sigma multipliers for each ring, drawn from outermost to + innermost. Accepts a single float or a sequence of floats. + Defaults to ``(1.0, 2.0, 3.0)``. + color: The color for each sigma level. Accepts a single + ``Color`` or a sequence of colors (one per sigma level). + Defaults to ``(Color.GREEN, Color.YELLOW, Color.RED)``. + opacity: Opacity of the overlay mask. Must be between ``0`` and + ``1``. + max_axis: Optional cap for ellipse semi-axis lengths in pixels. + """ + super().__init__(sigma=sigma, color=color, max_axis=max_axis) + self.opacity = opacity + + @ensure_cv2_image_for_class_method + def annotate(self, scene: ImageType, key_points: KeyPoints) -> ImageType: + """Draws filled semi-transparent covariance ellipses around each keypoint. + Keypoints marked as not visible via ``key_points.visible``, and keypoints whose + coordinates are not finite, are skipped. + + Args: + scene: The image to annotate. ``ImageType`` accepts either + ``numpy.ndarray`` or ``PIL.Image.Image``. + key_points: Key points with covariance data in + ``key_points.data["covariance"]``. + + Returns: + The annotated image, matching the type of ``scene``. + + Raises: + TypeError: If `scene` is not a `numpy.ndarray` or `PIL.Image.Image`. + + Example: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> image = np.zeros((800, 800, 3), dtype=np.uint8) + >>> key_points = sv.KeyPoints( + ... xy=np.array( + ... [[[400, 200], [300, 500], [500, 500]]], + ... dtype=np.float32, + ... ), + ... class_id=np.array([0]), + ... visible=np.array([[True, True, True]]), + ... data={ + ... "covariance": np.array( + ... [[[[800, 0], [0, 400]], + ... [[400, 0], [0, 800]], + ... [[600, 0], [0, 600]]]], + ... dtype=np.float32, + ... ) + ... }, + ... ) + >>> annotator = sv.VertexEllipseAreaAnnotator( + ... sigma=[1.0, 2.0], + ... color=[sv.Color.GREEN, sv.Color.RED], + ... ) + >>> result = annotator.annotate(image.copy(), key_points) + + ``` + """ + if len(key_points) == 0: + return scene + + overlay = scene.copy() + for level in self._iter_ellipse_params(key_points): + for center, axis_lengths, angle, _sigma, color in level: + cv2.ellipse( + img=overlay, + center=center, + axes=axis_lengths, + angle=angle, + startAngle=0, + endAngle=360, + color=color.as_bgr(), + thickness=-1, + lineType=cv2.LINE_AA, + ) + + cv2.addWeighted(overlay, self.opacity, scene, 1 - self.opacity, 0, dst=scene) + return scene + + +class VertexEllipseOutlineAnnotator(_BaseVertexEllipseAnnotator): + """ + Draws stroke-only concentric covariance ellipse rings at multiple sigma + levels around each keypoint. + + !!! warning + + This annotator uses `key_points.data["covariance"]` with shape + `(N, K, 2, 2)` in pixel coordinates. + """ + + def __init__( + self, + sigma: float | Sequence[float] = (1.0, 2.0, 3.0), + color: Color | Sequence[Color] = (Color.GREEN, Color.YELLOW, Color.RED), + thickness: int = 2, + max_axis: float | None = None, + ) -> None: + """ + Args: + sigma: Sigma multipliers for each ring, drawn from outermost to + innermost. Accepts a single float or a sequence of floats. + Defaults to ``(1.0, 2.0, 3.0)``. + color: The color for each sigma level. Accepts a single + ``Color`` or a sequence of colors (one per sigma level). + Defaults to ``(Color.GREEN, Color.YELLOW, Color.RED)``. + thickness: Line thickness of the ellipse outlines. + max_axis: Optional cap for ellipse semi-axis lengths in pixels. + """ + super().__init__(sigma=sigma, color=color, max_axis=max_axis) + self.thickness = thickness + + @ensure_cv2_image_for_class_method + def annotate(self, scene: ImageType, key_points: KeyPoints) -> ImageType: + """Draws stroke-only covariance ellipse outlines around each keypoint. Keypoints + marked as not visible via ``key_points.visible``, and keypoints whose + coordinates are not finite, are skipped. + + Args: + scene: The image to annotate. ``ImageType`` accepts either + ``numpy.ndarray`` or ``PIL.Image.Image``. + key_points: Key points with covariance data in + ``key_points.data["covariance"]``. + + Returns: + The annotated image, matching the type of ``scene``. + + Raises: + TypeError: If `scene` is not a `numpy.ndarray` or `PIL.Image.Image`. + + Example: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> image = np.zeros((800, 800, 3), dtype=np.uint8) + >>> key_points = sv.KeyPoints( + ... xy=np.array( + ... [[[400, 200], [300, 500], [500, 500]]], + ... dtype=np.float32, + ... ), + ... class_id=np.array([0]), + ... visible=np.array([[True, True, True]]), + ... data={ + ... "covariance": np.array( + ... [[[[800, 0], [0, 400]], + ... [[400, 0], [0, 800]], + ... [[600, 0], [0, 600]]]], + ... dtype=np.float32, + ... ) + ... }, + ... ) + >>> annotator = sv.VertexEllipseOutlineAnnotator( + ... sigma=[1.0, 2.0], + ... color=[sv.Color.GREEN, sv.Color.RED], + ... thickness=2, + ... ) + >>> result = annotator.annotate(image.copy(), key_points) + + ``` + """ + if len(key_points) == 0: + return scene + + for level in self._iter_ellipse_params(key_points): + for center, axis_lengths, angle, _sigma, color in level: + cv2.ellipse( + img=scene, + center=center, + axes=axis_lengths, + angle=angle, + startAngle=0, + endAngle=360, + color=color.as_bgr(), + thickness=self.thickness, + lineType=cv2.LINE_AA, + ) + + return scene + + +class VertexEllipseHaloAnnotator(_BaseVertexEllipseAnnotator): + """ + Draws filled covariance ellipses with a radial fade: full opacity at the + center, smoothly falling off to zero at the ellipse boundary. The falloff + follows a power curve controlled by ``decay``, producing a soft glow that + is strongest near the keypoint. + + !!! warning + + This annotator uses `key_points.data["covariance"]` with shape + `(N, K, 2, 2)` in pixel coordinates. + """ + + _DECAY: float = 2.0 + + def __init__( + self, + sigma: float | Sequence[float] = (1.0, 2.0, 3.0), + color: Color | Sequence[Color] = (Color.GREEN, Color.YELLOW, Color.RED), + opacity: float = 0.6, + max_axis: float | None = None, + ) -> None: + """ + Args: + sigma: Sigma multipliers for each ring, drawn from outermost to + innermost. Accepts a single float or a sequence of floats. + Defaults to ``(1.0, 2.0, 3.0)``. + color: The color for each sigma level. Accepts a single + ``Color`` or a sequence of colors (one per sigma level). + Defaults to ``(Color.GREEN, Color.YELLOW, Color.RED)``. + opacity: Peak opacity at the ellipse center. Must be between ``0`` + and ``1``. + max_axis: Optional cap for ellipse semi-axis lengths in pixels. + """ + super().__init__(sigma=sigma, color=color, max_axis=max_axis) + self.opacity = opacity + + @ensure_cv2_image_for_class_method + def annotate(self, scene: ImageType, key_points: KeyPoints) -> ImageType: + """Draws radially-fading covariance ellipses around each keypoint. Keypoints + marked as not visible via ``key_points.visible``, and keypoints whose + coordinates are not finite, are skipped. + + Args: + scene: The image to annotate. ``ImageType`` accepts either + ``numpy.ndarray`` or ``PIL.Image.Image``. + key_points: Key points with covariance data in + ``key_points.data["covariance"]``. + + Returns: + The annotated image, matching the type of ``scene``. + + Raises: + TypeError: If `scene` is not a `numpy.ndarray` or `PIL.Image.Image`. + + Example: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> image = np.zeros((800, 800, 3), dtype=np.uint8) + >>> key_points = sv.KeyPoints( + ... xy=np.array( + ... [[[400, 200], [300, 500], [500, 500]]], + ... dtype=np.float32, + ... ), + ... class_id=np.array([0]), + ... visible=np.array([[True, True, True]]), + ... data={ + ... "covariance": np.array( + ... [[[[800, 0], [0, 400]], + ... [[400, 0], [0, 800]], + ... [[600, 0], [0, 600]]]], + ... dtype=np.float32, + ... ) + ... }, + ... ) + >>> annotator = sv.VertexEllipseHaloAnnotator( + ... sigma=[1.0, 2.0], + ... color=[sv.Color.GREEN, sv.Color.RED], + ... ) + >>> result = annotator.annotate(image.copy(), key_points) + + ``` + """ + if len(key_points) == 0: + return scene + + h, w = scene.shape[:2] + composite: npt.NDArray[np.float32] = scene.astype(np.float32) + + for level in self._iter_ellipse_params(key_points): + for center, axis_lengths, angle, _sigma, color in level: + ax, ay = axis_lengths + if ax == 0 or ay == 0: + continue + + pad = 2 + roi_half_w = ax + pad + roi_half_h = ay + pad + cx, cy = center + + x_min = max(cx - roi_half_w, 0) + x_max = min(cx + roi_half_w, w) + y_min = max(cy - roi_half_h, 0) + y_max = min(cy + roi_half_h, h) + if x_min >= x_max or y_min >= y_max: + continue + + ys = np.arange(y_min, y_max, dtype=np.float32) - cy + xs = np.arange(x_min, x_max, dtype=np.float32) - cx + grid_x, grid_y = np.meshgrid(xs, ys) + + angle_rad = np.radians(-angle) + cos_a = np.cos(angle_rad) + sin_a = np.sin(angle_rad) + rx = grid_x * cos_a - grid_y * sin_a + ry = grid_x * sin_a + grid_y * cos_a + + dist_sq = (rx / ax) ** 2 + (ry / ay) ** 2 + inside = dist_sq <= 1.0 + + falloff = np.zeros_like(dist_sq) + falloff[inside] = (1.0 - dist_sq[inside]) ** self._DECAY + + scaled_alpha = falloff * self.opacity + + bgr = np.array(color.as_bgr(), dtype=np.float32) + roi = composite[y_min:y_max, x_min:x_max] + alpha_3 = scaled_alpha[:, :, np.newaxis] + roi[:] = roi * (1 - alpha_3) + bgr * alpha_3 + + np.copyto(scene, composite.astype(np.uint8)) + return scene + + +VertexEllipseAnnotator = VertexEllipseAreaAnnotator + + +class VertexLabelAnnotator: + """ + A class that draws labels of skeleton vertices on images. It uses specified key + points to determine the locations where the vertices should be drawn. + """ + + def __init__( + self, + color: Color | list[Color] = Color.ROBOFLOW, + text_color: Color | list[Color] = Color.WHITE, + text_scale: float = 0.5, + text_thickness: int = 1, + text_padding: int = 10, + border_radius: int = 0, + smart_position: bool = False, + ): + """ + Args: + color: The color to use for each keypoint label. If a list is + provided, the colors will be used in order for each keypoint. + text_color: The color to use for the labels. If a list is + provided, the colors will be used in order for each keypoint. + text_scale: The scale of the text. + text_thickness: The thickness of the text. + text_padding: The padding around the text. + border_radius: The radius of the rounded corners of the boxes. + Set to a high value to produce circles. + smart_position: Spread out the labels to avoid overlap. + """ + self.border_radius: int = border_radius + self.color: Color | list[Color] = color + self.text_color: Color | list[Color] = text_color + self.text_scale: float = text_scale + self.text_thickness: int = text_thickness + self.text_padding: int = text_padding + self.smart_position = smart_position + + @ensure_cv2_image_for_class_method + def annotate( + self, + scene: ImageType, + key_points: KeyPoints, + labels: list[str] | dict[int, list[str]] | None = None, + ) -> ImageType: + """Draws labels at skeleton vertex positions on the image. Vertices marked not + visible via ``key_points.visible``, and vertices whose coordinates are not + finite, are skipped. + + Args: + scene: The image where vertex labels will be drawn. `ImageType` is a + flexible type, accepting either `numpy.ndarray` or `PIL.Image.Image`. + key_points: A collection of key points where each key point consists of x + and y coordinates. + labels: Labels to display at each keypoint. If ``None``, keypoint + indices are used. A ``list[str]`` applies the same labels to + every instance. A ``dict[int, list[str]]`` maps ``class_id`` + to per-class label lists, enabling correct labeling for + datasets with multiple skeleton types. + + Returns: + The annotated image, matching the type of `scene` (`numpy.ndarray` + or `PIL.Image.Image`) + + Raises: + TypeError: If `scene` is not a `numpy.ndarray` or `PIL.Image.Image`. + + Example: + Single-skeleton example: + + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> image = np.zeros((800, 800, 3), dtype=np.uint8) + >>> key_points = sv.KeyPoints( + ... xy=np.array( + ... [[[400, 200], [300, 500], [500, 500]]], + ... dtype=np.float32, + ... ), + ... class_id=np.array([0]), + ... visible=np.array([[True, True, True]]), + ... ) + >>> annotator = sv.VertexLabelAnnotator( + ... color=sv.Color.ROBOFLOW, + ... text_color=sv.Color.WHITE, + ... border_radius=5, + ... ) + >>> result = annotator.annotate( + ... scene=image.copy(), + ... key_points=key_points, + ... labels=["head", "L-foot", "R-foot"], + ... ) + + ``` + + Multi-skeleton example with per-class labels: + + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> image = np.zeros((800, 800, 3), dtype=np.uint8) + >>> key_points = sv.KeyPoints( + ... xy=np.array( + ... [[[400, 200], [300, 500], [500, 500]], + ... [[700, 300], [650, 500], [0, 0]]], + ... dtype=np.float32, + ... ), + ... class_id=np.array([0, 1]), + ... visible=np.array( + ... [[True, True, True], + ... [True, True, False]], + ... ), + ... ) + >>> annotator = sv.VertexLabelAnnotator( + ... color=sv.Color.ROBOFLOW, + ... text_color=sv.Color.WHITE, + ... border_radius=5, + ... ) + >>> result = annotator.annotate( + ... scene=image.copy(), + ... key_points=key_points, + ... labels={ + ... 0: ["head", "L-foot", "R-foot"], + ... 1: ["top", "bottom", "pad"], + ... }, + ... ) + + ``` + """ + font = cv2.FONT_HERSHEY_SIMPLEX + + skeletons_count, points_count, _ = key_points.xy.shape + if skeletons_count == 0: + return scene + + all_anchors: list[tuple[int, int]] = [] + all_labels: list[str] = [] + all_colors: list[Color] = [] + all_text_colors: list[Color] = [] + + for i in range(skeletons_count): + xy = key_points.xy[i] + + class_id = ( + int(key_points.class_id[i]) if key_points.class_id is not None else None + ) + instance_labels = self._resolve_labels(labels, points_count, class_id) + instance_colors = self._resolve_color_list(self.color, points_count) + instance_text_colors = self._resolve_color_list( + self.text_color, points_count + ) + + for j in range(points_count): + if not _has_finite_coordinates(xy[j]): + continue + if key_points.visible is not None: + if not key_points.visible[i, j]: + continue + elif np.allclose(xy[j], 0): + continue + + anchor = (int(xy[j][0]), int(xy[j][1])) + all_anchors.append(anchor) + all_labels.append(instance_labels[j]) + all_colors.append(instance_colors[j]) + all_text_colors.append(instance_text_colors[j]) + + if not all_anchors: + return scene + + xyxy = np.array( + [ + self.get_text_bounding_box( + text=label, + font=font, + text_scale=self.text_scale, + text_thickness=self.text_thickness, + center_coordinates=anchor, + ) + for anchor, label in zip(all_anchors, all_labels) + ] + ) + xyxy_padded = pad_boxes(xyxy=xyxy, px=self.text_padding) + + if self.smart_position: + xyxy_padded = spread_out_boxes(xyxy_padded) + xyxy = pad_boxes(xyxy=xyxy_padded, px=-self.text_padding) + + for text, color, text_color, box, box_padded in zip( + all_labels, all_colors, all_text_colors, xyxy, xyxy_padded + ): + draw_rounded_rectangle( + scene=scene, + rect=Rect.from_xyxy(box_padded), + color=color, + border_radius=self.border_radius, + ) + cv2.putText( + img=scene, + text=text, + org=(box[0], box[3]), + fontFace=font, + fontScale=self.text_scale, + color=text_color.as_bgr(), + thickness=self.text_thickness, + lineType=cv2.LINE_AA, + ) + + return scene + + @staticmethod + def get_text_bounding_box( + text: str, + font: int, + text_scale: float, + text_thickness: int, + center_coordinates: tuple[int, int], + ) -> tuple[int, int, int, int]: + text_w, text_h = cv2.getTextSize( + text=text, + fontFace=font, + fontScale=text_scale, + thickness=text_thickness, + )[0] + center_x, center_y = center_coordinates + return ( + center_x - text_w // 2, + center_y - text_h // 2, + center_x + text_w // 2, + center_y + text_h // 2, + ) + + @staticmethod + def _resolve_labels( + labels: list[str] | dict[int, list[str]] | None, + points_count: int, + class_id: int | None = None, + ) -> list[str]: + """Return the label list for a single instance.""" + if labels is None: + return [str(j) for j in range(points_count)] + + resolved: list[str] + if isinstance(labels, dict): + if class_id is None: + raise ValueError( + "labels is a dict but class_id is None; " + "KeyPoints must have class_id set." + ) + if class_id not in labels: + raise ValueError(f"No labels defined for class_id={class_id}.") + resolved = labels[class_id] + else: + resolved = labels + + if len(resolved) != points_count: + raise ValueError( + f"Number of labels ({len(resolved)}) must match " + f"number of key points ({points_count})." + ) + return resolved + + @staticmethod + def _resolve_color_list( + colors: Color | list[Color], + points_count: int, + ) -> list[Color]: + """Return a per-keypoint color list for a single instance.""" + if isinstance(colors, list): + if len(colors) != points_count: + raise ValueError( + f"Number of colors ({len(colors)}) must match " + f"number of key points ({points_count})." + ) + return colors + return [colors] * points_count diff --git a/.venv/lib/python3.12/site-packages/supervision/key_points/core.py b/.venv/lib/python3.12/site-packages/supervision/key_points/core.py new file mode 100644 index 0000000000000000000000000000000000000000..6e25add99fb32f8044ea4e460feac9e7b1671b78 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/key_points/core.py @@ -0,0 +1,1499 @@ +from __future__ import annotations + +import logging +from collections.abc import Iterable, Iterator +from dataclasses import dataclass, field +from typing import Any, cast + +import numpy as np +import numpy.typing as npt + +from supervision.config import CLASS_NAME_DATA_FIELD +from supervision.detection.core import Detections +from supervision.detection.utils._typing import ( + _DetectionDataType, + _DetectionDataValueType, +) +from supervision.detection.utils.internal import ( + get_data_item, + is_data_equal, + merge_data, +) +from supervision.detection.utils.iou_and_nms import ( + OverlapMetric, + box_non_max_suppression, +) +from supervision.utils.internal import warn_deprecated +from supervision.validators import _validate_keypoints_fields + +logger = logging.getLogger(__name__) + +Index1D = ( + int | slice | list[int] | list[bool] | npt.NDArray[np.int_] | npt.NDArray[np.bool_] +) +Index2D = tuple[Index1D, Index1D] +_RowIndexInput = int | np.integer[Any] | npt.NDArray[np.generic] | list[Any] | slice +_NormalizedRowIndex = npt.NDArray[np.generic] | list[Any] | slice + + +def _optional_array_equal( + first: npt.NDArray[np.generic] | None, + second: npt.NDArray[np.generic] | None, +) -> bool: + if first is None or second is None: + return first is None and second is None + return np.array_equal(first, second) + + +def _normalize_row_index( + i: _RowIndexInput, +) -> _NormalizedRowIndex: + """Normalise *i* to a 1-D row index for 1-D per-object fields. + + Handles: + - Python int or np.integer scalar -> np.array([int(i)]) + - boolean np.ndarray (any shape) -> np.flatnonzero(i.ravel()) + - non-bool 0-d np.ndarray -> reshaped to shape (1,) + - list of bool -> np.flatnonzero(np.array(i)) + - slice, list of ints, 1-D ndarray -> returned as-is + """ + if isinstance(i, (int, np.integer)): + return cast(_NormalizedRowIndex, np.array([int(i)])) + if isinstance(i, np.ndarray) and i.dtype == bool: + return cast(_NormalizedRowIndex, np.flatnonzero(i.ravel())) + if isinstance(i, np.ndarray) and i.ndim == 0: + return cast(_NormalizedRowIndex, i.reshape(1)) + if isinstance(i, list) and i and all(isinstance(x, bool) for x in i): + return cast(_NormalizedRowIndex, np.flatnonzero(np.array(i))) + return i + + +@dataclass(init=False) +class KeyPoints: + """ + The `sv.KeyPoints` class in the Supervision library standardizes results from + various keypoint detection and pose estimation models into a consistent format. This + class simplifies data manipulation and filtering, providing a uniform API for + integration with Supervision [keypoints annotators](/latest/keypoint/annotators). + + === "RF-DETR" + + [RF-DETR](https://github.com/roboflow/rf-detr) keypoint models return + `sv.KeyPoints` directly from `model.predict()` — no additional + conversion is needed. + + ```python + from supervision import _cv2 as cv2 + import supervision as sv + from rfdetr import RFDETRKeypointPreview + + image = cv2.imread("") + model = RFDETRKeypointPreview() + + key_points = model.predict(image) + ``` + + === "Ultralytics" + + Use [`sv.KeyPoints.from_ultralytics`](/latest/keypoint/core/#supervision.key_points.core.KeyPoints.from_ultralytics) + method, which accepts [YOLOv8-pose](https://docs.ultralytics.com/models/yolov8/), [YOLO11-pose](https://docs.ultralytics.com/models/yolo11/) + [pose](https://docs.ultralytics.com/tasks/pose/) result. + + ```python + from supervision import _cv2 as cv2 + import supervision as sv + from ultralytics import YOLO + + image = cv2.imread("") + model = YOLO('yolo11s-pose.pt') + + result = model(image)[0] + key_points = sv.KeyPoints.from_ultralytics(result) + ``` + + === "Inference" + + Use [`sv.KeyPoints.from_inference`](/latest/keypoint/core/#supervision.key_points.core.KeyPoints.from_inference) + method, which accepts [Inference](https://inference.roboflow.com/) pose result. + + ```python + from supervision import _cv2 as cv2 + import supervision as sv + from inference import get_model + + image = cv2.imread("") + model = get_model(model_id="", api_key="") + + result = model.infer(image)[0] + key_points = sv.KeyPoints.from_inference(result) + ``` + + === "MediaPipe" + + Use [`sv.KeyPoints.from_mediapipe`](/latest/keypoint/core/#supervision.key_points.core.KeyPoints.from_mediapipe) + method, which accepts [MediaPipe](https://github.com/google-ai-edge/mediapipe) + pose result. + + + ```python + from supervision import _cv2 as cv2 + import mediapipe as mp + import supervision as sv + + image = cv2.imread("") + image_height, image_width, _ = image.shape + mediapipe_image = mp.Image( + image_format=mp.ImageFormat.SRGB, + data=cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) + + options = mp.tasks.vision.PoseLandmarkerOptions( + base_options=mp.tasks.BaseOptions( + model_asset_path="pose_landmarker_heavy.task" + ), + running_mode=mp.tasks.vision.RunningMode.IMAGE, + num_poses=2) + + PoseLandmarker = mp.tasks.vision.PoseLandmarker + with PoseLandmarker.create_from_options(options) as landmarker: + pose_landmarker_result = landmarker.detect(mediapipe_image) + + key_points = sv.KeyPoints.from_mediapipe( + pose_landmarker_result, (image_width, image_height)) + ``` + + === "Transformers" + + Use [`sv.KeyPoints.from_transformers`](/latest/keypoint/core/#supervision.key_points.core.KeyPoints.from_transformers) + method, which accepts [ViTPose](https://huggingface.co/docs/transformers/en/model_doc/vitpose) result. + + ```python + from PIL import Image + import requests + import supervision as sv + import torch + from transformers import ( + AutoProcessor, + RTDetrForObjectDetection, + VitPoseForPoseEstimation, + ) + + device = "cuda" if torch.cuda.is_available() else "cpu" + image = Image.open("") + + DETECTION_MODEL_ID = "PekingU/rtdetr_r50vd_coco_o365" + + detection_processor = AutoProcessor.from_pretrained(DETECTION_MODEL_ID, use_fast=True) + detection_model = RTDetrForObjectDetection.from_pretrained(DETECTION_MODEL_ID, device_map=DEVICE) + + inputs = detection_processor(images=frame, return_tensors="pt").to(DEVICE) + + with torch.no_grad(): + outputs = detection_model(**inputs) + + target_size = torch.tensor([(frame.height, frame.width)]) + results = detection_processor.post_process_object_detection( + outputs, target_sizes=target_size, threshold=0.3) + + detections = sv.Detections.from_transformers(results[0]) + boxes = sv.xyxy_to_xywh(detections[detections.class_id == 0].xyxy) + + POSE_ESTIMATION_MODEL_ID = "usyd-community/vitpose-base-simple" + + pose_estimation_processor = AutoProcessor.from_pretrained(POSE_ESTIMATION_MODEL_ID) + pose_estimation_model = VitPoseForPoseEstimation.from_pretrained( + POSE_ESTIMATION_MODEL_ID, device_map=DEVICE) + + inputs = pose_estimation_processor(frame, boxes=[boxes], return_tensors="pt").to(DEVICE) + + with torch.no_grad(): + outputs = pose_estimation_model(**inputs) + + results = pose_estimation_processor.post_process_pose_estimation(outputs, boxes=[boxes]) + key_point = sv.KeyPoints.from_transformers(results[0]) + ``` + + Attributes: + xy: An array of shape `(n, m, 2)` containing + `n` detected objects, each composed of `m` equally-sized + sets of key points, where each point is `[x, y]`. + class_id: An array of shape + `(n,)` containing the class ids of the detected objects. + keypoint_confidence: An array of shape + `(n, m)` containing the confidence scores of each keypoint. + detection_confidence: An array of shape + `(n,)` containing the detection-level confidence scores. + visible: An optional boolean array of shape + `(n, m)` indicating which keypoints are visible. When ``None``, + all keypoints are treated as visible. Set this to filter anchors + without removing data: ``key_points.visible = key_points.keypoint_confidence > 0.3``. + data: A dictionary containing additional + data where each key is a string representing the data type, and the value + is either a NumPy array or a list of corresponding data of length `n` + (one entry per detected object). + """ # noqa: E501 // docs + + xy: npt.NDArray[np.float32] + class_id: npt.NDArray[np.int_] | None = None + keypoint_confidence: npt.NDArray[np.float32] | None = None + detection_confidence: npt.NDArray[np.float32] | None = None + visible: npt.NDArray[np.bool_] | None = None + data: _DetectionDataType = field(default_factory=dict) + + def __init__( + self, + xy: npt.NDArray[np.float32], + class_id: npt.NDArray[np.int_] | None = None, + keypoint_confidence: npt.NDArray[np.float32] | None = None, + detection_confidence: npt.NDArray[np.float32] | None = None, + visible: npt.NDArray[np.bool_] | None = None, + data: _DetectionDataType | None = None, + *, + confidence: npt.NDArray[np.float32] | None = None, + ) -> None: + """Initialize KeyPoints. + + Args: + xy: Array of shape `(n, m, 2)` with keypoint coordinates. + class_id: Array of shape `(n,)` with class IDs. Defaults to None. + keypoint_confidence: Array of shape `(n, m)` with per-keypoint + confidence scores. Defaults to None. + detection_confidence: Array of shape `(n,)` with detection-level + confidence scores. Defaults to None. + visible: Boolean array of shape `(n, m)` indicating visible + keypoints. Defaults to None. + data: Dictionary of additional per-detection data arrays. + Defaults to an empty dict. + confidence: Deprecated since `0.29.0`, removed in `0.32.0`. + Use ``keypoint_confidence`` instead. Raises ``ValueError`` + if passed together with ``keypoint_confidence``. + + Raises: + ValueError: If both ``confidence`` and ``keypoint_confidence`` + are provided. + """ + if confidence is not None: + if keypoint_confidence is not None: + raise ValueError( + "Cannot pass both 'confidence' and 'keypoint_confidence'. " + "'confidence' is deprecated — use 'keypoint_confidence' only." + ) + warn_deprecated( + "'confidence' parameter in `KeyPoints()` is deprecated since " + "`0.29.0` and will be removed in `0.32.0`. Use " + "'keypoint_confidence' instead." + ) + keypoint_confidence = confidence + + self.xy = xy + self.class_id = class_id + self.keypoint_confidence = keypoint_confidence + self.detection_confidence = detection_confidence + self.visible = visible + self.data = data if data is not None else {} + self.__post_init__() + + def __post_init__(self) -> None: + _validate_keypoints_fields( + xy=self.xy, + class_id=self.class_id, + confidence=self.keypoint_confidence, + detection_confidence=self.detection_confidence, + visible=self.visible, + data=self.data, + ) + + @property + def confidence(self) -> npt.NDArray[np.float32] | None: + """Deprecated since 0.29.0. Use ``keypoint_confidence`` instead.""" + warn_deprecated( + "'KeyPoints.confidence' is deprecated since 0.29.0 and will be " + "removed in 0.32.0. Use 'KeyPoints.keypoint_confidence' instead." + ) + return self.keypoint_confidence + + @confidence.setter + def confidence(self, value: npt.NDArray[np.float32] | None) -> None: + warn_deprecated( + "'KeyPoints.confidence' is deprecated since 0.29.0 and will be " + "removed in 0.32.0. Use 'KeyPoints.keypoint_confidence' instead." + ) + self.keypoint_confidence = value + + def __len__(self) -> int: + """ + Returns the number of objects in the `sv.KeyPoints` object. + + Returns: + The number of objects. + + Example: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> xy = np.array([[[10, 20], [30, 40]]], dtype=np.float32) + >>> key_points = sv.KeyPoints(xy=xy) + >>> len(key_points) + 1 + + ``` + """ + return len(self.xy) + + def __iter__( + self, + ) -> Iterator[ + tuple[ + npt.NDArray[np.float32], + npt.NDArray[np.float32] | None, + npt.NDArray[np.int_] | None, + _DetectionDataType, + ] + ]: + """ + Iterates over the Keypoint object and yield a tuple of + `(xy, keypoint_confidence, class_id, data)` for each object detection. + """ + for i in range(len(self.xy)): + yield ( + self.xy[i], + self.keypoint_confidence[i] + if self.keypoint_confidence is not None + else None, + self.class_id[i] if self.class_id is not None else None, + get_data_item(self.data, i), + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, KeyPoints): + return NotImplemented + return all( + [ + np.array_equal(self.xy, other.xy), + _optional_array_equal(self.class_id, other.class_id), + _optional_array_equal( + self.keypoint_confidence, other.keypoint_confidence + ), + _optional_array_equal( + self.detection_confidence, other.detection_confidence + ), + _optional_array_equal(self.visible, other.visible), + is_data_equal(self.data, other.data), + ] + ) + + @classmethod + def from_inference(cls, inference_result: Any) -> KeyPoints: + """ + Create a `sv.KeyPoints` object from the [Roboflow](https://roboflow.com/) + API inference result or the [Inference](https://inference.roboflow.com/) + package results. + + Args: + inference_result: The result from the + Roboflow API or Inference package containing predictions with keypoints. + + Returns: + A `sv.KeyPoints` object containing the keypoint coordinates, class IDs, + class names, and confidences of each keypoint. + + Examples: + ```python + from supervision import _cv2 as cv2 + import supervision as sv + from inference import get_model + + image = cv2.imread("") + model = get_model(model_id="", api_key="") + + result = model.infer(image)[0] + key_points = sv.KeyPoints.from_inference(result) + ``` + + ```python + from supervision import _cv2 as cv2 + import supervision as sv + from inference_sdk import InferenceHTTPClient + + image = cv2.imread("") + client = InferenceHTTPClient( + api_url="https://detect.roboflow.com", + api_key="" + ) + + result = client.infer(image, model_id="") + key_points = sv.KeyPoints.from_inference(result) + ``` + """ + if isinstance(inference_result, list): + raise ValueError( + "from_inference() operates on a single result at a time." + "You can retrieve it like so: inference_result = model.infer(image)[0]" + ) + + if hasattr(inference_result, "dict"): + inference_result = inference_result.dict(exclude_none=True, by_alias=True) + elif hasattr(inference_result, "json"): + inference_result = inference_result.json() + if not inference_result.get("predictions"): + return cls.empty() + + predictions = inference_result["predictions"] + + # Inference omits every key point scored below the request's + # `keypoint_confidence`, so objects can list different key points. Each key + # point's `class_id` is its index in the skeleton; placing it there keeps + # skeleton edges on the right joints. Results without that field fall back + # to list order. Omitted slots stay at (0, 0) with zero confidence, the + # missing-key-point marker that the annotators and `as_detections` skip. + slots = [ + [ + keypoint.get("class_id", position) + for position, keypoint in enumerate(prediction["keypoints"]) + ] + for prediction in predictions + ] + keypoint_count = max( + (max(object_slots) + 1 for object_slots in slots if object_slots), + default=0, + ) + + xy = np.zeros((len(predictions), keypoint_count, 2), dtype=np.float32) + confidence = np.zeros((len(predictions), keypoint_count), dtype=np.float32) + for object_index, (prediction, object_slots) in enumerate( + zip(predictions, slots) + ): + for slot, keypoint in zip(object_slots, prediction["keypoints"]): + xy[object_index, slot] = (keypoint["x"], keypoint["y"]) + confidence[object_index, slot] = keypoint["confidence"] + + class_id = np.array([prediction["class_id"] for prediction in predictions]) + class_names = np.array([prediction["class"] for prediction in predictions]) + data: _DetectionDataType = {CLASS_NAME_DATA_FIELD: class_names} + + return cls( + xy=xy, + keypoint_confidence=confidence, + class_id=class_id.astype(int), + data=data, + ) + + @classmethod + def from_mediapipe( + cls, mediapipe_results: Any, resolution_wh: tuple[int, int] + ) -> KeyPoints: + """ + Creates a `sv.KeyPoints` instance from a + [MediaPipe](https://github.com/google-ai-edge/mediapipe) + pose landmark detection inference result. + + Args: + mediapipe_results: The output results from Mediapipe. It supports pose + and face landmarks from `PoseLandmarker`, `FaceLandmarker` and the + legacy ones from `Pose` and `FaceMesh`. + resolution_wh: A tuple of the form `(width, height)` representing the + resolution of the frame. + + Returns: + A `sv.KeyPoints` object containing the keypoint coordinates and + confidences of each keypoint. + + !!! tip + Before you start, download model bundles from the + [MediaPipe website](https://ai.google.dev/edge/mediapipe/solutions/vision/pose_landmarker/index#models). + + Examples: + ```python + from supervision import _cv2 as cv2 + import mediapipe as mp + import supervision as sv + + image = cv2.imread("") + image_height, image_width, _ = image.shape + mediapipe_image = mp.Image( + image_format=mp.ImageFormat.SRGB, + data=cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) + + options = mp.tasks.vision.PoseLandmarkerOptions( + base_options=mp.tasks.BaseOptions( + model_asset_path="pose_landmarker_heavy.task" + ), + running_mode=mp.tasks.vision.RunningMode.IMAGE, + num_poses=2) + + PoseLandmarker = mp.tasks.vision.PoseLandmarker + with PoseLandmarker.create_from_options(options) as landmarker: + pose_landmarker_result = landmarker.detect(mediapipe_image) + + key_points = sv.KeyPoints.from_mediapipe( + pose_landmarker_result, (image_width, image_height)) + ``` + + ```python + from supervision import _cv2 as cv2 + import mediapipe as mp + import supervision as sv + + image = cv2.imread("") + image_height, image_width, _ = image.shape + mediapipe_image = mp.Image( + image_format=mp.ImageFormat.SRGB, + data=cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) + + options = mp.tasks.vision.FaceLandmarkerOptions( + base_options=mp.tasks.BaseOptions( + model_asset_path="face_landmarker.task" + ), + output_face_blendshapes=True, + output_facial_transformation_matrixes=True, + num_faces=2) + + FaceLandmarker = mp.tasks.vision.FaceLandmarker + with FaceLandmarker.create_from_options(options) as landmarker: + face_landmarker_result = landmarker.detect(mediapipe_image) + + key_points = sv.KeyPoints.from_mediapipe( + face_landmarker_result, (image_width, image_height)) + ``` + + """ + if hasattr(mediapipe_results, "pose_landmarks"): + results = mediapipe_results.pose_landmarks + if not isinstance(mediapipe_results.pose_landmarks, list): + if mediapipe_results.pose_landmarks is None: + results = [] + else: + results = [ + [ + landmark + for landmark in mediapipe_results.pose_landmarks.landmark + ] + ] + elif hasattr(mediapipe_results, "face_landmarks"): + results = mediapipe_results.face_landmarks + elif hasattr(mediapipe_results, "multi_face_landmarks"): + if mediapipe_results.multi_face_landmarks is None: + results = [] + else: + results = [ + face_landmark.landmark + for face_landmark in mediapipe_results.multi_face_landmarks + ] + else: + # Reject unsupported MediaPipe-like payloads before landmark parsing. + raise ValueError( + "Unsupported MediaPipe result type. Expected an object with " + "pose_landmarks, face_landmarks, or multi_face_landmarks." + ) + + if len(results) == 0: + return cls.empty() + + xy = [] + confidence = [] + for pose in results: + prediction_xy = [] + prediction_confidence = [] + for landmark in pose: + keypoint_xy = [ + landmark.x * resolution_wh[0], + landmark.y * resolution_wh[1], + ] + prediction_xy.append(keypoint_xy) + prediction_confidence.append(landmark.visibility) + + xy.append(prediction_xy) + confidence.append(prediction_confidence) + + return cls( + xy=np.array(xy, dtype=np.float32), + keypoint_confidence=np.array(confidence, dtype=np.float32), + ) + + @classmethod + def from_ultralytics(cls, ultralytics_results: Any) -> KeyPoints: + """ + Creates a `sv.KeyPoints` instance from a + [YOLOv8](https://github.com/ultralytics/ultralytics) pose inference result. + + Args: + ultralytics_results: The output Results instance from YOLOv8. + + Returns: + A `sv.KeyPoints` object containing the keypoint coordinates, class IDs, + and class names, and confidences of each keypoint. + + Examples: + ```python + from supervision import _cv2 as cv2 + import supervision as sv + from ultralytics import YOLO + + image = cv2.imread("") + model = YOLO('yolov8s-pose.pt') + + result = model(image)[0] + key_points = sv.KeyPoints.from_ultralytics(result) + ``` + """ + if ultralytics_results.keypoints.xy.numel() == 0: + return cls.empty() + + xy = ultralytics_results.keypoints.xy.cpu().numpy() + class_id = ultralytics_results.boxes.cls.cpu().numpy().astype(int) + class_names = np.array([ultralytics_results.names[i] for i in class_id]) + + # Models trained with a two-value `kpt_shape` report no per-keypoint + # visibility, and Ultralytics exposes `keypoints.conf` as `None` for them. + keypoints_conf = ultralytics_results.keypoints.conf + confidence = None if keypoints_conf is None else keypoints_conf.cpu().numpy() + data: _DetectionDataType = {CLASS_NAME_DATA_FIELD: class_names} + return cls(xy=xy, class_id=class_id, keypoint_confidence=confidence, data=data) + + @classmethod + def from_yolo_nas(cls, yolo_nas_results: Any) -> KeyPoints: + """ + Create a `sv.KeyPoints` instance from a [YOLO-NAS](https://github.com/Deci-AI/super-gradients/blob/master/YOLONAS-POSE.md) + pose inference results. + + Args: + yolo_nas_results: The output object from YOLO NAS. + + Returns: + A `sv.KeyPoints` object containing the keypoint coordinates, class IDs, + and class names, and confidences of each keypoint. + + Examples: + ```python + from supervision import _cv2 as cv2 + import torch + import supervision as sv + import super_gradients + + image = cv2.imread("") + + device = "cuda" if torch.cuda.is_available() else "cpu" + model = super_gradients.training.models.get( + "yolo_nas_pose_s", pretrained_weights="coco_pose").to(device) + + results = model.predict(image, conf=0.1) + key_points = sv.KeyPoints.from_yolo_nas(results) + ``` + """ + if len(yolo_nas_results.prediction.poses) == 0: + return cls.empty() + + xy = yolo_nas_results.prediction.poses[:, :, :2] + confidence = yolo_nas_results.prediction.poses[:, :, 2] + + # yolo_nas_results treats params differently. + # prediction.labels may not exist, whereas class_names might be None + if hasattr(yolo_nas_results.prediction, "labels"): + class_id = yolo_nas_results.prediction.labels # np.array[int] + else: + class_id = None + + data: _DetectionDataType = {} + if class_id is not None and yolo_nas_results.class_names is not None: + class_names = [] + for c_id in class_id: + name = yolo_nas_results.class_names[c_id] # tuple[str] + class_names.append(name) + data[CLASS_NAME_DATA_FIELD] = class_names + + return cls( + xy=xy, + keypoint_confidence=confidence, + class_id=class_id, + data=data, + ) + + @classmethod + def from_detectron2(cls, detectron2_results: Any) -> KeyPoints: + """ + Create a `sv.KeyPoints` object from the + [Detectron2](https://github.com/facebookresearch/detectron2) inference result. + + Args: + detectron2_results: The output of a + Detectron2 model containing instances with prediction data. + + Returns: + A `sv.KeyPoints` object containing the keypoint coordinates, class IDs, + and class names, and confidences of each keypoint. + + Examples: + ```python + from supervision import _cv2 as cv2 + import supervision as sv + from detectron2.engine import DefaultPredictor + from detectron2.config import get_cfg + + + image = cv2.imread("") + cfg = get_cfg() + cfg.merge_from_file("") + cfg.MODEL.WEIGHTS = "" + predictor = DefaultPredictor(cfg) + + result = predictor(image) + keypoints = sv.KeyPoints.from_detectron2(result) + ``` + """ + + if hasattr(detectron2_results["instances"], "pred_keypoints"): + if detectron2_results["instances"].pred_keypoints.cpu().numpy().size == 0: + return cls.empty() + return cls( + xy=detectron2_results["instances"] + .pred_keypoints.cpu() + .numpy()[:, :, :2], + keypoint_confidence=detectron2_results["instances"] + .pred_keypoints.cpu() + .numpy()[:, :, 2], + class_id=detectron2_results["instances"] + .pred_classes.cpu() + .numpy() + .astype(int), + ) + else: + return cls.empty() + + @classmethod + def from_transformers(cls, transformers_results: Any) -> KeyPoints: + """ + Create a `sv.KeyPoints` object from the + [Transformers](https://github.com/huggingface/transformers) inference result. + + Args: + transformers_results: The output of a + Transformers model containing instances with prediction data. + + Returns: + A `sv.KeyPoints` object containing the keypoint coordinates, class IDs, + and class names, and confidences of each keypoint. + + Examples: + ```python + from PIL import Image + import requests + import supervision as sv + import torch + from transformers import ( + AutoProcessor, + RTDetrForObjectDetection, + VitPoseForPoseEstimation, + ) + + device = "cuda" if torch.cuda.is_available() else "cpu" + image = Image.open("") + + DETECTION_MODEL_ID = "PekingU/rtdetr_r50vd_coco_o365" + + detection_processor = AutoProcessor.from_pretrained(DETECTION_MODEL_ID, use_fast=True) + detection_model = RTDetrForObjectDetection.from_pretrained(DETECTION_MODEL_ID, device_map=device) + + inputs = detection_processor(images=frame, return_tensors="pt").to(device) + + with torch.no_grad(): + outputs = detection_model(**inputs) + + target_size = torch.tensor([(frame.height, frame.width)]) + results = detection_processor.post_process_object_detection( + outputs, target_sizes=target_size, threshold=0.3) + + detections = sv.Detections.from_transformers(results[0]) + boxes = sv.xyxy_to_xywh(detections[detections.class_id == 0].xyxy) + + POSE_ESTIMATION_MODEL_ID = "usyd-community/vitpose-base-simple" + + pose_estimation_processor = AutoProcessor.from_pretrained(POSE_ESTIMATION_MODEL_ID) + pose_estimation_model = VitPoseForPoseEstimation.from_pretrained( + POSE_ESTIMATION_MODEL_ID, device_map=device) + + inputs = pose_estimation_processor(frame, boxes=[boxes], return_tensors="pt").to(device) + + with torch.no_grad(): + outputs = pose_estimation_model(**inputs) + + results = pose_estimation_processor.post_process_pose_estimation(outputs, boxes=[boxes]) + key_point = sv.KeyPoints.from_transformers(results[0]) + ``` + + """ # noqa: E501 // docs + + if "keypoints" in transformers_results[0]: + if transformers_results[0]["keypoints"].cpu().numpy().size == 0: + return cls.empty() + + result_data = [ + ( + result["keypoints"].cpu().numpy(), + result["scores"].cpu().numpy(), + ) + for result in transformers_results + ] + + xy, scores = zip(*result_data) + + return cls( + xy=np.stack(xy).astype(np.float32), + keypoint_confidence=np.stack(scores).astype(np.float32), + class_id=np.arange(len(xy)).astype(int), + ) + else: + return cls.empty() + + def _get_by_2d_bool_mask(self, mask: npt.NDArray[np.bool_]) -> KeyPoints: + """Filter keypoints using a 2D boolean mask of shape `(n, m)`. + + This method selects the **same set of keypoints from every object**, so + every row of `mask` must contain the same number of `True` values. The + result is a new `KeyPoints` whose keypoint count is that uniform `k`. + + This is suitable for use cases such as *"keep only the left-side joints for + all persons"* — where the selected joint indices are identical across objects. + + It is **not** suitable for per-object confidence filtering + (`kp[kp.confidence > 0.5]`) when the threshold yields a different number of + passing keypoints per object, because NumPy cannot represent a ragged + `(n, ?, 2)` array. For that pattern either process objects individually or + zero out low-confidence entries in-place via `kp.confidence`. + + For the single-object case (`n == 1`) any boolean mask always satisfies the + uniform-count requirement, so `kp[kp.confidence > 0.5]` works as expected. + + Args: + mask: A boolean array of shape `(n, m)` where `n` is the number of + objects and `m` is the number of keypoints per object. Every row + must select the same number of keypoints so that the result can be + stored in a uniform `(n, k, ...)` array. + + Returns: + A new `KeyPoints` instance containing only the keypoints selected by + the mask for each object. + + Raises: + ValueError: If `mask.shape[0]` does not match the number of objects, if + `mask.shape[1]` does not match the number of keypoints, or if + different rows of the mask select different numbers of `True` values. + """ + n = len(self.xy) + if mask.shape[0] != n: + raise ValueError( + f"2D boolean mask row count {mask.shape[0]} does not match " + f"object count {n}." + ) + if mask.shape[1] != self.xy.shape[1]: + raise ValueError( + f"2D boolean mask column count {mask.shape[1]} does not match " + f"keypoint count {self.xy.shape[1]}." + ) + counts = np.sum(mask, axis=1) + if n > 0 and not np.all(counts == counts[0]): + raise ValueError( + "Cannot filter keypoints with a 2D boolean mask where rows have " + "different numbers of True values. " + "All objects must select the same number of keypoints. " + f"Got counts per object: {counts.tolist()}" + ) + k = int(counts[0]) if n > 0 else 0 + xy_selected = np.zeros((n, k, self.xy.shape[2]), dtype=self.xy.dtype) + keypoint_confidence_selected: npt.NDArray[np.float32] | None = None + if self.keypoint_confidence is not None: + keypoint_confidence_selected = cast( + npt.NDArray[np.float32], + np.zeros((n, k), dtype=self.keypoint_confidence.dtype), + ) + visible_selected: npt.NDArray[np.bool_] | None = None + if self.visible is not None: + visible_selected = np.zeros((n, k), dtype=bool) + for row in range(n): + row_indices = np.flatnonzero(mask[row]) + xy_selected[row] = self.xy[row, row_indices] + if ( + keypoint_confidence_selected is not None + and self.keypoint_confidence is not None + ): + keypoint_confidence_selected[row] = self.keypoint_confidence[ + row, row_indices + ] + if visible_selected is not None and self.visible is not None: + visible_selected[row] = self.visible[row, row_indices] + detection_confidence_selected = None + if self.detection_confidence is not None: + detection_confidence_selected = self.detection_confidence.copy() + + class_id_selected = None + if self.class_id is not None: + class_id_selected = self.class_id.copy() + + data_selected = get_data_item(self.data, slice(None)) + + return KeyPoints( + xy=xy_selected, + keypoint_confidence=keypoint_confidence_selected, + detection_confidence=detection_confidence_selected, + visible=visible_selected, + class_id=class_id_selected, + data=data_selected, + ) + + def get_data(self, key: str) -> _DetectionDataValueType | None: + """Get a value from the keypoint data dictionary. + + Args: + key: Data field name. + + Returns: + The stored data value, or `None` when the key is absent. + + Example: + ```pycon + >>> import numpy as np + >>> from supervision import KeyPoints + >>> key_points = KeyPoints( + ... xy=np.array([[[0, 0]]]), + ... data={"class_name": np.array(["person"])}, + ... ) + >>> key_points.get_data("class_name").tolist() + ['person'] + + ``` + """ + return self.data.get(key) + + def select( + self, + index: Index1D | Index2D, + ) -> KeyPoints: + """Get a subset of the KeyPoints object. + + Supports detection-level (skeleton) filtering, keypoint-level (anchor) + filtering, and combined tuple indexing. + + Args: + index: Index, indices, slice, or boolean mask selecting key points. + + Returns: + A new `KeyPoints` instance containing the selected rows or anchors. + + Example: + ```pycon + >>> import numpy as np + >>> from supervision import KeyPoints + >>> key_points = KeyPoints(xy=np.array([[[0, 1]], [[2, 3]]])) + >>> key_points.select([1]).xy.tolist() + [[[2, 3]]] + + ``` + """ + if isinstance(index, np.ndarray) and index.ndim == 2 and index.dtype == bool: + return self._get_by_2d_bool_mask(cast(npt.NDArray[np.bool_], index)) + + if not isinstance(index, tuple): + index = (index, slice(None)) + + i, j = index + + if isinstance(i, int): + i = [i] + + if isinstance(i, list) and i and all(isinstance(x, bool) for x in i): + i = np.array(i) + if isinstance(j, list) and j and all(isinstance(x, bool) for x in j): + j = np.array(j) + + if isinstance(i, np.ndarray) and i.dtype == bool: + i = np.flatnonzero(i) + if isinstance(j, np.ndarray) and j.dtype == bool: + j = np.flatnonzero(j) + + raw_i = i + + if ( + isinstance(i, (list, np.ndarray)) + and isinstance(j, (list, np.ndarray)) + and not np.isscalar(i) + and not np.isscalar(j) + ): + i_ix, j_ix = np.ix_(cast(Any, i), cast(Any, j)) + i = cast(Any, i_ix) + j = cast(Any, j_ix) + + row_i = _normalize_row_index(raw_i) + + xy_selected = self.xy[i, j] + + keypoint_confidence_selected = None + if self.keypoint_confidence is not None: + keypoint_confidence_selected = self.keypoint_confidence[i, j] + + detection_confidence_selected = None + if self.detection_confidence is not None: + detection_confidence_selected = self.detection_confidence[row_i] + + visible_selected = None + if self.visible is not None: + visible_selected = self.visible[i, j] + + class_id_selected = self.class_id[row_i] if self.class_id is not None else None + + data_selected = get_data_item(self.data, cast(Any, row_i)) + + if xy_selected.ndim == 1: + xy_selected = xy_selected.reshape(1, 1, 2) + if keypoint_confidence_selected is not None: + keypoint_confidence_selected = keypoint_confidence_selected.reshape( + 1, 1 + ) + if visible_selected is not None: + visible_selected = visible_selected.reshape(1, 1) + elif xy_selected.ndim == 2: + if np.isscalar(index[0]) or ( + isinstance(index[0], np.ndarray) and index[0].ndim == 0 + ): + xy_selected = xy_selected[np.newaxis, ...] + if keypoint_confidence_selected is not None: + keypoint_confidence_selected = keypoint_confidence_selected[ + np.newaxis, ... + ] + if visible_selected is not None: + visible_selected = visible_selected[np.newaxis, ...] + elif np.isscalar(index[1]) or ( + isinstance(index[1], np.ndarray) and index[1].ndim == 0 + ): + xy_selected = xy_selected[:, np.newaxis, :] + if keypoint_confidence_selected is not None: + keypoint_confidence_selected = keypoint_confidence_selected[ + :, np.newaxis + ] + if visible_selected is not None: + visible_selected = visible_selected[:, np.newaxis] + + return KeyPoints( + xy=xy_selected, + keypoint_confidence=keypoint_confidence_selected, + detection_confidence=detection_confidence_selected, + visible=visible_selected, + class_id=class_id_selected, + data=data_selected, + ) + + def __getitem__( + self, + index: Index1D | Index2D | str, + ) -> KeyPoints | npt.NDArray[np.generic] | list[Any] | None: + """ + Get a subset of the KeyPoints object or access an item from its data field. + + Supports detection-level (skeleton) filtering, keypoint-level (anchor) + filtering, combined tuple indexing, and data field access by string key. + + Args: + index: The index, indices, or key to access a subset of the KeyPoints + or an item from the data. + + Returns: + A subset of the KeyPoints object or an item from the data field. + + Examples: + ```python + import supervision as sv + + key_points = sv.KeyPoints(...) + + # detection-level filtering (returns KeyPoints) + high_conf = key_points[key_points.detection_confidence > 0.5] + class_0 = key_points[key_points.class_id == 0] + + # keypoint-level filtering (returns KeyPoints) + visible = key_points[key_points.keypoint_confidence > 0.3] + + # indexing + first = key_points[0] + first_two = key_points[0:2] + subset = key_points[[0, 2]] + + # anchor selection (uniform across all skeletons) + nose_and_eyes = key_points[:, [0, 1, 2]] + + # data field access + class_names = key_points['class_name'] + ``` + """ + if isinstance(index, str): + return self.get_data(index) + return self.select(index) + + def __setitem__(self, key: str, value: npt.NDArray[np.generic] | list[Any]) -> None: + """ + Set a value in the data dictionary of the `sv.KeyPoints` object. + + Args: + key: The key in the data dictionary to set. + value: The value to set for the key. + + Examples: + ```python + from supervision import _cv2 as cv2 + import supervision as sv + from ultralytics import YOLO + + image = cv2.imread("") + model = YOLO('yolov8s.pt') + + result = model(image)[0] + key_points = sv.KeyPoints.from_ultralytics(result) + + key_points['class_name'] = [ + model.model.names[class_id] + for class_id + in key_points.class_id + ] + ``` + """ + if not isinstance(value, (np.ndarray, list)): + raise TypeError("Value must be a np.ndarray or a list") + + if isinstance(value, list): + value = np.array(value) + + self.data[key] = value + + @classmethod + def empty(cls) -> KeyPoints: + """ + Create an empty KeyPoints object with no key points. + + Returns: + An empty `sv.KeyPoints` object. + + Examples: + ```pycon + >>> import supervision as sv + >>> key_points = sv.KeyPoints.empty() + >>> len(key_points) + 0 + + ``` + """ + return cls(xy=np.empty((0, 0, 2), dtype=np.float32)) + + def is_empty(self) -> bool: + """ + Returns `True` if the `KeyPoints` object is considered empty. + + Returns: + `True` if the object is empty, `False` otherwise. + + Example: + ```pycon + >>> import supervision as sv + >>> key_points = sv.KeyPoints.empty() + >>> key_points.is_empty() + True + + ``` + """ + return len(self) == 0 + + @classmethod + def merge(cls, key_points_list: list[KeyPoints]) -> KeyPoints: + """ + Merge a list of KeyPoints objects into a single KeyPoints object. + + This method takes a list of KeyPoints objects and combines their + respective fields (`xy`, `class_id`, `keypoint_confidence`, + `detection_confidence`, and `visible`) into a single KeyPoints object. + The `data` dictionaries are merged key-wise, following the same rules + as `Detections.merge`. + + For example, if merging KeyPoints with 2 and 3 skeletons, this method + will return a KeyPoints with 5 skeletons (5 entries in `xy`, etc). + + !!! Note + + When merging, empty `KeyPoints` objects are ignored. + + Args: + key_points_list: A list of KeyPoints objects to merge. + + Returns: + A single KeyPoints object containing the merged data from the input list. + + Raises: + ValueError: If the non-empty inputs do not share the same number + of keypoints per skeleton. + ValueError: If the non-empty inputs do not share the same + coordinate depth (`xy.shape[2]`) per skeleton. + ValueError: If some inputs have a field set (`class_id`, + `keypoint_confidence`, `detection_confidence`, or `visible`) + and others do not. + ValueError: If the input `data` dictionaries do not share the + same keys. + + Example: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> key_points_1 = sv.KeyPoints( + ... xy=np.array([[[10, 10], [20, 20]]], dtype=np.float32), + ... class_id=np.array([0]), + ... data={'class_name': np.array(['person'])}, + ... ) + >>> key_points_2 = sv.KeyPoints( + ... xy=np.array([[[30, 30], [40, 40]]], dtype=np.float32), + ... class_id=np.array([1]), + ... data={'class_name': np.array(['dog'])}, + ... ) + >>> merged = sv.KeyPoints.merge([key_points_1, key_points_2]) + >>> len(merged) + 2 + >>> merged.class_id + array([0, 1]) + >>> merged.data['class_name'] + array(['person', 'dog'], dtype=' 1: + raise ValueError( + "All KeyPoints must have the same number of keypoints per " + f"skeleton to be merged; got counts {sorted(keypoint_counts)}." + ) + + keypoint_depths = {key_points.xy.shape[2] for key_points in key_points_list} + if len(keypoint_depths) > 1: + raise ValueError( + "All KeyPoints must have the same coordinate depth per " + f"skeleton to be merged; got depths {sorted(keypoint_depths)}." + ) + + xy = np.vstack([key_points.xy for key_points in key_points_list]) + + def stack_or_none(name: str) -> npt.NDArray[np.generic] | None: + values = [getattr(key_points, name) for key_points in key_points_list] + if all(value is None for value in values): + return None + if any(value is None for value in values): + raise ValueError(f"All or none of the '{name}' fields must be None") + return cast(npt.NDArray[np.generic], np.concatenate(values, axis=0)) + + class_id = cast(npt.NDArray[np.int_] | None, stack_or_none("class_id")) + keypoint_confidence = cast( + npt.NDArray[np.float32] | None, stack_or_none("keypoint_confidence") + ) + detection_confidence = cast( + npt.NDArray[np.float32] | None, stack_or_none("detection_confidence") + ) + visible = cast(npt.NDArray[np.bool_] | None, stack_or_none("visible")) + + data = merge_data([key_points.data for key_points in key_points_list]) + + return cls( + xy=xy, + class_id=class_id, + keypoint_confidence=keypoint_confidence, + detection_confidence=detection_confidence, + visible=visible, + data=data, + ) + + def with_nms( + self, + threshold: float = 0.5, + class_agnostic: bool = False, + overlap_metric: OverlapMetric = OverlapMetric.IOU, + ) -> KeyPoints: + """Performs non-max suppression on the keypoint detections. Bounding boxes are + derived from valid keypoints of each skeleton, and standard box NMS is applied. + A keypoint is considered valid when its coordinates are finite and not all-zero, + and its `visible` flag is `True` (if `visible` is set). A skeleton left without + a valid keypoint keeps a zero-area box, so it overlaps nothing and passes + through. + + Args: + threshold: The intersection-over-union threshold to use for + non-maximum suppression. Must be in [0, 1]. Defaults to 0.5. + class_agnostic: Whether to perform class-agnostic non-maximum + suppression. If True, the class_id of each detection will be + ignored. Defaults to False. + overlap_metric: Metric used to compute the degree of overlap + between pairs of bounding boxes. Defaults to + `OverlapMetric.IOU`. + + Returns: + A new `sv.KeyPoints` object after non-maximum suppression. + + Raises: + ValueError: If `detection_confidence` is None. + ValueError: If `class_agnostic` is False and `class_id` + is None. + + Examples: + ```python + from supervision import _cv2 as cv2 + import supervision as sv + from rfdetr import RFDETRKeypointPreview + + image = cv2.imread("") + model = RFDETRKeypointPreview() + + key_points = model.predict(image) + key_points = key_points.with_nms(threshold=0.5) + ``` + """ + if len(self) == 0: + return self + + if self.detection_confidence is None: + raise ValueError( + "KeyPoints detection_confidence must be given for NMS to be executed." + ) + + if not class_agnostic and self.class_id is None: + raise ValueError( + "KeyPoints class_id must be given for NMS to be executed. If " + "you intended to perform class agnostic NMS set " + "class_agnostic=True." + ) + + xy = self.xy + # A non-finite keypoint marks an undetected joint, so it must not reach the + # box: `xy == 0` does not catch it and `np.min`/`np.max` propagate it into + # every corner, leaving an all-`NaN` box that compares False against every + # IoU threshold and therefore suppresses nothing. `as_detections` applies + # the same rule. + valid = ~np.all(xy == 0, axis=-1) & np.isfinite(xy).all(axis=-1) + if self.visible is not None: + valid = valid & self.visible + has_valid = valid.any(axis=1) + x_min = np.min(np.where(valid, xy[..., 0], np.inf), axis=1) + y_min = np.min(np.where(valid, xy[..., 1], np.inf), axis=1) + x_max = np.max(np.where(valid, xy[..., 0], -np.inf), axis=1) + y_max = np.max(np.where(valid, xy[..., 1], -np.inf), axis=1) + xyxy = np.stack([x_min, y_min, x_max, y_max], axis=1).astype(np.float32) + # Skeletons left without a single valid keypoint would otherwise carry the + # `inf` sentinels above; a zero-area box keeps them out of every overlap. + xyxy[~has_valid] = 0.0 + + if class_agnostic: + predictions = np.hstack([xyxy, self.detection_confidence.reshape(-1, 1)]) + else: + class_id = cast(npt.NDArray[np.int_], self.class_id) + predictions = np.hstack( + [ + xyxy, + self.detection_confidence.reshape(-1, 1), + class_id.reshape(-1, 1), + ] + ) + + keep = box_non_max_suppression( + predictions=predictions, + iou_threshold=threshold, + overlap_metric=overlap_metric, + ) + + return self.select(keep) + + def as_detections( + self, selected_keypoint_indices: Iterable[int] | None = None + ) -> Detections: + """Convert a KeyPoints object to a Detections object. This approximates the + bounding box of the detected object by taking the bounding box that fits all key + points. Key points that are missing (`[0, 0]`), not finite, or marked not + visible via `visible` are left out, as in `with_nms`, and a skeleton with no + other key point is dropped. + + Args: + selected_keypoint_indices: The + indices of the key points to include in the bounding box + calculation. This helps focus on a subset of key points, + e.g. when some are occluded. Captures all key points by + default. An empty sequence (`[]`) is treated the same as + `None` and selects all key points. + + Returns: + detections: The converted detections object. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> key_points = sv.KeyPoints( + ... xy=np.array([[[10, 20], [30, 40]]], dtype=np.float32) + ... ) + >>> detections = key_points.as_detections() + >>> detections.xyxy + array([[10., 20., 30., 40.]], dtype=float32) + + ``` + """ + # Inference can retain objects after every keypoint is omitted; an empty + # keypoint axis has no coordinates from which to construct a detection box. + if self.is_empty() or self.xy.shape[1] == 0: + return Detections.empty() + + xy = self.xy + indices: npt.NDArray[np.intp] | None = None + if selected_keypoint_indices is not None: + candidate = np.asarray(list(selected_keypoint_indices), dtype=np.intp) + if candidate.size > 0: + indices = candidate + if indices is not None: + xy = xy[:, indices, :] + + # [0, 0] is used by some frameworks to indicate a missing keypoint. Non-finite + # coordinates cannot form a valid detection box, so both cases are excluded. + valid = ~np.all(xy == 0, axis=2) & np.isfinite(xy).all(axis=2) # (N, M) + # Callers hide unreliable keypoints through `visible` instead of removing + # them; `with_nms` already builds its boxes from visible keypoints only. + if self.visible is not None: + valid &= self.visible if indices is None else self.visible[:, indices] + has_valid = valid.any(axis=1) # (N,) + + x, y = xy[:, :, 0], xy[:, :, 1] + x_min = np.where(valid, x, np.inf).min(axis=1) + y_min = np.where(valid, y, np.inf).min(axis=1) + x_max = np.where(valid, x, -np.inf).max(axis=1) + y_max = np.where(valid, y, -np.inf).max(axis=1) + + xyxy = np.stack((x_min, y_min, x_max, y_max), axis=1).astype(np.float32) + # Skeletons with no valid keypoints keep the original empty [0, 0, 0, 0] box. + xyxy[~has_valid] = 0.0 + + if self.detection_confidence is not None: + confidence = self.detection_confidence.astype(np.float32) + elif self.keypoint_confidence is not None: + keypoint_confidence = self.keypoint_confidence + if indices is not None: + keypoint_confidence = keypoint_confidence[:, indices] + confidence = keypoint_confidence.mean(axis=1).astype(np.float32) + else: + confidence = None + + detections = Detections(xyxy=xyxy, confidence=confidence) + detections.class_id = self.class_id + detections.data = self.data + detections = detections.select(has_valid) + + return detections diff --git a/.venv/lib/python3.12/site-packages/supervision/key_points/skeletons.py b/.venv/lib/python3.12/site-packages/supervision/key_points/skeletons.py new file mode 100644 index 0000000000000000000000000000000000000000..71edfd657ba9f7ee28cf7f9280d15b579685580e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/key_points/skeletons.py @@ -0,0 +1,2646 @@ +from enum import Enum + +Edges = tuple[tuple[int, int], ...] + + +class Skeleton(Enum): + COCO = ( + (1, 2), + (1, 3), + (2, 3), + (2, 4), + (3, 5), + (6, 12), + (6, 7), + (6, 8), + (7, 13), + (7, 9), + (8, 10), + (9, 11), + (12, 13), + (14, 12), + (15, 13), + (16, 14), + (17, 15), + ) + + GHUM = ( + (1, 2), + (1, 5), + (2, 3), + (3, 4), + (4, 8), + (5, 6), + (6, 7), + (7, 9), + (10, 11), + (12, 13), + (12, 14), + (12, 24), + (13, 15), + (13, 25), + (14, 16), + (15, 17), + (16, 18), + (15, 19), + (16, 22), + (17, 19), + (17, 21), + (17, 23), + (18, 20), + (19, 21), + (24, 25), + (24, 26), + (25, 27), + (26, 28), + (27, 29), + (28, 30), + (28, 32), + (29, 31), + (29, 33), + (30, 32), + (31, 33), + ) + + FACEMESH_TESSELATION_NO_IRIS = ( + (128, 35), + (35, 140), + (140, 128), + (12, 1), + (1, 38), + (38, 12), + (233, 232), + (232, 121), + (121, 233), + (73, 38), + (38, 40), + (40, 73), + (129, 122), + (122, 48), + (48, 129), + (233, 122), + (122, 129), + (129, 233), + (105, 70), + (70, 68), + (68, 105), + (176, 172), + (172, 149), + (149, 176), + (119, 51), + (51, 102), + (102, 119), + (74, 40), + (40, 41), + (41, 74), + (10, 152), + (152, 109), + (109, 10), + (49, 116), + (116, 132), + (132, 49), + (195, 205), + (205, 212), + (212, 195), + (75, 41), + (41, 186), + (186, 75), + (81, 43), + (43, 184), + (184, 81), + (41, 93), + (93, 187), + (187, 41), + (231, 230), + (230, 119), + (119, 231), + (203, 213), + (213, 215), + (215, 203), + (84, 19), + (19, 18), + (18, 84), + (77, 62), + (62, 147), + (147, 77), + (161, 30), + (30, 31), + (31, 161), + (57, 158), + (158, 174), + (174, 57), + (107, 205), + (205, 195), + (195, 107), + (136, 215), + (215, 193), + (193, 136), + (204, 166), + (166, 99), + (99, 204), + (22, 72), + (72, 69), + (69, 22), + (52, 46), + (46, 5), + (5, 52), + (145, 25), + (25, 24), + (24, 145), + (78, 147), + (147, 92), + (92, 78), + (206, 51), + (51, 188), + (188, 206), + (202, 201), + (201, 19), + (19, 202), + (92, 107), + (107, 183), + (183, 92), + (91, 92), + (92, 182), + (182, 91), + (86, 85), + (85, 18), + (18, 86), + (207, 204), + (204, 37), + (37, 207), + (149, 172), + (172, 141), + (141, 149), + (93, 41), + (41, 40), + (40, 93), + (194, 190), + (190, 245), + (245, 194), + (160, 159), + (159, 29), + (29, 160), + (248, 247), + (247, 162), + (162, 248), + (237, 4), + (4, 197), + (197, 237), + (55, 69), + (69, 105), + (105, 55), + (194, 169), + (169, 9), + (9, 194), + (118, 229), + (229, 32), + (32, 118), + (190, 194), + (194, 56), + (56, 190), + (99, 98), + (98, 100), + (100, 99), + (127, 48), + (48, 101), + (101, 127), + (167, 80), + (80, 219), + (219, 167), + (156, 155), + (155, 27), + (27, 156), + (210, 50), + (50, 132), + (132, 210), + (136, 137), + (137, 151), + (151, 136), + (48, 127), + (127, 218), + (218, 48), + (224, 53), + (53, 54), + (54, 224), + (46, 52), + (52, 135), + (135, 46), + (212, 171), + (171, 141), + (141, 212), + (68, 70), + (70, 109), + (109, 68), + (44, 107), + (107, 92), + (92, 44), + (231, 120), + (120, 121), + (121, 231), + (227, 131), + (131, 248), + (248, 227), + (64, 54), + (54, 53), + (53, 64), + (239, 21), + (21, 243), + (243, 239), + (47, 71), + (71, 157), + (157, 47), + (79, 63), + (63, 97), + (97, 79), + (47, 54), + (54, 64), + (64, 47), + (144, 35), + (35, 228), + (228, 144), + (124, 118), + (118, 112), + (112, 124), + (45, 126), + (126, 20), + (20, 45), + (237, 135), + (135, 52), + (52, 237), + (217, 207), + (207, 206), + (206, 217), + (155, 154), + (154, 23), + (23, 155), + (40, 38), + (38, 168), + (168, 40), + (201, 202), + (202, 209), + (209, 201), + (37, 143), + (143, 101), + (101, 37), + (58, 213), + (213, 203), + (203, 58), + (21, 61), + (61, 100), + (100, 21), + (29, 159), + (159, 158), + (158, 29), + (36, 227), + (227, 114), + (114, 36), + (161, 160), + (160, 28), + (28, 161), + (205, 203), + (203, 211), + (211, 205), + (114, 226), + (226, 47), + (47, 114), + (44, 203), + (203, 205), + (205, 44), + (63, 77), + (77, 78), + (78, 63), + (138, 124), + (124, 117), + (117, 138), + (42, 39), + (39, 73), + (73, 42), + (204, 130), + (130, 143), + (143, 204), + (65, 99), + (99, 241), + (241, 65), + (50, 103), + (103, 65), + (65, 50), + (42, 74), + (74, 75), + (75, 42), + (213, 217), + (217, 208), + (208, 213), + (43, 75), + (75, 185), + (185, 43), + (170, 171), + (171, 212), + (212, 170), + (171, 150), + (150, 177), + (177, 171), + (106, 67), + (67, 70), + (70, 106), + (123, 7), + (7, 169), + (169, 123), + (124, 148), + (148, 188), + (188, 124), + (97, 78), + (78, 91), + (91, 97), + (66, 56), + (56, 108), + (108, 66), + (90, 91), + (91, 181), + (181, 90), + (102, 101), + (101, 121), + (121, 102), + (64, 106), + (106, 105), + (105, 64), + (94, 138), + (138, 228), + (228, 94), + (16, 87), + (87, 86), + (86, 16), + (130, 103), + (103, 50), + (50, 130), + (15, 88), + (88, 87), + (87, 15), + (56, 9), + (9, 10), + (10, 56), + (101, 48), + (48, 122), + (122, 101), + (146, 24), + (24, 23), + (23, 146), + (89, 90), + (90, 180), + (180, 89), + (7, 123), + (123, 197), + (197, 7), + (89, 96), + (96, 97), + (97, 89), + (139, 173), + (173, 137), + (137, 139), + (216, 59), + (59, 173), + (173, 216), + (116, 49), + (49, 220), + (220, 116), + (43, 81), + (81, 82), + (82, 43), + (196, 4), + (4, 52), + (52, 196), + (44, 147), + (147, 62), + (62, 44), + (172, 176), + (176, 200), + (200, 172), + (82, 83), + (83, 39), + (39, 82), + (54, 47), + (47, 226), + (226, 54), + (145, 164), + (164, 111), + (111, 145), + (53, 66), + (66, 67), + (67, 53), + (230, 229), + (229, 118), + (118, 230), + (35, 128), + (128, 235), + (235, 35), + (108, 109), + (109, 70), + (70, 108), + (110, 109), + (109, 152), + (152, 110), + (49, 65), + (65, 236), + (236, 49), + (63, 79), + (79, 192), + (192, 63), + (130, 210), + (210, 127), + (127, 130), + (112, 36), + (36, 144), + (144, 112), + (118, 124), + (124, 51), + (51, 118), + (223, 66), + (66, 53), + (53, 223), + (20, 126), + (126, 142), + (142, 20), + (222, 56), + (56, 66), + (66, 222), + (4, 196), + (196, 198), + (198, 4), + (26, 8), + (8, 34), + (34, 26), + (221, 238), + (238, 45), + (45, 221), + (71, 72), + (72, 140), + (140, 71), + (123, 194), + (194, 246), + (246, 123), + (248, 131), + (131, 34), + (34, 248), + (72, 22), + (22, 163), + (163, 72), + (171, 170), + (170, 151), + (151, 171), + (189, 175), + (175, 197), + (197, 189), + (217, 187), + (187, 93), + (93, 217), + (3, 98), + (98, 168), + (168, 3), + (142, 126), + (126, 242), + (242, 142), + (165, 168), + (168, 38), + (38, 165), + (73, 39), + (39, 13), + (13, 73), + (39, 83), + (83, 14), + (14, 39), + (64, 69), + (69, 72), + (72, 64), + (227, 36), + (36, 112), + (112, 227), + (102, 51), + (51, 206), + (206, 102), + (207, 93), + (93, 166), + (166, 207), + (210, 199), + (199, 218), + (218, 210), + (166, 168), + (168, 98), + (98, 166), + (221, 116), + (116, 219), + (219, 221), + (134, 113), + (113, 244), + (244, 134), + (240, 239), + (239, 242), + (242, 240), + (215, 136), + (136, 170), + (170, 215), + (191, 174), + (174, 134), + (134, 191), + (172, 209), + (209, 33), + (33, 172), + (126, 45), + (45, 238), + (238, 126), + (87, 88), + (88, 179), + (179, 87), + (86, 87), + (87, 180), + (180, 86), + (85, 86), + (86, 181), + (181, 85), + (84, 85), + (85, 182), + (182, 84), + (202, 84), + (84, 183), + (183, 202), + (138, 94), + (94, 133), + (133, 138), + (77, 63), + (63, 184), + (184, 77), + (62, 77), + (77, 185), + (185, 62), + (58, 62), + (62, 186), + (186, 58), + (213, 58), + (58, 187), + (187, 213), + (215, 208), + (208, 188), + (188, 215), + (35, 144), + (144, 157), + (157, 35), + (80, 240), + (240, 238), + (238, 80), + (124, 138), + (138, 178), + (178, 124), + (45, 2), + (2, 5), + (5, 45), + (202, 195), + (195, 33), + (33, 202), + (65, 103), + (103, 130), + (130, 65), + (214, 216), + (216, 139), + (139, 214), + (60, 167), + (167, 220), + (220, 60), + (243, 100), + (100, 98), + (98, 243), + (3, 95), + (95, 142), + (142, 3), + (76, 60), + (60, 236), + (236, 76), + (25, 111), + (111, 229), + (229, 25), + (26, 131), + (131, 227), + (227, 26), + (24, 25), + (25, 230), + (230, 24), + (23, 24), + (24, 231), + (231, 23), + (27, 23), + (23, 232), + (232, 27), + (113, 27), + (27, 233), + (233, 113), + (190, 191), + (191, 244), + (244, 190), + (222, 57), + (57, 191), + (191, 222), + (29, 57), + (57, 222), + (222, 29), + (28, 29), + (29, 223), + (223, 28), + (30, 28), + (28, 224), + (224, 30), + (31, 30), + (30, 225), + (225, 31), + (248, 31), + (31, 226), + (226, 248), + (239, 80), + (80, 21), + (21, 239), + (167, 60), + (60, 76), + (76, 167), + (61, 76), + (76, 241), + (241, 61), + (148, 178), + (178, 216), + (216, 148), + (21, 80), + (80, 167), + (167, 21), + (188, 148), + (148, 214), + (214, 188), + (113, 234), + (234, 245), + (245, 113), + (234, 129), + (129, 246), + (246, 234), + (129, 115), + (115, 189), + (189, 129), + (115, 218), + (218, 175), + (175, 115), + (132, 116), + (116, 221), + (221, 132), + (218, 199), + (199, 237), + (237, 218), + (199, 132), + (132, 135), + (135, 199), + (178, 133), + (133, 59), + (59, 178), + (144, 36), + (36, 125), + (125, 144), + (111, 164), + (164, 8), + (8, 111), + (229, 111), + (111, 26), + (26, 229), + (357, 390), + (390, 369), + (369, 357), + (12, 303), + (303, 268), + (268, 12), + (453, 351), + (351, 350), + (350, 453), + (303, 304), + (304, 270), + (270, 303), + (358, 344), + (344, 278), + (278, 358), + (453, 454), + (454, 358), + (358, 453), + (334, 333), + (333, 298), + (298, 334), + (176, 153), + (153, 378), + (378, 176), + (348, 349), + (349, 331), + (331, 348), + (304, 305), + (305, 271), + (271, 304), + (10, 337), + (337, 338), + (338, 10), + (279, 280), + (280, 361), + (361, 279), + (419, 263), + (263, 432), + (432, 419), + (305, 409), + (409, 410), + (410, 305), + (311, 416), + (416, 408), + (408, 311), + (271, 410), + (410, 411), + (411, 271), + (451, 349), + (349, 348), + (348, 451), + (423, 431), + (431, 435), + (435, 423), + (314, 315), + (315, 18), + (18, 314), + (307, 308), + (308, 376), + (376, 307), + (388, 389), + (389, 261), + (261, 388), + (287, 415), + (415, 399), + (399, 287), + (336, 407), + (407, 419), + (419, 336), + (365, 368), + (368, 417), + (417, 365), + (424, 359), + (359, 328), + (328, 424), + (252, 285), + (285, 299), + (299, 252), + (282, 6), + (6, 5), + (5, 282), + (374, 375), + (375, 254), + (254, 374), + (308, 321), + (321, 322), + (322, 308), + (426, 428), + (428, 412), + (412, 426), + (422, 314), + (314, 19), + (19, 422), + (322, 406), + (406, 407), + (407, 322), + (321, 405), + (405, 406), + (406, 321), + (316, 17), + (17, 18), + (18, 316), + (427, 426), + (426, 267), + (267, 427), + (378, 401), + (401, 370), + (370, 378), + (323, 392), + (392, 270), + (270, 323), + (418, 466), + (466, 465), + (465, 418), + (387, 258), + (258, 259), + (259, 387), + (467, 261), + (261, 389), + (389, 467), + (457, 400), + (400, 420), + (420, 457), + (285, 333), + (333, 334), + (334, 285), + (418, 286), + (286, 9), + (9, 418), + (347, 341), + (341, 262), + (262, 347), + (414, 442), + (442, 286), + (286, 414), + (328, 461), + (461, 329), + (329, 328), + (356, 372), + (372, 330), + (330, 356), + (393, 440), + (440, 439), + (439, 393), + (383, 342), + (342, 257), + (257, 383), + (430, 421), + (421, 361), + (361, 430), + (365, 395), + (395, 380), + (380, 365), + (278, 344), + (344, 438), + (438, 278), + (444, 445), + (445, 284), + (284, 444), + (276, 441), + (441, 364), + (364, 276), + (432, 263), + (263, 370), + (370, 432), + (298, 339), + (339, 338), + (338, 298), + (274, 376), + (376, 322), + (322, 274), + (451, 452), + (452, 350), + (350, 451), + (447, 343), + (343, 468), + (468, 447), + (294, 335), + (335, 283), + (283, 294), + (459, 462), + (462, 463), + (463, 459), + (277, 354), + (354, 384), + (384, 277), + (309, 325), + (325, 326), + (326, 309), + (277, 301), + (301, 294), + (294, 277), + (373, 346), + (346, 448), + (448, 373), + (353, 346), + (346, 341), + (341, 353), + (275, 2), + (2, 20), + (20, 275), + (457, 249), + (249, 282), + (282, 457), + (437, 428), + (428, 426), + (426, 437), + (382, 257), + (257, 253), + (253, 382), + (270, 392), + (392, 394), + (394, 270), + (201, 200), + (200, 429), + (429, 201), + (267, 331), + (331, 330), + (330, 267), + (288, 274), + (274, 423), + (423, 288), + (251, 463), + (463, 329), + (329, 251), + (259, 287), + (287, 385), + (385, 259), + (266, 354), + (354, 343), + (343, 266), + (388, 260), + (260, 258), + (258, 388), + (425, 432), + (432, 431), + (431, 425), + (343, 354), + (354, 277), + (277, 343), + (274, 336), + (336, 425), + (425, 274), + (293, 326), + (326, 308), + (308, 293), + (367, 448), + (448, 346), + (346, 367), + (272, 304), + (304, 303), + (303, 272), + (424, 267), + (267, 372), + (372, 424), + (295, 456), + (456, 461), + (461, 295), + (280, 279), + (279, 295), + (295, 280), + (272, 273), + (273, 305), + (305, 272), + (433, 435), + (435, 428), + (428, 433), + (273, 408), + (408, 409), + (409, 273), + (395, 431), + (431, 432), + (432, 395), + (396, 370), + (370, 401), + (401, 396), + (335, 334), + (334, 300), + (300, 335), + (352, 418), + (418, 169), + (169, 352), + (353, 281), + (281, 412), + (412, 353), + (326, 320), + (320, 321), + (321, 326), + (296, 297), + (297, 337), + (337, 296), + (320, 404), + (404, 405), + (405, 320), + (331, 349), + (349, 350), + (350, 331), + (294, 299), + (299, 334), + (334, 294), + (324, 455), + (455, 448), + (448, 324), + (16, 17), + (17, 316), + (316, 16), + (359, 430), + (430, 280), + (280, 359), + (15, 16), + (16, 317), + (317, 15), + (286, 337), + (337, 10), + (10, 286), + (330, 350), + (350, 351), + (351, 330), + (375, 381), + (381, 253), + (253, 375), + (319, 403), + (403, 404), + (404, 319), + (7, 198), + (198, 420), + (420, 7), + (319, 320), + (320, 326), + (326, 319), + (368, 365), + (365, 366), + (366, 368), + (436, 368), + (368, 398), + (398, 436), + (345, 439), + (439, 440), + (440, 345), + (273, 272), + (272, 312), + (312, 273), + (196, 6), + (6, 282), + (282, 196), + (274, 288), + (288, 292), + (292, 274), + (397, 429), + (429, 200), + (200, 397), + (312, 272), + (272, 269), + (269, 312), + (284, 445), + (445, 446), + (446, 284), + (374, 255), + (255, 340), + (340, 374), + (283, 335), + (335, 297), + (297, 283), + (450, 348), + (348, 347), + (347, 450), + (265, 448), + (448, 455), + (455, 265), + (337, 297), + (297, 300), + (300, 337), + (339, 11), + (11, 152), + (152, 339), + (279, 440), + (440, 456), + (456, 279), + (293, 408), + (408, 416), + (416, 293), + (359, 372), + (372, 356), + (356, 359), + (341, 346), + (346, 373), + (373, 341), + (347, 348), + (348, 281), + (281, 347), + (443, 444), + (444, 283), + (283, 443), + (20, 95), + (95, 371), + (371, 20), + (442, 443), + (443, 296), + (296, 442), + (249, 420), + (420, 198), + (198, 249), + (264, 256), + (256, 360), + (360, 264), + (441, 276), + (276, 275), + (275, 441), + (301, 384), + (384, 369), + (369, 301), + (352, 413), + (413, 466), + (466, 352), + (264, 468), + (468, 467), + (467, 264), + (302, 369), + (369, 390), + (390, 302), + (396, 379), + (379, 380), + (380, 396), + (413, 352), + (352, 420), + (420, 413), + (437, 427), + (427, 323), + (323, 437), + (3, 165), + (165, 394), + (394, 3), + (371, 463), + (463, 462), + (462, 371), + (165, 1), + (1, 268), + (268, 165), + (303, 12), + (12, 13), + (13, 303), + (269, 13), + (13, 14), + (14, 269), + (294, 301), + (301, 302), + (302, 294), + (447, 262), + (262, 341), + (341, 447), + (331, 267), + (267, 426), + (426, 331), + (427, 424), + (424, 392), + (392, 427), + (430, 356), + (356, 438), + (438, 430), + (392, 328), + (328, 327), + (327, 392), + (441, 458), + (458, 439), + (439, 441), + (342, 383), + (383, 363), + (363, 342), + (460, 458), + (458, 462), + (462, 460), + (435, 431), + (431, 395), + (395, 435), + (415, 464), + (464, 363), + (363, 415), + (397, 370), + (370, 263), + (263, 397), + (355, 462), + (462, 458), + (458, 355), + (317, 404), + (404, 403), + (403, 317), + (316, 405), + (405, 404), + (404, 316), + (315, 406), + (406, 405), + (405, 315), + (314, 407), + (407, 406), + (406, 314), + (422, 419), + (419, 407), + (407, 422), + (367, 402), + (402, 362), + (362, 367), + (307, 409), + (409, 408), + (408, 307), + (292, 410), + (410, 409), + (409, 292), + (288, 411), + (411, 410), + (410, 288), + (433, 437), + (437, 411), + (411, 433), + (435, 417), + (417, 412), + (412, 435), + (265, 369), + (369, 384), + (384, 265), + (310, 439), + (439, 458), + (458, 310), + (353, 377), + (377, 402), + (402, 353), + (275, 276), + (276, 5), + (5, 275), + (422, 429), + (429, 263), + (263, 422), + (295, 328), + (328, 359), + (359, 295), + (434, 417), + (417, 368), + (368, 434), + (290, 456), + (456, 440), + (440, 290), + (463, 371), + (371, 327), + (327, 463), + (3, 327), + (327, 371), + (371, 3), + (306, 461), + (461, 456), + (456, 306), + (255, 450), + (450, 449), + (449, 255), + (256, 262), + (262, 447), + (447, 256), + (254, 451), + (451, 450), + (450, 254), + (253, 452), + (452, 451), + (451, 253), + (257, 453), + (453, 452), + (452, 257), + (342, 454), + (454, 453), + (453, 342), + (414, 465), + (465, 464), + (464, 414), + (442, 414), + (414, 415), + (415, 442), + (259, 443), + (443, 442), + (442, 259), + (258, 444), + (444, 443), + (443, 258), + (260, 445), + (445, 444), + (444, 260), + (261, 446), + (446, 445), + (445, 261), + (468, 343), + (343, 446), + (446, 468), + (460, 459), + (459, 251), + (251, 460), + (290, 393), + (393, 291), + (291, 290), + (291, 329), + (329, 461), + (461, 291), + (377, 434), + (434, 436), + (436, 377), + (251, 291), + (291, 393), + (393, 251), + (412, 417), + (417, 434), + (434, 412), + (342, 464), + (464, 465), + (465, 342), + (454, 465), + (465, 466), + (466, 454), + (358, 466), + (466, 413), + (413, 358), + (344, 413), + (413, 400), + (400, 344), + (361, 364), + (364, 441), + (441, 361), + (438, 400), + (400, 457), + (457, 438), + (421, 457), + (457, 364), + (364, 421), + (402, 436), + (436, 289), + (289, 402), + (373, 384), + (384, 354), + (354, 373), + (340, 256), + (256, 250), + (250, 340), + (449, 262), + (262, 256), + (256, 449), + (134, 244), + (244, 191), + (191, 134), + (134, 156), + (156, 113), + (113, 134), + (34, 247), + (247, 248), + (248, 34), + (34, 131), + (131, 26), + (26, 34), + (399, 385), + (385, 287), + (287, 399), + (363, 399), + (399, 415), + (415, 363), + (363, 464), + (464, 342), + (342, 363), + (264, 360), + (360, 468), + (468, 264), + (264, 250), + (250, 256), + (256, 264), + (467, 468), + (468, 261), + (261, 467), + (76, 61), + (61, 167), + (167, 76), + (239, 240), + (240, 80), + (80, 239), + (163, 128), + (128, 140), + (140, 163), + (73, 12), + (12, 38), + (38, 73), + (122, 233), + (233, 121), + (121, 122), + (74, 73), + (73, 40), + (40, 74), + (115, 129), + (129, 48), + (48, 115), + (234, 233), + (233, 129), + (129, 234), + (104, 105), + (105, 68), + (68, 104), + (153, 176), + (176, 149), + (149, 153), + (120, 119), + (119, 102), + (102, 120), + (75, 74), + (74, 41), + (41, 75), + (108, 10), + (10, 109), + (109, 108), + (50, 49), + (49, 132), + (132, 50), + (33, 195), + (195, 212), + (212, 33), + (185, 75), + (75, 186), + (186, 185), + (192, 81), + (81, 184), + (184, 192), + (186, 41), + (41, 187), + (187, 186), + (120, 231), + (231, 119), + (119, 120), + (211, 203), + (203, 215), + (215, 211), + (85, 84), + (84, 18), + (18, 85), + (78, 77), + (77, 147), + (147, 78), + (162, 161), + (161, 31), + (31, 162), + (191, 57), + (57, 174), + (174, 191), + (183, 107), + (107, 195), + (195, 183), + (139, 136), + (136, 193), + (193, 139), + (130, 204), + (204, 99), + (99, 130), + (55, 22), + (22, 69), + (69, 55), + (6, 52), + (52, 5), + (5, 6), + (146, 145), + (145, 24), + (24, 146), + (91, 78), + (78, 92), + (92, 91), + (208, 206), + (206, 188), + (188, 208), + (84, 202), + (202, 19), + (19, 84), + (182, 92), + (92, 183), + (183, 182), + (181, 91), + (91, 182), + (182, 181), + (17, 86), + (86, 18), + (18, 17), + (206, 207), + (207, 37), + (37, 206), + (177, 149), + (149, 141), + (141, 177), + (166, 93), + (93, 40), + (40, 166), + (246, 194), + (194, 245), + (245, 246), + (28, 160), + (160, 29), + (29, 28), + (31, 248), + (248, 162), + (162, 31), + (175, 237), + (237, 197), + (197, 175), + (104, 55), + (55, 105), + (105, 104), + (56, 194), + (194, 9), + (9, 56), + (112, 118), + (118, 32), + (32, 112), + (222, 190), + (190, 56), + (56, 222), + (241, 99), + (99, 100), + (100, 241), + (143, 127), + (127, 101), + (101, 143), + (220, 167), + (167, 219), + (219, 220), + (113, 156), + (156, 27), + (27, 113), + (199, 210), + (210, 132), + (132, 199), + (170, 136), + (136, 151), + (151, 170), + (115, 48), + (48, 218), + (218, 115), + (225, 224), + (224, 54), + (54, 225), + (221, 46), + (46, 135), + (135, 221), + (33, 212), + (212, 141), + (141, 33), + (110, 68), + (68, 109), + (109, 110), + (147, 44), + (44, 92), + (92, 147), + (232, 231), + (231, 121), + (121, 232), + (114, 227), + (227, 248), + (248, 114), + (106, 64), + (64, 53), + (53, 106), + (242, 239), + (239, 243), + (243, 242), + (125, 47), + (47, 157), + (157, 125), + (96, 79), + (79, 97), + (97, 96), + (71, 47), + (47, 64), + (64, 71), + (117, 144), + (144, 228), + (228, 117), + (117, 124), + (124, 112), + (112, 117), + (2, 45), + (45, 20), + (20, 2), + (4, 237), + (237, 52), + (52, 4), + (208, 217), + (217, 206), + (206, 208), + (27, 155), + (155, 23), + (23, 27), + (166, 40), + (40, 168), + (168, 166), + (200, 201), + (201, 209), + (209, 200), + (102, 37), + (37, 101), + (101, 102), + (44, 58), + (58, 203), + (203, 44), + (243, 21), + (21, 100), + (100, 243), + (57, 29), + (29, 158), + (158, 57), + (125, 36), + (36, 114), + (114, 125), + (30, 161), + (161, 28), + (28, 30), + (212, 205), + (205, 211), + (211, 212), + (125, 114), + (114, 47), + (47, 125), + (107, 44), + (44, 205), + (205, 107), + (97, 63), + (63, 78), + (78, 97), + (228, 138), + (138, 117), + (117, 228), + (74, 42), + (42, 73), + (73, 74), + (37, 204), + (204, 143), + (143, 37), + (236, 65), + (65, 241), + (241, 236), + (49, 50), + (50, 65), + (65, 49), + (43, 42), + (42, 75), + (75, 43), + (215, 213), + (213, 208), + (208, 215), + (184, 43), + (43, 185), + (185, 184), + (211, 170), + (170, 212), + (212, 211), + (141, 171), + (171, 177), + (177, 141), + (105, 106), + (106, 70), + (70, 105), + (194, 123), + (123, 169), + (169, 194), + (51, 124), + (124, 188), + (188, 51), + (90, 97), + (97, 91), + (91, 90), + (67, 66), + (66, 108), + (108, 67), + (180, 90), + (90, 181), + (181, 180), + (120, 102), + (102, 121), + (121, 120), + (69, 64), + (64, 105), + (105, 69), + (235, 94), + (94, 228), + (228, 235), + (17, 16), + (16, 86), + (86, 17), + (210, 130), + (130, 50), + (50, 210), + (16, 15), + (15, 87), + (87, 16), + (108, 56), + (56, 10), + (10, 108), + (121, 101), + (101, 122), + (122, 121), + (154, 146), + (146, 23), + (23, 154), + (179, 89), + (89, 180), + (180, 179), + (198, 7), + (7, 197), + (197, 198), + (90, 89), + (89, 97), + (97, 90), + (136, 139), + (139, 137), + (137, 136), + (139, 216), + (216, 173), + (173, 139), + (219, 116), + (116, 220), + (220, 219), + (42, 43), + (43, 82), + (82, 42), + (6, 196), + (196, 52), + (52, 6), + (58, 44), + (44, 62), + (62, 58), + (209, 172), + (172, 200), + (200, 209), + (42, 82), + (82, 39), + (39, 42), + (225, 54), + (54, 226), + (226, 225), + (25, 145), + (145, 111), + (111, 25), + (106, 53), + (53, 67), + (67, 106), + (119, 230), + (230, 118), + (118, 119), + (228, 35), + (35, 235), + (235, 228), + (67, 108), + (108, 70), + (70, 67), + (11, 110), + (110, 152), + (152, 11), + (220, 49), + (49, 236), + (236, 220), + (184, 63), + (63, 192), + (192, 184), + (143, 130), + (130, 127), + (127, 143), + (117, 112), + (112, 144), + (144, 117), + (119, 118), + (118, 51), + (51, 119), + (224, 223), + (223, 53), + (53, 224), + (95, 20), + (20, 142), + (142, 95), + (223, 222), + (222, 66), + (66, 223), + (197, 4), + (4, 198), + (198, 197), + (46, 221), + (221, 45), + (45, 46), + (157, 71), + (71, 140), + (140, 157), + (189, 123), + (123, 246), + (246, 189), + (140, 72), + (72, 163), + (163, 140), + (150, 171), + (171, 151), + (151, 150), + (123, 189), + (189, 197), + (197, 123), + (207, 217), + (217, 93), + (93, 207), + (165, 3), + (3, 168), + (168, 165), + (243, 142), + (142, 242), + (242, 243), + (1, 165), + (165, 38), + (38, 1), + (12, 73), + (73, 13), + (13, 12), + (13, 39), + (39, 14), + (14, 13), + (71, 64), + (64, 72), + (72, 71), + (32, 227), + (227, 112), + (112, 32), + (37, 102), + (102, 206), + (206, 37), + (204, 207), + (207, 166), + (166, 204), + (127, 210), + (210, 218), + (218, 127), + (99, 166), + (166, 98), + (98, 99), + (238, 221), + (221, 219), + (219, 238), + (238, 240), + (240, 242), + (242, 238), + (211, 215), + (215, 170), + (170, 211), + (141, 172), + (172, 33), + (33, 141), + (242, 126), + (126, 238), + (238, 242), + (180, 87), + (87, 179), + (179, 180), + (181, 86), + (86, 180), + (180, 181), + (182, 85), + (85, 181), + (181, 182), + (183, 84), + (84, 182), + (182, 183), + (195, 202), + (202, 183), + (183, 195), + (178, 138), + (138, 133), + (133, 178), + (185, 77), + (77, 184), + (184, 185), + (186, 62), + (62, 185), + (185, 186), + (187, 58), + (58, 186), + (186, 187), + (217, 213), + (213, 187), + (187, 217), + (193, 215), + (215, 188), + (188, 193), + (140, 35), + (35, 157), + (157, 140), + (219, 80), + (80, 238), + (238, 219), + (148, 124), + (124, 178), + (178, 148), + (46, 45), + (45, 5), + (5, 46), + (209, 202), + (202, 33), + (33, 209), + (99, 65), + (65, 130), + (130, 99), + (193, 214), + (214, 139), + (139, 193), + (236, 60), + (60, 220), + (220, 236), + (142, 243), + (243, 98), + (98, 142), + (98, 3), + (3, 142), + (142, 98), + (241, 76), + (76, 236), + (236, 241), + (230, 25), + (25, 229), + (229, 230), + (32, 26), + (26, 227), + (227, 32), + (231, 24), + (24, 230), + (230, 231), + (232, 23), + (23, 231), + (231, 232), + (233, 27), + (27, 232), + (232, 233), + (234, 113), + (113, 233), + (233, 234), + (245, 190), + (190, 244), + (244, 245), + (190, 222), + (222, 191), + (191, 190), + (223, 29), + (29, 222), + (222, 223), + (224, 28), + (28, 223), + (223, 224), + (225, 30), + (30, 224), + (224, 225), + (226, 31), + (31, 225), + (225, 226), + (114, 248), + (248, 226), + (226, 114), + (100, 61), + (61, 241), + (241, 100), + (214, 148), + (148, 216), + (216, 214), + (61, 21), + (21, 167), + (167, 61), + (193, 188), + (188, 214), + (214, 193), + (244, 113), + (113, 245), + (245, 244), + (245, 234), + (234, 246), + (246, 245), + (246, 129), + (129, 189), + (189, 246), + (189, 115), + (115, 175), + (175, 189), + (135, 132), + (132, 221), + (221, 135), + (175, 218), + (218, 237), + (237, 175), + (237, 199), + (199, 135), + (135, 237), + (216, 178), + (178, 59), + (59, 216), + (157, 144), + (144, 125), + (125, 157), + (26, 111), + (111, 8), + (8, 26), + (32, 229), + (229, 26), + (26, 32), + (265, 357), + (357, 369), + (369, 265), + (1, 12), + (12, 268), + (268, 1), + (452, 453), + (453, 350), + (350, 452), + (268, 303), + (303, 270), + (270, 268), + (351, 358), + (358, 278), + (278, 351), + (351, 453), + (453, 358), + (358, 351), + (300, 334), + (334, 298), + (298, 300), + (397, 176), + (176, 378), + (378, 397), + (281, 348), + (348, 331), + (331, 281), + (270, 304), + (304, 271), + (271, 270), + (152, 10), + (10, 338), + (338, 152), + (345, 279), + (279, 361), + (361, 345), + (425, 419), + (419, 432), + (432, 425), + (271, 305), + (305, 410), + (410, 271), + (273, 311), + (311, 408), + (408, 273), + (323, 271), + (271, 411), + (411, 323), + (450, 451), + (451, 348), + (348, 450), + (433, 423), + (423, 435), + (435, 433), + (19, 314), + (314, 18), + (18, 19), + (292, 307), + (307, 376), + (376, 292), + (260, 388), + (388, 261), + (261, 260), + (425, 336), + (336, 419), + (419, 425), + (435, 365), + (365, 417), + (417, 435), + (392, 424), + (424, 328), + (328, 392), + (302, 252), + (252, 299), + (299, 302), + (276, 282), + (282, 5), + (5, 276), + (255, 374), + (374, 254), + (254, 255), + (376, 308), + (308, 322), + (322, 376), + (281, 426), + (426, 412), + (412, 281), + (201, 422), + (422, 19), + (19, 201), + (336, 322), + (322, 407), + (407, 336), + (322, 321), + (321, 406), + (406, 322), + (315, 316), + (316, 18), + (18, 315), + (424, 427), + (427, 267), + (267, 424), + (397, 378), + (378, 370), + (370, 397), + (271, 323), + (323, 270), + (270, 271), + (414, 418), + (418, 465), + (465, 414), + (386, 387), + (387, 259), + (259, 386), + (249, 457), + (457, 420), + (420, 249), + (299, 285), + (285, 334), + (334, 299), + (169, 418), + (418, 9), + (9, 169), + (449, 347), + (347, 262), + (262, 449), + (418, 414), + (414, 286), + (286, 418), + (327, 328), + (328, 329), + (329, 327), + (278, 356), + (356, 330), + (330, 278), + (310, 393), + (393, 439), + (439, 310), + (382, 383), + (383, 257), + (257, 382), + (280, 430), + (430, 361), + (361, 280), + (366, 365), + (365, 380), + (380, 366), + (356, 278), + (278, 438), + (438, 356), + (283, 444), + (444, 284), + (284, 283), + (282, 276), + (276, 364), + (364, 282), + (396, 432), + (432, 370), + (370, 396), + (300, 298), + (298, 338), + (338, 300), + (336, 274), + (274, 322), + (322, 336), + (349, 451), + (451, 350), + (350, 349), + (360, 447), + (447, 468), + (468, 360), + (284, 294), + (294, 283), + (283, 284), + (251, 459), + (459, 463), + (463, 251), + (301, 277), + (277, 384), + (384, 301), + (293, 309), + (309, 326), + (326, 293), + (284, 277), + (277, 294), + (294, 284), + (265, 373), + (373, 448), + (448, 265), + (347, 353), + (353, 341), + (341, 347), + (355, 275), + (275, 20), + (20, 355), + (364, 457), + (457, 282), + (282, 364), + (427, 437), + (437, 426), + (426, 427), + (381, 382), + (382, 253), + (253, 381), + (268, 270), + (270, 394), + (394, 268), + (422, 201), + (201, 429), + (429, 422), + (372, 267), + (267, 330), + (330, 372), + (433, 288), + (288, 423), + (423, 433), + (291, 251), + (251, 329), + (329, 291), + (386, 259), + (259, 385), + (385, 386), + (447, 266), + (266, 343), + (343, 447), + (387, 388), + (388, 258), + (258, 387), + (423, 425), + (425, 431), + (431, 423), + (446, 343), + (343, 277), + (277, 446), + (423, 274), + (274, 425), + (425, 423), + (307, 293), + (293, 308), + (308, 307), + (353, 367), + (367, 346), + (346, 353), + (269, 272), + (272, 303), + (303, 269), + (359, 424), + (424, 372), + (372, 359), + (328, 295), + (295, 461), + (461, 328), + (332, 280), + (280, 295), + (295, 332), + (304, 272), + (272, 305), + (305, 304), + (437, 433), + (433, 428), + (428, 437), + (305, 273), + (273, 409), + (409, 305), + (396, 395), + (395, 432), + (432, 396), + (379, 396), + (396, 401), + (401, 379), + (297, 335), + (335, 300), + (300, 297), + (7, 352), + (352, 169), + (169, 7), + (377, 353), + (353, 412), + (412, 377), + (308, 326), + (326, 321), + (321, 308), + (286, 296), + (296, 337), + (337, 286), + (321, 320), + (320, 405), + (405, 321), + (330, 331), + (331, 350), + (350, 330), + (335, 294), + (294, 334), + (334, 335), + (367, 324), + (324, 448), + (448, 367), + (317, 16), + (16, 316), + (316, 317), + (332, 359), + (359, 280), + (280, 332), + (318, 15), + (15, 317), + (317, 318), + (9, 286), + (286, 10), + (10, 9), + (278, 330), + (330, 351), + (351, 278), + (254, 375), + (375, 253), + (253, 254), + (320, 319), + (319, 404), + (404, 320), + (352, 7), + (7, 420), + (420, 352), + (325, 319), + (319, 326), + (326, 325), + (398, 368), + (368, 366), + (366, 398), + (289, 436), + (436, 398), + (398, 289), + (279, 345), + (345, 440), + (440, 279), + (311, 273), + (273, 312), + (312, 311), + (249, 196), + (196, 282), + (282, 249), + (376, 274), + (274, 292), + (292, 376), + (176, 397), + (397, 200), + (200, 176), + (313, 312), + (312, 269), + (269, 313), + (277, 284), + (284, 446), + (446, 277), + (391, 374), + (374, 340), + (340, 391), + (296, 283), + (283, 297), + (297, 296), + (449, 450), + (450, 347), + (347, 449), + (357, 265), + (265, 455), + (455, 357), + (338, 337), + (337, 300), + (300, 338), + (338, 339), + (339, 152), + (152, 338), + (295, 279), + (279, 456), + (456, 295), + (309, 293), + (293, 416), + (416, 309), + (430, 359), + (359, 356), + (356, 430), + (266, 341), + (341, 373), + (373, 266), + (353, 347), + (347, 281), + (281, 353), + (296, 443), + (443, 283), + (283, 296), + (355, 20), + (20, 371), + (371, 355), + (286, 442), + (442, 296), + (296, 286), + (196, 249), + (249, 198), + (198, 196), + (458, 441), + (441, 275), + (275, 458), + (302, 301), + (301, 369), + (369, 302), + (418, 352), + (352, 466), + (466, 418), + (252, 302), + (302, 390), + (390, 252), + (395, 396), + (396, 380), + (380, 395), + (400, 413), + (413, 420), + (420, 400), + (411, 437), + (437, 323), + (323, 411), + (327, 3), + (3, 394), + (394, 327), + (355, 371), + (371, 462), + (462, 355), + (394, 165), + (165, 268), + (268, 394), + (269, 303), + (303, 13), + (13, 269), + (313, 269), + (269, 14), + (14, 313), + (299, 294), + (294, 302), + (302, 299), + (266, 447), + (447, 341), + (341, 266), + (281, 331), + (331, 426), + (426, 281), + (323, 427), + (427, 392), + (392, 323), + (421, 430), + (430, 438), + (438, 421), + (394, 392), + (392, 327), + (327, 394), + (345, 441), + (441, 439), + (439, 345), + (459, 460), + (460, 462), + (462, 459), + (365, 435), + (435, 395), + (395, 365), + (429, 397), + (397, 263), + (263, 429), + (275, 355), + (355, 458), + (458, 275), + (318, 317), + (317, 403), + (403, 318), + (317, 316), + (316, 404), + (404, 317), + (316, 315), + (315, 405), + (405, 316), + (315, 314), + (314, 406), + (406, 315), + (314, 422), + (422, 407), + (407, 314), + (324, 367), + (367, 362), + (362, 324), + (293, 307), + (307, 408), + (408, 293), + (307, 292), + (292, 409), + (409, 307), + (292, 288), + (288, 410), + (410, 292), + (288, 433), + (433, 411), + (411, 288), + (428, 435), + (435, 412), + (412, 428), + (373, 265), + (265, 384), + (384, 373), + (460, 310), + (310, 458), + (458, 460), + (367, 353), + (353, 402), + (402, 367), + (2, 275), + (275, 5), + (5, 2), + (419, 422), + (422, 263), + (263, 419), + (332, 295), + (295, 359), + (359, 332), + (436, 434), + (434, 368), + (368, 436), + (393, 290), + (290, 440), + (440, 393), + (329, 463), + (463, 327), + (327, 329), + (95, 3), + (3, 371), + (371, 95), + (290, 306), + (306, 456), + (456, 290), + (340, 255), + (255, 449), + (449, 340), + (360, 256), + (256, 447), + (447, 360), + (255, 254), + (254, 450), + (450, 255), + (254, 253), + (253, 451), + (451, 254), + (253, 257), + (257, 452), + (452, 253), + (257, 342), + (342, 453), + (453, 257), + (415, 414), + (414, 464), + (464, 415), + (287, 442), + (442, 415), + (415, 287), + (287, 259), + (259, 442), + (442, 287), + (259, 258), + (258, 443), + (443, 259), + (258, 260), + (260, 444), + (444, 258), + (260, 261), + (261, 445), + (445, 260), + (261, 468), + (468, 446), + (446, 261), + (310, 460), + (460, 251), + (251, 310), + (306, 290), + (290, 291), + (291, 306), + (306, 291), + (291, 461), + (461, 306), + (402, 377), + (377, 436), + (436, 402), + (310, 251), + (251, 393), + (393, 310), + (377, 412), + (412, 434), + (434, 377), + (454, 342), + (342, 465), + (465, 454), + (358, 454), + (454, 466), + (466, 358), + (344, 358), + (358, 413), + (413, 344), + (438, 344), + (344, 400), + (400, 438), + (345, 361), + (361, 441), + (441, 345), + (421, 438), + (438, 457), + (457, 421), + (361, 421), + (421, 364), + (364, 361), + (362, 402), + (402, 289), + (289, 362), + (266, 373), + (373, 354), + (354, 266), + (391, 340), + (340, 250), + (250, 391), + (340, 449), + (449, 256), + (256, 340), + ) + + FACEMESH_TESSELATION = ( + (474, 474), + (475, 476), + (476, 477), + (477, 478), + (478, 475), + (469, 469), + (470, 471), + (471, 472), + (472, 473), + (473, 470), + *FACEMESH_TESSELATION_NO_IRIS, + ) + + +SKELETONS_BY_EDGE_COUNT: dict[int, Edges] = {} +SKELETONS_BY_VERTEX_COUNT: dict[int, Edges] = {} + +for skeleton in Skeleton: + SKELETONS_BY_EDGE_COUNT[len(skeleton.value)] = skeleton.value + + unique_vertices = {vertex for edge in skeleton.value for vertex in edge} + SKELETONS_BY_VERTEX_COUNT[len(unique_vertices)] = skeleton.value diff --git a/.venv/lib/python3.12/site-packages/supervision/keypoint/__init__.py b/.venv/lib/python3.12/site-packages/supervision/keypoint/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7bda3ed844283d59695b96d1bffa1a1801b56ff5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/keypoint/__init__.py @@ -0,0 +1,13 @@ +from supervision.utils.internal import warn_deprecated + +warn_deprecated( + "The 'supervision.keypoint' module is deprecated in `0.27.0` and will be removed " + "in `0.31.0`. Please use 'supervision.key_points' instead." +) + +from supervision.key_points.annotators import ( + EdgeAnnotator, + VertexAnnotator, + VertexLabelAnnotator, +) +from supervision.key_points.core import KeyPoints diff --git a/.venv/lib/python3.12/site-packages/supervision/keypoint/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/keypoint/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78917392d62a620a4f3fb626b4741abcb5398f04 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/keypoint/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/keypoint/__pycache__/annotators.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/keypoint/__pycache__/annotators.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a51ebcbf0db480de173891252a113e96a4f1c3d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/keypoint/__pycache__/annotators.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/keypoint/__pycache__/core.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/keypoint/__pycache__/core.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..66aa48e97d8461718231ce1cc674ee7e4aa41c85 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/keypoint/__pycache__/core.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/keypoint/annotators.py b/.venv/lib/python3.12/site-packages/supervision/keypoint/annotators.py new file mode 100644 index 0000000000000000000000000000000000000000..1bb0a3aef44b1cd6345e2e32bb067cf2ea268493 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/keypoint/annotators.py @@ -0,0 +1,13 @@ +from supervision.utils.internal import warn_deprecated + +warn_deprecated( + "The 'supervision.keypoint' module is deprecated in `0.27.0` and will be removed " + "in `0.31.0`. Please use 'supervision.key_points' instead." +) + +from supervision.key_points.annotators import ( # noqa: E402, F401 + BaseKeyPointAnnotator, + EdgeAnnotator, + VertexAnnotator, + VertexLabelAnnotator, +) diff --git a/.venv/lib/python3.12/site-packages/supervision/keypoint/core.py b/.venv/lib/python3.12/site-packages/supervision/keypoint/core.py new file mode 100644 index 0000000000000000000000000000000000000000..cc0115540501648e6b7b17967e7e7d1ad452c664 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/keypoint/core.py @@ -0,0 +1,8 @@ +from supervision.utils.internal import warn_deprecated + +warn_deprecated( + "The 'supervision.keypoint' module is deprecated in `0.27.0` and will be removed " + "in `0.31.0`. Please use 'supervision.key_points' instead." +) + +from supervision.key_points.core import KeyPoints # noqa: E402, F401 diff --git a/.venv/lib/python3.12/site-packages/supervision/metrics/__init__.py b/.venv/lib/python3.12/site-packages/supervision/metrics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e1cba4c1886465d76502bafb23ef827c12317ab4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/metrics/__init__.py @@ -0,0 +1,40 @@ +from supervision.metrics.core import ( + AveragingMethod, + Metric, + MetricTarget, +) +from supervision.metrics.f1_score import F1Score, F1ScoreResult +from supervision.metrics.mean_average_precision import ( + MeanAveragePrecision, + MeanAveragePrecisionResult, +) +from supervision.metrics.mean_average_recall import ( + MeanAverageRecall, + MeanAverageRecallResult, +) +from supervision.metrics.precision import Precision, PrecisionResult +from supervision.metrics.recall import Recall, RecallResult +from supervision.metrics.utils.object_size import ( + ObjectSizeCategory, + get_detection_size_category, + get_object_size_category, +) + +__all__ = [ + "AveragingMethod", + "F1Score", + "F1ScoreResult", + "MeanAveragePrecision", + "MeanAveragePrecisionResult", + "MeanAverageRecall", + "MeanAverageRecallResult", + "Metric", + "MetricTarget", + "ObjectSizeCategory", + "Precision", + "PrecisionResult", + "Recall", + "RecallResult", + "get_detection_size_category", + "get_object_size_category", +] diff --git a/.venv/lib/python3.12/site-packages/supervision/metrics/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/metrics/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..95063effbfbbc7d2cb0f08fe8b2bcec009879baf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/metrics/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/metrics/__pycache__/core.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/metrics/__pycache__/core.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a226368f913af647966f7ef25386f9203b76eeb4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/metrics/__pycache__/core.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/metrics/__pycache__/detection.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/metrics/__pycache__/detection.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc492bb8f2e5639a0c5abdfcc580b605cb6179ec Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/metrics/__pycache__/detection.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/metrics/__pycache__/f1_score.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/metrics/__pycache__/f1_score.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fe8d2310ea304c22f9d9e2108f3894f280b9e7e2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/metrics/__pycache__/f1_score.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/metrics/__pycache__/mean_average_precision.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/metrics/__pycache__/mean_average_precision.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7351c06607ff53e8681ec4b50ca791f62d437709 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/metrics/__pycache__/mean_average_precision.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/metrics/__pycache__/mean_average_recall.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/metrics/__pycache__/mean_average_recall.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eca7c95658aa87c030d87639d943a4f874e9a8d8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/metrics/__pycache__/mean_average_recall.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/metrics/__pycache__/precision.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/metrics/__pycache__/precision.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d1ff2f286e6b5ab571d84f8365f5692ca938c5c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/metrics/__pycache__/precision.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/metrics/__pycache__/recall.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/metrics/__pycache__/recall.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb3a83a019c1d40320084682162cc29577bd370d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/metrics/__pycache__/recall.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/metrics/core.py b/.venv/lib/python3.12/site-packages/supervision/metrics/core.py new file mode 100644 index 0000000000000000000000000000000000000000..347b61dda18bba316925fc590f5c43d553ad98d0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/metrics/core.py @@ -0,0 +1,74 @@ +from __future__ import annotations + +from abc import ABC, abstractmethod +from enum import Enum +from typing import Any, Generic, TypeVar + +R = TypeVar("R") + + +class Metric(ABC, Generic[R]): + """ + The base class for all supervision metrics. + """ + + @abstractmethod + def update(self, *args: Any, **kwargs: Any) -> Metric[R]: + """ + Add data to the metric, without computing the result. + Return the metric itself to allow method chaining. + """ + raise NotImplementedError + + @abstractmethod + def reset(self) -> None: + """ + Reset internal metric state. + """ + raise NotImplementedError + + @abstractmethod + def compute(self, *args: Any, **kwargs: Any) -> R: + """ + Compute the metric from the internal state and return the result. + """ + raise NotImplementedError + + +class MetricTarget(Enum): + """ + Specifies what type of detection is used to compute the metric. + + Attributes: + BOXES: xyxy bounding boxes + MASKS: Binary masks + ORIENTED_BOUNDING_BOXES: Oriented bounding boxes (OBB) + """ + + BOXES = "boxes" + MASKS = "masks" + ORIENTED_BOUNDING_BOXES = "obb" + + +class AveragingMethod(Enum): + """ + Defines different ways of averaging the metric results. + + Suppose, before returning the final result, a metric is computed for each class. + How do you combine those to get the final number? + + Attributes: + MACRO: Calculate the metric for each class and average the results. The simplest + averaging method, but it does not take class imbalance into account. + MICRO: Calculate the metric globally by counting the total true positives, false + positives, and false negatives. Micro averaging is useful when you want to + give more importance to classes with more samples. It's also more + appropriate if you have an imbalance in the number of instances per class. + WEIGHTED: Calculate the metric for each class and average the results, weighted + by the number of true instances of each class. Use weighted averaging if + you want to take class imbalance into account. + """ + + MACRO = "macro" + MICRO = "micro" + WEIGHTED = "weighted" diff --git a/.venv/lib/python3.12/site-packages/supervision/metrics/detection.py b/.venv/lib/python3.12/site-packages/supervision/metrics/detection.py new file mode 100644 index 0000000000000000000000000000000000000000..569150176690c8e83ba49c017a07741c47df276c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/metrics/detection.py @@ -0,0 +1,1633 @@ +from __future__ import annotations + +import warnings +from collections.abc import Callable +from dataclasses import dataclass +from pathlib import Path +from typing import TYPE_CHECKING, Any, cast + +import numpy as np +import numpy.typing as npt +from deprecate import ( # type: ignore[import-untyped,unused-ignore] + TargetMode, + deprecated, + deprecated_class, + void, +) + +from supervision.config import ORIENTED_BOX_COORDINATES +from supervision.dataset.core import DetectionDataset +from supervision.detection.core import Detections +from supervision.detection.utils.iou_and_nms import ( + box_iou_batch, + oriented_box_iou_batch, +) +from supervision.metrics.core import MetricTarget +from supervision.metrics.utils.matching import _greedy_match + +if TYPE_CHECKING: + from matplotlib.figure import Figure + + +def _assert_supported_target(metric_target: MetricTarget) -> None: + if metric_target == MetricTarget.MASKS: + raise ValueError( + "MetricTarget.MASKS is not currently supported for ConfusionMatrix." + ) + + +def _validated_class_ids( + values: npt.NDArray[np.float32], + num_classes: int, + role: str, +) -> npt.NDArray[np.int64]: + """Return class ids that are safe to use as confusion-matrix indexes.""" + if values.size == 0: + return np.asarray(values, dtype=np.int64) + + finite = np.isfinite(values) + integral = values == np.floor(values) + if not np.all(finite & integral): + raise ValueError(f"{role} class ids must be finite integers.") + + class_ids = values.astype(np.int64) + invalid = (class_ids < 0) | (class_ids >= num_classes) + if np.any(invalid): + invalid_values = np.unique(class_ids[invalid]).tolist() + raise ValueError( + f"{role} class ids must be in [0, {num_classes - 1}], got {invalid_values}." + ) + return class_ids + + +def detections_to_tensor( + detections: Detections, + with_confidence: bool = False, + metric_target: MetricTarget = MetricTarget.BOXES, +) -> npt.NDArray[np.float32]: + """ + Convert Supervision Detections to a numpy tensor for metric computation. + + Args: + detections: Detections/Targets in the format of sv.Detections. + with_confidence: Whether to include confidence as the last column. + metric_target: The type of detection data to use. + Supports `MetricTarget.BOXES` and + `MetricTarget.ORIENTED_BOUNDING_BOXES`. + + Returns: + Detections as a float32 numpy array. Shape depends on `metric_target` + and `with_confidence`: + + | `metric_target` | `with_confidence` | shape | + |----------------------------------------|-------------------|-----------| + | `MetricTarget.BOXES` | `False` | `(N, 5)` | + | `MetricTarget.BOXES` | `True` | `(N, 6)` | + | `MetricTarget.ORIENTED_BOUNDING_BOXES` | `False` | `(N, 9)` | + | `MetricTarget.ORIENTED_BOUNDING_BOXES` | `True` | `(N, 10)` | + + Column layout: + + - `BOXES`: ``[x_min, y_min, x_max, y_max, class_id [, confidence]]`` + - `ORIENTED_BOUNDING_BOXES`: + ``[x1, y1, x2, y2, x3, y3, x4, y4, class_id [, confidence]]`` + + Raises: + ValueError: If `metric_target` is `MetricTarget.MASKS`. + ValueError: If `detections.class_id` is `None`. + ValueError: If `with_confidence=True` and `detections.confidence` is `None`. + ValueError: If `metric_target` is `MetricTarget.ORIENTED_BOUNDING_BOXES` + and `detections.data` does not contain `ORIENTED_BOX_COORDINATES`, + or if the stored array does not have exactly `N * 8` elements. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> from supervision.metrics.core import MetricTarget + >>> from supervision.config import ORIENTED_BOX_COORDINATES + >>> detections = sv.Detections( + ... xyxy=np.array([[0, 0, 10, 10]], dtype=np.float32), + ... class_id=np.array([0]), + ... confidence=np.array([0.9]), + ... ) + >>> tensor = detections_to_tensor(detections, with_confidence=True) + >>> tensor.shape + (1, 6) + >>> obb_coords = np.array([[0, 0, 10, 0, 10, 10, 0, 10]], dtype=np.float32) + >>> det_obb = sv.Detections( + ... xyxy=np.array([[0, 0, 10, 10]], dtype=np.float32), + ... class_id=np.array([0]), + ... data={ORIENTED_BOX_COORDINATES: obb_coords}, + ... ) + >>> tensor_obb = detections_to_tensor( + ... det_obb, metric_target=MetricTarget.ORIENTED_BOUNDING_BOXES + ... ) + >>> tensor_obb.shape + (1, 9) + + ``` + """ + _assert_supported_target(metric_target) + + if detections.class_id is None: + raise ValueError( + "ConfusionMatrix can only be calculated for Detections with class_id" + ) + + box_data: npt.NDArray[np.float32] + if metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES: + obb = detections.data.get(ORIENTED_BOX_COORDINATES) + if obb is None: + if len(detections) > 0: + raise ValueError( + "ORIENTED_BOUNDING_BOXES requested, but " + f"{ORIENTED_BOX_COORDINATES} is missing from detections.data" + ) + box_data = np.empty((0, 8), dtype=np.float32) + else: + obb_arr = np.asarray(obb, dtype=np.float32) + # Normalize (N, 4, 2) → (N, 8) as produced by from_ultralytics. + if obb_arr.ndim == 3 and obb_arr.shape[1:] == (4, 2): + obb_arr = obb_arr.reshape(-1, 8) + if obb_arr.size != len(detections) * 8: + raise ValueError( + f"Expected {ORIENTED_BOX_COORDINATES} to contain " + f"{len(detections) * 8} elements " + f"(N={len(detections)} detections x 8 coordinates), " + f"but got {obb_arr.size}. " + "Each OBB must be stored as [x1, y1, x2, y2, x3, y3, x4, y4]." + ) + box_data = obb_arr.reshape(-1, 8) + else: + box_data = np.asarray(detections.xyxy, dtype=np.float32) + + arrays_to_concat = [ + box_data, + np.expand_dims(detections.class_id.astype(np.float32), 1), + ] + + if with_confidence: + if detections.confidence is None: + raise ValueError( + "ConfusionMatrix can only be calculated for Detections with confidence" + ) + arrays_to_concat.append(np.expand_dims(detections.confidence, 1)) + + result: npt.NDArray[np.float32] = np.concatenate(arrays_to_concat, axis=1) + return result + + +def _validate_input_tensors( + predictions: list[npt.NDArray[np.float32]], + targets: list[npt.NDArray[np.float32]], + metric_target: MetricTarget = MetricTarget.BOXES, +) -> None: + """ + Checks for shape consistency of input tensors. + """ + if len(predictions) != len(targets): + raise ValueError( + f"Number of predictions ({len(predictions)}) and" + f"targets ({len(targets)}) must be equal." + ) + if len(predictions) > 0: + if not isinstance(predictions[0], np.ndarray) or not isinstance( + targets[0], np.ndarray + ): + raise ValueError( + "Predictions and targets must be lists of numpy arrays. " + f"Got {type(predictions[0])} and {type(targets[0])} instead." + ) + + expected_pred_cols = ( + 10 if metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES else 6 + ) + expected_target_cols = ( + 9 if metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES else 5 + ) + + if predictions[0].shape[1] != expected_pred_cols: + raise ValueError( + f"Predictions must have shape (N, {expected_pred_cols}). " + f"Got {predictions[0].shape} instead." + ) + if targets[0].shape[1] != expected_target_cols: + raise ValueError( + f"Targets must have shape (N, {expected_target_cols}). " + f"Got {targets[0].shape} instead." + ) + + +def _split_detections_by_outcome( + predictions: Detections, + targets: Detections, + conf_threshold: float, + iou_threshold: float, + metric_target: MetricTarget = MetricTarget.BOXES, +) -> tuple[Detections, Detections, Detections]: + """ + Split detections into true positives, false positives, and false negatives. + + Matching follows the same attribution logic as + ``ConfusionMatrix.evaluate_detection_batch``: + - matches are computed globally across classes + - same-class matches are prioritized + - higher-IoU matches are preferred + - each prediction and target can be matched at most once + + Cross-class spatial matches are treated as: + - false positives for the prediction + - false negatives for the target + + Args: + predictions: Predicted detections for a single image. + targets: Ground-truth detections for a single image. + conf_threshold: Confidence threshold; predictions below this are excluded. + iou_threshold: IoU threshold; candidate pairs below this are not matched. + metric_target: Coordinate representation to use for IoU computation. + Use ``MetricTarget.ORIENTED_BOUNDING_BOXES`` for rotated-box datasets. + + Returns: + A 3-tuple ``(true_positives, false_positives, false_negatives)`` where + each element is a ``Detections`` instance sliced from the input arrays. + """ + + if predictions.class_id is None: + raise ValueError("Predictions must contain class_id values.") + + if targets.class_id is None: + raise ValueError("Targets must contain class_id values.") + + target_class_ids = targets.class_id + + if predictions.confidence is None: + filtered_predictions = predictions + else: + prediction_confidence = np.asarray(predictions.confidence, dtype=np.float32) + filtered_predictions = predictions.select( + prediction_confidence >= conf_threshold + ) + + filtered_prediction_class_ids = filtered_predictions.class_id + if filtered_prediction_class_ids is None: + raise ValueError("Predictions must contain class_id values.") + + prediction_count = len(filtered_predictions) + target_count = len(targets) + + tp_indices: list[int] = [] + fp_indices: list[int] = [] + fn_indices: list[int] = [] + + if prediction_count == 0: + fn_indices = list(range(target_count)) + return ( + filtered_predictions.select(tp_indices), + filtered_predictions.select(fp_indices), + targets.select(fn_indices), + ) + + if target_count == 0: + fp_indices = list(range(prediction_count)) + return ( + filtered_predictions.select(tp_indices), + filtered_predictions.select(fp_indices), + targets.select(fn_indices), + ) + + # IoU computation mirrors evaluate_detection_batch — keep in sync if either changes. + if metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES: + iou_matrix = oriented_box_iou_batch( + boxes_true=np.asarray( + targets.data[ORIENTED_BOX_COORDINATES], dtype=np.float32 + ).reshape(len(targets), 8), + boxes_detection=np.asarray( + filtered_predictions.data[ORIENTED_BOX_COORDINATES], dtype=np.float32 + ).reshape(len(filtered_predictions), 8), + ) + else: + iou_matrix = box_iou_batch( + boxes_true=targets.xyxy, + boxes_detection=filtered_predictions.xyxy, + ) + + target_candidate_indices, prediction_candidate_indices = np.where( + iou_matrix > iou_threshold + ) + + matched_predictions: npt.NDArray[np.bool_] = np.zeros(prediction_count, dtype=bool) + matched_targets: npt.NDArray[np.bool_] = np.zeros(target_count, dtype=bool) + + cross_class_prediction_indices: list[int] = [] + cross_class_target_indices: list[int] = [] + + if len(target_candidate_indices) > 0: + candidate_ious = iou_matrix[ + target_candidate_indices, + prediction_candidate_indices, + ] + + same_class_candidates = ( + target_class_ids[target_candidate_indices] + == filtered_prediction_class_ids[prediction_candidate_indices] + ) + + candidate_order = np.lexsort( + ( + -candidate_ious, + ~same_class_candidates, + ) + ) + + for candidate_index in candidate_order: + target_index = int(target_candidate_indices[candidate_index]) + prediction_index = int(prediction_candidate_indices[candidate_index]) + + if matched_predictions[prediction_index] or matched_targets[target_index]: + continue + + matched_predictions[prediction_index] = True + matched_targets[target_index] = True + + prediction_class = filtered_prediction_class_ids[prediction_index] + target_class = target_class_ids[target_index] + + if prediction_class == target_class: + tp_indices.append(prediction_index) + else: + cross_class_prediction_indices.append(prediction_index) + cross_class_target_indices.append(target_index) + + fp_indices.extend(np.flatnonzero(~matched_predictions).tolist()) + fn_indices.extend(np.flatnonzero(~matched_targets).tolist()) + + fp_indices.extend(cross_class_prediction_indices) + fn_indices.extend(cross_class_target_indices) + + return ( + filtered_predictions.select(tp_indices), + filtered_predictions.select(fp_indices), + targets.select(fn_indices), + ) + + +def _build_error_labels( + detections: Detections, + class_names: list[str] | None, +) -> list[str]: + """Build per-detection label strings for annotation panels. + + Produces labels like ``"cat 0.95"`` (class name + confidence when available) + or numeric class-id strings when ``class_names`` is ``None``. + + Args: + detections: Detections whose labels to build. + class_names: Optional list mapping class integer ids to name strings. + + Returns: + List of label strings, one per detection. Returns empty strings when + ``detections.class_id`` is ``None``. + """ + if detections.class_id is None: + return [""] * len(detections) + + labels: list[str] = [] + for index, class_id in enumerate(detections.class_id): + if class_names is not None and 0 <= int(class_id) < len(class_names): + class_label = class_names[int(class_id)] + else: + class_label = str(int(class_id)) + + confidence = "" + if detections.confidence is not None: + confidence = f" {detections.confidence[index]:.2f}" + + labels.append(f"{class_label}{confidence}") + + return labels + + +def _get_annotation_parameters( + scene: npt.NDArray[np.uint8], +) -> tuple[int, float, int, int, int]: + """Compute adaptive annotation parameters scaled to the panel size. + + Args: + scene: The image panel for which to compute parameters. + + Returns: + A 5-tuple ``(box_thickness, text_scale, text_thickness, text_padding, + font_size)`` where all values are ``int`` except ``text_scale`` (``float``). + """ + height, width = scene.shape[:2] + panel_size = max(min(height, width), 1) + grid_factor = 2 + + font_size = max(18, round(panel_size / (26 * grid_factor))) + box_thickness = max(2, round(font_size / 5)) + text_scale = float(max(1.0, font_size / 20.0)) + text_thickness = max(1, round(font_size / 15.0)) + text_padding = max(6, round(font_size / 3)) + + return box_thickness, text_scale, text_thickness, text_padding, font_size + + +def _annotate_detection_panel( + scene: npt.NDArray[np.uint8], + detections: Detections, + title: str, + class_names: list[str] | None, + annotation_parameters: tuple[int, float, int, int, int], +) -> npt.NDArray[np.uint8]: + """Render detections onto a copy of ``scene`` with a title overlay. + + Args: + scene: Source image panel (not mutated). + detections: Detections to annotate on the panel. + title: Text label rendered in the top-left corner of the panel. + class_names: Optional list mapping class integer ids to name strings. + annotation_parameters: Pre-computed parameters from + ``_get_annotation_parameters``. + + Returns: + Annotated copy of ``scene`` as a ``np.uint8`` array. + """ + from supervision import ( + _cv2 as cv2, # lazy: only needed when save_directory_path is set + ) + from supervision.annotators.core import BoxAnnotator, LabelAnnotator + from supervision.annotators.utils import ColorLookup + from supervision.draw.color import ColorPalette + + panel = scene.copy() + + box_thickness, text_scale, text_thickness, text_padding, font_size = ( + annotation_parameters + ) + + if len(detections) > 0: + box_annotator = BoxAnnotator( + color=ColorPalette.DEFAULT, + color_lookup=ColorLookup.CLASS, + thickness=box_thickness, + ) + label_annotator = LabelAnnotator( + color=ColorPalette.DEFAULT, + color_lookup=ColorLookup.CLASS, + text_scale=text_scale, + text_thickness=text_thickness, + text_padding=text_padding, + ) + labels = _build_error_labels(detections, class_names) + panel = box_annotator.annotate(panel, detections) + panel = cast( + npt.NDArray[np.uint8], + label_annotator.annotate(cast(Any, panel), detections, labels=labels), + ) + + title_scale = float(max(1.0, font_size / 18.0)) + title_thickness = max(2, round(font_size / 8)) + panel_height, panel_width = panel.shape[:2] + (title_width, title_height), title_baseline = cv2.getTextSize( + title, + cv2.FONT_HERSHEY_SIMPLEX, + title_scale, + title_thickness, + ) + title_x = max(0, min(text_padding, panel_width - title_width - 1)) + title_y = max(title_height + text_padding, 0) + title_y = min(title_y, max(panel_height - title_baseline - 1, 0)) + + cv2.putText( + panel, + title, + (title_x, title_y), + cv2.FONT_HERSHEY_SIMPLEX, + title_scale, + (240, 240, 240), + title_thickness, + cv2.LINE_AA, + ) + panel_array: npt.NDArray[np.uint8] = panel + return panel_array + + +def _save_detection_validation_visualization( + scene: npt.NDArray[np.uint8], + predictions: Detections, + targets: Detections, + save_path: Path, + conf_threshold: float, + iou_threshold: float, + class_names: list[str] | None, + metric_target: MetricTarget = MetricTarget.BOXES, +) -> None: + """Build and save a 2x2 GT/TP/FP/FN mosaic for one image. + + Splits ``predictions`` into true-positive, false-positive, and false-negative + groups using the same matching logic as + ``ConfusionMatrix.evaluate_detection_batch``, renders four annotation panels, + concatenates them into a 2x2 grid, and writes the result to ``save_path``. + + A ``UserWarning`` is emitted if ``cv2.imwrite`` fails (e.g. unsupported + extension or permission error); the benchmark loop continues regardless. + + Args: + scene: The original image for this dataset entry. + predictions: Raw model predictions for ``scene``. + targets: Ground-truth annotations for ``scene``. + save_path: Destination file path for the mosaic image. + conf_threshold: Confidence threshold forwarded to + ``_split_detections_by_outcome``. + iou_threshold: IoU threshold forwarded to ``_split_detections_by_outcome``. + class_names: Optional list mapping class integer ids to name strings. + metric_target: Coordinate representation used for IoU matching. + """ + from supervision import ( + _cv2 as cv2, # lazy: only needed when save_directory_path is set + ) + + tp_predictions, fp_predictions, fn_targets = _split_detections_by_outcome( + predictions=predictions, + targets=targets, + conf_threshold=conf_threshold, + iou_threshold=iou_threshold, + metric_target=metric_target, + ) + + annotation_parameters = _get_annotation_parameters(scene) + + gt_panel = _annotate_detection_panel( + scene=scene, + detections=targets, + title="Ground Truth", + class_names=class_names, + annotation_parameters=annotation_parameters, + ) + tp_panel = _annotate_detection_panel( + scene=scene, + detections=tp_predictions, + title="True Positives", + class_names=class_names, + annotation_parameters=annotation_parameters, + ) + fp_panel = _annotate_detection_panel( + scene=scene, + detections=fp_predictions, + title="False Positives", + class_names=class_names, + annotation_parameters=annotation_parameters, + ) + fn_panel = _annotate_detection_panel( + scene=scene, + detections=fn_targets, + title="False Negatives", + class_names=class_names, + annotation_parameters=annotation_parameters, + ) + + top_row = np.concatenate((gt_panel, tp_panel), axis=1) + bottom_row = np.concatenate((fp_panel, fn_panel), axis=1) + result = np.concatenate((top_row, bottom_row), axis=0) + + panel_height = result.shape[0] // 2 + panel_width = result.shape[1] // 2 + divider_thickness = max(1, min(8, min(panel_height, panel_width) // 32)) + + cv2.rectangle( + result, + (0, 0), + (result.shape[1] - 1, result.shape[0] - 1), + (255, 255, 255), + thickness=divider_thickness, + ) + + center_x = result.shape[1] // 2 + center_y = result.shape[0] // 2 + cv2.line( + result, + (center_x, 0), + (center_x, result.shape[0] - 1), + (255, 255, 255), + divider_thickness, + ) + cv2.line( + result, + (0, center_y), + (result.shape[1] - 1, center_y), + (255, 255, 255), + divider_thickness, + ) + + write_success = cv2.imwrite(str(save_path), result) + if not write_success: + warnings.warn( + f"Failed to write validation image to '{save_path}'.", + UserWarning, + stacklevel=2, + ) + + +@deprecated( # type: ignore[untyped-decorator] + target=_validate_input_tensors, + deprecated_in="0.29.0", + remove_in="0.32.0", +) +def validate_input_tensors( + predictions: list[npt.NDArray[np.float32]], + targets: list[npt.NDArray[np.float32]], +) -> None: + void(predictions, targets) + + +@dataclass +class ConfusionMatrix: + """ + Confusion matrix for object detection tasks. + + Attributes: + matrix: An 2D `np.ndarray` of shape `(len(classes) + 1, len(classes) + 1)` + containing the number of `TP`, `FP`, `FN` and `TN` for each class. + classes: Model class names. + conf_threshold: Detection confidence threshold between `0` and `1`. + Detections with lower confidence will be excluded from the matrix. + iou_threshold: Detection IoU threshold between `0` and `1`. + Detections with lower IoU will be classified as `FP`. + metric_target: The type of detection data used for IoU computation. + Informational metadata set by `from_detections` and `from_tensors`. + Excluded from `__eq__` comparisons — two `ConfusionMatrix` instances + with identical `matrix`, `classes`, `conf_threshold`, and + `iou_threshold` compare as equal regardless of `metric_target`. + """ + + matrix: npt.NDArray[np.int32] + classes: list[str] + conf_threshold: float + iou_threshold: float + metric_target: MetricTarget = MetricTarget.BOXES + + def __eq__(self, other: object) -> bool: + if not isinstance(other, ConfusionMatrix): + return NotImplemented + return ( + np.array_equal(self.matrix, other.matrix) + and self.classes == other.classes + and self.conf_threshold == other.conf_threshold + and self.iou_threshold == other.iou_threshold + ) + + __hash__ = None # type: ignore[assignment] + + @classmethod + def from_detections( + cls, + predictions: list[Detections], + targets: list[Detections], + classes: list[str], + conf_threshold: float = 0.3, + iou_threshold: float = 0.5, + metric_target: MetricTarget = MetricTarget.BOXES, + ) -> ConfusionMatrix: + """ + Calculate confusion matrix based on predicted and ground-truth detections. + + Args: + targets: Detections objects from ground-truth. + predictions: Detections objects predicted by the model. + classes: Model class names. + conf_threshold: Detection confidence threshold between `0` and `1`. + Detections with lower confidence will be excluded. + iou_threshold: Detection IoU threshold between `0` and `1`. + Detections with lower IoU will be classified as `FP`. + metric_target: The type of detection data to use. + Supports `MetricTarget.BOXES` (default) and + `MetricTarget.ORIENTED_BOUNDING_BOXES`. When using + `MetricTarget.ORIENTED_BOUNDING_BOXES`, each `Detections` + object must include OBB coordinates in + `detections.data[ORIENTED_BOX_COORDINATES]` as a float32 + array of shape `(N, 8)` (flat) or `(N, 4, 2)` (as stored by + `from_ultralytics`); both are normalised to `(N, 8)` internally. + `MetricTarget.MASKS` is not supported. + + Returns: + New instance of ConfusionMatrix. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> targets = [ + ... sv.Detections( + ... xyxy=np.array([[0, 0, 10, 10], [50, 50, 60, 60]]), + ... class_id=np.array([0, 0]) + ... ) + ... ] + >>> predictions = [ + ... sv.Detections( + ... xyxy=np.array([[0, 0, 10, 10], [100, 100, 110, 110]]), + ... class_id=np.array([0, 0]), + ... confidence=np.array([0.9, 0.8]) + ... ) + ... ] + >>> confusion_matrix = sv.ConfusionMatrix.from_detections( + ... predictions=predictions, + ... targets=targets, + ... classes=['person'] + ... ) + >>> confusion_matrix.matrix + array([[1, 1], + [1, 0]], dtype=int32) + + ``` + """ + prediction_tensors = [] + target_tensors = [] + for prediction, target in zip(predictions, targets): + prediction_tensors.append( + detections_to_tensor( + prediction, with_confidence=True, metric_target=metric_target + ) + ) + target_tensors.append( + detections_to_tensor( + target, with_confidence=False, metric_target=metric_target + ) + ) + return cls.from_tensors( + predictions=prediction_tensors, + targets=target_tensors, + classes=classes, + conf_threshold=conf_threshold, + iou_threshold=iou_threshold, + metric_target=metric_target, + ) + + @classmethod + def from_tensors( + cls, + predictions: list[npt.NDArray[np.float32]], + targets: list[npt.NDArray[np.float32]], + classes: list[str], + conf_threshold: float = 0.3, + iou_threshold: float = 0.5, + metric_target: MetricTarget = MetricTarget.BOXES, + ) -> ConfusionMatrix: + """ + Calculate confusion matrix based on predicted and ground-truth detections. + + Args: + predictions: Each element of the list describes a single + image and has `shape = (M, 6)` or `shape = (M, 10)` depending on + `metric_target`. + If `MetricTarget.BOXES`, each row is in + `(x_min, y_min, x_max, y_max, class, conf)` format. + If `MetricTarget.ORIENTED_BOUNDING_BOXES`, each row is in + `(x1, y1, x2, y2, x3, y3, x4, y4, class, conf)` format. + targets: Each element of the list describes a single + image and has `shape = (N, 5)` or `shape = (N, 9)` depending on + `metric_target`. + If `MetricTarget.BOXES`, each row is in + `(x_min, y_min, x_max, y_max, class)` format. + If `MetricTarget.ORIENTED_BOUNDING_BOXES`, each row is in + `(x1, y1, x2, y2, x3, y3, x4, y4, class)` format. + classes: Model class names. + conf_threshold: Detection confidence threshold between `0` and `1`. + Detections with lower confidence will be excluded. + iou_threshold: Detection iou threshold between `0` and `1`. + Detections with lower iou will be classified as `FP`. + metric_target: The type of detection data to use. + Determines expected tensor shapes (see Args above for column + layouts). `MetricTarget.MASKS` is not supported. + + Returns: + New instance of ConfusionMatrix. + + Examples: + ```pycon + >>> import supervision as sv + >>> import numpy as np + >>> targets = [ + ... np.array([ + ... [0.0, 0.0, 3.0, 3.0, 0], + ... [2.0, 2.0, 5.0, 5.0, 0], + ... [6.0, 1.0, 8.0, 3.0, 1], + ... ]) + ... ] + >>> predictions = [ + ... np.array([ + ... [0.0, 0.0, 3.0, 3.0, 0, 0.9], + ... [0.1, 0.1, 3.0, 3.0, 0, 0.9], + ... [6.0, 1.0, 8.0, 3.0, 1, 0.8], + ... ]) + ... ] + >>> confusion_matrix = sv.ConfusionMatrix.from_tensors( + ... predictions=predictions, + ... targets=targets, + ... classes=['person', 'dog'] + ... ) + >>> confusion_matrix.matrix + array([[1, 0, 1], + [0, 1, 0], + [1, 0, 0]], dtype=int32) + + ``` + """ + _assert_supported_target(metric_target) + _validate_input_tensors(predictions, targets, metric_target=metric_target) + + num_classes = len(classes) + matrix: npt.NDArray[np.int32] = np.zeros( + (num_classes + 1, num_classes + 1), dtype=np.int32 + ) + for true_batch, detection_batch in zip(targets, predictions): + matrix += cls.evaluate_detection_batch( + predictions=detection_batch, + targets=true_batch, + num_classes=num_classes, + conf_threshold=conf_threshold, + iou_threshold=iou_threshold, + metric_target=metric_target, + ) + return cls( + matrix=matrix, + classes=classes, + conf_threshold=conf_threshold, + iou_threshold=iou_threshold, + metric_target=metric_target, + ) + + @staticmethod + def evaluate_detection_batch( + predictions: npt.NDArray[np.float32], + targets: npt.NDArray[np.float32], + num_classes: int, + conf_threshold: float, + iou_threshold: float, + metric_target: MetricTarget = MetricTarget.BOXES, + ) -> npt.NDArray[np.int32]: + """ + Calculate confusion matrix for a batch of detections for a single image. + + Args: + predictions: Batch prediction. Describes a single image and + has `shape = (M, 6)` or `shape = (M, 10)` depending on + `metric_target`. + If `MetricTarget.BOXES`, each row is in + `(x_min, y_min, x_max, y_max, class, conf)` format. + If `MetricTarget.ORIENTED_BOUNDING_BOXES`, each row is in + `(x1, y1, x2, y2, x3, y3, x4, y4, class, conf)` format. + targets: Batch target labels. Describes a single image and + has `shape = (N, 5)` or `shape = (N, 9)` depending on + `metric_target`. + If `MetricTarget.BOXES`, each row is in + `(x_min, y_min, x_max, y_max, class)` format. + If `MetricTarget.ORIENTED_BOUNDING_BOXES`, each row is in + `(x1, y1, x2, y2, x3, y3, x4, y4, class)` format. + num_classes: Number of classes. + conf_threshold: Detection confidence threshold between `0` and `1`. + Detections with lower confidence will be excluded. + iou_threshold: Detection iou threshold between `0` and `1`. + Detections with lower iou will be classified as `FP`. + metric_target: The type of detection data to use. + Determines IoU function (`box_iou_batch` vs + `oriented_box_iou_batch`) and coordinate column count. + `MetricTarget.MASKS` is not supported. + + Returns: + Confusion matrix based on a single image. + """ + _assert_supported_target(metric_target) + + expected_pred_cols = ( + 10 if metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES else 6 + ) + expected_target_cols = ( + 9 if metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES else 5 + ) + if predictions.ndim != 2 or predictions.shape[1] != expected_pred_cols: + raise ValueError( + f"Predictions must have shape (M, {expected_pred_cols}). " + f"Got {predictions.shape} instead." + ) + if targets.ndim != 2 or targets.shape[1] != expected_target_cols: + raise ValueError( + f"Targets must have shape (N, {expected_target_cols}). " + f"Got {targets.shape} instead." + ) + + result_matrix: npt.NDArray[np.int32] = np.zeros( + (num_classes + 1, num_classes + 1), dtype=np.int32 + ) + + # Filter predictions by confidence threshold + coords_dim = 8 if metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES else 4 + class_id_idx = coords_dim + conf_idx = coords_dim + 1 + + confidence = predictions[:, conf_idx] + detection_batch_filtered = predictions[confidence >= conf_threshold] + + if len(detection_batch_filtered) == 0: + true_classes = _validated_class_ids( + targets[:, class_id_idx], num_classes, "Target" + ) + for gt_class in true_classes: + result_matrix[gt_class, num_classes] += 1 + return result_matrix + + if len(targets) == 0: + detection_classes = _validated_class_ids( + detection_batch_filtered[:, class_id_idx], num_classes, "Prediction" + ) + for det_class in detection_classes: + result_matrix[num_classes, det_class] += 1 + return result_matrix + + true_classes = _validated_class_ids( + targets[:, class_id_idx], num_classes, "Target" + ) + detection_classes = _validated_class_ids( + detection_batch_filtered[:, class_id_idx], num_classes, "Prediction" + ) + true_boxes = targets[:, :coords_dim] + detection_boxes = detection_batch_filtered[:, :coords_dim] + + # Calculate IoU matrix + if metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES: + iou_batch = oriented_box_iou_batch( + boxes_true=true_boxes, boxes_detection=detection_boxes + ) + else: + iou_batch = box_iou_batch( + boxes_true=true_boxes, boxes_detection=detection_boxes + ) + + # Find all valid matches (IoU > threshold, regardless of class) + # Use vectorized operations to avoid nested Python loops + iou_mask = iou_batch > iou_threshold + gt_indices, det_indices = np.nonzero(iou_mask) + + # If no pairs exceed the IoU threshold, skip matching + if gt_indices.size == 0: + valid_matches = [] + else: + ious = iou_batch[gt_indices, det_indices] + gt_match_classes = true_classes[gt_indices] + det_match_classes = detection_classes[det_indices] + class_matches = gt_match_classes == det_match_classes + + # Sort matches by class match first (True before False), + # then by IoU descending. + # np.lexsort sorts by the last key first, in ascending order. + # We use ~class_matches so that True becomes 0 + # and False becomes 1 (True first), + # and -ious so that larger IoUs come first. + sort_indices = np.lexsort((-ious, ~class_matches)) + + # Build list of matches in the same format as before: + # (gt_idx, det_idx, iou, class_match) + valid_matches = [ + ( + int(gt_indices[idx]), + int(det_indices[idx]), + float(ious[idx]), + bool(class_matches[idx]), + ) + for idx in sort_indices + ] + # Greedily assign matches, ensuring each GT + # and detection is matched at most once + matched_gt_idx = set() + matched_det_idx = set() + + for gt_idx, det_idx, iou, class_match in valid_matches: + if gt_idx not in matched_gt_idx and det_idx not in matched_det_idx: + # Valid spatial match - record the class prediction + gt_class = true_classes[gt_idx] + det_class = detection_classes[det_idx] + + # This handles both correct classification (TP) and misclassification + result_matrix[gt_class, det_class] += 1 + matched_gt_idx.add(gt_idx) + matched_det_idx.add(det_idx) + + # Count unmatched ground truth as FN + for gt_idx, gt_class in enumerate(true_classes): + if gt_idx not in matched_gt_idx: + result_matrix[gt_class, num_classes] += 1 + + # Count unmatched detections as FP + for det_idx, det_class in enumerate(detection_classes): + if det_idx not in matched_det_idx: + result_matrix[num_classes, det_class] += 1 + + return result_matrix + + @staticmethod + def _drop_extra_matches( + matches: npt.NDArray[np.float32], + ) -> npt.NDArray[np.float32]: + """ + Deduplicate matches. If there are multiple matches for the same true or + predicted box, only the one with the highest IoU is kept. + """ + if matches.shape[0] > 0: + matches = matches[matches[:, 2].argsort()[::-1]] + matches = matches[np.unique(matches[:, 1], return_index=True)[1]] + matches = matches[matches[:, 2].argsort()[::-1]] + matches = matches[np.unique(matches[:, 0], return_index=True)[1]] + result: npt.NDArray[np.float32] = matches + return result + + @classmethod + def benchmark( + cls, + dataset: DetectionDataset, + callback: Callable[[npt.NDArray[np.uint8]], Detections], + conf_threshold: float = 0.3, + iou_threshold: float = 0.5, + metric_target: MetricTarget = MetricTarget.BOXES, + *, + save_directory_path: str | Path | None = None, + ) -> ConfusionMatrix: + """ + Calculate confusion matrix from dataset and callback function. + + Args: + dataset: Object detection dataset used for evaluation. + callback: Function that takes an image as input and returns a + Detections object. + conf_threshold: Detection confidence threshold between `0` and `1`. + Detections with lower confidence will be excluded. + iou_threshold: Detection IoU threshold between `0` and `1`. + Detections with lower IoU will be classified as `FP`. + save_directory_path: Optional directory where per-image validation + result grids are saved using the original image filenames. Images + are written directly to this directory (no subdirectory is added). + When ``None`` (default), no images are saved. + metric_target: The type of detection data to use. + Supports `MetricTarget.BOXES` and + `MetricTarget.ORIENTED_BOUNDING_BOXES`. Passed through to + `from_detections`. `MetricTarget.MASKS` is not supported. + + Returns: + New instance of ConfusionMatrix. + + Example: + ```python + import supervision as sv + from rfdetr import RFDETRMedium + + dataset = sv.DetectionDataset.from_yolo(...) + + model = RFDETRMedium() + def callback(image: np.ndarray) -> sv.Detections: + return model.predict(image[:, :, ::-1]) + + confusion_matrix = sv.ConfusionMatrix.benchmark( + dataset = dataset, + callback = callback + ) + + print(confusion_matrix.matrix) + # np.array([ + # [0., 0., 0., 0.], + # [0., 1., 0., 1.], + # [0., 1., 1., 0.], + # [1., 1., 0., 0.] + # ]) + ``` + """ + if save_directory_path is not None: + save_directory = Path(save_directory_path) + save_directory.mkdir(parents=True, exist_ok=True) + + predictions, targets = [], [] + for index, (image_name, image, annotation) in enumerate(dataset): + predictions_batch = callback(image) + predictions.append(predictions_batch) + targets.append(annotation) + + if save_directory_path is not None: + if isinstance(image_name, Path): + image_filename = image_name.name + elif isinstance(image_name, str): + image_filename = Path(image_name).name + else: + image_filename = f"image_{index:06d}.jpg" + + if Path(image_filename).suffix == "": + image_filename = f"{image_filename}.jpg" + + save_path = save_directory / image_filename + if save_path.exists(): + warnings.warn( + f"Validation image '{image_filename}' already exists at " + f"'{save_path}' and will be overwritten.", + UserWarning, + stacklevel=2, + ) + _save_detection_validation_visualization( + scene=image, + predictions=predictions_batch, + targets=annotation, + save_path=save_path, + conf_threshold=conf_threshold, + iou_threshold=iou_threshold, + class_names=dataset.classes, + metric_target=metric_target, + ) + return cls.from_detections( + predictions=predictions, + targets=targets, + classes=dataset.classes, + conf_threshold=conf_threshold, + iou_threshold=iou_threshold, + metric_target=metric_target, + ) + + def plot( + self, + save_path: str | None = None, + title: str | None = None, + classes: list[str] | None = None, + normalize: bool = False, + fig_size: tuple[int, int] = (12, 10), + ) -> Figure: + """ + Create confusion matrix plot and save it at selected location. + + Args: + save_path: Path to save the plot. If not provided, + plot will be displayed. + title: Title of the plot. + classes: List of classes to be displayed on the plot. + If not provided, all classes will be displayed. + normalize: If True, normalize the confusion matrix. + fig_size: Size of the plot. + + Returns: + Confusion matrix plot. + """ + from matplotlib import pyplot as plt + + # Cast to float so that the NaN masking below never hits an integer + # matrix (assigning NaN into an int array raises ValueError). + array = self.matrix.astype(np.float64) + + if normalize: + eps = 1e-8 + array = array / (array.sum(0).reshape(1, -1) + eps) + + array[array < 0.005] = np.nan + + fig, ax = plt.subplots(figsize=fig_size, tight_layout=True, facecolor="white") + + class_names = classes if classes is not None else self.classes + use_labels_for_ticks = class_names is not None and (0 < len(class_names) < 99) + if use_labels_for_ticks: + x_tick_labels = [*class_names, "FN"] + y_tick_labels = [*class_names, "FP"] + num_ticks = len(x_tick_labels) + else: + x_tick_labels = None + y_tick_labels = None + num_ticks = len(array) + im = ax.imshow(array, cmap="Blues") + + cbar = ax.figure.colorbar(im, ax=ax) + cbar.mappable.set_clim(vmin=0, vmax=float(np.nanmax(array))) + + if x_tick_labels is None: + tick_interval = 2 + else: + tick_interval = 1 + ax.set_xticks(np.arange(0, num_ticks, tick_interval), labels=x_tick_labels) + ax.set_yticks(np.arange(0, num_ticks, tick_interval), labels=y_tick_labels) + + plt.setp(ax.get_xticklabels(), rotation=90, ha="right", rotation_mode="default") + + labelsize = 10 if num_ticks < 50 else 8 + ax.tick_params(axis="both", which="both", labelsize=labelsize) + + if num_ticks < 30: + for i in range(array.shape[0]): + for j in range(array.shape[1]): + n_preds = array[i, j] + if not np.isnan(n_preds): + ax.text( + j, + i, + f"{n_preds:.2f}" if normalize else f"{n_preds:.0f}", + ha="center", + va="center", + color="black" + if n_preds < 0.5 * np.nanmax(array) + else "white", + ) + + if title: + ax.set_title(title, fontsize=20) + + ax.set_xlabel("Predicted") + ax.set_ylabel("True") + ax.set_facecolor("white") + if save_path: + fig.savefig( + save_path, dpi=250, facecolor=fig.get_facecolor(), transparent=True + ) + return fig + + +@deprecated_class( + target=TargetMode.NOTIFY, + deprecated_in="0.27.0", + remove_in="0.31.0", +) +@dataclass(frozen=True) +class MeanAveragePrecision: + """ + !!! deprecated "Deprecated" + `MeanAveragePrecision` is **deprecated** and will be removed in + `supervision-0.31.0`. + + The deprecated implementation provides results that are inconsistent with + `pycocotools`. Please use + `supervision.metrics.mean_average_precision.MeanAveragePrecision` instead, + which matches the results of `pycocotools` and is now the recommended approach. + + Mean Average Precision for object detection tasks. + + Attributes: + map50_95: Mean Average Precision (mAP) calculated over IoU thresholds + ranging from `0.50` to `0.95` with a step size of `0.05`. + map50: Mean Average Precision (mAP) calculated specifically at + an IoU threshold of `0.50`. + map75: Mean Average Precision (mAP) calculated specifically at + an IoU threshold of `0.75`. + per_class_ap50_95: Average Precision (AP) values calculated over + IoU thresholds ranging from `0.50` to `0.95` with a step size of `0.05`, + provided for each individual class. + """ + + map50_95: float + map50: float + map75: float + per_class_ap50_95: npt.NDArray[np.float64] + + @classmethod + def from_detections( + cls, + predictions: list[Detections], + targets: list[Detections], + ) -> MeanAveragePrecision: + """ + Calculate mean average precision based on predicted and ground-truth detections. + + Args: + targets: Detections objects from ground-truth. + predictions: Detections objects predicted by the model. + Returns: + New instance of ConfusionMatrix. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> targets = [ + ... sv.Detections( + ... xyxy=np.array([[0, 0, 10, 10]]), + ... class_id=np.array([0]) + ... ) + ... ] + >>> predictions = [ + ... sv.Detections( + ... xyxy=np.array([[0, 0, 10, 10]]), + ... class_id=np.array([0]), + ... confidence=np.array([0.9]) + ... ) + ... ] + >>> mAP = sv.MeanAveragePrecision.from_detections( + ... predictions=predictions, + ... targets=targets, + ... ) + >>> round(float(mAP.map50), 2) + 1.0 + + ``` + """ + prediction_tensors = [] + target_tensors = [] + for prediction, target in zip(predictions, targets): + prediction_tensors.append( + detections_to_tensor(prediction, with_confidence=True) + ) + target_tensors.append(detections_to_tensor(target, with_confidence=False)) + return cls.from_tensors( + predictions=prediction_tensors, + targets=target_tensors, + ) + + @classmethod + def benchmark( + cls, + dataset: DetectionDataset, + callback: Callable[[npt.NDArray[np.uint8]], Detections], + ) -> MeanAveragePrecision: + """ + Calculate mean average precision from dataset and callback function. + + Args: + dataset: Object detection dataset used for evaluation. + callback: Function that takes + an image as input and returns Detections object. + Returns: + New instance of MeanAveragePrecision. + + Example: + ```python + import supervision as sv + from rfdetr import RFDETRMedium + + dataset = sv.DetectionDataset.from_yolo(...) + + model = RFDETRMedium() + def callback(image: np.ndarray) -> sv.Detections: + return model.predict(image[:, :, ::-1]) + + mean_average_precision = sv.MeanAveragePrecision.benchmark( + dataset = dataset, + callback = callback + ) + + print(mean_average_precision.map50_95) + # 0.433 + ``` + """ + predictions, targets = [], [] + for _, image, annotation in dataset: + predictions_batch = callback(image) + predictions.append(predictions_batch) + targets.append(annotation) + return cls.from_detections( + predictions=predictions, + targets=targets, + ) + + @classmethod + def from_tensors( + cls, + predictions: list[npt.NDArray[np.float32]], + targets: list[npt.NDArray[np.float32]], + ) -> MeanAveragePrecision: + """ + Calculate Mean Average Precision based on predicted and ground-truth + detections at different threshold. + + Args: + predictions: Each element of the list describes + a single image and has `shape = (M, 6)` where `M` is + the number of detected objects. Each row is expected to be + in `(x_min, y_min, x_max, y_max, class, conf)` format. + targets: Each element of the list describes a single + image and has `shape = (N, 5)` where `N` is the + number of ground-truth objects. Each row is expected to be in + `(x_min, y_min, x_max, y_max, class)` format. An empty array + (``N = 0``) represents a background image; all predictions on + that image count as false positives and reduce AP accordingly. + + Returns: + MeanAveragePrecision: New instance computed from the provided + predictions and targets. + + Examples: + ```pycon + >>> import supervision as sv + >>> import numpy as np + >>> targets = [ + ... np.array([ + ... [0.0, 0.0, 3.0, 3.0, 0], + ... [2.0, 2.0, 5.0, 5.0, 0], + ... [6.0, 1.0, 8.0, 3.0, 1], + ... ]) + ... ] + >>> predictions = [ + ... np.array([ + ... [0.0, 0.0, 3.0, 3.0, 0, 0.9], + ... [0.1, 0.1, 3.0, 3.0, 0, 0.9], + ... [6.0, 1.0, 8.0, 3.0, 1, 0.8], + ... ]) + ... ] + >>> mAP = sv.MeanAveragePrecision.from_tensors( + ... predictions=predictions, + ... targets=targets, + ... ) + >>> round(float(mAP.map50), 2) + 0.75 + + >>> bg_pred = [np.array([[0., 0., 10., 10., 0, 0.9]], dtype=np.float32)] + >>> bg_tgt = [np.zeros((0, 5), dtype=np.float32)] + >>> mAP_bg = sv.MeanAveragePrecision.from_tensors( + ... predictions=bg_pred, + ... targets=bg_tgt, + ... ) + >>> float(mAP_bg.map50) + 0.0 + + ``` + """ + _validate_input_tensors(predictions, targets) + iou_thresholds = np.linspace(0.5, 0.95, 10, dtype=np.float32) + stats = [] + + # Gather matching stats for predictions and targets + for true_objs, predicted_objs in zip(targets, predictions): + if predicted_objs.shape[0] == 0: + if true_objs.shape[0]: + stats.append( + ( + np.zeros((0, iou_thresholds.size), dtype=bool), + *np.zeros((2, 0)), + true_objs[:, 4], + ) + ) + continue + + if true_objs.shape[0]: + matches = cls._match_detection_batch( + predicted_objs, true_objs, iou_thresholds + ) + stats.append( + ( + matches, + predicted_objs[:, 5], + predicted_objs[:, 4], + true_objs[:, 4], + ) + ) + else: + # Background image: no GT boxes, so all predictions are FP matches. + # This lowers AP for classes that appear in at least one GT image + # elsewhere; classes absent from all GT images are excluded from AP + # (they never appear in true_class_ids and are skipped by the AP loop). + stats.append( + ( + np.zeros( + (predicted_objs.shape[0], iou_thresholds.size), dtype=bool + ), + predicted_objs[:, 5], + predicted_objs[:, 4], + np.zeros((0,), dtype=np.float32), + ) + ) + + # Compute average precisions if any matches exist + if stats: + concatenated_stats = [np.concatenate(items, 0) for items in zip(*stats)] + average_precisions = cls._average_precisions_per_class( + cast(npt.NDArray[np.bool_], concatenated_stats[0]), + cast(npt.NDArray[np.float32], concatenated_stats[1]), + cast(npt.NDArray[np.int32], concatenated_stats[2]), + cast(npt.NDArray[np.int32], concatenated_stats[3]), + ) + if average_precisions.size == 0: + # All images had no ground-truth objects; FPs recorded but no class + # to accumulate AP over → return 0.0 rather than NaN. + map50, map75, map50_95 = 0.0, 0.0, 0.0 + else: + map50 = float(average_precisions[:, 0].mean()) + map75 = float(average_precisions[:, 5].mean()) + map50_95 = float(average_precisions.mean()) + else: + map50, map75, map50_95 = 0, 0, 0 + average_precisions = np.array([]) + + return cls( + map50_95=map50_95, + map50=map50, + map75=map75, + per_class_ap50_95=average_precisions, + ) + + @staticmethod + def compute_average_precision( + recall: npt.NDArray[np.float64], + precision: npt.NDArray[np.float64], + ) -> float: + """ + Compute the average precision using 101-point interpolation (COCO), given + the recall and precision curves. + + Args: + recall: The recall curve. + precision: The precision curve. + + Returns: + Average precision. + """ + extended_recall = np.concatenate(([0.0], recall, [1.0])) + extended_precision = np.concatenate(([0.0], precision, [0.0])) + max_accumulated_precision = np.flip( + np.maximum.accumulate(np.flip(extended_precision)) + ) + interpolated_recall_levels = np.linspace(0, 1, 101) + recall_indices = np.searchsorted( + extended_recall, interpolated_recall_levels, side="left" + ) + interpolated_precision = max_accumulated_precision[recall_indices] + average_precision = np.mean(interpolated_precision) + + return float(average_precision) + + @staticmethod + def _match_detection_batch( + predictions: npt.NDArray[np.float32], + targets: npt.NDArray[np.float32], + iou_thresholds: npt.NDArray[np.float32], + ) -> npt.NDArray[np.bool_]: + """ + Match predictions with target labels based on IoU levels. + + Args: + predictions: Batch prediction. Describes a single image and + has `shape = (M, 6)` where `M` is the number of detected objects. + Each row is expected to be in + `(x_min, y_min, x_max, y_max, class, conf)` format. + targets: Batch target labels. Describes a single image and + has `shape = (N, 5)` where `N` is the number of ground-truth objects. + Each row is expected to be in + `(x_min, y_min, x_max, y_max, class)` format. + iou_thresholds: Array contains different IoU thresholds. + + Returns: + Matched prediction with target labels result. + """ + num_predictions, num_iou_levels = predictions.shape[0], iou_thresholds.shape[0] + correct = np.zeros((num_predictions, num_iou_levels), dtype=bool) + iou = box_iou_batch(targets[:, :4], predictions[:, :4]) + correct_class = targets[:, 4:5] == predictions[:, 4] + + for i, iou_level in enumerate(iou_thresholds): + matched_indices = np.where((iou >= iou_level) & correct_class) + + for t, p in _greedy_match(iou, matched_indices): + correct[p, i] = True + result: npt.NDArray[np.bool_] = correct + return result + + @staticmethod + def _average_precisions_per_class( + matches: npt.NDArray[np.bool_], + prediction_confidence: npt.NDArray[np.float32], + prediction_class_ids: npt.NDArray[np.int32], + true_class_ids: npt.NDArray[np.int32], + eps: float = 1e-16, + ) -> npt.NDArray[np.float64]: + """ + Compute the average precision, given the recall and precision curves. + Source: https://github.com/rafaelpadilla/Object-Detection-Metrics. + + Args: + matches: True positives. + prediction_confidence: Objectness value from 0-1. + prediction_class_ids: Predicted object classes. + true_class_ids: True object classes. + eps: Small value to prevent division by zero. + + Returns: + Average precision for different IoU levels. + """ + sorted_indices = np.argsort(-prediction_confidence) + matches = matches[sorted_indices] + prediction_class_ids = prediction_class_ids[sorted_indices] + + unique_classes, class_counts = np.unique(true_class_ids, return_counts=True) + num_classes = unique_classes.shape[0] + + average_precisions: npt.NDArray[np.float64] = np.zeros( + (num_classes, matches.shape[1]), dtype=np.float64 + ) + + for class_idx, class_id in enumerate(unique_classes): + is_class = prediction_class_ids == class_id + total_true = class_counts[class_idx] + total_prediction = is_class.sum() + + if total_prediction == 0 or total_true == 0: + continue + + false_positives = (1 - matches[is_class]).cumsum(0) + true_positives = matches[is_class].cumsum(0) + recall = true_positives / (total_true + eps) + precision = true_positives / (true_positives + false_positives) + + for iou_level_idx in range(matches.shape[1]): + average_precisions[class_idx, iou_level_idx] = ( + MeanAveragePrecision.compute_average_precision( + recall[:, iou_level_idx], precision[:, iou_level_idx] + ) + ) + + result: npt.NDArray[np.float64] = average_precisions + return result diff --git a/.venv/lib/python3.12/site-packages/supervision/metrics/f1_score.py b/.venv/lib/python3.12/site-packages/supervision/metrics/f1_score.py new file mode 100644 index 0000000000000000000000000000000000000000..a8c1402d56db8352c80ea8117c0f5a27400cbc47 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/metrics/f1_score.py @@ -0,0 +1,819 @@ +from __future__ import annotations + +from copy import deepcopy +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, cast + +import numpy as np +import numpy.typing as npt + +from supervision.config import ORIENTED_BOX_COORDINATES +from supervision.detection.compact_mask import CompactMask +from supervision.detection.core import Detections +from supervision.detection.utils.iou_and_nms import ( + box_iou_batch, + mask_iou_batch, + oriented_box_iou_batch, +) +from supervision.draw.color import LEGACY_COLOR_PALETTE +from supervision.metrics.core import AveragingMethod, Metric, MetricTarget +from supervision.metrics.utils.matching import ( + _match_detection_batch_with_target_indices, +) +from supervision.metrics.utils.object_size import ( + ObjectSizeCategory, + get_detection_size_category, +) +from supervision.metrics.utils.utils import ensure_pandas_installed + +if TYPE_CHECKING: + import pandas as pd + + +class F1Score(Metric["F1ScoreResult"]): + """ + F1 Score is a metric used to evaluate object detection models. It is the harmonic + mean of precision and recall, calculated at different IoU thresholds. + + In simple terms, F1 Score is a measure of a model's balance between precision and + recall (accuracy and completeness), calculated as: + + `F1 = 2 * (precision * recall) / (precision + recall)` + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> from supervision.metrics import F1Score + >>> predictions = sv.Detections( + ... xyxy=np.array([[0, 0, 10, 10]]), + ... class_id=np.array([0]), + ... confidence=np.array([0.9]) + ... ) + >>> targets = sv.Detections( + ... xyxy=np.array([[0, 0, 10, 10]]), + ... class_id=np.array([0]) + ... ) + >>> f1_metric = F1Score() + >>> f1_result = f1_metric.update(predictions, targets).compute() + >>> round(float(f1_result.f1_50), 2) + 1.0 + + ``` + + ![example_plot]( + https://media.roboflow.com/supervision-docs/metrics/f1_plot_example.png + ){ align=center width="800" } + """ + + def __init__( + self, + metric_target: MetricTarget = MetricTarget.BOXES, + averaging_method: AveragingMethod = AveragingMethod.WEIGHTED, + ): + """ + Initialize the F1Score metric. + + Args: + metric_target: The type of detection data to use. + averaging_method: The averaging method used to compute the + F1 scores. Determines how the F1 scores are aggregated across classes. + """ + self._metric_target = metric_target + self.averaging_method = averaging_method + + self._predictions_list: list[Detections] = [] + self._targets_list: list[Detections] = [] + + def reset(self) -> None: + """ + Reset the metric to its initial state, clearing all stored data. + """ + self._predictions_list = [] + self._targets_list = [] + + def update( + self, + predictions: Detections | list[Detections], + targets: Detections | list[Detections], + ) -> F1Score: + """ + Add new predictions and targets to the metric, but do not compute the result. + + Args: + predictions: The predicted detections. + targets: The target detections. + + Returns: + The updated metric instance. + """ + if not isinstance(predictions, list): + predictions = [predictions] + if not isinstance(targets, list): + targets = [targets] + + if len(predictions) != len(targets): + raise ValueError( + f"The number of predictions ({len(predictions)}) and" + f" targets ({len(targets)}) during the update must be the same." + ) + + self._predictions_list.extend(predictions) + self._targets_list.extend(targets) + + return self + + def compute(self) -> F1ScoreResult: + """ + Calculate the F1 score metric based on the stored predictions and ground-truth + data, at different IoU thresholds. + + Returns: + The F1 score metric result. + """ + result = self._compute(self._predictions_list, self._targets_list) + result.small_objects = self._compute( + self._predictions_list, self._targets_list, ObjectSizeCategory.SMALL + ) + result.medium_objects = self._compute( + self._predictions_list, self._targets_list, ObjectSizeCategory.MEDIUM + ) + result.large_objects = self._compute( + self._predictions_list, self._targets_list, ObjectSizeCategory.LARGE + ) + + return result + + def _compute( + self, + predictions_list: list[Detections], + targets_list: list[Detections], + size_category: ObjectSizeCategory = ObjectSizeCategory.ANY, + ) -> F1ScoreResult: + """Build per-image stats tuples and delegate to class-level computation. + + Each stats tuple is + ``(matches, ignored_matches, confidence, class_ids, true_class_ids)``: + - Both empty: skip (no information). + - Targets empty, predictions present: all predictions are FPs; true_class_ids + is ``zeros((0,))``. + - Targets present: IoU matching produces ``matches`` array. + """ + iou_thresholds = np.linspace(0.5, 0.95, 10, dtype=np.float32) + stats: list[Any] = [] + + for predictions, targets in zip(predictions_list, targets_list): + prediction_contents = self._detections_content(predictions) + target_contents = self._detections_content(targets) + prediction_size_mask = np.ones(len(predictions), dtype=bool) + target_size_mask = np.ones(len(targets), dtype=bool) + if size_category != ObjectSizeCategory.ANY: + if len(predictions) > 0: + prediction_size_mask = ( + get_detection_size_category(predictions, self._metric_target) + == size_category.value + ) + if len(targets) > 0: + target_size_mask = ( + get_detection_size_category(targets, self._metric_target) + == size_category.value + ) + + if len(targets) == 0 and len(predictions) > 0: + # Only predictions are present (e.g. a background image); every + # prediction is a false positive. + if predictions.class_id is None or predictions.confidence is None: + raise ValueError( + "F1Score metric requires `class_id` and `confidence` " + "on predictions." + ) + prediction_class_ids = np.asarray(predictions.class_id, dtype=np.int32)[ + prediction_size_mask + ] + prediction_confidence = np.asarray( + predictions.confidence, dtype=np.float32 + )[prediction_size_mask] + if len(prediction_class_ids) == 0: + continue + stats.append( + ( + np.zeros( + (len(prediction_class_ids), iou_thresholds.size), + dtype=np.bool_, + ), + np.zeros( + (len(prediction_class_ids), iou_thresholds.size), + dtype=np.bool_, + ), + prediction_confidence, + prediction_class_ids, + np.zeros((0,), dtype=np.int32), + ) + ) + elif len(targets) > 0: + if predictions.class_id is None or targets.class_id is None: + raise ValueError( + "F1Score metric requires `class_id` on both predictions " + "and targets." + ) + if len(predictions) == 0: + target_class_ids = np.asarray(targets.class_id, dtype=np.int32)[ + target_size_mask + ] + if len(target_class_ids) == 0: + continue + stats.append( + ( + np.zeros((0, iou_thresholds.size), dtype=bool), + np.zeros((0, iou_thresholds.size), dtype=bool), + np.zeros((0,), dtype=np.float32), + np.zeros((0,), dtype=int), + target_class_ids, + ) + ) + + else: + if predictions.confidence is None: + raise ValueError( + "F1Score metric requires `confidence` on predictions." + ) + prediction_class_ids = np.asarray( + predictions.class_id, dtype=np.int32 + ) + target_class_ids = np.asarray(targets.class_id, dtype=np.int32) + prediction_confidence = np.asarray( + predictions.confidence, dtype=np.float32 + ) + if self._metric_target == MetricTarget.BOXES: + # BOXES target never yields CompactMask; narrow for mypy. + iou = box_iou_batch( + cast(npt.NDArray[np.number], target_contents), + cast(npt.NDArray[np.number], prediction_contents), + ) + elif self._metric_target == MetricTarget.MASKS: + iou = mask_iou_batch(target_contents, prediction_contents) + elif self._metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES: + # OBB target never yields CompactMask; narrow for mypy. + iou = oriented_box_iou_batch( + cast(npt.NDArray[np.number], target_contents), + cast(npt.NDArray[np.number], prediction_contents), + ) + else: + raise ValueError( + "Unsupported metric target for IoU calculation" + ) + + # None keeps the matcher on its single-round fast path + # when no size bucket is scored. + target_scored_mask = ( + target_size_mask + if size_category != ObjectSizeCategory.ANY + else None + ) + matches, matched_target_indices = ( + _match_detection_batch_with_target_indices( + prediction_class_ids, + target_class_ids, + iou, + iou_thresholds, + target_scored_mask=target_scored_mask, + ) + ) + ignored_matches = np.zeros_like(matches, dtype=bool) + if size_category != ObjectSizeCategory.ANY: + valid_target_match = matched_target_indices >= 0 + matched_scored_target = np.zeros_like(matches, dtype=bool) + if np.any(valid_target_match): + matched_scored_target[valid_target_match] = ( + target_size_mask[ + matched_target_indices[valid_target_match] + ] + ) + prediction_scored = ( + prediction_size_mask[:, None] | matched_scored_target + ) + ignored_matches = ~prediction_scored | ( + valid_target_match & ~matched_scored_target + ) + prediction_keep = np.any(~ignored_matches, axis=1) + matches = ( + matches[prediction_keep] + & matched_scored_target[prediction_keep] + ) + ignored_matches = ignored_matches[prediction_keep] + prediction_confidence = prediction_confidence[prediction_keep] + prediction_class_ids = prediction_class_ids[prediction_keep] + target_class_ids = target_class_ids[target_size_mask] + if ( + len(prediction_class_ids) == 0 + and len(target_class_ids) == 0 + ): + continue + stats.append( + ( + matches, + ignored_matches, + prediction_confidence, + prediction_class_ids, + target_class_ids, + ) + ) + + if not stats: + return F1ScoreResult( + metric_target=self._metric_target, + averaging_method=self.averaging_method, + f1_scores=np.zeros(iou_thresholds.shape[0]), + f1_per_class=np.zeros((0, iou_thresholds.shape[0])), + iou_thresholds=iou_thresholds, + matched_classes=np.array([], dtype=int), + small_objects=None, + medium_objects=None, + large_objects=None, + ) + + concatenated_stats = [np.concatenate(items, 0) for items in zip(*stats)] + f1_scores, f1_per_class, unique_classes = self._compute_f1_for_classes( + *concatenated_stats + ) + + return F1ScoreResult( + metric_target=self._metric_target, + averaging_method=self.averaging_method, + f1_scores=f1_scores, + f1_per_class=f1_per_class, + iou_thresholds=iou_thresholds, + matched_classes=unique_classes, + small_objects=None, + medium_objects=None, + large_objects=None, + ) + + def _compute_f1_for_classes( + self, + matches: npt.NDArray[np.bool_], + ignored_matches: npt.NDArray[np.bool_], + prediction_confidence: npt.NDArray[np.float32], + prediction_class_ids: npt.NDArray[np.int32], + true_class_ids: npt.NDArray[np.int32], + ) -> tuple[ + npt.NDArray[np.float64], + npt.NDArray[np.float64], + npt.NDArray[np.int32], + ]: + """Compute F1 scores from concatenated stats across all images. + + ``unique_classes`` is the union of GT and predicted classes so that + predictions of classes absent from GT still count as false positives. + """ + sorted_indices = np.argsort(-prediction_confidence) + matches = matches[sorted_indices] + ignored_matches = ignored_matches[sorted_indices] + prediction_class_ids = prediction_class_ids[sorted_indices] + # Predictions whose class never appears in the ground truth are still + # false positives, so include those classes in the confusion matrix + # (their true-instance count is zero). + unique_classes = np.unique( + np.concatenate((true_class_ids, prediction_class_ids)) + ) + true_classes, true_counts = np.unique(true_class_ids, return_counts=True) + class_counts = np.zeros(unique_classes.shape[0], dtype=int) + class_counts[np.searchsorted(unique_classes, true_classes)] = true_counts + + # Shape: PxTh,P,C,C -> CxThx3 + confusion_matrix = self._compute_confusion_matrix( + matches, ignored_matches, prediction_class_ids, unique_classes, class_counts + ) + + # Shape: CxThx3 -> CxTh + f1_per_class = self._compute_f1(confusion_matrix) + + # Shape: CxTh -> Th + if self.averaging_method == AveragingMethod.MACRO: + f1_scores = np.mean(f1_per_class, axis=0) + elif self.averaging_method == AveragingMethod.MICRO: + confusion_matrix_merged = confusion_matrix.sum(0) + f1_scores = self._compute_f1(confusion_matrix_merged) + elif self.averaging_method == AveragingMethod.WEIGHTED: + class_counts = class_counts.astype(np.float32) + if class_counts.sum() == 0: + # No ground-truth support (e.g. only false-positive classes, or a + # size bucket with predictions but no targets): weighting is + # undefined, so report 0 as the empty case did before. + f1_scores = np.zeros(f1_per_class.shape[1]) + else: + f1_scores = np.average(f1_per_class, axis=0, weights=class_counts) + + return f1_scores, f1_per_class, unique_classes + + @staticmethod + def _match_detection_batch( + predictions_classes: npt.NDArray[np.int32], + target_classes: npt.NDArray[np.int32], + iou: npt.NDArray[np.float32], + iou_thresholds: npt.NDArray[np.float32], + ) -> npt.NDArray[np.bool_]: + result_correct, _ = _match_detection_batch_with_target_indices( + predictions_classes, target_classes, iou, iou_thresholds + ) + return result_correct + + @staticmethod + def _compute_confusion_matrix( + sorted_matches: npt.NDArray[np.bool_], + sorted_ignored_matches: npt.NDArray[np.bool_], + sorted_prediction_class_ids: npt.NDArray[np.int32], + unique_classes: npt.NDArray[np.int32], + class_counts: npt.NDArray[np.int32], + ) -> npt.NDArray[np.float64]: + """ + Compute the confusion matrix for each class and IoU threshold. + + Assumes the matches and prediction_class_ids are sorted by confidence + in descending order. + + Args: + sorted_matches: shape (P, Th), that is True + if the prediction is a true positive at the given IoU threshold. + sorted_ignored_matches: shape (P, Th), that is True + if the prediction should not affect the given IoU threshold. + sorted_prediction_class_ids: shape (P,), containing + the class id for each prediction. + unique_classes: shape (C,), containing the unique + class ids. + class_counts: shape (C,), containing the number + of true instances for each class. + + Returns: + shape (C, Th, 3), containing the true positives, false + positives, and false negatives for each class and IoU threshold. + """ + + num_thresholds = sorted_matches.shape[1] + num_classes = unique_classes.shape[0] + + confusion_matrix: npt.NDArray[np.float64] = np.zeros( + (num_classes, num_thresholds, 3), dtype=np.float64 + ) + for class_idx, class_id in enumerate(unique_classes): + is_class = sorted_prediction_class_ids == class_id + num_true = class_counts[class_idx] + num_predictions = is_class.sum() + + if num_predictions == 0: + true_positives = np.zeros(num_thresholds) + false_positives = np.zeros(num_thresholds) + false_negatives = np.full(num_thresholds, num_true) + elif num_true == 0: + true_positives = np.zeros(num_thresholds) + false_positives = (~sorted_ignored_matches[is_class]).sum(0) + false_negatives = np.zeros(num_thresholds) + else: + true_positives = sorted_matches[is_class].sum(0) + false_positives = ( + ~sorted_matches[is_class] & ~sorted_ignored_matches[is_class] + ).sum(0) + false_negatives = num_true - true_positives + confusion_matrix[class_idx] = np.stack( + [true_positives, false_positives, false_negatives], axis=1 + ) + + result_confusion_matrix: npt.NDArray[np.float64] = confusion_matrix + return result_confusion_matrix + + @staticmethod + def _compute_f1( + confusion_matrix: npt.NDArray[np.float64], + ) -> npt.NDArray[np.float64]: + """ + Broadcastable function, computing the F1 score from the confusion matrix. + + Args: + confusion_matrix: shape (N, ..., 3), where the last dimension + contains the true positives, false positives, and false negatives. + + Returns: + shape (N, ...), containing the F1 score for each element. + """ + if not confusion_matrix.shape[-1] == 3: + raise ValueError( + f"Confusion matrix must have shape (..., 3), got " + f"{confusion_matrix.shape}" + ) + true_positives = confusion_matrix[..., 0] + false_positives = confusion_matrix[..., 1] + false_negatives = confusion_matrix[..., 2] + + # Alternate formula, avoids multiple zero division checks + denominator = 2 * true_positives + false_positives + false_negatives + f1_score = np.divide( + 2 * true_positives, + denominator, + out=np.zeros_like(denominator, dtype=np.float64), + where=denominator != 0, + ) + + result_f1_score: npt.NDArray[np.float64] = f1_score + return result_f1_score + + def _detections_content( + self, detections: Detections + ) -> npt.NDArray[Any] | CompactMask: + """Return boxes, masks or oriented bounding boxes from detections. + + For the mask target this may return a + :class:`~supervision.detection.compact_mask.CompactMask` rather than a + dense boolean array when the detections carry compact masks. + """ + if self._metric_target == MetricTarget.BOXES: + return cast(npt.NDArray[Any], detections.xyxy) + if self._metric_target == MetricTarget.MASKS: + if detections.mask is not None: + # detections.mask is NDArray[bool] | CompactMask; return as-is. + return detections.mask + if len(detections) > 0: + raise ValueError( + "F1Score with `MetricTarget.MASKS` requires detections to " + "include masks." + ) + return self._make_empty_content() + if self._metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES: + obb = detections.data.get(ORIENTED_BOX_COORDINATES) + if obb is not None and len(obb) > 0: + result_obb: npt.NDArray[np.float32] = np.array(obb, dtype=np.float32) + return result_obb + return self._make_empty_content() + raise ValueError(f"Invalid metric target: {self._metric_target}") + + def _make_empty_content(self) -> npt.NDArray[Any]: + if self._metric_target == MetricTarget.BOXES: + empty_boxes: npt.NDArray[np.float32] = np.empty((0, 4), dtype=np.float32) + return empty_boxes + if self._metric_target == MetricTarget.MASKS: + empty_masks: npt.NDArray[np.bool_] = np.empty((0, 0, 0), dtype=bool) + return empty_masks + if self._metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES: + empty_obb: npt.NDArray[np.float32] = np.empty((0, 4, 2), dtype=np.float32) + return empty_obb + raise ValueError(f"Invalid metric target: {self._metric_target}") + + def _filter_detections_by_size( + self, detections: Detections, size_category: ObjectSizeCategory + ) -> Detections: + """Return a copy of detections with contents filtered by object size.""" + new_detections = deepcopy(detections) + if detections.is_empty() or size_category == ObjectSizeCategory.ANY: + return new_detections + + sizes = get_detection_size_category(new_detections, self._metric_target) + size_mask = sizes == size_category.value + + new_detections.xyxy = new_detections.xyxy[size_mask] + if new_detections.mask is not None: + new_detections.mask = new_detections.mask[size_mask] + if new_detections.class_id is not None: + new_detections.class_id = new_detections.class_id[size_mask] + if new_detections.confidence is not None: + new_detections.confidence = new_detections.confidence[size_mask] + if new_detections.tracker_id is not None: + new_detections.tracker_id = new_detections.tracker_id[size_mask] + if new_detections.data is not None: + for key, value in new_detections.data.items(): + new_detections.data[key] = np.array(value)[size_mask] + + return new_detections + + def _filter_predictions_and_targets_by_size( + self, + predictions_list: list[Detections], + targets_list: list[Detections], + size_category: ObjectSizeCategory, + ) -> tuple[list[Detections], list[Detections]]: + """ + Filter predictions and targets by object size category. + """ + new_predictions_list = [] + new_targets_list = [] + for predictions, targets in zip(predictions_list, targets_list): + new_predictions_list.append( + self._filter_detections_by_size(predictions, size_category) + ) + new_targets_list.append( + self._filter_detections_by_size(targets, size_category) + ) + return new_predictions_list, new_targets_list + + +@dataclass +class F1ScoreResult: + """ + The results of the F1 score metric calculation. + + Defaults to `0` if no detections or targets were provided. + + Attributes: + metric_target: the type of data used for the metric - + boxes, masks or oriented bounding boxes. + averaging_method: the averaging method used to compute the + F1 scores. Determines how the F1 scores are aggregated across classes. + f1_50: the F1 score at IoU threshold of `0.5`. + f1_75: the F1 score at IoU threshold of `0.75`. + f1_scores: the F1 scores at each IoU threshold. + Shape: `(num_iou_thresholds,)` + f1_per_class: the F1 scores per class and IoU threshold. + Shape: `(num_classes, num_iou_thresholds)` + iou_thresholds: the IoU thresholds used in the calculations. + matched_classes: the class IDs present in either predictions or ground + truth. Corresponds to the rows of `f1_per_class`. Classes that + appear only in predictions (no ground-truth instances) are + included; their per-threshold F1 values will be `0.0`. + small_objects: the F1 metric results + for small objects (area < 32²). + medium_objects: the F1 metric results + for medium objects (32² ≤ area < 96²). + large_objects: the F1 metric results + for large objects (area ≥ 96²). + """ + + metric_target: MetricTarget + averaging_method: AveragingMethod + + @property + def f1_50(self) -> float: + return float(self.f1_scores[0]) + + @property + def f1_75(self) -> float: + return float(self.f1_scores[5]) + + f1_scores: npt.NDArray[np.float64] + f1_per_class: npt.NDArray[np.float64] + iou_thresholds: npt.NDArray[np.float32] + matched_classes: npt.NDArray[np.int32] + + small_objects: F1ScoreResult | None + medium_objects: F1ScoreResult | None + large_objects: F1ScoreResult | None + + def __str__(self) -> str: + """ + Format as a pretty string. + + Example: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> from supervision.metrics import F1Score + >>> predictions = sv.Detections( + ... xyxy=np.array([[0, 0, 10, 10]]), + ... class_id=np.array([0]), + ... confidence=np.array([0.9]) + ... ) + >>> targets = sv.Detections( + ... xyxy=np.array([[0, 0, 10, 10]]), + ... class_id=np.array([0]) + ... ) + >>> f1_metric = F1Score() + >>> f1_result = f1_metric.update(predictions, targets).compute() + >>> print(f1_result) # doctest: +ELLIPSIS + F1ScoreResult: + Metric target: MetricTarget.BOXES + Averaging method: AveragingMethod.WEIGHTED + F1 @ 50: 1.0000 + F1 @ 75: 1.0000 + F1 @ thresh: [1. ... 1.] + IoU thresh: [0.5 0.55 ... 0.95] + F1 per class: + 0: [1. ... 1.] + ... + Medium objects: + F1ScoreResult: + Metric target: MetricTarget.BOXES + Averaging method: AveragingMethod.WEIGHTED + F1 @ 50: 0.0000 + ... + + ``` + """ + out_str = ( + f"{self.__class__.__name__}:\n" + f"Metric target: {self.metric_target}\n" + f"Averaging method: {self.averaging_method}\n" + f"F1 @ 50: {self.f1_50:.4f}\n" + f"F1 @ 75: {self.f1_75:.4f}\n" + f"F1 @ thresh: {self.f1_scores}\n" + f"IoU thresh: {self.iou_thresholds}\n" + f"F1 per class:\n" + ) + if self.f1_per_class.size == 0: + out_str += " No results\n" + for class_id, f1_of_class in zip(self.matched_classes, self.f1_per_class): + out_str += f" {class_id}: {f1_of_class}\n" + + indent = " " + if self.small_objects is not None: + indented = indent + str(self.small_objects).replace("\n", f"\n{indent}") + out_str += f"\nSmall objects:\n{indented}" + if self.medium_objects is not None: + indented = indent + str(self.medium_objects).replace("\n", f"\n{indent}") + out_str += f"\nMedium objects:\n{indented}" + if self.large_objects is not None: + indented = indent + str(self.large_objects).replace("\n", f"\n{indent}") + out_str += f"\nLarge objects:\n{indented}" + + return out_str + + def to_pandas(self) -> pd.DataFrame: + """ + Convert the result to a pandas DataFrame. + + Returns: + The result as a DataFrame. + """ + ensure_pandas_installed() + import pandas as pd + + pandas_data: dict[str, Any] = { + "F1@50": self.f1_50, + "F1@75": self.f1_75, + } + + if self.small_objects is not None: + small_objects_df = self.small_objects.to_pandas() + for key, value in small_objects_df.items(): + pandas_data[f"small_objects_{key}"] = value + if self.medium_objects is not None: + medium_objects_df = self.medium_objects.to_pandas() + for key, value in medium_objects_df.items(): + pandas_data[f"medium_objects_{key}"] = value + if self.large_objects is not None: + large_objects_df = self.large_objects.to_pandas() + for key, value in large_objects_df.items(): + pandas_data[f"large_objects_{key}"] = value + + return pd.DataFrame(pandas_data, index=[0]) + + def plot(self) -> None: + """ + Plot the F1 results. + + ![example_plot]( + https://media.roboflow.com/supervision-docs/metrics/f1_plot_example.png + ){ align=center width="800" } + """ + from matplotlib import pyplot as plt + + labels = ["F1@50", "F1@75"] + values = [self.f1_50, self.f1_75] + colors = [LEGACY_COLOR_PALETTE[0]] * 2 + + if self.small_objects is not None: + small_objects = self.small_objects + labels += ["Small: F1@50", "Small: F1@75"] + values += [small_objects.f1_50, small_objects.f1_75] + colors += [LEGACY_COLOR_PALETTE[3]] * 2 + + if self.medium_objects is not None: + medium_objects = self.medium_objects + labels += ["Medium: F1@50", "Medium: F1@75"] + values += [medium_objects.f1_50, medium_objects.f1_75] + colors += [LEGACY_COLOR_PALETTE[2]] * 2 + + if self.large_objects is not None: + large_objects = self.large_objects + labels += ["Large: F1@50", "Large: F1@75"] + values += [large_objects.f1_50, large_objects.f1_75] + colors += [LEGACY_COLOR_PALETTE[4]] * 2 + + plt.rcParams["font.family"] = "monospace" + + _, ax = plt.subplots(figsize=(10, 6)) + ax.set_ylim(0, 1) + ax.set_ylabel("Value", fontweight="bold") + title = ( + f"F1 Score, by Object Size" + f"\n(target: {self.metric_target.value}," + f" averaging: {self.averaging_method.value})" + ) + ax.set_title(title, fontweight="bold") + + x_positions = range(len(labels)) + bars = ax.bar(x_positions, values, color=colors, align="center") + + ax.set_xticks(x_positions) + ax.set_xticklabels(labels, rotation=45, ha="right") + + for bar in bars: + y_value = bar.get_height() + ax.text( + bar.get_x() + bar.get_width() / 2, + y_value + 0.02, + f"{y_value:.2f}", + ha="center", + va="bottom", + ) + + plt.rcParams["font.family"] = "sans-serif" + + plt.tight_layout() + plt.show() diff --git a/.venv/lib/python3.12/site-packages/supervision/metrics/mean_average_precision.py b/.venv/lib/python3.12/site-packages/supervision/metrics/mean_average_precision.py new file mode 100644 index 0000000000000000000000000000000000000000..5cd04fa6cc4e6a5c331cb945626f1a8dfdb4913a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/metrics/mean_average_precision.py @@ -0,0 +1,1726 @@ +from __future__ import annotations + +import copy +import datetime +import itertools +from collections import defaultdict +from copy import deepcopy +from dataclasses import dataclass +from enum import Enum +from typing import TYPE_CHECKING, Any, TypeAlias, TypedDict + +import numpy as np +import numpy.typing as npt + +from supervision.config import AREA_DATA_FIELD, ORIENTED_BOX_COORDINATES +from supervision.detection.core import Detections +from supervision.detection.utils.iou_and_nms import ( + box_iou_batch_with_jaccard, + mask_iou_batch, + oriented_box_iou_batch, +) +from supervision.draw.color import LEGACY_COLOR_PALETTE +from supervision.metrics.core import Metric, MetricTarget +from supervision.metrics.utils.utils import ensure_pandas_installed +from supervision.utils.logger import _get_logger + +logger = _get_logger(__name__) + +if TYPE_CHECKING: + import pandas as pd + + +class _TypeCocoDict(TypedDict, total=False): + id: int + image_id: int + category_id: int + bbox: list[float] + area: float + iscrowd: int + ignore: int + _ignore: int + score: float + segmentation: list[list[float]] + name: str + supercategory: str + caption: str + keypoints: list[float] + # Metric-target-specific content: a boolean mask of shape (H, W) for + # `MetricTarget.MASKS` or an oriented box of shape (4, 2) for + # `MetricTarget.ORIENTED_BOUNDING_BOXES`. Absent for `MetricTarget.BOXES`. + # Invariant: shape/dtype match `metric_target` of the owning COCOEvaluator. + content: npt.NDArray[Any] + + +_TypeCocoDataset: TypeAlias = dict[str, list[_TypeCocoDict]] + + +class _TypeEvaluationImageResult(TypedDict): + image_id: int + category_id: int + area_range: list[float] | tuple[float, float] + max_det: int + dt_ids: list[int] + gt_ids: list[int] + dtMatches: npt.NDArray[np.int64] + gtMatches: npt.NDArray[np.int64] + dtScores: list[float] + gtIgnore: npt.NDArray[np.int64] + dtIgnore: npt.NDArray[np.bool_] + + +@dataclass +class MeanAveragePrecisionResult: + """ + The result of the Mean Average Precision calculation. + + Returns `-1` sentinel scores when no detections or targets are present. + + Attributes: + metric_target: the type of data used for the metric - + boxes, masks or oriented bounding boxes. + is_class_agnostic: When computing class-agnostic results, class ID + is set to `-1`. + mAP_scores: the mAP scores at each IoU threshold. + Shape: `(num_iou_thresholds,)` + ap_per_class: the average precision scores per + class and IoU threshold. Shape: `(num_target_classes, num_iou_thresholds)` + iou_thresholds: the IoU thresholds used in the calculations. + matched_classes: the class IDs of all matched classes. + Corresponds to the rows of `ap_per_class`. + small_objects: the mAP results + for small objects (area < 32²). + medium_objects: the mAP results + for medium objects (32² ≤ area < 96²). + large_objects: the mAP results + for large objects (area ≥ 96²). + """ + + metric_target: MetricTarget + is_class_agnostic: bool + + @property + def map50_95(self) -> float: + """the mAP score at IoU thresholds from `0.5` to `0.95`.""" + valid_scores = self.mAP_scores[self.mAP_scores > -1] + if len(valid_scores) > 0: + return float(valid_scores.mean()) + else: + return -1 + + @property + def map50(self) -> float: + """the mAP score at IoU threshold of `0.5`.""" + return float(self.mAP_scores[0]) + + @property + def map75(self) -> float: + """the mAP score at IoU threshold of `0.75`.""" + return float(self.mAP_scores[5]) + + mAP_scores: npt.NDArray[np.float64] + ap_per_class: npt.NDArray[np.float64] + iou_thresholds: npt.NDArray[np.float64] + matched_classes: npt.NDArray[np.int32] + small_objects: MeanAveragePrecisionResult | None = None + medium_objects: MeanAveragePrecisionResult | None = None + large_objects: MeanAveragePrecisionResult | None = None + + def __str__(self) -> str: + """ + Formats the evaluation output metrics to match the structure used by pycocotools + + Example: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> from supervision.metrics import MeanAveragePrecision + >>> predictions = sv.Detections( + ... xyxy=np.array([[0, 0, 10, 10]]), + ... class_id=np.array([0]), + ... confidence=np.array([0.9]) + ... ) + >>> targets = sv.Detections( + ... xyxy=np.array([[0, 0, 10, 10]]), + ... class_id=np.array([0]) + ... ) + >>> map_metric = MeanAveragePrecision() + >>> map_result = map_metric.update(predictions, targets).compute() + >>> print(map_result) # doctest: +ELLIPSIS + Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = ... + Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = ... + Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = ... + Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = ... + Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = ... + Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = ... + + ``` + """ + if ( + self.small_objects is None + or self.medium_objects is None + or self.large_objects is None + ): + return ( + f"Average Precision (AP) @[ IoU=0.50:0.95 | area= all | " + f"maxDets=100 ] = {self.map50_95:.3f}\n" + f"Average Precision (AP) @[ IoU=0.50 | area= all | " + f"maxDets=100 ] = {self.map50:.3f}\n" + f"Average Precision (AP) @[ IoU=0.75 | area= all | " + f"maxDets=100 ] = {self.map75:.3f}" + ) + + return ( + f"Average Precision (AP) @[ IoU=0.50:0.95 | area= all | " + f"maxDets=100 ] = {self.map50_95:.3f}\n" + f"Average Precision (AP) @[ IoU=0.50 | area= all | " + f"maxDets=100 ] = {self.map50:.3f}\n" + f"Average Precision (AP) @[ IoU=0.75 | area= all | " + f"maxDets=100 ] = {self.map75:.3f}\n" + f"Average Precision (AP) @[ IoU=0.50:0.95 | area= small | " + f"maxDets=100 ] = {self.small_objects.map50_95:.3f}\n" + f"Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | " + f"maxDets=100 ] = {self.medium_objects.map50_95:.3f}\n" + f"Average Precision (AP) @[ IoU=0.50:0.95 | area= large | " + f"maxDets=100 ] = {self.large_objects.map50_95:.3f}" + ) + + def to_pandas(self) -> pd.DataFrame: + """ + Convert the result to a pandas DataFrame. + + Returns: + The result as a DataFrame. + """ + ensure_pandas_installed() + import pandas as pd + + pandas_data: dict[str, object] = { + "mAP@50:95": self.map50_95, + "mAP@50": self.map50, + "mAP@75": self.map75, + } + + if self.small_objects is not None: + small_objects_df = self.small_objects.to_pandas() + for key, value in small_objects_df.items(): + pandas_data[f"small_objects_{key}"] = value + if self.medium_objects is not None: + medium_objects_df = self.medium_objects.to_pandas() + for key, value in medium_objects_df.items(): + pandas_data[f"medium_objects_{key}"] = value + if self.large_objects is not None: + large_objects_df = self.large_objects.to_pandas() + for key, value in large_objects_df.items(): + pandas_data[f"large_objects_{key}"] = value + + # Average precisions are currently not included in the DataFrame. + return pd.DataFrame( + pandas_data, + index=[0], + ) + + def plot(self) -> None: + """ + Plot the mAP results. + + ![example_plot]( + https://media.roboflow.com/supervision-docs/metrics/mAP_plot_example.png + ){ align=center width="800" } + """ + from matplotlib import pyplot as plt + + labels = ["mAP@50:95", "mAP@50", "mAP@75"] + values = [self.map50_95, self.map50, self.map75] + colors = [LEGACY_COLOR_PALETTE[0]] * 3 + + if self.small_objects is not None: + labels += ["Small: mAP@50:95", "Small: mAP@50", "Small: mAP@75"] + values += [ + self.small_objects.map50_95, + self.small_objects.map50, + self.small_objects.map75, + ] + colors += [LEGACY_COLOR_PALETTE[3]] * 3 + + if self.medium_objects is not None: + labels += ["Medium: mAP@50:95", "Medium: mAP@50", "Medium: mAP@75"] + values += [ + self.medium_objects.map50_95, + self.medium_objects.map50, + self.medium_objects.map75, + ] + colors += [LEGACY_COLOR_PALETTE[2]] * 3 + + if self.large_objects is not None: + labels += ["Large: mAP@50:95", "Large: mAP@50", "Large: mAP@75"] + values += [ + self.large_objects.map50_95, + self.large_objects.map50, + self.large_objects.map75, + ] + colors += [LEGACY_COLOR_PALETTE[4]] * 3 + + plt.rcParams["font.family"] = "monospace" + + _, ax = plt.subplots(figsize=(10, 6)) + ax.set_ylim(0, 1) + ax.set_ylabel("Value", fontweight="bold") + ax.set_title("Mean Average Precision", fontweight="bold") + + x_positions = range(len(labels)) + bars = ax.bar(x_positions, values, color=colors, align="center") + + ax.set_xticks(x_positions) + ax.set_xticklabels(labels, rotation=45, ha="right") + + for bar in bars: + y_value = bar.get_height() + ax.text( + bar.get_x() + bar.get_width() / 2, + y_value + 0.02, + f"{y_value:.2f}", + ha="center", + va="bottom", + ) + + plt.rcParams["font.family"] = "sans-serif" + + plt.tight_layout() + plt.show() + + +class EvaluationDataset: + """ + Class used representing a dataset in the right format needed by the + `COCOEvaluator` class. + """ + + def __init__(self, targets: _TypeCocoDataset | None = None) -> None: + """ + Constructor of EvaluationDataset object used to evaluate models with + Mean Average Precision. + + Args: + targets: The targets (ground truth) of the dataset in a the + COCO format. + """ + # Initialize members + # Initialize members + self.dataset: _TypeCocoDataset = {} + self.anns: dict[int, _TypeCocoDict] = {} + self.cats: dict[int, _TypeCocoDict] = {} + self.imgs: dict[int, _TypeCocoDict] = {} + self.img_to_anns: dict[int, list[_TypeCocoDict]] = defaultdict(list) + self.cat_to_imgs: dict[int, list[int]] = defaultdict(list) + + if targets is None: + return + + # Load dataset + self.dataset = targets + self.create_class_members() + + @classmethod + def empty(cls) -> EvaluationDataset: + return cls(targets=None) + + def create_class_members(self) -> None: + """ + Create index elements for the dataset. + """ + anns: dict[int, _TypeCocoDict] = {} + cats: dict[int, _TypeCocoDict] = {} + imgs: dict[int, _TypeCocoDict] = {} + img_to_anns: dict[int, list[_TypeCocoDict]] = defaultdict(list) + cat_to_imgs: dict[int, list[int]] = defaultdict(list) + if "annotations" in self.dataset: + for ann in self.dataset["annotations"]: + img_to_anns[ann["image_id"]].append(ann) + anns[ann["id"]] = ann + + if "images" in self.dataset: + for img in self.dataset["images"]: + imgs[img["id"]] = img + + if "categories" in self.dataset: + for cat in self.dataset["categories"]: + cats[cat["id"]] = cat + + if "annotations" in self.dataset and "categories" in self.dataset: + for ann in self.dataset["annotations"]: + cat_to_imgs[ann["category_id"]].append(ann["image_id"]) + + # Populate class members + self.anns = anns + self.img_to_anns = img_to_anns + self.cat_to_imgs = cat_to_imgs + self.imgs = imgs + self.cats = cats + + def get_annotation_ids( + self, + img_ids: list[int] | None = None, + cat_ids: list[int] | None = None, + area_range: tuple[float, float] | None = None, + iscrowd: bool = False, + ) -> list[int]: + """ + Get annotation ids that satisfy given filter conditions. + + Args: + img_ids: ids of the images that we want to retrieve. + cat_ids: ids of the categories that we want to retrieve. + area_range: area range of the annotations that we want to retrieve + in the format [min_area, max_area]. + iscrowd: if annotations to retrieve are `iscrowded=1`. + """ + # If there are no filters, we use all annotations + if not img_ids and not cat_ids and not area_range: + anns = self.dataset["annotations"] + else: + if img_ids: + lists = [ + self.img_to_anns[img_id] + for img_id in img_ids + if img_id in self.img_to_anns + ] + anns = list(itertools.chain.from_iterable(lists)) + else: + anns = self.dataset["annotations"] + + # Filter by category + anns = ( + anns + if not cat_ids + else [ann for ann in anns if ann["category_id"] in cat_ids] + ) + + # Filter by area + anns = ( + anns + if not area_range + else [ + ann for ann in anns if area_range[0] < ann["area"] < area_range[1] + ] + ) + + # Filter by iscrowd + if iscrowd is True: + ids = [ann["id"] for ann in anns if ann["iscrowd"] == 1] + else: + ids = [ann["id"] for ann in anns] + return ids + + def get_category_ids( + self, + cat_names: list[str] | None = None, + supercategory_names: list[str] | None = None, + cat_ids: list[int] | None = None, + ) -> list[int]: + """ + Get category ids that satisfy given filter conditions. + + Args: + cat_names: names of the categories to retrieve. + supercategory_names: names of the supercategories to retrieve. + cat_ids: ids of the categories to retrieve. + + Returns: + ids: integer array of category ids. + """ + # If there are no filters, we use all categories + if not cat_names and not supercategory_names and not cat_ids: + cats = self.dataset["categories"] + else: + cats = self.dataset["categories"] + + # Filter by name + cats = ( + cats + if not cat_names + else [cat for cat in cats if cat["name"] in cat_names] + ) + + # Filter by supercategory + cats = ( + cats + if not supercategory_names + else [ + cat for cat in cats if cat["supercategory"] in supercategory_names + ] + ) + + # Filter by id + cats = ( + cats if not cat_ids else [cat for cat in cats if cat["id"] in cat_ids] + ) + ids = [cat["id"] for cat in cats] + return ids + + def get_image_ids( + self, + img_ids: list[int] | None = None, + cat_ids: list[int] | None = None, + ) -> list[int]: + """ + Get image ids that satisfy given filter conditions. + + Args: + img_ids: ids of the images to retrieve. + cat_ids: ids of the categories to retrieve. + + Returns: + ids: integer array of image ids. + """ + # If there are no filters, we use all images + if not img_ids and not cat_ids: + ids = self.imgs.keys() + return list(ids) + + ids_set = set(img_ids) if img_ids else set() + + if cat_ids: + for i, cat_id in enumerate(cat_ids): + if i == 0 and not ids_set: + ids_set = set(self.cat_to_imgs[cat_id]) + else: + ids_set &= set(self.cat_to_imgs[cat_id]) + + return list(ids_set) + + def get_annotations(self, ids: list[int] | None = None) -> list[_TypeCocoDict]: + """ + Get annotations with the specified ids. + + Args: + ids: integer ids specifying annotations. + + Returns: + anns: loaded annotations. + """ + if ids is None: + return [] + return [self.anns[idx] for idx in ids] + + def load_predictions(self, predictions: list[_TypeCocoDict]) -> EvaluationDataset: + """ + Load prediction result into an EvaluationDataset object. + + Args: + predictions: prediction result. + + Returns: + EvaluationDataset object representing the predictions. + """ + # Create an empty EvaluationDataset object for the predictions + predictions_dataset = EvaluationDataset.empty() + predictions_dataset.dataset["images"] = list(self.dataset["images"]) + + if not isinstance(predictions, list): + raise ValueError("results must be a list") + + # Handle empty predictions + if len(predictions) == 0: + predictions_dataset.dataset["annotations"] = [] + return predictions_dataset + + ids = [pred["image_id"] for pred in predictions] + + # Make sure the image ids from predictions exist in the current dataset. + # A plain ``assert`` would be stripped under ``python -O``, so validate + # this public-input contract with an explicit exception instead. + if not set(ids) <= set(self.get_image_ids()): + raise ValueError("Results do not correspond to current coco set") + + # Check if the predictions contain any unsupported keys + if "caption" in predictions[0]: + raise NotImplementedError( + "Evaluating predictions with caption is not supported." + ) + elif "segmentation" in predictions[0]: + raise NotImplementedError( + "Evaluating predictions with segmentation is not supported." + ) + elif "keypoints" in predictions[0]: + raise NotImplementedError( + "Evaluating predictions with keypoints is not supported." + ) + + elif "bbox" in predictions[0] and not predictions[0]["bbox"] == []: + predictions_dataset.dataset["categories"] = copy.deepcopy( + self.dataset["categories"] + ) + + # Prepare fields for every prediction of the given image + for idx, pred in enumerate(predictions): + x, y, w, h = pred["bbox"] + x1, x2, y1, y2 = [x, x + w, y, y + h] + + # Make segmentation from bounding box coordinates + if "segmentation" not in pred: + pred["segmentation"] = [[x1, y1, x1, y2, x2, y2, x2, y1]] + # Use provided area if available + if "area" not in pred: + pred["area"] = w * h + pred["id"] = idx + 1 + # For predictions we set iscrowd to 0 + pred["iscrowd"] = 0 + predictions_dataset.dataset["annotations"] = predictions + predictions_dataset.create_class_members() + return predictions_dataset + + +# Area ranges for object size in pixels +SMALL_OBJECT_AREA = 32**2 +MEDIUM_OBJECT_AREA = 96**2 +MAX_ALL_OBJECT_AREA = 1e5**2 + +# Smallest number to avoid division by zero +EPS = np.finfo(np.float32).eps + + +def _mask_iou_with_jaccard( + masks_true: list[npt.NDArray[np.bool_]], + masks_detection: list[npt.NDArray[np.bool_]], + is_crowd: list[bool], +) -> npt.NDArray[np.float64]: + """ + Calculate the IoU between detection masks (dt) and ground-truth masks (gt), + following the COCO convention: a detection may match any subregion of a + crowd ground truth, so for crowd rows the union collapses to the detection + area (mask counterpart of `box_iou_batch_with_jaccard`). + + Args: + masks_true: List of ground-truth masks of shape `(H, W)`. + masks_detection: List of detection masks of shape `(H, W)`. + is_crowd: List indicating if each ground-truth mask is a crowd region. + + Returns: + Array of IoU values of shape `(len(masks_detection), len(masks_true))`. + """ + if len(masks_detection) == 0 or len(masks_true) == 0: + return np.empty((len(masks_detection), len(masks_true)), dtype=np.float64) + + gt_masks = np.stack(masks_true).astype(bool) + dt_masks = np.stack(masks_detection).astype(bool) + crowd = np.asarray(is_crowd, dtype=bool) + + # Compute base IoU via the optimised path (float32 + memory-chunked). + # mask_iou_batch returns (gt, dt); the evaluator expects (dt, gt). + iou: npt.NDArray[np.float64] = mask_iou_batch(gt_masks, dt_masks).T.astype( + np.float64 + ) + + if not np.any(crowd): + return iou + + # Override crowd columns: COCO convention collapses the union to the + # detection area, so a small detection inside a large crowd region scores + # IoU ≈ 1. Recompute only the crowd columns to avoid a full float64 matmul. + eps = np.spacing(1) + crowd_idx = np.where(crowd)[0] + gt_flat = gt_masks[crowd_idx].reshape(len(crowd_idx), -1).astype(np.float32) + dt_flat = dt_masks.reshape(dt_masks.shape[0], -1).astype(np.float32) + area_inter = (dt_flat @ gt_flat.T).astype(np.float64) # (dt, N_crowd) + area_dt = dt_flat.sum(axis=1).astype(np.float64) # (dt,) + iou[:, crowd_idx] = area_inter / (area_dt[:, None] + eps) + return iou + + +class ObjectSize(Enum): + """ + Enum for object size. + """ + + ALL = "all" + SMALL = "small" + MEDIUM = "medium" + LARGE = "large" + + +class COCOEvaluatorParameters: + """ + Parameters for COCOEvaluator + """ + + def __init__(self) -> None: + """Initialize all parameters for evaluation""" + + self.img_ids: list[int] = [] + self.cat_ids: list[int] = [] + + # IoU thresholds [0.5, 0.55, 0.6, 0.65, ..., 0.95] + self.iou_thrs = np.linspace( + 0.5, + 0.95, + int(np.round((0.95 - 0.5) / 0.05)) + 1, + endpoint=True, + dtype=np.float32, + ) + # 101 recall thresholds [0.0, 0.01, 0.02, ..., 1.00] + self.rec_thrs = np.linspace( + 0.0, + 1.00, + int(np.round((1.00 - 0.0) / 0.01)) + 1, + endpoint=True, + dtype=np.float32, + ) + # 3 maximum detection thresholds [1, 10, 100] + self.max_dets = [1, 10, 100] + # Area ranges [0, 1e5], [0, 32], [32, 96], [96, 1e5] + self.area_range: list[list[float]] = [ + [0, MAX_ALL_OBJECT_AREA], + [0, SMALL_OBJECT_AREA], + [SMALL_OBJECT_AREA, MEDIUM_OBJECT_AREA], + [MEDIUM_OBJECT_AREA, MAX_ALL_OBJECT_AREA], + ] + + +class COCOEvaluator: + """ + Evaluator class to compute COCO metrics. + """ + + def __init__( + self, + coco_targets: EvaluationDataset, + coco_predictions: EvaluationDataset, + metric_target: MetricTarget = MetricTarget.BOXES, + ) -> None: + """ + Constructor of COCOEvaluator object. + + Args: + coco_targets: The dataset with the ground truths. + coco_predictions: The dataset with the predictions. + metric_target: The type of detection data used to compute the IoU - + boxes, masks or oriented bounding boxes. + """ + if coco_targets is None: + raise ValueError("coco_targets must be provided") + if coco_predictions is None: + raise ValueError("coco_predictions must be provided") + + self.coco_targets = coco_targets + self.coco_predictions = coco_predictions + self.metric_target = metric_target + # List of dictionaries containing the evaluation results + # len(eval_imgs) = (categories) * (area_ranges) * (images) + # For COCO 2017: len(eval_images) = 80 * 4 * 5000 = 1600000 + self.eval_imgs: list[_TypeEvaluationImageResult | None] = [] + # Dictionary of accumulated results + self.results: dict[str, object] = {} + # Dictionary of targets for evaluation + self._targets: defaultdict[tuple[int, int], list[_TypeCocoDict]] = defaultdict( + list + ) + self._predictions: defaultdict[tuple[int, int], list[_TypeCocoDict]] = ( + defaultdict(list) + ) + # Parameters for evaluation + self.params = COCOEvaluatorParameters() + # List of results summarization + self.stats: list[object] = [] + # Dictionary of IOUs between all targets and predictions + self.ious: dict[tuple[int, int], npt.NDArray[np.float32]] = {} + # Set image and category ids + self.params.img_ids = sorted(self.coco_targets.get_image_ids()) + self.params.cat_ids = sorted(self.coco_targets.get_category_ids()) + + def _prepare_targets_and_predictions(self) -> None: + """ + Prepare targets and predictions for evaluation. + """ + # Get the target samples for the evaluation + annotation_ids = self.coco_targets.get_annotation_ids( + img_ids=self.params.img_ids, cat_ids=self.params.cat_ids + ) + targets = self.coco_targets.get_annotations(annotation_ids) + # Get the prediction samples for the evaluation + prediction_ids = self.coco_predictions.get_annotation_ids( + img_ids=self.params.img_ids, cat_ids=self.params.cat_ids + ) + predictions = self.coco_predictions.get_annotations(prediction_ids) + + # Set ignore flag + for gt in targets: + ignore = int(gt.get("ignore", 0)) + iscrowd = int(gt.get("iscrowd", 0)) + gt["ignore"] = int(bool(ignore or iscrowd)) + + # Select targets + self._targets = defaultdict(list) + for gt in targets: + self._targets[gt["image_id"], gt["category_id"]].append(gt) + + # Select predictions + self._predictions = defaultdict(list) + for dt in predictions: + self._predictions[dt["image_id"], dt["category_id"]].append(dt) + + # Initialize evaluation results + self.eval_imgs = [] + self.results = {} + + def _compute_iou(self, img_id: int, cat_id: int) -> npt.NDArray[np.float32]: + """ + Compute the IoU between the targets and predictions for a given image and + category, using boxes, masks or oriented bounding boxes depending on the + configured metric target. + + Args: + img_id: The image id. + cat_id: The category id. + + Returns: + The IoU between the targets and predictions. + """ + + gt = self._targets[img_id, cat_id] + dt = self._predictions[img_id, cat_id] + + # If there is nothing to evaluate + if len(gt) == 0 and len(dt) == 0: + empty_result: npt.NDArray[np.float32] = np.array([], dtype=np.float32) + return empty_result + + # Sort predictions by highest score first + inds = np.argsort([-d["score"] for d in dt], kind="stable") + dt = [dt[i] for i in inds] + + # Truncate the predictions if there are more predictions than the max detections + # to evaluate + if len(dt) > self.params.max_dets[-1]: + dt = dt[0 : self.params.max_dets[-1]] + + # Get the iscrowd flag for each gt + is_crowd = [bool(o["iscrowd"]) for o in gt] + + # Compute iou between each prediction and gt region + if self.metric_target == MetricTarget.MASKS: + iou = _mask_iou_with_jaccard( + [g["content"] for g in gt], [d["content"] for d in dt], is_crowd + ) + elif self.metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES: + # Crowd regions are not supported for oriented boxes; the standard + # IoU is used for every ground truth. + if len(gt) == 0 or len(dt) == 0: + iou = np.empty((len(dt), len(gt)), dtype=np.float64) + else: + gt_obb = np.stack([g["content"] for g in gt]) + dt_obb = np.stack([d["content"] for d in dt]) + # oriented_box_iou_batch returns (gt, dt); + # the evaluator expects (dt, gt). + iou = oriented_box_iou_batch(gt_obb, dt_obb).T.astype(np.float64) + else: + gt_boxes = [g["bbox"] for g in gt] + dt_boxes = [d["bbox"] for d in dt] + iou = box_iou_batch_with_jaccard(gt_boxes, dt_boxes, is_crowd) + return iou.astype(np.float32) + + def _evaluate_image( + self, + img_id: int, + cat_id: int, + area_range: list[float] | tuple[float, float], + max_det: int, + ) -> _TypeEvaluationImageResult | None: + """ + Perform evaluation for single category and image. + Args: + img_id: The image id. + cat_id: The category id. + area_range: The area range. + max_det: The maximum number of detections. + + Returns: + The evaluation results. + """ + # Get targets (gt) and predictions (dt) for the given image and category + gt: list[_TypeCocoDict] = self._targets[img_id, cat_id] + dt: list[_TypeCocoDict] = self._predictions[img_id, cat_id] + + # If there is nothing to evaluate + if len(gt) == 0 and len(dt) == 0: + return None + + min_area, max_area = area_range + + # Create an `_ignore` flag for targets if they are set as ignore or their area + # is not in the range [min_area, max_area] + for g in gt: + if g["ignore"] or not (min_area <= g["area"] <= max_area): + g["_ignore"] = 1 + else: + g["_ignore"] = 0 + + # Sort ground-truths by ignore flag (0: non ignored, 1: ignored) + gt_sorted = np.argsort([g["_ignore"] for g in gt], kind="stable") + gt = [gt[i] for i in gt_sorted] + + # Sort predictions by scores in descending order + dt_sorted = np.argsort([-d["score"] for d in dt], kind="stable") + dt = [dt[i] for i in dt_sorted[0:max_det]] + + # Load computed ious for the given image and category + ious = ( + self.ious[img_id, cat_id][:, gt_sorted] + if len(self.ious[img_id, cat_id]) > 0 + else self.ious[img_id, cat_id] + ) + + # Get the number of thresholds, ground truths and detections + num_thresholds = len(self.params.iou_thrs) + num_ground_truths = len(gt) + num_detections = len(dt) + + # Initialize matches: 0 means no match + gt_matches = np.zeros((num_thresholds, num_ground_truths), dtype=np.int64) + dt_matches = np.zeros((num_thresholds, num_detections), dtype=np.int64) + # Initialize ignore flags: 0 means no ignore + gt_ignore = np.array([g["_ignore"] for g in gt], dtype=np.int64) + dt_ignore = np.zeros((num_thresholds, num_detections), dtype=np.bool_) + if len(ious) != 0: + # Go through the iou thresholds + for tresh_idx, thresh in enumerate(self.params.iou_thrs): + # Go through the detections + for det_idx, det in enumerate(dt): + # Start the iou of the best match + iou_best_match = min([thresh, 1 - 1e-10]) + # Set the best match index to -1 (unmatched) + best_match_idx = -1 + # Go through the ground truths + for g_idx, g in enumerate(gt): + # If current gt is already matched, and not a crowd, continue + # if gt_matches[tresh_idx, g_idx] > 0 and not iscrowd[g_idx]: + iscrowd = int(g.get("iscrowd", 0)) + if gt_matches[tresh_idx, g_idx] > 0 and not iscrowd: + continue + # Stop searching the ground truths + if ( + best_match_idx > -1 # detection is matched to a gt + and gt_ignore[best_match_idx] + == 0 # matched gt is not ignored + and gt_ignore[g_idx] == 1 # current gt is ignored + ): + break + + # A new best match was found + if ious[det_idx, g_idx] >= iou_best_match: + iou_best_match = ious[det_idx, g_idx] + best_match_idx = g_idx + + # A best match was found + if best_match_idx != -1: + dt_ignore[tresh_idx, det_idx] = gt_ignore[best_match_idx] + dt_matches[tresh_idx, det_idx] = gt[best_match_idx]["id"] + gt_matches[tresh_idx, best_match_idx] = det["id"] + + # Set unmatched detections outside of area range to ignore + area_range_mask = np.array( + [d["area"] < min_area or d["area"] > max_area for d in dt] + ).reshape((1, len(dt))) + + # Update the ignore flags for detections + dt_ignore = np.logical_or( + dt_ignore, + np.logical_and( + dt_matches == 0, np.repeat(area_range_mask, num_thresholds, 0) + ), + ) + + return { + "image_id": img_id, + "category_id": cat_id, + "area_range": area_range, + "max_det": max_det, + "dt_ids": [d["id"] for d in dt], + "gt_ids": [g["id"] for g in gt], + "dtMatches": dt_matches, + "gtMatches": gt_matches, + "dtScores": [d["score"] for d in dt], + "gtIgnore": gt_ignore, + "dtIgnore": dt_ignore, + } + + def _accumulate(self) -> None: + """ + Accumulate per image evaluation results and store the result in self.results + """ + # Get the number of thresholds, categories, area ranges, and max detections + num_iou_thresholds = len(self.params.iou_thrs) + num_recall_thresholds = len(self.params.rec_thrs) + num_categories = len(self.params.cat_ids) + num_area_ranges = len(self.params.area_range) + num_max_detections = len(self.params.max_dets) + num_imgs = len(self.params.img_ids) + + # Initialize precision, recall, and scores arrays + # -1 means absent categories + precision = -np.ones( + ( + num_iou_thresholds, + num_recall_thresholds, + num_categories, + num_area_ranges, + num_max_detections, + ), + dtype=np.float32, + ) + recall = -np.ones( + (num_iou_thresholds, num_categories, num_area_ranges, num_max_detections), + dtype=np.float32, + ) + scores = -np.ones( + ( + num_iou_thresholds, + num_recall_thresholds, + num_categories, + num_area_ranges, + num_max_detections, + ), + dtype=np.float32, + ) + + # Create sets for indexing + set_categories = set(self.params.cat_ids) + set_area_ranges: set[tuple[float, ...]] = { + tuple(a) for a in self.params.area_range + } + set_max_detections = set(self.params.max_dets) + set_image_ids = set(self.params.img_ids) + + # Select category indexes to evaluate + selected_category_ids = [ + n for n, k in enumerate(self.params.cat_ids) if k in set_categories + ] + # Select max detections to evaluate + selected_max_detections = [ + m for m in self.params.max_dets if m in set_max_detections + ] + # Select area ranges to evaluate + selected_area_ranges_ids = [ + idx + for idx, area in enumerate(self.params.area_range) + if tuple(area) in set_area_ranges + ] + # Select image indexes to evaluate + image_inds = [ + n for n, i in enumerate(self.params.img_ids) if i in set_image_ids + ] + + # Evaluating at all categories, area ranges, max number of detections, and + # IoU thresholds + + # Loop through categories + for cat_idx, cat_eval_idx in enumerate(selected_category_ids): + cat_offset = cat_eval_idx * num_area_ranges * num_imgs + + # Loop through area ranges + for area_idx, area_eval_idx in enumerate(selected_area_ranges_ids): + area_offset = area_eval_idx * num_imgs + + # Loop through max detections + for max_det_idx, max_det in enumerate(selected_max_detections): + eval_img_data_raw = [ + self.eval_imgs[cat_offset + area_offset + i] for i in image_inds + ] + eval_img_data: list[_TypeEvaluationImageResult] = [ + e for e in eval_img_data_raw if e is not None + ] + + # No image to evaluate + if len(eval_img_data) == 0: + continue + + # Sort detected scores in descending order + dt_scores = np.concatenate( + [e["dtScores"][0:max_det] for e in eval_img_data] + ) + inds = np.argsort(-dt_scores, kind="stable") + dt_scores_sorted = dt_scores[inds] + + # Get matches and ignored matches + dt_matches = np.concatenate( + [e["dtMatches"][:, 0:max_det] for e in eval_img_data], axis=1 + )[:, inds] + dt_ignored = np.concatenate( + [e["dtIgnore"][:, 0:max_det] for e in eval_img_data], axis=1 + )[:, inds] + + # Get ignored ground truth objects + gt_ignored = np.concatenate([e["gtIgnore"] for e in eval_img_data]) + num_non_ignored_gt = np.count_nonzero(gt_ignored == 0) + + # No ground truth objects to evaluate + if num_non_ignored_gt == 0: + continue + + # Compute true positives and false positives + true_positives = np.logical_and( + dt_matches, np.logical_not(dt_ignored) + ) + false_positives = np.logical_and( + np.logical_not(dt_matches), np.logical_not(dt_ignored) + ) + + tp_sum = np.cumsum(true_positives, axis=1).astype(dtype=np.float32) + fp_sum = np.cumsum(false_positives, axis=1).astype(dtype=np.float32) + + # Loop through thresholds + for iou_thresh_idx, (tp, fp) in enumerate(zip(tp_sum, fp_sum)): + tp = np.array(tp) + fp = np.array(fp) + num_tps = len(tp) + # Recall: TP / Total number of ground truth objects + rc = tp / np.float32(num_non_ignored_gt) + # Precision: TP / (FP + TP) + pr = (tp / (fp + tp + EPS)).tolist() + # List to compute the precision at each recall threshold + precision_at_recall = [0.0] * num_recall_thresholds + # List to compute the score at each recall threshold + score_at_recall = [0.0] * num_recall_thresholds + + # Set recall to either the final recall value or 0 (when there + # is no TP) + recall[iou_thresh_idx, cat_idx, area_idx, max_det_idx] = ( + rc[-1] if num_tps else 0 + ) + + # Loop through precision values + for i in range(num_tps - 1, 0, -1): + if pr[i] > pr[i - 1]: + pr[i - 1] = pr[i] + + recall_inds: npt.NDArray[np.int_] = np.searchsorted( + rc, self.params.rec_thrs, side="left" + ) + recall_inds_list: list[int] = recall_inds.tolist() + for ri, pos_idx_value in enumerate(recall_inds_list): + # Ensure pi is within the range of both arrays + pos_idx_int: int = int(pos_idx_value) + if 0 <= pos_idx_int < len(pr) and 0 <= pos_idx_int < len( + dt_scores_sorted + ): + precision_at_recall[ri] = pr[pos_idx_int] + score_at_recall[ri] = dt_scores_sorted[pos_idx_int] + + # Convert precision to numpy array + precision[iou_thresh_idx, :, cat_idx, area_idx, max_det_idx] = ( + np.array(precision_at_recall, dtype=np.float32) + ) + # Convert scores to numpy array + scores[iou_thresh_idx, :, cat_idx, area_idx, max_det_idx] = ( + np.array(score_at_recall, dtype=np.float32) + ) + + self.results = { + "params": self.params, + "counts": [ + num_iou_thresholds, + num_recall_thresholds, + num_categories, + num_area_ranges, + num_max_detections, + ], + "date": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), + "precision": precision, + "recall": recall, + "scores": scores, + } + + # Helper function to compute average precision while handling -1 sentinel values + def compute_average_precision( + precision_slice: npt.NDArray[np.float32], + ) -> tuple[npt.NDArray[np.float64], npt.NDArray[np.float64]]: + """Compute average precision while handling -1 sentinel values.""" + valid_mask = precision_slice != -1 + valid_precision = np.where(valid_mask, precision_slice, np.float32(0.0)) + + def mean_with_mask( + axis: int | tuple[int, ...], + ) -> npt.NDArray[np.float64]: + sums = valid_precision.sum(axis=axis, dtype=np.float64) + counts = valid_mask.sum(axis=axis) + means: npt.NDArray[np.float64] = np.divide( + sums, + counts, + out=np.full(sums.shape, -1.0, dtype=np.float64), + where=counts > 0, + ) + return means + + mAP_scores = mean_with_mask((1, 2)) + ap_per_class = mean_with_mask(1).transpose(1, 0) + return mAP_scores, ap_per_class + + # Average precision over all sizes, 100 max detections + area_range_idx = list(ObjectSize).index(ObjectSize.ALL) + max_100_dets_idx = self.params.max_dets.index(100) + # Average precision [threshold, recall, classes] + average_precision_all_sizes = precision[ + :, :, :, area_range_idx, max_100_dets_idx + ] + # mAP over thresholds (dimension=num_thresholds) + # Exclude -1 sentinel values when computing mean + mAP_scores_all_sizes, ap_per_class_all_sizes = compute_average_precision( + average_precision_all_sizes + ) + + # Average precision for SMALL objects and 100 max detections + small_area_range_idx = list(ObjectSize).index(ObjectSize.SMALL) + average_precision_small = precision[ + :, :, :, small_area_range_idx, max_100_dets_idx + ] + mAP_scores_small, ap_per_class_small = compute_average_precision( + average_precision_small + ) + + # Average precision for MEDIUM objects and 100 max detections + medium_area_range_idx = list(ObjectSize).index(ObjectSize.MEDIUM) + average_precision_medium = precision[ + :, :, :, medium_area_range_idx, max_100_dets_idx + ] + mAP_scores_medium, ap_per_class_medium = compute_average_precision( + average_precision_medium + ) + + # Average precision for LARGE objects and 100 max detections + large_area_range_idx = list(ObjectSize).index(ObjectSize.LARGE) + average_precision_large = precision[ + :, :, :, large_area_range_idx, max_100_dets_idx + ] + mAP_scores_large, ap_per_class_large = compute_average_precision( + average_precision_large + ) + + self.results = { + "params": self.params, + "counts": [ + num_iou_thresholds, + num_recall_thresholds, + num_categories, + num_area_ranges, + num_max_detections, + ], + "date": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), + "precision": precision, + "recall": recall, + "scores": scores, + "mAP_scores_all_sizes": mAP_scores_all_sizes, + "ap_per_class_all_sizes": ap_per_class_all_sizes, + "mAP_scores_small": mAP_scores_small, + "ap_per_class_small": ap_per_class_small, + "mAP_scores_medium": mAP_scores_medium, + "ap_per_class_medium": ap_per_class_medium, + "mAP_scores_large": mAP_scores_large, + "ap_per_class_large": ap_per_class_large, + } + + def _pycocotools_summarize(self) -> None: + """ + Compute and display summary metrics for evaluation results. + """ + + def _summarize( + use_ap: bool = True, + iou_thr: float | None = None, + area_range: ObjectSize = ObjectSize.ALL, + max_dets: int = 100, + ) -> float: + iStr = " {:<18} {} @[ IoU={:<9} | area={:>6s} | maxDets={:>3d} ] = {:0.10f}" + titleStr = "Average Precision" if use_ap else "Average Recall" + typeStr = "(AP)" if use_ap else "(AR)" + iou_str = ( + f"{self.params.iou_thrs[0]:0.2f}:{self.params.iou_thrs[-1]:0.2f}" + if iou_thr is None + else f"{iou_thr:0.2f}" + ) + all_object_sizes = list(ObjectSize) + area_range_idx = all_object_sizes.index(area_range) + max_detections_idx = self.params.max_dets.index(max_dets) + if use_ap: + # Dimension of precision: + # threshold x recall x classes x areas x max detections + s: npt.NDArray[np.float32] = np.asarray( + self.results["precision"], dtype=np.float32 + ) + # IOU + if iou_thr is not None: + t = np.where(iou_thr == self.params.iou_thrs)[0] + s = s[t] + s = s[:, :, :, area_range_idx, max_detections_idx] + else: + # Dimension of recall: + # threshold x classes x areas x max detections + s = np.asarray(self.results["recall"], dtype=np.float32) + if iou_thr is not None: + t = np.where(iou_thr == self.params.iou_thrs)[0] + s = s[t] + s = s[:, :, area_range_idx, max_detections_idx] + if len(s[s > -1]) == 0: + mean_s = -1.0 + else: + mean_s = float(np.mean(s[s > -1])) + logger.info( + iStr.format(titleStr, typeStr, iou_str, area_range, max_dets, mean_s) + ) + return mean_s + + def _summarize_predictions() -> npt.NDArray[np.float32]: + stats: npt.NDArray[np.float32] = np.zeros((12,), dtype=np.float32) + stats[0] = _summarize(use_ap=True) + stats[1] = _summarize( + use_ap=True, iou_thr=0.5, max_dets=self.params.max_dets[2] + ) + stats[2] = _summarize( + use_ap=True, iou_thr=0.75, max_dets=self.params.max_dets[2] + ) + stats[3] = _summarize( + use_ap=True, + area_range=ObjectSize.SMALL, + max_dets=self.params.max_dets[2], + ) + stats[4] = _summarize( + use_ap=True, + area_range=ObjectSize.MEDIUM, + max_dets=self.params.max_dets[2], + ) + stats[5] = _summarize( + use_ap=True, + area_range=ObjectSize.LARGE, + max_dets=self.params.max_dets[2], + ) + stats[6] = _summarize(use_ap=False, max_dets=self.params.max_dets[0]) + stats[7] = _summarize(use_ap=False, max_dets=self.params.max_dets[1]) + stats[8] = _summarize(use_ap=False, max_dets=self.params.max_dets[2]) + stats[9] = _summarize( + use_ap=False, + area_range=ObjectSize.SMALL, + max_dets=self.params.max_dets[2], + ) + stats[10] = _summarize( + use_ap=False, + area_range=ObjectSize.MEDIUM, + max_dets=self.params.max_dets[2], + ) + stats[11] = _summarize( + use_ap=False, + area_range=ObjectSize.LARGE, + max_dets=self.params.max_dets[2], + ) + return stats + + if len(self.results) != 0: + self.stats = _summarize_predictions().tolist() + + def evaluate(self) -> None: + """ + Start the per image evaluation on all images and keeep results in + self.eval_imgs (a list of dictionaries). + """ + # Select all parameters to evaluate + self.params.img_ids = list(np.unique(self.params.img_ids)) + self.params.cat_ids = list(np.unique(self.params.cat_ids)) + self.params.max_dets = sorted(self.params.max_dets) + + self._prepare_targets_and_predictions() + + # Compute IOUs between all targets and predictions for all images and categories + self.ious = { + (img_id, cat_id): self._compute_iou(img_id, cat_id) + for img_id in self.params.img_ids + for cat_id in self.params.cat_ids + } + + # Select the largest max area (the last element containing 100 dets + max_det = self.params.max_dets[-1] + + # Evaluate each image with all categories, area range and max detections + self.eval_imgs = [ + self._evaluate_image(img_id, cat_id, area_range, max_det) + for cat_id in self.params.cat_ids + for area_range in self.params.area_range + for img_id in self.params.img_ids + ] + + # Accumulate results + self._accumulate() + + +class MeanAveragePrecision(Metric[MeanAveragePrecisionResult]): + """ + Mean Average Precision (mAP) is a metric used to evaluate object detection models. + It is the average of the precision-recall curves at different IoU thresholds. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> from supervision.metrics import MeanAveragePrecision + >>> predictions = sv.Detections( + ... xyxy=np.array([[0, 0, 10, 10]]), + ... class_id=np.array([0]), + ... confidence=np.array([0.9]) + ... ) + >>> targets = sv.Detections( + ... xyxy=np.array([[0, 0, 10, 10]]), + ... class_id=np.array([0]) + ... ) + >>> map_metric = MeanAveragePrecision() + >>> map_result = map_metric.update(predictions, targets).compute() + >>> round(float(map_result.map50), 2) + 1.0 + >>> print(map_result) + Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 1.000 + Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 1.000 + Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 1.000 + Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 1.000 + Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = -1.000 + Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = -1.000 + + ``` + + ![example_plot]( + https://media.roboflow.com/supervision-docs/metrics/mAP_plot_example.png + ){ align=center width="800" } + """ + + def __init__( + self, + metric_target: MetricTarget = MetricTarget.BOXES, + class_agnostic: bool = False, + class_mapping: dict[int, int] | None = None, + image_indices: list[int] | None = None, + ) -> None: + """ + Initialize the Mean Average Precision metric. + + Args: + metric_target: The type of detection data to use. + class_agnostic: Whether to treat all data as a single class. + class_mapping: A dictionary to map class IDs to new IDs. + image_indices: The indices of the images to use. + """ + self._metric_target = metric_target + self._class_agnostic = class_agnostic + + self._predictions_list: list[Detections] = [] + self._targets_list: list[Detections] = [] + self._class_mapping = class_mapping + self._image_indices = image_indices + + def reset(self) -> None: + """ + Reset the metric to its initial state, clearing all stored data. + """ + self._predictions_list = [] + self._targets_list = [] + + def update( + self, + predictions: Detections | list[Detections], + targets: Detections | list[Detections], + ) -> MeanAveragePrecision: + """ + Add new predictions and targets to the metric, but do not compute the result. + + Args: + predictions: The predicted detections. + targets: The ground-truth detections. + + Returns: + The updated metric instance. + """ + if not isinstance(predictions, list): + predictions = [predictions] + if not isinstance(targets, list): + targets = [targets] + + if len(predictions) != len(targets): + raise ValueError( + f"The number of predictions ({len(predictions)}) and" + f" targets ({len(targets)}) during the update must be the same." + ) + + if self._class_agnostic: + predictions = deepcopy(predictions) + targets = deepcopy(targets) + + for prediction in predictions: + if prediction.class_id is not None: + prediction.class_id[:] = -1 + for target in targets: + if target.class_id is not None: + target.class_id[:] = -1 + + self._predictions_list.extend(predictions) + self._targets_list.extend(targets) + + return self + + def _detections_content(self, detections: Detections) -> npt.NDArray[Any] | None: + """Return per-detection masks or oriented boxes for the metric target, + or `None` for the box target and for empty detections.""" + if self._metric_target == MetricTarget.BOXES or len(detections) == 0: + return None + if self._metric_target == MetricTarget.MASKS: + if detections.mask is None: + raise ValueError( + "MeanAveragePrecision with `MetricTarget.MASKS` requires" + " masks on both predictions and targets." + ) + return np.asarray(detections.mask).astype(bool) + if self._metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES: + obb = detections.data.get(ORIENTED_BOX_COORDINATES) + if obb is None: + raise ValueError( + "MeanAveragePrecision with" + " `MetricTarget.ORIENTED_BOUNDING_BOXES` requires" + f" `{ORIENTED_BOX_COORDINATES}` in `data` on both" + " predictions and targets." + ) + return np.asarray(obb, dtype=np.float32).reshape(-1, 4, 2) + raise ValueError(f"Invalid metric target: {self._metric_target}") + + def _content_area( + self, xywh: list[float], content: npt.NDArray[Any] | None, idx: int + ) -> float: + """Compute the default annotation area for the metric target: bbox area + for boxes, pixel count for masks, polygon area for oriented boxes.""" + if content is None: + return float(xywh[2] * xywh[3]) + if self._metric_target == MetricTarget.MASKS: + return float(np.count_nonzero(content[idx])) + x, y = content[idx, :, 0], content[idx, :, 1] + # Shoelace formula + return float(0.5 * abs(np.sum(x * np.roll(y, -1) - np.roll(x, -1) * y))) + + def _prepare_targets( + self, targets: list[Detections] + ) -> dict[str, list[_TypeCocoDict]]: + """Transform targets into a dictionary that can be used by the COCO evaluator""" + images: list[_TypeCocoDict] = [{"id": img_id} for img_id in range(len(targets))] + if self._image_indices is not None: + images = [{"id": self._image_indices[img["id"]]} for img in images] + # Annotations list + annotations: list[_TypeCocoDict] = [] + for image_id, image_targets in enumerate(targets): + if self._image_indices is not None: + image_id = self._image_indices[image_id] + + # Ensure xyxy is not None + if image_targets.xyxy is None: + continue + + content = self._detections_content(image_targets) + for target_idx, xyxy in enumerate(image_targets.xyxy): + xywh = [xyxy[0], xyxy[1], xyxy[2] - xyxy[0], xyxy[3] - xyxy[1]] + + # Default values + category_id = 0 + + if image_targets.class_id is not None: + cls_id = image_targets.class_id[target_idx] + if self._class_mapping is not None: + category_id = self._class_mapping[int(cls_id)] + else: + category_id = int(cls_id) + + # Use area from data if available, otherwise calculate from the + # metric target content (bbox, mask or oriented box) + area = None + if ( + image_targets.data is not None + and AREA_DATA_FIELD in image_targets.data + ): + area_data: npt.NDArray[np.float32] = np.asarray( + image_targets.data[AREA_DATA_FIELD], dtype=np.float32 + ) + area = float(area_data[target_idx]) + + if area is None: + area = self._content_area(xywh, content, target_idx) + + iscrowd = 0 + if image_targets.data is not None and "iscrowd" in image_targets.data: + iscrowd_data: npt.NDArray[np.int64] = np.asarray( + image_targets.data["iscrowd"], dtype=np.int64 + ) + iscrowd = int(iscrowd_data[target_idx]) + + ignore = 0 + if image_targets.data is not None and "ignore" in image_targets.data: + ignore_data: npt.NDArray[np.int64] = np.asarray( + image_targets.data["ignore"], dtype=np.int64 + ) + ignore = int(ignore_data[target_idx]) + + dict_annotation: _TypeCocoDict = { + "area": area, + "iscrowd": iscrowd, + "image_id": image_id, + "bbox": xywh, + "category_id": category_id, + "id": len(annotations) + 1, # Start IDs from 1 (0 means no match) + "ignore": ignore, + } + if content is not None: + dict_annotation["content"] = content[target_idx] + annotations.append(dict_annotation) + # Category list + all_cat_ids = {annotation["category_id"] for annotation in annotations} + categories: list[_TypeCocoDict] = [{"id": cat_id} for cat_id in all_cat_ids] + # Create coco dictionary + return { + "images": images, + "annotations": annotations, + "categories": categories, + } + + def _prepare_predictions( + self, predictions: list[Detections] + ) -> list[_TypeCocoDict]: + """Transform predictions into a list of predictions that can be used by the COCO + evaluator.""" + coco_predictions: list[_TypeCocoDict] = [] + for image_id, image_predictions in enumerate(predictions): + if self._image_indices is not None: + image_id = self._image_indices[image_id] + + if image_predictions.xyxy is None: + continue + + content = self._detections_content(image_predictions) + for pred_idx, xyxy in enumerate(image_predictions.xyxy): + xywh = [xyxy[0], xyxy[1], xyxy[2] - xyxy[0], xyxy[3] - xyxy[1]] + + category_id = 0 + score = 0.0 + + if image_predictions.class_id is not None: + cls_id = image_predictions.class_id[pred_idx] + if self._class_mapping is not None: + category_id = self._class_mapping[int(cls_id)] + else: + category_id = int(cls_id) + + if image_predictions.confidence is not None: + score = float(image_predictions.confidence[pred_idx]) + + # Use area from data if available, otherwise calculate from the + # metric target content (bbox, mask or oriented box) + area = None + if ( + image_predictions.data is not None + and AREA_DATA_FIELD in image_predictions.data + ): + area_data: npt.NDArray[np.float32] = np.asarray( + image_predictions.data[AREA_DATA_FIELD], dtype=np.float32 + ) + area = float(area_data[pred_idx]) + + if area is None: + area = self._content_area(xywh, content, pred_idx) + + dict_prediction: _TypeCocoDict = { + "image_id": image_id, + "bbox": xywh, + "score": score, + "category_id": category_id, + "area": area, + "id": len(coco_predictions) + 1, + } + if content is not None: + dict_prediction["content"] = content[pred_idx] + coco_predictions.append(dict_prediction) + return coco_predictions + + def compute(self) -> MeanAveragePrecisionResult: + """ + Calculate Mean Average Precision based on predicted and ground-truth + detections at different thresholds using the COCO evaluation metrics. + Source: https://github.com/rafaelpadilla/review_object_detection_metrics + + Returns: + The Mean Average Precision result. + """ + total_images_predictions = len(self._predictions_list) + total_images_targets = len(self._targets_list) + + if total_images_predictions != total_images_targets: + raise ValueError( + f"The number of predictions ({total_images_predictions}) and" + f" targets ({total_images_targets}) during the evaluation must be" + " the same." + ) + dict_targets = self._prepare_targets(self._targets_list) + lst_predictions = self._prepare_predictions(self._predictions_list) + # Create a coco object with the targets + coco_gt = EvaluationDataset(targets=dict_targets) + # Include the predictions to coco object + coco_det = coco_gt.load_predictions(lst_predictions) + # Create a coco evaluator with the predictions + cocoEval = COCOEvaluator(coco_gt, coco_det, metric_target=self._metric_target) + + # Evaluate on all images + cocoEval.evaluate() + + # Create MeanAveragePrecisionResult object for small objects + mAP_small = MeanAveragePrecisionResult( + metric_target=self._metric_target, + is_class_agnostic=self._class_agnostic, + mAP_scores=np.asarray( + cocoEval.results["mAP_scores_small"], dtype=np.float64 + ), + ap_per_class=np.asarray( + cocoEval.results["ap_per_class_small"], dtype=np.float64 + ), + iou_thresholds=np.asarray(cocoEval.params.iou_thrs, dtype=np.float64), + matched_classes=np.asarray(cocoEval.params.cat_ids, dtype=np.int32), + ) + # Create MeanAveragePrecisionResult object for medium objects + mAP_medium = MeanAveragePrecisionResult( + metric_target=self._metric_target, + is_class_agnostic=self._class_agnostic, + mAP_scores=np.asarray( + cocoEval.results["mAP_scores_medium"], dtype=np.float64 + ), + ap_per_class=np.asarray( + cocoEval.results["ap_per_class_medium"], dtype=np.float64 + ), + iou_thresholds=np.asarray(cocoEval.params.iou_thrs, dtype=np.float64), + matched_classes=np.asarray(cocoEval.params.cat_ids, dtype=np.int32), + ) + # Create MeanAveragePrecisionResult object for large objects + mAP_large = MeanAveragePrecisionResult( + metric_target=self._metric_target, + is_class_agnostic=self._class_agnostic, + mAP_scores=np.asarray( + cocoEval.results["mAP_scores_large"], dtype=np.float64 + ), + ap_per_class=np.asarray( + cocoEval.results["ap_per_class_large"], dtype=np.float64 + ), + iou_thresholds=np.asarray(cocoEval.params.iou_thrs, dtype=np.float64), + matched_classes=np.asarray(cocoEval.params.cat_ids, dtype=np.int32), + ) + + # Create the final MeanAveragePrecisionResult object + mAP_result = MeanAveragePrecisionResult( + metric_target=self._metric_target, + is_class_agnostic=self._class_agnostic, + mAP_scores=np.asarray( + cocoEval.results["mAP_scores_all_sizes"], dtype=np.float64 + ), + ap_per_class=np.asarray( + cocoEval.results["ap_per_class_all_sizes"], dtype=np.float64 + ), + iou_thresholds=np.asarray(cocoEval.params.iou_thrs, dtype=np.float64), + matched_classes=np.asarray(cocoEval.params.cat_ids, dtype=np.int32), + small_objects=mAP_small, + medium_objects=mAP_medium, + large_objects=mAP_large, + ) + return mAP_result diff --git a/.venv/lib/python3.12/site-packages/supervision/metrics/mean_average_recall.py b/.venv/lib/python3.12/site-packages/supervision/metrics/mean_average_recall.py new file mode 100644 index 0000000000000000000000000000000000000000..0d2a1820656ef97a89d49f169c744c2c93d34918 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/metrics/mean_average_recall.py @@ -0,0 +1,792 @@ +from __future__ import annotations + +from copy import deepcopy +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, cast + +import numpy as np +import numpy.typing as npt + +from supervision.config import ORIENTED_BOX_COORDINATES +from supervision.detection.compact_mask import CompactMask +from supervision.detection.core import Detections +from supervision.detection.utils.iou_and_nms import ( + box_iou_batch, + mask_iou_batch, + oriented_box_iou_batch, +) +from supervision.draw.color import LEGACY_COLOR_PALETTE +from supervision.metrics.core import Metric, MetricTarget +from supervision.metrics.utils.matching import ( + _match_detection_batch_with_target_indices, +) +from supervision.metrics.utils.object_size import ( + ObjectSizeCategory, + get_detection_size_category, +) +from supervision.metrics.utils.utils import ensure_pandas_installed + +if TYPE_CHECKING: + import pandas as pd + + +@dataclass +class MeanAverageRecallResult: + """ + The results of the Mean Average Recall metric calculation. + + Defaults to `0` if no detections or targets were provided. + + Attributes: + metric_target: the type of data used for the metric - + boxes, masks or oriented bounding boxes. + mAR_at_1: the Mean Average Recall, when considering only the top + highest confidence detection for each image. + mAR_at_10: the Mean Average Recall, when considering top 10 + highest confidence detections for each image. + mAR_at_100: the Mean Average Recall, when considering top 100 + highest confidence detections for each image. + recall_per_class: the recall scores per max detection count, class and + IoU threshold. Shape: + `(num_max_detections, num_target_classes, num_iou_thresholds)`. + max_detections: the array with maximum number of detections + considered. + iou_thresholds: the IoU thresholds used in the calculations. + matched_classes: the class IDs of all matched classes. + Corresponds to the class axis of `recall_per_class`. + small_objects: the Mean Average Recall + metric results for small objects (area < 32²). + medium_objects: the Mean Average Recall + metric results for medium objects (32² ≤ area < 96²). + large_objects: the Mean Average Recall + metric results for large objects (area ≥ 96²). + """ + + metric_target: MetricTarget + + @property + def mAR_at_1(self) -> float: + return float(self.recall_scores[0]) + + @property + def mAR_at_10(self) -> float: + return float(self.recall_scores[1]) + + @property + def mAR_at_100(self) -> float: + return float(self.recall_scores[2]) + + recall_scores: npt.NDArray[np.float64] + recall_per_class: npt.NDArray[np.float64] + max_detections: npt.NDArray[np.int32] + iou_thresholds: npt.NDArray[np.float32] + matched_classes: npt.NDArray[np.int32] + + small_objects: MeanAverageRecallResult | None + medium_objects: MeanAverageRecallResult | None + large_objects: MeanAverageRecallResult | None + + def __str__(self) -> str: + """ + Format as a pretty string. + + Example: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> from supervision.metrics import MeanAverageRecall + >>> predictions = sv.Detections( + ... xyxy=np.array([[0, 0, 10, 10]]), + ... class_id=np.array([0]), + ... confidence=np.array([0.9]) + ... ) + >>> targets = sv.Detections( + ... xyxy=np.array([[0, 0, 10, 10]]), + ... class_id=np.array([0]) + ... ) + >>> mar_metric = MeanAverageRecall() + >>> mar_result = mar_metric.update(predictions, targets).compute() + >>> print(mar_result) # doctest: +ELLIPSIS + MeanAverageRecallResult: + Metric target: MetricTarget.BOXES + mAR @ 1: 1.0000 + mAR @ 10: 1.0000 + mAR @ 100: 1.0000 + max detections: [ 1 10 100] + IoU thresh: [0.5 0.55 ... 0.95] + mAR per class: + @1: + 0: [1. ... 1.] + @10: + 0: [1. ... 1.] + @100: + 0: [1. ... 1.] + ... + Medium objects: + MeanAverageRecallResult: + Metric target: MetricTarget.BOXES + mAR @ 1: 0.0000 + ... + + ``` + """ + out_str = ( + f"{self.__class__.__name__}:\n" + f"Metric target: {self.metric_target}\n" + f"mAR @ 1: {self.mAR_at_1:.4f}\n" + f"mAR @ 10: {self.mAR_at_10:.4f}\n" + f"mAR @ 100: {self.mAR_at_100:.4f}\n" + f"max detections: {self.max_detections}\n" + f"IoU thresh: {self.iou_thresholds}\n" + f"mAR per class:\n" + ) + if self.recall_per_class.size == 0: + out_str += " No results\n" + for max_detections, recalls_at_k in zip( + self.max_detections, self.recall_per_class + ): + out_str += f" @{max_detections}:\n" + for class_id, recall_of_class in zip(self.matched_classes, recalls_at_k): + out_str += f" {class_id}: {recall_of_class}\n" + + indent = " " + if self.small_objects is not None: + indented = indent + str(self.small_objects).replace("\n", f"\n{indent}") + out_str += f"\nSmall objects:\n{indented}" + if self.medium_objects is not None: + indented = indent + str(self.medium_objects).replace("\n", f"\n{indent}") + out_str += f"\nMedium objects:\n{indented}" + if self.large_objects is not None: + indented = indent + str(self.large_objects).replace("\n", f"\n{indent}") + out_str += f"\nLarge objects:\n{indented}" + + return out_str + + def to_pandas(self) -> pd.DataFrame: + """ + Convert the result to a pandas DataFrame. + + Returns: + The result as a DataFrame. + """ + ensure_pandas_installed() + import pandas as pd + + pandas_data: dict[str, Any] = { + "mAR @ 1": self.mAR_at_1, + "mAR @ 10": self.mAR_at_10, + "mAR @ 100": self.mAR_at_100, + } + + if self.small_objects is not None: + small_objects_df = self.small_objects.to_pandas() + for key, value in small_objects_df.items(): + pandas_data[f"small_objects_{key}"] = value + if self.medium_objects is not None: + medium_objects_df = self.medium_objects.to_pandas() + for key, value in medium_objects_df.items(): + pandas_data[f"medium_objects_{key}"] = value + if self.large_objects is not None: + large_objects_df = self.large_objects.to_pandas() + for key, value in large_objects_df.items(): + pandas_data[f"large_objects_{key}"] = value + + return pd.DataFrame(pandas_data, index=[0]) + + def plot(self) -> None: + """ + Plot the Mean Average Recall results. + + ![example_plot](\ + https://media.roboflow.com/supervision-docs/metrics/mAR_plot_example.png\ + ){ align=center width="800" } + """ + from matplotlib import pyplot as plt + + labels = ["mAR @ 1", "mAR @ 10", "mAR @ 100"] + values = [self.mAR_at_1, self.mAR_at_10, self.mAR_at_100] + colors = [LEGACY_COLOR_PALETTE[0]] * 3 + + if self.small_objects is not None: + small_objects = self.small_objects + labels += ["Small: mAR @ 1", "Small: mAR @ 10", "Small: mAR @ 100"] + values += [ + small_objects.mAR_at_1, + small_objects.mAR_at_10, + small_objects.mAR_at_100, + ] + colors += [LEGACY_COLOR_PALETTE[3]] * 3 + + if self.medium_objects is not None: + medium_objects = self.medium_objects + labels += ["Medium: mAR @ 1", "Medium: mAR @ 10", "Medium: mAR @ 100"] + values += [ + medium_objects.mAR_at_1, + medium_objects.mAR_at_10, + medium_objects.mAR_at_100, + ] + colors += [LEGACY_COLOR_PALETTE[2]] * 3 + + if self.large_objects is not None: + large_objects = self.large_objects + labels += ["Large: mAR @ 1", "Large: mAR @ 10", "Large: mAR @ 100"] + values += [ + large_objects.mAR_at_1, + large_objects.mAR_at_10, + large_objects.mAR_at_100, + ] + colors += [LEGACY_COLOR_PALETTE[4]] * 3 + + plt.rcParams["font.family"] = "monospace" + + _, ax = plt.subplots(figsize=(10, 6)) + ax.set_ylim(0, 1) + ax.set_ylabel("Value", fontweight="bold") + title = ( + f"Mean Average Recall, by Object Size\n(target: {self.metric_target.value})" + ) + ax.set_title(title, fontweight="bold") + + x_positions = range(len(labels)) + bars = ax.bar(x_positions, values, color=colors, align="center") + + ax.set_xticks(x_positions) + ax.set_xticklabels(labels, rotation=45, ha="right") + + for bar in bars: + y_value = bar.get_height() + ax.text( + bar.get_x() + bar.get_width() / 2, + y_value + 0.02, + f"{y_value:.2f}", + ha="center", + va="bottom", + ) + + plt.rcParams["font.family"] = "sans-serif" + + plt.tight_layout() + plt.show() + + +class MeanAverageRecall(Metric["MeanAverageRecallResult"]): + """ + Mean Average Recall (mAR) measures how well the model detects + and retrieves relevant objects by averaging recall over multiple + IoU thresholds, classes and detection limits. + + Intuitively, while Recall measures the ability to find all relevant + objects, mAR narrows down how many detections are considered for each + image. For example, mAR @ 100 considers the top 100 highest confidence + detections for each image. mAR @ 1 considers only the highest + confidence detection for each image. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> from supervision.metrics import MeanAverageRecall + >>> predictions = sv.Detections( + ... xyxy=np.array([[0, 0, 10, 10]]), + ... class_id=np.array([0]), + ... confidence=np.array([0.9]) + ... ) + >>> targets = sv.Detections( + ... xyxy=np.array([[0, 0, 10, 10]]), + ... class_id=np.array([0]) + ... ) + >>> mar_metric = MeanAverageRecall() + >>> mar_result = mar_metric.update(predictions, targets).compute() + >>> round(float(mar_result.mAR_at_100), 2) + 1.0 + + ``` + + ![example_plot]( + https://media.roboflow.com/supervision-docs/metrics/mAR_plot_example.png + ){ align=center width="800" } + """ + + def __init__( + self, + metric_target: MetricTarget = MetricTarget.BOXES, + ): + """ + Initialize the Mean Average Recall metric. + + Args: + metric_target: The type of detection data to use. + """ + self._metric_target = metric_target + + self._predictions_list: list[Detections] = [] + self._targets_list: list[Detections] = [] + + self.max_detections = np.array([1, 10, 100]) + + def reset(self) -> None: + """ + Reset the metric to its initial state, clearing all stored data. + """ + self._predictions_list = [] + self._targets_list = [] + + def update( + self, + predictions: Detections | list[Detections], + targets: Detections | list[Detections], + ) -> MeanAverageRecall: + """ + Add new predictions and targets to the metric, but do not compute the result. + + Args: + predictions: The predicted detections. + targets: The target detections. + + Returns: + The updated metric instance. + """ + if not isinstance(predictions, list): + predictions = [predictions] + if not isinstance(targets, list): + targets = [targets] + + if len(predictions) != len(targets): + raise ValueError( + f"The number of predictions ({len(predictions)}) and" + f" targets ({len(targets)}) during the update must be the same." + ) + + self._predictions_list.extend(predictions) + self._targets_list.extend(targets) + + return self + + def compute(self) -> MeanAverageRecallResult: + """ + Calculate the Mean Average Recall metric based on the stored predictions + and ground-truth, at different IoU thresholds and maximum detection counts. + + Returns: + The Mean Average Recall metric result. + """ + result = self._compute(self._predictions_list, self._targets_list) + result.small_objects = self._compute( + self._predictions_list, self._targets_list, ObjectSizeCategory.SMALL + ) + result.medium_objects = self._compute( + self._predictions_list, self._targets_list, ObjectSizeCategory.MEDIUM + ) + result.large_objects = self._compute( + self._predictions_list, self._targets_list, ObjectSizeCategory.LARGE + ) + + return result + + def _compute( + self, + predictions_list: list[Detections], + targets_list: list[Detections], + size_category: ObjectSizeCategory = ObjectSizeCategory.ANY, + ) -> MeanAverageRecallResult: + if size_category != ObjectSizeCategory.ANY: + # Recall is unaffected by false-positive bookkeeping, and out-of-bucket + # predictions must still consume top-K rank slots, so bucket-filtering + # the targets is all the size handling mAR needs. + targets_list = [ + self._filter_detections_by_size(targets, size_category) + for targets in targets_list + ] + + iou_thresholds = np.linspace(0.5, 0.95, 10, dtype=np.float32) + stats: list[Any] = [] + + for predictions, targets in zip(predictions_list, targets_list): + prediction_contents = self._detections_content(predictions) + target_contents = self._detections_content(targets) + if len(targets) > 0: + if predictions.class_id is None or targets.class_id is None: + raise ValueError( + "MeanAverageRecall metric requires `class_id` on both " + "predictions and targets." + ) + if len(predictions) == 0: + target_class_ids = np.asarray(targets.class_id, dtype=np.int32) + if len(target_class_ids) == 0: + continue + stats.append( + ( + np.zeros( + (0, iou_thresholds.size, self.max_detections.size), + dtype=bool, + ), + np.zeros((0, iou_thresholds.size), dtype=bool), + np.zeros((0,), dtype=int), + np.zeros((0,), dtype=int), + target_class_ids, + ) + ) + + else: + if predictions.confidence is None: + raise ValueError( + "MeanAverageRecall metric requires `confidence` on " + "predictions." + ) + prediction_class_ids = np.asarray( + predictions.class_id, dtype=np.int32 + ) + target_class_ids = np.asarray(targets.class_id, dtype=np.int32) + prediction_confidence = np.asarray( + predictions.confidence, dtype=np.float32 + ) + if self._metric_target == MetricTarget.BOXES: + # BOXES target never yields CompactMask; narrow for mypy. + iou = box_iou_batch( + cast(npt.NDArray[np.number], target_contents), + cast(npt.NDArray[np.number], prediction_contents), + ) + elif self._metric_target == MetricTarget.MASKS: + iou = mask_iou_batch(target_contents, prediction_contents) + elif self._metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES: + # OBB target never yields CompactMask; narrow for mypy. + iou = oriented_box_iou_batch( + cast(npt.NDArray[np.number], target_contents), + cast(npt.NDArray[np.number], prediction_contents), + ) + else: + raise ValueError( + "Unsupported metric target for IoU calculation" + ) + + sorted_indices = np.argsort(-prediction_confidence) + matches = self._match_top_predictions( + prediction_class_ids[sorted_indices], + target_class_ids, + iou[:, sorted_indices], + iou_thresholds, + ) + ignored_matches = np.zeros( + (len(sorted_indices), iou_thresholds.size), dtype=bool + ) + + stats.append( + ( + matches, + ignored_matches, + np.arange(len(prediction_confidence)), + prediction_class_ids[sorted_indices], + target_class_ids, + ) + ) + + if not stats: + max_detection_count = self.max_detections.shape[0] + return MeanAverageRecallResult( + metric_target=self._metric_target, + recall_scores=np.zeros(max_detection_count), + recall_per_class=np.zeros( + (max_detection_count, 0, iou_thresholds.shape[0]) + ), + max_detections=self.max_detections, + iou_thresholds=iou_thresholds, + matched_classes=np.array([], dtype=int), + small_objects=None, + medium_objects=None, + large_objects=None, + ) + + concatenated_stats = [np.concatenate(items, 0) for items in zip(*stats)] + recall_scores_per_k, recall_per_class_at_k, unique_classes = ( + self._compute_average_recall_for_classes(*concatenated_stats) + ) + + return MeanAverageRecallResult( + metric_target=self._metric_target, + recall_scores=recall_scores_per_k, + recall_per_class=recall_per_class_at_k, + max_detections=self.max_detections, + iou_thresholds=iou_thresholds, + matched_classes=unique_classes, + small_objects=None, + medium_objects=None, + large_objects=None, + ) + + def _match_top_predictions( + self, + sorted_prediction_class_ids: npt.NDArray[np.int32], + target_class_ids: npt.NDArray[np.int32], + sorted_iou: npt.NDArray[np.float32], + iou_thresholds: npt.NDArray[np.float32], + ) -> npt.NDArray[np.bool_]: + """Match one image's predictions separately for each detection limit. + + The matcher pairs by highest IoU rather than by confidence, so matching every + prediction and then keeping the top K would let a prediction ranked below K + take a target from one ranked within it. Each limit therefore matches only its + own top K predictions. + + Args: + sorted_prediction_class_ids: shape (P,), prediction class ids sorted by + descending confidence. + target_class_ids: shape (T,), target class ids. + sorted_iou: shape (T, P), IoU with prediction columns in the same order. + iou_thresholds: shape (Th,), IoU thresholds. + + Returns: + shape (P, Th, K), whether each prediction is a true positive when only + the top `max_detections[k]` predictions are matched; predictions + ranked below that limit are `False`. + """ + prediction_count = sorted_prediction_class_ids.shape[0] + matches = np.zeros( + (prediction_count, iou_thresholds.size, self.max_detections.size), + dtype=bool, + ) + for limit_index, max_detections in enumerate(self.max_detections): + top_count = min(int(max_detections), prediction_count) + limit_matches, _ = _match_detection_batch_with_target_indices( + sorted_prediction_class_ids[:top_count], + target_class_ids, + sorted_iou[:, :top_count], + iou_thresholds, + ) + matches[:top_count, :, limit_index] = limit_matches + return matches + + def _compute_average_recall_for_classes( + self, + matches: npt.NDArray[np.bool_], + ignored_matches: npt.NDArray[np.bool_], + prediction_indices: npt.NDArray[np.int32], + prediction_class_ids: npt.NDArray[np.int32], + true_class_ids: npt.NDArray[np.int32], + ) -> tuple[ + npt.NDArray[np.float64], + npt.NDArray[np.float64], + npt.NDArray[np.int32], + ]: + """Compute recall per detection limit and class from all images' matches. + + `matches` has shape (P, Th, K) and holds, for each detection limit, the + matches of that limit's own top predictions; the other arrays have one row + or entry per prediction, or per target for `true_class_ids`. + """ + unique_classes, class_counts = np.unique(true_class_ids, return_counts=True) + + if unique_classes.size == 0: + max_detection_count = self.max_detections.shape[0] + num_thresholds = matches.shape[1] + return ( + np.zeros(max_detection_count, dtype=np.float64), + np.zeros((max_detection_count, 0, num_thresholds), dtype=np.float64), + unique_classes, + ) + + recalls_at_k: list[npt.NDArray[np.float64]] = [] + for limit_index, max_detections in enumerate(self.max_detections): + # Shape: PxThxK,P,C,C -> CxThx3 + is_within_limit = prediction_indices < max_detections + confusion_matrix = self._compute_confusion_matrix( + matches[is_within_limit, :, limit_index], + ignored_matches[is_within_limit], + prediction_class_ids[is_within_limit], + unique_classes, + class_counts, + ) + + # Shape: CxThx3 -> CxTh + recall_per_class = self._compute_recall(confusion_matrix) + recalls_at_k.append(recall_per_class) + + # Shape: KxCxTh -> KxC + recall_per_class_at_k = np.array(recalls_at_k) + average_recall_per_class = np.mean(recall_per_class_at_k, axis=2) + + # Shape: KxC -> K + recall_scores = np.mean(average_recall_per_class, axis=1) + + return recall_scores, recall_per_class_at_k, unique_classes + + @staticmethod + def _match_detection_batch( + predictions_classes: npt.NDArray[np.int32], + target_classes: npt.NDArray[np.int32], + iou: npt.NDArray[np.float32], + iou_thresholds: npt.NDArray[np.float32], + ) -> npt.NDArray[np.bool_]: + result_correct, _ = _match_detection_batch_with_target_indices( + predictions_classes, target_classes, iou, iou_thresholds + ) + return result_correct + + @staticmethod + def _compute_confusion_matrix( + sorted_matches: npt.NDArray[np.bool_], + sorted_ignored_matches: npt.NDArray[np.bool_], + sorted_prediction_class_ids: npt.NDArray[np.int32], + unique_classes: npt.NDArray[np.integer], + class_counts: npt.NDArray[np.integer], + ) -> npt.NDArray[np.float64]: + """ + Compute the confusion matrix for each class and IoU threshold. + + Assumes the matches and prediction_class_ids are sorted by confidence + in descending order. + + Args: + sorted_matches: shape (P, Th), that is True + if the prediction is a true positive at the given IoU threshold. + sorted_ignored_matches: shape (P, Th), that is True + if the prediction should not affect the given IoU threshold. + sorted_prediction_class_ids: shape (P,), containing + the class id for each prediction. + unique_classes: shape (C,), containing the unique + class ids. + class_counts: shape (C,), containing the number + of true instances for each class. + max_detections: The maximum number of detections to + consider for each class. Extra detections are considered false + positives. By default, all detections are considered. + + Returns: + shape (C, Th, 3), containing the true positives, false + positives, and false negatives for each class and IoU threshold. + """ + num_thresholds = sorted_matches.shape[1] + num_classes = unique_classes.shape[0] + + confusion_matrix: npt.NDArray[np.float64] = np.zeros( + (num_classes, num_thresholds, 3), dtype=np.float64 + ) + for class_idx, class_id in enumerate(unique_classes): + is_class = sorted_prediction_class_ids == class_id + num_true = class_counts[class_idx] + num_predictions = is_class.sum() + + if num_predictions == 0: + true_positives = np.zeros(num_thresholds) + false_positives = np.zeros(num_thresholds) + false_negatives = np.full(num_thresholds, num_true) + elif num_true == 0: + true_positives = np.zeros(num_thresholds) + false_positives = (~sorted_ignored_matches[is_class]).sum(0) + false_negatives = np.zeros(num_thresholds) + else: + limited_matches = sorted_matches[is_class] + limited_ignored_matches = sorted_ignored_matches[is_class] + true_positives = limited_matches.sum(0) + + false_positives = (~limited_matches & ~limited_ignored_matches).sum(0) + false_negatives = num_true - true_positives + + confusion_matrix[class_idx] = np.stack( + [true_positives, false_positives, false_negatives], axis=1 + ) + + result_confusion_matrix: npt.NDArray[np.float64] = confusion_matrix + return result_confusion_matrix + + @staticmethod + def _compute_recall( + confusion_matrix: npt.NDArray[np.float64], + ) -> npt.NDArray[np.float64]: + """ + Broadcastable function, computing the recall from the confusion matrix. + + Args: + confusion_matrix: shape (N, ..., 3), where the last dimension + contains the true positives, false positives, and false negatives. + + Returns: + shape (N, ...), containing the recall for each element. + """ + if not confusion_matrix.shape[-1] == 3: + raise ValueError( + f"Confusion matrix must have shape (..., 3), got " + f"{confusion_matrix.shape}" + ) + true_positives = confusion_matrix[..., 0] + false_negatives = confusion_matrix[..., 2] + + denominator = true_positives + false_negatives + recall = np.divide( + true_positives, + denominator, + out=np.zeros_like(denominator, dtype=np.float64), + where=denominator != 0, + ) + + result_recall: npt.NDArray[np.float64] = recall + return result_recall + + def _detections_content( + self, detections: Detections + ) -> npt.NDArray[Any] | CompactMask: + """Return boxes, masks or oriented bounding boxes from detections. + + For the mask target this may return a + :class:`~supervision.detection.compact_mask.CompactMask` rather than a + dense boolean array when the detections carry compact masks. + """ + if self._metric_target == MetricTarget.BOXES: + return cast(npt.NDArray[Any], detections.xyxy) + if self._metric_target == MetricTarget.MASKS: + if detections.mask is not None: + # detections.mask is NDArray[bool] | CompactMask; return as-is. + return detections.mask + if len(detections) > 0: + raise ValueError( + "MeanAverageRecall with `MetricTarget.MASKS` requires " + "detections to include masks." + ) + return self._make_empty_content() + if self._metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES: + obb = detections.data.get(ORIENTED_BOX_COORDINATES) + if obb is not None and len(obb) > 0: + result_obb: npt.NDArray[np.float32] = np.array(obb, dtype=np.float32) + return result_obb + return self._make_empty_content() + raise ValueError(f"Invalid metric target: {self._metric_target}") + + def _make_empty_content(self) -> npt.NDArray[Any]: + if self._metric_target == MetricTarget.BOXES: + empty_boxes: npt.NDArray[np.float32] = np.empty((0, 4), dtype=np.float32) + return empty_boxes + + if self._metric_target == MetricTarget.MASKS: + empty_masks: npt.NDArray[np.bool_] = np.empty((0, 0, 0), dtype=bool) + return empty_masks + + if self._metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES: + empty_obb: npt.NDArray[np.float32] = np.empty((0, 4, 2), dtype=np.float32) + return empty_obb + + raise ValueError(f"Invalid metric target: {self._metric_target}") + + def _filter_detections_by_size( + self, detections: Detections, size_category: ObjectSizeCategory + ) -> Detections: + """Return a copy of detections with contents filtered by object size.""" + new_detections = deepcopy(detections) + if detections.is_empty() or size_category == ObjectSizeCategory.ANY: + return new_detections + + sizes = get_detection_size_category(new_detections, self._metric_target) + size_mask = sizes == size_category.value + + new_detections.xyxy = new_detections.xyxy[size_mask] + if new_detections.mask is not None: + new_detections.mask = new_detections.mask[size_mask] + if new_detections.class_id is not None: + new_detections.class_id = new_detections.class_id[size_mask] + if new_detections.confidence is not None: + new_detections.confidence = new_detections.confidence[size_mask] + if new_detections.tracker_id is not None: + new_detections.tracker_id = new_detections.tracker_id[size_mask] + if new_detections.data is not None: + for key, value in new_detections.data.items(): + new_detections.data[key] = np.array(value)[size_mask] + + return new_detections diff --git a/.venv/lib/python3.12/site-packages/supervision/metrics/precision.py b/.venv/lib/python3.12/site-packages/supervision/metrics/precision.py new file mode 100644 index 0000000000000000000000000000000000000000..c8bcf34b2dde6efc4bf302523fc0abf4ca175459 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/metrics/precision.py @@ -0,0 +1,814 @@ +from __future__ import annotations + +from copy import deepcopy +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, cast + +import numpy as np +import numpy.typing as npt + +from supervision.config import ORIENTED_BOX_COORDINATES +from supervision.detection.core import Detections +from supervision.detection.utils.iou_and_nms import ( + box_iou_batch, + mask_iou_batch, + oriented_box_iou_batch, +) +from supervision.draw.color import LEGACY_COLOR_PALETTE +from supervision.metrics.core import AveragingMethod, Metric, MetricTarget +from supervision.metrics.utils.matching import ( + _match_detection_batch_with_target_indices, +) +from supervision.metrics.utils.object_size import ( + ObjectSizeCategory, + get_detection_size_category, +) +from supervision.metrics.utils.utils import ensure_pandas_installed + +if TYPE_CHECKING: + import pandas as pd + + +class Precision(Metric["PrecisionResult"]): + """ + Precision is a metric used to evaluate object detection models. It is the ratio of + true positive detections to the total number of predicted detections. We calculate + it at different IoU thresholds. + + In simple terms, Precision is a measure of a model's accuracy, calculated as: + + `Precision = TP / (TP + FP)` + + Here, `TP` is the number of true positives (correct detections), and `FP` is the + number of false positive detections (detected, but incorrectly). + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> from supervision.metrics import Precision + >>> predictions = sv.Detections( + ... xyxy=np.array([[0, 0, 10, 10]]), + ... class_id=np.array([0]), + ... confidence=np.array([0.9]) + ... ) + >>> targets = sv.Detections( + ... xyxy=np.array([[0, 0, 10, 10]]), + ... class_id=np.array([0]) + ... ) + >>> precision_metric = Precision() + >>> precision_result = precision_metric.update(predictions, targets).compute() + >>> round(float(precision_result.precision_at_50), 2) + 1.0 + + ``` + + ![example_plot]( + https://media.roboflow.com/supervision-docs/metrics/precision_plot_example.png + ){ align=center width="800" } + """ + + def __init__( + self, + metric_target: MetricTarget = MetricTarget.BOXES, + averaging_method: AveragingMethod = AveragingMethod.WEIGHTED, + ): + """ + Initialize the Precision metric. + + Args: + metric_target: The type of detection data to use. + averaging_method: The averaging method used to compute the + precision. Determines how the precision is aggregated across classes. + """ + self._metric_target = metric_target + self.averaging_method = averaging_method + + self._predictions_list: list[Detections] = [] + self._targets_list: list[Detections] = [] + + def reset(self) -> None: + """ + Reset the metric to its initial state, clearing all stored data. + """ + self._predictions_list = [] + self._targets_list = [] + + def update( + self, + predictions: Detections | list[Detections], + targets: Detections | list[Detections], + ) -> Precision: + """ + Add new predictions and targets to the metric, but do not compute the result. + + Args: + predictions: The predicted detections. + targets: The target detections. + + Returns: + The updated metric instance. + """ + if not isinstance(predictions, list): + predictions = [predictions] + if not isinstance(targets, list): + targets = [targets] + + if len(predictions) != len(targets): + raise ValueError( + f"The number of predictions ({len(predictions)}) and" + f" targets ({len(targets)}) during the update must be the same." + ) + + self._predictions_list.extend(predictions) + self._targets_list.extend(targets) + + return self + + def compute(self) -> PrecisionResult: + """ + Calculate the precision metric based on the stored predictions and ground-truth + data, at different IoU thresholds. + + Returns: + The precision metric result. + """ + result = self._compute(self._predictions_list, self._targets_list) + result.small_objects = self._compute( + self._predictions_list, self._targets_list, ObjectSizeCategory.SMALL + ) + result.medium_objects = self._compute( + self._predictions_list, self._targets_list, ObjectSizeCategory.MEDIUM + ) + result.large_objects = self._compute( + self._predictions_list, self._targets_list, ObjectSizeCategory.LARGE + ) + + return result + + def _compute( + self, + predictions_list: list[Detections], + targets_list: list[Detections], + size_category: ObjectSizeCategory = ObjectSizeCategory.ANY, + ) -> PrecisionResult: + """Build per-image stats tuples and delegate to class-level computation. + + Each stats tuple is + ``(matches, ignored_matches, confidence, class_ids, true_class_ids)``: + - Both empty: skip (no information). + - Targets empty, predictions present: all predictions are FPs; true_class_ids + is ``zeros((0,))``. + - Targets present: IoU matching produces ``matches`` array. + """ + iou_thresholds = np.linspace(0.5, 0.95, 10, dtype=np.float32) + stats: list[Any] = [] + + for predictions, targets in zip(predictions_list, targets_list): + prediction_contents = self._detections_content(predictions) + target_contents = self._detections_content(targets) + prediction_size_mask = np.ones(len(predictions), dtype=bool) + target_size_mask = np.ones(len(targets), dtype=bool) + if size_category != ObjectSizeCategory.ANY: + if len(predictions) > 0: + prediction_size_mask = ( + get_detection_size_category(predictions, self._metric_target) + == size_category.value + ) + if len(targets) > 0: + target_size_mask = ( + get_detection_size_category(targets, self._metric_target) + == size_category.value + ) + + if len(targets) == 0 and len(predictions) > 0: + # Only predictions are present (e.g. a background image); every + # prediction is a false positive. + if predictions.class_id is None or predictions.confidence is None: + raise ValueError( + "Precision metric requires `class_id` and `confidence` " + "on predictions." + ) + prediction_class_ids = np.asarray(predictions.class_id, dtype=np.int32)[ + prediction_size_mask + ] + prediction_confidence = np.asarray( + predictions.confidence, dtype=np.float32 + )[prediction_size_mask] + if len(prediction_class_ids) == 0: + continue + stats.append( + ( + np.zeros( + (len(prediction_class_ids), iou_thresholds.size), + dtype=np.bool_, + ), + np.zeros( + (len(prediction_class_ids), iou_thresholds.size), + dtype=np.bool_, + ), + prediction_confidence, + prediction_class_ids, + np.zeros((0,), dtype=np.int32), + ) + ) + elif len(targets) > 0: + if predictions.class_id is None or targets.class_id is None: + raise ValueError( + "Precision metric requires `class_id` on both predictions " + "and targets." + ) + if len(predictions) == 0: + target_class_ids = np.asarray(targets.class_id, dtype=np.int32)[ + target_size_mask + ] + if len(target_class_ids) == 0: + continue + stats.append( + ( + np.zeros((0, iou_thresholds.size), dtype=bool), + np.zeros((0, iou_thresholds.size), dtype=bool), + np.zeros((0,), dtype=np.float32), + np.zeros((0,), dtype=int), + target_class_ids, + ) + ) + + else: + if predictions.confidence is None: + raise ValueError( + "Precision metric requires `confidence` on predictions." + ) + prediction_class_ids = np.asarray( + predictions.class_id, dtype=np.int32 + ) + target_class_ids = np.asarray(targets.class_id, dtype=np.int32) + prediction_confidence = np.asarray( + predictions.confidence, dtype=np.float32 + ) + if self._metric_target == MetricTarget.BOXES: + iou = box_iou_batch(target_contents, prediction_contents) + elif self._metric_target == MetricTarget.MASKS: + iou = mask_iou_batch(target_contents, prediction_contents) + elif self._metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES: + iou = oriented_box_iou_batch( + target_contents, prediction_contents + ) + else: + raise ValueError( + "Unsupported metric target for IoU calculation" + ) + + # None keeps the matcher on its single-round fast path + # when no size bucket is scored. + target_scored_mask = ( + target_size_mask + if size_category != ObjectSizeCategory.ANY + else None + ) + matches, matched_target_indices = ( + _match_detection_batch_with_target_indices( + prediction_class_ids, + target_class_ids, + iou, + iou_thresholds, + target_scored_mask=target_scored_mask, + ) + ) + ignored_matches = np.zeros_like(matches, dtype=bool) + if size_category != ObjectSizeCategory.ANY: + valid_target_match = matched_target_indices >= 0 + matched_scored_target = np.zeros_like(matches, dtype=bool) + if np.any(valid_target_match): + matched_scored_target[valid_target_match] = ( + target_size_mask[ + matched_target_indices[valid_target_match] + ] + ) + prediction_scored = ( + prediction_size_mask[:, None] | matched_scored_target + ) + ignored_matches = ~prediction_scored | ( + valid_target_match & ~matched_scored_target + ) + prediction_keep = np.any(~ignored_matches, axis=1) + matches = ( + matches[prediction_keep] + & matched_scored_target[prediction_keep] + ) + ignored_matches = ignored_matches[prediction_keep] + prediction_confidence = prediction_confidence[prediction_keep] + prediction_class_ids = prediction_class_ids[prediction_keep] + target_class_ids = target_class_ids[target_size_mask] + if ( + len(prediction_class_ids) == 0 + and len(target_class_ids) == 0 + ): + continue + stats.append( + ( + matches, + ignored_matches, + prediction_confidence, + prediction_class_ids, + target_class_ids, + ) + ) + + if not stats: + return PrecisionResult( + metric_target=self._metric_target, + averaging_method=self.averaging_method, + precision_scores=np.zeros(iou_thresholds.shape[0]), + precision_per_class=np.zeros((0, iou_thresholds.shape[0])), + iou_thresholds=iou_thresholds, + matched_classes=np.array([], dtype=int), + small_objects=None, + medium_objects=None, + large_objects=None, + ) + + concatenated_stats = [np.concatenate(items, 0) for items in zip(*stats)] + precision_scores, precision_per_class, unique_classes = ( + self._compute_precision_for_classes(*concatenated_stats) + ) + + return PrecisionResult( + metric_target=self._metric_target, + averaging_method=self.averaging_method, + precision_scores=precision_scores, + precision_per_class=precision_per_class, + iou_thresholds=iou_thresholds, + matched_classes=unique_classes, + small_objects=None, + medium_objects=None, + large_objects=None, + ) + + def _compute_precision_for_classes( + self, + matches: npt.NDArray[np.bool_], + ignored_matches: npt.NDArray[np.bool_], + prediction_confidence: npt.NDArray[np.float32], + prediction_class_ids: npt.NDArray[np.int32], + true_class_ids: npt.NDArray[np.int32], + ) -> tuple[ + npt.NDArray[np.float64], + npt.NDArray[np.float64], + npt.NDArray[np.int32], + ]: + """Compute precision scores from concatenated stats across all images. + + ``unique_classes`` is the union of GT and predicted classes so that + predictions of classes absent from GT still count as false positives. + """ + sorted_indices = np.argsort(-prediction_confidence) + matches = matches[sorted_indices] + ignored_matches = ignored_matches[sorted_indices] + prediction_class_ids = prediction_class_ids[sorted_indices] + # Predictions whose class never appears in the ground truth are still + # false positives, so include those classes in the confusion matrix + # (their true-instance count is zero). + unique_classes = np.unique( + np.concatenate((true_class_ids, prediction_class_ids)) + ) + true_classes, true_counts = np.unique(true_class_ids, return_counts=True) + class_counts = np.zeros(unique_classes.shape[0], dtype=int) + class_counts[np.searchsorted(unique_classes, true_classes)] = true_counts + + # Shape: PxTh,P,C,C -> CxThx3 + confusion_matrix = self._compute_confusion_matrix( + matches, ignored_matches, prediction_class_ids, unique_classes, class_counts + ) + + # Shape: CxThx3 -> CxTh + precision_per_class = self._compute_precision(confusion_matrix) + + # Shape: CxTh -> Th + if self.averaging_method == AveragingMethod.MACRO: + precision_scores = np.mean(precision_per_class, axis=0) + elif self.averaging_method == AveragingMethod.MICRO: + confusion_matrix_merged = confusion_matrix.sum(0) + precision_scores = self._compute_precision(confusion_matrix_merged) + elif self.averaging_method == AveragingMethod.WEIGHTED: + class_counts = class_counts.astype(np.float32) + if class_counts.sum() == 0: + # No ground-truth support (e.g. only false-positive classes, or a + # size bucket with predictions but no targets): weighting is + # undefined, so report 0 as the empty case did before. + precision_scores = np.zeros(precision_per_class.shape[1]) + else: + precision_scores = np.average( + precision_per_class, axis=0, weights=class_counts + ) + + return precision_scores, precision_per_class, unique_classes + + @staticmethod + def _match_detection_batch( + predictions_classes: npt.NDArray[np.int32], + target_classes: npt.NDArray[np.int32], + iou: npt.NDArray[np.float32], + iou_thresholds: npt.NDArray[np.float32], + ) -> npt.NDArray[np.bool_]: + result_correct, _ = _match_detection_batch_with_target_indices( + predictions_classes, target_classes, iou, iou_thresholds + ) + return result_correct + + @staticmethod + def _compute_confusion_matrix( + sorted_matches: npt.NDArray[np.bool_], + sorted_ignored_matches: npt.NDArray[np.bool_], + sorted_prediction_class_ids: npt.NDArray[np.int32], + unique_classes: npt.NDArray[np.int32], + class_counts: npt.NDArray[np.int32], + ) -> npt.NDArray[np.float64]: + """ + Compute the confusion matrix for each class and IoU threshold. + + Assumes the matches and prediction_class_ids are sorted by confidence + in descending order. + + Args: + sorted_matches: shape (P, Th), that is True + if the prediction is a true positive at the given IoU threshold. + sorted_ignored_matches: shape (P, Th), that is True + if the prediction should not affect the given IoU threshold. + sorted_prediction_class_ids: shape (P,), containing + the class id for each prediction. + unique_classes: shape (C,), containing the unique + class ids. + class_counts: shape (C,), containing the number + of true instances for each class. + + Returns: + shape (C, Th, 3), containing the true positives, false + positives, and false negatives for each class and IoU threshold. + """ + + num_thresholds = sorted_matches.shape[1] + num_classes = unique_classes.shape[0] + + confusion_matrix: npt.NDArray[np.float64] = np.zeros( + (num_classes, num_thresholds, 3), dtype=np.float64 + ) + for class_idx, class_id in enumerate(unique_classes): + is_class = sorted_prediction_class_ids == class_id + num_true = class_counts[class_idx] + num_predictions = is_class.sum() + + if num_predictions == 0: + true_positives = np.zeros(num_thresholds) + false_positives = np.zeros(num_thresholds) + false_negatives = np.full(num_thresholds, num_true) + elif num_true == 0: + true_positives = np.zeros(num_thresholds) + false_positives = (~sorted_ignored_matches[is_class]).sum(0) + false_negatives = np.zeros(num_thresholds) + else: + true_positives = sorted_matches[is_class].sum(0) + false_positives = ( + ~sorted_matches[is_class] & ~sorted_ignored_matches[is_class] + ).sum(0) + false_negatives = num_true - true_positives + confusion_matrix[class_idx] = np.stack( + [true_positives, false_positives, false_negatives], axis=1 + ) + result_matrix: npt.NDArray[np.float64] = confusion_matrix + return result_matrix + + @staticmethod + def _compute_precision( + confusion_matrix: npt.NDArray[np.float64], + ) -> npt.NDArray[np.float64]: + """ + Broadcastable function, computing the precision from the confusion matrix. + + Args: + confusion_matrix: shape (N, ..., 3), where the last dimension + contains the true positives, false positives, and false negatives. + + Returns: + shape (N, ...), containing the precision for each element. + """ + if not confusion_matrix.shape[-1] == 3: + raise ValueError( + f"Confusion matrix must have shape (..., 3), got " + f"{confusion_matrix.shape}" + ) + true_positives = confusion_matrix[..., 0] + false_positives = confusion_matrix[..., 1] + + denominator = true_positives + false_positives + precision = np.divide( + true_positives, + denominator, + out=np.zeros_like(true_positives), + where=denominator != 0, + ) + + result_precision: npt.NDArray[np.float64] = precision + return result_precision + + def _detections_content(self, detections: Detections) -> npt.NDArray[Any]: + """Return boxes, masks or oriented bounding boxes from detections.""" + if self._metric_target == MetricTarget.BOXES: + return cast(npt.NDArray[Any], detections.xyxy) + if self._metric_target == MetricTarget.MASKS: + if detections.mask is not None: + return cast(npt.NDArray[Any], detections.mask) + if len(detections) > 0: + raise ValueError( + "Precision with `MetricTarget.MASKS` requires detections to " + "include masks." + ) + return self._make_empty_content() + if self._metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES: + obb = detections.data.get(ORIENTED_BOX_COORDINATES) + if obb is not None and len(obb) > 0: + result_obb: npt.NDArray[np.float32] = np.array(obb, dtype=np.float32) + return result_obb + return self._make_empty_content() + raise ValueError(f"Invalid metric target: {self._metric_target}") + + def _make_empty_content(self) -> npt.NDArray[Any]: + if self._metric_target == MetricTarget.BOXES: + empty_boxes: npt.NDArray[np.float32] = np.empty((0, 4), dtype=np.float32) + return empty_boxes + + if self._metric_target == MetricTarget.MASKS: + empty_masks: npt.NDArray[np.bool_] = np.empty((0, 0, 0), dtype=bool) + return empty_masks + + if self._metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES: + empty_obb: npt.NDArray[np.float32] = np.empty((0, 4, 2), dtype=np.float32) + return empty_obb + + raise ValueError(f"Invalid metric target: {self._metric_target}") + + def _filter_detections_by_size( + self, detections: Detections, size_category: ObjectSizeCategory + ) -> Detections: + """Return a copy of detections with contents filtered by object size.""" + new_detections = deepcopy(detections) + if detections.is_empty() or size_category == ObjectSizeCategory.ANY: + return new_detections + + sizes = get_detection_size_category(new_detections, self._metric_target) + size_mask = sizes == size_category.value + + new_detections.xyxy = new_detections.xyxy[size_mask] + if new_detections.mask is not None: + new_detections.mask = new_detections.mask[size_mask] + if new_detections.class_id is not None: + new_detections.class_id = new_detections.class_id[size_mask] + if new_detections.confidence is not None: + new_detections.confidence = new_detections.confidence[size_mask] + if new_detections.tracker_id is not None: + new_detections.tracker_id = new_detections.tracker_id[size_mask] + if new_detections.data is not None: + for key, value in new_detections.data.items(): + new_detections.data[key] = np.array(value)[size_mask] + + return new_detections + + def _filter_predictions_and_targets_by_size( + self, + predictions_list: list[Detections], + targets_list: list[Detections], + size_category: ObjectSizeCategory, + ) -> tuple[list[Detections], list[Detections]]: + """ + Filter predictions and targets by object size category. + """ + new_predictions_list = [] + new_targets_list = [] + for predictions, targets in zip(predictions_list, targets_list): + new_predictions_list.append( + self._filter_detections_by_size(predictions, size_category) + ) + new_targets_list.append( + self._filter_detections_by_size(targets, size_category) + ) + return new_predictions_list, new_targets_list + + +@dataclass +class PrecisionResult: + """ + The results of the precision metric calculation. + + Defaults to `0` if no detections or targets were provided. + + Attributes: + metric_target: the type of data used for the metric - + boxes, masks or oriented bounding boxes. + averaging_method: the averaging method used to compute the + precision. Determines how the precision is aggregated across classes. + precision_at_50: the precision at IoU threshold of `0.5`. + precision_at_75: the precision at IoU threshold of `0.75`. + precision_scores: the precision scores at each IoU threshold. + Shape: `(num_iou_thresholds,)` + precision_per_class: the precision scores per class and + IoU threshold. Shape: `(num_classes, num_iou_thresholds)` + iou_thresholds: the IoU thresholds used in the calculations. + matched_classes: the class IDs present in either predictions or ground + truth. Corresponds to the rows of `precision_per_class`. Classes + that appear only in predictions (no ground-truth instances) are + included; their per-threshold precision values will be `0.0`. + small_objects: the Precision metric results + for small objects (area < 32²). + medium_objects: the Precision metric results + for medium objects (32² ≤ area < 96²). + large_objects: the Precision metric results + for large objects (area ≥ 96²). + """ + + metric_target: MetricTarget + averaging_method: AveragingMethod + + @property + def precision_at_50(self) -> float: + return float(self.precision_scores[0]) + + @property + def precision_at_75(self) -> float: + return float(self.precision_scores[5]) + + precision_scores: npt.NDArray[np.float64] + precision_per_class: npt.NDArray[np.float64] + iou_thresholds: npt.NDArray[np.float32] + matched_classes: npt.NDArray[np.int32] + + small_objects: PrecisionResult | None + medium_objects: PrecisionResult | None + large_objects: PrecisionResult | None + + def __str__(self) -> str: + """ + Format as a pretty string. + + Example: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> from supervision.metrics import Precision + >>> predictions = sv.Detections( + ... xyxy=np.array([[0, 0, 10, 10]]), + ... class_id=np.array([0]), + ... confidence=np.array([0.9]) + ... ) + >>> targets = sv.Detections( + ... xyxy=np.array([[0, 0, 10, 10]]), + ... class_id=np.array([0]) + ... ) + >>> precision_metric = Precision() + >>> precision_result = precision_metric.update( + ... predictions, targets + ... ).compute() + >>> print(precision_result) # doctest: +ELLIPSIS + PrecisionResult: + Metric target: MetricTarget.BOXES + Averaging method: AveragingMethod.WEIGHTED + P @ 50: 1.0000 + P @ 75: 1.0000 + P @ thresh: [1. ... 1.] + IoU thresh: [0.5 0.55 ... 0.95] + Precision per class: + 0: [1. ... 1.] + ... + Medium objects: + PrecisionResult: + Metric target: MetricTarget.BOXES + Averaging method: AveragingMethod.WEIGHTED + P @ 50: 0.0000 + ... + + ``` + """ + out_str = ( + f"{self.__class__.__name__}:\n" + f"Metric target: {self.metric_target}\n" + f"Averaging method: {self.averaging_method}\n" + f"P @ 50: {self.precision_at_50:.4f}\n" + f"P @ 75: {self.precision_at_75:.4f}\n" + f"P @ thresh: {self.precision_scores}\n" + f"IoU thresh: {self.iou_thresholds}\n" + f"Precision per class:\n" + ) + if self.precision_per_class.size == 0: + out_str += " No results\n" + for class_id, precision_of_class in zip( + self.matched_classes, self.precision_per_class + ): + out_str += f" {class_id}: {precision_of_class}\n" + + indent = " " + if self.small_objects is not None: + indented = indent + str(self.small_objects).replace("\n", f"\n{indent}") + out_str += f"\nSmall objects:\n{indented}" + if self.medium_objects is not None: + indented = indent + str(self.medium_objects).replace("\n", f"\n{indent}") + out_str += f"\nMedium objects:\n{indented}" + if self.large_objects is not None: + indented = indent + str(self.large_objects).replace("\n", f"\n{indent}") + out_str += f"\nLarge objects:\n{indented}" + + return out_str + + def to_pandas(self) -> pd.DataFrame: + """ + Convert the result to a pandas DataFrame. + + Returns: + The result as a DataFrame. + """ + ensure_pandas_installed() + import pandas as pd + + pandas_data = { + "P@50": self.precision_at_50, + "P@75": self.precision_at_75, + } + + if self.small_objects is not None: + small_objects_df = self.small_objects.to_pandas() + for key, value in small_objects_df.items(): + pandas_data[f"small_objects_{key}"] = value + if self.medium_objects is not None: + medium_objects_df = self.medium_objects.to_pandas() + for key, value in medium_objects_df.items(): + pandas_data[f"medium_objects_{key}"] = value + if self.large_objects is not None: + large_objects_df = self.large_objects.to_pandas() + for key, value in large_objects_df.items(): + pandas_data[f"large_objects_{key}"] = value + + return pd.DataFrame(pandas_data, index=[0]) + + def plot(self) -> None: + """ + Plot the precision results. + + ![example_plot]( + https://media.roboflow.com/supervision-docs/metrics/precision_plot_example.png + ){ align=center width="800" } + """ + + from matplotlib import pyplot as plt + + labels = ["Precision@50", "Precision@75"] + values = [self.precision_at_50, self.precision_at_75] + colors = [LEGACY_COLOR_PALETTE[0]] * 2 + + if self.small_objects is not None: + small_objects = self.small_objects + labels += ["Small: P@50", "Small: P@75"] + values += [small_objects.precision_at_50, small_objects.precision_at_75] + colors += [LEGACY_COLOR_PALETTE[3]] * 2 + + if self.medium_objects is not None: + medium_objects = self.medium_objects + labels += ["Medium: P@50", "Medium: P@75"] + values += [medium_objects.precision_at_50, medium_objects.precision_at_75] + colors += [LEGACY_COLOR_PALETTE[2]] * 2 + + if self.large_objects is not None: + large_objects = self.large_objects + labels += ["Large: P@50", "Large: P@75"] + values += [large_objects.precision_at_50, large_objects.precision_at_75] + colors += [LEGACY_COLOR_PALETTE[4]] * 2 + + plt.rcParams["font.family"] = "monospace" + + _, ax = plt.subplots(figsize=(10, 6)) + ax.set_ylim(0, 1) + ax.set_ylabel("Value", fontweight="bold") + title = ( + f"Precision, by Object Size" + f"\n(target: {self.metric_target.value}," + f" averaging: {self.averaging_method.value})" + ) + ax.set_title(title, fontweight="bold") + + x_positions = range(len(labels)) + bars = ax.bar(x_positions, values, color=colors, align="center") + + ax.set_xticks(x_positions) + ax.set_xticklabels(labels, rotation=45, ha="right") + + for bar in bars: + y_value = bar.get_height() + ax.text( + bar.get_x() + bar.get_width() / 2, + y_value + 0.02, + f"{y_value:.2f}", + ha="center", + va="bottom", + ) + + plt.rcParams["font.family"] = "sans-serif" + + plt.tight_layout() + plt.show() diff --git a/.venv/lib/python3.12/site-packages/supervision/metrics/recall.py b/.venv/lib/python3.12/site-packages/supervision/metrics/recall.py new file mode 100644 index 0000000000000000000000000000000000000000..e5be7bb566a971781d8bb708f836553306cea864 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/metrics/recall.py @@ -0,0 +1,845 @@ +from __future__ import annotations + +from copy import deepcopy +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, cast + +import numpy as np +import numpy.typing as npt + +from supervision.config import ORIENTED_BOX_COORDINATES +from supervision.detection.compact_mask import CompactMask +from supervision.detection.core import Detections +from supervision.detection.utils.iou_and_nms import ( + box_iou_batch, + mask_iou_batch, + oriented_box_iou_batch, +) +from supervision.draw.color import LEGACY_COLOR_PALETTE +from supervision.metrics.core import AveragingMethod, Metric, MetricTarget +from supervision.metrics.utils.matching import ( + _match_detection_batch_with_target_indices, +) +from supervision.metrics.utils.object_size import ( + ObjectSizeCategory, + get_detection_size_category, +) +from supervision.metrics.utils.utils import ensure_pandas_installed + +if TYPE_CHECKING: + import pandas as pd + + +class Recall(Metric["RecallResult"]): + """ + Recall is a metric used to evaluate object detection models. It is the ratio of + true positive detections to the total number of ground truth instances. We calculate + it at different IoU thresholds. + + In simple terms, Recall is a measure of a model's completeness, calculated as: + + `Recall = TP / (TP + FN)` + + Here, `TP` is the number of true positives (correct detections), and `FN` is the + number of false negatives (missed detections). + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> from supervision.metrics import Recall + >>> predictions = sv.Detections( + ... xyxy=np.array([[0, 0, 10, 10]]), + ... class_id=np.array([0]), + ... confidence=np.array([0.9]) + ... ) + >>> targets = sv.Detections( + ... xyxy=np.array([[0, 0, 10, 10]]), + ... class_id=np.array([0]) + ... ) + >>> recall_metric = Recall() + >>> recall_result = recall_metric.update(predictions, targets).compute() + >>> round(float(recall_result.recall_at_50), 2) + 1.0 + + ``` + + A class that only ever appears in the predictions (for example a detection + on a background image with no ground truth) has no instances to recall, so + it is tracked with a recall of `0.0` rather than dropped. This keeps the + tracked class set aligned with Precision and F1Score for the same input: + + ```pycon + >>> predictions = sv.Detections( + ... xyxy=np.array([[0, 0, 10, 10], [100, 0, 110, 10]]), + ... class_id=np.array([0, 1]), # class 1 has no ground-truth instance + ... confidence=np.array([0.9, 0.8]) + ... ) + >>> targets = sv.Detections( + ... xyxy=np.array([[0, 0, 10, 10]]), + ... class_id=np.array([0]) + ... ) + >>> recall_result = Recall().update(predictions, targets).compute() + >>> recall_result.matched_classes.tolist() + [0, 1] + >>> round(float(recall_result.recall_per_class[0][0]), 2) # matched class 0 + 1.0 + >>> round(float(recall_result.recall_per_class[1][0]), 2) # prediction-only + 0.0 + + ``` + + ![example_plot]( + https://media.roboflow.com/supervision-docs/metrics/recall_plot_example.png + ){ align=center width="800" } + """ + + def __init__( + self, + metric_target: MetricTarget = MetricTarget.BOXES, + averaging_method: AveragingMethod = AveragingMethod.WEIGHTED, + ): + """ + Initialize the Recall metric. + + Args: + metric_target: The type of detection data to use. + averaging_method: The averaging method used to compute the + recall. Determines how the recall is aggregated across classes. + """ + self._metric_target = metric_target + self.averaging_method = averaging_method + + self._predictions_list: list[Detections] = [] + self._targets_list: list[Detections] = [] + + def reset(self) -> None: + """ + Reset the metric to its initial state, clearing all stored data. + """ + self._predictions_list = [] + self._targets_list = [] + + def update( + self, + predictions: Detections | list[Detections], + targets: Detections | list[Detections], + ) -> Recall: + """ + Add new predictions and targets to the metric, but do not compute the result. + + Args: + predictions: The predicted detections. + targets: The target detections. + + Returns: + The updated metric instance. + """ + if not isinstance(predictions, list): + predictions = [predictions] + if not isinstance(targets, list): + targets = [targets] + + if len(predictions) != len(targets): + raise ValueError( + f"The number of predictions ({len(predictions)}) and" + f" targets ({len(targets)}) during the update must be the same." + ) + + self._predictions_list.extend(predictions) + self._targets_list.extend(targets) + + return self + + def compute(self) -> RecallResult: + """ + Calculate the recall metric based on the stored predictions and ground-truth + data, at different IoU thresholds. + + Returns: + The recall metric result. + """ + result = self._compute(self._predictions_list, self._targets_list) + result.small_objects = self._compute( + self._predictions_list, self._targets_list, ObjectSizeCategory.SMALL + ) + result.medium_objects = self._compute( + self._predictions_list, self._targets_list, ObjectSizeCategory.MEDIUM + ) + result.large_objects = self._compute( + self._predictions_list, self._targets_list, ObjectSizeCategory.LARGE + ) + + return result + + def _compute( + self, + predictions_list: list[Detections], + targets_list: list[Detections], + size_category: ObjectSizeCategory = ObjectSizeCategory.ANY, + ) -> RecallResult: + iou_thresholds = np.linspace(0.5, 0.95, 10, dtype=np.float32) + stats: list[Any] = [] + + for predictions, targets in zip(predictions_list, targets_list): + prediction_contents = self._detections_content(predictions) + target_contents = self._detections_content(targets) + prediction_size_mask = np.ones(len(predictions), dtype=bool) + target_size_mask = np.ones(len(targets), dtype=bool) + if size_category != ObjectSizeCategory.ANY: + if len(predictions) > 0: + prediction_size_mask = ( + get_detection_size_category(predictions, self._metric_target) + == size_category.value + ) + if len(targets) > 0: + target_size_mask = ( + get_detection_size_category(targets, self._metric_target) + == size_category.value + ) + + if len(targets) == 0 and len(predictions) > 0: + # Only predictions are present (e.g. a background image). They produce + # no false negatives, so no recall value changes, but the classes still + # have to be tracked or `matched_classes` silently disagrees with + # Precision and F1Score for the same input. + if predictions.class_id is None or predictions.confidence is None: + raise ValueError( + "Recall metric requires `class_id` and `confidence` " + "on predictions." + ) + prediction_class_ids = np.asarray(predictions.class_id, dtype=np.int32)[ + prediction_size_mask + ] + prediction_confidence = np.asarray( + predictions.confidence, dtype=np.float32 + )[prediction_size_mask] + if len(prediction_class_ids) == 0: + continue + stats.append( + ( + np.zeros( + (len(prediction_class_ids), iou_thresholds.size), + dtype=np.bool_, + ), + np.zeros( + (len(prediction_class_ids), iou_thresholds.size), + dtype=np.bool_, + ), + prediction_confidence, + prediction_class_ids, + np.zeros((0,), dtype=np.int32), + ) + ) + elif len(targets) > 0: + if predictions.class_id is None or targets.class_id is None: + raise ValueError( + "Recall metric requires `class_id` on both predictions " + "and targets." + ) + if len(predictions) == 0: + target_class_ids = np.asarray(targets.class_id, dtype=np.int32)[ + target_size_mask + ] + if len(target_class_ids) == 0: + continue + stats.append( + ( + np.zeros((0, iou_thresholds.size), dtype=bool), + np.zeros((0, iou_thresholds.size), dtype=bool), + np.zeros((0,), dtype=np.float32), + np.zeros((0,), dtype=int), + target_class_ids, + ) + ) + + else: + if predictions.confidence is None: + raise ValueError( + "Recall metric requires `confidence` on predictions." + ) + prediction_class_ids = np.asarray( + predictions.class_id, dtype=np.int32 + ) + target_class_ids = np.asarray(targets.class_id, dtype=np.int32) + prediction_confidence = np.asarray( + predictions.confidence, dtype=np.float32 + ) + if self._metric_target == MetricTarget.BOXES: + # BOXES target never yields CompactMask; narrow for mypy. + iou = box_iou_batch( + cast(npt.NDArray[np.number], target_contents), + cast(npt.NDArray[np.number], prediction_contents), + ) + elif self._metric_target == MetricTarget.MASKS: + iou = mask_iou_batch(target_contents, prediction_contents) + elif self._metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES: + # OBB target never yields CompactMask; narrow for mypy. + iou = oriented_box_iou_batch( + cast(npt.NDArray[np.number], target_contents), + cast(npt.NDArray[np.number], prediction_contents), + ) + else: + raise ValueError( + "Unsupported metric target for IoU calculation" + ) + + # None keeps the matcher on its single-round fast path + # when no size bucket is scored. + target_scored_mask = ( + target_size_mask + if size_category != ObjectSizeCategory.ANY + else None + ) + matches, matched_target_indices = ( + _match_detection_batch_with_target_indices( + prediction_class_ids, + target_class_ids, + iou, + iou_thresholds, + target_scored_mask=target_scored_mask, + ) + ) + ignored_matches = np.zeros_like(matches, dtype=bool) + if size_category != ObjectSizeCategory.ANY: + valid_target_match = matched_target_indices >= 0 + matched_scored_target = np.zeros_like(matches, dtype=bool) + if np.any(valid_target_match): + matched_scored_target[valid_target_match] = ( + target_size_mask[ + matched_target_indices[valid_target_match] + ] + ) + prediction_scored = ( + prediction_size_mask[:, None] | matched_scored_target + ) + ignored_matches = ~prediction_scored | ( + valid_target_match & ~matched_scored_target + ) + prediction_keep = np.any(~ignored_matches, axis=1) + matches = ( + matches[prediction_keep] + & matched_scored_target[prediction_keep] + ) + ignored_matches = ignored_matches[prediction_keep] + prediction_confidence = prediction_confidence[prediction_keep] + prediction_class_ids = prediction_class_ids[prediction_keep] + target_class_ids = target_class_ids[target_size_mask] + if ( + len(prediction_class_ids) == 0 + and len(target_class_ids) == 0 + ): + continue + stats.append( + ( + matches, + ignored_matches, + prediction_confidence, + prediction_class_ids, + target_class_ids, + ) + ) + + if not stats: + return RecallResult( + metric_target=self._metric_target, + averaging_method=self.averaging_method, + recall_scores=np.zeros(iou_thresholds.shape[0]), + recall_per_class=np.zeros((0, iou_thresholds.shape[0])), + iou_thresholds=iou_thresholds, + matched_classes=np.array([], dtype=int), + small_objects=None, + medium_objects=None, + large_objects=None, + ) + + concatenated_stats = [np.concatenate(items, 0) for items in zip(*stats)] + recall_scores, recall_per_class, unique_classes = ( + self._compute_recall_for_classes(*concatenated_stats) + ) + + return RecallResult( + metric_target=self._metric_target, + averaging_method=self.averaging_method, + recall_scores=recall_scores, + recall_per_class=recall_per_class, + iou_thresholds=iou_thresholds, + matched_classes=unique_classes, + small_objects=None, + medium_objects=None, + large_objects=None, + ) + + def _compute_recall_for_classes( + self, + matches: npt.NDArray[np.bool_], + ignored_matches: npt.NDArray[np.bool_], + prediction_confidence: npt.NDArray[np.float32], + prediction_class_ids: npt.NDArray[np.int32], + true_class_ids: npt.NDArray[np.int32], + ) -> tuple[ + npt.NDArray[np.float64], + npt.NDArray[np.float64], + npt.NDArray[np.int32], + ]: + sorted_indices = np.argsort(-prediction_confidence) + matches = matches[sorted_indices] + ignored_matches = ignored_matches[sorted_indices] + prediction_class_ids = prediction_class_ids[sorted_indices] + # Classes that appear only in predictions have no ground-truth instances, so + # their recall is 0.0 rather than undefined. Including them keeps the tracked + # class set identical to Precision and F1Score and matches sklearn, which infers + # labels from the union of y_true and y_pred. + true_classes, true_counts = np.unique(true_class_ids, return_counts=True) + pred_classes = np.unique(prediction_class_ids) + # Dedupe each side first, then union1d the already-unique arrays: this skips + # union1d's internal re-sort/re-unique of the full concatenation and measured + # ~1.4x faster than np.unique(np.concatenate(...)). Deduping after the union + # (or union1d on the raw arrays) yields no speedup. + unique_classes = np.union1d(true_classes, pred_classes) + class_counts = np.zeros(unique_classes.shape[0], dtype=int) + class_counts[np.searchsorted(unique_classes, true_classes)] = true_counts + + # Shape: PxTh,P,C,C -> CxThx3 + confusion_matrix = self._compute_confusion_matrix( + matches, ignored_matches, prediction_class_ids, unique_classes, class_counts + ) + + # Shape: CxThx3 -> CxTh + recall_per_class = self._compute_recall(confusion_matrix) + + # Shape: CxTh -> Th + if self.averaging_method == AveragingMethod.MACRO: + recall_scores = np.mean(recall_per_class, axis=0) + elif self.averaging_method == AveragingMethod.MICRO: + confusion_matrix_merged = confusion_matrix.sum(0) + recall_scores = self._compute_recall(confusion_matrix_merged) + elif self.averaging_method == AveragingMethod.WEIGHTED: + class_counts = class_counts.astype(np.float32) + if class_counts.sum() == 0: + # No ground-truth support (e.g. only false-positive classes, or a + # size bucket with predictions but no targets): weighting is + # undefined, so report 0 as the empty case did before. + recall_scores = np.zeros(recall_per_class.shape[1]) + else: + recall_scores = np.average( + recall_per_class, axis=0, weights=class_counts + ) + + return recall_scores, recall_per_class, unique_classes + + @staticmethod + def _match_detection_batch( + predictions_classes: npt.NDArray[np.int32], + target_classes: npt.NDArray[np.int32], + iou: npt.NDArray[np.float32], + iou_thresholds: npt.NDArray[np.float32], + ) -> npt.NDArray[np.bool_]: + result_correct, _ = _match_detection_batch_with_target_indices( + predictions_classes, target_classes, iou, iou_thresholds + ) + return result_correct + + @staticmethod + def _compute_confusion_matrix( + sorted_matches: npt.NDArray[np.bool_], + sorted_ignored_matches: npt.NDArray[np.bool_], + sorted_prediction_class_ids: npt.NDArray[np.int32], + unique_classes: npt.NDArray[np.integer], + class_counts: npt.NDArray[np.integer], + ) -> npt.NDArray[np.float64]: + """ + Compute the confusion matrix for each class and IoU threshold. + + Assumes the matches and prediction_class_ids are sorted by confidence + in descending order. + + Args: + sorted_matches: shape (P, Th), that is True + if the prediction is a true positive at the given IoU threshold. + sorted_ignored_matches: shape (P, Th), that is True + if the prediction should not affect the given IoU threshold. + sorted_prediction_class_ids: shape (P,), containing + the class id for each prediction. + unique_classes: shape (C,), containing the unique + class ids. + class_counts: shape (C,), containing the number + of true instances for each class. + + Returns: + shape (C, Th, 3), containing the true positives, false + positives, and false negatives for each class and IoU threshold. + """ + + num_thresholds = sorted_matches.shape[1] + num_classes = unique_classes.shape[0] + + confusion_matrix: npt.NDArray[np.float64] = np.zeros( + (num_classes, num_thresholds, 3), dtype=np.float64 + ) + for class_idx, class_id in enumerate(unique_classes): + is_class = sorted_prediction_class_ids == class_id + num_true = class_counts[class_idx] + num_predictions = is_class.sum() + + if num_predictions == 0: + true_positives = np.zeros(num_thresholds) + false_positives = np.zeros(num_thresholds) + false_negatives = np.full(num_thresholds, num_true) + elif num_true == 0: + true_positives = np.zeros(num_thresholds) + false_positives = (~sorted_ignored_matches[is_class]).sum(0) + false_negatives = np.zeros(num_thresholds) + else: + true_positives = sorted_matches[is_class].sum(0) + false_positives = ( + ~sorted_matches[is_class] & ~sorted_ignored_matches[is_class] + ).sum(0) + false_negatives = num_true - true_positives + confusion_matrix[class_idx] = np.stack( + [true_positives, false_positives, false_negatives], axis=1 + ) + result: npt.NDArray[np.float64] = confusion_matrix + return result + + @staticmethod + def _compute_recall( + confusion_matrix: npt.NDArray[np.float64], + ) -> npt.NDArray[np.float64]: + """ + Broadcastable function, computing the recall from the confusion matrix. + + Args: + confusion_matrix: shape (N, ..., 3), where the last dimension + contains the true positives, false positives, and false negatives. + + Returns: + shape (N, ...), containing the recall for each element. + """ + if not confusion_matrix.shape[-1] == 3: + raise ValueError( + f"Confusion matrix must have shape (..., 3), got " + f"{confusion_matrix.shape}" + ) + true_positives = confusion_matrix[..., 0] + false_negatives = confusion_matrix[..., 2] + + denominator = true_positives + false_negatives + recall = np.divide( + true_positives, + denominator, + out=np.zeros_like(true_positives), + where=denominator != 0, + ) + + result_recall: npt.NDArray[np.float64] = recall + return result_recall + + def _detections_content( + self, detections: Detections + ) -> npt.NDArray[Any] | CompactMask: + """Return boxes, masks or oriented bounding boxes from detections. + + For the mask target this may return a + :class:`~supervision.detection.compact_mask.CompactMask` rather than a + dense boolean array when the detections carry compact masks. + """ + if self._metric_target == MetricTarget.BOXES: + return cast(npt.NDArray[Any], detections.xyxy) + if self._metric_target == MetricTarget.MASKS: + if detections.mask is not None: + # detections.mask is NDArray[bool] | CompactMask; return as-is. + return detections.mask + if len(detections) > 0: + raise ValueError( + "Recall with `MetricTarget.MASKS` requires detections to " + "include masks." + ) + return self._make_empty_content() + if self._metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES: + obb = detections.data.get(ORIENTED_BOX_COORDINATES) + if obb is not None and len(obb) > 0: + result_obb: npt.NDArray[np.float32] = np.array(obb, dtype=np.float32) + return result_obb + return self._make_empty_content() + raise ValueError(f"Invalid metric target: {self._metric_target}") + + def _make_empty_content(self) -> npt.NDArray[Any]: + if self._metric_target == MetricTarget.BOXES: + empty_boxes: npt.NDArray[np.float32] = np.empty((0, 4), dtype=np.float32) + return empty_boxes + + if self._metric_target == MetricTarget.MASKS: + empty_masks: npt.NDArray[np.bool_] = np.empty((0, 0, 0), dtype=bool) + return empty_masks + + if self._metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES: + empty_obb: npt.NDArray[np.float32] = np.empty((0, 4, 2), dtype=np.float32) + return empty_obb + + raise ValueError(f"Invalid metric target: {self._metric_target}") + + raise ValueError(f"Invalid metric target: {self._metric_target}") + + def _filter_detections_by_size( + self, detections: Detections, size_category: ObjectSizeCategory + ) -> Detections: + """Return a copy of detections with contents filtered by object size.""" + new_detections = deepcopy(detections) + if detections.is_empty() or size_category == ObjectSizeCategory.ANY: + return new_detections + + sizes = get_detection_size_category(new_detections, self._metric_target) + size_mask = sizes == size_category.value + + new_detections.xyxy = new_detections.xyxy[size_mask] + if new_detections.mask is not None: + new_detections.mask = new_detections.mask[size_mask] + if new_detections.class_id is not None: + new_detections.class_id = new_detections.class_id[size_mask] + if new_detections.confidence is not None: + new_detections.confidence = new_detections.confidence[size_mask] + if new_detections.tracker_id is not None: + new_detections.tracker_id = new_detections.tracker_id[size_mask] + if new_detections.data is not None: + for key, value in new_detections.data.items(): + new_detections.data[key] = np.array(value)[size_mask] + + return new_detections + + def _filter_predictions_and_targets_by_size( + self, + predictions_list: list[Detections], + targets_list: list[Detections], + size_category: ObjectSizeCategory, + ) -> tuple[list[Detections], list[Detections]]: + """ + Filter predictions and targets by object size category. + """ + new_predictions_list = [] + new_targets_list = [] + for predictions, targets in zip(predictions_list, targets_list): + new_predictions_list.append( + self._filter_detections_by_size(predictions, size_category) + ) + new_targets_list.append( + self._filter_detections_by_size(targets, size_category) + ) + return new_predictions_list, new_targets_list + + +@dataclass +class RecallResult: + """ + The results of the recall metric calculation. + + Defaults to `0` if no detections or targets were provided. + + Attributes: + metric_target: the type of data used for the metric - + boxes, masks or oriented bounding boxes. + averaging_method: the averaging method used to compute the + recall. Determines how the recall is aggregated across classes. + recall_at_50: the recall at IoU threshold of `0.5`. + recall_at_75: the recall at IoU threshold of `0.75`. + recall_scores: the recall scores at each IoU threshold. + Shape: `(num_iou_thresholds,)` + recall_per_class: the recall scores per class and IoU threshold. + Shape: `(num_classes, num_iou_thresholds)` + iou_thresholds: the IoU thresholds used in the calculations. + matched_classes: the class IDs present in either predictions or ground + truth. Corresponds to the rows of `recall_per_class`. Classes that + appear only in predictions (no ground-truth instances) are included; + their per-threshold recall values will be `0.0`. + small_objects: the Recall metric results + for small objects (area < 32²). + medium_objects: the Recall metric results + for medium objects (32² ≤ area < 96²). + large_objects: the Recall metric results + for large objects (area ≥ 96²). + """ + + metric_target: MetricTarget + averaging_method: AveragingMethod + + @property + def recall_at_50(self) -> float: + return float(self.recall_scores[0]) + + @property + def recall_at_75(self) -> float: + return float(self.recall_scores[5]) + + recall_scores: npt.NDArray[np.float64] + recall_per_class: npt.NDArray[np.float64] + iou_thresholds: npt.NDArray[np.float32] + matched_classes: npt.NDArray[np.int32] + + small_objects: RecallResult | None + medium_objects: RecallResult | None + large_objects: RecallResult | None + + def __str__(self) -> str: + """ + Format as a pretty string. + + Example: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> from supervision.metrics import Recall + >>> predictions = sv.Detections( + ... xyxy=np.array([[0, 0, 10, 10]]), + ... class_id=np.array([0]), + ... confidence=np.array([0.9]) + ... ) + >>> targets = sv.Detections( + ... xyxy=np.array([[0, 0, 10, 10]]), + ... class_id=np.array([0]) + ... ) + >>> recall_metric = Recall() + >>> recall_result = recall_metric.update(predictions, targets).compute() + >>> print(recall_result) # doctest: +ELLIPSIS + RecallResult: + Metric target: MetricTarget.BOXES + Averaging method: AveragingMethod.WEIGHTED + R @ 50: 1.0000 + R @ 75: 1.0000 + R @ thresh: [1. ... 1.] + IoU thresh: [0.5 0.55 ... 0.95] + Recall per class: + 0: [1. ... 1.] + ... + Medium objects: + RecallResult: + Metric target: MetricTarget.BOXES + Averaging method: AveragingMethod.WEIGHTED + R @ 50: 0.0000 + ... + + ``` + """ + out_str = ( + f"{self.__class__.__name__}:\n" + f"Metric target: {self.metric_target}\n" + f"Averaging method: {self.averaging_method}\n" + f"R @ 50: {self.recall_at_50:.4f}\n" + f"R @ 75: {self.recall_at_75:.4f}\n" + f"R @ thresh: {self.recall_scores}\n" + f"IoU thresh: {self.iou_thresholds}\n" + f"Recall per class:\n" + ) + if self.recall_per_class.size == 0: + out_str += " No results\n" + for class_id, recall_of_class in zip( + self.matched_classes, self.recall_per_class + ): + out_str += f" {class_id}: {recall_of_class}\n" + + indent = " " + if self.small_objects is not None: + indented = indent + str(self.small_objects).replace("\n", f"\n{indent}") + out_str += f"\nSmall objects:\n{indented}" + if self.medium_objects is not None: + indented = indent + str(self.medium_objects).replace("\n", f"\n{indent}") + out_str += f"\nMedium objects:\n{indented}" + if self.large_objects is not None: + indented = indent + str(self.large_objects).replace("\n", f"\n{indent}") + out_str += f"\nLarge objects:\n{indented}" + + return out_str + + def to_pandas(self) -> pd.DataFrame: + """ + Convert the result to a pandas DataFrame. + + Returns: + The result as a DataFrame. + """ + ensure_pandas_installed() + import pandas as pd + + pandas_data: dict[str, Any] = { + "R@50": self.recall_at_50, + "R@75": self.recall_at_75, + } + + if self.small_objects is not None: + small_objects_df = self.small_objects.to_pandas() + for key, value in small_objects_df.items(): + pandas_data[f"small_objects_{key}"] = value + if self.medium_objects is not None: + medium_objects_df = self.medium_objects.to_pandas() + for key, value in medium_objects_df.items(): + pandas_data[f"medium_objects_{key}"] = value + if self.large_objects is not None: + large_objects_df = self.large_objects.to_pandas() + for key, value in large_objects_df.items(): + pandas_data[f"large_objects_{key}"] = value + + return pd.DataFrame(pandas_data, index=[0]) + + def plot(self) -> None: + """ + Plot the recall results. + + ![example_plot]( + https://media.roboflow.com/supervision-docs/metrics/recall_plot_example.png + ){ align=center width="800" } + """ + from matplotlib import pyplot as plt + + labels = ["Recall@50", "Recall@75"] + values = [self.recall_at_50, self.recall_at_75] + colors = [LEGACY_COLOR_PALETTE[0]] * 2 + + if self.small_objects is not None: + small_objects = self.small_objects + labels += ["Small: R@50", "Small: R@75"] + values += [small_objects.recall_at_50, small_objects.recall_at_75] + colors += [LEGACY_COLOR_PALETTE[3]] * 2 + + if self.medium_objects is not None: + medium_objects = self.medium_objects + labels += ["Medium: R@50", "Medium: R@75"] + values += [medium_objects.recall_at_50, medium_objects.recall_at_75] + colors += [LEGACY_COLOR_PALETTE[2]] * 2 + + if self.large_objects is not None: + large_objects = self.large_objects + labels += ["Large: R@50", "Large: R@75"] + values += [large_objects.recall_at_50, large_objects.recall_at_75] + colors += [LEGACY_COLOR_PALETTE[4]] * 2 + + plt.rcParams["font.family"] = "monospace" + + _, ax = plt.subplots(figsize=(10, 6)) + ax.set_ylim(0, 1) + ax.set_ylabel("Value", fontweight="bold") + title = ( + f"Recall, by Object Size" + f"\n(target: {self.metric_target.value}," + f" averaging: {self.averaging_method.value})" + ) + ax.set_title(title, fontweight="bold") + + x_positions = range(len(labels)) + bars = ax.bar(x_positions, values, color=colors, align="center") + + ax.set_xticks(x_positions) + ax.set_xticklabels(labels, rotation=45, ha="right") + + for bar in bars: + y_value = bar.get_height() + ax.text( + bar.get_x() + bar.get_width() / 2, + y_value + 0.02, + f"{y_value:.2f}", + ha="center", + va="bottom", + ) + + plt.rcParams["font.family"] = "sans-serif" + + plt.tight_layout() + plt.show() diff --git a/.venv/lib/python3.12/site-packages/supervision/metrics/utils/__init__.py b/.venv/lib/python3.12/site-packages/supervision/metrics/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/supervision/metrics/utils/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/metrics/utils/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f7f9c9ae8c96836e9c0581a9e406866d7c15108 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/metrics/utils/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/metrics/utils/__pycache__/matching.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/metrics/utils/__pycache__/matching.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..891874ce58189a31ae1a2e6a394c4f267c52a617 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/metrics/utils/__pycache__/matching.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/metrics/utils/__pycache__/object_size.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/metrics/utils/__pycache__/object_size.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..37573b9d6252eb4fd6fb7c9f16c21157deeff1ef Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/metrics/utils/__pycache__/object_size.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/metrics/utils/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/metrics/utils/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..231e722c319dfd0b7109a426b8e829895c615c66 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/metrics/utils/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/metrics/utils/matching.py b/.venv/lib/python3.12/site-packages/supervision/metrics/utils/matching.py new file mode 100644 index 0000000000000000000000000000000000000000..394cb1e3b923752a0f0f16d14200f0078ce4e94f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/metrics/utils/matching.py @@ -0,0 +1,96 @@ +from collections.abc import Iterator + +import numpy as np +import numpy.typing as npt + + +def _greedy_match( + iou: npt.NDArray[np.float32], + matched_indices: tuple[npt.NDArray[np.intp], ...], +) -> Iterator[tuple[int, int]]: + """Yield (target_idx, pred_idx) pairs in greedy highest-IoU-first one-to-one order. + + Candidate pairs are sorted by descending IoU and assigned one-to-one: a pair + is accepted only when neither the target nor the prediction has been matched. + + Examples: + ```pycon + >>> import numpy as np + >>> iou = np.array([[1.0, 0.667], [0.333, 0.538]], dtype=np.float32) + >>> matched_indices = np.where(iou >= 0.5) + >>> list(_greedy_match(iou, matched_indices)) + [(0, 0), (1, 1)] + + ``` + """ + target_idx = matched_indices[0] + pred_idx = matched_indices[1] + iou_values = iou[matched_indices] + order = np.argsort(-iou_values, kind="stable") + matched_targets: set[int] = set() + matched_preds: set[int] = set() + for t, p in zip(target_idx[order].tolist(), pred_idx[order].tolist()): + if t not in matched_targets and p not in matched_preds: + matched_targets.add(t) + matched_preds.add(p) + yield t, p + + +def _match_detection_batch_with_target_indices( + predictions_classes: npt.NDArray[np.int32], + target_classes: npt.NDArray[np.int32], + iou: npt.NDArray[np.float32], + iou_thresholds: npt.NDArray[np.float32], + target_scored_mask: npt.NDArray[np.bool_] | None = None, +) -> tuple[npt.NDArray[np.bool_], npt.NDArray[np.int32]]: + """Match predictions to targets and retain target indices per IoU threshold. + + When ``target_scored_mask`` is provided, scored targets are matched first and + only predictions left unmatched may then match unscored (ignored) targets. + This mirrors COCO evaluation, where detections prefer non-ignored ground + truth, so an out-of-bucket target can never steal a prediction from an + in-bucket one. + + Examples: + ```pycon + >>> import numpy as np + >>> predictions_classes = np.array([0], dtype=np.int32) + >>> target_classes = np.array([0], dtype=np.int32) + >>> iou = np.array([[1.0]], dtype=np.float32) + >>> thresholds = np.array([0.5], dtype=np.float32) + >>> correct, matched = _match_detection_batch_with_target_indices( + ... predictions_classes, + ... target_classes, + ... iou, + ... thresholds, + ... ) + >>> correct.tolist(), matched.tolist() + ([[True]], [[0]]) + + ``` + """ + num_predictions = predictions_classes.shape[0] + num_iou_levels = iou_thresholds.shape[0] + correct = np.zeros((num_predictions, num_iou_levels), dtype=bool) + matched_targets = np.full((num_predictions, num_iou_levels), -1, dtype=np.int32) + correct_class = target_classes[:, None] == predictions_classes + + for i, iou_level in enumerate(iou_thresholds): + candidate_pairs = (iou >= iou_level) & correct_class + if target_scored_mask is None: + match_rounds = [candidate_pairs] + else: + match_rounds = [ + candidate_pairs & target_scored_mask[:, None], + candidate_pairs & ~target_scored_mask[:, None], + ] + + for round_pairs in match_rounds: + unmatched_predictions = matched_targets[:, i] < 0 + matched_indices = np.where(round_pairs & unmatched_predictions) + + for target_idx, prediction_idx in _greedy_match(iou, matched_indices): + correct[prediction_idx, i] = True + matched_targets[prediction_idx, i] = target_idx + + return correct, matched_targets diff --git a/.venv/lib/python3.12/site-packages/supervision/metrics/utils/object_size.py b/.venv/lib/python3.12/site-packages/supervision/metrics/utils/object_size.py new file mode 100644 index 0000000000000000000000000000000000000000..b9b7bb2a9f981f172da6cb9b7d2e683dd01ba362 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/metrics/utils/object_size.py @@ -0,0 +1,322 @@ +from __future__ import annotations + +from enum import Enum +from typing import TYPE_CHECKING, cast + +import numpy as np +import numpy.typing as npt + +from supervision.config import AREA_DATA_FIELD, ORIENTED_BOX_COORDINATES +from supervision.detection.compact_mask import CompactMask +from supervision.detection.utils.masks import count_mask_pixels +from supervision.metrics.core import MetricTarget + +if TYPE_CHECKING: + from supervision.detection.core import Detections + +SIZE_THRESHOLDS = (32**2, 96**2) + + +class ObjectSizeCategory(Enum): + """ + Enum for object size categories based on area in pixels. + + Small: area < 32^2 + Medium: 32^2 <= area < 96^2 + Large: area >= 96^2 + + Example: + ```pycon + >>> from supervision.metrics.utils.object_size import ObjectSizeCategory + >>> ObjectSizeCategory.SMALL.value + 1 + >>> ObjectSizeCategory.MEDIUM.value + 2 + >>> ObjectSizeCategory.LARGE.value + 3 + + ``` + """ + + ANY = -1 + SMALL = 1 + MEDIUM = 2 + LARGE = 3 + + +def get_object_size_category( + data: npt.NDArray[np.number] | npt.NDArray[np.bool_], + metric_target: MetricTarget, +) -> npt.NDArray[np.int_]: + """ + Get the size category of an object. Distinguish based on the metric target. + + Args: + data: The object data, shaped (N, ...). + metric_target: Determines whether boxes, masks or + oriented bounding boxes are used. + + Returns: + The size category of each object, matching + the enum values of ObjectSizeCategory. Shaped (N,). + + Example: + ```pycon + >>> import numpy as np + >>> from supervision.metrics.core import MetricTarget + >>> from supervision.metrics.utils.object_size import get_object_size_category + >>> xyxy = np.array([ + ... [0, 0, 10, 10], # 100 (Small) + ... [0, 0, 50, 50], # 2500 (Medium) + ... [0, 0, 100, 100] # 10000 (Large) + ... ]) + >>> get_object_size_category(xyxy, MetricTarget.BOXES) + array([1, 2, 3]) + + ``` + """ + if metric_target == MetricTarget.BOXES: + bbox_data = cast(npt.NDArray[np.number], data) + return get_bbox_size_category(bbox_data) + if metric_target == MetricTarget.MASKS: + mask_data = cast(npt.NDArray[np.bool_], data) + return get_mask_size_category(mask_data) + if metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES: + obb_data = cast(npt.NDArray[np.number], data) + return get_obb_size_category(obb_data) + raise ValueError("Invalid metric type") + + +def get_bbox_size_category(xyxy: npt.NDArray[np.number]) -> npt.NDArray[np.int_]: + """ + Get the size category of a bounding boxes array. + + Args: + xyxy: The bounding boxes array shaped (N, 4). + + Returns: + The size category of each bounding box, matching + the enum values of ObjectSizeCategory. Shaped (N,). + + Example: + ```pycon + >>> import numpy as np + >>> from supervision.metrics.utils.object_size import get_bbox_size_category + >>> xyxy = np.array([ + ... [0, 0, 31, 31], # 961 (Small) + ... [0, 0, 32, 32], # 1024 (Medium) + ... [0, 0, 95, 95], # 9025 (Medium) + ... [0, 0, 96, 96] # 9216 (Large) + ... ]) + >>> get_bbox_size_category(xyxy) + array([1, 2, 2, 3]) + + ``` + """ + if len(xyxy.shape) != 2 or xyxy.shape[1] != 4: + raise ValueError("Bounding boxes must be shaped (N, 4)") + + width = xyxy[:, 2] - xyxy[:, 0] + height = xyxy[:, 3] - xyxy[:, 1] + areas = width * height + + result = np.full(areas.shape, ObjectSizeCategory.ANY.value) + SM, LG = SIZE_THRESHOLDS + result[areas < SM] = ObjectSizeCategory.SMALL.value + result[(areas >= SM) & (areas < LG)] = ObjectSizeCategory.MEDIUM.value + result[areas >= LG] = ObjectSizeCategory.LARGE.value + return result + + +def get_area_size_category( + areas: npt.NDArray[np.number], +) -> npt.NDArray[np.int_]: + """Get object size categories from per-detection pixel areas. + + Args: + areas: One-dimensional pixel areas shaped (N,). + + Returns: + The size category of each area, matching the enum values of + `ObjectSizeCategory`. Shaped (N,). + + Raises: + ValueError: If `areas` is not one-dimensional. + + Example: + ```pycon + >>> import numpy as np + >>> from supervision.metrics.utils.object_size import get_area_size_category + >>> get_area_size_category(np.array([100, 2500, 10000])) + array([1, 2, 3]) + + ``` + """ + if len(areas.shape) != 1: + raise ValueError("Areas must be shaped (N,)") + + result = np.full(areas.shape, ObjectSizeCategory.ANY.value) + sm, lg = SIZE_THRESHOLDS + result[areas < sm] = ObjectSizeCategory.SMALL.value + result[(areas >= sm) & (areas < lg)] = ObjectSizeCategory.MEDIUM.value + result[areas >= lg] = ObjectSizeCategory.LARGE.value + return result + + +def get_mask_size_category( + mask: npt.NDArray[np.bool_] | CompactMask, +) -> npt.NDArray[np.int_]: + """ + Get the size category of detection masks. + + Args: + mask: The mask array shaped (N, H, W), or a + :class:`~supervision.detection.compact_mask.CompactMask`. + + Returns: + The size category of each mask, matching + the enum values of ObjectSizeCategory. Shaped (N,). + + Example: + ```pycon + >>> import numpy as np + >>> from supervision.metrics.utils.object_size import get_mask_size_category + >>> mask = np.zeros((3, 100, 100), dtype=bool) + >>> mask[0, 0:10, 0:10] = True # 100 (Small) + >>> mask[1, 0:50, 0:50] = True # 2500 (Medium) + >>> mask[2, 0:100, 0:100] = True # 10000 (Large) + >>> get_mask_size_category(mask) + array([1, 2, 3]) + + ``` + """ + if isinstance(mask, CompactMask): + areas = mask.area + else: + if len(mask.shape) != 3: + raise ValueError("Masks must be shaped (N, H, W)") + # count_mask_pixels uses np.count_nonzero (no axis), which dispatches + # to SIMD popcount over the bool buffer and is ~6x faster than the + # vectorized np.sum(mask, axis=(1, 2)). Do not "simplify" back to + # np.sum(axis=(1,2)); benchmark before reverting. dtype=np.int64 keeps + # areas consistent across platforms (Windows NumPy defaults to int32). + areas = count_mask_pixels(mask) + + result = np.full(areas.shape, ObjectSizeCategory.ANY.value) + SM, LG = SIZE_THRESHOLDS + result[areas < SM] = ObjectSizeCategory.SMALL.value + result[(areas >= SM) & (areas < LG)] = ObjectSizeCategory.MEDIUM.value + result[areas >= LG] = ObjectSizeCategory.LARGE.value + return result + + +def get_obb_size_category(xyxyxyxy: npt.NDArray[np.number]) -> npt.NDArray[np.int_]: + """ + Get the size category of a oriented bounding boxes array. + + Args: + xyxyxyxy: The bounding boxes array shaped (N, 4, 2). + + Returns: + The size category of each bounding box, matching + the enum values of ObjectSizeCategory. Shaped (N,). + + Example: + ```pycon + >>> import numpy as np + >>> from supervision.metrics.utils.object_size import get_obb_size_category + >>> obb = np.array([ + ... [[0, 0], [10, 0], [10, 10], [0, 10]], # 100 (Small) + ... [[0, 0], [50, 0], [50, 50], [0, 50]], # 2500 (Medium) + ... [[0, 0], [100, 0], [100, 100], [0, 100]] # 10000 (Large) + ... ]) + >>> get_obb_size_category(obb) + array([1, 2, 3]) + + ``` + """ + if len(xyxyxyxy.shape) != 3 or xyxyxyxy.shape[1] != 4 or xyxyxyxy.shape[2] != 2: + raise ValueError("Oriented bounding boxes must be shaped (N, 4, 2)") + + # Shoelace formula + x = xyxyxyxy[:, :, 0] + y = xyxyxyxy[:, :, 1] + x1, x2, x3, x4 = x.T + y1, y2, y3, y4 = y.T + areas = 0.5 * np.abs( + (x1 * y2 + x2 * y3 + x3 * y4 + x4 * y1) + - (x2 * y1 + x3 * y2 + x4 * y3 + x1 * y4) + ) + + result = np.full(areas.shape, ObjectSizeCategory.ANY.value) + SM, LG = SIZE_THRESHOLDS + result[areas < SM] = ObjectSizeCategory.SMALL.value + result[(areas >= SM) & (areas < LG)] = ObjectSizeCategory.MEDIUM.value + result[areas >= LG] = ObjectSizeCategory.LARGE.value + return result + + +def get_detection_size_category( + detections: Detections, metric_target: MetricTarget = MetricTarget.BOXES +) -> npt.NDArray[np.int_]: + """Get the size category of each detection. + + Explicit area metadata takes precedence for every metric target, matching + COCO-style evaluation. Geometry, mask, or oriented-box content remains the + fallback when area metadata is absent. + + Args: + detections: The detections object. + metric_target: Determines whether boxes, masks or + oriented bounding boxes are used. + + Returns: + The size category of each bounding box, matching + the enum values of ObjectSizeCategory. Shaped (N,). + + Raises: + ValueError: If area metadata is not one-dimensional or is not aligned + with the detections. + + Example: + ```pycon + >>> import numpy as np + >>> from supervision.config import AREA_DATA_FIELD + >>> from supervision.detection.core import Detections + >>> detections = Detections( + ... xyxy=np.array([[0, 0, 10, 10]], dtype=np.float32), + ... data={AREA_DATA_FIELD: np.array([2500.0])}, + ... ) + >>> get_detection_size_category(detections) + array([2]) + + ``` + """ + area_data = detections.data.get(AREA_DATA_FIELD) + if area_data is not None: + areas = np.asarray(area_data, dtype=np.float64) + if len(areas.shape) != 1 or len(areas) != len(detections): + raise ValueError( + "Detection area metadata must be shaped (N,) and aligned " + "with detections" + ) + return get_area_size_category(areas) + + if metric_target == MetricTarget.BOXES: + return get_bbox_size_category(detections.xyxy) + if metric_target == MetricTarget.MASKS: + mask = detections.mask + if mask is None: + raise ValueError("Detections mask is not available") + return get_mask_size_category(mask) + if metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES: + oriented_box_coordinates = detections.data.get(ORIENTED_BOX_COORDINATES) + if oriented_box_coordinates is None: + raise ValueError("Detections oriented bounding boxes are not available") + return get_obb_size_category( + cast( + npt.NDArray[np.number], + np.asarray(oriented_box_coordinates, dtype=np.float32), + ) + ) + raise ValueError("Invalid metric type") diff --git a/.venv/lib/python3.12/site-packages/supervision/metrics/utils/utils.py b/.venv/lib/python3.12/site-packages/supervision/metrics/utils/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a108279ead8a20e10b40bf576f713e48e294e3cf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/metrics/utils/utils.py @@ -0,0 +1,9 @@ +def ensure_pandas_installed() -> None: + try: + import pandas # noqa + except ImportError: + raise ImportError( + "`metrics` extra is required to run the function." + " Run `uv pip install 'supervision[metrics]'` or" + " `uv add supervision --extra metrics`." + ) diff --git a/.venv/lib/python3.12/site-packages/supervision/py.typed b/.venv/lib/python3.12/site-packages/supervision/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/supervision/tracker/__init__.py b/.venv/lib/python3.12/site-packages/supervision/tracker/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3aa57aa32e8ccc30a39d198bdffa577ba7915634 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/tracker/__init__.py @@ -0,0 +1,5 @@ +"""Deprecated tracker compatibility exports.""" + +from supervision.tracker.byte_tracker.core import ByteTrack + +__all__ = ["ByteTrack"] diff --git a/.venv/lib/python3.12/site-packages/supervision/tracker/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/tracker/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ff8de49c7ee769cb7e13a8aad07c408c9766538 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/tracker/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/tracker/byte_tracker/__init__.py b/.venv/lib/python3.12/site-packages/supervision/tracker/byte_tracker/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/supervision/tracker/byte_tracker/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/tracker/byte_tracker/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc8f645c60d46bc045876addf39d408aa3fcc395 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/tracker/byte_tracker/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/tracker/byte_tracker/__pycache__/core.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/tracker/byte_tracker/__pycache__/core.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cab9a57d984f7db25d80ec1ea04d864250dc8911 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/tracker/byte_tracker/__pycache__/core.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/tracker/byte_tracker/__pycache__/kalman_filter.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/tracker/byte_tracker/__pycache__/kalman_filter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8242869324e055f65588932f5474b9c23e4e0374 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/tracker/byte_tracker/__pycache__/kalman_filter.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/tracker/byte_tracker/__pycache__/matching.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/tracker/byte_tracker/__pycache__/matching.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c2c621fc2d54539862d9943703be6347427fbc0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/tracker/byte_tracker/__pycache__/matching.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/tracker/byte_tracker/__pycache__/single_object_track.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/tracker/byte_tracker/__pycache__/single_object_track.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..19957d3ed595534745e18a4b27a218b4b6104a93 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/tracker/byte_tracker/__pycache__/single_object_track.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/tracker/byte_tracker/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/tracker/byte_tracker/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..510becffc502c1cc52167e6bd2bf5917f90efc56 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/tracker/byte_tracker/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/tracker/byte_tracker/core.py b/.venv/lib/python3.12/site-packages/supervision/tracker/byte_tracker/core.py new file mode 100644 index 0000000000000000000000000000000000000000..35363e5f55edeaa0fd491841a7ce79819ee51e2b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/tracker/byte_tracker/core.py @@ -0,0 +1,417 @@ +import numpy as np +import numpy.typing as npt +from deprecate import ( # type: ignore[import-untyped,unused-ignore] + TargetMode, + deprecated_class, +) + +from supervision.detection.core import Detections +from supervision.detection.utils.iou_and_nms import box_iou_batch +from supervision.tracker.byte_tracker import matching +from supervision.tracker.byte_tracker.kalman_filter import KalmanFilter +from supervision.tracker.byte_tracker.single_object_track import STrack, TrackState +from supervision.tracker.byte_tracker.utils import IdCounter + + +def _valid_tracking_tensors( + tensors: npt.NDArray[np.float32], +) -> npt.NDArray[np.bool_]: + """Identify finite tensors with positive-width and positive-height boxes.""" + bboxes = tensors[:, :4] + widths = bboxes[:, 2] - bboxes[:, 0] + heights = bboxes[:, 3] - bboxes[:, 1] + return np.isfinite(tensors).all(axis=1) & (widths > 0) & (heights > 0) + + +@deprecated_class( + target=TargetMode.NOTIFY, + deprecated_in="0.28.0", + remove_in="0.31.0", +) +class ByteTrack: + """ + Initialize the ByteTrack object. + + !!! deprecated "Deprecated" + + `ByteTrack` is deprecated since `supervision-0.28.0` and will be removed in + `supervision-0.31.0`. Use `ByteTrackTracker` from the `trackers` package + instead (`pip install trackers`). Note: the update method is renamed from + `update_with_detections()` to `update()`. + + + + Args: + track_activation_threshold: Detection confidence threshold + for track activation. Increasing track_activation_threshold improves accuracy + and stability but might miss true detections. Decreasing it increases + completeness but risks introducing noise and instability. + lost_track_buffer: Number of frames to buffer when a track is lost. + Increasing lost_track_buffer enhances occlusion handling, significantly + reducing the likelihood of track fragmentation or disappearance caused + by brief detection gaps. + minimum_matching_threshold: Threshold for matching tracks with detections. + Decreasing minimum_matching_threshold improves accuracy but risks fragmentation. + Increasing it improves completeness but risks false positives and drift. + frame_rate: The frame rate of the video. Accepts float values (e.g. 23.976, + 29.97) for accurate lost-track-buffer calculation. + minimum_consecutive_frames: Number of consecutive frames that an object must + be tracked before it is considered a 'valid' track. + Increasing minimum_consecutive_frames prevents the creation of accidental tracks from + false detection or double detection, but risks missing shorter tracks. + """ # noqa: E501 // docs + + def __init__( + self, + track_activation_threshold: float = 0.25, + lost_track_buffer: int = 30, + minimum_matching_threshold: float = 0.8, + frame_rate: float = 30, + minimum_consecutive_frames: int = 1, + ) -> None: + self.track_activation_threshold = track_activation_threshold + self.minimum_matching_threshold = minimum_matching_threshold + + self.frame_id = 0 + self.det_thresh = self.track_activation_threshold + 0.1 + if self.det_thresh > 1.0: + self.det_thresh = self.track_activation_threshold + self.max_time_lost = int(frame_rate / 30.0 * lost_track_buffer) + self.minimum_consecutive_frames = minimum_consecutive_frames + self.kalman_filter = KalmanFilter() + self.shared_kalman = KalmanFilter() + + self.tracked_tracks: list[STrack] = [] + self.lost_tracks: list[STrack] = [] + self.removed_tracks: list[STrack] = [] + + # Warning, possible bug: If you also set internal_id to start at 1, + # all traces will be connected across objects. + self.internal_id_counter = IdCounter() + self.external_id_counter = IdCounter(start_id=1) + + def update_with_detections(self, detections: Detections) -> Detections: + """ + Updates the tracker with the provided detections and returns the updated + detection results. + + Args: + detections: The detections to pass through the tracker. + + Example: + ```python + import supervision as sv + from rfdetr import RFDETRMedium + + model = RFDETRMedium() + tracker = sv.ByteTrack() + + box_annotator = sv.BoxAnnotator() + label_annotator = sv.LabelAnnotator() + + def callback(frame: np.ndarray, index: int) -> np.ndarray: + detections = model.predict(frame[:, :, ::-1]) + detections = tracker.update_with_detections(detections) + + labels = [f"#{tracker_id}" for tracker_id in detections.tracker_id] + + annotated_frame = box_annotator.annotate( + scene=frame.copy(), detections=detections) + annotated_frame = label_annotator.annotate( + scene=annotated_frame, detections=detections, labels=labels) + return annotated_frame + + sv.process_video( + source_path="", + target_path="", + callback=callback + ) + ``` + """ + if detections.confidence is None: + raise ValueError("Detections confidence must be provided for tracking.") + + tensors = np.hstack( + ( + detections.xyxy, + detections.confidence[:, np.newaxis], + ) + ) + tracks = self.update_with_tensors(tensors=tensors) + + if len(tracks) > 0: + detection_bounding_boxes = np.asarray([det[:4] for det in tensors]) + track_bounding_boxes = np.asarray([track.tlbr for track in tracks]) + + ious = box_iou_batch(detection_bounding_boxes, track_bounding_boxes) + + iou_costs: npt.NDArray[np.float32] = 1 - ious + + matches, _, _ = matching.linear_assignment(iou_costs, 0.5) + tracked_detections = detections.select(slice(None)) + tracked_detections.tracker_id = np.full(len(detections), -1, dtype=int) + for i_detection, i_track in matches: + tracked_detections.tracker_id[i_detection] = int( + tracks[i_track].external_track_id + ) + + return tracked_detections.select(tracked_detections.tracker_id != -1) + + else: + detections = Detections.empty() + detections.tracker_id = np.array([], dtype=int) + + return detections + + def reset(self) -> None: + """ + Resets the internal state of the ByteTrack tracker. + + This method clears the tracking data, including tracked, lost, + and removed tracks, as well as resetting the frame counter. It's + particularly useful when processing multiple videos sequentially, + ensuring the tracker starts with a clean state for each new video. + """ + self.frame_id = 0 + self.internal_id_counter.reset() + self.external_id_counter.reset() + self.tracked_tracks = [] + self.lost_tracks = [] + self.removed_tracks = [] + + def update_with_tensors(self, tensors: npt.NDArray[np.float32]) -> list[STrack]: + """ + Updates the tracker with the provided tensors and returns the updated tracks. + + Args: + tensors: The new tensors to update with. + + Returns: + Updated tracks. + """ + self.frame_id += 1 + activated_starcks = [] + refind_stracks = [] + lost_stracks = [] + removed_stracks = [] + + tensors = tensors[_valid_tracking_tensors(tensors)] + scores = tensors[:, 4] + bboxes = tensors[:, :4] + + remain_inds = scores >= self.track_activation_threshold + inds_low = scores > 0.1 + inds_high = scores < self.track_activation_threshold + + inds_second = np.logical_and(inds_low, inds_high) + dets_second = bboxes[inds_second] + dets = bboxes[remain_inds] + scores_keep = scores[remain_inds] + scores_second = scores[inds_second] + + if len(dets) > 0: + """Detections""" + detections = [ + STrack( + STrack.tlbr_to_tlwh(tlbr), + score_keep, + self.minimum_consecutive_frames, + self.shared_kalman, + self.internal_id_counter, + self.external_id_counter, + ) + for (tlbr, score_keep) in zip(dets, scores_keep) + ] + else: + detections = [] + + """ Add newly detected tracklets to tracked_stracks""" + unconfirmed = [] + tracked_stracks: list[STrack] = [] + + for track in self.tracked_tracks: + if not track.is_activated: + unconfirmed.append(track) + else: + tracked_stracks.append(track) + + """ Step 2: First association, with high score detection boxes""" + strack_pool = joint_tracks(tracked_stracks, self.lost_tracks) + # Predict the current location with KF + STrack.multi_predict(strack_pool, self.shared_kalman) + dists = matching.iou_distance(strack_pool, detections) + + dists = matching.fuse_score(dists, detections) + matches, u_track, u_detection = matching.linear_assignment( + dists, thresh=self.minimum_matching_threshold + ) + + for itracked, idet in matches: + track = strack_pool[itracked] + det = detections[idet] + if track.state == TrackState.Tracked: + track.update(detections[idet], self.frame_id) + activated_starcks.append(track) + else: + track.re_activate(det, self.frame_id) + refind_stracks.append(track) + + """ Step 3: Second association, with low score detection boxes""" + # association the untrack to the low score detections + if len(dets_second) > 0: + """Detections""" + detections_second = [ + STrack( + STrack.tlbr_to_tlwh(tlbr), + score_second, + self.minimum_consecutive_frames, + self.shared_kalman, + self.internal_id_counter, + self.external_id_counter, + ) + for (tlbr, score_second) in zip(dets_second, scores_second) + ] + else: + detections_second = [] + r_tracked_stracks = [ + strack_pool[i] + for i in u_track + if strack_pool[i].state == TrackState.Tracked + ] + dists = matching.iou_distance(r_tracked_stracks, detections_second) + matches, u_track, _u_detection_second = matching.linear_assignment( + dists, thresh=0.5 + ) + for itracked, idet in matches: + track = r_tracked_stracks[itracked] + det = detections_second[idet] + if track.state == TrackState.Tracked: + track.update(det, self.frame_id) + activated_starcks.append(track) + else: + track.re_activate(det, self.frame_id) + refind_stracks.append(track) + + for it in u_track: + track = r_tracked_stracks[it] + if not track.state == TrackState.Lost: + track.state = TrackState.Lost + lost_stracks.append(track) + + """Deal with unconfirmed tracks, usually tracks with only one beginning frame""" + detections = [detections[i] for i in u_detection] + dists = matching.iou_distance(unconfirmed, detections) + + dists = matching.fuse_score(dists, detections) + matches, u_unconfirmed, u_detection = matching.linear_assignment( + dists, thresh=0.7 + ) + for itracked, idet in matches: + unconfirmed[itracked].update(detections[idet], self.frame_id) + activated_starcks.append(unconfirmed[itracked]) + for it in u_unconfirmed: + track = unconfirmed[it] + track.state = TrackState.Removed + removed_stracks.append(track) + + """ Step 4: Init new stracks""" + for inew in u_detection: + track = detections[inew] + if track.score < self.det_thresh: + continue + track.activate(self.kalman_filter, self.frame_id) + activated_starcks.append(track) + """ Step 5: Update state""" + for track in self.lost_tracks: + if self.frame_id - track.frame_id > self.max_time_lost: + track.state = TrackState.Removed + removed_stracks.append(track) + + self.tracked_tracks = [ + t for t in self.tracked_tracks if t.state == TrackState.Tracked + ] + self.tracked_tracks = joint_tracks(self.tracked_tracks, activated_starcks) + self.tracked_tracks = joint_tracks(self.tracked_tracks, refind_stracks) + self.lost_tracks = sub_tracks(self.lost_tracks, self.tracked_tracks) + self.lost_tracks.extend(lost_stracks) + self.lost_tracks = sub_tracks(self.lost_tracks, self.removed_tracks) + self.removed_tracks = removed_stracks + self.tracked_tracks, self.lost_tracks = remove_duplicate_tracks( + self.tracked_tracks, self.lost_tracks + ) + output_stracks = [track for track in self.tracked_tracks if track.is_activated] + + return output_stracks + + +def joint_tracks( + track_list_a: list[STrack], track_list_b: list[STrack] +) -> list[STrack]: + """ + Joins two lists of tracks, ensuring that the resulting list does not + contain tracks with duplicate internal_track_id values. + + Args: + track_list_a: First list of tracks. + track_list_b: Second list of tracks. + + Returns: + Combined list of tracks from track_list_a and track_list_b + without duplicate internal_track_id values. + """ + seen_track_ids = set() + result = [] + + for track in track_list_a + track_list_b: + if track.internal_track_id not in seen_track_ids: + seen_track_ids.add(track.internal_track_id) + result.append(track) + + return result + + +def sub_tracks(track_list_a: list[STrack], track_list_b: list[STrack]) -> list[STrack]: + """ + Returns a list of tracks from track_list_a after removing any tracks + that share the same internal_track_id with tracks in track_list_b. + + Args: + track_list_a: List of tracks. + track_list_b: List of tracks to be subtracted from track_list_a. + Returns: + List of remaining tracks from track_list_a after subtraction. + """ + tracks = {track.internal_track_id: track for track in track_list_a} + track_ids_b = {track.internal_track_id for track in track_list_b} + + for track_id in track_ids_b: + tracks.pop(track_id, None) + + return list(tracks.values()) + + +def remove_duplicate_tracks( + tracks_a: list[STrack], tracks_b: list[STrack] +) -> tuple[list[STrack], list[STrack]]: + pairwise_distance = matching.iou_distance(tracks_a, tracks_b) + matching_pairs = np.where(pairwise_distance < 0.05) + + duplicates_a, duplicates_b = set(), set() + for track_index_a, track_index_b in zip(*matching_pairs): + time_a = tracks_a[track_index_a].frame_id - tracks_a[track_index_a].start_frame + time_b = tracks_b[track_index_b].frame_id - tracks_b[track_index_b].start_frame + if time_a > time_b: + duplicates_b.add(track_index_b) + else: + duplicates_a.add(track_index_a) + + result_a = [ + track for index, track in enumerate(tracks_a) if index not in duplicates_a + ] + result_b = [ + track for index, track in enumerate(tracks_b) if index not in duplicates_b + ] + + return result_a, result_b diff --git a/.venv/lib/python3.12/site-packages/supervision/tracker/byte_tracker/kalman_filter.py b/.venv/lib/python3.12/site-packages/supervision/tracker/byte_tracker/kalman_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..0d5cbeb936d4daabb76b2734505e398bd817120f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/tracker/byte_tracker/kalman_filter.py @@ -0,0 +1,191 @@ +import numpy as np +import numpy.typing as npt +import scipy.linalg + + +class KalmanFilter: + """ + A simple Kalman filter for tracking bounding boxes in image space. + + The 8-dimensional state space is (x, y, a, h, vx, vy, va, vh), where + (x, y) is the bounding box center, a is the aspect ratio (w/h), h is + the height, and their respective velocities. + + Object motion follows a constant velocity model. The bounding box location + (x, y, a, h) is taken as direct observation of the state space (linear + observation model). + """ + + def __init__(self) -> None: + ndim, dt = 4, 1.0 + + self._motion_mat: npt.NDArray[np.float64] = np.eye(2 * ndim, 2 * ndim) + for i in range(ndim): + self._motion_mat[i, ndim + i] = dt + self._update_mat: npt.NDArray[np.float64] = np.eye(ndim, 2 * ndim) + + self._std_weight_position: float = 1.0 / 20 + self._std_weight_velocity: float = 1.0 / 160 + + def initiate( + self, measurement: npt.NDArray[np.float32] + ) -> tuple[npt.NDArray[np.float32], npt.NDArray[np.float32]]: + """ + Create track from unassociated measurement. + + Args: + measurement: The initial measurement vector. + + Returns: + The mean vector and covariance matrix of the new track. + """ + mean_pos = measurement + mean_vel = np.zeros_like(mean_pos) + mean = np.r_[mean_pos, mean_vel] + + std = [ + 2 * self._std_weight_position * measurement[3], + 2 * self._std_weight_position * measurement[3], + 1e-2, + 2 * self._std_weight_position * measurement[3], + 10 * self._std_weight_velocity * measurement[3], + 10 * self._std_weight_velocity * measurement[3], + 1e-5, + 10 * self._std_weight_velocity * measurement[3], + ] + covariance = np.diag(np.square(std)) + return mean, covariance + + def predict( + self, mean: npt.NDArray[np.float32], covariance: npt.NDArray[np.float32] + ) -> tuple[npt.NDArray[np.float32], npt.NDArray[np.float32]]: + """ + Run Kalman filter prediction step. + + Args: + mean: The object state mean at the previous time step. + covariance: The object state covariance at the previous time step. + + Returns: + The mean vector and covariance matrix of the predicted state. + """ + std_pos = [ + self._std_weight_position * mean[3], + self._std_weight_position * mean[3], + 1e-2, + self._std_weight_position * mean[3], + ] + std_vel = [ + self._std_weight_velocity * mean[3], + self._std_weight_velocity * mean[3], + 1e-5, + self._std_weight_velocity * mean[3], + ] + motion_cov = np.diag(np.square(np.r_[std_pos, std_vel])) + + mean = np.dot(mean, self._motion_mat.T) + covariance = ( + np.linalg.multi_dot((self._motion_mat, covariance, self._motion_mat.T)) + + motion_cov + ) + + return mean, covariance + + def project( + self, mean: npt.NDArray[np.float32], covariance: npt.NDArray[np.float32] + ) -> tuple[npt.NDArray[np.float32], npt.NDArray[np.float32]]: + """ + Project state distribution to measurement space. + + Args: + mean: The state's mean vector. + covariance: The state's covariance matrix. + + Returns: + The projected mean and covariance matrix of the given state estimate. + """ + std = [ + self._std_weight_position * mean[3], + self._std_weight_position * mean[3], + 1e-1, + self._std_weight_position * mean[3], + ] + innovation_cov = np.diag(np.square(std)) + + mean = np.dot(self._update_mat, mean) + covariance = np.linalg.multi_dot( + (self._update_mat, covariance, self._update_mat.T) + ) + return mean, covariance + innovation_cov + + def multi_predict( + self, mean: npt.NDArray[np.float32], covariance: npt.NDArray[np.float32] + ) -> tuple[npt.NDArray[np.float32], npt.NDArray[np.float32]]: + """ + Run Kalman filter prediction step (Vectorized version). + Args: + mean: The object state means at the previous time step. + covariance: The object state covariances at the previous time step. + + Returns: + The mean vector and covariance matrix of the predicted state. + """ + std_pos = [ + self._std_weight_position * mean[:, 3], + self._std_weight_position * mean[:, 3], + 1e-2 * np.ones_like(mean[:, 3]), + self._std_weight_position * mean[:, 3], + ] + std_vel = [ + self._std_weight_velocity * mean[:, 3], + self._std_weight_velocity * mean[:, 3], + 1e-5 * np.ones_like(mean[:, 3]), + self._std_weight_velocity * mean[:, 3], + ] + sqr = np.square(np.r_[std_pos, std_vel]).T + + motion_cov_list: list[npt.NDArray[np.float32]] = [] + for i in range(len(mean)): + motion_cov_list.append(np.diag(sqr[i])) + motion_cov = np.asarray(motion_cov_list) + + mean = np.dot(mean, self._motion_mat.T) + left = np.dot(self._motion_mat, covariance).transpose((1, 0, 2)) + covariance = np.dot(left, self._motion_mat.T) + motion_cov + + return mean, covariance + + def update( + self, + mean: npt.NDArray[np.float32], + covariance: npt.NDArray[np.float32], + measurement: npt.NDArray[np.float32], + ) -> tuple[npt.NDArray[np.float32], npt.NDArray[np.float32]]: + """ + Run Kalman filter correction step. + + Args: + mean: The predicted state's mean vector. + covariance: The state's covariance matrix. + measurement: The measurement vector. + + Returns: + The measurement-corrected state distribution. + """ + projected_mean, projected_cov = self.project(mean, covariance) + + chol_factor, lower = scipy.linalg.cho_factor( + projected_cov, lower=True, check_finite=False + ) + kalman_gain = scipy.linalg.cho_solve( + (chol_factor, lower), + np.dot(covariance, self._update_mat.T).T, + check_finite=False, + ).T + innovation = measurement - projected_mean + + new_mean = mean + np.dot(innovation, kalman_gain.T) + new_covariance = covariance - np.linalg.multi_dot( + (kalman_gain, projected_cov, kalman_gain.T) + ) + return new_mean, new_covariance diff --git a/.venv/lib/python3.12/site-packages/supervision/tracker/byte_tracker/matching.py b/.venv/lib/python3.12/site-packages/supervision/tracker/byte_tracker/matching.py new file mode 100644 index 0000000000000000000000000000000000000000..b32871b7725a68bbae862acb5ae2407d2d848326 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/tracker/byte_tracker/matching.py @@ -0,0 +1,79 @@ +from typing import cast + +import numpy as np +import numpy.typing as npt +from scipy.optimize import linear_sum_assignment + +from supervision.detection.utils.iou_and_nms import box_iou_batch +from supervision.tracker.byte_tracker.single_object_track import STrack + + +def indices_to_matches( + cost_matrix: npt.NDArray[np.float32], indices: npt.NDArray[np.int_], thresh: float +) -> tuple[npt.NDArray[np.int_], tuple[int, ...], tuple[int, ...]]: + matched_cost = cost_matrix[tuple(zip(*indices))] + matched_mask = matched_cost <= thresh + + matches = indices[matched_mask] + unmatched_a = tuple(set(range(cost_matrix.shape[0])) - set(matches[:, 0])) + unmatched_b = tuple(set(range(cost_matrix.shape[1])) - set(matches[:, 1])) + return matches, unmatched_a, unmatched_b + + +def linear_assignment( + cost_matrix: npt.NDArray[np.float32], thresh: float +) -> tuple[npt.NDArray[np.int_], tuple[int, ...], tuple[int, ...]]: + """Match rows and columns without mutating the caller-owned cost matrix.""" + if cost_matrix.size == 0: + return ( + np.empty((0, 2), dtype=int), + tuple(range(cost_matrix.shape[0])), + tuple(range(cost_matrix.shape[1])), + ) + + assignment_cost_matrix = cost_matrix.copy() + assignment_cost_matrix[assignment_cost_matrix > thresh] = thresh + 1e-4 + row_ind, col_ind = linear_sum_assignment(assignment_cost_matrix) + indices = np.column_stack((row_ind, col_ind)) + + return indices_to_matches(cost_matrix, indices, thresh) + + +def iou_distance( + atracks: list[STrack] | list[npt.NDArray[np.float32]], + btracks: list[STrack] | list[npt.NDArray[np.float32]], +) -> npt.NDArray[np.float32]: + if (len(atracks) > 0 and isinstance(atracks[0], np.ndarray)) or ( + len(btracks) > 0 and isinstance(btracks[0], np.ndarray) + ): + atlbrs = cast(list[npt.NDArray[np.float32]], atracks) + btlbrs = cast(list[npt.NDArray[np.float32]], btracks) + else: + atlbrs = [track.tlbr for track in cast(list[STrack], atracks)] + btlbrs = [track.tlbr for track in cast(list[STrack], btracks)] + + if len(atlbrs) == 0 or len(btlbrs) == 0: + return cast( + npt.NDArray[np.float32], + np.empty((len(atlbrs), len(btlbrs)), dtype=np.float32), + ) + + ious = box_iou_batch( + np.asarray(atlbrs, dtype=np.float32), + np.asarray(btlbrs, dtype=np.float32), + ) + cost_matrix = np.asarray(1 - ious, dtype=np.float32) + return cost_matrix + + +def fuse_score( + cost_matrix: npt.NDArray[np.float32], stracks: list[STrack] +) -> npt.NDArray[np.float32]: + if cost_matrix.size == 0: + return cost_matrix + iou_sim = 1 - cost_matrix + det_scores = np.array([strack.score for strack in stracks], dtype=np.float32) + det_scores = np.expand_dims(det_scores, axis=0).repeat(cost_matrix.shape[0], axis=0) + fuse_sim = iou_sim * det_scores + fuse_cost = np.asarray(1 - fuse_sim, dtype=np.float32) + return fuse_cost diff --git a/.venv/lib/python3.12/site-packages/supervision/tracker/byte_tracker/single_object_track.py b/.venv/lib/python3.12/site-packages/supervision/tracker/byte_tracker/single_object_track.py new file mode 100644 index 0000000000000000000000000000000000000000..5d540db1b50f8b615e44015f8e68b6e4b74ef990 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/tracker/byte_tracker/single_object_track.py @@ -0,0 +1,186 @@ +from __future__ import annotations + +from enum import Enum +from typing import cast + +import numpy as np +import numpy.typing as npt + +from supervision.tracker.byte_tracker.kalman_filter import KalmanFilter +from supervision.tracker.byte_tracker.utils import IdCounter + + +class TrackState(Enum): + New = 0 + Tracked = 1 + Lost = 2 + Removed = 3 + + +class STrack: + def __init__( + self, + tlwh: npt.NDArray[np.float32], + score: float, + minimum_consecutive_frames: int, + shared_kalman: KalmanFilter, + internal_id_counter: IdCounter, + external_id_counter: IdCounter, + ): + self.state = TrackState.New + self.is_activated = False + self.start_frame = 0 + self.frame_id = 0 + + self._tlwh = np.asarray(tlwh, dtype=np.float32) + self.kalman_filter: KalmanFilter | None = None + self.shared_kalman = shared_kalman + self.mean: npt.NDArray[np.float32] | None = None + self.covariance: npt.NDArray[np.float32] | None = None + self.is_activated = False + + self.score: float = score + self.tracklet_len = 0 + + self.minimum_consecutive_frames = minimum_consecutive_frames + + self.internal_id_counter = internal_id_counter + self.external_id_counter = external_id_counter + self.internal_track_id = self.internal_id_counter.NO_ID + self.external_track_id = self.external_id_counter.NO_ID + + def predict(self) -> None: + assert self.mean is not None + assert self.covariance is not None + assert self.kalman_filter is not None + mean_state = self.mean.copy() + if self.state != TrackState.Tracked: + mean_state[7] = 0 + self.mean, self.covariance = self.kalman_filter.predict( + mean_state, self.covariance + ) + + @staticmethod + def multi_predict(stracks: list[STrack], shared_kalman: KalmanFilter) -> None: + if len(stracks) > 0: + multi_mean_states = [] + multi_covariance = [] + for i, st in enumerate(stracks): + assert st.mean is not None + assert st.covariance is not None + multi_mean_states.append(st.mean.copy()) + multi_covariance.append(st.covariance) + if st.state != TrackState.Tracked: + multi_mean_states[i][7] = 0 + + predicted_mean, predicted_covariance = shared_kalman.multi_predict( + np.asarray(multi_mean_states), np.asarray(multi_covariance) + ) + for i, (mean, cov) in enumerate(zip(predicted_mean, predicted_covariance)): + stracks[i].mean = mean + stracks[i].covariance = cov + + def activate(self, kalman_filter: KalmanFilter, frame_id: int) -> None: + """Start a new tracklet after its first detection.""" + self.kalman_filter = kalman_filter + self.internal_track_id = self.internal_id_counter.new_id() + self.mean, self.covariance = self.kalman_filter.initiate( + self.tlwh_to_xyah(self._tlwh) + ) + + self.tracklet_len = 1 + self.state = TrackState.Tracked + if frame_id == 1 and self.tracklet_len >= self.minimum_consecutive_frames: + self.is_activated = True + self.external_track_id = self.external_id_counter.new_id() + + self.frame_id = frame_id + self.start_frame = frame_id + + def re_activate(self, new_track: STrack, frame_id: int) -> None: + assert self.kalman_filter is not None + assert self.mean is not None + assert self.covariance is not None + self.mean, self.covariance = self.kalman_filter.update( + self.mean, self.covariance, self.tlwh_to_xyah(new_track.tlwh) + ) + self.tracklet_len = 0 + self.state = TrackState.Tracked + + self.frame_id = frame_id + self.score = new_track.score + + def update(self, new_track: STrack, frame_id: int) -> None: + """ + Update a matched track. + + Args: + new_track: The new track data. + frame_id: The current frame ID. + """ + assert self.kalman_filter is not None + assert self.mean is not None + assert self.covariance is not None + self.frame_id = frame_id + self.tracklet_len += 1 + + new_tlwh = new_track.tlwh + self.mean, self.covariance = self.kalman_filter.update( + self.mean, self.covariance, self.tlwh_to_xyah(new_tlwh) + ) + self.state = TrackState.Tracked + if self.tracklet_len >= self.minimum_consecutive_frames: + self.is_activated = True + if self.external_track_id == self.external_id_counter.NO_ID: + self.external_track_id = self.external_id_counter.new_id() + + self.score = new_track.score + + @property + def tlwh(self) -> npt.NDArray[np.float32]: + """Get current position in bounding box format `(top left x, top left y, + width, height)`. + """ + if self.mean is None: + return cast(npt.NDArray[np.float32], self._tlwh.copy()) + ret = self.mean[:4].copy() + ret[2] *= ret[3] + ret[:2] -= ret[2:] / 2 + return cast(npt.NDArray[np.float32], ret) + + @property + def tlbr(self) -> npt.NDArray[np.float32]: + """Convert bounding box to format `(min x, min y, max x, max y)`, i.e., + `(top left, bottom right)`. + """ + ret = self.tlwh.copy() + ret[2:] += ret[:2] + return cast(npt.NDArray[np.float32], ret) + + @staticmethod + def tlwh_to_xyah(tlwh: npt.NDArray[np.float32]) -> npt.NDArray[np.float32]: + """Convert bounding box to format `(center x, center y, aspect ratio, + height)`, where the aspect ratio is `width / height`. + """ + ret = np.asarray(tlwh).copy() + ret[:2] += ret[2:] / 2 + ret[2] /= ret[3] + return cast(npt.NDArray[np.float32], ret) + + def to_xyah(self) -> npt.NDArray[np.float32]: + return self.tlwh_to_xyah(self.tlwh) + + @staticmethod + def tlbr_to_tlwh(tlbr: npt.NDArray[np.float32]) -> npt.NDArray[np.float32]: + ret = np.asarray(tlbr).copy() + ret[2:] -= ret[:2] + return cast(npt.NDArray[np.float32], ret) + + @staticmethod + def tlwh_to_tlbr(tlwh: npt.NDArray[np.float32]) -> npt.NDArray[np.float32]: + ret = np.asarray(tlwh).copy() + ret[2:] += ret[:2] + return cast(npt.NDArray[np.float32], ret) + + def __repr__(self) -> str: + return f"OT_{self.internal_track_id}_({self.start_frame}-{self.frame_id})" diff --git a/.venv/lib/python3.12/site-packages/supervision/tracker/byte_tracker/utils.py b/.venv/lib/python3.12/site-packages/supervision/tracker/byte_tracker/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4e1c1c297af00dd3ce7db499e4f7a76107bd0fc1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/tracker/byte_tracker/utils.py @@ -0,0 +1,34 @@ +class IdCounter: + def __init__(self, start_id: int = 0) -> None: + """ + Initialize the ID counter. + + Args: + start_id: The starting integer for the counter. + + Raises: + ValueError: If start_id is less than or equal to -1. + """ + self.start_id = start_id + if self.start_id <= self.NO_ID: + raise ValueError(f"start_id must be greater than {self.NO_ID}") + self.reset() + + def reset(self) -> None: + """Reset the counter to the initial start_id.""" + self._id = self.start_id + + def new_id(self) -> int: + """ + Get the current ID and increment the counter. + + Returns: + The newly assigned ID. + """ + returned_id = self._id + self._id += 1 + return returned_id + + @property + def NO_ID(self) -> int: + return -1 diff --git a/.venv/lib/python3.12/site-packages/supervision/utils/__init__.py b/.venv/lib/python3.12/site-packages/supervision/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/supervision/utils/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/utils/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..07638b180f4d960d287b3fed87458c74317ac8ce Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/utils/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/utils/__pycache__/conversion.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/utils/__pycache__/conversion.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05c9d8cee2d4ff0067bd7dae1a8193723a4a00f9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/utils/__pycache__/conversion.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/utils/__pycache__/file.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/utils/__pycache__/file.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b701edbca1d6a566d939ac6bba0197af4c772f6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/utils/__pycache__/file.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/utils/__pycache__/image.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/utils/__pycache__/image.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf28db44e018aa3783ce7de41ff17b2253c2de7c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/utils/__pycache__/image.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/utils/__pycache__/image_window.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/utils/__pycache__/image_window.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00002dc9a752cf0e22af21508aac495f3a4b71d5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/utils/__pycache__/image_window.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/utils/__pycache__/internal.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/utils/__pycache__/internal.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..089f8d247f876a097c0b43464ffbbcde59edba5a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/utils/__pycache__/internal.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/utils/__pycache__/iterables.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/utils/__pycache__/iterables.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b642e9f12022b39bf476dfe608e380065ac4a74 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/utils/__pycache__/iterables.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/utils/__pycache__/logger.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/utils/__pycache__/logger.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6171be06eec73acec334a7e619f4e3e6fcc1535 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/utils/__pycache__/logger.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/utils/__pycache__/notebook.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/utils/__pycache__/notebook.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5b55d8ef07f00e39da49929b0d0043cee30a5e4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/utils/__pycache__/notebook.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/utils/__pycache__/video.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/utils/__pycache__/video.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51420bc26c359660480839da4ca0f7225deafb1f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/utils/__pycache__/video.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/supervision/utils/conversion.py b/.venv/lib/python3.12/site-packages/supervision/utils/conversion.py new file mode 100644 index 0000000000000000000000000000000000000000..30b51999569d68d66afa9eccbd46966118647b0d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/utils/conversion.py @@ -0,0 +1,236 @@ +import functools +from collections.abc import Callable +from typing import Any, TypeVar, cast + +import numpy as np +import numpy.typing as npt +from deprecate import deprecated, void # type: ignore[import-untyped,unused-ignore] +from PIL import Image + +from supervision import _cv2 as cv2 +from supervision.draw.base import ImageType + +F = TypeVar("F", bound=Callable[..., Any]) + + +def ensure_cv2_image_for_class_method( + annotate_func: F, +) -> F: + """ + Decorates `BaseAnnotator.annotate` implementations, converts scene to + an image type used internally by the annotators, converts back when annotation + is complete. + + Assumes the annotators modify the scene in-place. + + Raises: + TypeError: If `scene` is not a `numpy.ndarray` or `PIL.Image.Image`. + """ + + @functools.wraps(annotate_func) + def wrapper(self: Any, scene: ImageType, *args: Any, **kwargs: Any) -> Any: + if isinstance(scene, np.ndarray): + return annotate_func(self, scene, *args, **kwargs) + + if isinstance(scene, Image.Image): + scene_np = pillow_to_cv2(scene) + annotated_np = annotate_func(self, scene_np, *args, **kwargs) + scene.paste(cv2_to_pillow(annotated_np)) + return scene + + raise TypeError(f"Unsupported image type: {type(scene)}") + + return cast(F, wrapper) + + +@deprecated( # type: ignore[untyped-decorator] + target=ensure_cv2_image_for_class_method, + deprecated_in="0.27.0", + remove_in="0.31.0", +) +def ensure_cv2_image_for_annotation( + annotate_func: F, +) -> F: + return cast(F, void(annotate_func)) + + +def ensure_cv2_image_for_standalone_function( + image_processing_fun: F, +) -> F: + """ + Decorates image processing functions that accept np.ndarray, converting `image` to + np.ndarray, converts back when processing is complete. + + Assumes the annotators do NOT modify the scene in-place. + + Raises: + TypeError: If `image` is not a `numpy.ndarray` or `PIL.Image.Image`. + """ + + @functools.wraps(image_processing_fun) + def wrapper(image: ImageType, *args: Any, **kwargs: Any) -> Any: + if isinstance(image, np.ndarray): + return image_processing_fun(image, *args, **kwargs) + + if isinstance(image, Image.Image): + scene = pillow_to_cv2(image) + annotated = image_processing_fun(scene, *args, **kwargs) + return cv2_to_pillow(annotated) + + raise TypeError(f"Unsupported image type: {type(image)}") + + return cast(F, wrapper) + + +def ensure_pil_image_for_class_method( + annotate_func: F, +) -> F: + """ + Decorates image processing functions that accept np.ndarray, converting `image` to + PIL image, converts back when processing is complete. + + Assumes the annotators modify the scene in-place. + + Raises: + TypeError: If `scene` is not a `numpy.ndarray` or `PIL.Image.Image`. + """ + + @functools.wraps(annotate_func) + def wrapper(self: Any, scene: ImageType, *args: Any, **kwargs: Any) -> Any: + if isinstance(scene, np.ndarray): + scene_pil = cv2_to_pillow(scene) + annotated_pil = annotate_func(self, scene_pil, *args, **kwargs) + np.copyto(scene, pillow_to_cv2(annotated_pil)) + return scene + + if isinstance(scene, Image.Image): + return cast(ImageType, annotate_func(self, scene, *args, **kwargs)) + + raise TypeError(f"Unsupported image type: {type(scene)}") + + return cast(F, wrapper) + + +@deprecated( # type: ignore[untyped-decorator] + target=ensure_pil_image_for_class_method, + deprecated_in="0.27.0", + remove_in="0.31.0", +) +def ensure_pil_image_for_annotation( + annotate_func: F, +) -> F: + return cast(F, void(annotate_func)) + + +@deprecated( # type: ignore[untyped-decorator] + target=ensure_cv2_image_for_standalone_function, + deprecated_in="0.27.0", + remove_in="0.31.0", +) +def ensure_cv2_image_for_processing( + image_processing_fun: F, +) -> F: + return cast(F, void(image_processing_fun)) + + +def images_to_cv2( + images: list[npt.NDArray[np.uint8] | Image.Image], +) -> list[npt.NDArray[np.uint8]]: + """ + Converts images provided either as Pillow images or OpenCV + images into OpenCV format. + + Args: + images: Images to be converted + + Returns: + List of input images in OpenCV format + (with order preserved). + + """ + result: list[npt.NDArray[np.uint8]] = [] + for image in images: + if isinstance(image, Image.Image): + result.append(pillow_to_cv2(image)) + else: + result.append(image) + return result + + +def pillow_to_cv2(image: Image.Image) -> npt.NDArray[np.uint8]: + """ + Converts Pillow image into OpenCV image, handling RGB -> BGR + conversion. Palette images are first expanded to RGB so palette indices are + resolved to their actual colors. RGBA images are converted to BGR, matching + OpenCV by dropping the alpha channel. + + Args: + image: Pillow image in RGB, RGBA, grayscale, or palette mode. + + Returns: + Input image converted to OpenCV format. + + Examples: + ```pycon + >>> from PIL import Image + >>> from supervision.utils.conversion import pillow_to_cv2 + >>> image = Image.new("RGB", (10, 10), color=(255, 0, 0)) + >>> scene = pillow_to_cv2(image) + >>> scene.shape + (10, 10, 3) + >>> scene[0, 0].tolist() + [0, 0, 255] + + ``` + """ + if image.mode == "P": + image = image.convert("RGB") + + scene = np.array(image) + if scene.ndim == 2: + return cast(npt.NDArray[np.uint8], scene.astype(np.uint8, copy=False)) + scene = cv2.cvtColor(scene, cv2.COLOR_RGB2BGR) + # cvtColor already returns uint8 here, so astype is a no-op other than the + # full-image copy it forces; copy=False keeps the dtype guard without it. + return cast(npt.NDArray[np.uint8], scene.astype(np.uint8, copy=False)) + + +def cv2_to_pillow(image: npt.NDArray[np.uint8]) -> Image.Image: + """ + Converts an OpenCV image into a Pillow image, reordering channels from + OpenCV's BGR(A) convention to Pillow's RGB(A). + + Args: + image: OpenCV image. Accepted shapes: + - `(H, W)` — grayscale, passed through unchanged. + - `(H, W, 3)` — BGR, converted to RGB. + - `(H, W, 4)` — BGRA, converted to RGBA. + + Returns: + Input image converted to Pillow format. + + Raises: + ValueError: If `image` is not 2-D or 3-D with 3 or 4 channels. + + Examples: + ```pycon + >>> import numpy as np + >>> from supervision.utils.conversion import cv2_to_pillow + >>> scene = np.zeros((10, 10, 3), dtype=np.uint8) + >>> scene[:, :, 2] = 255 + >>> image = cv2_to_pillow(scene) + >>> image.size + (10, 10) + >>> image.getpixel((0, 0)) + (255, 0, 0) + + ``` + """ + if image.ndim == 2: + return Image.fromarray(np.ascontiguousarray(image)) + if image.ndim == 3 and image.shape[2] == 3: + rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) + return Image.fromarray(rgb_image) + if image.ndim == 3 and image.shape[2] == 4: + return Image.fromarray(np.ascontiguousarray(image[..., [2, 1, 0, 3]])) + raise ValueError(f"Expected shape (H,W), (H,W,3), or (H,W,4), got {image.shape}.") diff --git a/.venv/lib/python3.12/site-packages/supervision/utils/file.py b/.venv/lib/python3.12/site-packages/supervision/utils/file.py new file mode 100644 index 0000000000000000000000000000000000000000..311d9186f786805d6b492f01bd6fb26e906c569d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/utils/file.py @@ -0,0 +1,308 @@ +import json +import os +import tempfile +import urllib.parse +from pathlib import Path +from shutil import copyfileobj +from typing import Any + +import numpy as np +import requests +import yaml + +SUPERVISION_CACHE_DIR = Path(tempfile.gettempdir()) / "supervision" + + +def _normalize_http_url(url: str) -> str: + """ + Validate and normalize an HTTP(S) URL. + + Args: + url: URL to validate. + + Returns: + Normalized URL string. + + Raises: + ValueError: If the URL is invalid or uses an unsupported scheme. + """ + try: + original_parsed_url = urllib.parse.urlparse(url) + if "\\" in original_parsed_url.netloc: + raise ValueError("URL authority contains a backslash") + + prepared_request = requests.Request(method="GET", url=url).prepare() + prepared_url = prepared_request.url + if prepared_url is None: + raise ValueError("prepared URL is empty") + + parsed_url = urllib.parse.urlparse(prepared_url) + except (requests.RequestException, ValueError) as error: + raise ValueError(f"Invalid URL {url!r}: {error}") from error + + if parsed_url.scheme not in {"http", "https"}: + raise ValueError( + f"Unsupported URL scheme {parsed_url.scheme!r} in {url!r}. " + "Only HTTP and HTTPS URLs are supported." + ) + if parsed_url.hostname is None: + raise ValueError(f"Invalid URL {url!r}: no host supplied.") + + return prepared_url + + +def _download_to_file( + url: str, target: Path, *, timeout: float = 30.0, stream: bool = False +) -> None: + """ + Download `url` to `target` atomically using a temporary file and `os.replace`. + + Args: + url: HTTP(S) URL to download. + target: Destination file path. Parent directories are created as needed. + timeout: Request timeout in seconds. Defaults to `30.0`. + stream: If `True`, stream the response to disk in chunks and display a + progress bar. If `False`, buffer the response in memory before + writing. Defaults to `False`. + + Raises: + requests.RequestException: If the request fails or returns an error status. + """ + response = requests.get(url, stream=stream, allow_redirects=True, timeout=timeout) + try: + response.raise_for_status() + target.parent.mkdir(parents=True, exist_ok=True) + with tempfile.NamedTemporaryFile( + delete=False, dir=target.parent, suffix=target.suffix + ) as file: + temp_path = Path(file.name) + try: + if stream: + from tqdm.auto import tqdm + + file_size = int(response.headers.get("Content-Length", 0)) + with tqdm.wrapattr( + response.raw, "read", total=file_size, desc="", colour="#a351fb" + ) as raw_response: + copyfileobj(raw_response, file) + else: + file.write(response.content) + except BaseException: + file.close() + temp_path.unlink(missing_ok=True) + raise + finally: + response.close() + + try: + os.replace(temp_path, target) + finally: + temp_path.unlink(missing_ok=True) + + +class NumpyJsonEncoder(json.JSONEncoder): + def default(self, obj: Any) -> Any: + if isinstance(obj, np.integer): + return int(obj) + if isinstance(obj, np.floating): + return float(obj) + if isinstance(obj, np.ndarray): + return obj.tolist() + return super().default(obj) + + +def list_files_with_extensions( + directory: str | Path, extensions: list[str] | None = None +) -> list[Path]: + """ + List files in a directory with specified extensions or + all files if no extensions are provided. + + Args: + directory: The directory path as a string or Path object. + extensions: A list of file extensions to filter. Extensions may be + supplied with or without a leading dot (e.g. ``'jpg'`` and + ``'.jpg'`` are equivalent). Matching is case-insensitive. + Multi-part extensions are supported (e.g. ``'tar.gz'``). Pass + ``None`` (default) to list all files; pass an empty list to + return no files. + + Returns: + A list of Path objects for the matching files. + + Examples: + ```pycon + >>> import supervision as sv + >>> from pathlib import Path + >>> import tempfile + >>> # Keep a reference to the directory object + >>> tmp_dir_obj = tempfile.TemporaryDirectory() + >>> tmpdir = tmp_dir_obj.name + >>> # Create test files + >>> (Path(tmpdir) / "test1.txt").touch() + >>> (Path(tmpdir) / "test2.md").touch() + >>> (Path(tmpdir) / "test3.py").touch() + >>> # List all files in the directory + >>> files = sv.list_files_with_extensions(directory=tmpdir) + >>> len(files) + 3 + >>> # Leading dot accepted; matching is case-insensitive + >>> files = sv.list_files_with_extensions( + ... directory=tmpdir, extensions=['.txt', 'md']) + >>> len(files) + 2 + + ``` + """ + + directory = Path(directory) + files_with_extensions: list[Path] = [] + + if extensions is not None: + candidates = [p for p in directory.glob("*") if p.is_file()] + path_index: dict[Path, set[str]] = {} + for path in candidates: + suffixes = [suffix.lower().lstrip(".") for suffix in path.suffixes] + path_index[path] = { + ".".join(suffixes[index:]) for index in range(len(suffixes)) + } + seen_paths: set[Path] = set() + for ext in extensions: + normalized_extension = ext.lower().lstrip(".") + if not normalized_extension: + continue + for path, path_extensions in path_index.items(): + if path not in seen_paths and normalized_extension in path_extensions: + files_with_extensions.append(path) + seen_paths.add(path) + else: + files_with_extensions.extend(p for p in directory.glob("*") if p.is_file()) + + return files_with_extensions + + +def read_txt_file(file_path: str | Path, skip_empty: bool = False) -> list[str]: + """ + Read a text file and return a list of strings without newline characters. + Optionally skip empty lines. + + Args: + file_path: The file path as a string or Path object. + skip_empty: If True, skip lines that are empty or contain only + whitespace. Default is False. + + Returns: + A list of strings representing the lines in the text file. + + Examples: + ```pycon + >>> import tempfile + >>> from pathlib import Path + >>> from supervision.utils.file import read_txt_file, save_text_file + >>> with tempfile.TemporaryDirectory() as tmpdir: + ... file_path = Path(tmpdir) / "test.txt" + ... save_text_file(["line1", " ", "line3"], file_path) + ... print(read_txt_file(file_path)) + ... print(read_txt_file(file_path, skip_empty=True)) + ['line1', ' ', 'line3'] + ['line1', 'line3'] + + ``` + """ + with open(str(file_path)) as file: + if skip_empty: + lines = [line.rstrip("\n") for line in file if line.strip()] + else: + lines = [line.rstrip("\n") for line in file] + + return lines + + +def save_text_file(lines: list[str], file_path: str | Path) -> None: + """ + Write a list of strings to a text file, each string on a new line. + + Args: + lines: The list of strings to be written to the file. + file_path: The file path as a string or Path object. + """ + with open(str(file_path), "w") as file: + for line in lines: + file.write(line + "\n") + + +def read_json_file(file_path: str | Path) -> dict[str, Any]: + """ + Read a json file and return a dict. + + The file is decoded as UTF-8, the encoding JSON files are written in, whatever + the platform's default encoding is. + + Args: + file_path: The file path as a string or Path object. + + Returns: + A dict of annotations information + + Examples: + ```pycon + >>> import tempfile + >>> from pathlib import Path + >>> from supervision.utils.file import read_json_file, save_json_file + >>> data = {"key": "value", "list": [1, 2, 3]} + >>> with tempfile.TemporaryDirectory() as tmpdir: + ... file_path = Path(tmpdir) / "test.json" + ... save_json_file(data, file_path) + ... print(read_json_file(file_path)) + {'key': 'value', 'list': [1, 2, 3]} + + ``` + """ + with open(str(file_path), encoding="utf-8") as file: + data = json.load(file) + return data # type: ignore + + +def save_json_file( + data: dict[str, Any], file_path: str | Path, indent: int = 3 +) -> None: + """ + Write a dict to a json file. + + Args: + data: dict with unique keys and value as pair. + file_path: The file path as a string or Path object. + indent: + """ + with open(str(file_path), "w") as fp: + json.dump(data, fp, cls=NumpyJsonEncoder, indent=indent) + + +def read_yaml_file(file_path: str | Path) -> dict[str, Any]: + """ + Read a yaml file and return a dict. + + The file is decoded as UTF-8, whatever the platform's default encoding is. + + Args: + file_path: The file path as a string or Path object. + + Returns: + A dict of content information + """ + with open(str(file_path), encoding="utf-8") as file: + data = yaml.safe_load(file) + return data # type: ignore + + +def save_yaml_file(data: dict[str, Any], file_path: str | Path) -> None: + """ + Save a dict to a yaml file. + + Args: + data: dict with unique keys and value as pair. + file_path: The file path as a string or Path object. + """ + + with open(str(file_path), "w") as outfile: + yaml.dump(data, outfile, sort_keys=False, default_flow_style=None) diff --git a/.venv/lib/python3.12/site-packages/supervision/utils/image.py b/.venv/lib/python3.12/site-packages/supervision/utils/image.py new file mode 100644 index 0000000000000000000000000000000000000000..1bc0ef1d759c036bf6af92e8f280b428ded6ae0f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/utils/image.py @@ -0,0 +1,1129 @@ +from __future__ import annotations + +import itertools +import math +import os +import shutil +import tempfile +import urllib.parse +from collections.abc import Callable +from functools import partial +from hashlib import md5 +from pathlib import Path +from types import TracebackType +from typing import Literal, cast + +import numpy as np +import numpy.typing as npt +from deprecate import ( # type: ignore[import-untyped,unused-ignore] + TargetMode, + deprecated, +) +from PIL import Image + +from supervision import _cv2 as cv2 +from supervision.draw.base import ImageType +from supervision.draw.color import Color, unify_to_bgr +from supervision.draw.utils import calculate_optimal_text_scale, draw_text +from supervision.geometry.core import Point +from supervision.utils.conversion import ( + cv2_to_pillow, + ensure_cv2_image_for_standalone_function, + images_to_cv2, +) +from supervision.utils.file import ( + SUPERVISION_CACHE_DIR, + _download_to_file, + _normalize_http_url, +) +from supervision.utils.iterables import create_batches, fill + +RelativePosition = Literal["top", "bottom"] + +MAX_COLUMNS_FOR_SINGLE_ROW_GRID = 3 + +DEFAULT_IMAGE_URL_CACHE_DIR = SUPERVISION_CACHE_DIR / "image-url" + + +def _get_image_url_cache_path(value: str, cache_dir: str | Path | None) -> Path: + """ + Build the cache file path for a URL: `/`. + """ + cache_root = ( + DEFAULT_IMAGE_URL_CACHE_DIR + if cache_dir is None + else Path(cache_dir).expanduser().resolve() + ) + url_path = urllib.parse.urlparse(value).path + suffix = Path(url_path).suffix or ".image" + url_hash = md5(value.encode("utf-8"), usedforsecurity=False).hexdigest() + return cache_root / f"{url_hash}{suffix}" + + +def _decode_image_from_bytes( + value: bytes, + cv_imread_flags: int, +) -> npt.NDArray[np.uint8]: + """ + Decode raw image bytes into an OpenCV image, raising on undecodable data. + """ + image = cv2.imdecode( + np.frombuffer(value, dtype=np.uint8), + cv_imread_flags, + ) + if image is None: + raise ValueError("Data pointed by URL could not be decoded into image.") + + return cast(npt.NDArray[np.uint8], image) + + +def load_image_from_url( + value: str, + cv_imread_flags: int = cv2.IMREAD_COLOR, + timeout: float = 30.0, + use_cache: bool = True, + cache_dir: str | Path | None = None, + force_reload: bool = False, +) -> npt.NDArray[np.uint8]: + """ + Load an image from a URL as an OpenCV image. + + Args: + value: HTTP(S) URL of the image. + cv_imread_flags: OpenCV image read flag passed to `cv2.imdecode`. + Defaults to `cv2.IMREAD_COLOR`. + timeout: Request timeout in seconds. Defaults to `30.0`. + use_cache: If `True`, cache downloaded image bytes locally and reuse them + on repeated calls. Defaults to `True`. + cache_dir: Directory where downloaded image bytes are cached. If `None`, + uses the system temporary directory. Defaults to `None`. + force_reload: If `True`, re-download the image and refresh the cache. + Defaults to `False`. + + Returns: + Image as a NumPy array in the format selected by `cv_imread_flags`. + + Raises: + ValueError: If the URL is invalid or the downloaded bytes cannot be decoded. + requests.RequestException: If the request fails or returns an error status. + + Examples: + ```python + import supervision as sv + + image = sv.load_image_from_url( + "https://media.roboflow.com/quickstart/dog.jpeg" + ) + image.shape + + ``` + """ + prepared_url = _normalize_http_url(url=value) + if not use_cache: + with tempfile.TemporaryDirectory() as temp_dir: + temp_target = Path(temp_dir) / "image" + _download_to_file(prepared_url, temp_target, timeout=timeout) + return _decode_image_from_bytes( + value=temp_target.read_bytes(), + cv_imread_flags=cv_imread_flags, + ) + + cache_path = _get_image_url_cache_path( + value=prepared_url, + cache_dir=cache_dir, + ) + if cache_path.exists() and not force_reload: + try: + return _decode_image_from_bytes( + value=cache_path.read_bytes(), + cv_imread_flags=cv_imread_flags, + ) + except ValueError: + cache_path.unlink(missing_ok=True) + + _download_to_file(prepared_url, cache_path, timeout=timeout) + try: + return _decode_image_from_bytes( + value=cache_path.read_bytes(), + cv_imread_flags=cv_imread_flags, + ) + except ValueError: + cache_path.unlink(missing_ok=True) + raise + + +@ensure_cv2_image_for_standalone_function +def crop_image( + image: ImageType, + xyxy: npt.NDArray[np.number] | list[int] | tuple[int, int, int, int], +) -> ImageType: + """ + Crop image based on bounding box coordinates. + + Args: + image: The image to crop. + xyxy: + Bounding box coordinates in `(x_min, y_min, x_max, y_max)` format. + + Returns: + Cropped image matching input + type. + + Note: + Coordinates are rounded to integers and clipped to the image bounds + before slicing. This keeps NumPy and Pillow inputs aligned and avoids + negative-index wrap-around on NumPy arrays. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> image = np.zeros((1080, 1920, 3), dtype=np.uint8) + >>> image.shape + (1080, 1920, 3) + >>> xyxy = (400, 400, 800, 800) + >>> cropped_image = sv.crop_image(image=image, xyxy=xyxy) + >>> cropped_image.shape + (400, 400, 3) + + ``` + + ```pycon + >>> image = np.zeros((1920, 1080), dtype=np.uint8) + >>> image.shape + (1920, 1080) + >>> xyxy = (400, 400, 800, 800) + >>> cropped_image = sv.crop_image(image=image, xyxy=xyxy) + >>> cropped_image.shape + (400, 400) + + ``` + + ![crop-image](https://media.roboflow.com/supervision-docs/supervision-docs-crop-image-2.png){ align=center width="1000" } + """ # noqa E501 // docs + xyxy_arr = np.asarray(xyxy, dtype=np.float64).round().astype(np.int32) + x_min, y_min, x_max, y_max = xyxy_arr.flatten() + + if isinstance(image, np.ndarray): + height, width = image.shape[:2] + x_min = int(np.clip(x_min, 0, width)) + y_min = int(np.clip(y_min, 0, height)) + x_max = int(np.clip(x_max, 0, width)) + y_max = int(np.clip(y_max, 0, height)) + return image[y_min:y_max, x_min:x_max] + + if isinstance(image, Image.Image): + width, height = image.size + x_min = int(np.clip(x_min, 0, width)) + y_min = int(np.clip(y_min, 0, height)) + x_max = int(np.clip(x_max, 0, width)) + y_max = int(np.clip(y_max, 0, height)) + return image.crop((float(x_min), float(y_min), float(x_max), float(y_max))) + + raise TypeError( + f"`image` must be a numpy.ndarray or PIL.Image.Image. Received {type(image)}" + ) + + +@ensure_cv2_image_for_standalone_function +def scale_image(image: ImageType, scale_factor: float) -> ImageType: + """ + Scale image by given factor. Scale factor > 1.0 zooms in, < 1.0 zooms out. + + Args: + image: The image to scale. + scale_factor: Factor by which to scale the image. + + Returns: + Scaled image matching input + type. + + Raises: + TypeError: If `image` is not a `numpy.ndarray` or `PIL.Image.Image`. + ValueError: If scale factor is non-positive. + + Note: + Each axis keeps at least one pixel, so a factor small enough to round an + axis of a small image down to zero returns a one-pixel-wide or + one-pixel-tall image rather than raising. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> image = np.zeros((1080, 1920, 3), dtype=np.uint8) + >>> image.shape + (1080, 1920, 3) + >>> scaled_image = sv.scale_image(image=image, scale_factor=0.5) + >>> scaled_image.shape + (540, 960, 3) + + ``` + + ```pycon + >>> image = np.zeros((1920, 1080), dtype=np.uint8) + >>> image.shape + (1920, 1080) + >>> scaled_image = sv.scale_image(image=image, scale_factor=0.5) + >>> scaled_image.shape + (960, 540) + + ``` + + ![scale-image](https://media.roboflow.com/supervision-docs/supervision-docs-scale-image-2.png){ align=center width="1000" } + """ # noqa E501 // docs + if scale_factor <= 0: + raise ValueError("Scale factor must be positive.") + + width_old, height_old = image.shape[1], image.shape[0] + # A small factor on a small image truncates an axis to zero, and `cv2.resize` + # answers a zero-sized target with a bare assertion. One pixel is the smallest + # image that still exists, so clamp there instead. + width_new = max(1, int(width_old * scale_factor)) + height_new = max(1, int(height_old * scale_factor)) + return cast( + npt.NDArray[np.uint8], + cv2.resize(image, (width_new, height_new), interpolation=cv2.INTER_LINEAR), + ) + + +@ensure_cv2_image_for_standalone_function +def resize_image( + image: ImageType, + resolution_wh: tuple[int, int], + keep_aspect_ratio: bool = False, +) -> ImageType: + """ + Resize image to specified resolution. Can optionally maintain aspect ratio. + + Args: + image: The image to resize. + resolution_wh: Target resolution as `(width, height)`. + keep_aspect_ratio: Flag to maintain original aspect ratio. + Defaults to `False`. + + Returns: + Resized image matching input + type. + + Raises: + TypeError: If `image` is not a `numpy.ndarray` or `PIL.Image.Image`. + + Note: + With `keep_aspect_ratio=True` the fitted axis keeps at least one pixel, so + an aspect ratio too extreme to fit the target box returns a one-pixel-wide + or one-pixel-tall image rather than raising. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> image = np.zeros((1080, 1920, 3), dtype=np.uint8) + >>> image.shape + (1080, 1920, 3) + >>> resized_image = sv.resize_image( + ... image=image, resolution_wh=(1000, 1000), keep_aspect_ratio=True + ... ) + >>> resized_image.shape + (562, 1000, 3) + + ``` + + ```pycon + >>> image = np.zeros((1920, 1080), dtype=np.uint8) + >>> image.shape + (1920, 1080) + >>> resized_image = sv.resize_image( + ... image=image, resolution_wh=(1000, 1000), keep_aspect_ratio=True + ... ) + >>> resized_image.shape + (1000, 562) + + ``` + + ![resize-image](https://media.roboflow.com/supervision-docs/supervision-docs-resize-image-2.png){ align=center width="1000" } + """ # noqa E501 // docs + if keep_aspect_ratio: + image_ratio = image.shape[1] / image.shape[0] + target_ratio = resolution_wh[0] / resolution_wh[1] + # The fitted axis truncates to zero once the aspect ratio outgrows the target + # box, and `cv2.resize` answers a zero-sized target with a bare assertion. + # One pixel is the smallest image that still exists, so clamp there instead. + if image_ratio >= target_ratio: + width_new = resolution_wh[0] + height_new = max(1, int(resolution_wh[0] / image_ratio)) + else: + height_new = resolution_wh[1] + width_new = max(1, int(resolution_wh[1] * image_ratio)) + else: + width_new, height_new = resolution_wh + + return cast( + npt.NDArray[np.uint8], + cv2.resize(image, (width_new, height_new), interpolation=cv2.INTER_LINEAR), + ) + + +@ensure_cv2_image_for_standalone_function +def letterbox_image( + image: ImageType, + resolution_wh: tuple[int, int], + color: tuple[int, int, int] | Color = Color.BLACK, +) -> ImageType: + """ + Resize image and pad with color to achieve desired resolution while + maintaining aspect ratio. + + Args: + image: The image to resize and pad. Accepts BGR arrays of shape + ``(H, W, 3)``, BGRA arrays of shape ``(H, W, 4)``, grayscale + arrays of shape ``(H, W)``, or a PIL ``Image``. + resolution_wh: Target resolution as `(width, height)`. + color: Padding color. If tuple, should be in BGR format. + Defaults to `Color.BLACK`. + + Returns: + Letterboxed image matching input type. + + Raises: + TypeError: If `image` is not a `numpy.ndarray` or `PIL.Image.Image`. + + Note: + For BGRA inputs, the alpha channel in the padding region is set to + 0 (fully transparent). Grayscale inputs receive scalar padding + from ``color[0]``. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> image = np.zeros((1080, 1920, 3), dtype=np.uint8) + >>> image.shape + (1080, 1920, 3) + >>> letterboxed_image = sv.letterbox_image( + ... image=image, resolution_wh=(1000, 1000) + ... ) + >>> letterboxed_image.shape + (1000, 1000, 3) + >>> gray = np.zeros((4, 6), dtype=np.uint8) + >>> sv.letterbox_image(image=gray, resolution_wh=(10, 10)).shape + (10, 10) + + ``` + + ![letterbox-image](https://media.roboflow.com/supervision-docs/supervision-docs-letterbox-image-2.png){ align=center width="1000" } + """ # noqa E501 // docs + color = unify_to_bgr(color=color) + resized_image = resize_image( + image=image, resolution_wh=resolution_wh, keep_aspect_ratio=True + ) + height_new, width_new = resized_image.shape[:2] + padding_top = (resolution_wh[1] - height_new) // 2 + padding_bottom = resolution_wh[1] - height_new - padding_top + padding_left = (resolution_wh[0] - width_new) // 2 + padding_right = resolution_wh[0] - width_new - padding_left + image_with_borders = cast( + npt.NDArray[np.uint8], + cv2.copyMakeBorder( + resized_image, + padding_top, + padding_bottom, + padding_left, + padding_right, + cv2.BORDER_CONSTANT, + value=color, + ), + ) + + return image_with_borders + + +@deprecated( # type: ignore[untyped-decorator] + target=TargetMode.NOTIFY, + deprecated_in="0.27.0", + remove_in="0.31.0", +) +def overlay_image( + image: npt.NDArray[np.uint8], + overlay: npt.NDArray[np.uint8], + anchor: tuple[int, int], +) -> npt.NDArray[np.uint8]: + """ + Deprecated since 0.27.0; removal in 0.31.0. Use `_overlay_image` for + internal callers, or avoid calling `overlay_image` directly in external code. + + Overlay image onto scene at specified anchor point. Handles cases where + overlay position is partially or completely outside scene bounds. + + Args: + image: Background scene with shape `(height, width, 3)`. + overlay: Image to overlay with shape + `(height, width, 3)` or `(height, width, 4)`. + anchor: Coordinates `(x, y)` where top-left corner + of overlay will be placed. + + Returns: + Scene with overlay applied, shape `(height, width, 3)`. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> image = np.zeros((1000, 1000, 3), dtype=np.uint8) + >>> overlay = np.zeros((400, 400, 3), dtype=np.uint8) + >>> overlay[:] = (0, 255, 0) # Green overlay + >>> result_image = sv.overlay_image( + ... image=image, overlay=overlay, anchor=(200, 400) + ... ) + >>> result_image.shape + (1000, 1000, 3) + + ``` + """ + return _overlay_image(image=image, overlay=overlay, anchor=anchor) + + +def _overlay_image( + image: npt.NDArray[np.uint8], + overlay: npt.NDArray[np.uint8], + anchor: tuple[int, int], +) -> npt.NDArray[np.uint8]: + """Overlay `overlay` onto `image` at `anchor`, clipping to scene bounds. + + Non-deprecated internal implementation backing the public `overlay_image`. + Kept separate so library-internal callers do not emit a deprecation warning. + + Args: + image: Background BGR array of shape ``(H, W, 3)``. Modified in place + and returned. + overlay: Overlay array of shape ``(H, W, 3)`` or ``(H, W, 4)``; channel + 4, when present, is treated as alpha. + anchor: ``(x, y)`` pixel position of the overlay top-left corner. May + be negative (partial off-screen placement is clipped). + + Returns: + The ``image`` array with the overlay applied. + """ + scene_height, scene_width = image.shape[:2] + image_height, image_width = overlay.shape[:2] + anchor_x, anchor_y = anchor + + is_out_horizontally = anchor_x + image_width <= 0 or anchor_x >= scene_width + is_out_vertically = anchor_y + image_height <= 0 or anchor_y >= scene_height + + if is_out_horizontally or is_out_vertically: + return image + + x_min = max(anchor_x, 0) + y_min = max(anchor_y, 0) + x_max = min(scene_width, anchor_x + image_width) + y_max = min(scene_height, anchor_y + image_height) + + crop_x_min = max(-anchor_x, 0) + crop_y_min = max(-anchor_y, 0) + crop_x_max = image_width - max((anchor_x + image_width) - scene_width, 0) + crop_y_max = image_height - max((anchor_y + image_height) - scene_height, 0) + + if overlay.shape[2] == 4: + b, g, r, alpha = cv2.split( + overlay[crop_y_min:crop_y_max, crop_x_min:crop_x_max] + ) + alpha_f32 = alpha[:, :, None].astype(np.float32) / 255.0 + overlay_color = cv2.merge((b, g, r)).astype(np.float32) + + roi = image[y_min:y_max, x_min:x_max].astype(np.float32) + blended = roi * (1 - alpha_f32) + overlay_color * alpha_f32 + image[y_min:y_max, x_min:x_max] = np.clip(blended, 0, 255).astype(np.uint8) + else: + image[y_min:y_max, x_min:x_max] = overlay[ + crop_y_min:crop_y_max, crop_x_min:crop_x_max + ] + + return image + + +@ensure_cv2_image_for_standalone_function +def tint_image( + image: ImageType, + color: Color = Color.BLACK, + opacity: float = 0.5, +) -> ImageType: + """ + Tint image with solid color overlay at specified opacity. + + Args: + image: The image to tint. + color: Overlay tint color. Defaults to `Color.BLACK`. + opacity: Blend ratio between overlay and image (0.0-1.0). + Defaults to `0.5`. + + Returns: + Tinted image matching input + type. The input image is left unchanged. + + Raises: + TypeError: If `image` is not a `numpy.ndarray` or `PIL.Image.Image`. + ValueError: If opacity is outside range [0.0, 1.0]. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> image = np.zeros((100, 100, 3), dtype=np.uint8) + >>> tinted_image = sv.tint_image( + ... image=image, color=sv.Color.ROBOFLOW, opacity=0.5 + ... ) + >>> tinted_image.shape + (100, 100, 3) + >>> int(image.max()) + 0 + + ``` + + ![tint-image](https://media.roboflow.com/supervision-docs/supervision-docs-tint-image-2.png){ align=center width="1000" } + """ # noqa E501 // docs + if not 0.0 <= opacity <= 1.0: + raise ValueError("opacity must be between 0.0 and 1.0") + + overlay = np.full_like(image, fill_value=color.as_bgr(), dtype=image.dtype) + # No `dst`: let the blend allocate its own buffer. Passing `image` there wrote + # the tint back into the caller's array for a NumPy input, while a Pillow input + # was shielded by the ndarray conversion the decorator makes. + return cast( + npt.NDArray[np.uint8], + cv2.addWeighted( + src1=overlay, alpha=opacity, src2=image, beta=1 - opacity, gamma=0 + ), + ) + + +@ensure_cv2_image_for_standalone_function +def grayscale_image(image: ImageType) -> ImageType: + """ + Convert image to 3-channel grayscale. Luminance channel is broadcast to + all three channels for compatibility with color-based drawing helpers. + + Args: + image: The image to convert to + grayscale. + + Returns: + 3-channel grayscale image + matching input type. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> image = np.ones((100, 100, 3), dtype=np.uint8) * 128 + >>> grayscale_image = sv.grayscale_image(image=image) + >>> grayscale_image.shape + (100, 100, 3) + + ``` + + ![grayscale-image](https://media.roboflow.com/supervision-docs/supervision-docs-grayscale-image-2.png){ align=center width="1000" } + """ # noqa E501 // docs + assert isinstance(image, np.ndarray) + grayscaled = cast(npt.NDArray[np.uint8], cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)) + return cast(npt.NDArray[np.uint8], cv2.cvtColor(grayscaled, cv2.COLOR_GRAY2BGR)) + + +def get_image_resolution_wh(image: ImageType) -> tuple[int, int]: + """ + Get image width and height as a tuple `(width, height)` for various image formats. + + Supports both `numpy.ndarray` images (with shape `(H, W, ...)`) and + `PIL.Image.Image` inputs. + + Args: + image: Input image. + + Returns: + Image resolution as `(width, height)`. + + Raises: + ValueError: If a `numpy.ndarray` image has fewer than 2 dimensions. + TypeError: If `image` is not a supported type (`numpy.ndarray` or + `PIL.Image.Image`). + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> image = np.zeros((1080, 1920, 3), dtype=np.uint8) + >>> sv.get_image_resolution_wh(image) + (1920, 1080) + + ``` + """ + if isinstance(image, np.ndarray): + if image.ndim < 2: + raise ValueError( + "NumPy image must have at least 2 dimensions (H, W, ...). " + f"Received shape: {image.shape}" + ) + height, width = image.shape[:2] + return int(width), int(height) + + if isinstance(image, Image.Image): + width, height = image.size + return int(width), int(height) + + raise TypeError( + "`image` must be a numpy.ndarray or PIL.Image.Image. " + f"Received type: {type(image)}" + ) + + +class ImageSink: + """ + Save sequential images into a directory through a context manager. + + `ImageSink` creates the target directory on entry and writes each image + using `save_image`, incrementing the image name pattern after every save. + """ + + def __init__( + self, + target_dir_path: str, + overwrite: bool = False, + image_name_pattern: str = "image_{:05d}.png", + ) -> None: + """ + Initialize context manager for saving images to directory. + + Args: + target_dir_path: Target directory path where images will be + saved. + overwrite: Whether to overwrite existing directory. + Defaults to `False`. + image_name_pattern: File name pattern for saved images. + Defaults to `"image_{:05d}.png"`. + + Examples: + ```pycon + >>> import numpy as np + >>> import supervision as sv + >>> import tempfile + >>> import os + >>> with tempfile.TemporaryDirectory() as tmpdir: + ... image = np.zeros((100, 100, 3), dtype=np.uint8) + ... with sv.ImageSink(target_dir_path=tmpdir, overwrite=True) as sink: + ... sink.save_image(image=image) + ... sink.save_image(image=image) + ... files = sorted(os.listdir(tmpdir)) + ... len(files) + 2 + + ``` + """ + self.target_dir_path = target_dir_path + self.overwrite = overwrite + self.image_name_pattern = image_name_pattern + self.image_count = 0 + + def __enter__(self) -> ImageSink: + if os.path.exists(self.target_dir_path): + if self.overwrite: + shutil.rmtree(self.target_dir_path) + os.makedirs(self.target_dir_path) + else: + os.makedirs(self.target_dir_path) + + return self + + def save_image( + self, image: npt.NDArray[np.uint8], image_name: str | None = None + ) -> None: + """ + Save image to target directory with optional custom filename. + + Args: + image: Image to save with shape `(height, width, 3)` + in BGR format. + image_name: Custom filename for saved image. If + `None`, generates name using `image_name_pattern`. Defaults to + `None`. + + Raises: + OSError: If `cv2.imwrite` cannot write the image to disk. + """ + if image_name is None: + image_name = self.image_name_pattern.format(self.image_count) + + image_path = os.path.join(self.target_dir_path, image_name) + if not cv2.imwrite(image_path, image): + raise OSError(f"Failed to save image to path: {image_path}") + self.image_count += 1 + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + exc_traceback: TracebackType | None, + ) -> None: + pass + + +@deprecated( # type: ignore[untyped-decorator] + target=TargetMode.NOTIFY, + deprecated_in="0.27.0", + remove_in="0.31.0", +) +def create_tiles( + images: list[ImageType], + grid_size: tuple[int | None, int | None] | None = None, + single_tile_size: tuple[int, int] | None = None, + tile_scaling: Literal["min", "max", "avg"] = "avg", + tile_padding_color: tuple[int, int, int] | Color = Color.from_hex("#D9D9D9"), + tile_margin: int = 10, + tile_margin_color: tuple[int, int, int] | Color = Color.from_hex("#BFBEBD"), + return_type: Literal["auto", "cv2", "pillow"] = "auto", + titles: list[str | None] | None = None, + titles_anchors: Point | list[Point | None] | None = None, + titles_color: tuple[int, int, int] | Color = Color.from_hex("#262523"), + titles_scale: float | None = None, + titles_thickness: int = 1, + titles_padding: int = 10, + titles_text_font: int = cv2.FONT_HERSHEY_SIMPLEX, + titles_background_color: tuple[int, int, int] | Color = Color.from_hex("#D9D9D9"), + default_title_placement: RelativePosition = "top", +) -> ImageType: + """ + Creates tiles mosaic from input images, automating grid placement and + converting images to common resolution maintaining aspect ratio. It is + also possible to render text titles on tiles, using optional set of + parameters specifying text drawing (see parameters description). + + Automated grid placement will try to maintain square shape of grid + (with size being the nearest integer square root of #images), up to two exceptions: + * if there are up to 3 images - images will be displayed in single row + * if square-grid placement causes last row to be empty - number of rows is trimmed + until last row has at least one image + + Args: + images: Images to create tiles. Elements can be either np.ndarray or + PIL.Image, and a common representation will be agreed by the + function. + grid_size: Expected grid size in format (n_rows, n_cols). If not + given, automated grid placement will be applied. One may also + provide only one out of two elements of the tuple - then grid + will be created with either n_rows or n_cols fixed, leaving the + other dimension to be adjusted by the number of images. + single_tile_size: Size of a single tile element provided in + (width, height) format. If not given, size of tile will be + automatically calculated based on `tile_scaling`. + tile_scaling: Strategy used to calculate tile size when + `single_tile_size` is not given, using the min / max / avg size + of images provided in `images`. + tile_padding_color: Color to be used in the image letterbox procedure + while standardizing tile sizes. If a tuple is provided, it should + be in BGR order. + tile_margin: Size of margin between tiles, in pixels. + tile_margin_color: Color of the tile margin. If a tuple is provided, + it should be in BGR order. + return_type: Format of the returned image. One may choose a specific + format ("cv2" or "pillow") to enforce conversion. "auto" mode + takes a majority vote between types of elements in `images`, + resolving draws in favour of OpenCV format. "auto" can be safely + used when all input images are of the same type. + titles: Optional titles to be added to tiles. Elements of that list + may be empty - then a specific tile, in the order presented in + `images`, will not be filled with a title. It is possible to + provide a list of titles shorter than `images` - then remaining + titles will be assumed empty. + titles_anchors: Anchor points for titles. It is possible to specify + an anchor either globally or for specific tiles, following the + order of `images`. If not given, either globally or for a + specific element of the list, it will be calculated + automatically based on `default_title_placement`. + titles_color: Color of the title text. If a tuple is provided, it + should be in BGR order. + titles_scale: Scale of titles. If not provided, the value will be + calculated using `calculate_optimal_text_scale(...)`. + titles_thickness: Thickness of title text. + titles_padding: Size of title padding. + titles_text_font: Font used to render titles. Must be an integer + constant representing an OpenCV font. + (See docs: https://docs.opencv.org/4.x/d6/d6e/group__imgproc__draw.html) + titles_background_color: Color of the title text padding. + default_title_placement: Title anchor placement used when an explicit + anchor is not provided. + + Returns: + ImageType: Image with all input images located in tiles grid. The output type is + determined by `return_type` parameter. + + Raises: + ValueError: In case when input images list is empty, provided `grid_size` is too + small to fit all images, `tile_scaling` mode is invalid. + """ + if len(images) == 0: + raise ValueError("Could not create image tiles from empty list of images.") + if return_type == "auto": + return_type = _negotiate_tiles_format(images=images) + tile_padding_color = unify_to_bgr(color=tile_padding_color) + tile_margin_color = unify_to_bgr(color=tile_margin_color) + images_cv2 = images_to_cv2(images=images) + if single_tile_size is None: + single_tile_size = _aggregate_images_shape(images=images_cv2, mode=tile_scaling) + resized_images = [ + letterbox_image( + image=i, resolution_wh=single_tile_size, color=tile_padding_color + ) + for i in images_cv2 + ] + grid_size = _establish_grid_size(images=images_cv2, grid_size=grid_size) + if len(images_cv2) > grid_size[0] * grid_size[1]: + raise ValueError( + f"Could not place {len(images_cv2)} in grid with size: {grid_size}." + ) + if titles is not None: + titles = fill(sequence=titles, desired_size=len(images_cv2), content=None) + if isinstance(titles_anchors, list): + titles_anchors_sequence = titles_anchors + else: + titles_anchors_sequence = [titles_anchors] + titles_anchors = fill( + sequence=titles_anchors_sequence, desired_size=len(images_cv2), content=None + ) + titles_color = unify_to_bgr(color=titles_color) + titles_background_color = unify_to_bgr(color=titles_background_color) + tiles_image = _generate_tiles( + images=resized_images, + grid_size=grid_size, + single_tile_size=single_tile_size, + tile_padding_color=tile_padding_color, + tile_margin=tile_margin, + tile_margin_color=tile_margin_color, + titles=titles, + titles_anchors=titles_anchors, + titles_color=titles_color, + titles_scale=titles_scale, + titles_thickness=titles_thickness, + titles_padding=titles_padding, + titles_text_font=titles_text_font, + titles_background_color=titles_background_color, + default_title_placement=default_title_placement, + ) + if return_type == "pillow": + tiles_image_pillow: object = cv2_to_pillow(image=tiles_image) + return cast(ImageType, tiles_image_pillow) + tiles_image_cv2: object = tiles_image + return cast(ImageType, tiles_image_cv2) + + +def _negotiate_tiles_format(images: list[ImageType]) -> Literal["cv2", "pillow"]: + number_of_np_arrays = sum(issubclass(type(i), np.ndarray) for i in images) + if number_of_np_arrays * 2 >= len(images): + return "cv2" + return "pillow" + + +def _calculate_aggregated_images_shape( + images: list[npt.NDArray[np.uint8]], aggregator: Callable[[list[int]], float] +) -> tuple[int, int]: + height = round(aggregator([i.shape[0] for i in images])) + width = round(aggregator([i.shape[1] for i in images])) + return width, height + + +SHAPE_AGGREGATION_FUN = { + "min": partial(_calculate_aggregated_images_shape, aggregator=np.min), + "max": partial(_calculate_aggregated_images_shape, aggregator=np.max), + "avg": partial(_calculate_aggregated_images_shape, aggregator=np.average), +} + + +def _aggregate_images_shape( + images: list[npt.NDArray[np.uint8]], mode: Literal["min", "max", "avg"] +) -> tuple[int, int]: + if mode not in SHAPE_AGGREGATION_FUN: + raise ValueError( + f"Could not aggregate images shape - provided unknown mode: {mode}. " + f"Supported modes: {list(SHAPE_AGGREGATION_FUN.keys())}." + ) + return SHAPE_AGGREGATION_FUN[mode](images) + + +def _establish_grid_size( + images: list[npt.NDArray[np.uint8]], + grid_size: tuple[int | None, int | None] | None, +) -> tuple[int, int]: + if grid_size is None or all(e is None for e in grid_size): + return _negotiate_grid_size(images=images) + if grid_size[0] is None: + columns = grid_size[1] + assert columns is not None + return math.ceil(len(images) / columns), columns + if grid_size[1] is None: + rows = grid_size[0] + assert rows is not None + return rows, math.ceil(len(images) / rows) + return cast(tuple[int, int], grid_size) + + +def _negotiate_grid_size(images: list[npt.NDArray[np.uint8]]) -> tuple[int, int]: + if len(images) <= MAX_COLUMNS_FOR_SINGLE_ROW_GRID: + return 1, len(images) + nearest_sqrt = math.ceil(np.sqrt(len(images))) + proposed_columns = nearest_sqrt + proposed_rows = nearest_sqrt + while proposed_columns * (proposed_rows - 1) >= len(images): + proposed_rows -= 1 + return proposed_rows, proposed_columns + + +def _generate_tiles( + images: list[npt.NDArray[np.uint8]], + grid_size: tuple[int, int], + single_tile_size: tuple[int, int], + tile_padding_color: tuple[int, int, int], + tile_margin: int, + tile_margin_color: tuple[int, int, int], + titles: list[str | None] | None, + titles_anchors: list[Point | None], + titles_color: tuple[int, int, int], + titles_scale: float | None, + titles_thickness: int, + titles_padding: int, + titles_text_font: int, + titles_background_color: tuple[int, int, int], + default_title_placement: RelativePosition, +) -> npt.NDArray[np.uint8]: + images = _draw_texts( + images=images, + titles=titles, + titles_anchors=titles_anchors, + titles_color=titles_color, + titles_scale=titles_scale, + titles_thickness=titles_thickness, + titles_padding=titles_padding, + titles_text_font=titles_text_font, + titles_background_color=titles_background_color, + default_title_placement=default_title_placement, + ) + rows, columns = grid_size + tiles_elements = list(create_batches(sequence=images, batch_size=columns)) + while len(tiles_elements[-1]) < columns: + tiles_elements[-1].append( + _generate_color_image(shape=single_tile_size, color=tile_padding_color) + ) + while len(tiles_elements) < rows: + tiles_elements.append( + [_generate_color_image(shape=single_tile_size, color=tile_padding_color)] + * columns + ) + return _merge_tiles_elements( + tiles_elements=tiles_elements, + grid_size=grid_size, + single_tile_size=single_tile_size, + tile_margin=tile_margin, + tile_margin_color=tile_margin_color, + ) + + +def _draw_texts( + images: list[npt.NDArray[np.uint8]], + titles: list[str | None] | None, + titles_anchors: list[Point | None], + titles_color: tuple[int, int, int], + titles_scale: float | None, + titles_thickness: int, + titles_padding: int, + titles_text_font: int, + titles_background_color: tuple[int, int, int], + default_title_placement: RelativePosition, +) -> list[npt.NDArray[np.uint8]]: + if titles is None: + return images + prepared_titles_anchors = _prepare_default_titles_anchors( + images=images, + titles_anchors=titles_anchors, + default_title_placement=default_title_placement, + ) + if titles_scale is None: + image_height, image_width = images[0].shape[:2] + titles_scale = calculate_optimal_text_scale( + resolution_wh=(image_width, image_height) + ) + result = [] + for image, text, anchor in zip(images, titles, prepared_titles_anchors): + if text is None: + result.append(image) + continue + processed_image = draw_text( + scene=image, + text=text, + text_anchor=anchor, + text_color=Color.from_bgr_tuple(titles_color), + text_scale=titles_scale, + text_thickness=titles_thickness, + text_padding=titles_padding, + text_font=titles_text_font, + background_color=Color.from_bgr_tuple(titles_background_color), + ) + result.append(processed_image) + return result + + +def _prepare_default_titles_anchors( + images: list[npt.NDArray[np.uint8]], + titles_anchors: list[Point | None], + default_title_placement: RelativePosition, +) -> list[Point]: + result = [] + for image, anchor in zip(images, titles_anchors): + if anchor is not None: + result.append(anchor) + continue + image_height, image_width = image.shape[:2] + if default_title_placement == "top": + default_anchor = Point(x=image_width / 2, y=image_height * 0.1) + else: + default_anchor = Point(x=image_width / 2, y=image_height * 0.9) + result.append(default_anchor) + return result + + +def _merge_tiles_elements( + tiles_elements: list[list[npt.NDArray[np.uint8]]], + grid_size: tuple[int, int], + single_tile_size: tuple[int, int], + tile_margin: int, + tile_margin_color: tuple[int, int, int], +) -> npt.NDArray[np.uint8]: + vertical_padding: npt.NDArray[np.uint8] = np.full( + (single_tile_size[1], tile_margin, 3), + tile_margin_color, + dtype=np.uint8, + ) + merged_rows = [ + np.concatenate( + list( + itertools.chain.from_iterable( + zip(row, [vertical_padding] * grid_size[1]) + ) + )[:-1], + axis=1, + ) + for row in tiles_elements + ] + row_width = merged_rows[0].shape[1] + horizontal_padding: npt.NDArray[np.uint8] = np.full( + (tile_margin, row_width, 3), + tile_margin_color, + dtype=np.uint8, + ) + rows_with_paddings: list[npt.NDArray[np.uint8]] = [] + for row in merged_rows: + rows_with_paddings.append(row) + rows_with_paddings.append(horizontal_padding) + return np.concatenate(rows_with_paddings[:-1], axis=0).astype(np.uint8, copy=False) + + +def _generate_color_image( + shape: tuple[int, int], color: tuple[int, int, int] +) -> npt.NDArray[np.uint8]: + return np.full((*shape[::-1], 3), color, dtype=np.uint8) diff --git a/.venv/lib/python3.12/site-packages/supervision/utils/image_window.py b/.venv/lib/python3.12/site-packages/supervision/utils/image_window.py new file mode 100644 index 0000000000000000000000000000000000000000..796b018fcf178582b2a410b8a199bebea6ebef1a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/utils/image_window.py @@ -0,0 +1,323 @@ +from __future__ import annotations + +from collections.abc import Callable +from contextlib import suppress +from typing import Any + +import numpy as np +import numpy.typing as npt +from PIL import Image + +from supervision.utils.conversion import cv2_to_pillow + +MouseCallback = Callable[[int, int, str], None] + + +class ImageWindow: + """Desktop image window backed by stdlib tkinter + pillow. + + Functional replacement for `cv2.imshow` / `cv2.waitKey` that works under + `opencv-python-headless`. Requires tkinter (stdlib) and pillow (already a + supervision dependency). Instantiation always succeeds; `show()` raises + `ModuleNotFoundError` (No module named '_tkinter') on environments where + `python3-tk` is absent — install with ``sudo apt-get install python3-tk`` + (Debian/Ubuntu) or ``brew install tcl-tk`` (macOS with Homebrew/pyenv) + — and raises `tkinter.TclError` on headless servers where a display is + unavailable. + + Differences from cv2: + - `wait_key()` returns a tkinter keysym `str` (e.g. ``"q"``, + ``"Return"``, ``"Escape"``) or ``None``, not an ``int``. Code + relying on ``key == ord("q")`` or ``key & 0xFF == 27`` must be + updated to ``key == "q"`` or ``key == "Escape"``. + - Mouse callback signature is ``(x: int, y: int, event_type: str)`` + where ``event_type`` is ``"down"``, ``"up"``, or ``"move"``. This + differs from cv2's ``(event: int, x, y, flags, param)`` — existing + cv2 mouse callbacks are not compatible without modification. + - Only left-button events are captured. Right-button clicks, scroll + events, and modifier-key flags (Ctrl, Shift) have no equivalent. + + Args: + title: Window title bar text. + keep_aspect_ratio: If ``True`` (default), frames are scaled to fit + inside the window while preserving aspect ratio (letterboxed). If + ``False``, frames are stretched to fill the window exactly. + + Examples: + ```python + import supervision as sv + + window = sv.ImageWindow("preview") + for frame in sv.get_video_frames_generator(source_path="video.mp4"): + annotated = ... # annotate frame + window.show(annotated) + if window.wait_key(delay_ms=1) == "q": + break + window.close() + ``` + + Context-manager form closes automatically: + + ```python + import supervision as sv + + with sv.ImageWindow("preview") as window: + for frame in sv.get_video_frames_generator(source_path="video.mp4"): + window.show(frame) + if window.wait_key(delay_ms=1) == "q": + break + ``` + """ + + def __init__( + self, title: str = "supervision", keep_aspect_ratio: bool = True + ) -> None: + self.title = title + self.keep_aspect_ratio = keep_aspect_ratio + self._mouse_callback: MouseCallback | None = None + self._root: Any = None + self._label: Any = None + self._photo: Any = None + self._key_event: Any = None + self._key_queue: list[str] = [] + self._pil_image: Image.Image | None = None + self._win_w: int = 0 + self._win_h: int = 0 + self._display_scale_x: float = 1.0 + self._display_scale_y: float = 1.0 + self._display_offset_x: float = 0.0 + self._display_offset_y: float = 0.0 + + def show(self, image: npt.NDArray[np.uint8]) -> None: + """Display a BGR, grayscale, or BGRA frame in the window. + + The image is scaled to fit the current window dimensions. Aspect ratio is + preserved unless `keep_aspect_ratio=False`. Resizing the window rescales live. + Args: + image: uint8 numpy array. Accepted shapes: + - ``(H, W)`` — grayscale + - ``(H, W, 3)`` — BGR (OpenCV convention; channels are swapped + to RGB before display) + - ``(H, W, 4)`` — BGRA (channels reordered to RGBA) + + Raises: + TypeError: If `image.dtype` is not `uint8`. + ValueError: If `image` is not 2-D or 3-D with 3 or 4 channels. + """ + if image.dtype != np.uint8: + raise TypeError( + f"image must be uint8, got {image.dtype}. " + "Convert with image.astype(np.uint8) before calling show()." + ) + self._pil_image = _bgr_to_pil(image) + self._ensure_window() + self._update_display() + self._root.update_idletasks() + self._root.update() + + def wait_key(self, delay_ms: int = 0) -> str | None: + """Wait for a keypress and return its name. + + Args: + delay_ms: How long to wait in milliseconds. ``0`` blocks until a + key is pressed. Positive values poll for up to `delay_ms` ms + and return ``None`` if no key arrives in time. + + Returns: + The tkinter keysym string (e.g. ``"q"``, ``"Return"``, ``"Escape"``) + or ``None`` if the timeout elapsed without a key event. + """ + if self._root is None and not self._key_queue: + return None + self._ensure_window() + if self._key_queue: + return self._key_queue.pop(0) + root = self._root + if delay_ms <= 0: + self._wait_for_key_or_close() + else: + timeout_id = root.after(delay_ms, self._signal_wait) + self._wait_for_key_or_close() + if self._root is not None: + with suppress(Exception): + root.after_cancel(timeout_id) + return self._key_queue.pop(0) if self._key_queue else None + + def set_mouse_callback(self, callback: MouseCallback | None) -> None: + """Register a callback for mouse events on the image. + + Args: + callback: Callable receiving ``(x, y, event_type)`` where + ``event_type`` is one of ``"down"``, ``"up"``, or ``"move"``. + Pass ``None`` to remove the callback. + """ + self._mouse_callback = callback + + @property + def is_open(self) -> bool: + """Return whether the underlying Tk window currently exists.""" + return self._window_exists() + + def close(self) -> None: + """Destroy the window and release its resources.""" + if self._root is not None: + root = self._root + self._signal_wait() + with suppress(Exception): + root.destroy() + self._reset_window_refs() + + def __enter__(self) -> ImageWindow: + return self + + def __exit__(self, *_: object) -> None: + self.close() + + def _ensure_window(self) -> None: + if self._window_exists(): + return + self._reset_window_refs() + import tkinter as tk + + self._root = tk.Tk() + self._root.title(self.title) + self._label = tk.Label(self._root) + self._label.pack(expand=True, fill="both") + self._key_event = tk.IntVar(master=self._root, value=0) + self._root.bind("", self._on_key) + self._root.bind("", self._on_configure) + self._root.protocol("WM_DELETE_WINDOW", self.close) + self._label.bind("", lambda e: self._on_mouse(e, "down")) + self._label.bind("", lambda e: self._on_mouse(e, "up")) + self._label.bind("", lambda e: self._on_mouse(e, "move")) + + def _on_configure(self, event: Any) -> None: + if event.widget is not self._root: + return + w, h = event.width, event.height + if w > 1 and h > 1 and (w, h) != (self._win_w, self._win_h): + self._win_w, self._win_h = w, h + if self._pil_image is not None: + self._update_display() + + def _update_display(self) -> None: + if self._pil_image is None or self._label is None: + return + from PIL import ImageTk + + img = self._pil_image + if self._win_w > 1 and self._win_h > 1: + img = _fit_image(img, self._win_w, self._win_h, self.keep_aspect_ratio) + self._update_display_transform(img) + self._photo = ImageTk.PhotoImage(img) + self._label.configure(image=self._photo) + + def _update_display_transform(self, fitted: Image.Image) -> None: + """Record the scale and letterbox offset from the last display pass. + + The fitted image is drawn centered inside the label, so mouse events on + the label carry display-space coordinates. Storing the per-axis scale + and centering offset lets `_on_mouse` invert the transform back to + original image-pixel coordinates. Falls back to an identity transform + while the window geometry is still unknown. + """ + if self._pil_image is None: + return + orig_w, orig_h = self._pil_image.size + fit_w, fit_h = fitted.size + win_w = self._win_w if self._win_w > 1 else fit_w + win_h = self._win_h if self._win_h > 1 else fit_h + self._display_scale_x = fit_w / orig_w if orig_w else 1.0 + self._display_scale_y = fit_h / orig_h if orig_h else 1.0 + self._display_offset_x = max(0.0, (win_w - fit_w) / 2) + self._display_offset_y = max(0.0, (win_h - fit_h) / 2) + + def _on_key(self, event: Any) -> None: + self._key_queue.append(event.keysym) + self._signal_wait() + + def _on_mouse(self, event: Any, event_type: str) -> None: + if self._mouse_callback is None: + return + x, y = self._to_image_coords(event.x, event.y) + self._mouse_callback(x, y, event_type) + + def _to_image_coords(self, event_x: int, event_y: int) -> tuple[int, int]: + """Map label-space event coordinates to original image pixels. + + Inverts the scale and letterbox offset recorded by `_update_display` + so callbacks receive coordinates in the source image's pixel space, + regardless of how the window has been resized. Results are rounded to + the nearest pixel and clamped inside the image bounds. When no image + has been shown, the raw event coordinates are returned unchanged. + """ + if self._pil_image is None: + return event_x, event_y + orig_w, orig_h = self._pil_image.size + image_x = round((event_x - self._display_offset_x) / self._display_scale_x) + image_y = round((event_y - self._display_offset_y) / self._display_scale_y) + clamped_x = min(max(image_x, 0), orig_w - 1) + clamped_y = min(max(image_y, 0), orig_h - 1) + return clamped_x, clamped_y + + def _signal_wait(self) -> None: + if self._key_event is None: + return + with suppress(Exception): + self._key_event.set(self._key_event.get() + 1) + + def _wait_for_key_or_close(self) -> None: + if self._root is None or self._key_event is None: + return + if self._key_queue: + return + try: + self._root.wait_variable(self._key_event) + except Exception: + self._reset_window_refs() + + def _window_exists(self) -> bool: + if self._root is None: + return False + try: + return bool(self._root.winfo_exists()) + except Exception: + return False + + def _reset_window_refs(self) -> None: + self._root = None + self._label = None + self._photo = None + self._key_event = None + self._key_queue.clear() + self._win_w = 0 + self._win_h = 0 + self._display_scale_x = 1.0 + self._display_scale_y = 1.0 + self._display_offset_x = 0.0 + self._display_offset_y = 0.0 + self._pil_image = None + + +def _fit_image( + image: Image.Image, width: int, height: int, keep_aspect_ratio: bool = True +) -> Image.Image: + iw, ih = image.size + if keep_aspect_ratio: + scale = min(width / iw, height / ih) + new_w, new_h = max(1, round(iw * scale)), max(1, round(ih * scale)) + else: + new_w, new_h = width, height + if (new_w, new_h) == (iw, ih): + return image + return image.resize((new_w, new_h), Image.Resampling.LANCZOS) + + +def _bgr_to_pil(image: npt.NDArray[np.uint8]) -> Image.Image: + """Convert a BGR, grayscale, or BGRA OpenCV array to a Pillow image. + + Thin wrapper delegating to `sv.cv2_to_pillow`, which reorders channels + from OpenCV's BGR(A) convention to Pillow's RGB(A) and passes grayscale + arrays through unchanged. + """ + return cv2_to_pillow(image) diff --git a/.venv/lib/python3.12/site-packages/supervision/utils/internal.py b/.venv/lib/python3.12/site-packages/supervision/utils/internal.py new file mode 100644 index 0000000000000000000000000000000000000000..2376324ac0b8d3535b1ec91a0552582ce5b20060 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/utils/internal.py @@ -0,0 +1,209 @@ +import functools +import inspect +import os +import warnings +from collections.abc import Callable +from typing import Any, Generic, TypeVar + + +class SupervisionWarnings(Warning): + """Supervision warning category. + Set the deprecation warnings visibility for Supervision library. + You can set the environment variable SUPERVISION_DEPRECATION_WARNING to '0' + to disable the deprecation warnings. The legacy misspelled + SUPERVISON_DEPRECATION_WARNING variable is still accepted. + """ + + pass + + +def format_warning( + message: Warning | str, + category: type[Warning], + filename: str, + lineno: int, + line: str | None = None, +) -> str: + """ + Format a warning the same way as the default formatter, but also include the + category name in the output. + """ + return f"{category.__name__}: {message}\n" + + +deprecation_warning_env = os.getenv( + "SUPERVISION_DEPRECATION_WARNING", + os.getenv("SUPERVISON_DEPRECATION_WARNING"), +) +if deprecation_warning_env == "0": + warnings.simplefilter("ignore", SupervisionWarnings) +else: + warnings.simplefilter("always", SupervisionWarnings) + + +def warn_deprecated(message: str) -> None: + """ + Issue a warning that a function is deprecated. + + Args: + message: The message to display when the function is called. + """ + warnings.warn(message, category=SupervisionWarnings, stacklevel=2) + + +def deprecated_parameter( + old_parameter: str, + new_parameter: str, + map_function: Callable[[Any], Any] = lambda x: x, + warning_message: str = "Warning: '{old_parameter}' in '{function_name}' is " + "deprecated: use '{new_parameter}' instead.", + **message_kwargs: Any, +) -> Callable[[Any], Any]: + """ + A decorator to mark a function's parameter as deprecated and issue a warning when + used. + + Args: + old_parameter: The name of the deprecated parameter. + new_parameter: The name of the parameter that should be used instead. + map_function: A function used to map the value of the old + parameter to the new parameter. Defaults to the identity function. + warning_message: The warning message to be displayed when the + deprecated parameter is used. Defaults to a generic warning message with + placeholders for the old parameter, new parameter, and function name. + **message_kwargs: Additional keyword arguments that can be used to customize + the warning message. + + Returns: + A decorator function that can be applied to mark a function's + parameter as deprecated. + + Examples: + ```pycon + >>> from supervision.utils.internal import deprecated_parameter + >>> import warnings + >>> @deprecated_parameter( + ... old_parameter='old_name', + ... new_parameter='new_name' + ... ) + ... def example_function(new_name=None): + ... return new_name + >>> # Calling with new parameter works normally + >>> example_function(new_name='value') + 'value' + >>> # Calling with old parameter triggers warning but still works + >>> with warnings.catch_warnings(record=True): + ... result = example_function(old_name='deprecated_value') + ... print(result) + deprecated_value + + ``` + """ + + def decorator(func: Callable[..., Any]) -> Callable[..., Any]: + @functools.wraps(func) + def wrapper(*args: Any, **kwargs: Any) -> Any: + if old_parameter in kwargs: + if args and hasattr(args[0], "__class__"): + class_name = args[0].__class__.__name__ + function_name = f"{class_name}.{func.__name__}" + else: + function_name = func.__name__ + + warn_deprecated( + message=warning_message.format( + function_name=function_name, + old_parameter=old_parameter, + new_parameter=new_parameter, + **message_kwargs, + ) + ) + + kwargs[new_parameter] = map_function(kwargs.pop(old_parameter)) + + return func(*args, **kwargs) + + return wrapper + + return decorator + + +T = TypeVar("T") + + +class classproperty(Generic[T]): + """ + A decorator that combines @classmethod and @property. + It allows a method to be accessed as a property of the class, + rather than an instance, similar to a classmethod. + + Usage: + @classproperty + def my_method(cls): + ... + """ + + def __init__(self, fget: Callable[..., T]) -> None: + """ + Args: + The function that is called when the property is accessed. + """ + self.fget = fget + + def __get__(self, owner_self: Any, owner_cls: type | None = None) -> T: + """ + Override the __get__ method to return the result of the function call. + + Args: + owner_self: The instance through which the attribute was accessed, or None. + Irrelevant for class properties. + owner_cls: The class through which the attribute was accessed. + + Returns: + The result of calling the function stored in 'fget' with 'owner_cls'. + """ + if self.fget is None: + raise AttributeError("unreadable attribute") + return self.fget(owner_cls) + + +def get_instance_variables(instance: Any, include_properties: bool = False) -> set[str]: + """ + Get the public variables of a class instance. + + Args: + instance: The instance of a class + include_properties: Whether to include properties in the result + + Usage: + ```pycon + >>> from supervision.utils.internal import get_instance_variables + >>> import numpy as np + >>> from supervision import Detections + >>> detections = Detections(xyxy=np.array([[1, 2, 3, 4]])) + >>> variables = get_instance_variables(detections) + >>> 'xyxy' in variables + True + >>> 'data' in variables + True + + ``` + """ + if isinstance(instance, type): + raise ValueError("Only class instances are supported, not classes.") + + fields = { + name + for name, val in inspect.getmembers(instance) + if not callable(val) and not name.startswith("_") + } + + if not include_properties: + properties = { + name + for name, val in inspect.getmembers(instance.__class__) + if isinstance(val, property) + } + fields -= properties + + return fields diff --git a/.venv/lib/python3.12/site-packages/supervision/utils/iterables.py b/.venv/lib/python3.12/site-packages/supervision/utils/iterables.py new file mode 100644 index 0000000000000000000000000000000000000000..9b30e6bb3bab07f1f51c626c2ac5f31632980fa5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/utils/iterables.py @@ -0,0 +1,103 @@ +from collections.abc import Generator, Iterable +from typing import TypeVar + +V = TypeVar("V") + + +def create_batches( + sequence: Iterable[V], batch_size: int +) -> Generator[list[V], None, None]: + """ + Provides a generator that yields chunks of the input sequence + of the size specified by the `batch_size` parameter. The last + chunk may be a smaller batch. + + Args: + sequence: The sequence to be split into batches. + batch_size: The expected size of a batch. + + Returns: + A generator that yields chunks + of `sequence` of size `batch_size`, up to the length of + the input `sequence`. + + Examples: + ```pycon + >>> from supervision.utils.iterables import create_batches + >>> list(create_batches([1, 2, 3, 4, 5], 2)) + [[1, 2], [3, 4], [5]] + >>> list(create_batches("abcde", 3)) + [['a', 'b', 'c'], ['d', 'e']] + + ``` + """ + batch_size = max(batch_size, 1) + current_batch: list[V] = [] + for element in sequence: + if len(current_batch) == batch_size: + yield current_batch + current_batch = [] + current_batch.append(element) + if current_batch: + yield current_batch + + +def fill(sequence: list[V], desired_size: int, content: V) -> list[V]: + """ + Fill the sequence with padding elements until the sequence reaches + the desired size. + + Args: + sequence: The input sequence. + desired_size: The expected size of the output list. The + difference between this value and the actual length of `sequence` + (if positive) dictates how many elements will be added as padding. + content: The element to be placed at the end of the input + `sequence` as padding. + + Returns: + A padded version of the input `sequence` (if needed). + + Examples: + ```pycon + >>> from supervision.utils.iterables import fill + >>> fill([1, 2], 4, 0) + [1, 2, 0, 0] + >>> fill(['a', 'b'], 3, 'c') + ['a', 'b', 'c'] + + ``` + """ + missing_size = max(0, desired_size - len(sequence)) + sequence.extend([content] * missing_size) + return sequence + + +def find_duplicates(sequence: list[V]) -> list[V]: + """ + Find all duplicate elements in the input sequence. + + Args: + sequence: The input sequence. + + Returns: + A list of duplicate elements found in the sequence. + + Examples: + ```pycon + >>> from supervision.utils.iterables import find_duplicates + >>> sorted(find_duplicates([1, 2, 3, 2, 4, 5, 1])) + [1, 2] + >>> find_duplicates(['a', 'b', 'c']) + [] + + ``` + """ + seen = set() + duplicates = set() + for element in sequence: + if element in seen: + duplicates.add(element) + else: + seen.add(element) + return list(duplicates) diff --git a/.venv/lib/python3.12/site-packages/supervision/utils/logger.py b/.venv/lib/python3.12/site-packages/supervision/utils/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..2ed8c452d8ba852c40192787f9ee513c2b26a4f5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/utils/logger.py @@ -0,0 +1,61 @@ +import logging +import os +import sys + + +def _get_logger(name: str = "supervision", level: int | None = None) -> logging.Logger: + """Creates and configures a logger with stdout and stderr handlers. + + This function creates a logger that sends INFO and DEBUG level logs to stdout, + and WARNING, ERROR, and CRITICAL level logs to stderr. If the logger already + has handlers, it returns the existing logger without adding new handlers. + + The log level can be specified directly or through the `LOG_LEVEL` environment + variable. + + Args: + name: The name of the logger. Defaults to `"supervision"`. + level: The logging level to set. If `None`, uses the `LOG_LEVEL` environment + variable, defaulting to `INFO` if not set. + + Returns: + A configured `logging.Logger` instance. + + Example: + ```pycon + >>> from supervision.utils.logger import _get_logger + >>> import logging + >>> logger = _get_logger("test_logger", level=logging.INFO) + >>> logger.name + 'test_logger' + >>> logger.level == logging.INFO + True + + ``` + """ + if level is None: + level = getattr(logging, os.getenv("LOG_LEVEL", "INFO").upper(), logging.INFO) + + logger = logging.getLogger(name) + logger.setLevel(level) + + if not logger.handlers: + formatter = logging.Formatter( + "[%(asctime)s] [%(levelname)s] %(name)s - %(message)s", + datefmt="%Y-%m-%d %H:%M:%S", + ) + + stdout_handler = logging.StreamHandler(sys.stdout) + stdout_handler.setLevel(logging.DEBUG) + stdout_handler.addFilter(lambda r: r.levelno <= logging.INFO) + stdout_handler.setFormatter(formatter) + + stderr_handler = logging.StreamHandler(sys.stderr) + stderr_handler.setLevel(logging.WARNING) + stderr_handler.setFormatter(formatter) + + logger.addHandler(stdout_handler) + logger.addHandler(stderr_handler) + logger.propagate = False + + return logger diff --git a/.venv/lib/python3.12/site-packages/supervision/utils/notebook.py b/.venv/lib/python3.12/site-packages/supervision/utils/notebook.py new file mode 100644 index 0000000000000000000000000000000000000000..b9965d43949d1b7dc8598070ea04ce64fd2b797b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/utils/notebook.py @@ -0,0 +1,123 @@ +import numpy as np +import numpy.typing as npt +from PIL import Image + +from supervision import _cv2 as cv2 +from supervision.draw.base import ImageType +from supervision.utils.conversion import pillow_to_cv2 + + +def plot_image( + image: ImageType, size: tuple[int, int] = (12, 12), cmap: str | None = "gray" +) -> None: + """ + Plots image using matplotlib. + + Args: + image: The frame to be displayed ImageType + is a flexible type, accepting either `numpy.ndarray` or `PIL.Image.Image`. + size: The size of the plot in inches. + cmap: the colormap to use for single channel images. + + Examples: + ```pycon + >>> import numpy as np + >>> import matplotlib + >>> matplotlib.use('Agg') # Prevents the GUI window from popping up + >>> import supervision as sv + >>> image = np.zeros((100, 100, 3), dtype=np.uint8) + >>> sv.plot_image(image=image, size=(16, 16)) + ... + + ``` + """ + if isinstance(image, Image.Image): + image_np = pillow_to_cv2(image) + else: + image_np = image + + # Keep pyplot lazy so importing notebook helpers does not import matplotlib. + import matplotlib.pyplot as plt + + plt.figure(figsize=size) + + if image_np.ndim == 2: + plt.imshow(image_np, cmap=cmap) + else: + plt.imshow(cv2.cvtColor(image_np, cv2.COLOR_BGR2RGB)) + + plt.axis("off") + plt.show() + + +def plot_images_grid( + images: list[ImageType], + grid_size: tuple[int, int], + titles: list[str] | None = None, + size: tuple[int, int] = (12, 12), + cmap: str | None = "gray", +) -> None: + """ + Plots images in a grid using matplotlib. + + Args: + images: A list of images as ImageType + is a flexible type, accepting either `numpy.ndarray` or `PIL.Image.Image`. + grid_size: A tuple specifying the number + of rows and columns for the grid. + titles: A list of titles for each image. + Defaults to None. + size: A tuple specifying the width and + height of the entire plot in inches. + cmap: the colormap to use for single channel images. + + Raises: + ValueError: If the number of images exceeds the grid size. + + Examples: + ```pycon + >>> import numpy as np + >>> import matplotlib + >>> matplotlib.use('Agg') # Prevents the GUI window from popping up + >>> import supervision as sv + >>> from PIL import Image + >>> image1 = np.zeros((100, 100, 3), dtype=np.uint8) + >>> image2 = Image.new('RGB', (100, 100)) + >>> image3 = np.zeros((100, 100, 3), dtype=np.uint8) + >>> images = [image1, image2, image3] + >>> titles = ["Image 1", "Image 2", "Image 3"] + >>> sv.plot_images_grid(images, grid_size=(2, 2), titles=titles, size=(16, 16)) + ... + + ``` + """ + nrows, ncols = grid_size + + images_np: list[npt.NDArray[np.uint8]] = [ + pillow_to_cv2(img) if isinstance(img, Image.Image) else img for img in images + ] + + if len(images_np) > nrows * ncols: + raise ValueError( + "The number of images exceeds the grid size. Please increase the grid size" + " or reduce the number of images." + ) + + # Keep pyplot lazy so importing notebook helpers does not import matplotlib. + import matplotlib.pyplot as plt + + # Without `squeeze=False`, a 1x1 grid returns a lone `Axes` that has no `.flat`. + _fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=size, squeeze=False) + + for idx, ax in enumerate(axes.flat): + if idx < len(images_np): + if images_np[idx].ndim == 2: + ax.imshow(images_np[idx], cmap=cmap) + else: + ax.imshow(cv2.cvtColor(images_np[idx], cv2.COLOR_BGR2RGB)) + + if titles is not None and idx < len(titles): + ax.set_title(titles[idx]) + + ax.axis("off") + plt.show() diff --git a/.venv/lib/python3.12/site-packages/supervision/utils/video.py b/.venv/lib/python3.12/site-packages/supervision/utils/video.py new file mode 100644 index 0000000000000000000000000000000000000000..732b9bf6c50ecc0a01659b778896f6d91a31818e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/utils/video.py @@ -0,0 +1,634 @@ +from __future__ import annotations + +import threading +import time +from collections import deque +from collections.abc import Callable, Generator +from dataclasses import dataclass +from queue import Empty, Full, Queue +from types import TracebackType +from typing import cast + +import numpy as np +import numpy.typing as npt +from tqdm.auto import tqdm + +from supervision import _cv2 as cv2 +from supervision._cv2._video import _mux_audio +from supervision.utils.logger import _get_logger + +logger = _get_logger(__name__) + + +@dataclass +class VideoInfo: + """ + A class to store video information, including width, height, fps and + total number of frames. + + Attributes: + width: width of the video in pixels + height: height of the video in pixels + fps: frames per second of the video as a float. Common values include + 23.976, 24.0, 25.0, 29.97, 30.0, 59.94, and 60.0. + total_frames: total number of frames in the video, + default is None + + Examples: + ```python + import supervision as sv + + video_info = sv.VideoInfo.from_video_path(video_path="") + + video_info + # VideoInfo(width=3840, height=2160, fps=25.0, total_frames=538) + + video_info.resolution_wh + # (3840, 2160) + ``` + """ + + width: int + height: int + fps: float + total_frames: int | None = None + + @classmethod + def from_video_path(cls, video_path: str) -> VideoInfo: + """Read video metadata from a file path. + + Args: + video_path: Path to the video file. + + Returns: + A `VideoInfo` instance with width, height, fps, and total_frames. + + Examples: + ```python + import supervision as sv + + video_info = sv.VideoInfo.from_video_path(video_path="") + # VideoInfo(width=3840, height=2160, fps=25.0, total_frames=538) + ``` + """ + video = cv2.VideoCapture(video_path) + if not video.isOpened(): + raise Exception(f"Could not open video at {video_path}") + + width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH)) + height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT)) + fps = float(video.get(cv2.CAP_PROP_FPS)) + total_frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT)) + video.release() + return VideoInfo(width, height, fps, total_frames) + + @property + def resolution_wh(self) -> tuple[int, int]: + return self.width, self.height + + +class VideoSink: + """ + Context manager that saves video frames to a file using OpenCV. + + Attributes: + target_path: The path to the output file where the video will be saved. + video_info: Information about the video resolution, fps, + and total frame count. + codec: FOURCC code for video format + + Example: + ```python + import supervision as sv + + video_info = sv.VideoInfo.from_video_path("") + frames_generator = sv.get_video_frames_generator("") + + with sv.VideoSink(target_path="", video_info=video_info) as sink: + for frame in frames_generator: + sink.write_frame(frame=frame) + ``` + """ # noqa: E501 // docs + + def __init__( + self, target_path: str, video_info: VideoInfo, codec: str = "mp4v" + ) -> None: + self.target_path = target_path + self.video_info = video_info + self.__codec = codec + self.__fourcc: int = 0 + self.__writer: cv2.VideoWriter | None = None + + def __enter__(self) -> VideoSink: + """Open the underlying video writer for context-managed frame output.""" + fourcc_fn = cast( + Callable[[str, str, str, str], int], getattr(cv2, "VideoWriter_fourcc") + ) + try: + self.__fourcc = int(fourcc_fn(*self.__codec)) + except TypeError as e: + logger.warning("%s. Defaulting to mp4v...", str(e)) + self.__fourcc = int(fourcc_fn(*"mp4v")) + self.__writer = cv2.VideoWriter( + self.target_path, + self.__fourcc, + self.video_info.fps, + self.video_info.resolution_wh, + ) + # OpenCV can construct a writer object that is not usable for the target path. + if not self.__writer.isOpened(): + self.__writer.release() + self.__writer = None + raise RuntimeError(f"Could not open video writer for {self.target_path}") + return self + + def write_frame(self, frame: npt.NDArray[np.uint8]) -> None: + """ + Writes a single video frame to the target video file. + + Args: + frame: The video frame to be written to the file. The frame + must be in BGR color format. + """ + # Preserve the context-manager invariant instead of silently dropping frames. + if self.__writer is None: + raise RuntimeError("write_frame requires an open VideoSink context.") + self.__writer.write(frame) + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + exc_traceback: TracebackType | None, + ) -> None: + """Release the underlying video writer when leaving the context.""" + if self.__writer is not None: + self.__writer.release() + self.__writer = None + + +def _validate_and_setup_video( + source_path: str, start: int, end: int | None, iterative_seek: bool = False +) -> tuple[cv2.VideoCapture, int, int]: + """Open a video, position it at `start`, and return it with the clamped range.""" + video = cv2.VideoCapture(source_path) + if not video.isOpened(): + raise Exception(f"Could not open video at {source_path}") + total_frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT)) + if end is not None and end > total_frames: + raise Exception("Requested frames are outbound") + start = max(start, 0) + end = min(end, total_frames) if end is not None else total_frames + + if iterative_seek: + # Count grabs separately: `start` is returned as the position of the first + # frame read, and the caller measures `end` from it. + for _ in range(start): + success = video.grab() + if not success: + break + elif start > 0: + video.set(cv2.CAP_PROP_POS_FRAMES, start) + + return video, start, end + + +def get_video_frames_generator( + source_path: str, + stride: int = 1, + start: int = 0, + end: int | None = None, + iterative_seek: bool = False, + prefetch: int = 0, +) -> Generator[npt.NDArray[np.uint8], None, None]: + """ + Get a generator that yields the frames of the video. + + Args: + source_path: The path of the video file. + stride: Indicates the interval at which frames are returned, + skipping stride - 1 frames between each. + start: Indicates the starting position from which + video should generate frames + end: Indicates the ending position at which video + should stop generating frames. If None, video will be read to the end. + iterative_seek: If True, the generator will seek to the + `start` frame by grabbing each frame, which is much slower. This is a + workaround for videos that don't open at all when you set the `start` value. + prefetch: If > 0, decode frames in a background thread and buffer up to + this many frames in a bounded queue. Useful when the consumer (e.g. + CPU inference) is the bottleneck and can overlap with decode I/O. + This works best when the consumer releases the GIL during frame + processing (common for numpy/PyTorch/ONNX C-extension calls). Pure + Python per-frame consumers that hold the GIL (for example, heavy + Python loops, PIL usage, or pandas `apply`) usually see little + speedup. + Default 0 keeps the original synchronous behaviour unchanged. Note: + each buffered frame occupies width x height x 3 bytes of uncompressed + memory; use `sv.VideoInfo.from_video_path()` to size appropriately. + + Returns: + A generator that yields the frames of the video. + + Raises: + ValueError: If `prefetch` is negative. + RuntimeError: If `prefetch` is greater than 0 and the background reader + thread encounters a decode/open error, raised as + `RuntimeError(f"Reader thread raised: {item!r}") from item`. Errors are + drained after buffered frames, so when `prefetch` > 0 the consumer may + yield up to `prefetch` additional good frames before the exception is + raised. + + Note: + For live camera streams, use `cv2.VideoCapture` with an integer device + index directly. `get_video_frames_generator` is designed for file-based + sources; `cv2.VideoCapture` must be released by the caller when done. + This requires OpenCV to be installed — the PyAV-based fallback used + when OpenCV is unavailable only supports file paths, not webcam device + indexes; passing an integer source to it always leaves the capture + closed (`isOpened()` returns `False`): + + ```python + from supervision import _cv2 as cv2 + + cap = cv2.VideoCapture(0) # 0 = default webcam + try: + while cap.isOpened(): + success, frame = cap.read() + if not success: + break + ... # process frame + finally: + cap.release() + ``` + + Examples: + ```python + import supervision as sv + + for frame in sv.get_video_frames_generator(source_path=""): + ... + + # Prefetch frames in a background thread to overlap I/O with CPU inference: + for frame in sv.get_video_frames_generator( + source_path="", prefetch=8 + ): + ... + ``` + """ + if prefetch < 0: + raise ValueError(f"prefetch must be >= 0, got {prefetch!r}") + if prefetch > 0: + yield from _prefetched_frames_generator( + source_path=source_path, + stride=stride, + start=start, + end=end, + iterative_seek=iterative_seek, + prefetch=prefetch, + ) + return + + video, start, end = _validate_and_setup_video( + source_path, start, end, iterative_seek + ) + frame_position = start + try: + while True: + success, frame = video.read() + if not success or frame_position >= end: + break + if frame is not None: + yield cast(npt.NDArray[np.uint8], frame) + for _ in range(stride - 1): + success = video.grab() + if not success: + break + frame_position += stride + finally: + video.release() + + +def _prefetched_frames_generator( + source_path: str, + stride: int, + start: int, + end: int | None, + iterative_seek: bool, + prefetch: int, +) -> Generator[npt.NDArray[np.uint8], None, None]: + """Read frames into a bounded queue on a daemon thread. + + Sentinel protocol: None = normal EOF, Exception instance = reader error. + """ + frame_queue: Queue[npt.NDArray[np.uint8] | BaseException | None] = Queue( + maxsize=prefetch + ) + stop_event = threading.Event() + + def reader() -> None: + sentinel: BaseException | None = None + try: + for frame in get_video_frames_generator( + source_path=source_path, + stride=stride, + start=start, + end=end, + iterative_seek=iterative_seek, + prefetch=0, + ): + if stop_event.is_set(): + return + while True: + try: + frame_queue.put(frame, timeout=0.1) + break + except Full: + if stop_event.is_set(): + return + except Exception as exc: + sentinel = exc + finally: + while not stop_event.is_set(): + try: + frame_queue.put(sentinel, timeout=0.1) + return + except Full: + pass + + thread = threading.Thread(target=reader, daemon=True) + thread.start() + try: + while True: + try: + item = frame_queue.get(timeout=0.5) + except Empty: + if not thread.is_alive(): + break + continue + if isinstance(item, BaseException): + raise RuntimeError(f"Reader thread raised: {item!r}") from item + if item is None: + break + yield item + finally: + stop_event.set() + thread.join(timeout=2.0) + + +def process_video( + source_path: str, + target_path: str, + callback: Callable[[npt.NDArray[np.uint8], int], npt.NDArray[np.uint8]], + *, + max_frames: int | None = None, + prefetch: int = 32, + writer_buffer: int = 32, + show_progress: bool = False, + progress_message: str = "Processing video", + preserve_audio: bool = False, +) -> None: + """ + Process video frames asynchronously using a threaded pipeline. + + This function orchestrates a three-stage pipeline to optimize video processing + throughput: + + 1. Reader thread: Continuously reads frames from the source video file and + enqueues them into a bounded queue (`frame_read_queue`). The queue size is + limited by the `prefetch` parameter to control memory usage. + 2. Main thread (Processor): Dequeues frames from `frame_read_queue`, applies the + user-defined `callback` function to process each frame, then enqueues the + processed frames into another bounded queue (`frame_write_queue`) for writing. + The processing happens in the main thread, simplifying use of stateful objects + without synchronization. + 3. Writer thread: Dequeues processed frames from `frame_write_queue` and writes + them sequentially to the output video file. + + Args: + source_path: Path to the input video file. + target_path: Path where the processed video will be saved. + callback: Function called for + each frame, accepting the frame as a numpy array and its zero-based index, + returning the processed frame. + max_frames: Optional maximum number of frames to process. + If None, the entire video is processed (default). A value larger + than the number of frames in the video processes the whole video. + prefetch: Maximum number of frames buffered by the reader thread. + Controls memory use; default is 32. + writer_buffer: Maximum number of frames buffered before writing. + Controls output buffer size; default is 32. + show_progress: Whether to display a tqdm progress bar during processing. + Default is False. + progress_message: Description shown in the progress bar. + preserve_audio: If True, copy the audio stream from `source_path` into + `target_path` after frame processing. Remuxing is done with PyAV; + no external `ffmpeg` executable is required. If the mux step + fails, a warning is logged and the output video is saved without + audio — no exception is raised. Audio is truncated to match the + processed video duration. Default is False. + + Returns: + None + + Raises: + RuntimeError: If the reader thread fails to open or decode the source + video, raised as `RuntimeError(f"Reader thread raised: {exc!r}")` + from the original exception. Exceptions raised by `callback` are + re-raised unchanged. + + Example: + ```python + import supervision as sv + from rfdetr import RFDETRMedium + + model = RFDETRMedium() + + def callback(frame, frame_index): + return model.predict(frame) + + sv.process_video( + source_path="source.mp4", + target_path="target.mp4", + callback=callback, + preserve_audio=True, + ) + ``` + """ + video_info = VideoInfo.from_video_path(video_path=source_path) + video_total_frames = video_info.total_frames or 0 + total_frames = video_total_frames + if max_frames is not None: + total_frames = min(video_total_frames, max_frames) + + # `max_frames` is a cap, not an exact count: a value larger than the video + # must process the whole video. `get_video_frames_generator` raises when + # `end` exceeds the frame count, so clamp it whenever the count is known. + frames_end: int | None = max_frames + if max_frames is not None and video_total_frames > 0: + frames_end = total_frames + + frame_read_queue: Queue[tuple[int, npt.NDArray[np.uint8]] | None] = Queue( + maxsize=prefetch + ) + frame_write_queue: Queue[npt.NDArray[np.uint8] | None] = Queue( + maxsize=writer_buffer + ) + + reader_exception: Exception | None = None + + def reader_thread() -> None: + """Feed frames into the read queue, always ending with the sentinel.""" + nonlocal reader_exception + try: + frame_generator = get_video_frames_generator( + source_path=source_path, + end=frames_end, + ) + for frame_index, frame in enumerate(frame_generator): + frame_read_queue.put((frame_index, frame)) + except Exception as exc: + # The main loop blocks on `frame_read_queue.get()` with no timeout, + # so a reader failure must still enqueue the sentinel or the call + # never returns. Surface the error once the pipeline has shut down. + reader_exception = exc + finally: + frame_read_queue.put(None) + + def writer_thread(video_sink: VideoSink) -> None: + while True: + frame = frame_write_queue.get() + if frame is None: + break + video_sink.write_frame(frame=frame) + + reader_worker = threading.Thread(target=reader_thread, daemon=True) + with VideoSink(target_path=target_path, video_info=video_info) as video_sink: + writer_worker = threading.Thread( + target=writer_thread, + args=(video_sink,), + daemon=True, + ) + + reader_worker.start() + writer_worker.start() + + progress_bar = tqdm( + total=total_frames, + disable=not show_progress, + desc=progress_message, + ) + + exception_in_worker: Exception | None = None + read_finished = False + + try: + while True: + read_item = frame_read_queue.get() + if read_item is None: + read_finished = True + break + + frame_index, frame = read_item + try: + processed_frame = callback(frame, frame_index) + frame_write_queue.put(processed_frame) + progress_bar.update(1) + except Exception as exc: + exception_in_worker = exc + break + finally: + try: + frame_write_queue.put(None, timeout=1) + except Full: + # Best effort: if the writer is stuck and the queue never drains, + # do not block shutdown forever trying to enqueue the sentinel. + pass + if not read_finished: + while True: + # Use timeout to prevent indefinite blocking if reader thread fails + try: + read_item = frame_read_queue.get(timeout=1) + if read_item is None: + break + # If we timeout waiting for a frame, only assume failure if reader + # thread is no longer alive. Otherwise, keep waiting as the reader + # may simply be slow (for example, due to a slow source). + except Empty: + if not reader_worker.is_alive(): + break + # Reader is still alive; continue waiting for frames. + continue + reader_worker.join(timeout=10) + writer_worker.join(timeout=10) + progress_bar.close() + if exception_in_worker is not None: + raise exception_in_worker + if reader_exception is not None: + raise RuntimeError( + f"Reader thread raised: {reader_exception!r}" + ) from reader_exception + + if preserve_audio: + if writer_worker.is_alive(): + logger.warning( + "Writer thread did not finish in time; skipping audio mux " + "to avoid reading an incomplete output file." + ) + else: + _mux_audio(source_path=source_path, video_path=target_path) + + +class FPSMonitor: + """ + A class for monitoring frames per second (FPS) to benchmark latency. + """ + + def __init__(self, sample_size: int = 30) -> None: + """ + Args: + sample_size: The maximum number of observations for latency + benchmarking. + + Examples: + ```python + import supervision as sv + + frames_generator = sv.get_video_frames_generator( + source_path="") + fps_monitor = sv.FPSMonitor() + + for frame in frames_generator: + # your processing code here + fps_monitor.tick() + fps = fps_monitor.fps + ``` + """ + self.all_timestamps: deque[float] = deque(maxlen=sample_size) + + @property + def fps(self) -> float: + """ + Computes and returns the average FPS based on the stored time stamps. + + Returns: + The average FPS across the recorded intervals. Returns 0.0 if fewer + than two time stamps are stored. + """ + if len(self.all_timestamps) < 2: + return 0.0 + taken_time = self.all_timestamps[-1] - self.all_timestamps[0] + frame_intervals = len(self.all_timestamps) - 1 + return frame_intervals / taken_time if taken_time != 0 else 0.0 + + def tick(self) -> None: + """ + Adds a new time stamp to the deque for FPS calculation. + """ + self.all_timestamps.append(time.monotonic()) + + def reset(self) -> None: + """ + Clears all the time stamps from the deque. + """ + self.all_timestamps.clear() diff --git a/.venv/lib/python3.12/site-packages/supervision/validators/__init__.py b/.venv/lib/python3.12/site-packages/supervision/validators/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b8cd58d399598d281365d77886a545ddbc13976f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/supervision/validators/__init__.py @@ -0,0 +1,363 @@ +from typing import Any + +import numpy as np +from deprecate import deprecated, void # type: ignore[import-untyped,unused-ignore] + +from supervision.detection.compact_mask import CompactMask +from supervision.utils.internal import warn_deprecated + + +def _validate_xyxy(xyxy: Any) -> None: + """Validate that xyxy is a 2D np.ndarray with shape (N, 4). + + ```pycon + >>> _validate_xyxy(np.array([[0, 0, 1, 1], [1, 1, 2, 2]])) + + ``` + """ + expected_shape = "(_, 4)" + actual_shape = str(getattr(xyxy, "shape", None)) + is_valid = isinstance(xyxy, np.ndarray) and xyxy.ndim == 2 and xyxy.shape[1] == 4 + if not is_valid: + raise ValueError( + f"xyxy must be a 2D np.ndarray with shape {expected_shape}, but got shape " + f"{actual_shape}" + ) + + +@deprecated( # type: ignore[untyped-decorator] + target=_validate_xyxy, + deprecated_in="0.29.0", + remove_in="0.32.0", +) +def validate_xyxy(xyxy: Any) -> None: + void(xyxy) + + +def _validate_mask(mask: Any, n: int) -> None: + if mask is None: + return + + # Fast path: CompactMask only needs a length check. + + if isinstance(mask, CompactMask): + if len(mask) != n: + raise ValueError(f"mask must contain {n} masks, but got {len(mask)}") + return + + expected_shape = f"({n}, H, W)" + actual_shape = str(getattr(mask, "shape", None)) + actual_dtype = getattr(mask, "dtype", None) + + is_valid_shape = ( + isinstance(mask, np.ndarray) and len(mask.shape) == 3 and mask.shape[0] == n + ) + if not is_valid_shape: + raise ValueError( + "mask must be a 3D np.ndarray with shape " + + f"{expected_shape}, but got shape {actual_shape}" + ) + if not np.issubdtype(actual_dtype, bool): + warn_deprecated( + f"A `Detections` object was created with a mask of type {actual_dtype}." + " Masks of type other than `bool` are deprecated and may produce unexpected" + " behavior. Starting from `supervision-0.28.0`, passing a mask with" + " `dtype` different from `bool` to `Detections` will raise a `ValueError`" + " during validation instead of being accepted with a warning. To migrate," + " please ensure your masks are boolean, for example by using" + " `mask = np.array(..., dtype=bool)` or by converting existing masks with" + " `mask = mask.astype(bool)` before creating the `Detections` object. If" + " you did not create the mask manually, please report the issue to the" + " `supervision` team." + ) + + +@deprecated( # type: ignore[untyped-decorator] + target=_validate_mask, + deprecated_in="0.29.0", + remove_in="0.32.0", +) +def validate_mask(mask: Any, n: int) -> None: + void(mask, n) + + +def _validate_class_id(class_id: Any, n: int) -> None: + expected_shape = f"({n},)" + actual_shape = str(getattr(class_id, "shape", None)) + is_valid = class_id is None or ( + isinstance(class_id, np.ndarray) and class_id.shape == (n,) + ) + if not is_valid: + raise ValueError( + f"class_id must be a 1D np.ndarray with shape {expected_shape}, but got " + f"shape {actual_shape}" + ) + + +@deprecated( # type: ignore[untyped-decorator] + target=_validate_class_id, + deprecated_in="0.29.0", + remove_in="0.32.0", +) +def validate_class_id(class_id: Any, n: int) -> None: + void(class_id, n) + + +def _validate_confidence(confidence: Any, n: int) -> None: + """Validate detection-level confidence: 1D ``np.ndarray`` with shape ``(n,)``.""" + expected_shape = f"({n},)" + actual_shape = str(getattr(confidence, "shape", None)) + is_valid = confidence is None or ( + isinstance(confidence, np.ndarray) and confidence.shape == (n,) + ) + if not is_valid: + raise ValueError( + f"confidence must be a 1D np.ndarray with shape {expected_shape}, but got " + f"shape {actual_shape}" + ) + + +@deprecated( # type: ignore[untyped-decorator] + target=_validate_confidence, + deprecated_in="0.29.0", + remove_in="0.32.0", +) +def validate_confidence(confidence: Any, n: int) -> None: + void(confidence, n) + + +def _validate_keypoint_confidence(confidence: Any, n: int, m: int) -> None: + """Validate per-keypoint confidence: 2D ``np.ndarray`` with shape ``(n, m)``.""" + actual_shape = str(getattr(confidence, "shape", None)) + + if confidence is not None: + if not isinstance(confidence, np.ndarray) or confidence.ndim != 2: + raise ValueError( + f"keypoint_confidence must be a 2D np.ndarray with shape (n, m), but " + f"got shape {actual_shape}" + ) + if confidence.shape[0] != n: + raise ValueError( + f"keypoint_confidence first dimension must be {n}, " + f"but got shape {actual_shape}" + ) + if n > 0 and confidence.shape[1] != m: + raise ValueError( + f"keypoint_confidence second dimension must be {m}, but " + f"got shape {actual_shape}" + ) + + +@deprecated( # type: ignore[untyped-decorator] + target=_validate_keypoint_confidence, + deprecated_in="0.29.0", + remove_in="0.32.0", +) +def validate_key_point_confidence(confidence: Any, n: int, m: int) -> None: + void(confidence, n, m) + + +@deprecated( # type: ignore[untyped-decorator] + target=_validate_keypoint_confidence, + deprecated_in="0.27.0", + remove_in="0.31.0", +) +def validate_keypoint_confidence(confidence: Any, n: int, m: int) -> None: + void(confidence, n, m) + + +def _validate_tracker_id(tracker_id: Any, n: int) -> None: + expected_shape = f"({n},)" + actual_shape = str(getattr(tracker_id, "shape", None)) + is_valid = tracker_id is None or ( + isinstance(tracker_id, np.ndarray) and tracker_id.shape == (n,) + ) + if not is_valid: + raise ValueError( + f"tracker_id must be a 1D np.ndarray with shape {expected_shape}, but got " + f"shape {actual_shape}" + ) + + +@deprecated( # type: ignore[untyped-decorator] + target=_validate_tracker_id, + deprecated_in="0.29.0", + remove_in="0.32.0", +) +def validate_tracker_id(tracker_id: Any, n: int) -> None: + void(tracker_id, n) + + +def _validate_data(data: dict[str, Any], n: int) -> None: + for key, value in data.items(): + if isinstance(value, list): + if len(value) != n: + raise ValueError(f"Length of list for key '{key}' must be {n}") + elif isinstance(value, np.ndarray): + if value.ndim == 1 and value.shape[0] != n: + raise ValueError(f"Shape of np.ndarray for key '{key}' must be ({n},)") + elif value.ndim > 1 and value.shape[0] != n: + raise ValueError( + f"First dimension of np.ndarray for key '{key}' must have size {n}" + ) + else: + raise ValueError(f"Value for key '{key}' must be a list or np.ndarray") + + +@deprecated( # type: ignore[untyped-decorator] + target=_validate_data, + deprecated_in="0.29.0", + remove_in="0.32.0", +) +def validate_data(data: dict[str, Any], n: int) -> None: + void(data, n) + + +def _validate_xy(xy: Any, n: int, m: int) -> None: + expected_shape = f"({n}, {m}, 2) or ({n}, {m}, 3)" + actual_shape = str(getattr(xy, "shape", None)) + + if not isinstance(xy, np.ndarray) or xy.ndim != 3 or xy.shape[2] not in (2, 3): + raise ValueError( + f"xy must be a 3D np.ndarray with shape {expected_shape}, but got shape " + f"{actual_shape}" + ) + + +@deprecated( # type: ignore[untyped-decorator] + target=_validate_xy, + deprecated_in="0.29.0", + remove_in="0.32.0", +) +def validate_xy(xy: Any, n: int, m: int) -> None: + void(xy, n, m) + + +def _validate_visible(visible: Any, n: int, m: int) -> None: + """Validate per-keypoint visibility mask. + + Expects a 2D bool ``np.ndarray`` with shape ``(n, m)``. + """ + if visible is None: + return + actual_shape = str(getattr(visible, "shape", None)) + if not isinstance(visible, np.ndarray) or visible.ndim != 2: + raise ValueError( + "visible must be a 2D np.ndarray with shape (n, m), but " + f"got shape {actual_shape}" + ) + if visible.shape[0] != n: + raise ValueError( + f"visible first dimension must be {n}, but got shape {actual_shape}" + ) + if n > 0 and visible.shape[1] != m: + raise ValueError( + f"visible second dimension must be {m}, but got shape {actual_shape}" + ) + + +def _validate_detections_fields( + xyxy: Any, + mask: Any, + class_id: Any, + confidence: Any, + tracker_id: Any, + data: dict[str, Any], +) -> None: + _validate_xyxy(xyxy) + n = len(xyxy) + _validate_mask(mask, n) + _validate_class_id(class_id, n) + _validate_confidence(confidence, n) + _validate_tracker_id(tracker_id, n) + _validate_data(data, n) + + +@deprecated( # type: ignore[untyped-decorator] + target=_validate_detections_fields, + deprecated_in="0.29.0", + remove_in="0.32.0", +) +def validate_detections_fields( + xyxy: Any, + mask: Any, + class_id: Any, + confidence: Any, + tracker_id: Any, + data: dict[str, Any], +) -> None: + void(xyxy, mask, class_id, confidence, tracker_id, data) + + +def _validate_keypoints_fields( + xy: Any, + class_id: Any, + confidence: Any, + detection_confidence: Any = None, + visible: Any = None, + data: dict[str, Any] | None = None, +) -> None: + n = len(xy) + m = len(xy[0]) if len(xy) > 0 else 0 + _validate_xy(xy, n, m) + _validate_class_id(class_id, n) + _validate_keypoint_confidence(confidence, n, m) + if detection_confidence is not None: + _validate_confidence(detection_confidence, n) + _validate_visible(visible, n, m) + if data is not None: + _validate_data(data, n) + + +@deprecated( # type: ignore[untyped-decorator] + target=_validate_keypoints_fields, + deprecated_in="0.29.0", + remove_in="0.32.0", +) +def validate_key_points_fields( + xy: Any, class_id: Any, confidence: Any, data: dict[str, Any] +) -> None: + void(xy, class_id, confidence, data) + + +@deprecated( # type: ignore[untyped-decorator] + target=_validate_keypoints_fields, + deprecated_in="0.27.0", + remove_in="0.31.0", +) +def validate_keypoints_fields( + xy: Any, class_id: Any, confidence: Any, data: dict[str, Any] +) -> None: + void(xy, class_id, confidence, data) + + +def _validate_resolution(resolution: Any) -> tuple[int, int]: + if not (isinstance(resolution, tuple) and len(resolution) == 2): + raise ValueError( + f""" + resolution must be a tuple of two integers, got + {type(resolution)} with value {resolution} + """ + ) + w, h = resolution + if not (isinstance(w, int) and isinstance(h, int)): + raise ValueError( + f""" + Both elements in resolution must be integers. + Got types ({type(w)}, {type(h)}) + """ + ) + if w <= 0 or h <= 0: + raise ValueError( + f"Both dimensions in resolution must be positive. Got ({w}, {h})." + ) + return w, h + + +@deprecated( # type: ignore[untyped-decorator] + target=_validate_resolution, + deprecated_in="0.29.0", + remove_in="0.32.0", +) +def validate_resolution(resolution: Any) -> tuple[int, int]: + return void(resolution) # type: ignore[no-any-return] diff --git a/.venv/lib/python3.12/site-packages/supervision/validators/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/supervision/validators/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49ee53337a40a83b39178cba2e2245c5c9803b35 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/supervision/validators/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/__init__.py b/.venv/lib/python3.12/site-packages/sympy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c67ba49409169c49ac5d34f2be365def3c30369b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/__init__.py @@ -0,0 +1,545 @@ +""" +SymPy is a Python library for symbolic mathematics. It aims to become a +full-featured computer algebra system (CAS) while keeping the code as simple +as possible in order to be comprehensible and easily extensible. SymPy is +written entirely in Python. It depends on mpmath, and other external libraries +may be optionally for things like plotting support. + +See the webpage for more information and documentation: + + https://sympy.org + +""" + + +# Keep this in sync with setup.py/pyproject.toml +import sys +if sys.version_info < (3, 9): + raise ImportError("Python version 3.9 or above is required for SymPy.") +del sys + + +try: + import mpmath +except ImportError: + raise ImportError("SymPy now depends on mpmath as an external library. " + "See https://docs.sympy.org/latest/install.html#mpmath for more information.") + +del mpmath + +from sympy.release import __version__ +from sympy.core.cache import lazy_function + +if 'dev' in __version__: + def enable_warnings(): + import warnings + warnings.filterwarnings('default', '.*', DeprecationWarning, module='sympy.*') + del warnings + enable_warnings() + del enable_warnings + + +def __sympy_debug(): + # helper function so we don't import os globally + import os + debug_str = os.getenv('SYMPY_DEBUG', 'False') + if debug_str in ('True', 'False'): + return eval(debug_str) + else: + raise RuntimeError("unrecognized value for SYMPY_DEBUG: %s" % + debug_str) +# Fails py2 test if using type hinting +SYMPY_DEBUG = __sympy_debug() # type: bool + + +from .core import (sympify, SympifyError, cacheit, Basic, Atom, + preorder_traversal, S, Expr, AtomicExpr, UnevaluatedExpr, Symbol, + Wild, Dummy, symbols, var, Number, Float, Rational, Integer, + NumberSymbol, RealNumber, igcd, ilcm, seterr, E, I, nan, oo, pi, zoo, + AlgebraicNumber, comp, mod_inverse, Pow, integer_nthroot, integer_log, + trailing, Mul, prod, Add, Mod, Rel, Eq, Ne, Lt, Le, Gt, Ge, Equality, + GreaterThan, LessThan, Unequality, StrictGreaterThan, StrictLessThan, + vectorize, Lambda, WildFunction, Derivative, diff, FunctionClass, + Function, Subs, expand, PoleError, count_ops, expand_mul, expand_log, + expand_func, expand_trig, expand_complex, expand_multinomial, nfloat, + expand_power_base, expand_power_exp, arity, PrecisionExhausted, N, + evalf, Tuple, Dict, gcd_terms, factor_terms, factor_nc, evaluate, + Catalan, EulerGamma, GoldenRatio, TribonacciConstant, bottom_up, use, + postorder_traversal, default_sort_key, ordered, num_digits) + +from .logic import (to_cnf, to_dnf, to_nnf, And, Or, Not, Xor, Nand, Nor, + Implies, Equivalent, ITE, POSform, SOPform, simplify_logic, bool_map, + true, false, satisfiable) + +from .assumptions import (AppliedPredicate, Predicate, AssumptionsContext, + assuming, Q, ask, register_handler, remove_handler, refine) + +from .polys import (Poly, PurePoly, poly_from_expr, parallel_poly_from_expr, + degree, total_degree, degree_list, LC, LM, LT, pdiv, prem, pquo, + pexquo, div, rem, quo, exquo, half_gcdex, gcdex, invert, + subresultants, resultant, discriminant, cofactors, gcd_list, gcd, + lcm_list, lcm, terms_gcd, trunc, monic, content, primitive, compose, + decompose, sturm, gff_list, gff, sqf_norm, sqf_part, sqf_list, sqf, + factor_list, factor, intervals, refine_root, count_roots, all_roots, + real_roots, nroots, ground_roots, nth_power_roots_poly, cancel, + reduced, groebner, is_zero_dimensional, GroebnerBasis, poly, + symmetrize, horner, interpolate, rational_interpolate, viete, together, + BasePolynomialError, ExactQuotientFailed, PolynomialDivisionFailed, + OperationNotSupported, HeuristicGCDFailed, HomomorphismFailed, + IsomorphismFailed, ExtraneousFactors, EvaluationFailed, + RefinementFailed, CoercionFailed, NotInvertible, NotReversible, + NotAlgebraic, DomainError, PolynomialError, UnificationFailed, + GeneratorsError, GeneratorsNeeded, ComputationFailed, + UnivariatePolynomialError, MultivariatePolynomialError, + PolificationFailed, OptionError, FlagError, minpoly, + minimal_polynomial, primitive_element, field_isomorphism, + to_number_field, isolate, round_two, prime_decomp, prime_valuation, + galois_group, itermonomials, Monomial, lex, grlex, + grevlex, ilex, igrlex, igrevlex, CRootOf, rootof, RootOf, + ComplexRootOf, RootSum, roots, Domain, FiniteField, IntegerRing, + RationalField, RealField, ComplexField, PythonFiniteField, + GMPYFiniteField, PythonIntegerRing, GMPYIntegerRing, PythonRational, + GMPYRationalField, AlgebraicField, PolynomialRing, FractionField, + ExpressionDomain, FF_python, FF_gmpy, ZZ_python, ZZ_gmpy, QQ_python, + QQ_gmpy, GF, FF, ZZ, QQ, ZZ_I, QQ_I, RR, CC, EX, EXRAW, + construct_domain, swinnerton_dyer_poly, cyclotomic_poly, + symmetric_poly, random_poly, interpolating_poly, jacobi_poly, + chebyshevt_poly, chebyshevu_poly, hermite_poly, hermite_prob_poly, + legendre_poly, laguerre_poly, apart, apart_list, assemble_partfrac_list, + Options, ring, xring, vring, sring, field, xfield, vfield, sfield) + +from .series import (Order, O, limit, Limit, gruntz, series, approximants, + residue, EmptySequence, SeqPer, SeqFormula, sequence, SeqAdd, SeqMul, + fourier_series, fps, difference_delta, limit_seq) + +from .functions import (factorial, factorial2, rf, ff, binomial, + RisingFactorial, FallingFactorial, subfactorial, carmichael, + fibonacci, lucas, motzkin, tribonacci, harmonic, bernoulli, bell, euler, + catalan, genocchi, andre, partition, divisor_sigma, legendre_symbol, + jacobi_symbol, kronecker_symbol, mobius, primenu, primeomega, + totient, reduced_totient, primepi, sqrt, root, Min, Max, Id, + real_root, Rem, cbrt, re, im, sign, Abs, conjugate, arg, polar_lift, + periodic_argument, unbranched_argument, principal_branch, transpose, + adjoint, polarify, unpolarify, sin, cos, tan, sec, csc, cot, sinc, + asin, acos, atan, asec, acsc, acot, atan2, exp_polar, exp, ln, log, + LambertW, sinh, cosh, tanh, coth, sech, csch, asinh, acosh, atanh, + acoth, asech, acsch, floor, ceiling, frac, Piecewise, piecewise_fold, + piecewise_exclusive, erf, erfc, erfi, erf2, erfinv, erfcinv, erf2inv, + Ei, expint, E1, li, Li, Si, Ci, Shi, Chi, fresnels, fresnelc, gamma, + lowergamma, uppergamma, polygamma, loggamma, digamma, trigamma, + multigamma, dirichlet_eta, zeta, lerchphi, polylog, stieltjes, Eijk, + LeviCivita, KroneckerDelta, SingularityFunction, DiracDelta, Heaviside, + bspline_basis, bspline_basis_set, interpolating_spline, besselj, + bessely, besseli, besselk, hankel1, hankel2, jn, yn, jn_zeros, hn1, + hn2, airyai, airybi, airyaiprime, airybiprime, marcumq, hyper, + meijerg, appellf1, legendre, assoc_legendre, hermite, hermite_prob, + chebyshevt, chebyshevu, chebyshevu_root, chebyshevt_root, laguerre, + assoc_laguerre, gegenbauer, jacobi, jacobi_normalized, Ynm, Ynm_c, + Znm, elliptic_k, elliptic_f, elliptic_e, elliptic_pi, beta, mathieus, + mathieuc, mathieusprime, mathieucprime, riemann_xi, betainc, betainc_regularized) + +from .ntheory import (nextprime, prevprime, prime, primerange, + randprime, Sieve, sieve, primorial, cycle_length, composite, + compositepi, isprime, divisors, proper_divisors, factorint, + multiplicity, perfect_power, factor_cache, pollard_pm1, pollard_rho, primefactors, + divisor_count, proper_divisor_count, + factorrat, + mersenne_prime_exponent, is_perfect, is_mersenne_prime, is_abundant, + is_deficient, is_amicable, is_carmichael, abundance, npartitions, is_primitive_root, + is_quad_residue, n_order, sqrt_mod, + quadratic_residues, primitive_root, nthroot_mod, is_nthpow_residue, + sqrt_mod_iter, discrete_log, quadratic_congruence, + binomial_coefficients, binomial_coefficients_list, + multinomial_coefficients, continued_fraction_periodic, + continued_fraction_iterator, continued_fraction_reduce, + continued_fraction_convergents, continued_fraction, egyptian_fraction) + +from .concrete import product, Product, summation, Sum + +from .discrete import (fft, ifft, ntt, intt, fwht, ifwht, mobius_transform, + inverse_mobius_transform, convolution, covering_product, + intersecting_product) + +from .simplify import (simplify, hypersimp, hypersimilar, logcombine, + separatevars, posify, besselsimp, kroneckersimp, signsimp, + nsimplify, FU, fu, sqrtdenest, cse, epath, EPath, hyperexpand, + collect, rcollect, radsimp, collect_const, fraction, numer, denom, + trigsimp, exptrigsimp, powsimp, powdenest, combsimp, gammasimp, + ratsimp, ratsimpmodprime) + +from .sets import (Set, Interval, Union, EmptySet, FiniteSet, ProductSet, + Intersection, DisjointUnion, imageset, Complement, SymmetricDifference, ImageSet, + Range, ComplexRegion, Complexes, Reals, Contains, ConditionSet, Ordinal, + OmegaPower, ord0, PowerSet, Naturals, Naturals0, UniversalSet, + Integers, Rationals) + +from .solvers import (solve, solve_linear_system, solve_linear_system_LU, + solve_undetermined_coeffs, nsolve, solve_linear, checksol, det_quick, + inv_quick, check_assumptions, failing_assumptions, diophantine, + rsolve, rsolve_poly, rsolve_ratio, rsolve_hyper, checkodesol, + classify_ode, dsolve, homogeneous_order, solve_poly_system, factor_system, + solve_triangulated, pde_separate, pde_separate_add, pde_separate_mul, + pdsolve, classify_pde, checkpdesol, ode_order, reduce_inequalities, + reduce_abs_inequality, reduce_abs_inequalities, solve_poly_inequality, + solve_rational_inequalities, solve_univariate_inequality, decompogen, + solveset, linsolve, linear_eq_to_matrix, nonlinsolve, substitution) + +from .matrices import (ShapeError, NonSquareMatrixError, GramSchmidt, + casoratian, diag, eye, hessian, jordan_cell, list2numpy, matrix2numpy, + matrix_multiply_elementwise, ones, randMatrix, rot_axis1, rot_axis2, + rot_axis3, symarray, wronskian, zeros, MutableDenseMatrix, + DeferredVector, MatrixBase, Matrix, MutableMatrix, + MutableSparseMatrix, banded, ImmutableDenseMatrix, + ImmutableSparseMatrix, ImmutableMatrix, SparseMatrix, MatrixSlice, + BlockDiagMatrix, BlockMatrix, FunctionMatrix, Identity, Inverse, + MatAdd, MatMul, MatPow, MatrixExpr, MatrixSymbol, Trace, Transpose, + ZeroMatrix, OneMatrix, blockcut, block_collapse, matrix_symbols, + Adjoint, hadamard_product, HadamardProduct, HadamardPower, + Determinant, det, diagonalize_vector, DiagMatrix, DiagonalMatrix, + DiagonalOf, trace, DotProduct, kronecker_product, KroneckerProduct, + PermutationMatrix, MatrixPermute, Permanent, per, rot_ccw_axis1, + rot_ccw_axis2, rot_ccw_axis3, rot_givens) + +from .geometry import (Point, Point2D, Point3D, Line, Ray, Segment, Line2D, + Segment2D, Ray2D, Line3D, Segment3D, Ray3D, Plane, Ellipse, Circle, + Polygon, RegularPolygon, Triangle, rad, deg, are_similar, centroid, + convex_hull, idiff, intersection, closest_points, farthest_points, + GeometryError, Curve, Parabola) + +from .utilities import (flatten, group, take, subsets, variations, + numbered_symbols, cartes, capture, dict_merge, prefixes, postfixes, + sift, topological_sort, unflatten, has_dups, has_variety, reshape, + rotations, filldedent, lambdify, + threaded, xthreaded, public, memoize_property, timed) + +from .integrals import (integrate, Integral, line_integrate, mellin_transform, + inverse_mellin_transform, MellinTransform, InverseMellinTransform, + laplace_transform, laplace_correspondence, laplace_initial_conds, + inverse_laplace_transform, LaplaceTransform, + InverseLaplaceTransform, fourier_transform, inverse_fourier_transform, + FourierTransform, InverseFourierTransform, sine_transform, + inverse_sine_transform, SineTransform, InverseSineTransform, + cosine_transform, inverse_cosine_transform, CosineTransform, + InverseCosineTransform, hankel_transform, inverse_hankel_transform, + HankelTransform, InverseHankelTransform, singularityintegrate) + +from .tensor import (IndexedBase, Idx, Indexed, get_contraction_structure, + get_indices, shape, MutableDenseNDimArray, ImmutableDenseNDimArray, + MutableSparseNDimArray, ImmutableSparseNDimArray, NDimArray, + tensorproduct, tensorcontraction, tensordiagonal, derive_by_array, + permutedims, Array, DenseNDimArray, SparseNDimArray) + +from .parsing import parse_expr + +from .calculus import (euler_equations, singularities, is_increasing, + is_strictly_increasing, is_decreasing, is_strictly_decreasing, + is_monotonic, finite_diff_weights, apply_finite_diff, + differentiate_finite, periodicity, not_empty_in, AccumBounds, + is_convex, stationary_points, minimum, maximum) + +from .algebras import Quaternion + +from .printing import (pager_print, pretty, pretty_print, pprint, + pprint_use_unicode, pprint_try_use_unicode, latex, print_latex, + multiline_latex, mathml, print_mathml, python, print_python, pycode, + ccode, print_ccode, smtlib_code, glsl_code, print_glsl, cxxcode, fcode, + print_fcode, rcode, print_rcode, jscode, print_jscode, julia_code, + mathematica_code, octave_code, rust_code, print_gtk, preview, srepr, + print_tree, StrPrinter, sstr, sstrrepr, TableForm, dotprint, + maple_code, print_maple_code) + +test = lazy_function('sympy.testing.runtests_pytest', 'test') +doctest = lazy_function('sympy.testing.runtests', 'doctest') + +# This module causes conflicts with other modules: +# from .stats import * +# Adds about .04-.05 seconds of import time +# from combinatorics import * +# This module is slow to import: +#from physics import units +from .plotting import plot, textplot, plot_backends, plot_implicit, plot_parametric +from .interactive import init_session, init_printing, interactive_traversal + +evalf._create_evalf_table() + +__all__ = [ + '__version__', + + # sympy.core + 'sympify', 'SympifyError', 'cacheit', 'Basic', 'Atom', + 'preorder_traversal', 'S', 'Expr', 'AtomicExpr', 'UnevaluatedExpr', + 'Symbol', 'Wild', 'Dummy', 'symbols', 'var', 'Number', 'Float', + 'Rational', 'Integer', 'NumberSymbol', 'RealNumber', 'igcd', 'ilcm', + 'seterr', 'E', 'I', 'nan', 'oo', 'pi', 'zoo', 'AlgebraicNumber', 'comp', + 'mod_inverse', 'Pow', 'integer_nthroot', 'integer_log', 'trailing', 'Mul', 'prod', + 'Add', 'Mod', 'Rel', 'Eq', 'Ne', 'Lt', 'Le', 'Gt', 'Ge', 'Equality', + 'GreaterThan', 'LessThan', 'Unequality', 'StrictGreaterThan', + 'StrictLessThan', 'vectorize', 'Lambda', 'WildFunction', 'Derivative', + 'diff', 'FunctionClass', 'Function', 'Subs', 'expand', 'PoleError', + 'count_ops', 'expand_mul', 'expand_log', 'expand_func', 'expand_trig', + 'expand_complex', 'expand_multinomial', 'nfloat', 'expand_power_base', + 'expand_power_exp', 'arity', 'PrecisionExhausted', 'N', 'evalf', 'Tuple', + 'Dict', 'gcd_terms', 'factor_terms', 'factor_nc', 'evaluate', 'Catalan', + 'EulerGamma', 'GoldenRatio', 'TribonacciConstant', 'bottom_up', 'use', + 'postorder_traversal', 'default_sort_key', 'ordered', 'num_digits', + + # sympy.logic + 'to_cnf', 'to_dnf', 'to_nnf', 'And', 'Or', 'Not', 'Xor', 'Nand', 'Nor', + 'Implies', 'Equivalent', 'ITE', 'POSform', 'SOPform', 'simplify_logic', + 'bool_map', 'true', 'false', 'satisfiable', + + # sympy.assumptions + 'AppliedPredicate', 'Predicate', 'AssumptionsContext', 'assuming', 'Q', + 'ask', 'register_handler', 'remove_handler', 'refine', + + # sympy.polys + 'Poly', 'PurePoly', 'poly_from_expr', 'parallel_poly_from_expr', 'degree', + 'total_degree', 'degree_list', 'LC', 'LM', 'LT', 'pdiv', 'prem', 'pquo', + 'pexquo', 'div', 'rem', 'quo', 'exquo', 'half_gcdex', 'gcdex', 'invert', + 'subresultants', 'resultant', 'discriminant', 'cofactors', 'gcd_list', + 'gcd', 'lcm_list', 'lcm', 'terms_gcd', 'trunc', 'monic', 'content', + 'primitive', 'compose', 'decompose', 'sturm', 'gff_list', 'gff', + 'sqf_norm', 'sqf_part', 'sqf_list', 'sqf', 'factor_list', 'factor', + 'intervals', 'refine_root', 'count_roots', 'all_roots', 'real_roots', + 'nroots', 'ground_roots', 'nth_power_roots_poly', 'cancel', 'reduced', + 'groebner', 'is_zero_dimensional', 'GroebnerBasis', 'poly', 'symmetrize', + 'horner', 'interpolate', 'rational_interpolate', 'viete', 'together', + 'BasePolynomialError', 'ExactQuotientFailed', 'PolynomialDivisionFailed', + 'OperationNotSupported', 'HeuristicGCDFailed', 'HomomorphismFailed', + 'IsomorphismFailed', 'ExtraneousFactors', 'EvaluationFailed', + 'RefinementFailed', 'CoercionFailed', 'NotInvertible', 'NotReversible', + 'NotAlgebraic', 'DomainError', 'PolynomialError', 'UnificationFailed', + 'GeneratorsError', 'GeneratorsNeeded', 'ComputationFailed', + 'UnivariatePolynomialError', 'MultivariatePolynomialError', + 'PolificationFailed', 'OptionError', 'FlagError', 'minpoly', + 'minimal_polynomial', 'primitive_element', 'field_isomorphism', + 'to_number_field', 'isolate', 'round_two', 'prime_decomp', + 'prime_valuation', 'galois_group', 'itermonomials', 'Monomial', 'lex', 'grlex', + 'grevlex', 'ilex', 'igrlex', 'igrevlex', 'CRootOf', 'rootof', 'RootOf', + 'ComplexRootOf', 'RootSum', 'roots', 'Domain', 'FiniteField', + 'IntegerRing', 'RationalField', 'RealField', 'ComplexField', + 'PythonFiniteField', 'GMPYFiniteField', 'PythonIntegerRing', + 'GMPYIntegerRing', 'PythonRational', 'GMPYRationalField', + 'AlgebraicField', 'PolynomialRing', 'FractionField', 'ExpressionDomain', + 'FF_python', 'FF_gmpy', 'ZZ_python', 'ZZ_gmpy', 'QQ_python', 'QQ_gmpy', + 'GF', 'FF', 'ZZ', 'QQ', 'ZZ_I', 'QQ_I', 'RR', 'CC', 'EX', 'EXRAW', + 'construct_domain', 'swinnerton_dyer_poly', 'cyclotomic_poly', + 'symmetric_poly', 'random_poly', 'interpolating_poly', 'jacobi_poly', + 'chebyshevt_poly', 'chebyshevu_poly', 'hermite_poly', 'hermite_prob_poly', + 'legendre_poly', 'laguerre_poly', 'apart', 'apart_list', 'assemble_partfrac_list', + 'Options', 'ring', 'xring', 'vring', 'sring', 'field', 'xfield', 'vfield', + 'sfield', + + # sympy.series + 'Order', 'O', 'limit', 'Limit', 'gruntz', 'series', 'approximants', + 'residue', 'EmptySequence', 'SeqPer', 'SeqFormula', 'sequence', 'SeqAdd', + 'SeqMul', 'fourier_series', 'fps', 'difference_delta', 'limit_seq', + + # sympy.functions + 'factorial', 'factorial2', 'rf', 'ff', 'binomial', 'RisingFactorial', + 'FallingFactorial', 'subfactorial', 'carmichael', 'fibonacci', 'lucas', + 'motzkin', 'tribonacci', 'harmonic', 'bernoulli', 'bell', 'euler', 'catalan', + 'genocchi', 'andre', 'partition', 'divisor_sigma', 'legendre_symbol', 'jacobi_symbol', + 'kronecker_symbol', 'mobius', 'primenu', 'primeomega', 'totient', 'primepi', + 'reduced_totient', 'sqrt', 'root', 'Min', 'Max', 'Id', 'real_root', + 'Rem', 'cbrt', 're', 'im', 'sign', 'Abs', 'conjugate', 'arg', 'polar_lift', + 'periodic_argument', 'unbranched_argument', 'principal_branch', + 'transpose', 'adjoint', 'polarify', 'unpolarify', 'sin', 'cos', 'tan', + 'sec', 'csc', 'cot', 'sinc', 'asin', 'acos', 'atan', 'asec', 'acsc', + 'acot', 'atan2', 'exp_polar', 'exp', 'ln', 'log', 'LambertW', 'sinh', + 'cosh', 'tanh', 'coth', 'sech', 'csch', 'asinh', 'acosh', 'atanh', + 'acoth', 'asech', 'acsch', 'floor', 'ceiling', 'frac', 'Piecewise', + 'piecewise_fold', 'piecewise_exclusive', 'erf', 'erfc', 'erfi', 'erf2', + 'erfinv', 'erfcinv', 'erf2inv', 'Ei', 'expint', 'E1', 'li', 'Li', 'Si', + 'Ci', 'Shi', 'Chi', 'fresnels', 'fresnelc', 'gamma', 'lowergamma', + 'uppergamma', 'polygamma', 'loggamma', 'digamma', 'trigamma', 'multigamma', + 'dirichlet_eta', 'zeta', 'lerchphi', 'polylog', 'stieltjes', 'Eijk', 'LeviCivita', + 'KroneckerDelta', 'SingularityFunction', 'DiracDelta', 'Heaviside', + 'bspline_basis', 'bspline_basis_set', 'interpolating_spline', 'besselj', + 'bessely', 'besseli', 'besselk', 'hankel1', 'hankel2', 'jn', 'yn', + 'jn_zeros', 'hn1', 'hn2', 'airyai', 'airybi', 'airyaiprime', + 'airybiprime', 'marcumq', 'hyper', 'meijerg', 'appellf1', 'legendre', + 'assoc_legendre', 'hermite', 'hermite_prob', 'chebyshevt', 'chebyshevu', + 'chebyshevu_root', 'chebyshevt_root', 'laguerre', 'assoc_laguerre', + 'gegenbauer', 'jacobi', 'jacobi_normalized', 'Ynm', 'Ynm_c', 'Znm', + 'elliptic_k', 'elliptic_f', 'elliptic_e', 'elliptic_pi', 'beta', + 'mathieus', 'mathieuc', 'mathieusprime', 'mathieucprime', 'riemann_xi','betainc', + 'betainc_regularized', + + # sympy.ntheory + 'nextprime', 'prevprime', 'prime', 'primerange', 'randprime', + 'Sieve', 'sieve', 'primorial', 'cycle_length', 'composite', 'compositepi', + 'isprime', 'divisors', 'proper_divisors', 'factorint', 'multiplicity', + 'perfect_power', 'pollard_pm1', 'factor_cache', 'pollard_rho', 'primefactors', + 'divisor_count', 'proper_divisor_count', + 'factorrat', + 'mersenne_prime_exponent', 'is_perfect', 'is_mersenne_prime', + 'is_abundant', 'is_deficient', 'is_amicable', 'is_carmichael', 'abundance', + 'npartitions', + 'is_primitive_root', 'is_quad_residue', + 'n_order', 'sqrt_mod', 'quadratic_residues', + 'primitive_root', 'nthroot_mod', 'is_nthpow_residue', 'sqrt_mod_iter', + 'discrete_log', 'quadratic_congruence', 'binomial_coefficients', + 'binomial_coefficients_list', 'multinomial_coefficients', + 'continued_fraction_periodic', 'continued_fraction_iterator', + 'continued_fraction_reduce', 'continued_fraction_convergents', + 'continued_fraction', 'egyptian_fraction', + + # sympy.concrete + 'product', 'Product', 'summation', 'Sum', + + # sympy.discrete + 'fft', 'ifft', 'ntt', 'intt', 'fwht', 'ifwht', 'mobius_transform', + 'inverse_mobius_transform', 'convolution', 'covering_product', + 'intersecting_product', + + # sympy.simplify + 'simplify', 'hypersimp', 'hypersimilar', 'logcombine', 'separatevars', + 'posify', 'besselsimp', 'kroneckersimp', 'signsimp', + 'nsimplify', 'FU', 'fu', 'sqrtdenest', 'cse', 'epath', 'EPath', + 'hyperexpand', 'collect', 'rcollect', 'radsimp', 'collect_const', + 'fraction', 'numer', 'denom', 'trigsimp', 'exptrigsimp', 'powsimp', + 'powdenest', 'combsimp', 'gammasimp', 'ratsimp', 'ratsimpmodprime', + + # sympy.sets + 'Set', 'Interval', 'Union', 'EmptySet', 'FiniteSet', 'ProductSet', + 'Intersection', 'imageset', 'DisjointUnion', 'Complement', 'SymmetricDifference', + 'ImageSet', 'Range', 'ComplexRegion', 'Reals', 'Contains', 'ConditionSet', + 'Ordinal', 'OmegaPower', 'ord0', 'PowerSet', 'Naturals', + 'Naturals0', 'UniversalSet', 'Integers', 'Rationals', 'Complexes', + + # sympy.solvers + 'solve', 'solve_linear_system', 'solve_linear_system_LU', + 'solve_undetermined_coeffs', 'nsolve', 'solve_linear', 'checksol', + 'det_quick', 'inv_quick', 'check_assumptions', 'failing_assumptions', + 'diophantine', 'rsolve', 'rsolve_poly', 'rsolve_ratio', 'rsolve_hyper', + 'checkodesol', 'classify_ode', 'dsolve', 'homogeneous_order', + 'solve_poly_system', 'factor_system', 'solve_triangulated', 'pde_separate', + 'pde_separate_add', 'pde_separate_mul', 'pdsolve', 'classify_pde', + 'checkpdesol', 'ode_order', 'reduce_inequalities', + 'reduce_abs_inequality', 'reduce_abs_inequalities', + 'solve_poly_inequality', 'solve_rational_inequalities', + 'solve_univariate_inequality', 'decompogen', 'solveset', 'linsolve', + 'linear_eq_to_matrix', 'nonlinsolve', 'substitution', + + # sympy.matrices + 'ShapeError', 'NonSquareMatrixError', 'GramSchmidt', 'casoratian', 'diag', + 'eye', 'hessian', 'jordan_cell', 'list2numpy', 'matrix2numpy', + 'matrix_multiply_elementwise', 'ones', 'randMatrix', 'rot_axis1', + 'rot_axis2', 'rot_axis3', 'symarray', 'wronskian', 'zeros', + 'MutableDenseMatrix', 'DeferredVector', 'MatrixBase', 'Matrix', + 'MutableMatrix', 'MutableSparseMatrix', 'banded', 'ImmutableDenseMatrix', + 'ImmutableSparseMatrix', 'ImmutableMatrix', 'SparseMatrix', 'MatrixSlice', + 'BlockDiagMatrix', 'BlockMatrix', 'FunctionMatrix', 'Identity', 'Inverse', + 'MatAdd', 'MatMul', 'MatPow', 'MatrixExpr', 'MatrixSymbol', 'Trace', + 'Transpose', 'ZeroMatrix', 'OneMatrix', 'blockcut', 'block_collapse', + 'matrix_symbols', 'Adjoint', 'hadamard_product', 'HadamardProduct', + 'HadamardPower', 'Determinant', 'det', 'diagonalize_vector', 'DiagMatrix', + 'DiagonalMatrix', 'DiagonalOf', 'trace', 'DotProduct', + 'kronecker_product', 'KroneckerProduct', 'PermutationMatrix', + 'MatrixPermute', 'Permanent', 'per', 'rot_ccw_axis1', 'rot_ccw_axis2', + 'rot_ccw_axis3', 'rot_givens', + + # sympy.geometry + 'Point', 'Point2D', 'Point3D', 'Line', 'Ray', 'Segment', 'Line2D', + 'Segment2D', 'Ray2D', 'Line3D', 'Segment3D', 'Ray3D', 'Plane', 'Ellipse', + 'Circle', 'Polygon', 'RegularPolygon', 'Triangle', 'rad', 'deg', + 'are_similar', 'centroid', 'convex_hull', 'idiff', 'intersection', + 'closest_points', 'farthest_points', 'GeometryError', 'Curve', 'Parabola', + + # sympy.utilities + 'flatten', 'group', 'take', 'subsets', 'variations', 'numbered_symbols', + 'cartes', 'capture', 'dict_merge', 'prefixes', 'postfixes', 'sift', + 'topological_sort', 'unflatten', 'has_dups', 'has_variety', 'reshape', + 'rotations', 'filldedent', 'lambdify', 'threaded', 'xthreaded', + 'public', 'memoize_property', 'timed', + + # sympy.integrals + 'integrate', 'Integral', 'line_integrate', 'mellin_transform', + 'inverse_mellin_transform', 'MellinTransform', 'InverseMellinTransform', + 'laplace_transform', 'inverse_laplace_transform', 'LaplaceTransform', + 'laplace_correspondence', 'laplace_initial_conds', + 'InverseLaplaceTransform', 'fourier_transform', + 'inverse_fourier_transform', 'FourierTransform', + 'InverseFourierTransform', 'sine_transform', 'inverse_sine_transform', + 'SineTransform', 'InverseSineTransform', 'cosine_transform', + 'inverse_cosine_transform', 'CosineTransform', 'InverseCosineTransform', + 'hankel_transform', 'inverse_hankel_transform', 'HankelTransform', + 'InverseHankelTransform', 'singularityintegrate', + + # sympy.tensor + 'IndexedBase', 'Idx', 'Indexed', 'get_contraction_structure', + 'get_indices', 'shape', 'MutableDenseNDimArray', 'ImmutableDenseNDimArray', + 'MutableSparseNDimArray', 'ImmutableSparseNDimArray', 'NDimArray', + 'tensorproduct', 'tensorcontraction', 'tensordiagonal', 'derive_by_array', + 'permutedims', 'Array', 'DenseNDimArray', 'SparseNDimArray', + + # sympy.parsing + 'parse_expr', + + # sympy.calculus + 'euler_equations', 'singularities', 'is_increasing', + 'is_strictly_increasing', 'is_decreasing', 'is_strictly_decreasing', + 'is_monotonic', 'finite_diff_weights', 'apply_finite_diff', + 'differentiate_finite', 'periodicity', 'not_empty_in', + 'AccumBounds', 'is_convex', 'stationary_points', 'minimum', 'maximum', + + # sympy.algebras + 'Quaternion', + + # sympy.printing + 'pager_print', 'pretty', 'pretty_print', 'pprint', 'pprint_use_unicode', + 'pprint_try_use_unicode', 'latex', 'print_latex', 'multiline_latex', + 'mathml', 'print_mathml', 'python', 'print_python', 'pycode', 'ccode', + 'print_ccode', 'smtlib_code', 'glsl_code', 'print_glsl', 'cxxcode', 'fcode', + 'print_fcode', 'rcode', 'print_rcode', 'jscode', 'print_jscode', + 'julia_code', 'mathematica_code', 'octave_code', 'rust_code', 'print_gtk', + 'preview', 'srepr', 'print_tree', 'StrPrinter', 'sstr', 'sstrrepr', + 'TableForm', 'dotprint', 'maple_code', 'print_maple_code', + + # sympy.plotting + 'plot', 'textplot', 'plot_backends', 'plot_implicit', 'plot_parametric', + + # sympy.interactive + 'init_session', 'init_printing', 'interactive_traversal', + + # sympy.testing + 'test', 'doctest', +] + + +#===========================================================================# +# # +# XXX: The names below were importable before SymPy 1.6 using # +# # +# from sympy import * # +# # +# This happened implicitly because there was no __all__ defined in this # +# __init__.py file. Not every package is imported. The list matches what # +# would have been imported before. It is possible that these packages will # +# not be imported by a star-import from sympy in future. # +# # +#===========================================================================# + + +__all__.extend(( + 'algebras', + 'assumptions', + 'calculus', + 'concrete', + 'discrete', + 'external', + 'functions', + 'geometry', + 'interactive', + 'multipledispatch', + 'ntheory', + 'parsing', + 'plotting', + 'polys', + 'printing', + 'release', + 'strategies', + 'tensor', + 'utilities', +)) diff --git a/.venv/lib/python3.12/site-packages/sympy/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..accc9a910868d882464e66c3d8e76709cb170e12 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/__pycache__/abc.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/__pycache__/abc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef324cb42fa638a701a9e73ba88265067034a8a9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/__pycache__/abc.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/__pycache__/conftest.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/__pycache__/conftest.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f9251bcbcd4b55ac6bbd1290452ede7f8aee4a4e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/__pycache__/conftest.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/__pycache__/galgebra.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/__pycache__/galgebra.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a9cdac9046a3b615982bddba03b07d4721b28757 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/__pycache__/galgebra.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/__pycache__/release.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/__pycache__/release.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ab4a6e7db2b5e8676f9ded7acfe8a0adb29691c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/__pycache__/release.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/__pycache__/this.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/__pycache__/this.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08e4af7ddc7e3ba3870b55b35d5969396a3cd7e9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/__pycache__/this.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/abc.py b/.venv/lib/python3.12/site-packages/sympy/abc.py new file mode 100644 index 0000000000000000000000000000000000000000..a6f7a4056e60b0d651becc0b9909bd0ab3c1723f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/abc.py @@ -0,0 +1,111 @@ +""" +This module exports all latin and greek letters as Symbols, so you can +conveniently do + + >>> from sympy.abc import x, y + +instead of the slightly more clunky-looking + + >>> from sympy import symbols + >>> x, y = symbols('x y') + +Caveats +======= + +1. As of the time of writing this, the names ``O``, ``S``, ``I``, ``N``, +``E``, and ``Q`` are colliding with names defined in SymPy. If you import them +from both ``sympy.abc`` and ``sympy``, the second import will "win". +This is an issue only for * imports, which should only be used for short-lived +code such as interactive sessions and throwaway scripts that do not survive +until the next SymPy upgrade, where ``sympy`` may contain a different set of +names. + +2. This module does not define symbol names on demand, i.e. +``from sympy.abc import foo`` will be reported as an error because +``sympy.abc`` does not contain the name ``foo``. To get a symbol named ``foo``, +you still need to use ``Symbol('foo')`` or ``symbols('foo')``. +You can freely mix usage of ``sympy.abc`` and ``Symbol``/``symbols``, though +sticking with one and only one way to get the symbols does tend to make the code +more readable. + +The module also defines some special names to help detect which names clash +with the default SymPy namespace. + +``_clash1`` defines all the single letter variables that clash with +SymPy objects; ``_clash2`` defines the multi-letter clashing symbols; +and ``_clash`` is the union of both. These can be passed for ``locals`` +during sympification if one desires Symbols rather than the non-Symbol +objects for those names. + +Examples +======== + +>>> from sympy import S +>>> from sympy.abc import _clash1, _clash2, _clash +>>> S("Q & C", locals=_clash1) +C & Q +>>> S('pi(x)', locals=_clash2) +pi(x) +>>> S('pi(C, Q)', locals=_clash) +pi(C, Q) + +""" +from __future__ import annotations +from typing import Any + +import string + +from .core import Symbol, symbols +from .core.alphabets import greeks +from sympy.parsing.sympy_parser import null + +##### Symbol definitions ##### + +# Implementation note: The easiest way to avoid typos in the symbols() +# parameter is to copy it from the left-hand side of the assignment. + +a, b, c, d, e, f, g, h, i, j = symbols('a, b, c, d, e, f, g, h, i, j') +k, l, m, n, o, p, q, r, s, t = symbols('k, l, m, n, o, p, q, r, s, t') +u, v, w, x, y, z = symbols('u, v, w, x, y, z') + +A, B, C, D, E, F, G, H, I, J = symbols('A, B, C, D, E, F, G, H, I, J') +K, L, M, N, O, P, Q, R, S, T = symbols('K, L, M, N, O, P, Q, R, S, T') +U, V, W, X, Y, Z = symbols('U, V, W, X, Y, Z') + +alpha, beta, gamma, delta = symbols('alpha, beta, gamma, delta') +epsilon, zeta, eta, theta = symbols('epsilon, zeta, eta, theta') +iota, kappa, lamda, mu = symbols('iota, kappa, lamda, mu') +nu, xi, omicron, pi = symbols('nu, xi, omicron, pi') +rho, sigma, tau, upsilon = symbols('rho, sigma, tau, upsilon') +phi, chi, psi, omega = symbols('phi, chi, psi, omega') + + +##### Clashing-symbols diagnostics ##### + +# We want to know which names in SymPy collide with those in here. +# This is mostly for diagnosing SymPy's namespace during SymPy development. + +_latin = list(string.ascii_letters) +# QOSINE should not be imported as they clash; gamma, pi and zeta clash, too +_greek = list(greeks) # make a copy, so we can mutate it +# Note: We import lamda since lambda is a reserved keyword in Python +_greek.remove("lambda") +_greek.append("lamda") + +ns: dict[str, Any] = {} +exec('from sympy import *', ns) +_clash1: dict[str, Any] = {} +_clash2: dict[str, Any] = {} +while ns: + _k, _ = ns.popitem() + if _k in _greek: + _clash2[_k] = null + _greek.remove(_k) + elif _k in _latin: + _clash1[_k] = null + _latin.remove(_k) +_clash = {} +_clash.update(_clash1) +_clash.update(_clash2) + +del _latin, _greek, Symbol, _k, null diff --git a/.venv/lib/python3.12/site-packages/sympy/algebras/__init__.py b/.venv/lib/python3.12/site-packages/sympy/algebras/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..58013d2e0377a016d1a21fbf21c344ee76765189 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/algebras/__init__.py @@ -0,0 +1,3 @@ +from .quaternion import Quaternion + +__all__ = ["Quaternion",] diff --git a/.venv/lib/python3.12/site-packages/sympy/algebras/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/algebras/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8166e89f08f55fac0e84f274cb6313f5f88a2eb2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/algebras/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/algebras/__pycache__/quaternion.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/algebras/__pycache__/quaternion.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4116d83d57224e586bfd80eb161ee67a62a4add4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/algebras/__pycache__/quaternion.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/algebras/quaternion.py b/.venv/lib/python3.12/site-packages/sympy/algebras/quaternion.py new file mode 100644 index 0000000000000000000000000000000000000000..1bf4b363545128e50294e825461106ef9b41990d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/algebras/quaternion.py @@ -0,0 +1,1666 @@ +from sympy.core.numbers import Rational +from sympy.core.singleton import S +from sympy.core.relational import is_eq +from sympy.functions.elementary.complexes import (conjugate, im, re, sign) +from sympy.functions.elementary.exponential import (exp, log as ln) +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import (acos, asin, atan2) +from sympy.functions.elementary.trigonometric import (cos, sin) +from sympy.simplify.trigsimp import trigsimp +from sympy.integrals.integrals import integrate +from sympy.matrices.dense import MutableDenseMatrix as Matrix +from sympy.core.sympify import sympify, _sympify +from sympy.core.expr import Expr +from sympy.core.logic import fuzzy_not, fuzzy_or +from sympy.utilities.misc import as_int + +from mpmath.libmp.libmpf import prec_to_dps + + +def _check_norm(elements, norm): + """validate if input norm is consistent""" + if norm is not None and norm.is_number: + if norm.is_positive is False: + raise ValueError("Input norm must be positive.") + + numerical = all(i.is_number and i.is_real is True for i in elements) + if numerical and is_eq(norm**2, sum(i**2 for i in elements)) is False: + raise ValueError("Incompatible value for norm.") + + +def _is_extrinsic(seq): + """validate seq and return True if seq is lowercase and False if uppercase""" + if type(seq) != str: + raise ValueError('Expected seq to be a string.') + if len(seq) != 3: + raise ValueError("Expected 3 axes, got `{}`.".format(seq)) + + intrinsic = seq.isupper() + extrinsic = seq.islower() + if not (intrinsic or extrinsic): + raise ValueError("seq must either be fully uppercase (for extrinsic " + "rotations), or fully lowercase, for intrinsic " + "rotations).") + + i, j, k = seq.lower() + if (i == j) or (j == k): + raise ValueError("Consecutive axes must be different") + + bad = set(seq) - set('xyzXYZ') + if bad: + raise ValueError("Expected axes from `seq` to be from " + "['x', 'y', 'z'] or ['X', 'Y', 'Z'], " + "got {}".format(''.join(bad))) + + return extrinsic + + +class Quaternion(Expr): + """Provides basic quaternion operations. + Quaternion objects can be instantiated as ``Quaternion(a, b, c, d)`` + as in $q = a + bi + cj + dk$. + + Parameters + ========== + + norm : None or number + Pre-defined quaternion norm. If a value is given, Quaternion.norm + returns this pre-defined value instead of calculating the norm + + Examples + ======== + + >>> from sympy import Quaternion + >>> q = Quaternion(1, 2, 3, 4) + >>> q + 1 + 2*i + 3*j + 4*k + + Quaternions over complex fields can be defined as: + + >>> from sympy import Quaternion + >>> from sympy import symbols, I + >>> x = symbols('x') + >>> q1 = Quaternion(x, x**3, x, x**2, real_field = False) + >>> q2 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False) + >>> q1 + x + x**3*i + x*j + x**2*k + >>> q2 + (3 + 4*I) + (2 + 5*I)*i + 0*j + (7 + 8*I)*k + + Defining symbolic unit quaternions: + + >>> from sympy import Quaternion + >>> from sympy.abc import w, x, y, z + >>> q = Quaternion(w, x, y, z, norm=1) + >>> q + w + x*i + y*j + z*k + >>> q.norm() + 1 + + References + ========== + + .. [1] https://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/ + .. [2] https://en.wikipedia.org/wiki/Quaternion + + """ + _op_priority = 11.0 + + is_commutative = False + + def __new__(cls, a=0, b=0, c=0, d=0, real_field=True, norm=None): + a, b, c, d = map(sympify, (a, b, c, d)) + + if any(i.is_commutative is False for i in [a, b, c, d]): + raise ValueError("arguments have to be commutative") + obj = super().__new__(cls, a, b, c, d) + obj._real_field = real_field + obj.set_norm(norm) + return obj + + def set_norm(self, norm): + """Sets norm of an already instantiated quaternion. + + Parameters + ========== + + norm : None or number + Pre-defined quaternion norm. If a value is given, Quaternion.norm + returns this pre-defined value instead of calculating the norm + + Examples + ======== + + >>> from sympy import Quaternion + >>> from sympy.abc import a, b, c, d + >>> q = Quaternion(a, b, c, d) + >>> q.norm() + sqrt(a**2 + b**2 + c**2 + d**2) + + Setting the norm: + + >>> q.set_norm(1) + >>> q.norm() + 1 + + Removing set norm: + + >>> q.set_norm(None) + >>> q.norm() + sqrt(a**2 + b**2 + c**2 + d**2) + + """ + norm = sympify(norm) + _check_norm(self.args, norm) + self._norm = norm + + @property + def a(self): + return self.args[0] + + @property + def b(self): + return self.args[1] + + @property + def c(self): + return self.args[2] + + @property + def d(self): + return self.args[3] + + @property + def real_field(self): + return self._real_field + + @property + def product_matrix_left(self): + r"""Returns 4 x 4 Matrix equivalent to a Hamilton product from the + left. This can be useful when treating quaternion elements as column + vectors. Given a quaternion $q = a + bi + cj + dk$ where a, b, c and d + are real numbers, the product matrix from the left is: + + .. math:: + + M = \begin{bmatrix} a &-b &-c &-d \\ + b & a &-d & c \\ + c & d & a &-b \\ + d &-c & b & a \end{bmatrix} + + Examples + ======== + + >>> from sympy import Quaternion + >>> from sympy.abc import a, b, c, d + >>> q1 = Quaternion(1, 0, 0, 1) + >>> q2 = Quaternion(a, b, c, d) + >>> q1.product_matrix_left + Matrix([ + [1, 0, 0, -1], + [0, 1, -1, 0], + [0, 1, 1, 0], + [1, 0, 0, 1]]) + + >>> q1.product_matrix_left * q2.to_Matrix() + Matrix([ + [a - d], + [b - c], + [b + c], + [a + d]]) + + This is equivalent to: + + >>> (q1 * q2).to_Matrix() + Matrix([ + [a - d], + [b - c], + [b + c], + [a + d]]) + """ + return Matrix([ + [self.a, -self.b, -self.c, -self.d], + [self.b, self.a, -self.d, self.c], + [self.c, self.d, self.a, -self.b], + [self.d, -self.c, self.b, self.a]]) + + @property + def product_matrix_right(self): + r"""Returns 4 x 4 Matrix equivalent to a Hamilton product from the + right. This can be useful when treating quaternion elements as column + vectors. Given a quaternion $q = a + bi + cj + dk$ where a, b, c and d + are real numbers, the product matrix from the left is: + + .. math:: + + M = \begin{bmatrix} a &-b &-c &-d \\ + b & a & d &-c \\ + c &-d & a & b \\ + d & c &-b & a \end{bmatrix} + + + Examples + ======== + + >>> from sympy import Quaternion + >>> from sympy.abc import a, b, c, d + >>> q1 = Quaternion(a, b, c, d) + >>> q2 = Quaternion(1, 0, 0, 1) + >>> q2.product_matrix_right + Matrix([ + [1, 0, 0, -1], + [0, 1, 1, 0], + [0, -1, 1, 0], + [1, 0, 0, 1]]) + + Note the switched arguments: the matrix represents the quaternion on + the right, but is still considered as a matrix multiplication from the + left. + + >>> q2.product_matrix_right * q1.to_Matrix() + Matrix([ + [ a - d], + [ b + c], + [-b + c], + [ a + d]]) + + This is equivalent to: + + >>> (q1 * q2).to_Matrix() + Matrix([ + [ a - d], + [ b + c], + [-b + c], + [ a + d]]) + """ + return Matrix([ + [self.a, -self.b, -self.c, -self.d], + [self.b, self.a, self.d, -self.c], + [self.c, -self.d, self.a, self.b], + [self.d, self.c, -self.b, self.a]]) + + def to_Matrix(self, vector_only=False): + """Returns elements of quaternion as a column vector. + By default, a ``Matrix`` of length 4 is returned, with the real part as the + first element. + If ``vector_only`` is ``True``, returns only imaginary part as a Matrix of + length 3. + + Parameters + ========== + + vector_only : bool + If True, only imaginary part is returned. + Default value: False + + Returns + ======= + + Matrix + A column vector constructed by the elements of the quaternion. + + Examples + ======== + + >>> from sympy import Quaternion + >>> from sympy.abc import a, b, c, d + >>> q = Quaternion(a, b, c, d) + >>> q + a + b*i + c*j + d*k + + >>> q.to_Matrix() + Matrix([ + [a], + [b], + [c], + [d]]) + + + >>> q.to_Matrix(vector_only=True) + Matrix([ + [b], + [c], + [d]]) + + """ + if vector_only: + return Matrix(self.args[1:]) + else: + return Matrix(self.args) + + @classmethod + def from_Matrix(cls, elements): + """Returns quaternion from elements of a column vector`. + If vector_only is True, returns only imaginary part as a Matrix of + length 3. + + Parameters + ========== + + elements : Matrix, list or tuple of length 3 or 4. If length is 3, + assume real part is zero. + Default value: False + + Returns + ======= + + Quaternion + A quaternion created from the input elements. + + Examples + ======== + + >>> from sympy import Quaternion + >>> from sympy.abc import a, b, c, d + >>> q = Quaternion.from_Matrix([a, b, c, d]) + >>> q + a + b*i + c*j + d*k + + >>> q = Quaternion.from_Matrix([b, c, d]) + >>> q + 0 + b*i + c*j + d*k + + """ + length = len(elements) + if length != 3 and length != 4: + raise ValueError("Input elements must have length 3 or 4, got {} " + "elements".format(length)) + + if length == 3: + return Quaternion(0, *elements) + else: + return Quaternion(*elements) + + @classmethod + def from_euler(cls, angles, seq): + """Returns quaternion equivalent to rotation represented by the Euler + angles, in the sequence defined by ``seq``. + + Parameters + ========== + + angles : list, tuple or Matrix of 3 numbers + The Euler angles (in radians). + seq : string of length 3 + Represents the sequence of rotations. + For extrinsic rotations, seq must be all lowercase and its elements + must be from the set ``{'x', 'y', 'z'}`` + For intrinsic rotations, seq must be all uppercase and its elements + must be from the set ``{'X', 'Y', 'Z'}`` + + Returns + ======= + + Quaternion + The normalized rotation quaternion calculated from the Euler angles + in the given sequence. + + Examples + ======== + + >>> from sympy import Quaternion + >>> from sympy import pi + >>> q = Quaternion.from_euler([pi/2, 0, 0], 'xyz') + >>> q + sqrt(2)/2 + sqrt(2)/2*i + 0*j + 0*k + + >>> q = Quaternion.from_euler([0, pi/2, pi] , 'zyz') + >>> q + 0 + (-sqrt(2)/2)*i + 0*j + sqrt(2)/2*k + + >>> q = Quaternion.from_euler([0, pi/2, pi] , 'ZYZ') + >>> q + 0 + sqrt(2)/2*i + 0*j + sqrt(2)/2*k + + """ + + if len(angles) != 3: + raise ValueError("3 angles must be given.") + + extrinsic = _is_extrinsic(seq) + i, j, k = seq.lower() + + # get elementary basis vectors + ei = [1 if n == i else 0 for n in 'xyz'] + ej = [1 if n == j else 0 for n in 'xyz'] + ek = [1 if n == k else 0 for n in 'xyz'] + + # calculate distinct quaternions + qi = cls.from_axis_angle(ei, angles[0]) + qj = cls.from_axis_angle(ej, angles[1]) + qk = cls.from_axis_angle(ek, angles[2]) + + if extrinsic: + return trigsimp(qk * qj * qi) + else: + return trigsimp(qi * qj * qk) + + def to_euler(self, seq, angle_addition=True, avoid_square_root=False): + r"""Returns Euler angles representing same rotation as the quaternion, + in the sequence given by ``seq``. This implements the method described + in [1]_. + + For degenerate cases (gymbal lock cases), the third angle is + set to zero. + + Parameters + ========== + + seq : string of length 3 + Represents the sequence of rotations. + For extrinsic rotations, seq must be all lowercase and its elements + must be from the set ``{'x', 'y', 'z'}`` + For intrinsic rotations, seq must be all uppercase and its elements + must be from the set ``{'X', 'Y', 'Z'}`` + + angle_addition : bool + When True, first and third angles are given as an addition and + subtraction of two simpler ``atan2`` expressions. When False, the + first and third angles are each given by a single more complicated + ``atan2`` expression. This equivalent expression is given by: + + .. math:: + + \operatorname{atan_2} (b,a) \pm \operatorname{atan_2} (d,c) = + \operatorname{atan_2} (bc\pm ad, ac\mp bd) + + Default value: True + + avoid_square_root : bool + When True, the second angle is calculated with an expression based + on ``acos``, which is slightly more complicated but avoids a square + root. When False, second angle is calculated with ``atan2``, which + is simpler and can be better for numerical reasons (some + numerical implementations of ``acos`` have problems near zero). + Default value: False + + + Returns + ======= + + Tuple + The Euler angles calculated from the quaternion + + Examples + ======== + + >>> from sympy import Quaternion + >>> from sympy.abc import a, b, c, d + >>> euler = Quaternion(a, b, c, d).to_euler('zyz') + >>> euler + (-atan2(-b, c) + atan2(d, a), + 2*atan2(sqrt(b**2 + c**2), sqrt(a**2 + d**2)), + atan2(-b, c) + atan2(d, a)) + + + References + ========== + + .. [1] https://doi.org/10.1371/journal.pone.0276302 + + """ + if self.is_zero_quaternion(): + raise ValueError('Cannot convert a quaternion with norm 0.') + + angles = [0, 0, 0] + + extrinsic = _is_extrinsic(seq) + i, j, k = seq.lower() + + # get index corresponding to elementary basis vectors + i = 'xyz'.index(i) + 1 + j = 'xyz'.index(j) + 1 + k = 'xyz'.index(k) + 1 + + if not extrinsic: + i, k = k, i + + # check if sequence is symmetric + symmetric = i == k + if symmetric: + k = 6 - i - j + + # parity of the permutation + sign = (i - j) * (j - k) * (k - i) // 2 + + # permutate elements + elements = [self.a, self.b, self.c, self.d] + a = elements[0] + b = elements[i] + c = elements[j] + d = elements[k] * sign + + if not symmetric: + a, b, c, d = a - c, b + d, c + a, d - b + + if avoid_square_root: + if symmetric: + n2 = self.norm()**2 + angles[1] = acos((a * a + b * b - c * c - d * d) / n2) + else: + n2 = 2 * self.norm()**2 + angles[1] = asin((c * c + d * d - a * a - b * b) / n2) + else: + angles[1] = 2 * atan2(sqrt(c * c + d * d), sqrt(a * a + b * b)) + if not symmetric: + angles[1] -= S.Pi / 2 + + # Check for singularities in numerical cases + case = 0 + if is_eq(c, S.Zero) and is_eq(d, S.Zero): + case = 1 + if is_eq(a, S.Zero) and is_eq(b, S.Zero): + case = 2 + + if case == 0: + if angle_addition: + angles[0] = atan2(b, a) + atan2(d, c) + angles[2] = atan2(b, a) - atan2(d, c) + else: + angles[0] = atan2(b*c + a*d, a*c - b*d) + angles[2] = atan2(b*c - a*d, a*c + b*d) + + else: # any degenerate case + angles[2 * (not extrinsic)] = S.Zero + if case == 1: + angles[2 * extrinsic] = 2 * atan2(b, a) + else: + angles[2 * extrinsic] = 2 * atan2(d, c) + angles[2 * extrinsic] *= (-1 if extrinsic else 1) + + # for Tait-Bryan angles + if not symmetric: + angles[0] *= sign + + if extrinsic: + return tuple(angles[::-1]) + else: + return tuple(angles) + + @classmethod + def from_axis_angle(cls, vector, angle): + """Returns a rotation quaternion given the axis and the angle of rotation. + + Parameters + ========== + + vector : tuple of three numbers + The vector representation of the given axis. + angle : number + The angle by which axis is rotated (in radians). + + Returns + ======= + + Quaternion + The normalized rotation quaternion calculated from the given axis and the angle of rotation. + + Examples + ======== + + >>> from sympy import Quaternion + >>> from sympy import pi, sqrt + >>> q = Quaternion.from_axis_angle((sqrt(3)/3, sqrt(3)/3, sqrt(3)/3), 2*pi/3) + >>> q + 1/2 + 1/2*i + 1/2*j + 1/2*k + + """ + (x, y, z) = vector + norm = sqrt(x**2 + y**2 + z**2) + (x, y, z) = (x / norm, y / norm, z / norm) + s = sin(angle * S.Half) + a = cos(angle * S.Half) + b = x * s + c = y * s + d = z * s + + # note that this quaternion is already normalized by construction: + # c^2 + (s*x)^2 + (s*y)^2 + (s*z)^2 = c^2 + s^2*(x^2 + y^2 + z^2) = c^2 + s^2 * 1 = c^2 + s^2 = 1 + # so, what we return is a normalized quaternion + + return cls(a, b, c, d) + + @classmethod + def from_rotation_matrix(cls, M): + """Returns the equivalent quaternion of a matrix. The quaternion will be normalized + only if the matrix is special orthogonal (orthogonal and det(M) = 1). + + Parameters + ========== + + M : Matrix + Input matrix to be converted to equivalent quaternion. M must be special + orthogonal (orthogonal and det(M) = 1) for the quaternion to be normalized. + + Returns + ======= + + Quaternion + The quaternion equivalent to given matrix. + + Examples + ======== + + >>> from sympy import Quaternion + >>> from sympy import Matrix, symbols, cos, sin, trigsimp + >>> x = symbols('x') + >>> M = Matrix([[cos(x), -sin(x), 0], [sin(x), cos(x), 0], [0, 0, 1]]) + >>> q = trigsimp(Quaternion.from_rotation_matrix(M)) + >>> q + sqrt(2)*sqrt(cos(x) + 1)/2 + 0*i + 0*j + sqrt(2 - 2*cos(x))*sign(sin(x))/2*k + + """ + + absQ = M.det()**Rational(1, 3) + + a = sqrt(absQ + M[0, 0] + M[1, 1] + M[2, 2]) / 2 + b = sqrt(absQ + M[0, 0] - M[1, 1] - M[2, 2]) / 2 + c = sqrt(absQ - M[0, 0] + M[1, 1] - M[2, 2]) / 2 + d = sqrt(absQ - M[0, 0] - M[1, 1] + M[2, 2]) / 2 + + b = b * sign(M[2, 1] - M[1, 2]) + c = c * sign(M[0, 2] - M[2, 0]) + d = d * sign(M[1, 0] - M[0, 1]) + + return Quaternion(a, b, c, d) + + def __add__(self, other): + return self.add(other) + + def __radd__(self, other): + return self.add(other) + + def __sub__(self, other): + return self.add(other*-1) + + def __mul__(self, other): + return self._generic_mul(self, _sympify(other)) + + def __rmul__(self, other): + return self._generic_mul(_sympify(other), self) + + def __pow__(self, p): + return self.pow(p) + + def __neg__(self): + return Quaternion(-self.a, -self.b, -self.c, -self.d) + + def __truediv__(self, other): + return self * sympify(other)**-1 + + def __rtruediv__(self, other): + return sympify(other) * self**-1 + + def _eval_Integral(self, *args): + return self.integrate(*args) + + def diff(self, *symbols, **kwargs): + kwargs.setdefault('evaluate', True) + return self.func(*[a.diff(*symbols, **kwargs) for a in self.args]) + + def add(self, other): + """Adds quaternions. + + Parameters + ========== + + other : Quaternion + The quaternion to add to current (self) quaternion. + + Returns + ======= + + Quaternion + The resultant quaternion after adding self to other + + Examples + ======== + + >>> from sympy import Quaternion + >>> from sympy import symbols + >>> q1 = Quaternion(1, 2, 3, 4) + >>> q2 = Quaternion(5, 6, 7, 8) + >>> q1.add(q2) + 6 + 8*i + 10*j + 12*k + >>> q1 + 5 + 6 + 2*i + 3*j + 4*k + >>> x = symbols('x', real = True) + >>> q1.add(x) + (x + 1) + 2*i + 3*j + 4*k + + Quaternions over complex fields : + + >>> from sympy import Quaternion + >>> from sympy import I + >>> q3 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False) + >>> q3.add(2 + 3*I) + (5 + 7*I) + (2 + 5*I)*i + 0*j + (7 + 8*I)*k + + """ + q1 = self + q2 = sympify(other) + + # If q2 is a number or a SymPy expression instead of a quaternion + if not isinstance(q2, Quaternion): + if q1.real_field and q2.is_complex: + return Quaternion(re(q2) + q1.a, im(q2) + q1.b, q1.c, q1.d) + elif q2.is_commutative: + return Quaternion(q1.a + q2, q1.b, q1.c, q1.d) + else: + raise ValueError("Only commutative expressions can be added with a Quaternion.") + + return Quaternion(q1.a + q2.a, q1.b + q2.b, q1.c + q2.c, q1.d + + q2.d) + + def mul(self, other): + """Multiplies quaternions. + + Parameters + ========== + + other : Quaternion or symbol + The quaternion to multiply to current (self) quaternion. + + Returns + ======= + + Quaternion + The resultant quaternion after multiplying self with other + + Examples + ======== + + >>> from sympy import Quaternion + >>> from sympy import symbols + >>> q1 = Quaternion(1, 2, 3, 4) + >>> q2 = Quaternion(5, 6, 7, 8) + >>> q1.mul(q2) + (-60) + 12*i + 30*j + 24*k + >>> q1.mul(2) + 2 + 4*i + 6*j + 8*k + >>> x = symbols('x', real = True) + >>> q1.mul(x) + x + 2*x*i + 3*x*j + 4*x*k + + Quaternions over complex fields : + + >>> from sympy import Quaternion + >>> from sympy import I + >>> q3 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False) + >>> q3.mul(2 + 3*I) + (2 + 3*I)*(3 + 4*I) + (2 + 3*I)*(2 + 5*I)*i + 0*j + (2 + 3*I)*(7 + 8*I)*k + + """ + return self._generic_mul(self, _sympify(other)) + + @staticmethod + def _generic_mul(q1, q2): + """Generic multiplication. + + Parameters + ========== + + q1 : Quaternion or symbol + q2 : Quaternion or symbol + + It is important to note that if neither q1 nor q2 is a Quaternion, + this function simply returns q1 * q2. + + Returns + ======= + + Quaternion + The resultant quaternion after multiplying q1 and q2 + + Examples + ======== + + >>> from sympy import Quaternion + >>> from sympy import Symbol, S + >>> q1 = Quaternion(1, 2, 3, 4) + >>> q2 = Quaternion(5, 6, 7, 8) + >>> Quaternion._generic_mul(q1, q2) + (-60) + 12*i + 30*j + 24*k + >>> Quaternion._generic_mul(q1, S(2)) + 2 + 4*i + 6*j + 8*k + >>> x = Symbol('x', real = True) + >>> Quaternion._generic_mul(q1, x) + x + 2*x*i + 3*x*j + 4*x*k + + Quaternions over complex fields : + + >>> from sympy import I + >>> q3 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False) + >>> Quaternion._generic_mul(q3, 2 + 3*I) + (2 + 3*I)*(3 + 4*I) + (2 + 3*I)*(2 + 5*I)*i + 0*j + (2 + 3*I)*(7 + 8*I)*k + + """ + # None is a Quaternion: + if not isinstance(q1, Quaternion) and not isinstance(q2, Quaternion): + return q1 * q2 + + # If q1 is a number or a SymPy expression instead of a quaternion + if not isinstance(q1, Quaternion): + if q2.real_field and q1.is_complex: + return Quaternion(re(q1), im(q1), 0, 0) * q2 + elif q1.is_commutative: + return Quaternion(q1 * q2.a, q1 * q2.b, q1 * q2.c, q1 * q2.d) + else: + raise ValueError("Only commutative expressions can be multiplied with a Quaternion.") + + # If q2 is a number or a SymPy expression instead of a quaternion + if not isinstance(q2, Quaternion): + if q1.real_field and q2.is_complex: + return q1 * Quaternion(re(q2), im(q2), 0, 0) + elif q2.is_commutative: + return Quaternion(q2 * q1.a, q2 * q1.b, q2 * q1.c, q2 * q1.d) + else: + raise ValueError("Only commutative expressions can be multiplied with a Quaternion.") + + # If any of the quaternions has a fixed norm, pre-compute norm + if q1._norm is None and q2._norm is None: + norm = None + else: + norm = q1.norm() * q2.norm() + + return Quaternion(-q1.b*q2.b - q1.c*q2.c - q1.d*q2.d + q1.a*q2.a, + q1.b*q2.a + q1.c*q2.d - q1.d*q2.c + q1.a*q2.b, + -q1.b*q2.d + q1.c*q2.a + q1.d*q2.b + q1.a*q2.c, + q1.b*q2.c - q1.c*q2.b + q1.d*q2.a + q1.a * q2.d, + norm=norm) + + def _eval_conjugate(self): + """Returns the conjugate of the quaternion.""" + q = self + return Quaternion(q.a, -q.b, -q.c, -q.d, norm=q._norm) + + def norm(self): + """Returns the norm of the quaternion.""" + if self._norm is None: # check if norm is pre-defined + q = self + # trigsimp is used to simplify sin(x)^2 + cos(x)^2 (these terms + # arise when from_axis_angle is used). + return sqrt(trigsimp(q.a**2 + q.b**2 + q.c**2 + q.d**2)) + + return self._norm + + def normalize(self): + """Returns the normalized form of the quaternion.""" + q = self + return q * (1/q.norm()) + + def inverse(self): + """Returns the inverse of the quaternion.""" + q = self + if not q.norm(): + raise ValueError("Cannot compute inverse for a quaternion with zero norm") + return conjugate(q) * (1/q.norm()**2) + + def pow(self, p): + """Finds the pth power of the quaternion. + + Parameters + ========== + + p : int + Power to be applied on quaternion. + + Returns + ======= + + Quaternion + Returns the p-th power of the current quaternion. + Returns the inverse if p = -1. + + Examples + ======== + + >>> from sympy import Quaternion + >>> q = Quaternion(1, 2, 3, 4) + >>> q.pow(4) + 668 + (-224)*i + (-336)*j + (-448)*k + + """ + try: + q, p = self, as_int(p) + except ValueError: + return NotImplemented + + if p < 0: + q, p = q.inverse(), -p + + if p == 1: + return q + + res = Quaternion(1, 0, 0, 0) + while p > 0: + if p & 1: + res *= q + q *= q + p >>= 1 + + return res + + def exp(self): + """Returns the exponential of $q$, given by $e^q$. + + Returns + ======= + + Quaternion + The exponential of the quaternion. + + Examples + ======== + + >>> from sympy import Quaternion + >>> q = Quaternion(1, 2, 3, 4) + >>> q.exp() + E*cos(sqrt(29)) + + 2*sqrt(29)*E*sin(sqrt(29))/29*i + + 3*sqrt(29)*E*sin(sqrt(29))/29*j + + 4*sqrt(29)*E*sin(sqrt(29))/29*k + + """ + # exp(q) = e^a(cos||v|| + v/||v||*sin||v||) + q = self + vector_norm = sqrt(q.b**2 + q.c**2 + q.d**2) + a = exp(q.a) * cos(vector_norm) + b = exp(q.a) * sin(vector_norm) * q.b / vector_norm + c = exp(q.a) * sin(vector_norm) * q.c / vector_norm + d = exp(q.a) * sin(vector_norm) * q.d / vector_norm + + return Quaternion(a, b, c, d) + + def log(self): + r"""Returns the logarithm of the quaternion, given by $\log q$. + + Examples + ======== + + >>> from sympy import Quaternion + >>> q = Quaternion(1, 2, 3, 4) + >>> q.log() + log(sqrt(30)) + + 2*sqrt(29)*acos(sqrt(30)/30)/29*i + + 3*sqrt(29)*acos(sqrt(30)/30)/29*j + + 4*sqrt(29)*acos(sqrt(30)/30)/29*k + + """ + # log(q) = log||q|| + v/||v||*arccos(a/||q||) + q = self + vector_norm = sqrt(q.b**2 + q.c**2 + q.d**2) + q_norm = q.norm() + a = ln(q_norm) + b = q.b * acos(q.a / q_norm) / vector_norm + c = q.c * acos(q.a / q_norm) / vector_norm + d = q.d * acos(q.a / q_norm) / vector_norm + + return Quaternion(a, b, c, d) + + def _eval_subs(self, *args): + elements = [i.subs(*args) for i in self.args] + norm = self._norm + if norm is not None: + norm = norm.subs(*args) + _check_norm(elements, norm) + return Quaternion(*elements, norm=norm) + + def _eval_evalf(self, prec): + """Returns the floating point approximations (decimal numbers) of the quaternion. + + Returns + ======= + + Quaternion + Floating point approximations of quaternion(self) + + Examples + ======== + + >>> from sympy import Quaternion + >>> from sympy import sqrt + >>> q = Quaternion(1/sqrt(1), 1/sqrt(2), 1/sqrt(3), 1/sqrt(4)) + >>> q.evalf() + 1.00000000000000 + + 0.707106781186547*i + + 0.577350269189626*j + + 0.500000000000000*k + + """ + nprec = prec_to_dps(prec) + return Quaternion(*[arg.evalf(n=nprec) for arg in self.args]) + + def pow_cos_sin(self, p): + """Computes the pth power in the cos-sin form. + + Parameters + ========== + + p : int + Power to be applied on quaternion. + + Returns + ======= + + Quaternion + The p-th power in the cos-sin form. + + Examples + ======== + + >>> from sympy import Quaternion + >>> q = Quaternion(1, 2, 3, 4) + >>> q.pow_cos_sin(4) + 900*cos(4*acos(sqrt(30)/30)) + + 1800*sqrt(29)*sin(4*acos(sqrt(30)/30))/29*i + + 2700*sqrt(29)*sin(4*acos(sqrt(30)/30))/29*j + + 3600*sqrt(29)*sin(4*acos(sqrt(30)/30))/29*k + + """ + # q = ||q||*(cos(a) + u*sin(a)) + # q^p = ||q||^p * (cos(p*a) + u*sin(p*a)) + + q = self + (v, angle) = q.to_axis_angle() + q2 = Quaternion.from_axis_angle(v, p * angle) + return q2 * (q.norm()**p) + + def integrate(self, *args): + """Computes integration of quaternion. + + Returns + ======= + + Quaternion + Integration of the quaternion(self) with the given variable. + + Examples + ======== + + Indefinite Integral of quaternion : + + >>> from sympy import Quaternion + >>> from sympy.abc import x + >>> q = Quaternion(1, 2, 3, 4) + >>> q.integrate(x) + x + 2*x*i + 3*x*j + 4*x*k + + Definite integral of quaternion : + + >>> from sympy import Quaternion + >>> from sympy.abc import x + >>> q = Quaternion(1, 2, 3, 4) + >>> q.integrate((x, 1, 5)) + 4 + 8*i + 12*j + 16*k + + """ + return Quaternion(integrate(self.a, *args), integrate(self.b, *args), + integrate(self.c, *args), integrate(self.d, *args)) + + @staticmethod + def rotate_point(pin, r): + """Returns the coordinates of the point pin (a 3 tuple) after rotation. + + Parameters + ========== + + pin : tuple + A 3-element tuple of coordinates of a point which needs to be + rotated. + r : Quaternion or tuple + Axis and angle of rotation. + + It's important to note that when r is a tuple, it must be of the form + (axis, angle) + + Returns + ======= + + tuple + The coordinates of the point after rotation. + + Examples + ======== + + >>> from sympy import Quaternion + >>> from sympy import symbols, trigsimp, cos, sin + >>> x = symbols('x') + >>> q = Quaternion(cos(x/2), 0, 0, sin(x/2)) + >>> trigsimp(Quaternion.rotate_point((1, 1, 1), q)) + (sqrt(2)*cos(x + pi/4), sqrt(2)*sin(x + pi/4), 1) + >>> (axis, angle) = q.to_axis_angle() + >>> trigsimp(Quaternion.rotate_point((1, 1, 1), (axis, angle))) + (sqrt(2)*cos(x + pi/4), sqrt(2)*sin(x + pi/4), 1) + + """ + if isinstance(r, tuple): + # if r is of the form (vector, angle) + q = Quaternion.from_axis_angle(r[0], r[1]) + else: + # if r is a quaternion + q = r.normalize() + pout = q * Quaternion(0, pin[0], pin[1], pin[2]) * conjugate(q) + return (pout.b, pout.c, pout.d) + + def to_axis_angle(self): + """Returns the axis and angle of rotation of a quaternion. + + Returns + ======= + + tuple + Tuple of (axis, angle) + + Examples + ======== + + >>> from sympy import Quaternion + >>> q = Quaternion(1, 1, 1, 1) + >>> (axis, angle) = q.to_axis_angle() + >>> axis + (sqrt(3)/3, sqrt(3)/3, sqrt(3)/3) + >>> angle + 2*pi/3 + + """ + q = self + if q.a.is_negative: + q = q * -1 + + q = q.normalize() + angle = trigsimp(2 * acos(q.a)) + + # Since quaternion is normalised, q.a is less than 1. + s = sqrt(1 - q.a*q.a) + + x = trigsimp(q.b / s) + y = trigsimp(q.c / s) + z = trigsimp(q.d / s) + + v = (x, y, z) + t = (v, angle) + + return t + + def to_rotation_matrix(self, v=None, homogeneous=True): + """Returns the equivalent rotation transformation matrix of the quaternion + which represents rotation about the origin if ``v`` is not passed. + + Parameters + ========== + + v : tuple or None + Default value: None + homogeneous : bool + When True, gives an expression that may be more efficient for + symbolic calculations but less so for direct evaluation. Both + formulas are mathematically equivalent. + Default value: True + + Returns + ======= + + tuple + Returns the equivalent rotation transformation matrix of the quaternion + which represents rotation about the origin if v is not passed. + + Examples + ======== + + >>> from sympy import Quaternion + >>> from sympy import symbols, trigsimp, cos, sin + >>> x = symbols('x') + >>> q = Quaternion(cos(x/2), 0, 0, sin(x/2)) + >>> trigsimp(q.to_rotation_matrix()) + Matrix([ + [cos(x), -sin(x), 0], + [sin(x), cos(x), 0], + [ 0, 0, 1]]) + + Generates a 4x4 transformation matrix (used for rotation about a point + other than the origin) if the point(v) is passed as an argument. + """ + + q = self + s = q.norm()**-2 + + # diagonal elements are different according to parameter normal + if homogeneous: + m00 = s*(q.a**2 + q.b**2 - q.c**2 - q.d**2) + m11 = s*(q.a**2 - q.b**2 + q.c**2 - q.d**2) + m22 = s*(q.a**2 - q.b**2 - q.c**2 + q.d**2) + else: + m00 = 1 - 2*s*(q.c**2 + q.d**2) + m11 = 1 - 2*s*(q.b**2 + q.d**2) + m22 = 1 - 2*s*(q.b**2 + q.c**2) + + m01 = 2*s*(q.b*q.c - q.d*q.a) + m02 = 2*s*(q.b*q.d + q.c*q.a) + + m10 = 2*s*(q.b*q.c + q.d*q.a) + m12 = 2*s*(q.c*q.d - q.b*q.a) + + m20 = 2*s*(q.b*q.d - q.c*q.a) + m21 = 2*s*(q.c*q.d + q.b*q.a) + + if not v: + return Matrix([[m00, m01, m02], [m10, m11, m12], [m20, m21, m22]]) + + else: + (x, y, z) = v + + m03 = x - x*m00 - y*m01 - z*m02 + m13 = y - x*m10 - y*m11 - z*m12 + m23 = z - x*m20 - y*m21 - z*m22 + m30 = m31 = m32 = 0 + m33 = 1 + + return Matrix([[m00, m01, m02, m03], [m10, m11, m12, m13], + [m20, m21, m22, m23], [m30, m31, m32, m33]]) + + def scalar_part(self): + r"""Returns scalar part($\mathbf{S}(q)$) of the quaternion q. + + Explanation + =========== + + Given a quaternion $q = a + bi + cj + dk$, returns $\mathbf{S}(q) = a$. + + Examples + ======== + + >>> from sympy.algebras.quaternion import Quaternion + >>> q = Quaternion(4, 8, 13, 12) + >>> q.scalar_part() + 4 + + """ + + return self.a + + def vector_part(self): + r""" + Returns $\mathbf{V}(q)$, the vector part of the quaternion $q$. + + Explanation + =========== + + Given a quaternion $q = a + bi + cj + dk$, returns $\mathbf{V}(q) = bi + cj + dk$. + + Examples + ======== + + >>> from sympy.algebras.quaternion import Quaternion + >>> q = Quaternion(1, 1, 1, 1) + >>> q.vector_part() + 0 + 1*i + 1*j + 1*k + + >>> q = Quaternion(4, 8, 13, 12) + >>> q.vector_part() + 0 + 8*i + 13*j + 12*k + + """ + + return Quaternion(0, self.b, self.c, self.d) + + def axis(self): + r""" + Returns $\mathbf{Ax}(q)$, the axis of the quaternion $q$. + + Explanation + =========== + + Given a quaternion $q = a + bi + cj + dk$, returns $\mathbf{Ax}(q)$ i.e., the versor of the vector part of that quaternion + equal to $\mathbf{U}[\mathbf{V}(q)]$. + The axis is always an imaginary unit with square equal to $-1 + 0i + 0j + 0k$. + + Examples + ======== + + >>> from sympy.algebras.quaternion import Quaternion + >>> q = Quaternion(1, 1, 1, 1) + >>> q.axis() + 0 + sqrt(3)/3*i + sqrt(3)/3*j + sqrt(3)/3*k + + See Also + ======== + + vector_part + + """ + axis = self.vector_part().normalize() + + return Quaternion(0, axis.b, axis.c, axis.d) + + def is_pure(self): + """ + Returns true if the quaternion is pure, false if the quaternion is not pure + or returns none if it is unknown. + + Explanation + =========== + + A pure quaternion (also a vector quaternion) is a quaternion with scalar + part equal to 0. + + Examples + ======== + + >>> from sympy.algebras.quaternion import Quaternion + >>> q = Quaternion(0, 8, 13, 12) + >>> q.is_pure() + True + + See Also + ======== + scalar_part + + """ + + return self.a.is_zero + + def is_zero_quaternion(self): + """ + Returns true if the quaternion is a zero quaternion or false if it is not a zero quaternion + and None if the value is unknown. + + Explanation + =========== + + A zero quaternion is a quaternion with both scalar part and + vector part equal to 0. + + Examples + ======== + + >>> from sympy.algebras.quaternion import Quaternion + >>> q = Quaternion(1, 0, 0, 0) + >>> q.is_zero_quaternion() + False + + >>> q = Quaternion(0, 0, 0, 0) + >>> q.is_zero_quaternion() + True + + See Also + ======== + scalar_part + vector_part + + """ + + return self.norm().is_zero + + def angle(self): + r""" + Returns the angle of the quaternion measured in the real-axis plane. + + Explanation + =========== + + Given a quaternion $q = a + bi + cj + dk$ where $a$, $b$, $c$ and $d$ + are real numbers, returns the angle of the quaternion given by + + .. math:: + \theta := 2 \operatorname{atan_2}\left(\sqrt{b^2 + c^2 + d^2}, {a}\right) + + Examples + ======== + + >>> from sympy.algebras.quaternion import Quaternion + >>> q = Quaternion(1, 4, 4, 4) + >>> q.angle() + 2*atan(4*sqrt(3)) + + """ + + return 2 * atan2(self.vector_part().norm(), self.scalar_part()) + + + def arc_coplanar(self, other): + """ + Returns True if the transformation arcs represented by the input quaternions happen in the same plane. + + Explanation + =========== + + Two quaternions are said to be coplanar (in this arc sense) when their axes are parallel. + The plane of a quaternion is the one normal to its axis. + + Parameters + ========== + + other : a Quaternion + + Returns + ======= + + True : if the planes of the two quaternions are the same, apart from its orientation/sign. + False : if the planes of the two quaternions are not the same, apart from its orientation/sign. + None : if plane of either of the quaternion is unknown. + + Examples + ======== + + >>> from sympy.algebras.quaternion import Quaternion + >>> q1 = Quaternion(1, 4, 4, 4) + >>> q2 = Quaternion(3, 8, 8, 8) + >>> Quaternion.arc_coplanar(q1, q2) + True + + >>> q1 = Quaternion(2, 8, 13, 12) + >>> Quaternion.arc_coplanar(q1, q2) + False + + See Also + ======== + + vector_coplanar + is_pure + + """ + if (self.is_zero_quaternion()) or (other.is_zero_quaternion()): + raise ValueError('Neither of the given quaternions can be 0') + + return fuzzy_or([(self.axis() - other.axis()).is_zero_quaternion(), (self.axis() + other.axis()).is_zero_quaternion()]) + + @classmethod + def vector_coplanar(cls, q1, q2, q3): + r""" + Returns True if the axis of the pure quaternions seen as 3D vectors + ``q1``, ``q2``, and ``q3`` are coplanar. + + Explanation + =========== + + Three pure quaternions are vector coplanar if the quaternions seen as 3D vectors are coplanar. + + Parameters + ========== + + q1 + A pure Quaternion. + q2 + A pure Quaternion. + q3 + A pure Quaternion. + + Returns + ======= + + True : if the axis of the pure quaternions seen as 3D vectors + q1, q2, and q3 are coplanar. + False : if the axis of the pure quaternions seen as 3D vectors + q1, q2, and q3 are not coplanar. + None : if the axis of the pure quaternions seen as 3D vectors + q1, q2, and q3 are coplanar is unknown. + + Examples + ======== + + >>> from sympy.algebras.quaternion import Quaternion + >>> q1 = Quaternion(0, 4, 4, 4) + >>> q2 = Quaternion(0, 8, 8, 8) + >>> q3 = Quaternion(0, 24, 24, 24) + >>> Quaternion.vector_coplanar(q1, q2, q3) + True + + >>> q1 = Quaternion(0, 8, 16, 8) + >>> q2 = Quaternion(0, 8, 3, 12) + >>> Quaternion.vector_coplanar(q1, q2, q3) + False + + See Also + ======== + + axis + is_pure + + """ + + if fuzzy_not(q1.is_pure()) or fuzzy_not(q2.is_pure()) or fuzzy_not(q3.is_pure()): + raise ValueError('The given quaternions must be pure') + + M = Matrix([[q1.b, q1.c, q1.d], [q2.b, q2.c, q2.d], [q3.b, q3.c, q3.d]]).det() + return M.is_zero + + def parallel(self, other): + """ + Returns True if the two pure quaternions seen as 3D vectors are parallel. + + Explanation + =========== + + Two pure quaternions are called parallel when their vector product is commutative which + implies that the quaternions seen as 3D vectors have same direction. + + Parameters + ========== + + other : a Quaternion + + Returns + ======= + + True : if the two pure quaternions seen as 3D vectors are parallel. + False : if the two pure quaternions seen as 3D vectors are not parallel. + None : if the two pure quaternions seen as 3D vectors are parallel is unknown. + + Examples + ======== + + >>> from sympy.algebras.quaternion import Quaternion + >>> q = Quaternion(0, 4, 4, 4) + >>> q1 = Quaternion(0, 8, 8, 8) + >>> q.parallel(q1) + True + + >>> q1 = Quaternion(0, 8, 13, 12) + >>> q.parallel(q1) + False + + """ + + if fuzzy_not(self.is_pure()) or fuzzy_not(other.is_pure()): + raise ValueError('The provided quaternions must be pure') + + return (self*other - other*self).is_zero_quaternion() + + def orthogonal(self, other): + """ + Returns the orthogonality of two quaternions. + + Explanation + =========== + + Two pure quaternions are called orthogonal when their product is anti-commutative. + + Parameters + ========== + + other : a Quaternion + + Returns + ======= + + True : if the two pure quaternions seen as 3D vectors are orthogonal. + False : if the two pure quaternions seen as 3D vectors are not orthogonal. + None : if the two pure quaternions seen as 3D vectors are orthogonal is unknown. + + Examples + ======== + + >>> from sympy.algebras.quaternion import Quaternion + >>> q = Quaternion(0, 4, 4, 4) + >>> q1 = Quaternion(0, 8, 8, 8) + >>> q.orthogonal(q1) + False + + >>> q1 = Quaternion(0, 2, 2, 0) + >>> q = Quaternion(0, 2, -2, 0) + >>> q.orthogonal(q1) + True + + """ + + if fuzzy_not(self.is_pure()) or fuzzy_not(other.is_pure()): + raise ValueError('The given quaternions must be pure') + + return (self*other + other*self).is_zero_quaternion() + + def index_vector(self): + r""" + Returns the index vector of the quaternion. + + Explanation + =========== + + The index vector is given by $\mathbf{T}(q)$, the norm (or magnitude) of + the quaternion $q$, multiplied by $\mathbf{Ax}(q)$, the axis of $q$. + + Returns + ======= + + Quaternion: representing index vector of the provided quaternion. + + Examples + ======== + + >>> from sympy.algebras.quaternion import Quaternion + >>> q = Quaternion(2, 4, 2, 4) + >>> q.index_vector() + 0 + 4*sqrt(10)/3*i + 2*sqrt(10)/3*j + 4*sqrt(10)/3*k + + See Also + ======== + + axis + norm + + """ + + return self.norm() * self.axis() + + def mensor(self): + """ + Returns the natural logarithm of the norm(magnitude) of the quaternion. + + Examples + ======== + + >>> from sympy.algebras.quaternion import Quaternion + >>> q = Quaternion(2, 4, 2, 4) + >>> q.mensor() + log(2*sqrt(10)) + >>> q.norm() + 2*sqrt(10) + + See Also + ======== + + norm + + """ + + return ln(self.norm()) diff --git a/.venv/lib/python3.12/site-packages/sympy/algebras/tests/__init__.py b/.venv/lib/python3.12/site-packages/sympy/algebras/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/sympy/algebras/tests/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/algebras/tests/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd1e7237c724d9ba89100cee34dc50327ca64d2d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/algebras/tests/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/algebras/tests/__pycache__/test_quaternion.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/algebras/tests/__pycache__/test_quaternion.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8fd9a4a45efe4ac9cb8f0d8ecfc0114fb75f6408 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/algebras/tests/__pycache__/test_quaternion.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/algebras/tests/test_quaternion.py b/.venv/lib/python3.12/site-packages/sympy/algebras/tests/test_quaternion.py new file mode 100644 index 0000000000000000000000000000000000000000..a4331cd6afa05c96e8e11d59df4b7520e4810930 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/algebras/tests/test_quaternion.py @@ -0,0 +1,437 @@ +from sympy.testing.pytest import slow +from sympy.core.function import diff +from sympy.core.function import expand +from sympy.core.numbers import (E, I, Rational, pi) +from sympy.core.singleton import S +from sympy.core.symbol import (Symbol, symbols) +from sympy.functions.elementary.complexes import (Abs, conjugate, im, re, sign) +from sympy.functions.elementary.exponential import log +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import (acos, asin, cos, sin, atan2, atan) +from sympy.integrals.integrals import integrate +from sympy.matrices.dense import Matrix +from sympy.simplify import simplify +from sympy.simplify.trigsimp import trigsimp +from sympy.algebras.quaternion import Quaternion +from sympy.testing.pytest import raises +import math +from itertools import permutations, product + +w, x, y, z = symbols('w:z') +phi = symbols('phi') + +def test_quaternion_construction(): + q = Quaternion(w, x, y, z) + assert q + q == Quaternion(2*w, 2*x, 2*y, 2*z) + + q2 = Quaternion.from_axis_angle((sqrt(3)/3, sqrt(3)/3, sqrt(3)/3), + pi*Rational(2, 3)) + assert q2 == Quaternion(S.Half, S.Half, + S.Half, S.Half) + + M = Matrix([[cos(phi), -sin(phi), 0], [sin(phi), cos(phi), 0], [0, 0, 1]]) + q3 = trigsimp(Quaternion.from_rotation_matrix(M)) + assert q3 == Quaternion( + sqrt(2)*sqrt(cos(phi) + 1)/2, 0, 0, sqrt(2 - 2*cos(phi))*sign(sin(phi))/2) + + nc = Symbol('nc', commutative=False) + raises(ValueError, lambda: Quaternion(w, x, nc, z)) + + +def test_quaternion_construction_norm(): + q1 = Quaternion(*symbols('a:d')) + + q2 = Quaternion(w, x, y, z) + assert expand((q1*q2).norm()**2 - (q1.norm()**2 * q2.norm()**2)) == 0 + + q3 = Quaternion(w, x, y, z, norm=1) + assert (q1 * q3).norm() == q1.norm() + + +def test_issue_25254(): + # calculating the inverse cached the norm which caused problems + # when multiplying + p = Quaternion(1, 0, 0, 0) + q = Quaternion.from_axis_angle((1, 1, 1), 3 * math.pi/4) + qi = q.inverse() # this operation cached the norm + test = q * p * qi + assert ((test - p).norm() < 1E-10) + + +def test_to_and_from_Matrix(): + q = Quaternion(w, x, y, z) + q_full = Quaternion.from_Matrix(q.to_Matrix()) + q_vect = Quaternion.from_Matrix(q.to_Matrix(True)) + assert (q - q_full).is_zero_quaternion() + assert (q.vector_part() - q_vect).is_zero_quaternion() + + +def test_product_matrices(): + q1 = Quaternion(w, x, y, z) + q2 = Quaternion(*(symbols("a:d"))) + assert (q1 * q2).to_Matrix() == q1.product_matrix_left * q2.to_Matrix() + assert (q1 * q2).to_Matrix() == q2.product_matrix_right * q1.to_Matrix() + + R1 = (q1.product_matrix_left * q1.product_matrix_right.T)[1:, 1:] + R2 = simplify(q1.to_rotation_matrix()*q1.norm()**2) + assert R1 == R2 + + +def test_quaternion_axis_angle(): + + test_data = [ # axis, angle, expected_quaternion + ((1, 0, 0), 0, (1, 0, 0, 0)), + ((1, 0, 0), pi/2, (sqrt(2)/2, sqrt(2)/2, 0, 0)), + ((0, 1, 0), pi/2, (sqrt(2)/2, 0, sqrt(2)/2, 0)), + ((0, 0, 1), pi/2, (sqrt(2)/2, 0, 0, sqrt(2)/2)), + ((1, 0, 0), pi, (0, 1, 0, 0)), + ((0, 1, 0), pi, (0, 0, 1, 0)), + ((0, 0, 1), pi, (0, 0, 0, 1)), + ((1, 1, 1), pi, (0, 1/sqrt(3),1/sqrt(3),1/sqrt(3))), + ((sqrt(3)/3, sqrt(3)/3, sqrt(3)/3), pi*2/3, (S.Half, S.Half, S.Half, S.Half)) + ] + + for axis, angle, expected in test_data: + assert Quaternion.from_axis_angle(axis, angle) == Quaternion(*expected) + + +def test_quaternion_axis_angle_simplification(): + result = Quaternion.from_axis_angle((1, 2, 3), asin(4)) + assert result.a == cos(asin(4)/2) + assert result.b == sqrt(14)*sin(asin(4)/2)/14 + assert result.c == sqrt(14)*sin(asin(4)/2)/7 + assert result.d == 3*sqrt(14)*sin(asin(4)/2)/14 + +def test_quaternion_complex_real_addition(): + a = symbols("a", complex=True) + b = symbols("b", real=True) + # This symbol is not complex: + c = symbols("c", commutative=False) + + q = Quaternion(w, x, y, z) + assert a + q == Quaternion(w + re(a), x + im(a), y, z) + assert 1 + q == Quaternion(1 + w, x, y, z) + assert I + q == Quaternion(w, 1 + x, y, z) + assert b + q == Quaternion(w + b, x, y, z) + raises(ValueError, lambda: c + q) + raises(ValueError, lambda: q * c) + raises(ValueError, lambda: c * q) + + assert -q == Quaternion(-w, -x, -y, -z) + + q1 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False) + q2 = Quaternion(1, 4, 7, 8) + + assert q1 + (2 + 3*I) == Quaternion(5 + 7*I, 2 + 5*I, 0, 7 + 8*I) + assert q2 + (2 + 3*I) == Quaternion(3, 7, 7, 8) + assert q1 * (2 + 3*I) == \ + Quaternion((2 + 3*I)*(3 + 4*I), (2 + 3*I)*(2 + 5*I), 0, (2 + 3*I)*(7 + 8*I)) + assert q2 * (2 + 3*I) == Quaternion(-10, 11, 38, -5) + + q1 = Quaternion(1, 2, 3, 4) + q0 = Quaternion(0, 0, 0, 0) + assert q1 + q0 == q1 + assert q1 - q0 == q1 + assert q1 - q1 == q0 + + +def test_quaternion_subs(): + q = Quaternion.from_axis_angle((0, 0, 1), phi) + assert q.subs(phi, 0) == Quaternion(1, 0, 0, 0) + + +def test_quaternion_evalf(): + assert (Quaternion(sqrt(2), 0, 0, sqrt(3)).evalf() == + Quaternion(sqrt(2).evalf(), 0, 0, sqrt(3).evalf())) + assert (Quaternion(1/sqrt(2), 0, 0, 1/sqrt(2)).evalf() == + Quaternion((1/sqrt(2)).evalf(), 0, 0, (1/sqrt(2)).evalf())) + + +def test_quaternion_functions(): + q = Quaternion(w, x, y, z) + q1 = Quaternion(1, 2, 3, 4) + q0 = Quaternion(0, 0, 0, 0) + + assert conjugate(q) == Quaternion(w, -x, -y, -z) + assert q.norm() == sqrt(w**2 + x**2 + y**2 + z**2) + assert q.normalize() == Quaternion(w, x, y, z) / sqrt(w**2 + x**2 + y**2 + z**2) + assert q.inverse() == Quaternion(w, -x, -y, -z) / (w**2 + x**2 + y**2 + z**2) + assert q.inverse() == q.pow(-1) + raises(ValueError, lambda: q0.inverse()) + assert q.pow(2) == Quaternion(w**2 - x**2 - y**2 - z**2, 2*w*x, 2*w*y, 2*w*z) + assert q**(2) == Quaternion(w**2 - x**2 - y**2 - z**2, 2*w*x, 2*w*y, 2*w*z) + assert q1.pow(-2) == Quaternion( + Rational(-7, 225), Rational(-1, 225), Rational(-1, 150), Rational(-2, 225)) + assert q1**(-2) == Quaternion( + Rational(-7, 225), Rational(-1, 225), Rational(-1, 150), Rational(-2, 225)) + assert q1.pow(-0.5) == NotImplemented + raises(TypeError, lambda: q1**(-0.5)) + + assert q1.exp() == \ + Quaternion(E * cos(sqrt(29)), + 2 * sqrt(29) * E * sin(sqrt(29)) / 29, + 3 * sqrt(29) * E * sin(sqrt(29)) / 29, + 4 * sqrt(29) * E * sin(sqrt(29)) / 29) + assert q1.log() == \ + Quaternion(log(sqrt(30)), + 2 * sqrt(29) * acos(sqrt(30)/30) / 29, + 3 * sqrt(29) * acos(sqrt(30)/30) / 29, + 4 * sqrt(29) * acos(sqrt(30)/30) / 29) + + assert q1.pow_cos_sin(2) == \ + Quaternion(30 * cos(2 * acos(sqrt(30)/30)), + 60 * sqrt(29) * sin(2 * acos(sqrt(30)/30)) / 29, + 90 * sqrt(29) * sin(2 * acos(sqrt(30)/30)) / 29, + 120 * sqrt(29) * sin(2 * acos(sqrt(30)/30)) / 29) + + assert diff(Quaternion(x, x, x, x), x) == Quaternion(1, 1, 1, 1) + + assert integrate(Quaternion(x, x, x, x), x) == \ + Quaternion(x**2 / 2, x**2 / 2, x**2 / 2, x**2 / 2) + + assert Quaternion(1, x, x**2, x**3).integrate(x) == \ + Quaternion(x, x**2/2, x**3/3, x**4/4) + + assert Quaternion(sin(x), cos(x), sin(2*x), cos(2*x)).integrate(x) == \ + Quaternion(-cos(x), sin(x), -cos(2*x)/2, sin(2*x)/2) + + assert Quaternion(x**2, y**2, z**2, x*y*z).integrate(x, y) == \ + Quaternion(x**3*y/3, x*y**3/3, x*y*z**2, x**2*y**2*z/4) + + assert Quaternion.rotate_point((1, 1, 1), q1) == (S.One / 5, 1, S(7) / 5) + n = Symbol('n') + raises(TypeError, lambda: q1**n) + n = Symbol('n', integer=True) + raises(TypeError, lambda: q1**n) + + assert Quaternion(22, 23, 55, 8).scalar_part() == 22 + assert Quaternion(w, x, y, z).scalar_part() == w + + assert Quaternion(22, 23, 55, 8).vector_part() == Quaternion(0, 23, 55, 8) + assert Quaternion(w, x, y, z).vector_part() == Quaternion(0, x, y, z) + + assert q1.axis() == Quaternion(0, 2*sqrt(29)/29, 3*sqrt(29)/29, 4*sqrt(29)/29) + assert q1.axis().pow(2) == Quaternion(-1, 0, 0, 0) + assert q0.axis().scalar_part() == 0 + assert (q.axis() == Quaternion(0, + x/sqrt(x**2 + y**2 + z**2), + y/sqrt(x**2 + y**2 + z**2), + z/sqrt(x**2 + y**2 + z**2))) + + assert q0.is_pure() is True + assert q1.is_pure() is False + assert Quaternion(0, 0, 0, 3).is_pure() is True + assert Quaternion(0, 2, 10, 3).is_pure() is True + assert Quaternion(w, 2, 10, 3).is_pure() is None + + assert q1.angle() == 2*atan(sqrt(29)) + assert q.angle() == 2*atan2(sqrt(x**2 + y**2 + z**2), w) + + assert Quaternion.arc_coplanar(q1, Quaternion(2, 4, 6, 8)) is True + assert Quaternion.arc_coplanar(q1, Quaternion(1, -2, -3, -4)) is True + assert Quaternion.arc_coplanar(q1, Quaternion(1, 8, 12, 16)) is True + assert Quaternion.arc_coplanar(q1, Quaternion(1, 2, 3, 4)) is True + assert Quaternion.arc_coplanar(q1, Quaternion(w, 4, 6, 8)) is True + assert Quaternion.arc_coplanar(q1, Quaternion(2, 7, 4, 1)) is False + assert Quaternion.arc_coplanar(q1, Quaternion(w, x, y, z)) is None + raises(ValueError, lambda: Quaternion.arc_coplanar(q1, q0)) + + assert Quaternion.vector_coplanar( + Quaternion(0, 8, 12, 16), + Quaternion(0, 4, 6, 8), + Quaternion(0, 2, 3, 4)) is True + assert Quaternion.vector_coplanar( + Quaternion(0, 0, 0, 0), Quaternion(0, 4, 6, 8), Quaternion(0, 2, 3, 4)) is True + assert Quaternion.vector_coplanar( + Quaternion(0, 8, 2, 6), Quaternion(0, 1, 6, 6), Quaternion(0, 0, 3, 4)) is False + assert Quaternion.vector_coplanar( + Quaternion(0, 1, 3, 4), + Quaternion(0, 4, w, 6), + Quaternion(0, 6, 8, 1)) is None + raises(ValueError, lambda: + Quaternion.vector_coplanar(q0, Quaternion(0, 4, 6, 8), q1)) + + assert Quaternion(0, 1, 2, 3).parallel(Quaternion(0, 2, 4, 6)) is True + assert Quaternion(0, 1, 2, 3).parallel(Quaternion(0, 2, 2, 6)) is False + assert Quaternion(0, 1, 2, 3).parallel(Quaternion(w, x, y, 6)) is None + raises(ValueError, lambda: q0.parallel(q1)) + + assert Quaternion(0, 1, 2, 3).orthogonal(Quaternion(0, -2, 1, 0)) is True + assert Quaternion(0, 2, 4, 7).orthogonal(Quaternion(0, 2, 2, 6)) is False + assert Quaternion(0, 2, 4, 7).orthogonal(Quaternion(w, x, y, 6)) is None + raises(ValueError, lambda: q0.orthogonal(q1)) + + assert q1.index_vector() == Quaternion( + 0, 2*sqrt(870)/29, + 3*sqrt(870)/29, + 4*sqrt(870)/29) + assert Quaternion(0, 3, 9, 4).index_vector() == Quaternion(0, 3, 9, 4) + + assert Quaternion(4, 3, 9, 4).mensor() == log(sqrt(122)) + assert Quaternion(3, 3, 0, 2).mensor() == log(sqrt(22)) + + assert q0.is_zero_quaternion() is True + assert q1.is_zero_quaternion() is False + assert Quaternion(w, 0, 0, 0).is_zero_quaternion() is None + +def test_quaternion_conversions(): + q1 = Quaternion(1, 2, 3, 4) + + assert q1.to_axis_angle() == ((2 * sqrt(29)/29, + 3 * sqrt(29)/29, + 4 * sqrt(29)/29), + 2 * acos(sqrt(30)/30)) + + assert (q1.to_rotation_matrix() == + Matrix([[Rational(-2, 3), Rational(2, 15), Rational(11, 15)], + [Rational(2, 3), Rational(-1, 3), Rational(2, 3)], + [Rational(1, 3), Rational(14, 15), Rational(2, 15)]])) + + assert (q1.to_rotation_matrix((1, 1, 1)) == + Matrix([ + [Rational(-2, 3), Rational(2, 15), Rational(11, 15), Rational(4, 5)], + [Rational(2, 3), Rational(-1, 3), Rational(2, 3), S.Zero], + [Rational(1, 3), Rational(14, 15), Rational(2, 15), Rational(-2, 5)], + [S.Zero, S.Zero, S.Zero, S.One]])) + + theta = symbols("theta", real=True) + q2 = Quaternion(cos(theta/2), 0, 0, sin(theta/2)) + + assert trigsimp(q2.to_rotation_matrix()) == Matrix([ + [cos(theta), -sin(theta), 0], + [sin(theta), cos(theta), 0], + [0, 0, 1]]) + + assert q2.to_axis_angle() == ((0, 0, sin(theta/2)/Abs(sin(theta/2))), + 2*acos(cos(theta/2))) + + assert trigsimp(q2.to_rotation_matrix((1, 1, 1))) == Matrix([ + [cos(theta), -sin(theta), 0, sin(theta) - cos(theta) + 1], + [sin(theta), cos(theta), 0, -sin(theta) - cos(theta) + 1], + [0, 0, 1, 0], + [0, 0, 0, 1]]) + + +def test_rotation_matrix_homogeneous(): + q = Quaternion(w, x, y, z) + R1 = q.to_rotation_matrix(homogeneous=True) * q.norm()**2 + R2 = simplify(q.to_rotation_matrix(homogeneous=False) * q.norm()**2) + assert R1 == R2 + + +def test_quaternion_rotation_iss1593(): + """ + There was a sign mistake in the definition, + of the rotation matrix. This tests that particular sign mistake. + See issue 1593 for reference. + See wikipedia + https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation#Quaternion-derived_rotation_matrix + for the correct definition + """ + q = Quaternion(cos(phi/2), sin(phi/2), 0, 0) + assert(trigsimp(q.to_rotation_matrix()) == Matrix([ + [1, 0, 0], + [0, cos(phi), -sin(phi)], + [0, sin(phi), cos(phi)]])) + + +def test_quaternion_multiplication(): + q1 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False) + q2 = Quaternion(1, 2, 3, 5) + q3 = Quaternion(1, 1, 1, y) + + assert Quaternion._generic_mul(S(4), S.One) == 4 + assert (Quaternion._generic_mul(S(4), q1) == + Quaternion(12 + 16*I, 8 + 20*I, 0, 28 + 32*I)) + assert q2.mul(2) == Quaternion(2, 4, 6, 10) + assert q2.mul(q3) == Quaternion(-5*y - 4, 3*y - 2, 9 - 2*y, y + 4) + assert q2.mul(q3) == q2*q3 + + z = symbols('z', complex=True) + z_quat = Quaternion(re(z), im(z), 0, 0) + q = Quaternion(*symbols('q:4', real=True)) + + assert z * q == z_quat * q + assert q * z == q * z_quat + + +def test_issue_16318(): + #for rtruediv + q0 = Quaternion(0, 0, 0, 0) + raises(ValueError, lambda: 1/q0) + #for rotate_point + q = Quaternion(1, 2, 3, 4) + (axis, angle) = q.to_axis_angle() + assert Quaternion.rotate_point((1, 1, 1), (axis, angle)) == (S.One / 5, 1, S(7) / 5) + #test for to_axis_angle + q = Quaternion(-1, 1, 1, 1) + axis = (-sqrt(3)/3, -sqrt(3)/3, -sqrt(3)/3) + angle = 2*pi/3 + assert (axis, angle) == q.to_axis_angle() + + +@slow +def test_to_euler(): + q = Quaternion(w, x, y, z) + q_normalized = q.normalize() + + seqs = ['zxy', 'zyx', 'zyz', 'zxz'] + seqs += [seq.upper() for seq in seqs] + + for seq in seqs: + euler_from_q = q.to_euler(seq) + q_back = simplify(Quaternion.from_euler(euler_from_q, seq)) + assert q_back == q_normalized + + +def test_to_euler_iss24504(): + """ + There was a mistake in the degenerate case testing + See issue 24504 for reference. + """ + q = Quaternion.from_euler((phi, 0, 0), 'zyz') + assert trigsimp(q.to_euler('zyz'), inverse=True) == (phi, 0, 0) + + +def test_to_euler_numerical_singilarities(): + + def test_one_case(angles, seq): + q = Quaternion.from_euler(angles, seq) + assert q.to_euler(seq) == angles + + # symmetric + test_one_case((pi/2, 0, 0), 'zyz') + test_one_case((pi/2, 0, 0), 'ZYZ') + test_one_case((pi/2, pi, 0), 'zyz') + test_one_case((pi/2, pi, 0), 'ZYZ') + + # asymmetric + test_one_case((pi/2, pi/2, 0), 'zyx') + test_one_case((pi/2, -pi/2, 0), 'zyx') + test_one_case((pi/2, pi/2, 0), 'ZYX') + test_one_case((pi/2, -pi/2, 0), 'ZYX') + + +@slow +def test_to_euler_options(): + def test_one_case(q): + angles1 = Matrix(q.to_euler(seq, True, True)) + angles2 = Matrix(q.to_euler(seq, False, False)) + angle_errors = simplify(angles1-angles2).evalf() + for angle_error in angle_errors: + # forcing angles to set {-pi, pi} + angle_error = (angle_error + pi) % (2 * pi) - pi + assert angle_error < 10e-7 + + for xyz in ('xyz', 'XYZ'): + for seq_tuple in permutations(xyz): + for symmetric in (True, False): + if symmetric: + seq = ''.join([seq_tuple[0], seq_tuple[1], seq_tuple[0]]) + else: + seq = ''.join(seq_tuple) + + for elements in product([-1, 0, 1], repeat=4): + q = Quaternion(*elements) + if not q.is_zero_quaternion(): + test_one_case(q) diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/__init__.py b/.venv/lib/python3.12/site-packages/sympy/assumptions/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..af862653f3ce0eeb67f7764e16c32f3466e87024 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/assumptions/__init__.py @@ -0,0 +1,18 @@ +""" +A module to implement logical predicates and assumption system. +""" + +from .assume import ( + AppliedPredicate, Predicate, AssumptionsContext, assuming, + global_assumptions +) +from .ask import Q, ask, register_handler, remove_handler +from .refine import refine +from .relation import BinaryRelation, AppliedBinaryRelation + +__all__ = [ + 'AppliedPredicate', 'Predicate', 'AssumptionsContext', 'assuming', + 'global_assumptions', 'Q', 'ask', 'register_handler', 'remove_handler', + 'refine', + 'BinaryRelation', 'AppliedBinaryRelation' +] diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/assumptions/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8e4e6c4d031ca483d00d85677201f06ab861714 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/assumptions/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/__pycache__/ask.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/assumptions/__pycache__/ask.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..383604eca721f58b8842408444af555792ff2c5b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/assumptions/__pycache__/ask.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/__pycache__/ask_generated.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/assumptions/__pycache__/ask_generated.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e3961c7ba1ab3447ca1d33d642c4e284f4359f2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/assumptions/__pycache__/ask_generated.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/__pycache__/assume.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/assumptions/__pycache__/assume.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4af9056386460f822b3dab13affa284f53896cb5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/assumptions/__pycache__/assume.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/__pycache__/cnf.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/assumptions/__pycache__/cnf.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c381363113a69a54e22760da523c71a6945c0f3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/assumptions/__pycache__/cnf.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/__pycache__/facts.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/assumptions/__pycache__/facts.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb2fd70cfa1d4bacaf869ae69ed5cee7c7bddb51 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/assumptions/__pycache__/facts.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/__pycache__/lra_satask.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/assumptions/__pycache__/lra_satask.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..33e36c7207d967368e6d53f45f994ccf8e96bc27 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/assumptions/__pycache__/lra_satask.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/__pycache__/refine.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/assumptions/__pycache__/refine.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b94931930db4ea9c8c5870398329f796f51495d6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/assumptions/__pycache__/refine.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/__pycache__/satask.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/assumptions/__pycache__/satask.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df1095d667a4ae157938a9eec828e29d63d635b7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/assumptions/__pycache__/satask.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/__pycache__/sathandlers.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/assumptions/__pycache__/sathandlers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dbdcac163ec516070adf8d275541e185b6d932df Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/assumptions/__pycache__/sathandlers.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/__pycache__/wrapper.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/assumptions/__pycache__/wrapper.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5188052323d8ae5649998235bbdfc15f93c4cc1c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/assumptions/__pycache__/wrapper.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/ask.py b/.venv/lib/python3.12/site-packages/sympy/assumptions/ask.py new file mode 100644 index 0000000000000000000000000000000000000000..ec81ec8ecce245c2a798cf9e71af1e9373292bc1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/assumptions/ask.py @@ -0,0 +1,651 @@ +"""Module for querying SymPy objects about assumptions.""" + +from sympy.assumptions.assume import (global_assumptions, Predicate, + AppliedPredicate) +from sympy.assumptions.cnf import CNF, EncodedCNF, Literal +from sympy.core import sympify +from sympy.core.kind import BooleanKind +from sympy.core.relational import Eq, Ne, Gt, Lt, Ge, Le +from sympy.logic.inference import satisfiable +from sympy.utilities.decorator import memoize_property +from sympy.utilities.exceptions import (sympy_deprecation_warning, + SymPyDeprecationWarning, + ignore_warnings) + + +# Memoization is necessary for the properties of AssumptionKeys to +# ensure that only one object of Predicate objects are created. +# This is because assumption handlers are registered on those objects. + + +class AssumptionKeys: + """ + This class contains all the supported keys by ``ask``. + It should be accessed via the instance ``sympy.Q``. + + """ + + # DO NOT add methods or properties other than predicate keys. + # SAT solver checks the properties of Q and use them to compute the + # fact system. Non-predicate attributes will break this. + + @memoize_property + def hermitian(self): + from .handlers.sets import HermitianPredicate + return HermitianPredicate() + + @memoize_property + def antihermitian(self): + from .handlers.sets import AntihermitianPredicate + return AntihermitianPredicate() + + @memoize_property + def real(self): + from .handlers.sets import RealPredicate + return RealPredicate() + + @memoize_property + def extended_real(self): + from .handlers.sets import ExtendedRealPredicate + return ExtendedRealPredicate() + + @memoize_property + def imaginary(self): + from .handlers.sets import ImaginaryPredicate + return ImaginaryPredicate() + + @memoize_property + def complex(self): + from .handlers.sets import ComplexPredicate + return ComplexPredicate() + + @memoize_property + def algebraic(self): + from .handlers.sets import AlgebraicPredicate + return AlgebraicPredicate() + + @memoize_property + def transcendental(self): + from .predicates.sets import TranscendentalPredicate + return TranscendentalPredicate() + + @memoize_property + def integer(self): + from .handlers.sets import IntegerPredicate + return IntegerPredicate() + + @memoize_property + def noninteger(self): + from .predicates.sets import NonIntegerPredicate + return NonIntegerPredicate() + + @memoize_property + def rational(self): + from .handlers.sets import RationalPredicate + return RationalPredicate() + + @memoize_property + def irrational(self): + from .handlers.sets import IrrationalPredicate + return IrrationalPredicate() + + @memoize_property + def finite(self): + from .handlers.calculus import FinitePredicate + return FinitePredicate() + + @memoize_property + def infinite(self): + from .handlers.calculus import InfinitePredicate + return InfinitePredicate() + + @memoize_property + def positive_infinite(self): + from .handlers.calculus import PositiveInfinitePredicate + return PositiveInfinitePredicate() + + @memoize_property + def negative_infinite(self): + from .handlers.calculus import NegativeInfinitePredicate + return NegativeInfinitePredicate() + + @memoize_property + def positive(self): + from .handlers.order import PositivePredicate + return PositivePredicate() + + @memoize_property + def negative(self): + from .handlers.order import NegativePredicate + return NegativePredicate() + + @memoize_property + def zero(self): + from .handlers.order import ZeroPredicate + return ZeroPredicate() + + @memoize_property + def extended_positive(self): + from .handlers.order import ExtendedPositivePredicate + return ExtendedPositivePredicate() + + @memoize_property + def extended_negative(self): + from .handlers.order import ExtendedNegativePredicate + return ExtendedNegativePredicate() + + @memoize_property + def nonzero(self): + from .handlers.order import NonZeroPredicate + return NonZeroPredicate() + + @memoize_property + def nonpositive(self): + from .handlers.order import NonPositivePredicate + return NonPositivePredicate() + + @memoize_property + def nonnegative(self): + from .handlers.order import NonNegativePredicate + return NonNegativePredicate() + + @memoize_property + def extended_nonzero(self): + from .handlers.order import ExtendedNonZeroPredicate + return ExtendedNonZeroPredicate() + + @memoize_property + def extended_nonpositive(self): + from .handlers.order import ExtendedNonPositivePredicate + return ExtendedNonPositivePredicate() + + @memoize_property + def extended_nonnegative(self): + from .handlers.order import ExtendedNonNegativePredicate + return ExtendedNonNegativePredicate() + + @memoize_property + def even(self): + from .handlers.ntheory import EvenPredicate + return EvenPredicate() + + @memoize_property + def odd(self): + from .handlers.ntheory import OddPredicate + return OddPredicate() + + @memoize_property + def prime(self): + from .handlers.ntheory import PrimePredicate + return PrimePredicate() + + @memoize_property + def composite(self): + from .handlers.ntheory import CompositePredicate + return CompositePredicate() + + @memoize_property + def commutative(self): + from .handlers.common import CommutativePredicate + return CommutativePredicate() + + @memoize_property + def is_true(self): + from .handlers.common import IsTruePredicate + return IsTruePredicate() + + @memoize_property + def symmetric(self): + from .handlers.matrices import SymmetricPredicate + return SymmetricPredicate() + + @memoize_property + def invertible(self): + from .handlers.matrices import InvertiblePredicate + return InvertiblePredicate() + + @memoize_property + def orthogonal(self): + from .handlers.matrices import OrthogonalPredicate + return OrthogonalPredicate() + + @memoize_property + def unitary(self): + from .handlers.matrices import UnitaryPredicate + return UnitaryPredicate() + + @memoize_property + def positive_definite(self): + from .handlers.matrices import PositiveDefinitePredicate + return PositiveDefinitePredicate() + + @memoize_property + def upper_triangular(self): + from .handlers.matrices import UpperTriangularPredicate + return UpperTriangularPredicate() + + @memoize_property + def lower_triangular(self): + from .handlers.matrices import LowerTriangularPredicate + return LowerTriangularPredicate() + + @memoize_property + def diagonal(self): + from .handlers.matrices import DiagonalPredicate + return DiagonalPredicate() + + @memoize_property + def fullrank(self): + from .handlers.matrices import FullRankPredicate + return FullRankPredicate() + + @memoize_property + def square(self): + from .handlers.matrices import SquarePredicate + return SquarePredicate() + + @memoize_property + def integer_elements(self): + from .handlers.matrices import IntegerElementsPredicate + return IntegerElementsPredicate() + + @memoize_property + def real_elements(self): + from .handlers.matrices import RealElementsPredicate + return RealElementsPredicate() + + @memoize_property + def complex_elements(self): + from .handlers.matrices import ComplexElementsPredicate + return ComplexElementsPredicate() + + @memoize_property + def singular(self): + from .predicates.matrices import SingularPredicate + return SingularPredicate() + + @memoize_property + def normal(self): + from .predicates.matrices import NormalPredicate + return NormalPredicate() + + @memoize_property + def triangular(self): + from .predicates.matrices import TriangularPredicate + return TriangularPredicate() + + @memoize_property + def unit_triangular(self): + from .predicates.matrices import UnitTriangularPredicate + return UnitTriangularPredicate() + + @memoize_property + def eq(self): + from .relation.equality import EqualityPredicate + return EqualityPredicate() + + @memoize_property + def ne(self): + from .relation.equality import UnequalityPredicate + return UnequalityPredicate() + + @memoize_property + def gt(self): + from .relation.equality import StrictGreaterThanPredicate + return StrictGreaterThanPredicate() + + @memoize_property + def ge(self): + from .relation.equality import GreaterThanPredicate + return GreaterThanPredicate() + + @memoize_property + def lt(self): + from .relation.equality import StrictLessThanPredicate + return StrictLessThanPredicate() + + @memoize_property + def le(self): + from .relation.equality import LessThanPredicate + return LessThanPredicate() + + +Q = AssumptionKeys() + +def _extract_all_facts(assump, exprs): + """ + Extract all relevant assumptions from *assump* with respect to given *exprs*. + + Parameters + ========== + + assump : sympy.assumptions.cnf.CNF + + exprs : tuple of expressions + + Returns + ======= + + sympy.assumptions.cnf.CNF + + Examples + ======== + + >>> from sympy import Q + >>> from sympy.assumptions.cnf import CNF + >>> from sympy.assumptions.ask import _extract_all_facts + >>> from sympy.abc import x, y + >>> assump = CNF.from_prop(Q.positive(x) & Q.integer(y)) + >>> exprs = (x,) + >>> cnf = _extract_all_facts(assump, exprs) + >>> cnf.clauses + {frozenset({Literal(Q.positive, False)})} + + """ + facts = set() + + for clause in assump.clauses: + args = [] + for literal in clause: + if isinstance(literal.lit, AppliedPredicate) and len(literal.lit.arguments) == 1: + if literal.lit.arg in exprs: + # Add literal if it has matching in it + args.append(Literal(literal.lit.function, literal.is_Not)) + else: + # If any of the literals doesn't have matching expr don't add the whole clause. + break + else: + # If any of the literals aren't unary predicate don't add the whole clause. + break + + else: + if args: + facts.add(frozenset(args)) + return CNF(facts) + + +def ask(proposition, assumptions=True, context=global_assumptions): + """ + Function to evaluate the proposition with assumptions. + + Explanation + =========== + + This function evaluates the proposition to ``True`` or ``False`` if + the truth value can be determined. If not, it returns ``None``. + + It should be discerned from :func:`~.refine` which, when applied to a + proposition, simplifies the argument to symbolic ``Boolean`` instead of + Python built-in ``True``, ``False`` or ``None``. + + **Syntax** + + * ask(proposition) + Evaluate the *proposition* in global assumption context. + + * ask(proposition, assumptions) + Evaluate the *proposition* with respect to *assumptions* in + global assumption context. + + Parameters + ========== + + proposition : Boolean + Proposition which will be evaluated to boolean value. If this is + not ``AppliedPredicate``, it will be wrapped by ``Q.is_true``. + + assumptions : Boolean, optional + Local assumptions to evaluate the *proposition*. + + context : AssumptionsContext, optional + Default assumptions to evaluate the *proposition*. By default, + this is ``sympy.assumptions.global_assumptions`` variable. + + Returns + ======= + + ``True``, ``False``, or ``None`` + + Raises + ====== + + TypeError : *proposition* or *assumptions* is not valid logical expression. + + ValueError : assumptions are inconsistent. + + Examples + ======== + + >>> from sympy import ask, Q, pi + >>> from sympy.abc import x, y + >>> ask(Q.rational(pi)) + False + >>> ask(Q.even(x*y), Q.even(x) & Q.integer(y)) + True + >>> ask(Q.prime(4*x), Q.integer(x)) + False + + If the truth value cannot be determined, ``None`` will be returned. + + >>> print(ask(Q.odd(3*x))) # cannot determine unless we know x + None + + ``ValueError`` is raised if assumptions are inconsistent. + + >>> ask(Q.integer(x), Q.even(x) & Q.odd(x)) + Traceback (most recent call last): + ... + ValueError: inconsistent assumptions Q.even(x) & Q.odd(x) + + Notes + ===== + + Relations in assumptions are not implemented (yet), so the following + will not give a meaningful result. + + >>> ask(Q.positive(x), x > 0) + + It is however a work in progress. + + See Also + ======== + + sympy.assumptions.refine.refine : Simplification using assumptions. + Proposition is not reduced to ``None`` if the truth value cannot + be determined. + """ + from sympy.assumptions.satask import satask + from sympy.assumptions.lra_satask import lra_satask + from sympy.logic.algorithms.lra_theory import UnhandledInput + + proposition = sympify(proposition) + assumptions = sympify(assumptions) + + if isinstance(proposition, Predicate) or proposition.kind is not BooleanKind: + raise TypeError("proposition must be a valid logical expression") + + if isinstance(assumptions, Predicate) or assumptions.kind is not BooleanKind: + raise TypeError("assumptions must be a valid logical expression") + + binrelpreds = {Eq: Q.eq, Ne: Q.ne, Gt: Q.gt, Lt: Q.lt, Ge: Q.ge, Le: Q.le} + if isinstance(proposition, AppliedPredicate): + key, args = proposition.function, proposition.arguments + elif proposition.func in binrelpreds: + key, args = binrelpreds[type(proposition)], proposition.args + else: + key, args = Q.is_true, (proposition,) + + # convert local and global assumptions to CNF + assump_cnf = CNF.from_prop(assumptions) + assump_cnf.extend(context) + + # extract the relevant facts from assumptions with respect to args + local_facts = _extract_all_facts(assump_cnf, args) + + # convert default facts and assumed facts to encoded CNF + known_facts_cnf = get_all_known_facts() + enc_cnf = EncodedCNF() + enc_cnf.from_cnf(CNF(known_facts_cnf)) + enc_cnf.add_from_cnf(local_facts) + + # check the satisfiability of given assumptions + if local_facts.clauses and satisfiable(enc_cnf) is False: + raise ValueError("inconsistent assumptions %s" % assumptions) + + # quick computation for single fact + res = _ask_single_fact(key, local_facts) + if res is not None: + return res + + # direct resolution method, no logic + res = key(*args)._eval_ask(assumptions) + if res is not None: + return bool(res) + + # using satask (still costly) + res = satask(proposition, assumptions=assumptions, context=context) + if res is not None: + return res + + try: + res = lra_satask(proposition, assumptions=assumptions, context=context) + except UnhandledInput: + return None + + return res + + +def _ask_single_fact(key, local_facts): + """ + Compute the truth value of single predicate using assumptions. + + Parameters + ========== + + key : sympy.assumptions.assume.Predicate + Proposition predicate. + + local_facts : sympy.assumptions.cnf.CNF + Local assumption in CNF form. + + Returns + ======= + + ``True``, ``False`` or ``None`` + + Examples + ======== + + >>> from sympy import Q + >>> from sympy.assumptions.cnf import CNF + >>> from sympy.assumptions.ask import _ask_single_fact + + If prerequisite of proposition is rejected by the assumption, + return ``False``. + + >>> key, assump = Q.zero, ~Q.zero + >>> local_facts = CNF.from_prop(assump) + >>> _ask_single_fact(key, local_facts) + False + >>> key, assump = Q.zero, ~Q.even + >>> local_facts = CNF.from_prop(assump) + >>> _ask_single_fact(key, local_facts) + False + + If assumption implies the proposition, return ``True``. + + >>> key, assump = Q.even, Q.zero + >>> local_facts = CNF.from_prop(assump) + >>> _ask_single_fact(key, local_facts) + True + + If proposition rejects the assumption, return ``False``. + + >>> key, assump = Q.even, Q.odd + >>> local_facts = CNF.from_prop(assump) + >>> _ask_single_fact(key, local_facts) + False + """ + if local_facts.clauses: + + known_facts_dict = get_known_facts_dict() + + if len(local_facts.clauses) == 1: + cl, = local_facts.clauses + if len(cl) == 1: + f, = cl + prop_facts = known_facts_dict.get(key, None) + prop_req = prop_facts[0] if prop_facts is not None else set() + if f.is_Not and f.arg in prop_req: + # the prerequisite of proposition is rejected + return False + + for clause in local_facts.clauses: + if len(clause) == 1: + f, = clause + prop_facts = known_facts_dict.get(f.arg, None) if not f.is_Not else None + if prop_facts is None: + continue + + prop_req, prop_rej = prop_facts + if key in prop_req: + # assumption implies the proposition + return True + elif key in prop_rej: + # proposition rejects the assumption + return False + + return None + + +def register_handler(key, handler): + """ + Register a handler in the ask system. key must be a string and handler a + class inheriting from AskHandler. + + .. deprecated:: 1.8. + Use multipledispatch handler instead. See :obj:`~.Predicate`. + + """ + sympy_deprecation_warning( + """ + The AskHandler system is deprecated. The register_handler() function + should be replaced with the multipledispatch handler of Predicate. + """, + deprecated_since_version="1.8", + active_deprecations_target='deprecated-askhandler', + ) + if isinstance(key, Predicate): + key = key.name.name + Qkey = getattr(Q, key, None) + if Qkey is not None: + Qkey.add_handler(handler) + else: + setattr(Q, key, Predicate(key, handlers=[handler])) + + +def remove_handler(key, handler): + """ + Removes a handler from the ask system. + + .. deprecated:: 1.8. + Use multipledispatch handler instead. See :obj:`~.Predicate`. + + """ + sympy_deprecation_warning( + """ + The AskHandler system is deprecated. The remove_handler() function + should be replaced with the multipledispatch handler of Predicate. + """, + deprecated_since_version="1.8", + active_deprecations_target='deprecated-askhandler', + ) + if isinstance(key, Predicate): + key = key.name.name + # Don't show the same warning again recursively + with ignore_warnings(SymPyDeprecationWarning): + getattr(Q, key).remove_handler(handler) + + +from sympy.assumptions.ask_generated import (get_all_known_facts, + get_known_facts_dict) diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/ask_generated.py b/.venv/lib/python3.12/site-packages/sympy/assumptions/ask_generated.py new file mode 100644 index 0000000000000000000000000000000000000000..d90cdffc1e127d78e18f70cda13d8d5e0530d41b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/assumptions/ask_generated.py @@ -0,0 +1,352 @@ +""" +Do NOT manually edit this file. +Instead, run ./bin/ask_update.py. +""" + +from sympy.assumptions.ask import Q +from sympy.assumptions.cnf import Literal +from sympy.core.cache import cacheit + +@cacheit +def get_all_known_facts(): + """ + Known facts between unary predicates as CNF clauses. + """ + return { + frozenset((Literal(Q.algebraic, False), Literal(Q.imaginary, True), Literal(Q.transcendental, False))), + frozenset((Literal(Q.algebraic, False), Literal(Q.negative, True), Literal(Q.transcendental, False))), + frozenset((Literal(Q.algebraic, False), Literal(Q.positive, True), Literal(Q.transcendental, False))), + frozenset((Literal(Q.algebraic, False), Literal(Q.rational, True))), + frozenset((Literal(Q.algebraic, False), Literal(Q.transcendental, False), Literal(Q.zero, True))), + frozenset((Literal(Q.algebraic, True), Literal(Q.finite, False))), + frozenset((Literal(Q.algebraic, True), Literal(Q.transcendental, True))), + frozenset((Literal(Q.antihermitian, False), Literal(Q.hermitian, False), Literal(Q.zero, True))), + frozenset((Literal(Q.antihermitian, False), Literal(Q.imaginary, True))), + frozenset((Literal(Q.commutative, False), Literal(Q.finite, True))), + frozenset((Literal(Q.commutative, False), Literal(Q.infinite, True))), + frozenset((Literal(Q.complex_elements, False), Literal(Q.real_elements, True))), + frozenset((Literal(Q.composite, False), Literal(Q.even, True), Literal(Q.positive, True), Literal(Q.prime, False))), + frozenset((Literal(Q.composite, True), Literal(Q.even, False), Literal(Q.odd, False))), + frozenset((Literal(Q.composite, True), Literal(Q.positive, False))), + frozenset((Literal(Q.composite, True), Literal(Q.prime, True))), + frozenset((Literal(Q.diagonal, False), Literal(Q.lower_triangular, True), Literal(Q.upper_triangular, True))), + frozenset((Literal(Q.diagonal, True), Literal(Q.lower_triangular, False))), + frozenset((Literal(Q.diagonal, True), Literal(Q.normal, False))), + frozenset((Literal(Q.diagonal, True), Literal(Q.symmetric, False))), + frozenset((Literal(Q.diagonal, True), Literal(Q.upper_triangular, False))), + frozenset((Literal(Q.even, False), Literal(Q.odd, False), Literal(Q.prime, True))), + frozenset((Literal(Q.even, False), Literal(Q.zero, True))), + frozenset((Literal(Q.even, True), Literal(Q.odd, True))), + frozenset((Literal(Q.even, True), Literal(Q.rational, False))), + frozenset((Literal(Q.finite, False), Literal(Q.transcendental, True))), + frozenset((Literal(Q.finite, True), Literal(Q.infinite, True))), + frozenset((Literal(Q.fullrank, False), Literal(Q.invertible, True))), + frozenset((Literal(Q.fullrank, True), Literal(Q.invertible, False), Literal(Q.square, True))), + frozenset((Literal(Q.hermitian, False), Literal(Q.negative, True))), + frozenset((Literal(Q.hermitian, False), Literal(Q.positive, True))), + frozenset((Literal(Q.hermitian, False), Literal(Q.zero, True))), + frozenset((Literal(Q.imaginary, True), Literal(Q.negative, True))), + frozenset((Literal(Q.imaginary, True), Literal(Q.positive, True))), + frozenset((Literal(Q.imaginary, True), Literal(Q.zero, True))), + frozenset((Literal(Q.infinite, False), Literal(Q.negative_infinite, True))), + frozenset((Literal(Q.infinite, False), Literal(Q.positive_infinite, True))), + frozenset((Literal(Q.integer_elements, True), Literal(Q.real_elements, False))), + frozenset((Literal(Q.invertible, False), Literal(Q.positive_definite, True))), + frozenset((Literal(Q.invertible, False), Literal(Q.singular, False))), + frozenset((Literal(Q.invertible, False), Literal(Q.unitary, True))), + frozenset((Literal(Q.invertible, True), Literal(Q.singular, True))), + frozenset((Literal(Q.invertible, True), Literal(Q.square, False))), + frozenset((Literal(Q.irrational, False), Literal(Q.negative, True), Literal(Q.rational, False))), + frozenset((Literal(Q.irrational, False), Literal(Q.positive, True), Literal(Q.rational, False))), + frozenset((Literal(Q.irrational, False), Literal(Q.rational, False), Literal(Q.zero, True))), + frozenset((Literal(Q.irrational, True), Literal(Q.negative, False), Literal(Q.positive, False), Literal(Q.zero, False))), + frozenset((Literal(Q.irrational, True), Literal(Q.rational, True))), + frozenset((Literal(Q.lower_triangular, False), Literal(Q.triangular, True), Literal(Q.upper_triangular, False))), + frozenset((Literal(Q.lower_triangular, True), Literal(Q.triangular, False))), + frozenset((Literal(Q.negative, False), Literal(Q.positive, False), Literal(Q.rational, True), Literal(Q.zero, False))), + frozenset((Literal(Q.negative, True), Literal(Q.negative_infinite, True))), + frozenset((Literal(Q.negative, True), Literal(Q.positive, True))), + frozenset((Literal(Q.negative, True), Literal(Q.positive_infinite, True))), + frozenset((Literal(Q.negative, True), Literal(Q.zero, True))), + frozenset((Literal(Q.negative_infinite, True), Literal(Q.positive, True))), + frozenset((Literal(Q.negative_infinite, True), Literal(Q.positive_infinite, True))), + frozenset((Literal(Q.negative_infinite, True), Literal(Q.zero, True))), + frozenset((Literal(Q.normal, False), Literal(Q.unitary, True))), + frozenset((Literal(Q.normal, True), Literal(Q.square, False))), + frozenset((Literal(Q.odd, True), Literal(Q.rational, False))), + frozenset((Literal(Q.orthogonal, False), Literal(Q.real_elements, True), Literal(Q.unitary, True))), + frozenset((Literal(Q.orthogonal, True), Literal(Q.positive_definite, False))), + frozenset((Literal(Q.orthogonal, True), Literal(Q.unitary, False))), + frozenset((Literal(Q.positive, False), Literal(Q.prime, True))), + frozenset((Literal(Q.positive, True), Literal(Q.positive_infinite, True))), + frozenset((Literal(Q.positive, True), Literal(Q.zero, True))), + frozenset((Literal(Q.positive_infinite, True), Literal(Q.zero, True))), + frozenset((Literal(Q.square, False), Literal(Q.symmetric, True))), + frozenset((Literal(Q.triangular, False), Literal(Q.unit_triangular, True))), + frozenset((Literal(Q.triangular, False), Literal(Q.upper_triangular, True))) + } + +@cacheit +def get_all_known_matrix_facts(): + """ + Known facts between unary predicates for matrices as CNF clauses. + """ + return { + frozenset((Literal(Q.complex_elements, False), Literal(Q.real_elements, True))), + frozenset((Literal(Q.diagonal, False), Literal(Q.lower_triangular, True), Literal(Q.upper_triangular, True))), + frozenset((Literal(Q.diagonal, True), Literal(Q.lower_triangular, False))), + frozenset((Literal(Q.diagonal, True), Literal(Q.normal, False))), + frozenset((Literal(Q.diagonal, True), Literal(Q.symmetric, False))), + frozenset((Literal(Q.diagonal, True), Literal(Q.upper_triangular, False))), + frozenset((Literal(Q.fullrank, False), Literal(Q.invertible, True))), + frozenset((Literal(Q.fullrank, True), Literal(Q.invertible, False), Literal(Q.square, True))), + frozenset((Literal(Q.integer_elements, True), Literal(Q.real_elements, False))), + frozenset((Literal(Q.invertible, False), Literal(Q.positive_definite, True))), + frozenset((Literal(Q.invertible, False), Literal(Q.singular, False))), + frozenset((Literal(Q.invertible, False), Literal(Q.unitary, True))), + frozenset((Literal(Q.invertible, True), Literal(Q.singular, True))), + frozenset((Literal(Q.invertible, True), Literal(Q.square, False))), + frozenset((Literal(Q.lower_triangular, False), Literal(Q.triangular, True), Literal(Q.upper_triangular, False))), + frozenset((Literal(Q.lower_triangular, True), Literal(Q.triangular, False))), + frozenset((Literal(Q.normal, False), Literal(Q.unitary, True))), + frozenset((Literal(Q.normal, True), Literal(Q.square, False))), + frozenset((Literal(Q.orthogonal, False), Literal(Q.real_elements, True), Literal(Q.unitary, True))), + frozenset((Literal(Q.orthogonal, True), Literal(Q.positive_definite, False))), + frozenset((Literal(Q.orthogonal, True), Literal(Q.unitary, False))), + frozenset((Literal(Q.square, False), Literal(Q.symmetric, True))), + frozenset((Literal(Q.triangular, False), Literal(Q.unit_triangular, True))), + frozenset((Literal(Q.triangular, False), Literal(Q.upper_triangular, True))) + } + +@cacheit +def get_all_known_number_facts(): + """ + Known facts between unary predicates for numbers as CNF clauses. + """ + return { + frozenset((Literal(Q.algebraic, False), Literal(Q.imaginary, True), Literal(Q.transcendental, False))), + frozenset((Literal(Q.algebraic, False), Literal(Q.negative, True), Literal(Q.transcendental, False))), + frozenset((Literal(Q.algebraic, False), Literal(Q.positive, True), Literal(Q.transcendental, False))), + frozenset((Literal(Q.algebraic, False), Literal(Q.rational, True))), + frozenset((Literal(Q.algebraic, False), Literal(Q.transcendental, False), Literal(Q.zero, True))), + frozenset((Literal(Q.algebraic, True), Literal(Q.finite, False))), + frozenset((Literal(Q.algebraic, True), Literal(Q.transcendental, True))), + frozenset((Literal(Q.antihermitian, False), Literal(Q.hermitian, False), Literal(Q.zero, True))), + frozenset((Literal(Q.antihermitian, False), Literal(Q.imaginary, True))), + frozenset((Literal(Q.commutative, False), Literal(Q.finite, True))), + frozenset((Literal(Q.commutative, False), Literal(Q.infinite, True))), + frozenset((Literal(Q.composite, False), Literal(Q.even, True), Literal(Q.positive, True), Literal(Q.prime, False))), + frozenset((Literal(Q.composite, True), Literal(Q.even, False), Literal(Q.odd, False))), + frozenset((Literal(Q.composite, True), Literal(Q.positive, False))), + frozenset((Literal(Q.composite, True), Literal(Q.prime, True))), + frozenset((Literal(Q.even, False), Literal(Q.odd, False), Literal(Q.prime, True))), + frozenset((Literal(Q.even, False), Literal(Q.zero, True))), + frozenset((Literal(Q.even, True), Literal(Q.odd, True))), + frozenset((Literal(Q.even, True), Literal(Q.rational, False))), + frozenset((Literal(Q.finite, False), Literal(Q.transcendental, True))), + frozenset((Literal(Q.finite, True), Literal(Q.infinite, True))), + frozenset((Literal(Q.hermitian, False), Literal(Q.negative, True))), + frozenset((Literal(Q.hermitian, False), Literal(Q.positive, True))), + frozenset((Literal(Q.hermitian, False), Literal(Q.zero, True))), + frozenset((Literal(Q.imaginary, True), Literal(Q.negative, True))), + frozenset((Literal(Q.imaginary, True), Literal(Q.positive, True))), + frozenset((Literal(Q.imaginary, True), Literal(Q.zero, True))), + frozenset((Literal(Q.infinite, False), Literal(Q.negative_infinite, True))), + frozenset((Literal(Q.infinite, False), Literal(Q.positive_infinite, True))), + frozenset((Literal(Q.irrational, False), Literal(Q.negative, True), Literal(Q.rational, False))), + frozenset((Literal(Q.irrational, False), Literal(Q.positive, True), Literal(Q.rational, False))), + frozenset((Literal(Q.irrational, False), Literal(Q.rational, False), Literal(Q.zero, True))), + frozenset((Literal(Q.irrational, True), Literal(Q.negative, False), Literal(Q.positive, False), Literal(Q.zero, False))), + frozenset((Literal(Q.irrational, True), Literal(Q.rational, True))), + frozenset((Literal(Q.negative, False), Literal(Q.positive, False), Literal(Q.rational, True), Literal(Q.zero, False))), + frozenset((Literal(Q.negative, True), Literal(Q.negative_infinite, True))), + frozenset((Literal(Q.negative, True), Literal(Q.positive, True))), + frozenset((Literal(Q.negative, True), Literal(Q.positive_infinite, True))), + frozenset((Literal(Q.negative, True), Literal(Q.zero, True))), + frozenset((Literal(Q.negative_infinite, True), Literal(Q.positive, True))), + frozenset((Literal(Q.negative_infinite, True), Literal(Q.positive_infinite, True))), + frozenset((Literal(Q.negative_infinite, True), Literal(Q.zero, True))), + frozenset((Literal(Q.odd, True), Literal(Q.rational, False))), + frozenset((Literal(Q.positive, False), Literal(Q.prime, True))), + frozenset((Literal(Q.positive, True), Literal(Q.positive_infinite, True))), + frozenset((Literal(Q.positive, True), Literal(Q.zero, True))), + frozenset((Literal(Q.positive_infinite, True), Literal(Q.zero, True))) + } + +@cacheit +def get_known_facts_dict(): + """ + Logical relations between unary predicates as dictionary. + + Each key is a predicate, and item is two groups of predicates. + First group contains the predicates which are implied by the key, and + second group contains the predicates which are rejected by the key. + + """ + return { + Q.algebraic: (set([Q.algebraic, Q.commutative, Q.complex, Q.finite]), + set([Q.infinite, Q.negative_infinite, Q.positive_infinite, + Q.transcendental])), + Q.antihermitian: (set([Q.antihermitian]), set([])), + Q.commutative: (set([Q.commutative]), set([])), + Q.complex: (set([Q.commutative, Q.complex, Q.finite]), + set([Q.infinite, Q.negative_infinite, Q.positive_infinite])), + Q.complex_elements: (set([Q.complex_elements]), set([])), + Q.composite: (set([Q.algebraic, Q.commutative, Q.complex, Q.composite, + Q.extended_nonnegative, Q.extended_nonzero, + Q.extended_positive, Q.extended_real, Q.finite, Q.hermitian, + Q.integer, Q.nonnegative, Q.nonzero, Q.positive, Q.rational, + Q.real]), set([Q.extended_negative, Q.extended_nonpositive, + Q.imaginary, Q.infinite, Q.irrational, Q.negative, + Q.negative_infinite, Q.nonpositive, Q.positive_infinite, + Q.prime, Q.transcendental, Q.zero])), + Q.diagonal: (set([Q.diagonal, Q.lower_triangular, Q.normal, Q.square, + Q.symmetric, Q.triangular, Q.upper_triangular]), set([])), + Q.even: (set([Q.algebraic, Q.commutative, Q.complex, Q.even, + Q.extended_real, Q.finite, Q.hermitian, Q.integer, Q.rational, + Q.real]), set([Q.imaginary, Q.infinite, Q.irrational, + Q.negative_infinite, Q.odd, Q.positive_infinite, + Q.transcendental])), + Q.extended_negative: (set([Q.commutative, Q.extended_negative, + Q.extended_nonpositive, Q.extended_nonzero, Q.extended_real]), + set([Q.composite, Q.extended_nonnegative, Q.extended_positive, + Q.imaginary, Q.nonnegative, Q.positive, Q.positive_infinite, + Q.prime, Q.zero])), + Q.extended_nonnegative: (set([Q.commutative, Q.extended_nonnegative, + Q.extended_real]), set([Q.extended_negative, Q.imaginary, + Q.negative, Q.negative_infinite])), + Q.extended_nonpositive: (set([Q.commutative, Q.extended_nonpositive, + Q.extended_real]), set([Q.composite, Q.extended_positive, + Q.imaginary, Q.positive, Q.positive_infinite, Q.prime])), + Q.extended_nonzero: (set([Q.commutative, Q.extended_nonzero, + Q.extended_real]), set([Q.imaginary, Q.zero])), + Q.extended_positive: (set([Q.commutative, Q.extended_nonnegative, + Q.extended_nonzero, Q.extended_positive, Q.extended_real]), + set([Q.extended_negative, Q.extended_nonpositive, Q.imaginary, + Q.negative, Q.negative_infinite, Q.nonpositive, Q.zero])), + Q.extended_real: (set([Q.commutative, Q.extended_real]), + set([Q.imaginary])), + Q.finite: (set([Q.commutative, Q.finite]), set([Q.infinite, + Q.negative_infinite, Q.positive_infinite])), + Q.fullrank: (set([Q.fullrank]), set([])), + Q.hermitian: (set([Q.hermitian]), set([])), + Q.imaginary: (set([Q.antihermitian, Q.commutative, Q.complex, + Q.finite, Q.imaginary]), set([Q.composite, Q.even, + Q.extended_negative, Q.extended_nonnegative, + Q.extended_nonpositive, Q.extended_nonzero, + Q.extended_positive, Q.extended_real, Q.infinite, Q.integer, + Q.irrational, Q.negative, Q.negative_infinite, Q.nonnegative, + Q.nonpositive, Q.nonzero, Q.odd, Q.positive, + Q.positive_infinite, Q.prime, Q.rational, Q.real, Q.zero])), + Q.infinite: (set([Q.commutative, Q.infinite]), set([Q.algebraic, + Q.complex, Q.composite, Q.even, Q.finite, Q.imaginary, + Q.integer, Q.irrational, Q.negative, Q.nonnegative, + Q.nonpositive, Q.nonzero, Q.odd, Q.positive, Q.prime, + Q.rational, Q.real, Q.transcendental, Q.zero])), + Q.integer: (set([Q.algebraic, Q.commutative, Q.complex, + Q.extended_real, Q.finite, Q.hermitian, Q.integer, Q.rational, + Q.real]), set([Q.imaginary, Q.infinite, Q.irrational, + Q.negative_infinite, Q.positive_infinite, Q.transcendental])), + Q.integer_elements: (set([Q.complex_elements, Q.integer_elements, + Q.real_elements]), set([])), + Q.invertible: (set([Q.fullrank, Q.invertible, Q.square]), + set([Q.singular])), + Q.irrational: (set([Q.commutative, Q.complex, Q.extended_nonzero, + Q.extended_real, Q.finite, Q.hermitian, Q.irrational, + Q.nonzero, Q.real]), set([Q.composite, Q.even, Q.imaginary, + Q.infinite, Q.integer, Q.negative_infinite, Q.odd, + Q.positive_infinite, Q.prime, Q.rational, Q.zero])), + Q.is_true: (set([Q.is_true]), set([])), + Q.lower_triangular: (set([Q.lower_triangular, Q.triangular]), set([])), + Q.negative: (set([Q.commutative, Q.complex, Q.extended_negative, + Q.extended_nonpositive, Q.extended_nonzero, Q.extended_real, + Q.finite, Q.hermitian, Q.negative, Q.nonpositive, Q.nonzero, + Q.real]), set([Q.composite, Q.extended_nonnegative, + Q.extended_positive, Q.imaginary, Q.infinite, + Q.negative_infinite, Q.nonnegative, Q.positive, + Q.positive_infinite, Q.prime, Q.zero])), + Q.negative_infinite: (set([Q.commutative, Q.extended_negative, + Q.extended_nonpositive, Q.extended_nonzero, Q.extended_real, + Q.infinite, Q.negative_infinite]), set([Q.algebraic, + Q.complex, Q.composite, Q.even, Q.extended_nonnegative, + Q.extended_positive, Q.finite, Q.imaginary, Q.integer, + Q.irrational, Q.negative, Q.nonnegative, Q.nonpositive, + Q.nonzero, Q.odd, Q.positive, Q.positive_infinite, Q.prime, + Q.rational, Q.real, Q.transcendental, Q.zero])), + Q.noninteger: (set([Q.noninteger]), set([])), + Q.nonnegative: (set([Q.commutative, Q.complex, Q.extended_nonnegative, + Q.extended_real, Q.finite, Q.hermitian, Q.nonnegative, + Q.real]), set([Q.extended_negative, Q.imaginary, Q.infinite, + Q.negative, Q.negative_infinite, Q.positive_infinite])), + Q.nonpositive: (set([Q.commutative, Q.complex, Q.extended_nonpositive, + Q.extended_real, Q.finite, Q.hermitian, Q.nonpositive, + Q.real]), set([Q.composite, Q.extended_positive, Q.imaginary, + Q.infinite, Q.negative_infinite, Q.positive, + Q.positive_infinite, Q.prime])), + Q.nonzero: (set([Q.commutative, Q.complex, Q.extended_nonzero, + Q.extended_real, Q.finite, Q.hermitian, Q.nonzero, Q.real]), + set([Q.imaginary, Q.infinite, Q.negative_infinite, + Q.positive_infinite, Q.zero])), + Q.normal: (set([Q.normal, Q.square]), set([])), + Q.odd: (set([Q.algebraic, Q.commutative, Q.complex, + Q.extended_nonzero, Q.extended_real, Q.finite, Q.hermitian, + Q.integer, Q.nonzero, Q.odd, Q.rational, Q.real]), + set([Q.even, Q.imaginary, Q.infinite, Q.irrational, + Q.negative_infinite, Q.positive_infinite, Q.transcendental, + Q.zero])), + Q.orthogonal: (set([Q.fullrank, Q.invertible, Q.normal, Q.orthogonal, + Q.positive_definite, Q.square, Q.unitary]), set([Q.singular])), + Q.positive: (set([Q.commutative, Q.complex, Q.extended_nonnegative, + Q.extended_nonzero, Q.extended_positive, Q.extended_real, + Q.finite, Q.hermitian, Q.nonnegative, Q.nonzero, Q.positive, + Q.real]), set([Q.extended_negative, Q.extended_nonpositive, + Q.imaginary, Q.infinite, Q.negative, Q.negative_infinite, + Q.nonpositive, Q.positive_infinite, Q.zero])), + Q.positive_definite: (set([Q.fullrank, Q.invertible, + Q.positive_definite, Q.square]), set([Q.singular])), + Q.positive_infinite: (set([Q.commutative, Q.extended_nonnegative, + Q.extended_nonzero, Q.extended_positive, Q.extended_real, + Q.infinite, Q.positive_infinite]), set([Q.algebraic, + Q.complex, Q.composite, Q.even, Q.extended_negative, + Q.extended_nonpositive, Q.finite, Q.imaginary, Q.integer, + Q.irrational, Q.negative, Q.negative_infinite, Q.nonnegative, + Q.nonpositive, Q.nonzero, Q.odd, Q.positive, Q.prime, + Q.rational, Q.real, Q.transcendental, Q.zero])), + Q.prime: (set([Q.algebraic, Q.commutative, Q.complex, + Q.extended_nonnegative, Q.extended_nonzero, + Q.extended_positive, Q.extended_real, Q.finite, Q.hermitian, + Q.integer, Q.nonnegative, Q.nonzero, Q.positive, Q.prime, + Q.rational, Q.real]), set([Q.composite, Q.extended_negative, + Q.extended_nonpositive, Q.imaginary, Q.infinite, Q.irrational, + Q.negative, Q.negative_infinite, Q.nonpositive, + Q.positive_infinite, Q.transcendental, Q.zero])), + Q.rational: (set([Q.algebraic, Q.commutative, Q.complex, + Q.extended_real, Q.finite, Q.hermitian, Q.rational, Q.real]), + set([Q.imaginary, Q.infinite, Q.irrational, + Q.negative_infinite, Q.positive_infinite, Q.transcendental])), + Q.real: (set([Q.commutative, Q.complex, Q.extended_real, Q.finite, + Q.hermitian, Q.real]), set([Q.imaginary, Q.infinite, + Q.negative_infinite, Q.positive_infinite])), + Q.real_elements: (set([Q.complex_elements, Q.real_elements]), set([])), + Q.singular: (set([Q.singular]), set([Q.invertible, Q.orthogonal, + Q.positive_definite, Q.unitary])), + Q.square: (set([Q.square]), set([])), + Q.symmetric: (set([Q.square, Q.symmetric]), set([])), + Q.transcendental: (set([Q.commutative, Q.complex, Q.finite, + Q.transcendental]), set([Q.algebraic, Q.composite, Q.even, + Q.infinite, Q.integer, Q.negative_infinite, Q.odd, + Q.positive_infinite, Q.prime, Q.rational, Q.zero])), + Q.triangular: (set([Q.triangular]), set([])), + Q.unit_triangular: (set([Q.triangular, Q.unit_triangular]), set([])), + Q.unitary: (set([Q.fullrank, Q.invertible, Q.normal, Q.square, + Q.unitary]), set([Q.singular])), + Q.upper_triangular: (set([Q.triangular, Q.upper_triangular]), set([])), + Q.zero: (set([Q.algebraic, Q.commutative, Q.complex, Q.even, + Q.extended_nonnegative, Q.extended_nonpositive, + Q.extended_real, Q.finite, Q.hermitian, Q.integer, + Q.nonnegative, Q.nonpositive, Q.rational, Q.real, Q.zero]), + set([Q.composite, Q.extended_negative, Q.extended_nonzero, + Q.extended_positive, Q.imaginary, Q.infinite, Q.irrational, + Q.negative, Q.negative_infinite, Q.nonzero, Q.odd, Q.positive, + Q.positive_infinite, Q.prime, Q.transcendental])), + } diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/assume.py b/.venv/lib/python3.12/site-packages/sympy/assumptions/assume.py new file mode 100644 index 0000000000000000000000000000000000000000..743195a865a1d39389d471b95728ca79834ed019 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/assumptions/assume.py @@ -0,0 +1,485 @@ +"""A module which implements predicates and assumption context.""" + +from contextlib import contextmanager +import inspect +from sympy.core.symbol import Str +from sympy.core.sympify import _sympify +from sympy.logic.boolalg import Boolean, false, true +from sympy.multipledispatch.dispatcher import Dispatcher, str_signature +from sympy.utilities.exceptions import sympy_deprecation_warning +from sympy.utilities.iterables import is_sequence +from sympy.utilities.source import get_class + + +class AssumptionsContext(set): + """ + Set containing default assumptions which are applied to the ``ask()`` + function. + + Explanation + =========== + + This is used to represent global assumptions, but you can also use this + class to create your own local assumptions contexts. It is basically a thin + wrapper to Python's set, so see its documentation for advanced usage. + + Examples + ======== + + The default assumption context is ``global_assumptions``, which is initially empty: + + >>> from sympy import ask, Q + >>> from sympy.assumptions import global_assumptions + >>> global_assumptions + AssumptionsContext() + + You can add default assumptions: + + >>> from sympy.abc import x + >>> global_assumptions.add(Q.real(x)) + >>> global_assumptions + AssumptionsContext({Q.real(x)}) + >>> ask(Q.real(x)) + True + + And remove them: + + >>> global_assumptions.remove(Q.real(x)) + >>> print(ask(Q.real(x))) + None + + The ``clear()`` method removes every assumption: + + >>> global_assumptions.add(Q.positive(x)) + >>> global_assumptions + AssumptionsContext({Q.positive(x)}) + >>> global_assumptions.clear() + >>> global_assumptions + AssumptionsContext() + + See Also + ======== + + assuming + + """ + + def add(self, *assumptions): + """Add assumptions.""" + for a in assumptions: + super().add(a) + + def _sympystr(self, printer): + if not self: + return "%s()" % self.__class__.__name__ + return "{}({})".format(self.__class__.__name__, printer._print_set(self)) + +global_assumptions = AssumptionsContext() + + +class AppliedPredicate(Boolean): + """ + The class of expressions resulting from applying ``Predicate`` to + the arguments. ``AppliedPredicate`` merely wraps its argument and + remain unevaluated. To evaluate it, use the ``ask()`` function. + + Examples + ======== + + >>> from sympy import Q, ask + >>> Q.integer(1) + Q.integer(1) + + The ``function`` attribute returns the predicate, and the ``arguments`` + attribute returns the tuple of arguments. + + >>> type(Q.integer(1)) + + >>> Q.integer(1).function + Q.integer + >>> Q.integer(1).arguments + (1,) + + Applied predicates can be evaluated to a boolean value with ``ask``: + + >>> ask(Q.integer(1)) + True + + """ + __slots__ = () + + def __new__(cls, predicate, *args): + if not isinstance(predicate, Predicate): + raise TypeError("%s is not a Predicate." % predicate) + args = map(_sympify, args) + return super().__new__(cls, predicate, *args) + + @property + def arg(self): + """ + Return the expression used by this assumption. + + Examples + ======== + + >>> from sympy import Q, Symbol + >>> x = Symbol('x') + >>> a = Q.integer(x + 1) + >>> a.arg + x + 1 + + """ + # Will be deprecated + args = self._args + if len(args) == 2: + # backwards compatibility + return args[1] + raise TypeError("'arg' property is allowed only for unary predicates.") + + @property + def function(self): + """ + Return the predicate. + """ + # Will be changed to self.args[0] after args overriding is removed + return self._args[0] + + @property + def arguments(self): + """ + Return the arguments which are applied to the predicate. + """ + # Will be changed to self.args[1:] after args overriding is removed + return self._args[1:] + + def _eval_ask(self, assumptions): + return self.function.eval(self.arguments, assumptions) + + @property + def binary_symbols(self): + from .ask import Q + if self.function == Q.is_true: + i = self.arguments[0] + if i.is_Boolean or i.is_Symbol: + return i.binary_symbols + if self.function in (Q.eq, Q.ne): + if true in self.arguments or false in self.arguments: + if self.arguments[0].is_Symbol: + return {self.arguments[0]} + elif self.arguments[1].is_Symbol: + return {self.arguments[1]} + return set() + + +class PredicateMeta(type): + def __new__(cls, clsname, bases, dct): + # If handler is not defined, assign empty dispatcher. + if "handler" not in dct: + name = f"Ask{clsname.capitalize()}Handler" + handler = Dispatcher(name, doc="Handler for key %s" % name) + dct["handler"] = handler + + dct["_orig_doc"] = dct.get("__doc__", "") + + return super().__new__(cls, clsname, bases, dct) + + @property + def __doc__(cls): + handler = cls.handler + doc = cls._orig_doc + if cls is not Predicate and handler is not None: + doc += "Handler\n" + doc += " =======\n\n" + + # Append the handler's doc without breaking sphinx documentation. + docs = [" Multiply dispatched method: %s" % handler.name] + if handler.doc: + for line in handler.doc.splitlines(): + if not line: + continue + docs.append(" %s" % line) + other = [] + for sig in handler.ordering[::-1]: + func = handler.funcs[sig] + if func.__doc__: + s = ' Inputs: <%s>' % str_signature(sig) + lines = [] + for line in func.__doc__.splitlines(): + lines.append(" %s" % line) + s += "\n".join(lines) + docs.append(s) + else: + other.append(str_signature(sig)) + if other: + othersig = " Other signatures:" + for line in other: + othersig += "\n * %s" % line + docs.append(othersig) + + doc += '\n\n'.join(docs) + + return doc + + +class Predicate(Boolean, metaclass=PredicateMeta): + """ + Base class for mathematical predicates. It also serves as a + constructor for undefined predicate objects. + + Explanation + =========== + + Predicate is a function that returns a boolean value [1]. + + Predicate function is object, and it is instance of predicate class. + When a predicate is applied to arguments, ``AppliedPredicate`` + instance is returned. This merely wraps the argument and remain + unevaluated. To obtain the truth value of applied predicate, use the + function ``ask``. + + Evaluation of predicate is done by multiple dispatching. You can + register new handler to the predicate to support new types. + + Every predicate in SymPy can be accessed via the property of ``Q``. + For example, ``Q.even`` returns the predicate which checks if the + argument is even number. + + To define a predicate which can be evaluated, you must subclass this + class, make an instance of it, and register it to ``Q``. After then, + dispatch the handler by argument types. + + If you directly construct predicate using this class, you will get + ``UndefinedPredicate`` which cannot be dispatched. This is useful + when you are building boolean expressions which do not need to be + evaluated. + + Examples + ======== + + Applying and evaluating to boolean value: + + >>> from sympy import Q, ask + >>> ask(Q.prime(7)) + True + + You can define a new predicate by subclassing and dispatching. Here, + we define a predicate for sexy primes [2] as an example. + + >>> from sympy import Predicate, Integer + >>> class SexyPrimePredicate(Predicate): + ... name = "sexyprime" + >>> Q.sexyprime = SexyPrimePredicate() + >>> @Q.sexyprime.register(Integer, Integer) + ... def _(int1, int2, assumptions): + ... args = sorted([int1, int2]) + ... if not all(ask(Q.prime(a), assumptions) for a in args): + ... return False + ... return args[1] - args[0] == 6 + >>> ask(Q.sexyprime(5, 11)) + True + + Direct constructing returns ``UndefinedPredicate``, which can be + applied but cannot be dispatched. + + >>> from sympy import Predicate, Integer + >>> Q.P = Predicate("P") + >>> type(Q.P) + + >>> Q.P(1) + Q.P(1) + >>> Q.P.register(Integer)(lambda expr, assump: True) + Traceback (most recent call last): + ... + TypeError: cannot be dispatched. + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Predicate_%28mathematical_logic%29 + .. [2] https://en.wikipedia.org/wiki/Sexy_prime + + """ + + is_Atom = True + + def __new__(cls, *args, **kwargs): + if cls is Predicate: + return UndefinedPredicate(*args, **kwargs) + obj = super().__new__(cls, *args) + return obj + + @property + def name(self): + # May be overridden + return type(self).__name__ + + @classmethod + def register(cls, *types, **kwargs): + """ + Register the signature to the handler. + """ + if cls.handler is None: + raise TypeError("%s cannot be dispatched." % type(cls)) + return cls.handler.register(*types, **kwargs) + + @classmethod + def register_many(cls, *types, **kwargs): + """ + Register multiple signatures to same handler. + """ + def _(func): + for t in types: + if not is_sequence(t): + t = (t,) # for convenience, allow passing `type` to mean `(type,)` + cls.register(*t, **kwargs)(func) + return _ + + def __call__(self, *args): + return AppliedPredicate(self, *args) + + def eval(self, args, assumptions=True): + """ + Evaluate ``self(*args)`` under the given assumptions. + + This uses only direct resolution methods, not logical inference. + """ + result = None + try: + result = self.handler(*args, assumptions=assumptions) + except NotImplementedError: + pass + return result + + def _eval_refine(self, assumptions): + # When Predicate is no longer Boolean, delete this method + return self + + +class UndefinedPredicate(Predicate): + """ + Predicate without handler. + + Explanation + =========== + + This predicate is generated by using ``Predicate`` directly for + construction. It does not have a handler, and evaluating this with + arguments is done by SAT solver. + + Examples + ======== + + >>> from sympy import Predicate, Q + >>> Q.P = Predicate('P') + >>> Q.P.func + + >>> Q.P.name + Str('P') + + """ + + handler = None + + def __new__(cls, name, handlers=None): + # "handlers" parameter supports old design + if not isinstance(name, Str): + name = Str(name) + obj = super(Boolean, cls).__new__(cls, name) + obj.handlers = handlers or [] + return obj + + @property + def name(self): + return self.args[0] + + def _hashable_content(self): + return (self.name,) + + def __getnewargs__(self): + return (self.name,) + + def __call__(self, expr): + return AppliedPredicate(self, expr) + + def add_handler(self, handler): + sympy_deprecation_warning( + """ + The AskHandler system is deprecated. Predicate.add_handler() + should be replaced with the multipledispatch handler of Predicate. + """, + deprecated_since_version="1.8", + active_deprecations_target='deprecated-askhandler', + ) + self.handlers.append(handler) + + def remove_handler(self, handler): + sympy_deprecation_warning( + """ + The AskHandler system is deprecated. Predicate.remove_handler() + should be replaced with the multipledispatch handler of Predicate. + """, + deprecated_since_version="1.8", + active_deprecations_target='deprecated-askhandler', + ) + self.handlers.remove(handler) + + def eval(self, args, assumptions=True): + # Support for deprecated design + # When old design is removed, this will always return None + sympy_deprecation_warning( + """ + The AskHandler system is deprecated. Evaluating UndefinedPredicate + objects should be replaced with the multipledispatch handler of + Predicate. + """, + deprecated_since_version="1.8", + active_deprecations_target='deprecated-askhandler', + stacklevel=5, + ) + expr, = args + res, _res = None, None + mro = inspect.getmro(type(expr)) + for handler in self.handlers: + cls = get_class(handler) + for subclass in mro: + eval_ = getattr(cls, subclass.__name__, None) + if eval_ is None: + continue + res = eval_(expr, assumptions) + # Do not stop if value returned is None + # Try to check for higher classes + if res is None: + continue + if _res is None: + _res = res + else: + # only check consistency if both resolutors have concluded + if _res != res: + raise ValueError('incompatible resolutors') + break + return res + + +@contextmanager +def assuming(*assumptions): + """ + Context manager for assumptions. + + Examples + ======== + + >>> from sympy import assuming, Q, ask + >>> from sympy.abc import x, y + >>> print(ask(Q.integer(x + y))) + None + >>> with assuming(Q.integer(x), Q.integer(y)): + ... print(ask(Q.integer(x + y))) + True + """ + old_global_assumptions = global_assumptions.copy() + global_assumptions.update(assumptions) + try: + yield + finally: + global_assumptions.clear() + global_assumptions.update(old_global_assumptions) diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/cnf.py b/.venv/lib/python3.12/site-packages/sympy/assumptions/cnf.py new file mode 100644 index 0000000000000000000000000000000000000000..a95d27bed6eeb64c42f4edd9d49bd8e5753069e5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/assumptions/cnf.py @@ -0,0 +1,445 @@ +""" +The classes used here are for the internal use of assumptions system +only and should not be used anywhere else as these do not possess the +signatures common to SymPy objects. For general use of logic constructs +please refer to sympy.logic classes And, Or, Not, etc. +""" +from itertools import combinations, product, zip_longest +from sympy.assumptions.assume import AppliedPredicate, Predicate +from sympy.core.relational import Eq, Ne, Gt, Lt, Ge, Le +from sympy.core.singleton import S +from sympy.logic.boolalg import Or, And, Not, Xnor +from sympy.logic.boolalg import (Equivalent, ITE, Implies, Nand, Nor, Xor) + + +class Literal: + """ + The smallest element of a CNF object. + + Parameters + ========== + + lit : Boolean expression + + is_Not : bool + + Examples + ======== + + >>> from sympy import Q + >>> from sympy.assumptions.cnf import Literal + >>> from sympy.abc import x + >>> Literal(Q.even(x)) + Literal(Q.even(x), False) + >>> Literal(~Q.even(x)) + Literal(Q.even(x), True) + """ + + def __new__(cls, lit, is_Not=False): + if isinstance(lit, Not): + lit = lit.args[0] + is_Not = True + elif isinstance(lit, (AND, OR, Literal)): + return ~lit if is_Not else lit + obj = super().__new__(cls) + obj.lit = lit + obj.is_Not = is_Not + return obj + + @property + def arg(self): + return self.lit + + def rcall(self, expr): + if callable(self.lit): + lit = self.lit(expr) + else: + lit = self.lit.apply(expr) + return type(self)(lit, self.is_Not) + + def __invert__(self): + is_Not = not self.is_Not + return Literal(self.lit, is_Not) + + def __str__(self): + return '{}({}, {})'.format(type(self).__name__, self.lit, self.is_Not) + + __repr__ = __str__ + + def __eq__(self, other): + return self.arg == other.arg and self.is_Not == other.is_Not + + def __hash__(self): + h = hash((type(self).__name__, self.arg, self.is_Not)) + return h + + +class OR: + """ + A low-level implementation for Or + """ + def __init__(self, *args): + self._args = args + + @property + def args(self): + return sorted(self._args, key=str) + + def rcall(self, expr): + return type(self)(*[arg.rcall(expr) + for arg in self._args + ]) + + def __invert__(self): + return AND(*[~arg for arg in self._args]) + + def __hash__(self): + return hash((type(self).__name__,) + tuple(self.args)) + + def __eq__(self, other): + return self.args == other.args + + def __str__(self): + s = '(' + ' | '.join([str(arg) for arg in self.args]) + ')' + return s + + __repr__ = __str__ + + +class AND: + """ + A low-level implementation for And + """ + def __init__(self, *args): + self._args = args + + def __invert__(self): + return OR(*[~arg for arg in self._args]) + + @property + def args(self): + return sorted(self._args, key=str) + + def rcall(self, expr): + return type(self)(*[arg.rcall(expr) + for arg in self._args + ]) + + def __hash__(self): + return hash((type(self).__name__,) + tuple(self.args)) + + def __eq__(self, other): + return self.args == other.args + + def __str__(self): + s = '('+' & '.join([str(arg) for arg in self.args])+')' + return s + + __repr__ = __str__ + + +def to_NNF(expr, composite_map=None): + """ + Generates the Negation Normal Form of any boolean expression in terms + of AND, OR, and Literal objects. + + Examples + ======== + + >>> from sympy import Q, Eq + >>> from sympy.assumptions.cnf import to_NNF + >>> from sympy.abc import x, y + >>> expr = Q.even(x) & ~Q.positive(x) + >>> to_NNF(expr) + (Literal(Q.even(x), False) & Literal(Q.positive(x), True)) + + Supported boolean objects are converted to corresponding predicates. + + >>> to_NNF(Eq(x, y)) + Literal(Q.eq(x, y), False) + + If ``composite_map`` argument is given, ``to_NNF`` decomposes the + specified predicate into a combination of primitive predicates. + + >>> cmap = {Q.nonpositive: Q.negative | Q.zero} + >>> to_NNF(Q.nonpositive, cmap) + (Literal(Q.negative, False) | Literal(Q.zero, False)) + >>> to_NNF(Q.nonpositive(x), cmap) + (Literal(Q.negative(x), False) | Literal(Q.zero(x), False)) + """ + from sympy.assumptions.ask import Q + + if composite_map is None: + composite_map = {} + + + binrelpreds = {Eq: Q.eq, Ne: Q.ne, Gt: Q.gt, Lt: Q.lt, Ge: Q.ge, Le: Q.le} + if type(expr) in binrelpreds: + pred = binrelpreds[type(expr)] + expr = pred(*expr.args) + + if isinstance(expr, Not): + arg = expr.args[0] + tmp = to_NNF(arg, composite_map) # Strategy: negate the NNF of expr + return ~tmp + + if isinstance(expr, Or): + return OR(*[to_NNF(x, composite_map) for x in Or.make_args(expr)]) + + if isinstance(expr, And): + return AND(*[to_NNF(x, composite_map) for x in And.make_args(expr)]) + + if isinstance(expr, Nand): + tmp = AND(*[to_NNF(x, composite_map) for x in expr.args]) + return ~tmp + + if isinstance(expr, Nor): + tmp = OR(*[to_NNF(x, composite_map) for x in expr.args]) + return ~tmp + + if isinstance(expr, Xor): + cnfs = [] + for i in range(0, len(expr.args) + 1, 2): + for neg in combinations(expr.args, i): + clause = [~to_NNF(s, composite_map) if s in neg else to_NNF(s, composite_map) + for s in expr.args] + cnfs.append(OR(*clause)) + return AND(*cnfs) + + if isinstance(expr, Xnor): + cnfs = [] + for i in range(0, len(expr.args) + 1, 2): + for neg in combinations(expr.args, i): + clause = [~to_NNF(s, composite_map) if s in neg else to_NNF(s, composite_map) + for s in expr.args] + cnfs.append(OR(*clause)) + return ~AND(*cnfs) + + if isinstance(expr, Implies): + L, R = to_NNF(expr.args[0], composite_map), to_NNF(expr.args[1], composite_map) + return OR(~L, R) + + if isinstance(expr, Equivalent): + cnfs = [] + for a, b in zip_longest(expr.args, expr.args[1:], fillvalue=expr.args[0]): + a = to_NNF(a, composite_map) + b = to_NNF(b, composite_map) + cnfs.append(OR(~a, b)) + return AND(*cnfs) + + if isinstance(expr, ITE): + L = to_NNF(expr.args[0], composite_map) + M = to_NNF(expr.args[1], composite_map) + R = to_NNF(expr.args[2], composite_map) + return AND(OR(~L, M), OR(L, R)) + + if isinstance(expr, AppliedPredicate): + pred, args = expr.function, expr.arguments + newpred = composite_map.get(pred, None) + if newpred is not None: + return to_NNF(newpred.rcall(*args), composite_map) + + if isinstance(expr, Predicate): + newpred = composite_map.get(expr, None) + if newpred is not None: + return to_NNF(newpred, composite_map) + + return Literal(expr) + + +def distribute_AND_over_OR(expr): + """ + Distributes AND over OR in the NNF expression. + Returns the result( Conjunctive Normal Form of expression) + as a CNF object. + """ + if not isinstance(expr, (AND, OR)): + tmp = set() + tmp.add(frozenset((expr,))) + return CNF(tmp) + + if isinstance(expr, OR): + return CNF.all_or(*[distribute_AND_over_OR(arg) + for arg in expr._args]) + + if isinstance(expr, AND): + return CNF.all_and(*[distribute_AND_over_OR(arg) + for arg in expr._args]) + + +class CNF: + """ + Class to represent CNF of a Boolean expression. + Consists of set of clauses, which themselves are stored as + frozenset of Literal objects. + + Examples + ======== + + >>> from sympy import Q + >>> from sympy.assumptions.cnf import CNF + >>> from sympy.abc import x + >>> cnf = CNF.from_prop(Q.real(x) & ~Q.zero(x)) + >>> cnf.clauses + {frozenset({Literal(Q.zero(x), True)}), + frozenset({Literal(Q.negative(x), False), + Literal(Q.positive(x), False), Literal(Q.zero(x), False)})} + """ + def __init__(self, clauses=None): + if not clauses: + clauses = set() + self.clauses = clauses + + def add(self, prop): + clauses = CNF.to_CNF(prop).clauses + self.add_clauses(clauses) + + def __str__(self): + s = ' & '.join( + ['(' + ' | '.join([str(lit) for lit in clause]) +')' + for clause in self.clauses] + ) + return s + + def extend(self, props): + for p in props: + self.add(p) + return self + + def copy(self): + return CNF(set(self.clauses)) + + def add_clauses(self, clauses): + self.clauses |= clauses + + @classmethod + def from_prop(cls, prop): + res = cls() + res.add(prop) + return res + + def __iand__(self, other): + self.add_clauses(other.clauses) + return self + + def all_predicates(self): + predicates = set() + for c in self.clauses: + predicates |= {arg.lit for arg in c} + return predicates + + def _or(self, cnf): + clauses = set() + for a, b in product(self.clauses, cnf.clauses): + tmp = set(a) + tmp.update(b) + clauses.add(frozenset(tmp)) + return CNF(clauses) + + def _and(self, cnf): + clauses = self.clauses.union(cnf.clauses) + return CNF(clauses) + + def _not(self): + clss = list(self.clauses) + ll = {frozenset((~x,)) for x in clss[-1]} + ll = CNF(ll) + + for rest in clss[:-1]: + p = {frozenset((~x,)) for x in rest} + ll = ll._or(CNF(p)) + return ll + + def rcall(self, expr): + clause_list = [] + for clause in self.clauses: + lits = [arg.rcall(expr) for arg in clause] + clause_list.append(OR(*lits)) + expr = AND(*clause_list) + return distribute_AND_over_OR(expr) + + @classmethod + def all_or(cls, *cnfs): + b = cnfs[0].copy() + for rest in cnfs[1:]: + b = b._or(rest) + return b + + @classmethod + def all_and(cls, *cnfs): + b = cnfs[0].copy() + for rest in cnfs[1:]: + b = b._and(rest) + return b + + @classmethod + def to_CNF(cls, expr): + from sympy.assumptions.facts import get_composite_predicates + expr = to_NNF(expr, get_composite_predicates()) + expr = distribute_AND_over_OR(expr) + return expr + + @classmethod + def CNF_to_cnf(cls, cnf): + """ + Converts CNF object to SymPy's boolean expression + retaining the form of expression. + """ + def remove_literal(arg): + return Not(arg.lit) if arg.is_Not else arg.lit + + return And(*(Or(*(remove_literal(arg) for arg in clause)) for clause in cnf.clauses)) + + +class EncodedCNF: + """ + Class for encoding the CNF expression. + """ + def __init__(self, data=None, encoding=None): + if not data and not encoding: + data = [] + encoding = {} + self.data = data + self.encoding = encoding + self._symbols = list(encoding.keys()) + + def from_cnf(self, cnf): + self._symbols = list(cnf.all_predicates()) + n = len(self._symbols) + self.encoding = dict(zip(self._symbols, range(1, n + 1))) + self.data = [self.encode(clause) for clause in cnf.clauses] + + @property + def symbols(self): + return self._symbols + + @property + def variables(self): + return range(1, len(self._symbols) + 1) + + def copy(self): + new_data = [set(clause) for clause in self.data] + return EncodedCNF(new_data, dict(self.encoding)) + + def add_prop(self, prop): + cnf = CNF.from_prop(prop) + self.add_from_cnf(cnf) + + def add_from_cnf(self, cnf): + clauses = [self.encode(clause) for clause in cnf.clauses] + self.data += clauses + + def encode_arg(self, arg): + literal = arg.lit + value = self.encoding.get(literal, None) + if value is None: + n = len(self._symbols) + self._symbols.append(literal) + value = self.encoding[literal] = n + 1 + if arg.is_Not: + return -value + else: + return value + + def encode(self, clause): + return {self.encode_arg(arg) if not arg.lit == S.false else 0 for arg in clause} diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/facts.py b/.venv/lib/python3.12/site-packages/sympy/assumptions/facts.py new file mode 100644 index 0000000000000000000000000000000000000000..2ff268677cf74e252ac6c3bc3eecbea08b9414d0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/assumptions/facts.py @@ -0,0 +1,270 @@ +""" +Known facts in assumptions module. + +This module defines the facts between unary predicates in ``get_known_facts()``, +and supports functions to generate the contents in +``sympy.assumptions.ask_generated`` file. +""" + +from sympy.assumptions.ask import Q +from sympy.assumptions.assume import AppliedPredicate +from sympy.core.cache import cacheit +from sympy.core.symbol import Symbol +from sympy.logic.boolalg import (to_cnf, And, Not, Implies, Equivalent, + Exclusive,) +from sympy.logic.inference import satisfiable + + +@cacheit +def get_composite_predicates(): + # To reduce the complexity of sat solver, these predicates are + # transformed into the combination of primitive predicates. + return { + Q.real : Q.negative | Q.zero | Q.positive, + Q.integer : Q.even | Q.odd, + Q.nonpositive : Q.negative | Q.zero, + Q.nonzero : Q.negative | Q.positive, + Q.nonnegative : Q.zero | Q.positive, + Q.extended_real : Q.negative_infinite | Q.negative | Q.zero | Q.positive | Q.positive_infinite, + Q.extended_positive: Q.positive | Q.positive_infinite, + Q.extended_negative: Q.negative | Q.negative_infinite, + Q.extended_nonzero: Q.negative_infinite | Q.negative | Q.positive | Q.positive_infinite, + Q.extended_nonpositive: Q.negative_infinite | Q.negative | Q.zero, + Q.extended_nonnegative: Q.zero | Q.positive | Q.positive_infinite, + Q.complex : Q.algebraic | Q.transcendental + } + + +@cacheit +def get_known_facts(x=None): + """ + Facts between unary predicates. + + Parameters + ========== + + x : Symbol, optional + Placeholder symbol for unary facts. Default is ``Symbol('x')``. + + Returns + ======= + + fact : Known facts in conjugated normal form. + + """ + if x is None: + x = Symbol('x') + + fact = And( + get_number_facts(x), + get_matrix_facts(x) + ) + return fact + + +@cacheit +def get_number_facts(x = None): + """ + Facts between unary number predicates. + + Parameters + ========== + + x : Symbol, optional + Placeholder symbol for unary facts. Default is ``Symbol('x')``. + + Returns + ======= + + fact : Known facts in conjugated normal form. + + """ + if x is None: + x = Symbol('x') + + fact = And( + # primitive predicates for extended real exclude each other. + Exclusive(Q.negative_infinite(x), Q.negative(x), Q.zero(x), + Q.positive(x), Q.positive_infinite(x)), + + # build complex plane + Exclusive(Q.real(x), Q.imaginary(x)), + Implies(Q.real(x) | Q.imaginary(x), Q.complex(x)), + + # other subsets of complex + Exclusive(Q.transcendental(x), Q.algebraic(x)), + Equivalent(Q.real(x), Q.rational(x) | Q.irrational(x)), + Exclusive(Q.irrational(x), Q.rational(x)), + Implies(Q.rational(x), Q.algebraic(x)), + + # integers + Exclusive(Q.even(x), Q.odd(x)), + Implies(Q.integer(x), Q.rational(x)), + Implies(Q.zero(x), Q.even(x)), + Exclusive(Q.composite(x), Q.prime(x)), + Implies(Q.composite(x) | Q.prime(x), Q.integer(x) & Q.positive(x)), + Implies(Q.even(x) & Q.positive(x) & ~Q.prime(x), Q.composite(x)), + + # hermitian and antihermitian + Implies(Q.real(x), Q.hermitian(x)), + Implies(Q.imaginary(x), Q.antihermitian(x)), + Implies(Q.zero(x), Q.hermitian(x) | Q.antihermitian(x)), + + # define finity and infinity, and build extended real line + Exclusive(Q.infinite(x), Q.finite(x)), + Implies(Q.complex(x), Q.finite(x)), + Implies(Q.negative_infinite(x) | Q.positive_infinite(x), Q.infinite(x)), + + # commutativity + Implies(Q.finite(x) | Q.infinite(x), Q.commutative(x)), + ) + return fact + + +@cacheit +def get_matrix_facts(x = None): + """ + Facts between unary matrix predicates. + + Parameters + ========== + + x : Symbol, optional + Placeholder symbol for unary facts. Default is ``Symbol('x')``. + + Returns + ======= + + fact : Known facts in conjugated normal form. + + """ + if x is None: + x = Symbol('x') + + fact = And( + # matrices + Implies(Q.orthogonal(x), Q.positive_definite(x)), + Implies(Q.orthogonal(x), Q.unitary(x)), + Implies(Q.unitary(x) & Q.real_elements(x), Q.orthogonal(x)), + Implies(Q.unitary(x), Q.normal(x)), + Implies(Q.unitary(x), Q.invertible(x)), + Implies(Q.normal(x), Q.square(x)), + Implies(Q.diagonal(x), Q.normal(x)), + Implies(Q.positive_definite(x), Q.invertible(x)), + Implies(Q.diagonal(x), Q.upper_triangular(x)), + Implies(Q.diagonal(x), Q.lower_triangular(x)), + Implies(Q.lower_triangular(x), Q.triangular(x)), + Implies(Q.upper_triangular(x), Q.triangular(x)), + Implies(Q.triangular(x), Q.upper_triangular(x) | Q.lower_triangular(x)), + Implies(Q.upper_triangular(x) & Q.lower_triangular(x), Q.diagonal(x)), + Implies(Q.diagonal(x), Q.symmetric(x)), + Implies(Q.unit_triangular(x), Q.triangular(x)), + Implies(Q.invertible(x), Q.fullrank(x)), + Implies(Q.invertible(x), Q.square(x)), + Implies(Q.symmetric(x), Q.square(x)), + Implies(Q.fullrank(x) & Q.square(x), Q.invertible(x)), + Equivalent(Q.invertible(x), ~Q.singular(x)), + Implies(Q.integer_elements(x), Q.real_elements(x)), + Implies(Q.real_elements(x), Q.complex_elements(x)), + ) + return fact + + + +def generate_known_facts_dict(keys, fact): + """ + Computes and returns a dictionary which contains the relations between + unary predicates. + + Each key is a predicate, and item is two groups of predicates. + First group contains the predicates which are implied by the key, and + second group contains the predicates which are rejected by the key. + + All predicates in *keys* and *fact* must be unary and have same placeholder + symbol. + + Parameters + ========== + + keys : list of AppliedPredicate instances. + + fact : Fact between predicates in conjugated normal form. + + Examples + ======== + + >>> from sympy import Q, And, Implies + >>> from sympy.assumptions.facts import generate_known_facts_dict + >>> from sympy.abc import x + >>> keys = [Q.even(x), Q.odd(x), Q.zero(x)] + >>> fact = And(Implies(Q.even(x), ~Q.odd(x)), + ... Implies(Q.zero(x), Q.even(x))) + >>> generate_known_facts_dict(keys, fact) + {Q.even: ({Q.even}, {Q.odd}), + Q.odd: ({Q.odd}, {Q.even, Q.zero}), + Q.zero: ({Q.even, Q.zero}, {Q.odd})} + """ + fact_cnf = to_cnf(fact) + mapping = single_fact_lookup(keys, fact_cnf) + + ret = {} + for key, value in mapping.items(): + implied = set() + rejected = set() + for expr in value: + if isinstance(expr, AppliedPredicate): + implied.add(expr.function) + elif isinstance(expr, Not): + pred = expr.args[0] + rejected.add(pred.function) + ret[key.function] = (implied, rejected) + return ret + + +@cacheit +def get_known_facts_keys(): + """ + Return every unary predicates registered to ``Q``. + + This function is used to generate the keys for + ``generate_known_facts_dict``. + + """ + # exclude polyadic predicates + exclude = {Q.eq, Q.ne, Q.gt, Q.lt, Q.ge, Q.le} + + result = [] + for attr in Q.__class__.__dict__: + if attr.startswith('__'): + continue + pred = getattr(Q, attr) + if pred in exclude: + continue + result.append(pred) + return result + + +def single_fact_lookup(known_facts_keys, known_facts_cnf): + # Return the dictionary for quick lookup of single fact + mapping = {} + for key in known_facts_keys: + mapping[key] = {key} + for other_key in known_facts_keys: + if other_key != key: + if ask_full_inference(other_key, key, known_facts_cnf): + mapping[key].add(other_key) + if ask_full_inference(~other_key, key, known_facts_cnf): + mapping[key].add(~other_key) + return mapping + + +def ask_full_inference(proposition, assumptions, known_facts_cnf): + """ + Method for inferring properties about objects. + + """ + if not satisfiable(And(known_facts_cnf, assumptions, proposition)): + return False + if not satisfiable(And(known_facts_cnf, assumptions, Not(proposition))): + return True + return None diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/__init__.py b/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0fbe618eb8b43e252ac8fb0baf1eeee22bf347cc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/__init__.py @@ -0,0 +1,13 @@ +""" +Multipledispatch handlers for ``Predicate`` are implemented here. +Handlers in this module are not directly imported to other modules in +order to avoid circular import problem. +""" + +from .common import (AskHandler, CommonHandler, + test_closed_group) + +__all__ = [ + 'AskHandler', 'CommonHandler', + 'test_closed_group' +] diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7cd154abe2ef0ba8663ad6890c37e41cf4e059c0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/__pycache__/calculus.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/__pycache__/calculus.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db8ad99aa7a416406e5e22230cf4099628ca436b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/__pycache__/calculus.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/__pycache__/common.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/__pycache__/common.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..04ed731a8abb07ed21efc389f1dbdca1bf894334 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/__pycache__/common.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/__pycache__/matrices.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/__pycache__/matrices.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..357ed3a2cb6ed7f0fe44091418fc5a294d2bec0c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/__pycache__/matrices.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/__pycache__/ntheory.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/__pycache__/ntheory.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b3d1fd088017e7222867f952915f7071e9abf8d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/__pycache__/ntheory.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/__pycache__/order.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/__pycache__/order.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55efc57d5778d403babc6d12c6779e7238577303 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/__pycache__/order.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/__pycache__/sets.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/__pycache__/sets.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b8e4292e3cc05ee523de774dd2587a2899a4e5c3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/__pycache__/sets.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/calculus.py b/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/calculus.py new file mode 100644 index 0000000000000000000000000000000000000000..e2b9c43ccea216988a25aa671ea23bc81d2209ff --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/calculus.py @@ -0,0 +1,273 @@ +""" +This module contains query handlers responsible for calculus queries: +infinitesimal, finite, etc. +""" + +from sympy.assumptions import Q, ask +from sympy.core import Expr, Add, Mul, Pow, Symbol +from sympy.core.numbers import (NegativeInfinity, GoldenRatio, + Infinity, Exp1, ComplexInfinity, ImaginaryUnit, NaN, Number, Pi, E, + TribonacciConstant) +from sympy.functions import cos, exp, log, sign, sin +from sympy.logic.boolalg import conjuncts + +from ..predicates.calculus import (FinitePredicate, InfinitePredicate, + PositiveInfinitePredicate, NegativeInfinitePredicate) + + +# FinitePredicate + + +@FinitePredicate.register(Symbol) +def _(expr, assumptions): + """ + Handles Symbol. + """ + if expr.is_finite is not None: + return expr.is_finite + if Q.finite(expr) in conjuncts(assumptions): + return True + return None + +@FinitePredicate.register(Add) +def _(expr, assumptions): + """ + Return True if expr is bounded, False if not and None if unknown. + + Truth Table: + + +-------+-----+-----------+-----------+ + | | | | | + | | B | U | ? | + | | | | | + +-------+-----+---+---+---+---+---+---+ + | | | | | | | | | + | | |'+'|'-'|'x'|'+'|'-'|'x'| + | | | | | | | | | + +-------+-----+---+---+---+---+---+---+ + | | | | | + | B | B | U | ? | + | | | | | + +---+---+-----+---+---+---+---+---+---+ + | | | | | | | | | | + | |'+'| | U | ? | ? | U | ? | ? | + | | | | | | | | | | + | +---+-----+---+---+---+---+---+---+ + | | | | | | | | | | + | U |'-'| | ? | U | ? | ? | U | ? | + | | | | | | | | | | + | +---+-----+---+---+---+---+---+---+ + | | | | | | + | |'x'| | ? | ? | + | | | | | | + +---+---+-----+---+---+---+---+---+---+ + | | | | | + | ? | | | ? | + | | | | | + +-------+-----+-----------+---+---+---+ + + * 'B' = Bounded + + * 'U' = Unbounded + + * '?' = unknown boundedness + + * '+' = positive sign + + * '-' = negative sign + + * 'x' = sign unknown + + * All Bounded -> True + + * 1 Unbounded and the rest Bounded -> False + + * >1 Unbounded, all with same known sign -> False + + * Any Unknown and unknown sign -> None + + * Else -> None + + When the signs are not the same you can have an undefined + result as in oo - oo, hence 'bounded' is also undefined. + """ + sign = -1 # sign of unknown or infinite + result = True + for arg in expr.args: + _bounded = ask(Q.finite(arg), assumptions) + if _bounded: + continue + s = ask(Q.extended_positive(arg), assumptions) + # if there has been more than one sign or if the sign of this arg + # is None and Bounded is None or there was already + # an unknown sign, return None + if sign != -1 and s != sign or \ + s is None and None in (_bounded, sign): + return None + else: + sign = s + # once False, do not change + if result is not False: + result = _bounded + return result + +@FinitePredicate.register(Mul) +def _(expr, assumptions): + """ + Return True if expr is bounded, False if not and None if unknown. + + Truth Table: + + +---+---+---+--------+ + | | | | | + | | B | U | ? | + | | | | | + +---+---+---+---+----+ + | | | | | | + | | | | s | /s | + | | | | | | + +---+---+---+---+----+ + | | | | | + | B | B | U | ? | + | | | | | + +---+---+---+---+----+ + | | | | | | + | U | | U | U | ? | + | | | | | | + +---+---+---+---+----+ + | | | | | + | ? | | | ? | + | | | | | + +---+---+---+---+----+ + + * B = Bounded + + * U = Unbounded + + * ? = unknown boundedness + + * s = signed (hence nonzero) + + * /s = not signed + """ + result = True + possible_zero = False + for arg in expr.args: + _bounded = ask(Q.finite(arg), assumptions) + if _bounded: + if ask(Q.zero(arg), assumptions) is not False: + if result is False: + return None + possible_zero = True + elif _bounded is None: + if result is None: + return None + if ask(Q.extended_nonzero(arg), assumptions) is None: + return None + if result is not False: + result = None + else: + if possible_zero: + return None + result = False + return result + +@FinitePredicate.register(Pow) +def _(expr, assumptions): + """ + * Unbounded ** NonZero -> Unbounded + + * Bounded ** Bounded -> Bounded + + * Abs()<=1 ** Positive -> Bounded + + * Abs()>=1 ** Negative -> Bounded + + * Otherwise unknown + """ + if expr.base == E: + return ask(Q.finite(expr.exp), assumptions) + + base_bounded = ask(Q.finite(expr.base), assumptions) + exp_bounded = ask(Q.finite(expr.exp), assumptions) + if base_bounded is None and exp_bounded is None: # Common Case + return None + if base_bounded is False and ask(Q.extended_nonzero(expr.exp), assumptions): + return False + if base_bounded and exp_bounded: + is_base_zero = ask(Q.zero(expr.base),assumptions) + is_exp_negative = ask(Q.negative(expr.exp),assumptions) + if is_base_zero is True and is_exp_negative is True: + return False + if is_base_zero is not False and is_exp_negative is not False: + return None + return True + if (abs(expr.base) <= 1) == True and ask(Q.extended_positive(expr.exp), assumptions): + return True + if (abs(expr.base) >= 1) == True and ask(Q.extended_negative(expr.exp), assumptions): + return True + if (abs(expr.base) >= 1) == True and exp_bounded is False: + return False + return None + +@FinitePredicate.register(exp) +def _(expr, assumptions): + return ask(Q.finite(expr.exp), assumptions) + +@FinitePredicate.register(log) +def _(expr, assumptions): + # After complex -> finite fact is registered to new assumption system, + # querying Q.infinite may be removed. + if ask(Q.infinite(expr.args[0]), assumptions): + return False + return ask(~Q.zero(expr.args[0]), assumptions) + +@FinitePredicate.register_many(cos, sin, Number, Pi, Exp1, GoldenRatio, + TribonacciConstant, ImaginaryUnit, sign) +def _(expr, assumptions): + return True + +@FinitePredicate.register_many(ComplexInfinity, Infinity, NegativeInfinity) +def _(expr, assumptions): + return False + +@FinitePredicate.register(NaN) +def _(expr, assumptions): + return None + + +# InfinitePredicate + + +@InfinitePredicate.register(Expr) +def _(expr, assumptions): + is_finite = Q.finite(expr)._eval_ask(assumptions) + if is_finite is None: + return None + return not is_finite + + +# PositiveInfinitePredicate + + +@PositiveInfinitePredicate.register(Infinity) +def _(expr, assumptions): + return True + + +@PositiveInfinitePredicate.register_many(NegativeInfinity, ComplexInfinity) +def _(expr, assumptions): + return False + + +# NegativeInfinitePredicate + + +@NegativeInfinitePredicate.register(NegativeInfinity) +def _(expr, assumptions): + return True + + +@NegativeInfinitePredicate.register_many(Infinity, ComplexInfinity) +def _(expr, assumptions): + return False diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/common.py b/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/common.py new file mode 100644 index 0000000000000000000000000000000000000000..f6e9f6f321be461c09b16c03b9cec5708404d21a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/common.py @@ -0,0 +1,164 @@ +""" +This module defines base class for handlers and some core handlers: +``Q.commutative`` and ``Q.is_true``. +""" + +from sympy.assumptions import Q, ask, AppliedPredicate +from sympy.core import Basic, Symbol +from sympy.core.logic import _fuzzy_group, fuzzy_and, fuzzy_or +from sympy.core.numbers import NaN, Number +from sympy.logic.boolalg import (And, BooleanTrue, BooleanFalse, conjuncts, + Equivalent, Implies, Not, Or) +from sympy.utilities.exceptions import sympy_deprecation_warning + +from ..predicates.common import CommutativePredicate, IsTruePredicate + + +class AskHandler: + """Base class that all Ask Handlers must inherit.""" + def __new__(cls, *args, **kwargs): + sympy_deprecation_warning( + """ + The AskHandler system is deprecated. The AskHandler class should + be replaced with the multipledispatch handler of Predicate + """, + deprecated_since_version="1.8", + active_deprecations_target='deprecated-askhandler', + ) + return super().__new__(cls, *args, **kwargs) + + +class CommonHandler(AskHandler): + # Deprecated + """Defines some useful methods common to most Handlers. """ + + @staticmethod + def AlwaysTrue(expr, assumptions): + return True + + @staticmethod + def AlwaysFalse(expr, assumptions): + return False + + @staticmethod + def AlwaysNone(expr, assumptions): + return None + + NaN = AlwaysFalse + + +# CommutativePredicate + +@CommutativePredicate.register(Symbol) +def _(expr, assumptions): + """Objects are expected to be commutative unless otherwise stated""" + assumps = conjuncts(assumptions) + if expr.is_commutative is not None: + return expr.is_commutative and not ~Q.commutative(expr) in assumps + if Q.commutative(expr) in assumps: + return True + elif ~Q.commutative(expr) in assumps: + return False + return True + +@CommutativePredicate.register(Basic) +def _(expr, assumptions): + for arg in expr.args: + if not ask(Q.commutative(arg), assumptions): + return False + return True + +@CommutativePredicate.register(Number) +def _(expr, assumptions): + return True + +@CommutativePredicate.register(NaN) +def _(expr, assumptions): + return True + + +# IsTruePredicate + +@IsTruePredicate.register(bool) +def _(expr, assumptions): + return expr + +@IsTruePredicate.register(BooleanTrue) +def _(expr, assumptions): + return True + +@IsTruePredicate.register(BooleanFalse) +def _(expr, assumptions): + return False + +@IsTruePredicate.register(AppliedPredicate) +def _(expr, assumptions): + return ask(expr, assumptions) + +@IsTruePredicate.register(Not) +def _(expr, assumptions): + arg = expr.args[0] + if arg.is_Symbol: + # symbol used as abstract boolean object + return None + value = ask(arg, assumptions=assumptions) + if value in (True, False): + return not value + else: + return None + +@IsTruePredicate.register(Or) +def _(expr, assumptions): + result = False + for arg in expr.args: + p = ask(arg, assumptions=assumptions) + if p is True: + return True + if p is None: + result = None + return result + +@IsTruePredicate.register(And) +def _(expr, assumptions): + result = True + for arg in expr.args: + p = ask(arg, assumptions=assumptions) + if p is False: + return False + if p is None: + result = None + return result + +@IsTruePredicate.register(Implies) +def _(expr, assumptions): + p, q = expr.args + return ask(~p | q, assumptions=assumptions) + +@IsTruePredicate.register(Equivalent) +def _(expr, assumptions): + p, q = expr.args + pt = ask(p, assumptions=assumptions) + if pt is None: + return None + qt = ask(q, assumptions=assumptions) + if qt is None: + return None + return pt == qt + + +#### Helper methods +def test_closed_group(expr, assumptions, key): + """ + Test for membership in a group with respect + to the current operation. + """ + return _fuzzy_group( + (ask(key(a), assumptions) for a in expr.args), quick_exit=True) + +def ask_all(*queries, assumptions): + return fuzzy_and( + (ask(query, assumptions) for query in queries)) + +def ask_any(*queries, assumptions): + return fuzzy_or( + (ask(query, assumptions) for query in queries)) diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/matrices.py b/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/matrices.py new file mode 100644 index 0000000000000000000000000000000000000000..3b20385360136629ea037eb7238c45b70ba57fd2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/matrices.py @@ -0,0 +1,716 @@ +""" +This module contains query handlers responsible for Matrices queries: +Square, Symmetric, Invertible etc. +""" + +from sympy.logic.boolalg import conjuncts +from sympy.assumptions import Q, ask +from sympy.assumptions.handlers import test_closed_group +from sympy.matrices import MatrixBase +from sympy.matrices.expressions import (BlockMatrix, BlockDiagMatrix, Determinant, + DiagMatrix, DiagonalMatrix, HadamardProduct, Identity, Inverse, MatAdd, MatMul, + MatPow, MatrixExpr, MatrixSlice, MatrixSymbol, OneMatrix, Trace, Transpose, + ZeroMatrix) +from sympy.matrices.expressions.blockmatrix import reblock_2x2 +from sympy.matrices.expressions.factorizations import Factorization +from sympy.matrices.expressions.fourier import DFT +from sympy.core.logic import fuzzy_and +from sympy.utilities.iterables import sift +from sympy.core import Basic + +from ..predicates.matrices import (SquarePredicate, SymmetricPredicate, + InvertiblePredicate, OrthogonalPredicate, UnitaryPredicate, + FullRankPredicate, PositiveDefinitePredicate, UpperTriangularPredicate, + LowerTriangularPredicate, DiagonalPredicate, IntegerElementsPredicate, + RealElementsPredicate, ComplexElementsPredicate) + + +def _Factorization(predicate, expr, assumptions): + if predicate in expr.predicates: + return True + + +# SquarePredicate + +@SquarePredicate.register(MatrixExpr) +def _(expr, assumptions): + return expr.shape[0] == expr.shape[1] + + +# SymmetricPredicate + +@SymmetricPredicate.register(MatMul) +def _(expr, assumptions): + factor, mmul = expr.as_coeff_mmul() + if all(ask(Q.symmetric(arg), assumptions) for arg in mmul.args): + return True + # TODO: implement sathandlers system for the matrices. + # Now it duplicates the general fact: Implies(Q.diagonal, Q.symmetric). + if ask(Q.diagonal(expr), assumptions): + return True + if len(mmul.args) >= 2 and mmul.args[0] == mmul.args[-1].T: + if len(mmul.args) == 2: + return True + return ask(Q.symmetric(MatMul(*mmul.args[1:-1])), assumptions) + +@SymmetricPredicate.register(MatPow) +def _(expr, assumptions): + # only for integer powers + base, exp = expr.args + int_exp = ask(Q.integer(exp), assumptions) + if not int_exp: + return None + non_negative = ask(~Q.negative(exp), assumptions) + if (non_negative or non_negative == False + and ask(Q.invertible(base), assumptions)): + return ask(Q.symmetric(base), assumptions) + return None + +@SymmetricPredicate.register(MatAdd) +def _(expr, assumptions): + return all(ask(Q.symmetric(arg), assumptions) for arg in expr.args) + +@SymmetricPredicate.register(MatrixSymbol) +def _(expr, assumptions): + if not expr.is_square: + return False + # TODO: implement sathandlers system for the matrices. + # Now it duplicates the general fact: Implies(Q.diagonal, Q.symmetric). + if ask(Q.diagonal(expr), assumptions): + return True + if Q.symmetric(expr) in conjuncts(assumptions): + return True + +@SymmetricPredicate.register_many(OneMatrix, ZeroMatrix) +def _(expr, assumptions): + return ask(Q.square(expr), assumptions) + +@SymmetricPredicate.register_many(Inverse, Transpose) +def _(expr, assumptions): + return ask(Q.symmetric(expr.arg), assumptions) + +@SymmetricPredicate.register(MatrixSlice) +def _(expr, assumptions): + # TODO: implement sathandlers system for the matrices. + # Now it duplicates the general fact: Implies(Q.diagonal, Q.symmetric). + if ask(Q.diagonal(expr), assumptions): + return True + if not expr.on_diag: + return None + else: + return ask(Q.symmetric(expr.parent), assumptions) + +@SymmetricPredicate.register(Identity) +def _(expr, assumptions): + return True + + +# InvertiblePredicate + +@InvertiblePredicate.register(MatMul) +def _(expr, assumptions): + factor, mmul = expr.as_coeff_mmul() + if all(ask(Q.invertible(arg), assumptions) for arg in mmul.args): + return True + if any(ask(Q.invertible(arg), assumptions) is False + for arg in mmul.args): + return False + +@InvertiblePredicate.register(MatPow) +def _(expr, assumptions): + # only for integer powers + base, exp = expr.args + int_exp = ask(Q.integer(exp), assumptions) + if not int_exp: + return None + if exp.is_negative == False: + return ask(Q.invertible(base), assumptions) + return None + +@InvertiblePredicate.register(MatAdd) +def _(expr, assumptions): + return None + +@InvertiblePredicate.register(MatrixSymbol) +def _(expr, assumptions): + if not expr.is_square: + return False + if Q.invertible(expr) in conjuncts(assumptions): + return True + +@InvertiblePredicate.register_many(Identity, Inverse) +def _(expr, assumptions): + return True + +@InvertiblePredicate.register(ZeroMatrix) +def _(expr, assumptions): + return False + +@InvertiblePredicate.register(OneMatrix) +def _(expr, assumptions): + return expr.shape[0] == 1 and expr.shape[1] == 1 + +@InvertiblePredicate.register(Transpose) +def _(expr, assumptions): + return ask(Q.invertible(expr.arg), assumptions) + +@InvertiblePredicate.register(MatrixSlice) +def _(expr, assumptions): + if not expr.on_diag: + return None + else: + return ask(Q.invertible(expr.parent), assumptions) + +@InvertiblePredicate.register(MatrixBase) +def _(expr, assumptions): + if not expr.is_square: + return False + return expr.rank() == expr.rows + +@InvertiblePredicate.register(MatrixExpr) +def _(expr, assumptions): + if not expr.is_square: + return False + return None + +@InvertiblePredicate.register(BlockMatrix) +def _(expr, assumptions): + if not expr.is_square: + return False + if expr.blockshape == (1, 1): + return ask(Q.invertible(expr.blocks[0, 0]), assumptions) + expr = reblock_2x2(expr) + if expr.blockshape == (2, 2): + [[A, B], [C, D]] = expr.blocks.tolist() + if ask(Q.invertible(A), assumptions) == True: + invertible = ask(Q.invertible(D - C * A.I * B), assumptions) + if invertible is not None: + return invertible + if ask(Q.invertible(B), assumptions) == True: + invertible = ask(Q.invertible(C - D * B.I * A), assumptions) + if invertible is not None: + return invertible + if ask(Q.invertible(C), assumptions) == True: + invertible = ask(Q.invertible(B - A * C.I * D), assumptions) + if invertible is not None: + return invertible + if ask(Q.invertible(D), assumptions) == True: + invertible = ask(Q.invertible(A - B * D.I * C), assumptions) + if invertible is not None: + return invertible + return None + +@InvertiblePredicate.register(BlockDiagMatrix) +def _(expr, assumptions): + if expr.rowblocksizes != expr.colblocksizes: + return None + return fuzzy_and([ask(Q.invertible(a), assumptions) for a in expr.diag]) + + +# OrthogonalPredicate + +@OrthogonalPredicate.register(MatMul) +def _(expr, assumptions): + factor, mmul = expr.as_coeff_mmul() + if (all(ask(Q.orthogonal(arg), assumptions) for arg in mmul.args) and + factor == 1): + return True + if any(ask(Q.invertible(arg), assumptions) is False + for arg in mmul.args): + return False + +@OrthogonalPredicate.register(MatPow) +def _(expr, assumptions): + # only for integer powers + base, exp = expr.args + int_exp = ask(Q.integer(exp), assumptions) + if int_exp: + return ask(Q.orthogonal(base), assumptions) + return None + +@OrthogonalPredicate.register(MatAdd) +def _(expr, assumptions): + if (len(expr.args) == 1 and + ask(Q.orthogonal(expr.args[0]), assumptions)): + return True + +@OrthogonalPredicate.register(MatrixSymbol) +def _(expr, assumptions): + if (not expr.is_square or + ask(Q.invertible(expr), assumptions) is False): + return False + if Q.orthogonal(expr) in conjuncts(assumptions): + return True + +@OrthogonalPredicate.register(Identity) +def _(expr, assumptions): + return True + +@OrthogonalPredicate.register(ZeroMatrix) +def _(expr, assumptions): + return False + +@OrthogonalPredicate.register_many(Inverse, Transpose) +def _(expr, assumptions): + return ask(Q.orthogonal(expr.arg), assumptions) + +@OrthogonalPredicate.register(MatrixSlice) +def _(expr, assumptions): + if not expr.on_diag: + return None + else: + return ask(Q.orthogonal(expr.parent), assumptions) + +@OrthogonalPredicate.register(Factorization) +def _(expr, assumptions): + return _Factorization(Q.orthogonal, expr, assumptions) + + +# UnitaryPredicate + +@UnitaryPredicate.register(MatMul) +def _(expr, assumptions): + factor, mmul = expr.as_coeff_mmul() + if (all(ask(Q.unitary(arg), assumptions) for arg in mmul.args) and + abs(factor) == 1): + return True + if any(ask(Q.invertible(arg), assumptions) is False + for arg in mmul.args): + return False + +@UnitaryPredicate.register(MatPow) +def _(expr, assumptions): + # only for integer powers + base, exp = expr.args + int_exp = ask(Q.integer(exp), assumptions) + if int_exp: + return ask(Q.unitary(base), assumptions) + return None + +@UnitaryPredicate.register(MatrixSymbol) +def _(expr, assumptions): + if (not expr.is_square or + ask(Q.invertible(expr), assumptions) is False): + return False + if Q.unitary(expr) in conjuncts(assumptions): + return True + +@UnitaryPredicate.register_many(Inverse, Transpose) +def _(expr, assumptions): + return ask(Q.unitary(expr.arg), assumptions) + +@UnitaryPredicate.register(MatrixSlice) +def _(expr, assumptions): + if not expr.on_diag: + return None + else: + return ask(Q.unitary(expr.parent), assumptions) + +@UnitaryPredicate.register_many(DFT, Identity) +def _(expr, assumptions): + return True + +@UnitaryPredicate.register(ZeroMatrix) +def _(expr, assumptions): + return False + +@UnitaryPredicate.register(Factorization) +def _(expr, assumptions): + return _Factorization(Q.unitary, expr, assumptions) + + +# FullRankPredicate + +@FullRankPredicate.register(MatMul) +def _(expr, assumptions): + if all(ask(Q.fullrank(arg), assumptions) for arg in expr.args): + return True + +@FullRankPredicate.register(MatPow) +def _(expr, assumptions): + # only for integer powers + base, exp = expr.args + int_exp = ask(Q.integer(exp), assumptions) + if int_exp and ask(~Q.negative(exp), assumptions): + return ask(Q.fullrank(base), assumptions) + return None + +@FullRankPredicate.register(Identity) +def _(expr, assumptions): + return True + +@FullRankPredicate.register(ZeroMatrix) +def _(expr, assumptions): + return False + +@FullRankPredicate.register(OneMatrix) +def _(expr, assumptions): + return expr.shape[0] == 1 and expr.shape[1] == 1 + +@FullRankPredicate.register_many(Inverse, Transpose) +def _(expr, assumptions): + return ask(Q.fullrank(expr.arg), assumptions) + +@FullRankPredicate.register(MatrixSlice) +def _(expr, assumptions): + if ask(Q.orthogonal(expr.parent), assumptions): + return True + + +# PositiveDefinitePredicate + +@PositiveDefinitePredicate.register(MatMul) +def _(expr, assumptions): + factor, mmul = expr.as_coeff_mmul() + if (all(ask(Q.positive_definite(arg), assumptions) + for arg in mmul.args) and factor > 0): + return True + if (len(mmul.args) >= 2 + and mmul.args[0] == mmul.args[-1].T + and ask(Q.fullrank(mmul.args[0]), assumptions)): + return ask(Q.positive_definite( + MatMul(*mmul.args[1:-1])), assumptions) + +@PositiveDefinitePredicate.register(MatPow) +def _(expr, assumptions): + # a power of a positive definite matrix is positive definite + if ask(Q.positive_definite(expr.args[0]), assumptions): + return True + +@PositiveDefinitePredicate.register(MatAdd) +def _(expr, assumptions): + if all(ask(Q.positive_definite(arg), assumptions) + for arg in expr.args): + return True + +@PositiveDefinitePredicate.register(MatrixSymbol) +def _(expr, assumptions): + if not expr.is_square: + return False + if Q.positive_definite(expr) in conjuncts(assumptions): + return True + +@PositiveDefinitePredicate.register(Identity) +def _(expr, assumptions): + return True + +@PositiveDefinitePredicate.register(ZeroMatrix) +def _(expr, assumptions): + return False + +@PositiveDefinitePredicate.register(OneMatrix) +def _(expr, assumptions): + return expr.shape[0] == 1 and expr.shape[1] == 1 + +@PositiveDefinitePredicate.register_many(Inverse, Transpose) +def _(expr, assumptions): + return ask(Q.positive_definite(expr.arg), assumptions) + +@PositiveDefinitePredicate.register(MatrixSlice) +def _(expr, assumptions): + if not expr.on_diag: + return None + else: + return ask(Q.positive_definite(expr.parent), assumptions) + + +# UpperTriangularPredicate + +@UpperTriangularPredicate.register(MatMul) +def _(expr, assumptions): + factor, matrices = expr.as_coeff_matrices() + if all(ask(Q.upper_triangular(m), assumptions) for m in matrices): + return True + +@UpperTriangularPredicate.register(MatAdd) +def _(expr, assumptions): + if all(ask(Q.upper_triangular(arg), assumptions) for arg in expr.args): + return True + +@UpperTriangularPredicate.register(MatPow) +def _(expr, assumptions): + # only for integer powers + base, exp = expr.args + int_exp = ask(Q.integer(exp), assumptions) + if not int_exp: + return None + non_negative = ask(~Q.negative(exp), assumptions) + if (non_negative or non_negative == False + and ask(Q.invertible(base), assumptions)): + return ask(Q.upper_triangular(base), assumptions) + return None + +@UpperTriangularPredicate.register(MatrixSymbol) +def _(expr, assumptions): + if Q.upper_triangular(expr) in conjuncts(assumptions): + return True + +@UpperTriangularPredicate.register_many(Identity, ZeroMatrix) +def _(expr, assumptions): + return True + +@UpperTriangularPredicate.register(OneMatrix) +def _(expr, assumptions): + return expr.shape[0] == 1 and expr.shape[1] == 1 + +@UpperTriangularPredicate.register(Transpose) +def _(expr, assumptions): + return ask(Q.lower_triangular(expr.arg), assumptions) + +@UpperTriangularPredicate.register(Inverse) +def _(expr, assumptions): + return ask(Q.upper_triangular(expr.arg), assumptions) + +@UpperTriangularPredicate.register(MatrixSlice) +def _(expr, assumptions): + if not expr.on_diag: + return None + else: + return ask(Q.upper_triangular(expr.parent), assumptions) + +@UpperTriangularPredicate.register(Factorization) +def _(expr, assumptions): + return _Factorization(Q.upper_triangular, expr, assumptions) + +# LowerTriangularPredicate + +@LowerTriangularPredicate.register(MatMul) +def _(expr, assumptions): + factor, matrices = expr.as_coeff_matrices() + if all(ask(Q.lower_triangular(m), assumptions) for m in matrices): + return True + +@LowerTriangularPredicate.register(MatAdd) +def _(expr, assumptions): + if all(ask(Q.lower_triangular(arg), assumptions) for arg in expr.args): + return True + +@LowerTriangularPredicate.register(MatPow) +def _(expr, assumptions): + # only for integer powers + base, exp = expr.args + int_exp = ask(Q.integer(exp), assumptions) + if not int_exp: + return None + non_negative = ask(~Q.negative(exp), assumptions) + if (non_negative or non_negative == False + and ask(Q.invertible(base), assumptions)): + return ask(Q.lower_triangular(base), assumptions) + return None + +@LowerTriangularPredicate.register(MatrixSymbol) +def _(expr, assumptions): + if Q.lower_triangular(expr) in conjuncts(assumptions): + return True + +@LowerTriangularPredicate.register_many(Identity, ZeroMatrix) +def _(expr, assumptions): + return True + +@LowerTriangularPredicate.register(OneMatrix) +def _(expr, assumptions): + return expr.shape[0] == 1 and expr.shape[1] == 1 + +@LowerTriangularPredicate.register(Transpose) +def _(expr, assumptions): + return ask(Q.upper_triangular(expr.arg), assumptions) + +@LowerTriangularPredicate.register(Inverse) +def _(expr, assumptions): + return ask(Q.lower_triangular(expr.arg), assumptions) + +@LowerTriangularPredicate.register(MatrixSlice) +def _(expr, assumptions): + if not expr.on_diag: + return None + else: + return ask(Q.lower_triangular(expr.parent), assumptions) + +@LowerTriangularPredicate.register(Factorization) +def _(expr, assumptions): + return _Factorization(Q.lower_triangular, expr, assumptions) + + +# DiagonalPredicate + +def _is_empty_or_1x1(expr): + return expr.shape in ((0, 0), (1, 1)) + +@DiagonalPredicate.register(MatMul) +def _(expr, assumptions): + if _is_empty_or_1x1(expr): + return True + factor, matrices = expr.as_coeff_matrices() + if all(ask(Q.diagonal(m), assumptions) for m in matrices): + return True + +@DiagonalPredicate.register(MatPow) +def _(expr, assumptions): + # only for integer powers + base, exp = expr.args + int_exp = ask(Q.integer(exp), assumptions) + if not int_exp: + return None + non_negative = ask(~Q.negative(exp), assumptions) + if (non_negative or non_negative == False + and ask(Q.invertible(base), assumptions)): + return ask(Q.diagonal(base), assumptions) + return None + +@DiagonalPredicate.register(MatAdd) +def _(expr, assumptions): + if all(ask(Q.diagonal(arg), assumptions) for arg in expr.args): + return True + +@DiagonalPredicate.register(MatrixSymbol) +def _(expr, assumptions): + if _is_empty_or_1x1(expr): + return True + if Q.diagonal(expr) in conjuncts(assumptions): + return True + +@DiagonalPredicate.register(OneMatrix) +def _(expr, assumptions): + return expr.shape[0] == 1 and expr.shape[1] == 1 + +@DiagonalPredicate.register_many(Inverse, Transpose) +def _(expr, assumptions): + return ask(Q.diagonal(expr.arg), assumptions) + +@DiagonalPredicate.register(MatrixSlice) +def _(expr, assumptions): + if _is_empty_or_1x1(expr): + return True + if not expr.on_diag: + return None + else: + return ask(Q.diagonal(expr.parent), assumptions) + +@DiagonalPredicate.register_many(DiagonalMatrix, DiagMatrix, Identity, ZeroMatrix) +def _(expr, assumptions): + return True + +@DiagonalPredicate.register(Factorization) +def _(expr, assumptions): + return _Factorization(Q.diagonal, expr, assumptions) + + +# IntegerElementsPredicate + +def BM_elements(predicate, expr, assumptions): + """ Block Matrix elements. """ + return all(ask(predicate(b), assumptions) for b in expr.blocks) + +def MS_elements(predicate, expr, assumptions): + """ Matrix Slice elements. """ + return ask(predicate(expr.parent), assumptions) + +def MatMul_elements(matrix_predicate, scalar_predicate, expr, assumptions): + d = sift(expr.args, lambda x: isinstance(x, MatrixExpr)) + factors, matrices = d[False], d[True] + return fuzzy_and([ + test_closed_group(Basic(*factors), assumptions, scalar_predicate), + test_closed_group(Basic(*matrices), assumptions, matrix_predicate)]) + + +@IntegerElementsPredicate.register_many(Determinant, HadamardProduct, MatAdd, + Trace, Transpose) +def _(expr, assumptions): + return test_closed_group(expr, assumptions, Q.integer_elements) + +@IntegerElementsPredicate.register(MatPow) +def _(expr, assumptions): + # only for integer powers + base, exp = expr.args + int_exp = ask(Q.integer(exp), assumptions) + if not int_exp: + return None + if exp.is_negative == False: + return ask(Q.integer_elements(base), assumptions) + return None + +@IntegerElementsPredicate.register_many(Identity, OneMatrix, ZeroMatrix) +def _(expr, assumptions): + return True + +@IntegerElementsPredicate.register(MatMul) +def _(expr, assumptions): + return MatMul_elements(Q.integer_elements, Q.integer, expr, assumptions) + +@IntegerElementsPredicate.register(MatrixSlice) +def _(expr, assumptions): + return MS_elements(Q.integer_elements, expr, assumptions) + +@IntegerElementsPredicate.register(BlockMatrix) +def _(expr, assumptions): + return BM_elements(Q.integer_elements, expr, assumptions) + + +# RealElementsPredicate + +@RealElementsPredicate.register_many(Determinant, Factorization, HadamardProduct, + MatAdd, Trace, Transpose) +def _(expr, assumptions): + return test_closed_group(expr, assumptions, Q.real_elements) + +@RealElementsPredicate.register(MatPow) +def _(expr, assumptions): + # only for integer powers + base, exp = expr.args + int_exp = ask(Q.integer(exp), assumptions) + if not int_exp: + return None + non_negative = ask(~Q.negative(exp), assumptions) + if (non_negative or non_negative == False + and ask(Q.invertible(base), assumptions)): + return ask(Q.real_elements(base), assumptions) + return None + +@RealElementsPredicate.register(MatMul) +def _(expr, assumptions): + return MatMul_elements(Q.real_elements, Q.real, expr, assumptions) + +@RealElementsPredicate.register(MatrixSlice) +def _(expr, assumptions): + return MS_elements(Q.real_elements, expr, assumptions) + +@RealElementsPredicate.register(BlockMatrix) +def _(expr, assumptions): + return BM_elements(Q.real_elements, expr, assumptions) + + +# ComplexElementsPredicate + +@ComplexElementsPredicate.register_many(Determinant, Factorization, HadamardProduct, + Inverse, MatAdd, Trace, Transpose) +def _(expr, assumptions): + return test_closed_group(expr, assumptions, Q.complex_elements) + +@ComplexElementsPredicate.register(MatPow) +def _(expr, assumptions): + # only for integer powers + base, exp = expr.args + int_exp = ask(Q.integer(exp), assumptions) + if not int_exp: + return None + non_negative = ask(~Q.negative(exp), assumptions) + if (non_negative or non_negative == False + and ask(Q.invertible(base), assumptions)): + return ask(Q.complex_elements(base), assumptions) + return None + +@ComplexElementsPredicate.register(MatMul) +def _(expr, assumptions): + return MatMul_elements(Q.complex_elements, Q.complex, expr, assumptions) + +@ComplexElementsPredicate.register(MatrixSlice) +def _(expr, assumptions): + return MS_elements(Q.complex_elements, expr, assumptions) + +@ComplexElementsPredicate.register(BlockMatrix) +def _(expr, assumptions): + return BM_elements(Q.complex_elements, expr, assumptions) + +@ComplexElementsPredicate.register(DFT) +def _(expr, assumptions): + return True diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/ntheory.py b/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/ntheory.py new file mode 100644 index 0000000000000000000000000000000000000000..cfe63ba6467ea6863c6112c5e35bb3a78191a23e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/ntheory.py @@ -0,0 +1,279 @@ +""" +Handlers for keys related to number theory: prime, even, odd, etc. +""" + +from sympy.assumptions import Q, ask +from sympy.core import Add, Basic, Expr, Float, Mul, Pow, S +from sympy.core.numbers import (ImaginaryUnit, Infinity, Integer, NaN, + NegativeInfinity, NumberSymbol, Rational, int_valued) +from sympy.functions import Abs, im, re +from sympy.ntheory import isprime + +from sympy.multipledispatch import MDNotImplementedError + +from ..predicates.ntheory import (PrimePredicate, CompositePredicate, + EvenPredicate, OddPredicate) + + +# PrimePredicate + +def _PrimePredicate_number(expr, assumptions): + # helper method + exact = not expr.atoms(Float) + try: + i = int(expr.round()) + if (expr - i).equals(0) is False: + raise TypeError + except TypeError: + return False + if exact: + return isprime(i) + # when not exact, we won't give a True or False + # since the number represents an approximate value + +@PrimePredicate.register(Expr) +def _(expr, assumptions): + ret = expr.is_prime + if ret is None: + raise MDNotImplementedError + return ret + +@PrimePredicate.register(Basic) +def _(expr, assumptions): + if expr.is_number: + return _PrimePredicate_number(expr, assumptions) + +@PrimePredicate.register(Mul) +def _(expr, assumptions): + if expr.is_number: + return _PrimePredicate_number(expr, assumptions) + for arg in expr.args: + if not ask(Q.integer(arg), assumptions): + return None + for arg in expr.args: + if arg.is_number and arg.is_composite: + return False + +@PrimePredicate.register(Pow) +def _(expr, assumptions): + """ + Integer**Integer -> !Prime + """ + if expr.is_number: + return _PrimePredicate_number(expr, assumptions) + if ask(Q.integer(expr.exp), assumptions) and \ + ask(Q.integer(expr.base), assumptions): + prime_base = ask(Q.prime(expr.base), assumptions) + if prime_base is False: + return False + is_exp_one = ask(Q.eq(expr.exp, 1), assumptions) + if is_exp_one is False: + return False + if prime_base is True and is_exp_one is True: + return True + +@PrimePredicate.register(Integer) +def _(expr, assumptions): + return isprime(expr) + +@PrimePredicate.register_many(Rational, Infinity, NegativeInfinity, ImaginaryUnit) +def _(expr, assumptions): + return False + +@PrimePredicate.register(Float) +def _(expr, assumptions): + return _PrimePredicate_number(expr, assumptions) + +@PrimePredicate.register(NumberSymbol) +def _(expr, assumptions): + return _PrimePredicate_number(expr, assumptions) + +@PrimePredicate.register(NaN) +def _(expr, assumptions): + return None + + +# CompositePredicate + +@CompositePredicate.register(Expr) +def _(expr, assumptions): + ret = expr.is_composite + if ret is None: + raise MDNotImplementedError + return ret + +@CompositePredicate.register(Basic) +def _(expr, assumptions): + _positive = ask(Q.positive(expr), assumptions) + if _positive: + _integer = ask(Q.integer(expr), assumptions) + if _integer: + _prime = ask(Q.prime(expr), assumptions) + if _prime is None: + return + # Positive integer which is not prime is not + # necessarily composite + _is_one = ask(Q.eq(expr, 1), assumptions) + if _is_one: + return False + if _is_one is None: + return None + return not _prime + else: + return _integer + else: + return _positive + + +# EvenPredicate + +def _EvenPredicate_number(expr, assumptions): + # helper method + if isinstance(expr, (float, Float)): + if int_valued(expr): + return None + return False + try: + i = int(expr.round()) + except TypeError: + return False + if not (expr - i).equals(0): + return False + return i % 2 == 0 + +@EvenPredicate.register(Expr) +def _(expr, assumptions): + ret = expr.is_even + if ret is None: + raise MDNotImplementedError + return ret + +@EvenPredicate.register(Basic) +def _(expr, assumptions): + if expr.is_number: + return _EvenPredicate_number(expr, assumptions) + +@EvenPredicate.register(Mul) +def _(expr, assumptions): + """ + Even * Integer -> Even + Even * Odd -> Even + Integer * Odd -> ? + Odd * Odd -> Odd + Even * Even -> Even + Integer * Integer -> Even if Integer + Integer = Odd + otherwise -> ? + """ + if expr.is_number: + return _EvenPredicate_number(expr, assumptions) + even, odd, irrational, acc = False, 0, False, 1 + for arg in expr.args: + # check for all integers and at least one even + if ask(Q.integer(arg), assumptions): + if ask(Q.even(arg), assumptions): + even = True + elif ask(Q.odd(arg), assumptions): + odd += 1 + elif not even and acc != 1: + if ask(Q.odd(acc + arg), assumptions): + even = True + elif ask(Q.irrational(arg), assumptions): + # one irrational makes the result False + # two makes it undefined + if irrational: + break + irrational = True + else: + break + acc = arg + else: + if irrational: + return False + if even: + return True + if odd == len(expr.args): + return False + +@EvenPredicate.register(Add) +def _(expr, assumptions): + """ + Even + Odd -> Odd + Even + Even -> Even + Odd + Odd -> Even + + """ + if expr.is_number: + return _EvenPredicate_number(expr, assumptions) + _result = True + for arg in expr.args: + if ask(Q.even(arg), assumptions): + pass + elif ask(Q.odd(arg), assumptions): + _result = not _result + else: + break + else: + return _result + +@EvenPredicate.register(Pow) +def _(expr, assumptions): + if expr.is_number: + return _EvenPredicate_number(expr, assumptions) + if ask(Q.integer(expr.exp), assumptions): + if ask(Q.positive(expr.exp), assumptions): + return ask(Q.even(expr.base), assumptions) + elif ask(~Q.negative(expr.exp) & Q.odd(expr.base), assumptions): + return False + elif expr.base is S.NegativeOne: + return False + +@EvenPredicate.register(Integer) +def _(expr, assumptions): + return not bool(expr.p & 1) + +@EvenPredicate.register_many(Rational, Infinity, NegativeInfinity, ImaginaryUnit) +def _(expr, assumptions): + return False + +@EvenPredicate.register(NumberSymbol) +def _(expr, assumptions): + return _EvenPredicate_number(expr, assumptions) + +@EvenPredicate.register(Abs) +def _(expr, assumptions): + if ask(Q.real(expr.args[0]), assumptions): + return ask(Q.even(expr.args[0]), assumptions) + +@EvenPredicate.register(re) +def _(expr, assumptions): + if ask(Q.real(expr.args[0]), assumptions): + return ask(Q.even(expr.args[0]), assumptions) + +@EvenPredicate.register(im) +def _(expr, assumptions): + if ask(Q.real(expr.args[0]), assumptions): + return True + +@EvenPredicate.register(NaN) +def _(expr, assumptions): + return None + + +# OddPredicate + +@OddPredicate.register(Expr) +def _(expr, assumptions): + ret = expr.is_odd + if ret is None: + raise MDNotImplementedError + return ret + +@OddPredicate.register(Basic) +def _(expr, assumptions): + _integer = ask(Q.integer(expr), assumptions) + if _integer: + _even = ask(Q.even(expr), assumptions) + if _even is None: + return None + return not _even + return _integer diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/order.py b/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/order.py new file mode 100644 index 0000000000000000000000000000000000000000..24a8bae7f30777f62a1bec0579d58b9875143679 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/order.py @@ -0,0 +1,440 @@ +""" +Handlers related to order relations: positive, negative, etc. +""" + +from sympy.assumptions import Q, ask +from sympy.core import Add, Basic, Expr, Mul, Pow, S +from sympy.core.logic import fuzzy_not, fuzzy_and, fuzzy_or +from sympy.core.numbers import E, ImaginaryUnit, NaN, I, pi +from sympy.functions import Abs, acos, acot, asin, atan, exp, factorial, log +from sympy.matrices import Determinant, Trace +from sympy.matrices.expressions.matexpr import MatrixElement + +from sympy.multipledispatch import MDNotImplementedError + +from ..predicates.order import (NegativePredicate, NonNegativePredicate, + NonZeroPredicate, ZeroPredicate, NonPositivePredicate, PositivePredicate, + ExtendedNegativePredicate, ExtendedNonNegativePredicate, + ExtendedNonPositivePredicate, ExtendedNonZeroPredicate, + ExtendedPositivePredicate,) + + +# NegativePredicate + +def _NegativePredicate_number(expr, assumptions): + r, i = expr.as_real_imag() + + if r == S.NaN or i == S.NaN: + return None + + # If the imaginary part can symbolically be shown to be zero then + # we just evaluate the real part; otherwise we evaluate the imaginary + # part to see if it actually evaluates to zero and if it does then + # we make the comparison between the real part and zero. + if not i: + r = r.evalf(2) + if r._prec != 1: + return r < 0 + else: + i = i.evalf(2) + if i._prec != 1: + if i != 0: + return False + r = r.evalf(2) + if r._prec != 1: + return r < 0 + +@NegativePredicate.register(Basic) +def _(expr, assumptions): + if expr.is_number: + return _NegativePredicate_number(expr, assumptions) + +@NegativePredicate.register(Expr) +def _(expr, assumptions): + ret = expr.is_negative + if ret is None: + raise MDNotImplementedError + return ret + +@NegativePredicate.register(Add) +def _(expr, assumptions): + """ + Positive + Positive -> Positive, + Negative + Negative -> Negative + """ + if expr.is_number: + return _NegativePredicate_number(expr, assumptions) + + r = ask(Q.real(expr), assumptions) + if r is not True: + return r + + nonpos = 0 + for arg in expr.args: + if ask(Q.negative(arg), assumptions) is not True: + if ask(Q.positive(arg), assumptions) is False: + nonpos += 1 + else: + break + else: + if nonpos < len(expr.args): + return True + +@NegativePredicate.register(Mul) +def _(expr, assumptions): + if expr.is_number: + return _NegativePredicate_number(expr, assumptions) + result = None + for arg in expr.args: + if result is None: + result = False + if ask(Q.negative(arg), assumptions): + result = not result + elif ask(Q.positive(arg), assumptions): + pass + else: + return + return result + +@NegativePredicate.register(Pow) +def _(expr, assumptions): + """ + Real ** Even -> NonNegative + Real ** Odd -> same_as_base + NonNegative ** Positive -> NonNegative + """ + if expr.base == E: + # Exponential is always positive: + if ask(Q.real(expr.exp), assumptions): + return False + return + + if expr.is_number: + return _NegativePredicate_number(expr, assumptions) + if ask(Q.real(expr.base), assumptions): + if ask(Q.positive(expr.base), assumptions): + if ask(Q.real(expr.exp), assumptions): + return False + if ask(Q.even(expr.exp), assumptions): + return False + if ask(Q.odd(expr.exp), assumptions): + return ask(Q.negative(expr.base), assumptions) + +@NegativePredicate.register_many(Abs, ImaginaryUnit) +def _(expr, assumptions): + return False + +@NegativePredicate.register(exp) +def _(expr, assumptions): + if ask(Q.real(expr.exp), assumptions): + return False + raise MDNotImplementedError + + +# NonNegativePredicate + +@NonNegativePredicate.register(Basic) +def _(expr, assumptions): + if expr.is_number: + notnegative = fuzzy_not(_NegativePredicate_number(expr, assumptions)) + if notnegative: + return ask(Q.real(expr), assumptions) + else: + return notnegative + +@NonNegativePredicate.register(Expr) +def _(expr, assumptions): + ret = expr.is_nonnegative + if ret is None: + raise MDNotImplementedError + return ret + + +# NonZeroPredicate + +@NonZeroPredicate.register(Expr) +def _(expr, assumptions): + ret = expr.is_nonzero + if ret is None: + raise MDNotImplementedError + return ret + +@NonZeroPredicate.register(Basic) +def _(expr, assumptions): + if ask(Q.real(expr)) is False: + return False + if expr.is_number: + # if there are no symbols just evalf + i = expr.evalf(2) + def nonz(i): + if i._prec != 1: + return i != 0 + return fuzzy_or(nonz(i) for i in i.as_real_imag()) + +@NonZeroPredicate.register(Add) +def _(expr, assumptions): + if all(ask(Q.positive(x), assumptions) for x in expr.args) \ + or all(ask(Q.negative(x), assumptions) for x in expr.args): + return True + +@NonZeroPredicate.register(Mul) +def _(expr, assumptions): + for arg in expr.args: + result = ask(Q.nonzero(arg), assumptions) + if result: + continue + return result + return True + +@NonZeroPredicate.register(Pow) +def _(expr, assumptions): + return ask(Q.nonzero(expr.base), assumptions) + +@NonZeroPredicate.register(Abs) +def _(expr, assumptions): + return ask(Q.nonzero(expr.args[0]), assumptions) + +@NonZeroPredicate.register(NaN) +def _(expr, assumptions): + return None + + +# ZeroPredicate + +@ZeroPredicate.register(Expr) +def _(expr, assumptions): + ret = expr.is_zero + if ret is None: + raise MDNotImplementedError + return ret + +@ZeroPredicate.register(Basic) +def _(expr, assumptions): + return fuzzy_and([fuzzy_not(ask(Q.nonzero(expr), assumptions)), + ask(Q.real(expr), assumptions)]) + +@ZeroPredicate.register(Mul) +def _(expr, assumptions): + # TODO: This should be deducible from the nonzero handler + return fuzzy_or(ask(Q.zero(arg), assumptions) for arg in expr.args) + + +# NonPositivePredicate + +@NonPositivePredicate.register(Expr) +def _(expr, assumptions): + ret = expr.is_nonpositive + if ret is None: + raise MDNotImplementedError + return ret + +@NonPositivePredicate.register(Basic) +def _(expr, assumptions): + if expr.is_number: + notpositive = fuzzy_not(_PositivePredicate_number(expr, assumptions)) + if notpositive: + return ask(Q.real(expr), assumptions) + else: + return notpositive + + +# PositivePredicate + +def _PositivePredicate_number(expr, assumptions): + r, i = expr.as_real_imag() + # If the imaginary part can symbolically be shown to be zero then + # we just evaluate the real part; otherwise we evaluate the imaginary + # part to see if it actually evaluates to zero and if it does then + # we make the comparison between the real part and zero. + if not i: + r = r.evalf(2) + if r._prec != 1: + return r > 0 + else: + i = i.evalf(2) + if i._prec != 1: + if i != 0: + return False + r = r.evalf(2) + if r._prec != 1: + return r > 0 + +@PositivePredicate.register(Expr) +def _(expr, assumptions): + ret = expr.is_positive + if ret is None: + raise MDNotImplementedError + return ret + +@PositivePredicate.register(Basic) +def _(expr, assumptions): + if expr.is_number: + return _PositivePredicate_number(expr, assumptions) + +@PositivePredicate.register(Mul) +def _(expr, assumptions): + if expr.is_number: + return _PositivePredicate_number(expr, assumptions) + result = True + for arg in expr.args: + if ask(Q.positive(arg), assumptions): + continue + elif ask(Q.negative(arg), assumptions): + result = result ^ True + else: + return + return result + +@PositivePredicate.register(Add) +def _(expr, assumptions): + if expr.is_number: + return _PositivePredicate_number(expr, assumptions) + + r = ask(Q.real(expr), assumptions) + if r is not True: + return r + + nonneg = 0 + for arg in expr.args: + if ask(Q.positive(arg), assumptions) is not True: + if ask(Q.negative(arg), assumptions) is False: + nonneg += 1 + else: + break + else: + if nonneg < len(expr.args): + return True + +@PositivePredicate.register(Pow) +def _(expr, assumptions): + if expr.base == E: + if ask(Q.real(expr.exp), assumptions): + return True + if ask(Q.imaginary(expr.exp), assumptions): + return ask(Q.even(expr.exp/(I*pi)), assumptions) + return + + if expr.is_number: + return _PositivePredicate_number(expr, assumptions) + if ask(Q.positive(expr.base), assumptions): + if ask(Q.real(expr.exp), assumptions): + return True + if ask(Q.negative(expr.base), assumptions): + if ask(Q.even(expr.exp), assumptions): + return True + if ask(Q.odd(expr.exp), assumptions): + return False + +@PositivePredicate.register(exp) +def _(expr, assumptions): + if ask(Q.real(expr.exp), assumptions): + return True + if ask(Q.imaginary(expr.exp), assumptions): + return ask(Q.even(expr.exp/(I*pi)), assumptions) + +@PositivePredicate.register(log) +def _(expr, assumptions): + r = ask(Q.real(expr.args[0]), assumptions) + if r is not True: + return r + if ask(Q.positive(expr.args[0] - 1), assumptions): + return True + if ask(Q.negative(expr.args[0] - 1), assumptions): + return False + +@PositivePredicate.register(factorial) +def _(expr, assumptions): + x = expr.args[0] + if ask(Q.integer(x) & Q.positive(x), assumptions): + return True + +@PositivePredicate.register(ImaginaryUnit) +def _(expr, assumptions): + return False + +@PositivePredicate.register(Abs) +def _(expr, assumptions): + return ask(Q.nonzero(expr), assumptions) + +@PositivePredicate.register(Trace) +def _(expr, assumptions): + if ask(Q.positive_definite(expr.arg), assumptions): + return True + +@PositivePredicate.register(Determinant) +def _(expr, assumptions): + if ask(Q.positive_definite(expr.arg), assumptions): + return True + +@PositivePredicate.register(MatrixElement) +def _(expr, assumptions): + if (expr.i == expr.j + and ask(Q.positive_definite(expr.parent), assumptions)): + return True + +@PositivePredicate.register(atan) +def _(expr, assumptions): + return ask(Q.positive(expr.args[0]), assumptions) + +@PositivePredicate.register(asin) +def _(expr, assumptions): + x = expr.args[0] + if ask(Q.positive(x) & Q.nonpositive(x - 1), assumptions): + return True + if ask(Q.negative(x) & Q.nonnegative(x + 1), assumptions): + return False + +@PositivePredicate.register(acos) +def _(expr, assumptions): + x = expr.args[0] + if ask(Q.nonpositive(x - 1) & Q.nonnegative(x + 1), assumptions): + return True + +@PositivePredicate.register(acot) +def _(expr, assumptions): + return ask(Q.real(expr.args[0]), assumptions) + +@PositivePredicate.register(NaN) +def _(expr, assumptions): + return None + + +# ExtendedNegativePredicate + +@ExtendedNegativePredicate.register(object) +def _(expr, assumptions): + return ask(Q.negative(expr) | Q.negative_infinite(expr), assumptions) + + +# ExtendedPositivePredicate + +@ExtendedPositivePredicate.register(object) +def _(expr, assumptions): + return ask(Q.positive(expr) | Q.positive_infinite(expr), assumptions) + + +# ExtendedNonZeroPredicate + +@ExtendedNonZeroPredicate.register(object) +def _(expr, assumptions): + return ask( + Q.negative_infinite(expr) | Q.negative(expr) | Q.positive(expr) | Q.positive_infinite(expr), + assumptions) + + +# ExtendedNonPositivePredicate + +@ExtendedNonPositivePredicate.register(object) +def _(expr, assumptions): + return ask( + Q.negative_infinite(expr) | Q.negative(expr) | Q.zero(expr), + assumptions) + + +# ExtendedNonNegativePredicate + +@ExtendedNonNegativePredicate.register(object) +def _(expr, assumptions): + return ask( + Q.zero(expr) | Q.positive(expr) | Q.positive_infinite(expr), + assumptions) diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/sets.py b/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/sets.py new file mode 100644 index 0000000000000000000000000000000000000000..7a13ed9bf99c5b0ffc4f32fd55cb60c2c15ab836 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/assumptions/handlers/sets.py @@ -0,0 +1,816 @@ +""" +Handlers for predicates related to set membership: integer, rational, etc. +""" + +from sympy.assumptions import Q, ask +from sympy.core import Add, Basic, Expr, Mul, Pow, S +from sympy.core.numbers import (AlgebraicNumber, ComplexInfinity, Exp1, Float, + GoldenRatio, ImaginaryUnit, Infinity, Integer, NaN, NegativeInfinity, + Number, NumberSymbol, Pi, pi, Rational, TribonacciConstant, E) +from sympy.core.logic import fuzzy_bool +from sympy.functions import (Abs, acos, acot, asin, atan, cos, cot, exp, im, + log, re, sin, tan) +from sympy.core.numbers import I +from sympy.core.relational import Eq +from sympy.functions.elementary.complexes import conjugate +from sympy.matrices import Determinant, MatrixBase, Trace +from sympy.matrices.expressions.matexpr import MatrixElement + +from sympy.multipledispatch import MDNotImplementedError + +from .common import test_closed_group, ask_all, ask_any +from ..predicates.sets import (IntegerPredicate, RationalPredicate, + IrrationalPredicate, RealPredicate, ExtendedRealPredicate, + HermitianPredicate, ComplexPredicate, ImaginaryPredicate, + AntihermitianPredicate, AlgebraicPredicate) + + +# IntegerPredicate + +def _IntegerPredicate_number(expr, assumptions): + # helper function + try: + i = int(expr.round()) + if not (expr - i).equals(0): + raise TypeError + return True + except TypeError: + return False + +@IntegerPredicate.register_many(int, Integer) # type:ignore +def _(expr, assumptions): + return True + +@IntegerPredicate.register_many(Exp1, GoldenRatio, ImaginaryUnit, Infinity, + NegativeInfinity, Pi, Rational, TribonacciConstant) +def _(expr, assumptions): + return False + +@IntegerPredicate.register(Expr) +def _(expr, assumptions): + ret = expr.is_integer + if ret is None: + raise MDNotImplementedError + return ret + +@IntegerPredicate.register(Add) +def _(expr, assumptions): + """ + * Integer + Integer -> Integer + * Integer + !Integer -> !Integer + * !Integer + !Integer -> ? + """ + if expr.is_number: + return _IntegerPredicate_number(expr, assumptions) + return test_closed_group(expr, assumptions, Q.integer) + +@IntegerPredicate.register(Pow) +def _(expr,assumptions): + if expr.is_number: + return _IntegerPredicate_number(expr, assumptions) + if ask_all(~Q.zero(expr.base), Q.finite(expr.base), Q.zero(expr.exp), assumptions=assumptions): + return True + if ask_all(Q.integer(expr.base), Q.integer(expr.exp), assumptions=assumptions): + if ask_any(Q.positive(expr.exp), Q.nonnegative(expr.exp) & ~Q.zero(expr.base), Q.zero(expr.base-1), Q.zero(expr.base+1), assumptions=assumptions): + return True + +@IntegerPredicate.register(Mul) +def _(expr, assumptions): + """ + * Integer*Integer -> Integer + * Integer*Irrational -> !Integer + * Odd/Even -> !Integer + * Integer*Rational -> ? + """ + if expr.is_number: + return _IntegerPredicate_number(expr, assumptions) + _output = True + for arg in expr.args: + if not ask(Q.integer(arg), assumptions): + if arg.is_Rational: + if arg.q == 2: + return ask(Q.even(2*expr), assumptions) + if ~(arg.q & 1): + return None + elif ask(Q.irrational(arg), assumptions): + if _output: + _output = False + else: + return + else: + return + + return _output + +@IntegerPredicate.register(Abs) +def _(expr, assumptions): + if ask(Q.integer(expr.args[0]), assumptions): + return True + +@IntegerPredicate.register_many(Determinant, MatrixElement, Trace) +def _(expr, assumptions): + return ask(Q.integer_elements(expr.args[0]), assumptions) + + +# RationalPredicate + +@RationalPredicate.register(Rational) +def _(expr, assumptions): + return True + +@RationalPredicate.register(Float) +def _(expr, assumptions): + return None + +@RationalPredicate.register_many(Exp1, GoldenRatio, ImaginaryUnit, Infinity, + NegativeInfinity, Pi, TribonacciConstant) +def _(expr, assumptions): + return False + +@RationalPredicate.register(Expr) +def _(expr, assumptions): + ret = expr.is_rational + if ret is None: + raise MDNotImplementedError + return ret + +@RationalPredicate.register_many(Add, Mul) +def _(expr, assumptions): + """ + * Rational + Rational -> Rational + * Rational + !Rational -> !Rational + * !Rational + !Rational -> ? + """ + if expr.is_number: + if expr.as_real_imag()[1]: + return False + return test_closed_group(expr, assumptions, Q.rational) + +@RationalPredicate.register(Pow) +def _(expr, assumptions): + """ + * Rational ** Integer -> Rational + * Irrational ** Rational -> Irrational + * Rational ** Irrational -> ? + """ + if expr.base == E: + x = expr.exp + if ask(Q.rational(x), assumptions): + return ask(Q.zero(x), assumptions) + return + + is_exp_integer = ask(Q.integer(expr.exp), assumptions) + if is_exp_integer: + is_base_rational = ask(Q.rational(expr.base),assumptions) + if is_base_rational: + is_base_zero = ask(Q.zero(expr.base),assumptions) + if is_base_zero is False: + return True + if is_base_zero and ask(Q.positive(expr.exp)): + return True + if ask(Q.algebraic(expr.base),assumptions) is False: + return ask(Q.zero(expr.exp), assumptions) + if ask(Q.irrational(expr.base),assumptions) and ask(Q.eq(expr.exp,-1)): + return False + return + elif ask(Q.rational(expr.exp), assumptions): + if ask(Q.prime(expr.base), assumptions) and is_exp_integer is False: + return False + if ask(Q.zero(expr.base)) and ask(Q.positive(expr.exp)): + return True + if ask(Q.eq(expr.base,1)): + return True + +@RationalPredicate.register_many(asin, atan, cos, sin, tan) +def _(expr, assumptions): + x = expr.args[0] + if ask(Q.rational(x), assumptions): + return ask(~Q.nonzero(x), assumptions) + +@RationalPredicate.register(exp) +def _(expr, assumptions): + x = expr.exp + if ask(Q.rational(x), assumptions): + return ask(~Q.nonzero(x), assumptions) + +@RationalPredicate.register_many(acot, cot) +def _(expr, assumptions): + x = expr.args[0] + if ask(Q.rational(x), assumptions): + return False + +@RationalPredicate.register_many(acos, log) +def _(expr, assumptions): + x = expr.args[0] + if ask(Q.rational(x), assumptions): + return ask(~Q.nonzero(x - 1), assumptions) + + +# IrrationalPredicate + +@IrrationalPredicate.register(Expr) +def _(expr, assumptions): + ret = expr.is_irrational + if ret is None: + raise MDNotImplementedError + return ret + +@IrrationalPredicate.register(Basic) +def _(expr, assumptions): + _real = ask(Q.real(expr), assumptions) + if _real: + _rational = ask(Q.rational(expr), assumptions) + if _rational is None: + return None + return not _rational + else: + return _real + + +# RealPredicate + +def _RealPredicate_number(expr, assumptions): + # let as_real_imag() work first since the expression may + # be simpler to evaluate + i = expr.as_real_imag()[1].evalf(2) + if i._prec != 1: + return not i + # allow None to be returned if we couldn't show for sure + # that i was 0 + +@RealPredicate.register_many(Abs, Exp1, Float, GoldenRatio, im, Pi, Rational, + re, TribonacciConstant) +def _(expr, assumptions): + return True + +@RealPredicate.register_many(ImaginaryUnit, Infinity, NegativeInfinity) +def _(expr, assumptions): + return False + +@RealPredicate.register(Expr) +def _(expr, assumptions): + ret = expr.is_real + if ret is None: + raise MDNotImplementedError + return ret + +@RealPredicate.register(Add) +def _(expr, assumptions): + """ + * Real + Real -> Real + * Real + (Complex & !Real) -> !Real + """ + if expr.is_number: + return _RealPredicate_number(expr, assumptions) + return test_closed_group(expr, assumptions, Q.real) + +@RealPredicate.register(Mul) +def _(expr, assumptions): + """ + * Real*Real -> Real + * Real*Imaginary -> !Real + * Imaginary*Imaginary -> Real + """ + if expr.is_number: + return _RealPredicate_number(expr, assumptions) + result = True + for arg in expr.args: + if ask(Q.real(arg), assumptions): + pass + elif ask(Q.imaginary(arg), assumptions): + result = result ^ True + else: + break + else: + return result + +@RealPredicate.register(Pow) +def _(expr, assumptions): + """ + * Real**Integer -> Real + * Positive**Real -> Real + * Negative**Real -> ? + * Real**(Integer/Even) -> Real if base is nonnegative + * Real**(Integer/Odd) -> Real + * Imaginary**(Integer/Even) -> Real + * Imaginary**(Integer/Odd) -> not Real + * Imaginary**Real -> ? since Real could be 0 (giving real) + or 1 (giving imaginary) + * b**Imaginary -> Real if log(b) is imaginary and b != 0 + and exponent != integer multiple of + I*pi/log(b) + * Real**Real -> ? e.g. sqrt(-1) is imaginary and + sqrt(2) is not + """ + if expr.is_number: + return _RealPredicate_number(expr, assumptions) + + if expr.base == E: + return ask( + Q.integer(expr.exp/I/pi) | Q.real(expr.exp), assumptions + ) + + if expr.base.func == exp or (expr.base.is_Pow and expr.base.base == E): + if ask(Q.imaginary(expr.base.exp), assumptions): + if ask(Q.imaginary(expr.exp), assumptions): + return True + # If the i = (exp's arg)/(I*pi) is an integer or half-integer + # multiple of I*pi then 2*i will be an integer. In addition, + # exp(i*I*pi) = (-1)**i so the overall realness of the expr + # can be determined by replacing exp(i*I*pi) with (-1)**i. + i = expr.base.exp/I/pi + if ask(Q.integer(2*i), assumptions): + return ask(Q.real((S.NegativeOne**i)**expr.exp), assumptions) + return + + if ask(Q.imaginary(expr.base), assumptions): + if ask(Q.integer(expr.exp), assumptions): + odd = ask(Q.odd(expr.exp), assumptions) + if odd is not None: + return not odd + return + + if ask(Q.imaginary(expr.exp), assumptions): + imlog = ask(Q.imaginary(log(expr.base)), assumptions) + if imlog is not None: + # I**i -> real, log(I) is imag; + # (2*I)**i -> complex, log(2*I) is not imag + return imlog + + if ask(Q.real(expr.base), assumptions): + if ask(Q.real(expr.exp), assumptions): + if ask(Q.zero(expr.base), assumptions) is not False: + if ask(Q.positive(expr.exp), assumptions): + return True + return + if expr.exp.is_Rational and \ + ask(Q.even(expr.exp.q), assumptions): + return ask(Q.positive(expr.base), assumptions) + elif ask(Q.integer(expr.exp), assumptions): + return True + elif ask(Q.positive(expr.base), assumptions): + return True + +@RealPredicate.register_many(cos, sin) +def _(expr, assumptions): + if ask(Q.real(expr.args[0]), assumptions): + return True + +@RealPredicate.register(exp) +def _(expr, assumptions): + return ask( + Q.integer(expr.exp/I/pi) | Q.real(expr.exp), assumptions + ) + +@RealPredicate.register(log) +def _(expr, assumptions): + return ask(Q.positive(expr.args[0]), assumptions) + +@RealPredicate.register_many(Determinant, MatrixElement, Trace) +def _(expr, assumptions): + return ask(Q.real_elements(expr.args[0]), assumptions) + + +# ExtendedRealPredicate + +@ExtendedRealPredicate.register(object) +def _(expr, assumptions): + return ask(Q.negative_infinite(expr) + | Q.negative(expr) + | Q.zero(expr) + | Q.positive(expr) + | Q.positive_infinite(expr), + assumptions) + +@ExtendedRealPredicate.register_many(Infinity, NegativeInfinity) +def _(expr, assumptions): + return True + +@ExtendedRealPredicate.register_many(Add, Mul, Pow) # type:ignore +def _(expr, assumptions): + return test_closed_group(expr, assumptions, Q.extended_real) + + +# HermitianPredicate + +@HermitianPredicate.register(object) # type:ignore +def _(expr, assumptions): + if isinstance(expr, MatrixBase): + return None + return ask(Q.real(expr), assumptions) + +@HermitianPredicate.register(Add) # type:ignore +def _(expr, assumptions): + """ + * Hermitian + Hermitian -> Hermitian + * Hermitian + !Hermitian -> !Hermitian + """ + if expr.is_number: + raise MDNotImplementedError + return test_closed_group(expr, assumptions, Q.hermitian) + +@HermitianPredicate.register(Mul) # type:ignore +def _(expr, assumptions): + """ + As long as there is at most only one noncommutative term: + + * Hermitian*Hermitian -> Hermitian + * Hermitian*Antihermitian -> !Hermitian + * Antihermitian*Antihermitian -> Hermitian + """ + if expr.is_number: + raise MDNotImplementedError + nccount = 0 + result = True + for arg in expr.args: + if ask(Q.antihermitian(arg), assumptions): + result = result ^ True + elif not ask(Q.hermitian(arg), assumptions): + break + if ask(~Q.commutative(arg), assumptions): + nccount += 1 + if nccount > 1: + break + else: + return result + +@HermitianPredicate.register(Pow) # type:ignore +def _(expr, assumptions): + """ + * Hermitian**Integer -> Hermitian + """ + if expr.is_number: + raise MDNotImplementedError + if expr.base == E: + if ask(Q.hermitian(expr.exp), assumptions): + return True + raise MDNotImplementedError + if ask(Q.hermitian(expr.base), assumptions): + if ask(Q.integer(expr.exp), assumptions): + return True + raise MDNotImplementedError + +@HermitianPredicate.register_many(cos, sin) # type:ignore +def _(expr, assumptions): + if ask(Q.hermitian(expr.args[0]), assumptions): + return True + raise MDNotImplementedError + +@HermitianPredicate.register(exp) # type:ignore +def _(expr, assumptions): + if ask(Q.hermitian(expr.exp), assumptions): + return True + raise MDNotImplementedError + +@HermitianPredicate.register(MatrixBase) # type:ignore +def _(mat, assumptions): + rows, cols = mat.shape + ret_val = True + for i in range(rows): + for j in range(i, cols): + cond = fuzzy_bool(Eq(mat[i, j], conjugate(mat[j, i]))) + if cond is None: + ret_val = None + if cond == False: + return False + if ret_val is None: + raise MDNotImplementedError + return ret_val + + +# ComplexPredicate + +@ComplexPredicate.register_many(Abs, cos, exp, im, ImaginaryUnit, log, Number, # type:ignore + NumberSymbol, re, sin) +def _(expr, assumptions): + return True + +@ComplexPredicate.register_many(Infinity, NegativeInfinity) # type:ignore +def _(expr, assumptions): + return False + +@ComplexPredicate.register(Expr) # type:ignore +def _(expr, assumptions): + ret = expr.is_complex + if ret is None: + raise MDNotImplementedError + return ret + +@ComplexPredicate.register_many(Add, Mul) # type:ignore +def _(expr, assumptions): + return test_closed_group(expr, assumptions, Q.complex) + +@ComplexPredicate.register(Pow) # type:ignore +def _(expr, assumptions): + if expr.base == E: + return True + return test_closed_group(expr, assumptions, Q.complex) + +@ComplexPredicate.register_many(Determinant, MatrixElement, Trace) # type:ignore +def _(expr, assumptions): + return ask(Q.complex_elements(expr.args[0]), assumptions) + +@ComplexPredicate.register(NaN) # type:ignore +def _(expr, assumptions): + return None + + +# ImaginaryPredicate + +def _Imaginary_number(expr, assumptions): + # let as_real_imag() work first since the expression may + # be simpler to evaluate + r = expr.as_real_imag()[0].evalf(2) + if r._prec != 1: + return not r + # allow None to be returned if we couldn't show for sure + # that r was 0 + +@ImaginaryPredicate.register(ImaginaryUnit) # type:ignore +def _(expr, assumptions): + return True + +@ImaginaryPredicate.register(Expr) # type:ignore +def _(expr, assumptions): + ret = expr.is_imaginary + if ret is None: + raise MDNotImplementedError + return ret + +@ImaginaryPredicate.register(Add) # type:ignore +def _(expr, assumptions): + """ + * Imaginary + Imaginary -> Imaginary + * Imaginary + Complex -> ? + * Imaginary + Real -> !Imaginary + """ + if expr.is_number: + return _Imaginary_number(expr, assumptions) + + reals = 0 + for arg in expr.args: + if ask(Q.imaginary(arg), assumptions): + pass + elif ask(Q.real(arg), assumptions): + reals += 1 + else: + break + else: + if reals == 0: + return True + if reals in (1, len(expr.args)): + # two reals could sum 0 thus giving an imaginary + return False + +@ImaginaryPredicate.register(Mul) # type:ignore +def _(expr, assumptions): + """ + * Real*Imaginary -> Imaginary + * Imaginary*Imaginary -> Real + """ + if expr.is_number: + return _Imaginary_number(expr, assumptions) + result = False + reals = 0 + for arg in expr.args: + if ask(Q.imaginary(arg), assumptions): + result = result ^ True + elif not ask(Q.real(arg), assumptions): + break + else: + if reals == len(expr.args): + return False + return result + +@ImaginaryPredicate.register(Pow) # type:ignore +def _(expr, assumptions): + """ + * Imaginary**Odd -> Imaginary + * Imaginary**Even -> Real + * b**Imaginary -> !Imaginary if exponent is an integer + multiple of I*pi/log(b) + * Imaginary**Real -> ? + * Positive**Real -> Real + * Negative**Integer -> Real + * Negative**(Integer/2) -> Imaginary + * Negative**Real -> not Imaginary if exponent is not Rational + """ + if expr.is_number: + return _Imaginary_number(expr, assumptions) + + if expr.base == E: + a = expr.exp/I/pi + return ask(Q.integer(2*a) & ~Q.integer(a), assumptions) + + if expr.base.func == exp or (expr.base.is_Pow and expr.base.base == E): + if ask(Q.imaginary(expr.base.exp), assumptions): + if ask(Q.imaginary(expr.exp), assumptions): + return False + i = expr.base.exp/I/pi + if ask(Q.integer(2*i), assumptions): + return ask(Q.imaginary((S.NegativeOne**i)**expr.exp), assumptions) + + if ask(Q.imaginary(expr.base), assumptions): + if ask(Q.integer(expr.exp), assumptions): + odd = ask(Q.odd(expr.exp), assumptions) + if odd is not None: + return odd + return + + if ask(Q.imaginary(expr.exp), assumptions): + imlog = ask(Q.imaginary(log(expr.base)), assumptions) + if imlog is not None: + # I**i -> real; (2*I)**i -> complex ==> not imaginary + return False + + if ask(Q.real(expr.base) & Q.real(expr.exp), assumptions): + if ask(Q.positive(expr.base), assumptions): + return False + else: + rat = ask(Q.rational(expr.exp), assumptions) + if not rat: + return rat + if ask(Q.integer(expr.exp), assumptions): + return False + else: + half = ask(Q.integer(2*expr.exp), assumptions) + if half: + return ask(Q.negative(expr.base), assumptions) + return half + +@ImaginaryPredicate.register(log) # type:ignore +def _(expr, assumptions): + if ask(Q.real(expr.args[0]), assumptions): + if ask(Q.positive(expr.args[0]), assumptions): + return False + return + # XXX it should be enough to do + # return ask(Q.nonpositive(expr.args[0]), assumptions) + # but ask(Q.nonpositive(exp(x)), Q.imaginary(x)) -> None; + # it should return True since exp(x) will be either 0 or complex + if expr.args[0].func == exp or (expr.args[0].is_Pow and expr.args[0].base == E): + if expr.args[0].exp in [I, -I]: + return True + im = ask(Q.imaginary(expr.args[0]), assumptions) + if im is False: + return False + +@ImaginaryPredicate.register(exp) # type:ignore +def _(expr, assumptions): + a = expr.exp/I/pi + return ask(Q.integer(2*a) & ~Q.integer(a), assumptions) + +@ImaginaryPredicate.register_many(Number, NumberSymbol) # type:ignore +def _(expr, assumptions): + return not (expr.as_real_imag()[1] == 0) + +@ImaginaryPredicate.register(NaN) # type:ignore +def _(expr, assumptions): + return None + + +# AntihermitianPredicate + +@AntihermitianPredicate.register(object) # type:ignore +def _(expr, assumptions): + if isinstance(expr, MatrixBase): + return None + if ask(Q.zero(expr), assumptions): + return True + return ask(Q.imaginary(expr), assumptions) + +@AntihermitianPredicate.register(Add) # type:ignore +def _(expr, assumptions): + """ + * Antihermitian + Antihermitian -> Antihermitian + * Antihermitian + !Antihermitian -> !Antihermitian + """ + if expr.is_number: + raise MDNotImplementedError + return test_closed_group(expr, assumptions, Q.antihermitian) + +@AntihermitianPredicate.register(Mul) # type:ignore +def _(expr, assumptions): + """ + As long as there is at most only one noncommutative term: + + * Hermitian*Hermitian -> !Antihermitian + * Hermitian*Antihermitian -> Antihermitian + * Antihermitian*Antihermitian -> !Antihermitian + """ + if expr.is_number: + raise MDNotImplementedError + nccount = 0 + result = False + for arg in expr.args: + if ask(Q.antihermitian(arg), assumptions): + result = result ^ True + elif not ask(Q.hermitian(arg), assumptions): + break + if ask(~Q.commutative(arg), assumptions): + nccount += 1 + if nccount > 1: + break + else: + return result + +@AntihermitianPredicate.register(Pow) # type:ignore +def _(expr, assumptions): + """ + * Hermitian**Integer -> !Antihermitian + * Antihermitian**Even -> !Antihermitian + * Antihermitian**Odd -> Antihermitian + """ + if expr.is_number: + raise MDNotImplementedError + if ask(Q.hermitian(expr.base), assumptions): + if ask(Q.integer(expr.exp), assumptions): + return False + elif ask(Q.antihermitian(expr.base), assumptions): + if ask(Q.even(expr.exp), assumptions): + return False + elif ask(Q.odd(expr.exp), assumptions): + return True + raise MDNotImplementedError + +@AntihermitianPredicate.register(MatrixBase) # type:ignore +def _(mat, assumptions): + rows, cols = mat.shape + ret_val = True + for i in range(rows): + for j in range(i, cols): + cond = fuzzy_bool(Eq(mat[i, j], -conjugate(mat[j, i]))) + if cond is None: + ret_val = None + if cond == False: + return False + if ret_val is None: + raise MDNotImplementedError + return ret_val + + +# AlgebraicPredicate + +@AlgebraicPredicate.register_many(AlgebraicNumber, Float, GoldenRatio, # type:ignore + ImaginaryUnit, TribonacciConstant) +def _(expr, assumptions): + return True + +@AlgebraicPredicate.register_many(ComplexInfinity, Exp1, Infinity, # type:ignore + NegativeInfinity, Pi) +def _(expr, assumptions): + return False + +@AlgebraicPredicate.register_many(Add, Mul) # type:ignore +def _(expr, assumptions): + return test_closed_group(expr, assumptions, Q.algebraic) + +@AlgebraicPredicate.register(Pow) # type:ignore +def _(expr, assumptions): + if expr.base == E: + if ask(Q.algebraic(expr.exp), assumptions): + return ask(~Q.nonzero(expr.exp), assumptions) + return + if expr.base == pi: + if ask(Q.integer(expr.exp), assumptions) and ask(Q.positive(expr.exp), assumptions): + return False + return + exp_rational = ask(Q.rational(expr.exp), assumptions) + base_algebraic = ask(Q.algebraic(expr.base), assumptions) + exp_algebraic = ask(Q.algebraic(expr.exp),assumptions) + if base_algebraic and exp_algebraic: + if exp_rational: + return True + # Check based on the Gelfond-Schneider theorem: + # If the base is algebraic and not equal to 0 or 1, and the exponent + # is irrational,then the result is transcendental. + if ask(Q.ne(expr.base,0) & Q.ne(expr.base,1)) and exp_rational is False: + return False + +@AlgebraicPredicate.register(Rational) # type:ignore +def _(expr, assumptions): + return expr.q != 0 + +@AlgebraicPredicate.register_many(asin, atan, cos, sin, tan) # type:ignore +def _(expr, assumptions): + x = expr.args[0] + if ask(Q.algebraic(x), assumptions): + return ask(~Q.nonzero(x), assumptions) + +@AlgebraicPredicate.register(exp) # type:ignore +def _(expr, assumptions): + x = expr.exp + if ask(Q.algebraic(x), assumptions): + return ask(~Q.nonzero(x), assumptions) + +@AlgebraicPredicate.register_many(acot, cot) # type:ignore +def _(expr, assumptions): + x = expr.args[0] + if ask(Q.algebraic(x), assumptions): + return False + +@AlgebraicPredicate.register_many(acos, log) # type:ignore +def _(expr, assumptions): + x = expr.args[0] + if ask(Q.algebraic(x), assumptions): + return ask(~Q.nonzero(x - 1), assumptions) diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/lra_satask.py b/.venv/lib/python3.12/site-packages/sympy/assumptions/lra_satask.py new file mode 100644 index 0000000000000000000000000000000000000000..53afe3e5abe99109ec01a47f19f1a8a4c99c5628 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/assumptions/lra_satask.py @@ -0,0 +1,286 @@ +from sympy.assumptions.assume import global_assumptions +from sympy.assumptions.cnf import CNF, EncodedCNF +from sympy.assumptions.ask import Q +from sympy.logic.inference import satisfiable +from sympy.logic.algorithms.lra_theory import UnhandledInput, ALLOWED_PRED +from sympy.matrices.kind import MatrixKind +from sympy.core.kind import NumberKind +from sympy.assumptions.assume import AppliedPredicate +from sympy.core.mul import Mul +from sympy.core.singleton import S + + +def lra_satask(proposition, assumptions=True, context=global_assumptions): + """ + Function to evaluate the proposition with assumptions using SAT algorithm + in conjunction with an Linear Real Arithmetic theory solver. + + Used to handle inequalities. Should eventually be depreciated and combined + into satask, but infinity handling and other things need to be implemented + before that can happen. + """ + props = CNF.from_prop(proposition) + _props = CNF.from_prop(~proposition) + + cnf = CNF.from_prop(assumptions) + assumptions = EncodedCNF() + assumptions.from_cnf(cnf) + + context_cnf = CNF() + if context: + context_cnf = context_cnf.extend(context) + + assumptions.add_from_cnf(context_cnf) + + return check_satisfiability(props, _props, assumptions) + +# Some predicates such as Q.prime can't be handled by lra_satask. +# For example, (x > 0) & (x < 1) & Q.prime(x) is unsat but lra_satask would think it was sat. +# WHITE_LIST is a list of predicates that can always be handled. +WHITE_LIST = ALLOWED_PRED | {Q.positive, Q.negative, Q.zero, Q.nonzero, Q.nonpositive, Q.nonnegative, + Q.extended_positive, Q.extended_negative, Q.extended_nonpositive, + Q.extended_negative, Q.extended_nonzero, Q.negative_infinite, + Q.positive_infinite} + + +def check_satisfiability(prop, _prop, factbase): + sat_true = factbase.copy() + sat_false = factbase.copy() + sat_true.add_from_cnf(prop) + sat_false.add_from_cnf(_prop) + + all_pred, all_exprs = get_all_pred_and_expr_from_enc_cnf(sat_true) + + for pred in all_pred: + if pred.function not in WHITE_LIST and pred.function != Q.ne: + raise UnhandledInput(f"LRASolver: {pred} is an unhandled predicate") + for expr in all_exprs: + if expr.kind == MatrixKind(NumberKind): + raise UnhandledInput(f"LRASolver: {expr} is of MatrixKind") + if expr == S.NaN: + raise UnhandledInput("LRASolver: nan") + + # convert old assumptions into predicates and add them to sat_true and sat_false + # also check for unhandled predicates + for assm in extract_pred_from_old_assum(all_exprs): + n = len(sat_true.encoding) + if assm not in sat_true.encoding: + sat_true.encoding[assm] = n+1 + sat_true.data.append([sat_true.encoding[assm]]) + + n = len(sat_false.encoding) + if assm not in sat_false.encoding: + sat_false.encoding[assm] = n+1 + sat_false.data.append([sat_false.encoding[assm]]) + + + sat_true = _preprocess(sat_true) + sat_false = _preprocess(sat_false) + + can_be_true = satisfiable(sat_true, use_lra_theory=True) is not False + can_be_false = satisfiable(sat_false, use_lra_theory=True) is not False + + if can_be_true and can_be_false: + return None + + if can_be_true and not can_be_false: + return True + + if not can_be_true and can_be_false: + return False + + if not can_be_true and not can_be_false: + raise ValueError("Inconsistent assumptions") + + +def _preprocess(enc_cnf): + """ + Returns an encoded cnf with only Q.eq, Q.gt, Q.lt, + Q.ge, and Q.le predicate. + + Converts every unequality into a disjunction of strict + inequalities. For example, x != 3 would become + x < 3 OR x > 3. + + Also converts all negated Q.ne predicates into + equalities. + """ + + # loops through each literal in each clause + # to construct a new, preprocessed encodedCNF + + enc_cnf = enc_cnf.copy() + cur_enc = 1 + rev_encoding = {value: key for key, value in enc_cnf.encoding.items()} + + new_encoding = {} + new_data = [] + for clause in enc_cnf.data: + new_clause = [] + for lit in clause: + if lit == 0: + new_clause.append(lit) + new_encoding[lit] = False + continue + prop = rev_encoding[abs(lit)] + negated = lit < 0 + sign = (lit > 0) - (lit < 0) + + prop = _pred_to_binrel(prop) + + if not isinstance(prop, AppliedPredicate): + if prop not in new_encoding: + new_encoding[prop] = cur_enc + cur_enc += 1 + lit = new_encoding[prop] + new_clause.append(sign*lit) + continue + + + if negated and prop.function == Q.eq: + negated = False + prop = Q.ne(*prop.arguments) + + if prop.function == Q.ne: + arg1, arg2 = prop.arguments + if negated: + new_prop = Q.eq(arg1, arg2) + if new_prop not in new_encoding: + new_encoding[new_prop] = cur_enc + cur_enc += 1 + + new_enc = new_encoding[new_prop] + new_clause.append(new_enc) + continue + else: + new_props = (Q.gt(arg1, arg2), Q.lt(arg1, arg2)) + for new_prop in new_props: + if new_prop not in new_encoding: + new_encoding[new_prop] = cur_enc + cur_enc += 1 + + new_enc = new_encoding[new_prop] + new_clause.append(new_enc) + continue + + if prop.function == Q.eq and negated: + assert False + + if prop not in new_encoding: + new_encoding[prop] = cur_enc + cur_enc += 1 + new_clause.append(new_encoding[prop]*sign) + new_data.append(new_clause) + + assert len(new_encoding) >= cur_enc - 1 + + enc_cnf = EncodedCNF(new_data, new_encoding) + return enc_cnf + + +def _pred_to_binrel(pred): + if not isinstance(pred, AppliedPredicate): + return pred + + if pred.function in pred_to_pos_neg_zero: + f = pred_to_pos_neg_zero[pred.function] + if f is False: + return False + pred = f(pred.arguments[0]) + + if pred.function == Q.positive: + pred = Q.gt(pred.arguments[0], 0) + elif pred.function == Q.negative: + pred = Q.lt(pred.arguments[0], 0) + elif pred.function == Q.zero: + pred = Q.eq(pred.arguments[0], 0) + elif pred.function == Q.nonpositive: + pred = Q.le(pred.arguments[0], 0) + elif pred.function == Q.nonnegative: + pred = Q.ge(pred.arguments[0], 0) + elif pred.function == Q.nonzero: + pred = Q.ne(pred.arguments[0], 0) + + return pred + +pred_to_pos_neg_zero = { + Q.extended_positive: Q.positive, + Q.extended_negative: Q.negative, + Q.extended_nonpositive: Q.nonpositive, + Q.extended_negative: Q.negative, + Q.extended_nonzero: Q.nonzero, + Q.negative_infinite: False, + Q.positive_infinite: False +} + +def get_all_pred_and_expr_from_enc_cnf(enc_cnf): + all_exprs = set() + all_pred = set() + for pred in enc_cnf.encoding.keys(): + if isinstance(pred, AppliedPredicate): + all_pred.add(pred) + all_exprs.update(pred.arguments) + + return all_pred, all_exprs + +def extract_pred_from_old_assum(all_exprs): + """ + Returns a list of relevant new assumption predicate + based on any old assumptions. + + Raises an UnhandledInput exception if any of the assumptions are + unhandled. + + Ignored predicate: + - commutative + - complex + - algebraic + - transcendental + - extended_real + - real + - all matrix predicate + - rational + - irrational + + Example + ======= + >>> from sympy.assumptions.lra_satask import extract_pred_from_old_assum + >>> from sympy import symbols + >>> x, y = symbols("x y", positive=True) + >>> extract_pred_from_old_assum([x, y, 2]) + [Q.positive(x), Q.positive(y)] + """ + ret = [] + for expr in all_exprs: + if not hasattr(expr, "free_symbols"): + continue + if len(expr.free_symbols) == 0: + continue + + if expr.is_real is not True: + raise UnhandledInput(f"LRASolver: {expr} must be real") + # test for I times imaginary variable; such expressions are considered real + if isinstance(expr, Mul) and any(arg.is_real is not True for arg in expr.args): + raise UnhandledInput(f"LRASolver: {expr} must be real") + + if expr.is_integer == True and expr.is_zero != True: + raise UnhandledInput(f"LRASolver: {expr} is an integer") + if expr.is_integer == False: + raise UnhandledInput(f"LRASolver: {expr} can't be an integer") + if expr.is_rational == False: + raise UnhandledInput(f"LRASolver: {expr} is irational") + + if expr.is_zero: + ret.append(Q.zero(expr)) + elif expr.is_positive: + ret.append(Q.positive(expr)) + elif expr.is_negative: + ret.append(Q.negative(expr)) + elif expr.is_nonzero: + ret.append(Q.nonzero(expr)) + elif expr.is_nonpositive: + ret.append(Q.nonpositive(expr)) + elif expr.is_nonnegative: + ret.append(Q.nonnegative(expr)) + + return ret diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/__init__.py b/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8e294544bfdce13633ecff762ff42861aa12719f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/__init__.py @@ -0,0 +1,5 @@ +""" +Module to implement predicate classes. + +Class of every predicate registered to ``Q`` is defined here. +""" diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2204f440303b49b474eeb1793f2fc5ddbc58e786 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/__pycache__/calculus.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/__pycache__/calculus.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90100f0484a3aa21bc14bcd830c5c4eac655b1b2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/__pycache__/calculus.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/__pycache__/common.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/__pycache__/common.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..536652ee088870ac898fe94f541a71545aa5940c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/__pycache__/common.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/__pycache__/matrices.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/__pycache__/matrices.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2fe2fe59e2e76e8e8a9bd0d75e472f32c0d0e083 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/__pycache__/matrices.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/__pycache__/ntheory.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/__pycache__/ntheory.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a8c5cfb5efb0c6e9742e8d7caa03df36b9a9a46 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/__pycache__/ntheory.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/__pycache__/order.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/__pycache__/order.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3852902ee2124438b2cef738f24fdc4fb29071b1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/__pycache__/order.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/__pycache__/sets.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/__pycache__/sets.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a70fa03d1c172890419f4342c51cd4fbb32cb84 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/__pycache__/sets.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/calculus.py b/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/calculus.py new file mode 100644 index 0000000000000000000000000000000000000000..f300703788683c07649ee3a0afd6e9d4eabd4567 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/calculus.py @@ -0,0 +1,82 @@ +from sympy.assumptions import Predicate +from sympy.multipledispatch import Dispatcher + +class FinitePredicate(Predicate): + """ + Finite number predicate. + + Explanation + =========== + + ``Q.finite(x)`` is true if ``x`` is a number but neither an infinity + nor a ``NaN``. In other words, ``ask(Q.finite(x))`` is true for all + numerical ``x`` having a bounded absolute value. + + Examples + ======== + + >>> from sympy import Q, ask, S, oo, I, zoo + >>> from sympy.abc import x + >>> ask(Q.finite(oo)) + False + >>> ask(Q.finite(-oo)) + False + >>> ask(Q.finite(zoo)) + False + >>> ask(Q.finite(1)) + True + >>> ask(Q.finite(2 + 3*I)) + True + >>> ask(Q.finite(x), Q.positive(x)) + True + >>> print(ask(Q.finite(S.NaN))) + None + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Finite + + """ + name = 'finite' + handler = Dispatcher( + "FiniteHandler", + doc=("Handler for Q.finite. Test that an expression is bounded respect" + " to all its variables.") + ) + + +class InfinitePredicate(Predicate): + """ + Infinite number predicate. + + ``Q.infinite(x)`` is true iff the absolute value of ``x`` is + infinity. + + """ + # TODO: Add examples + name = 'infinite' + handler = Dispatcher( + "InfiniteHandler", + doc="""Handler for Q.infinite key.""" + ) + + +class PositiveInfinitePredicate(Predicate): + """ + Positive infinity predicate. + + ``Q.positive_infinite(x)`` is true iff ``x`` is positive infinity ``oo``. + """ + name = 'positive_infinite' + handler = Dispatcher("PositiveInfiniteHandler") + + +class NegativeInfinitePredicate(Predicate): + """ + Negative infinity predicate. + + ``Q.negative_infinite(x)`` is true iff ``x`` is negative infinity ``-oo``. + """ + name = 'negative_infinite' + handler = Dispatcher("NegativeInfiniteHandler") diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/common.py b/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/common.py new file mode 100644 index 0000000000000000000000000000000000000000..a53892747131b03636abeb8f563c4f76cf3e281e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/common.py @@ -0,0 +1,81 @@ +from sympy.assumptions import Predicate, AppliedPredicate, Q +from sympy.core.relational import Eq, Ne, Gt, Lt, Ge, Le +from sympy.multipledispatch import Dispatcher + + +class CommutativePredicate(Predicate): + """ + Commutative predicate. + + Explanation + =========== + + ``ask(Q.commutative(x))`` is true iff ``x`` commutes with any other + object with respect to multiplication operation. + + """ + # TODO: Add examples + name = 'commutative' + handler = Dispatcher("CommutativeHandler", doc="Handler for key 'commutative'.") + + +binrelpreds = {Eq: Q.eq, Ne: Q.ne, Gt: Q.gt, Lt: Q.lt, Ge: Q.ge, Le: Q.le} + +class IsTruePredicate(Predicate): + """ + Generic predicate. + + Explanation + =========== + + ``ask(Q.is_true(x))`` is true iff ``x`` is true. This only makes + sense if ``x`` is a boolean object. + + Examples + ======== + + >>> from sympy import ask, Q + >>> from sympy.abc import x, y + >>> ask(Q.is_true(True)) + True + + Wrapping another applied predicate just returns the applied predicate. + + >>> Q.is_true(Q.even(x)) + Q.even(x) + + Wrapping binary relation classes in SymPy core returns applied binary + relational predicates. + + >>> from sympy import Eq, Gt + >>> Q.is_true(Eq(x, y)) + Q.eq(x, y) + >>> Q.is_true(Gt(x, y)) + Q.gt(x, y) + + Notes + ===== + + This class is designed to wrap the boolean objects so that they can + behave as if they are applied predicates. Consequently, wrapping another + applied predicate is unnecessary and thus it just returns the argument. + Also, binary relation classes in SymPy core have binary predicates to + represent themselves and thus wrapping them with ``Q.is_true`` converts them + to these applied predicates. + + """ + name = 'is_true' + handler = Dispatcher( + "IsTrueHandler", + doc="Wrapper allowing to query the truth value of a boolean expression." + ) + + def __call__(self, arg): + # No need to wrap another predicate + if isinstance(arg, AppliedPredicate): + return arg + # Convert relational predicates instead of wrapping them + if getattr(arg, "is_Relational", False): + pred = binrelpreds[type(arg)] + return pred(*arg.args) + return super().__call__(arg) diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/matrices.py b/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/matrices.py new file mode 100644 index 0000000000000000000000000000000000000000..151e78c4ff345800e1d2f17973fb0591b8d379d2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/matrices.py @@ -0,0 +1,511 @@ +from sympy.assumptions import Predicate +from sympy.multipledispatch import Dispatcher + +class SquarePredicate(Predicate): + """ + Square matrix predicate. + + Explanation + =========== + + ``Q.square(x)`` is true iff ``x`` is a square matrix. A square matrix + is a matrix with the same number of rows and columns. + + Examples + ======== + + >>> from sympy import Q, ask, MatrixSymbol, ZeroMatrix, Identity + >>> X = MatrixSymbol('X', 2, 2) + >>> Y = MatrixSymbol('X', 2, 3) + >>> ask(Q.square(X)) + True + >>> ask(Q.square(Y)) + False + >>> ask(Q.square(ZeroMatrix(3, 3))) + True + >>> ask(Q.square(Identity(3))) + True + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Square_matrix + + """ + name = 'square' + handler = Dispatcher("SquareHandler", doc="Handler for Q.square.") + + +class SymmetricPredicate(Predicate): + """ + Symmetric matrix predicate. + + Explanation + =========== + + ``Q.symmetric(x)`` is true iff ``x`` is a square matrix and is equal to + its transpose. Every square diagonal matrix is a symmetric matrix. + + Examples + ======== + + >>> from sympy import Q, ask, MatrixSymbol + >>> X = MatrixSymbol('X', 2, 2) + >>> Y = MatrixSymbol('Y', 2, 3) + >>> Z = MatrixSymbol('Z', 2, 2) + >>> ask(Q.symmetric(X*Z), Q.symmetric(X) & Q.symmetric(Z)) + True + >>> ask(Q.symmetric(X + Z), Q.symmetric(X) & Q.symmetric(Z)) + True + >>> ask(Q.symmetric(Y)) + False + + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Symmetric_matrix + + """ + # TODO: Add handlers to make these keys work with + # actual matrices and add more examples in the docstring. + name = 'symmetric' + handler = Dispatcher("SymmetricHandler", doc="Handler for Q.symmetric.") + + +class InvertiblePredicate(Predicate): + """ + Invertible matrix predicate. + + Explanation + =========== + + ``Q.invertible(x)`` is true iff ``x`` is an invertible matrix. + A square matrix is called invertible only if its determinant is 0. + + Examples + ======== + + >>> from sympy import Q, ask, MatrixSymbol + >>> X = MatrixSymbol('X', 2, 2) + >>> Y = MatrixSymbol('Y', 2, 3) + >>> Z = MatrixSymbol('Z', 2, 2) + >>> ask(Q.invertible(X*Y), Q.invertible(X)) + False + >>> ask(Q.invertible(X*Z), Q.invertible(X) & Q.invertible(Z)) + True + >>> ask(Q.invertible(X), Q.fullrank(X) & Q.square(X)) + True + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Invertible_matrix + + """ + name = 'invertible' + handler = Dispatcher("InvertibleHandler", doc="Handler for Q.invertible.") + + +class OrthogonalPredicate(Predicate): + """ + Orthogonal matrix predicate. + + Explanation + =========== + + ``Q.orthogonal(x)`` is true iff ``x`` is an orthogonal matrix. + A square matrix ``M`` is an orthogonal matrix if it satisfies + ``M^TM = MM^T = I`` where ``M^T`` is the transpose matrix of + ``M`` and ``I`` is an identity matrix. Note that an orthogonal + matrix is necessarily invertible. + + Examples + ======== + + >>> from sympy import Q, ask, MatrixSymbol, Identity + >>> X = MatrixSymbol('X', 2, 2) + >>> Y = MatrixSymbol('Y', 2, 3) + >>> Z = MatrixSymbol('Z', 2, 2) + >>> ask(Q.orthogonal(Y)) + False + >>> ask(Q.orthogonal(X*Z*X), Q.orthogonal(X) & Q.orthogonal(Z)) + True + >>> ask(Q.orthogonal(Identity(3))) + True + >>> ask(Q.invertible(X), Q.orthogonal(X)) + True + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Orthogonal_matrix + + """ + name = 'orthogonal' + handler = Dispatcher("OrthogonalHandler", doc="Handler for key 'orthogonal'.") + + +class UnitaryPredicate(Predicate): + """ + Unitary matrix predicate. + + Explanation + =========== + + ``Q.unitary(x)`` is true iff ``x`` is a unitary matrix. + Unitary matrix is an analogue to orthogonal matrix. A square + matrix ``M`` with complex elements is unitary if :math:``M^TM = MM^T= I`` + where :math:``M^T`` is the conjugate transpose matrix of ``M``. + + Examples + ======== + + >>> from sympy import Q, ask, MatrixSymbol, Identity + >>> X = MatrixSymbol('X', 2, 2) + >>> Y = MatrixSymbol('Y', 2, 3) + >>> Z = MatrixSymbol('Z', 2, 2) + >>> ask(Q.unitary(Y)) + False + >>> ask(Q.unitary(X*Z*X), Q.unitary(X) & Q.unitary(Z)) + True + >>> ask(Q.unitary(Identity(3))) + True + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Unitary_matrix + + """ + name = 'unitary' + handler = Dispatcher("UnitaryHandler", doc="Handler for key 'unitary'.") + + +class FullRankPredicate(Predicate): + """ + Fullrank matrix predicate. + + Explanation + =========== + + ``Q.fullrank(x)`` is true iff ``x`` is a full rank matrix. + A matrix is full rank if all rows and columns of the matrix + are linearly independent. A square matrix is full rank iff + its determinant is nonzero. + + Examples + ======== + + >>> from sympy import Q, ask, MatrixSymbol, ZeroMatrix, Identity + >>> X = MatrixSymbol('X', 2, 2) + >>> ask(Q.fullrank(X.T), Q.fullrank(X)) + True + >>> ask(Q.fullrank(ZeroMatrix(3, 3))) + False + >>> ask(Q.fullrank(Identity(3))) + True + + """ + name = 'fullrank' + handler = Dispatcher("FullRankHandler", doc="Handler for key 'fullrank'.") + + +class PositiveDefinitePredicate(Predicate): + r""" + Positive definite matrix predicate. + + Explanation + =========== + + If $M$ is a :math:`n \times n` symmetric real matrix, it is said + to be positive definite if :math:`Z^TMZ` is positive for + every non-zero column vector $Z$ of $n$ real numbers. + + Examples + ======== + + >>> from sympy import Q, ask, MatrixSymbol, Identity + >>> X = MatrixSymbol('X', 2, 2) + >>> Y = MatrixSymbol('Y', 2, 3) + >>> Z = MatrixSymbol('Z', 2, 2) + >>> ask(Q.positive_definite(Y)) + False + >>> ask(Q.positive_definite(Identity(3))) + True + >>> ask(Q.positive_definite(X + Z), Q.positive_definite(X) & + ... Q.positive_definite(Z)) + True + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Positive-definite_matrix + + """ + name = "positive_definite" + handler = Dispatcher("PositiveDefiniteHandler", doc="Handler for key 'positive_definite'.") + + +class UpperTriangularPredicate(Predicate): + """ + Upper triangular matrix predicate. + + Explanation + =========== + + A matrix $M$ is called upper triangular matrix if :math:`M_{ij}=0` + for :math:`i>> from sympy import Q, ask, ZeroMatrix, Identity + >>> ask(Q.upper_triangular(Identity(3))) + True + >>> ask(Q.upper_triangular(ZeroMatrix(3, 3))) + True + + References + ========== + + .. [1] https://mathworld.wolfram.com/UpperTriangularMatrix.html + + """ + name = "upper_triangular" + handler = Dispatcher("UpperTriangularHandler", doc="Handler for key 'upper_triangular'.") + + +class LowerTriangularPredicate(Predicate): + """ + Lower triangular matrix predicate. + + Explanation + =========== + + A matrix $M$ is called lower triangular matrix if :math:`M_{ij}=0` + for :math:`i>j`. + + Examples + ======== + + >>> from sympy import Q, ask, ZeroMatrix, Identity + >>> ask(Q.lower_triangular(Identity(3))) + True + >>> ask(Q.lower_triangular(ZeroMatrix(3, 3))) + True + + References + ========== + + .. [1] https://mathworld.wolfram.com/LowerTriangularMatrix.html + + """ + name = "lower_triangular" + handler = Dispatcher("LowerTriangularHandler", doc="Handler for key 'lower_triangular'.") + + +class DiagonalPredicate(Predicate): + """ + Diagonal matrix predicate. + + Explanation + =========== + + ``Q.diagonal(x)`` is true iff ``x`` is a diagonal matrix. A diagonal + matrix is a matrix in which the entries outside the main diagonal + are all zero. + + Examples + ======== + + >>> from sympy import Q, ask, MatrixSymbol, ZeroMatrix + >>> X = MatrixSymbol('X', 2, 2) + >>> ask(Q.diagonal(ZeroMatrix(3, 3))) + True + >>> ask(Q.diagonal(X), Q.lower_triangular(X) & + ... Q.upper_triangular(X)) + True + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Diagonal_matrix + + """ + name = "diagonal" + handler = Dispatcher("DiagonalHandler", doc="Handler for key 'diagonal'.") + + +class IntegerElementsPredicate(Predicate): + """ + Integer elements matrix predicate. + + Explanation + =========== + + ``Q.integer_elements(x)`` is true iff all the elements of ``x`` + are integers. + + Examples + ======== + + >>> from sympy import Q, ask, MatrixSymbol + >>> X = MatrixSymbol('X', 4, 4) + >>> ask(Q.integer(X[1, 2]), Q.integer_elements(X)) + True + + """ + name = "integer_elements" + handler = Dispatcher("IntegerElementsHandler", doc="Handler for key 'integer_elements'.") + + +class RealElementsPredicate(Predicate): + """ + Real elements matrix predicate. + + Explanation + =========== + + ``Q.real_elements(x)`` is true iff all the elements of ``x`` + are real numbers. + + Examples + ======== + + >>> from sympy import Q, ask, MatrixSymbol + >>> X = MatrixSymbol('X', 4, 4) + >>> ask(Q.real(X[1, 2]), Q.real_elements(X)) + True + + """ + name = "real_elements" + handler = Dispatcher("RealElementsHandler", doc="Handler for key 'real_elements'.") + + +class ComplexElementsPredicate(Predicate): + """ + Complex elements matrix predicate. + + Explanation + =========== + + ``Q.complex_elements(x)`` is true iff all the elements of ``x`` + are complex numbers. + + Examples + ======== + + >>> from sympy import Q, ask, MatrixSymbol + >>> X = MatrixSymbol('X', 4, 4) + >>> ask(Q.complex(X[1, 2]), Q.complex_elements(X)) + True + >>> ask(Q.complex_elements(X), Q.integer_elements(X)) + True + + """ + name = "complex_elements" + handler = Dispatcher("ComplexElementsHandler", doc="Handler for key 'complex_elements'.") + + +class SingularPredicate(Predicate): + """ + Singular matrix predicate. + + A matrix is singular iff the value of its determinant is 0. + + Examples + ======== + + >>> from sympy import Q, ask, MatrixSymbol + >>> X = MatrixSymbol('X', 4, 4) + >>> ask(Q.singular(X), Q.invertible(X)) + False + >>> ask(Q.singular(X), ~Q.invertible(X)) + True + + References + ========== + + .. [1] https://mathworld.wolfram.com/SingularMatrix.html + + """ + name = "singular" + handler = Dispatcher("SingularHandler", doc="Predicate fore key 'singular'.") + + +class NormalPredicate(Predicate): + """ + Normal matrix predicate. + + A matrix is normal if it commutes with its conjugate transpose. + + Examples + ======== + + >>> from sympy import Q, ask, MatrixSymbol + >>> X = MatrixSymbol('X', 4, 4) + >>> ask(Q.normal(X), Q.unitary(X)) + True + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Normal_matrix + + """ + name = "normal" + handler = Dispatcher("NormalHandler", doc="Predicate fore key 'normal'.") + + +class TriangularPredicate(Predicate): + """ + Triangular matrix predicate. + + Explanation + =========== + + ``Q.triangular(X)`` is true if ``X`` is one that is either lower + triangular or upper triangular. + + Examples + ======== + + >>> from sympy import Q, ask, MatrixSymbol + >>> X = MatrixSymbol('X', 4, 4) + >>> ask(Q.triangular(X), Q.upper_triangular(X)) + True + >>> ask(Q.triangular(X), Q.lower_triangular(X)) + True + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Triangular_matrix + + """ + name = "triangular" + handler = Dispatcher("TriangularHandler", doc="Predicate fore key 'triangular'.") + + +class UnitTriangularPredicate(Predicate): + """ + Unit triangular matrix predicate. + + Explanation + =========== + + A unit triangular matrix is a triangular matrix with 1s + on the diagonal. + + Examples + ======== + + >>> from sympy import Q, ask, MatrixSymbol + >>> X = MatrixSymbol('X', 4, 4) + >>> ask(Q.triangular(X), Q.unit_triangular(X)) + True + + """ + name = "unit_triangular" + handler = Dispatcher("UnitTriangularHandler", doc="Predicate fore key 'unit_triangular'.") diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/ntheory.py b/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/ntheory.py new file mode 100644 index 0000000000000000000000000000000000000000..6c598e0ed1bd4a1170aa28044f9ae6de2fa1a1e0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/ntheory.py @@ -0,0 +1,126 @@ +from sympy.assumptions import Predicate +from sympy.multipledispatch import Dispatcher + + +class PrimePredicate(Predicate): + """ + Prime number predicate. + + Explanation + =========== + + ``ask(Q.prime(x))`` is true iff ``x`` is a natural number greater + than 1 that has no positive divisors other than ``1`` and the + number itself. + + Examples + ======== + + >>> from sympy import Q, ask + >>> ask(Q.prime(0)) + False + >>> ask(Q.prime(1)) + False + >>> ask(Q.prime(2)) + True + >>> ask(Q.prime(20)) + False + >>> ask(Q.prime(-3)) + False + + """ + name = 'prime' + handler = Dispatcher( + "PrimeHandler", + doc=("Handler for key 'prime'. Test that an expression represents a prime" + " number. When the expression is an exact number, the result (when True)" + " is subject to the limitations of isprime() which is used to return the " + "result.") + ) + + +class CompositePredicate(Predicate): + """ + Composite number predicate. + + Explanation + =========== + + ``ask(Q.composite(x))`` is true iff ``x`` is a positive integer and has + at least one positive divisor other than ``1`` and the number itself. + + Examples + ======== + + >>> from sympy import Q, ask + >>> ask(Q.composite(0)) + False + >>> ask(Q.composite(1)) + False + >>> ask(Q.composite(2)) + False + >>> ask(Q.composite(20)) + True + + """ + name = 'composite' + handler = Dispatcher("CompositeHandler", doc="Handler for key 'composite'.") + + +class EvenPredicate(Predicate): + """ + Even number predicate. + + Explanation + =========== + + ``ask(Q.even(x))`` is true iff ``x`` belongs to the set of even + integers. + + Examples + ======== + + >>> from sympy import Q, ask, pi + >>> ask(Q.even(0)) + True + >>> ask(Q.even(2)) + True + >>> ask(Q.even(3)) + False + >>> ask(Q.even(pi)) + False + + """ + name = 'even' + handler = Dispatcher("EvenHandler", doc="Handler for key 'even'.") + + +class OddPredicate(Predicate): + """ + Odd number predicate. + + Explanation + =========== + + ``ask(Q.odd(x))`` is true iff ``x`` belongs to the set of odd numbers. + + Examples + ======== + + >>> from sympy import Q, ask, pi + >>> ask(Q.odd(0)) + False + >>> ask(Q.odd(2)) + False + >>> ask(Q.odd(3)) + True + >>> ask(Q.odd(pi)) + False + + """ + name = 'odd' + handler = Dispatcher( + "OddHandler", + doc=("Handler for key 'odd'. Test that an expression represents an odd" + " number.") + ) diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/order.py b/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/order.py new file mode 100644 index 0000000000000000000000000000000000000000..86bfb2ae49789efd5b0df99e2cfc63984e956dd0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/order.py @@ -0,0 +1,390 @@ +from sympy.assumptions import Predicate +from sympy.multipledispatch import Dispatcher + + +class NegativePredicate(Predicate): + r""" + Negative number predicate. + + Explanation + =========== + + ``Q.negative(x)`` is true iff ``x`` is a real number and :math:`x < 0`, that is, + it is in the interval :math:`(-\infty, 0)`. Note in particular that negative + infinity is not negative. + + A few important facts about negative numbers: + + - Note that ``Q.nonnegative`` and ``~Q.negative`` are *not* the same + thing. ``~Q.negative(x)`` simply means that ``x`` is not negative, + whereas ``Q.nonnegative(x)`` means that ``x`` is real and not + negative, i.e., ``Q.nonnegative(x)`` is logically equivalent to + ``Q.zero(x) | Q.positive(x)``. So for example, ``~Q.negative(I)`` is + true, whereas ``Q.nonnegative(I)`` is false. + + - See the documentation of ``Q.real`` for more information about + related facts. + + Examples + ======== + + >>> from sympy import Q, ask, symbols, I + >>> x = symbols('x') + >>> ask(Q.negative(x), Q.real(x) & ~Q.positive(x) & ~Q.zero(x)) + True + >>> ask(Q.negative(-1)) + True + >>> ask(Q.nonnegative(I)) + False + >>> ask(~Q.negative(I)) + True + + """ + name = 'negative' + handler = Dispatcher( + "NegativeHandler", + doc=("Handler for Q.negative. Test that an expression is strictly less" + " than zero.") + ) + + +class NonNegativePredicate(Predicate): + """ + Nonnegative real number predicate. + + Explanation + =========== + + ``ask(Q.nonnegative(x))`` is true iff ``x`` belongs to the set of + positive numbers including zero. + + - Note that ``Q.nonnegative`` and ``~Q.negative`` are *not* the same + thing. ``~Q.negative(x)`` simply means that ``x`` is not negative, + whereas ``Q.nonnegative(x)`` means that ``x`` is real and not + negative, i.e., ``Q.nonnegative(x)`` is logically equivalent to + ``Q.zero(x) | Q.positive(x)``. So for example, ``~Q.negative(I)`` is + true, whereas ``Q.nonnegative(I)`` is false. + + Examples + ======== + + >>> from sympy import Q, ask, I + >>> ask(Q.nonnegative(1)) + True + >>> ask(Q.nonnegative(0)) + True + >>> ask(Q.nonnegative(-1)) + False + >>> ask(Q.nonnegative(I)) + False + >>> ask(Q.nonnegative(-I)) + False + + """ + name = 'nonnegative' + handler = Dispatcher( + "NonNegativeHandler", + doc=("Handler for Q.nonnegative.") + ) + + +class NonZeroPredicate(Predicate): + """ + Nonzero real number predicate. + + Explanation + =========== + + ``ask(Q.nonzero(x))`` is true iff ``x`` is real and ``x`` is not zero. Note in + particular that ``Q.nonzero(x)`` is false if ``x`` is not real. Use + ``~Q.zero(x)`` if you want the negation of being zero without any real + assumptions. + + A few important facts about nonzero numbers: + + - ``Q.nonzero`` is logically equivalent to ``Q.positive | Q.negative``. + + - See the documentation of ``Q.real`` for more information about + related facts. + + Examples + ======== + + >>> from sympy import Q, ask, symbols, I, oo + >>> x = symbols('x') + >>> print(ask(Q.nonzero(x), ~Q.zero(x))) + None + >>> ask(Q.nonzero(x), Q.positive(x)) + True + >>> ask(Q.nonzero(x), Q.zero(x)) + False + >>> ask(Q.nonzero(0)) + False + >>> ask(Q.nonzero(I)) + False + >>> ask(~Q.zero(I)) + True + >>> ask(Q.nonzero(oo)) + False + + """ + name = 'nonzero' + handler = Dispatcher( + "NonZeroHandler", + doc=("Handler for key 'nonzero'. Test that an expression is not identically" + " zero.") + ) + + +class ZeroPredicate(Predicate): + """ + Zero number predicate. + + Explanation + =========== + + ``ask(Q.zero(x))`` is true iff the value of ``x`` is zero. + + Examples + ======== + + >>> from sympy import ask, Q, oo, symbols + >>> x, y = symbols('x, y') + >>> ask(Q.zero(0)) + True + >>> ask(Q.zero(1/oo)) + True + >>> print(ask(Q.zero(0*oo))) + None + >>> ask(Q.zero(1)) + False + >>> ask(Q.zero(x*y), Q.zero(x) | Q.zero(y)) + True + + """ + name = 'zero' + handler = Dispatcher( + "ZeroHandler", + doc="Handler for key 'zero'." + ) + + +class NonPositivePredicate(Predicate): + """ + Nonpositive real number predicate. + + Explanation + =========== + + ``ask(Q.nonpositive(x))`` is true iff ``x`` belongs to the set of + negative numbers including zero. + + - Note that ``Q.nonpositive`` and ``~Q.positive`` are *not* the same + thing. ``~Q.positive(x)`` simply means that ``x`` is not positive, + whereas ``Q.nonpositive(x)`` means that ``x`` is real and not + positive, i.e., ``Q.nonpositive(x)`` is logically equivalent to + `Q.negative(x) | Q.zero(x)``. So for example, ``~Q.positive(I)`` is + true, whereas ``Q.nonpositive(I)`` is false. + + Examples + ======== + + >>> from sympy import Q, ask, I + + >>> ask(Q.nonpositive(-1)) + True + >>> ask(Q.nonpositive(0)) + True + >>> ask(Q.nonpositive(1)) + False + >>> ask(Q.nonpositive(I)) + False + >>> ask(Q.nonpositive(-I)) + False + + """ + name = 'nonpositive' + handler = Dispatcher( + "NonPositiveHandler", + doc="Handler for key 'nonpositive'." + ) + + +class PositivePredicate(Predicate): + r""" + Positive real number predicate. + + Explanation + =========== + + ``Q.positive(x)`` is true iff ``x`` is real and `x > 0`, that is if ``x`` + is in the interval `(0, \infty)`. In particular, infinity is not + positive. + + A few important facts about positive numbers: + + - Note that ``Q.nonpositive`` and ``~Q.positive`` are *not* the same + thing. ``~Q.positive(x)`` simply means that ``x`` is not positive, + whereas ``Q.nonpositive(x)`` means that ``x`` is real and not + positive, i.e., ``Q.nonpositive(x)`` is logically equivalent to + `Q.negative(x) | Q.zero(x)``. So for example, ``~Q.positive(I)`` is + true, whereas ``Q.nonpositive(I)`` is false. + + - See the documentation of ``Q.real`` for more information about + related facts. + + Examples + ======== + + >>> from sympy import Q, ask, symbols, I + >>> x = symbols('x') + >>> ask(Q.positive(x), Q.real(x) & ~Q.negative(x) & ~Q.zero(x)) + True + >>> ask(Q.positive(1)) + True + >>> ask(Q.nonpositive(I)) + False + >>> ask(~Q.positive(I)) + True + + """ + name = 'positive' + handler = Dispatcher( + "PositiveHandler", + doc=("Handler for key 'positive'. Test that an expression is strictly" + " greater than zero.") + ) + + +class ExtendedPositivePredicate(Predicate): + r""" + Positive extended real number predicate. + + Explanation + =========== + + ``Q.extended_positive(x)`` is true iff ``x`` is extended real and + `x > 0`, that is if ``x`` is in the interval `(0, \infty]`. + + Examples + ======== + + >>> from sympy import ask, I, oo, Q + >>> ask(Q.extended_positive(1)) + True + >>> ask(Q.extended_positive(oo)) + True + >>> ask(Q.extended_positive(I)) + False + + """ + name = 'extended_positive' + handler = Dispatcher("ExtendedPositiveHandler") + + +class ExtendedNegativePredicate(Predicate): + r""" + Negative extended real number predicate. + + Explanation + =========== + + ``Q.extended_negative(x)`` is true iff ``x`` is extended real and + `x < 0`, that is if ``x`` is in the interval `[-\infty, 0)`. + + Examples + ======== + + >>> from sympy import ask, I, oo, Q + >>> ask(Q.extended_negative(-1)) + True + >>> ask(Q.extended_negative(-oo)) + True + >>> ask(Q.extended_negative(-I)) + False + + """ + name = 'extended_negative' + handler = Dispatcher("ExtendedNegativeHandler") + + +class ExtendedNonZeroPredicate(Predicate): + """ + Nonzero extended real number predicate. + + Explanation + =========== + + ``ask(Q.extended_nonzero(x))`` is true iff ``x`` is extended real and + ``x`` is not zero. + + Examples + ======== + + >>> from sympy import ask, I, oo, Q + >>> ask(Q.extended_nonzero(-1)) + True + >>> ask(Q.extended_nonzero(oo)) + True + >>> ask(Q.extended_nonzero(I)) + False + + """ + name = 'extended_nonzero' + handler = Dispatcher("ExtendedNonZeroHandler") + + +class ExtendedNonPositivePredicate(Predicate): + """ + Nonpositive extended real number predicate. + + Explanation + =========== + + ``ask(Q.extended_nonpositive(x))`` is true iff ``x`` is extended real and + ``x`` is not positive. + + Examples + ======== + + >>> from sympy import ask, I, oo, Q + >>> ask(Q.extended_nonpositive(-1)) + True + >>> ask(Q.extended_nonpositive(oo)) + False + >>> ask(Q.extended_nonpositive(0)) + True + >>> ask(Q.extended_nonpositive(I)) + False + + """ + name = 'extended_nonpositive' + handler = Dispatcher("ExtendedNonPositiveHandler") + + +class ExtendedNonNegativePredicate(Predicate): + """ + Nonnegative extended real number predicate. + + Explanation + =========== + + ``ask(Q.extended_nonnegative(x))`` is true iff ``x`` is extended real and + ``x`` is not negative. + + Examples + ======== + + >>> from sympy import ask, I, oo, Q + >>> ask(Q.extended_nonnegative(-1)) + False + >>> ask(Q.extended_nonnegative(oo)) + True + >>> ask(Q.extended_nonnegative(0)) + True + >>> ask(Q.extended_nonnegative(I)) + False + + """ + name = 'extended_nonnegative' + handler = Dispatcher("ExtendedNonNegativeHandler") diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/sets.py b/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/sets.py new file mode 100644 index 0000000000000000000000000000000000000000..18261cee2d9de65df14a31a56b2cd22328328ed0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/assumptions/predicates/sets.py @@ -0,0 +1,399 @@ +from sympy.assumptions import Predicate +from sympy.multipledispatch import Dispatcher + + +class IntegerPredicate(Predicate): + """ + Integer predicate. + + Explanation + =========== + + ``Q.integer(x)`` is true iff ``x`` belongs to the set of integer + numbers. + + Examples + ======== + + >>> from sympy import Q, ask, S + >>> ask(Q.integer(5)) + True + >>> ask(Q.integer(S(1)/2)) + False + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Integer + + """ + name = 'integer' + handler = Dispatcher( + "IntegerHandler", + doc=("Handler for Q.integer.\n\n" + "Test that an expression belongs to the field of integer numbers.") + ) + + +class NonIntegerPredicate(Predicate): + """ + Non-integer extended real predicate. + """ + name = 'noninteger' + handler = Dispatcher( + "NonIntegerHandler", + doc=("Handler for Q.noninteger.\n\n" + "Test that an expression is a non-integer extended real number.") + ) + + +class RationalPredicate(Predicate): + """ + Rational number predicate. + + Explanation + =========== + + ``Q.rational(x)`` is true iff ``x`` belongs to the set of + rational numbers. + + Examples + ======== + + >>> from sympy import ask, Q, pi, S + >>> ask(Q.rational(0)) + True + >>> ask(Q.rational(S(1)/2)) + True + >>> ask(Q.rational(pi)) + False + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Rational_number + + """ + name = 'rational' + handler = Dispatcher( + "RationalHandler", + doc=("Handler for Q.rational.\n\n" + "Test that an expression belongs to the field of rational numbers.") + ) + + +class IrrationalPredicate(Predicate): + """ + Irrational number predicate. + + Explanation + =========== + + ``Q.irrational(x)`` is true iff ``x`` is any real number that + cannot be expressed as a ratio of integers. + + Examples + ======== + + >>> from sympy import ask, Q, pi, S, I + >>> ask(Q.irrational(0)) + False + >>> ask(Q.irrational(S(1)/2)) + False + >>> ask(Q.irrational(pi)) + True + >>> ask(Q.irrational(I)) + False + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Irrational_number + + """ + name = 'irrational' + handler = Dispatcher( + "IrrationalHandler", + doc=("Handler for Q.irrational.\n\n" + "Test that an expression is irrational numbers.") + ) + + +class RealPredicate(Predicate): + r""" + Real number predicate. + + Explanation + =========== + + ``Q.real(x)`` is true iff ``x`` is a real number, i.e., it is in the + interval `(-\infty, \infty)`. Note that, in particular the + infinities are not real. Use ``Q.extended_real`` if you want to + consider those as well. + + A few important facts about reals: + + - Every real number is positive, negative, or zero. Furthermore, + because these sets are pairwise disjoint, each real number is + exactly one of those three. + + - Every real number is also complex. + + - Every real number is finite. + + - Every real number is either rational or irrational. + + - Every real number is either algebraic or transcendental. + + - The facts ``Q.negative``, ``Q.zero``, ``Q.positive``, + ``Q.nonnegative``, ``Q.nonpositive``, ``Q.nonzero``, + ``Q.integer``, ``Q.rational``, and ``Q.irrational`` all imply + ``Q.real``, as do all facts that imply those facts. + + - The facts ``Q.algebraic``, and ``Q.transcendental`` do not imply + ``Q.real``; they imply ``Q.complex``. An algebraic or + transcendental number may or may not be real. + + - The "non" facts (i.e., ``Q.nonnegative``, ``Q.nonzero``, + ``Q.nonpositive`` and ``Q.noninteger``) are not equivalent to + not the fact, but rather, not the fact *and* ``Q.real``. + For example, ``Q.nonnegative`` means ``~Q.negative & Q.real``. + So for example, ``I`` is not nonnegative, nonzero, or + nonpositive. + + Examples + ======== + + >>> from sympy import Q, ask, symbols + >>> x = symbols('x') + >>> ask(Q.real(x), Q.positive(x)) + True + >>> ask(Q.real(0)) + True + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Real_number + + """ + name = 'real' + handler = Dispatcher( + "RealHandler", + doc=("Handler for Q.real.\n\n" + "Test that an expression belongs to the field of real numbers.") + ) + + +class ExtendedRealPredicate(Predicate): + r""" + Extended real predicate. + + Explanation + =========== + + ``Q.extended_real(x)`` is true iff ``x`` is a real number or + `\{-\infty, \infty\}`. + + See documentation of ``Q.real`` for more information about related + facts. + + Examples + ======== + + >>> from sympy import ask, Q, oo, I + >>> ask(Q.extended_real(1)) + True + >>> ask(Q.extended_real(I)) + False + >>> ask(Q.extended_real(oo)) + True + + """ + name = 'extended_real' + handler = Dispatcher( + "ExtendedRealHandler", + doc=("Handler for Q.extended_real.\n\n" + "Test that an expression belongs to the field of extended real\n" + "numbers, that is real numbers union {Infinity, -Infinity}.") + ) + + +class HermitianPredicate(Predicate): + """ + Hermitian predicate. + + Explanation + =========== + + ``ask(Q.hermitian(x))`` is true iff ``x`` belongs to the set of + Hermitian operators. + + References + ========== + + .. [1] https://mathworld.wolfram.com/HermitianOperator.html + + """ + # TODO: Add examples + name = 'hermitian' + handler = Dispatcher( + "HermitianHandler", + doc=("Handler for Q.hermitian.\n\n" + "Test that an expression belongs to the field of Hermitian operators.") + ) + + +class ComplexPredicate(Predicate): + """ + Complex number predicate. + + Explanation + =========== + + ``Q.complex(x)`` is true iff ``x`` belongs to the set of complex + numbers. Note that every complex number is finite. + + Examples + ======== + + >>> from sympy import Q, Symbol, ask, I, oo + >>> x = Symbol('x') + >>> ask(Q.complex(0)) + True + >>> ask(Q.complex(2 + 3*I)) + True + >>> ask(Q.complex(oo)) + False + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Complex_number + + """ + name = 'complex' + handler = Dispatcher( + "ComplexHandler", + doc=("Handler for Q.complex.\n\n" + "Test that an expression belongs to the field of complex numbers.") + ) + + +class ImaginaryPredicate(Predicate): + """ + Imaginary number predicate. + + Explanation + =========== + + ``Q.imaginary(x)`` is true iff ``x`` can be written as a real + number multiplied by the imaginary unit ``I``. Please note that ``0`` + is not considered to be an imaginary number. + + Examples + ======== + + >>> from sympy import Q, ask, I + >>> ask(Q.imaginary(3*I)) + True + >>> ask(Q.imaginary(2 + 3*I)) + False + >>> ask(Q.imaginary(0)) + False + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Imaginary_number + + """ + name = 'imaginary' + handler = Dispatcher( + "ImaginaryHandler", + doc=("Handler for Q.imaginary.\n\n" + "Test that an expression belongs to the field of imaginary numbers,\n" + "that is, numbers in the form x*I, where x is real.") + ) + + +class AntihermitianPredicate(Predicate): + """ + Antihermitian predicate. + + Explanation + =========== + + ``Q.antihermitian(x)`` is true iff ``x`` belongs to the field of + antihermitian operators, i.e., operators in the form ``x*I``, where + ``x`` is Hermitian. + + References + ========== + + .. [1] https://mathworld.wolfram.com/HermitianOperator.html + + """ + # TODO: Add examples + name = 'antihermitian' + handler = Dispatcher( + "AntiHermitianHandler", + doc=("Handler for Q.antihermitian.\n\n" + "Test that an expression belongs to the field of anti-Hermitian\n" + "operators, that is, operators in the form x*I, where x is Hermitian.") + ) + + +class AlgebraicPredicate(Predicate): + r""" + Algebraic number predicate. + + Explanation + =========== + + ``Q.algebraic(x)`` is true iff ``x`` belongs to the set of + algebraic numbers. ``x`` is algebraic if there is some polynomial + in ``p(x)\in \mathbb\{Q\}[x]`` such that ``p(x) = 0``. + + Examples + ======== + + >>> from sympy import ask, Q, sqrt, I, pi + >>> ask(Q.algebraic(sqrt(2))) + True + >>> ask(Q.algebraic(I)) + True + >>> ask(Q.algebraic(pi)) + False + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Algebraic_number + + """ + name = 'algebraic' + AlgebraicHandler = Dispatcher( + "AlgebraicHandler", + doc="""Handler for Q.algebraic key.""" + ) + + +class TranscendentalPredicate(Predicate): + """ + Transcedental number predicate. + + Explanation + =========== + + ``Q.transcendental(x)`` is true iff ``x`` belongs to the set of + transcendental numbers. A transcendental number is a real + or complex number that is not algebraic. + + """ + # TODO: Add examples + name = 'transcendental' + handler = Dispatcher( + "Transcendental", + doc="""Handler for Q.transcendental key.""" + ) diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/refine.py b/.venv/lib/python3.12/site-packages/sympy/assumptions/refine.py new file mode 100644 index 0000000000000000000000000000000000000000..c36a4e1cdb40f1b59a96f60a3b36182b587920fa --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/assumptions/refine.py @@ -0,0 +1,405 @@ +from __future__ import annotations +from typing import Callable + +from sympy.core import S, Add, Expr, Basic, Mul, Pow, Rational +from sympy.core.logic import fuzzy_not +from sympy.logic.boolalg import Boolean + +from sympy.assumptions import ask, Q # type: ignore + + +def refine(expr, assumptions=True): + """ + Simplify an expression using assumptions. + + Explanation + =========== + + Unlike :func:`~.simplify` which performs structural simplification + without any assumption, this function transforms the expression into + the form which is only valid under certain assumptions. Note that + ``simplify()`` is generally not done in refining process. + + Refining boolean expression involves reducing it to ``S.true`` or + ``S.false``. Unlike :func:`~.ask`, the expression will not be reduced + if the truth value cannot be determined. + + Examples + ======== + + >>> from sympy import refine, sqrt, Q + >>> from sympy.abc import x + >>> refine(sqrt(x**2), Q.real(x)) + Abs(x) + >>> refine(sqrt(x**2), Q.positive(x)) + x + + >>> refine(Q.real(x), Q.positive(x)) + True + >>> refine(Q.positive(x), Q.real(x)) + Q.positive(x) + + See Also + ======== + + sympy.simplify.simplify.simplify : Structural simplification without assumptions. + sympy.assumptions.ask.ask : Query for boolean expressions using assumptions. + """ + if not isinstance(expr, Basic): + return expr + + if not expr.is_Atom: + args = [refine(arg, assumptions) for arg in expr.args] + # TODO: this will probably not work with Integral or Polynomial + expr = expr.func(*args) + if hasattr(expr, '_eval_refine'): + ref_expr = expr._eval_refine(assumptions) + if ref_expr is not None: + return ref_expr + name = expr.__class__.__name__ + handler = handlers_dict.get(name, None) + if handler is None: + return expr + new_expr = handler(expr, assumptions) + if (new_expr is None) or (expr == new_expr): + return expr + if not isinstance(new_expr, Expr): + return new_expr + return refine(new_expr, assumptions) + + +def refine_abs(expr, assumptions): + """ + Handler for the absolute value. + + Examples + ======== + + >>> from sympy import Q, Abs + >>> from sympy.assumptions.refine import refine_abs + >>> from sympy.abc import x + >>> refine_abs(Abs(x), Q.real(x)) + >>> refine_abs(Abs(x), Q.positive(x)) + x + >>> refine_abs(Abs(x), Q.negative(x)) + -x + + """ + from sympy.functions.elementary.complexes import Abs + arg = expr.args[0] + if ask(Q.real(arg), assumptions) and \ + fuzzy_not(ask(Q.negative(arg), assumptions)): + # if it's nonnegative + return arg + if ask(Q.negative(arg), assumptions): + return -arg + # arg is Mul + if isinstance(arg, Mul): + r = [refine(abs(a), assumptions) for a in arg.args] + non_abs = [] + in_abs = [] + for i in r: + if isinstance(i, Abs): + in_abs.append(i.args[0]) + else: + non_abs.append(i) + return Mul(*non_abs) * Abs(Mul(*in_abs)) + + +def refine_Pow(expr, assumptions): + """ + Handler for instances of Pow. + + Examples + ======== + + >>> from sympy import Q + >>> from sympy.assumptions.refine import refine_Pow + >>> from sympy.abc import x,y,z + >>> refine_Pow((-1)**x, Q.real(x)) + >>> refine_Pow((-1)**x, Q.even(x)) + 1 + >>> refine_Pow((-1)**x, Q.odd(x)) + -1 + + For powers of -1, even parts of the exponent can be simplified: + + >>> refine_Pow((-1)**(x+y), Q.even(x)) + (-1)**y + >>> refine_Pow((-1)**(x+y+z), Q.odd(x) & Q.odd(z)) + (-1)**y + >>> refine_Pow((-1)**(x+y+2), Q.odd(x)) + (-1)**(y + 1) + >>> refine_Pow((-1)**(x+3), True) + (-1)**(x + 1) + + """ + from sympy.functions.elementary.complexes import Abs + from sympy.functions import sign + if isinstance(expr.base, Abs): + if ask(Q.real(expr.base.args[0]), assumptions) and \ + ask(Q.even(expr.exp), assumptions): + return expr.base.args[0] ** expr.exp + if ask(Q.real(expr.base), assumptions): + if expr.base.is_number: + if ask(Q.even(expr.exp), assumptions): + return abs(expr.base) ** expr.exp + if ask(Q.odd(expr.exp), assumptions): + return sign(expr.base) * abs(expr.base) ** expr.exp + if isinstance(expr.exp, Rational): + if isinstance(expr.base, Pow): + return abs(expr.base.base) ** (expr.base.exp * expr.exp) + + if expr.base is S.NegativeOne: + if expr.exp.is_Add: + + old = expr + + # For powers of (-1) we can remove + # - even terms + # - pairs of odd terms + # - a single odd term + 1 + # - A numerical constant N can be replaced with mod(N,2) + + coeff, terms = expr.exp.as_coeff_add() + terms = set(terms) + even_terms = set() + odd_terms = set() + initial_number_of_terms = len(terms) + + for t in terms: + if ask(Q.even(t), assumptions): + even_terms.add(t) + elif ask(Q.odd(t), assumptions): + odd_terms.add(t) + + terms -= even_terms + if len(odd_terms) % 2: + terms -= odd_terms + new_coeff = (coeff + S.One) % 2 + else: + terms -= odd_terms + new_coeff = coeff % 2 + + if new_coeff != coeff or len(terms) < initial_number_of_terms: + terms.add(new_coeff) + expr = expr.base**(Add(*terms)) + + # Handle (-1)**((-1)**n/2 + m/2) + e2 = 2*expr.exp + if ask(Q.even(e2), assumptions): + if e2.could_extract_minus_sign(): + e2 *= expr.base + if e2.is_Add: + i, p = e2.as_two_terms() + if p.is_Pow and p.base is S.NegativeOne: + if ask(Q.integer(p.exp), assumptions): + i = (i + 1)/2 + if ask(Q.even(i), assumptions): + return expr.base**p.exp + elif ask(Q.odd(i), assumptions): + return expr.base**(p.exp + 1) + else: + return expr.base**(p.exp + i) + + if old != expr: + return expr + + +def refine_atan2(expr, assumptions): + """ + Handler for the atan2 function. + + Examples + ======== + + >>> from sympy import Q, atan2 + >>> from sympy.assumptions.refine import refine_atan2 + >>> from sympy.abc import x, y + >>> refine_atan2(atan2(y,x), Q.real(y) & Q.positive(x)) + atan(y/x) + >>> refine_atan2(atan2(y,x), Q.negative(y) & Q.negative(x)) + atan(y/x) - pi + >>> refine_atan2(atan2(y,x), Q.positive(y) & Q.negative(x)) + atan(y/x) + pi + >>> refine_atan2(atan2(y,x), Q.zero(y) & Q.negative(x)) + pi + >>> refine_atan2(atan2(y,x), Q.positive(y) & Q.zero(x)) + pi/2 + >>> refine_atan2(atan2(y,x), Q.negative(y) & Q.zero(x)) + -pi/2 + >>> refine_atan2(atan2(y,x), Q.zero(y) & Q.zero(x)) + nan + """ + from sympy.functions.elementary.trigonometric import atan + y, x = expr.args + if ask(Q.real(y) & Q.positive(x), assumptions): + return atan(y / x) + elif ask(Q.negative(y) & Q.negative(x), assumptions): + return atan(y / x) - S.Pi + elif ask(Q.positive(y) & Q.negative(x), assumptions): + return atan(y / x) + S.Pi + elif ask(Q.zero(y) & Q.negative(x), assumptions): + return S.Pi + elif ask(Q.positive(y) & Q.zero(x), assumptions): + return S.Pi/2 + elif ask(Q.negative(y) & Q.zero(x), assumptions): + return -S.Pi/2 + elif ask(Q.zero(y) & Q.zero(x), assumptions): + return S.NaN + else: + return expr + + +def refine_re(expr, assumptions): + """ + Handler for real part. + + Examples + ======== + + >>> from sympy.assumptions.refine import refine_re + >>> from sympy import Q, re + >>> from sympy.abc import x + >>> refine_re(re(x), Q.real(x)) + x + >>> refine_re(re(x), Q.imaginary(x)) + 0 + """ + arg = expr.args[0] + if ask(Q.real(arg), assumptions): + return arg + if ask(Q.imaginary(arg), assumptions): + return S.Zero + return _refine_reim(expr, assumptions) + + +def refine_im(expr, assumptions): + """ + Handler for imaginary part. + + Explanation + =========== + + >>> from sympy.assumptions.refine import refine_im + >>> from sympy import Q, im + >>> from sympy.abc import x + >>> refine_im(im(x), Q.real(x)) + 0 + >>> refine_im(im(x), Q.imaginary(x)) + -I*x + """ + arg = expr.args[0] + if ask(Q.real(arg), assumptions): + return S.Zero + if ask(Q.imaginary(arg), assumptions): + return - S.ImaginaryUnit * arg + return _refine_reim(expr, assumptions) + +def refine_arg(expr, assumptions): + """ + Handler for complex argument + + Explanation + =========== + + >>> from sympy.assumptions.refine import refine_arg + >>> from sympy import Q, arg + >>> from sympy.abc import x + >>> refine_arg(arg(x), Q.positive(x)) + 0 + >>> refine_arg(arg(x), Q.negative(x)) + pi + """ + rg = expr.args[0] + if ask(Q.positive(rg), assumptions): + return S.Zero + if ask(Q.negative(rg), assumptions): + return S.Pi + return None + + +def _refine_reim(expr, assumptions): + # Helper function for refine_re & refine_im + expanded = expr.expand(complex = True) + if expanded != expr: + refined = refine(expanded, assumptions) + if refined != expanded: + return refined + # Best to leave the expression as is + return None + + +def refine_sign(expr, assumptions): + """ + Handler for sign. + + Examples + ======== + + >>> from sympy.assumptions.refine import refine_sign + >>> from sympy import Symbol, Q, sign, im + >>> x = Symbol('x', real = True) + >>> expr = sign(x) + >>> refine_sign(expr, Q.positive(x) & Q.nonzero(x)) + 1 + >>> refine_sign(expr, Q.negative(x) & Q.nonzero(x)) + -1 + >>> refine_sign(expr, Q.zero(x)) + 0 + >>> y = Symbol('y', imaginary = True) + >>> expr = sign(y) + >>> refine_sign(expr, Q.positive(im(y))) + I + >>> refine_sign(expr, Q.negative(im(y))) + -I + """ + arg = expr.args[0] + if ask(Q.zero(arg), assumptions): + return S.Zero + if ask(Q.real(arg)): + if ask(Q.positive(arg), assumptions): + return S.One + if ask(Q.negative(arg), assumptions): + return S.NegativeOne + if ask(Q.imaginary(arg)): + arg_re, arg_im = arg.as_real_imag() + if ask(Q.positive(arg_im), assumptions): + return S.ImaginaryUnit + if ask(Q.negative(arg_im), assumptions): + return -S.ImaginaryUnit + return expr + + +def refine_matrixelement(expr, assumptions): + """ + Handler for symmetric part. + + Examples + ======== + + >>> from sympy.assumptions.refine import refine_matrixelement + >>> from sympy import MatrixSymbol, Q + >>> X = MatrixSymbol('X', 3, 3) + >>> refine_matrixelement(X[0, 1], Q.symmetric(X)) + X[0, 1] + >>> refine_matrixelement(X[1, 0], Q.symmetric(X)) + X[0, 1] + """ + from sympy.matrices.expressions.matexpr import MatrixElement + matrix, i, j = expr.args + if ask(Q.symmetric(matrix), assumptions): + if (i - j).could_extract_minus_sign(): + return expr + return MatrixElement(matrix, j, i) + +handlers_dict: dict[str, Callable[[Expr, Boolean], Expr]] = { + 'Abs': refine_abs, + 'Pow': refine_Pow, + 'atan2': refine_atan2, + 're': refine_re, + 'im': refine_im, + 'arg': refine_arg, + 'sign': refine_sign, + 'MatrixElement': refine_matrixelement +} diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/relation/__init__.py b/.venv/lib/python3.12/site-packages/sympy/assumptions/relation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..04f5ed37893766feec941614691a9177f14e4027 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/assumptions/relation/__init__.py @@ -0,0 +1,13 @@ +""" +A module to implement finitary relations [1] as predicate. + +References +========== + +.. [1] https://en.wikipedia.org/wiki/Finitary_relation + +""" + +__all__ = ['BinaryRelation', 'AppliedBinaryRelation'] + +from .binrel import BinaryRelation, AppliedBinaryRelation diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/relation/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/assumptions/relation/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc07b82155e87bc24ba2610e3b5c9284a3dfaedc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/assumptions/relation/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/relation/__pycache__/binrel.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/assumptions/relation/__pycache__/binrel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d07ce70563875991913bfb046d8749dca3cf3a0e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/assumptions/relation/__pycache__/binrel.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/relation/__pycache__/equality.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/assumptions/relation/__pycache__/equality.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c83bdffd8f1172cfde8fb18e962d06ba36aed667 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/assumptions/relation/__pycache__/equality.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/relation/binrel.py b/.venv/lib/python3.12/site-packages/sympy/assumptions/relation/binrel.py new file mode 100644 index 0000000000000000000000000000000000000000..4b4eba05bcce40f1a05483a30136b6ccd891c42f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/assumptions/relation/binrel.py @@ -0,0 +1,212 @@ +""" +General binary relations. +""" +from typing import Optional + +from sympy.core.singleton import S +from sympy.assumptions import AppliedPredicate, ask, Predicate, Q # type: ignore +from sympy.core.kind import BooleanKind +from sympy.core.relational import Eq, Ne, Gt, Lt, Ge, Le +from sympy.logic.boolalg import conjuncts, Not + +__all__ = ["BinaryRelation", "AppliedBinaryRelation"] + + +class BinaryRelation(Predicate): + """ + Base class for all binary relational predicates. + + Explanation + =========== + + Binary relation takes two arguments and returns ``AppliedBinaryRelation`` + instance. To evaluate it to boolean value, use :obj:`~.ask()` or + :obj:`~.refine()` function. + + You can add support for new types by registering the handler to dispatcher. + See :obj:`~.Predicate()` for more information about predicate dispatching. + + Examples + ======== + + Applying and evaluating to boolean value: + + >>> from sympy import Q, ask, sin, cos + >>> from sympy.abc import x + >>> Q.eq(sin(x)**2+cos(x)**2, 1) + Q.eq(sin(x)**2 + cos(x)**2, 1) + >>> ask(_) + True + + You can define a new binary relation by subclassing and dispatching. + Here, we define a relation $R$ such that $x R y$ returns true if + $x = y + 1$. + + >>> from sympy import ask, Number, Q + >>> from sympy.assumptions import BinaryRelation + >>> class MyRel(BinaryRelation): + ... name = "R" + ... is_reflexive = False + >>> Q.R = MyRel() + >>> @Q.R.register(Number, Number) + ... def _(n1, n2, assumptions): + ... return ask(Q.zero(n1 - n2 - 1), assumptions) + >>> Q.R(2, 1) + Q.R(2, 1) + + Now, we can use ``ask()`` to evaluate it to boolean value. + + >>> ask(Q.R(2, 1)) + True + >>> ask(Q.R(1, 2)) + False + + ``Q.R`` returns ``False`` with minimum cost if two arguments have same + structure because it is antireflexive relation [1] by + ``is_reflexive = False``. + + >>> ask(Q.R(x, x)) + False + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Reflexive_relation + """ + + is_reflexive: Optional[bool] = None + is_symmetric: Optional[bool] = None + + def __call__(self, *args): + if not len(args) == 2: + raise ValueError("Binary relation takes two arguments, but got %s." % len(args)) + return AppliedBinaryRelation(self, *args) + + @property + def reversed(self): + if self.is_symmetric: + return self + return None + + @property + def negated(self): + return None + + def _compare_reflexive(self, lhs, rhs): + # quick exit for structurally same arguments + # do not check != here because it cannot catch the + # equivalent arguments with different structures. + + # reflexivity does not hold to NaN + if lhs is S.NaN or rhs is S.NaN: + return None + + reflexive = self.is_reflexive + if reflexive is None: + pass + elif reflexive and (lhs == rhs): + return True + elif not reflexive and (lhs == rhs): + return False + return None + + def eval(self, args, assumptions=True): + # quick exit for structurally same arguments + ret = self._compare_reflexive(*args) + if ret is not None: + return ret + + # don't perform simplify on args here. (done by AppliedBinaryRelation._eval_ask) + # evaluate by multipledispatch + lhs, rhs = args + ret = self.handler(lhs, rhs, assumptions=assumptions) + if ret is not None: + return ret + + # check reversed order if the relation is reflexive + if self.is_reflexive: + types = (type(lhs), type(rhs)) + if self.handler.dispatch(*types) is not self.handler.dispatch(*reversed(types)): + ret = self.handler(rhs, lhs, assumptions=assumptions) + + return ret + + +class AppliedBinaryRelation(AppliedPredicate): + """ + The class of expressions resulting from applying ``BinaryRelation`` + to the arguments. + + """ + + @property + def lhs(self): + """The left-hand side of the relation.""" + return self.arguments[0] + + @property + def rhs(self): + """The right-hand side of the relation.""" + return self.arguments[1] + + @property + def reversed(self): + """ + Try to return the relationship with sides reversed. + """ + revfunc = self.function.reversed + if revfunc is None: + return self + return revfunc(self.rhs, self.lhs) + + @property + def reversedsign(self): + """ + Try to return the relationship with signs reversed. + """ + revfunc = self.function.reversed + if revfunc is None: + return self + if not any(side.kind is BooleanKind for side in self.arguments): + return revfunc(-self.lhs, -self.rhs) + return self + + @property + def negated(self): + neg_rel = self.function.negated + if neg_rel is None: + return Not(self, evaluate=False) + return neg_rel(*self.arguments) + + def _eval_ask(self, assumptions): + conj_assumps = set() + binrelpreds = {Eq: Q.eq, Ne: Q.ne, Gt: Q.gt, Lt: Q.lt, Ge: Q.ge, Le: Q.le} + for a in conjuncts(assumptions): + if a.func in binrelpreds: + conj_assumps.add(binrelpreds[type(a)](*a.args)) + else: + conj_assumps.add(a) + + # After CNF in assumptions module is modified to take polyadic + # predicate, this will be removed + if any(rel in conj_assumps for rel in (self, self.reversed)): + return True + neg_rels = (self.negated, self.reversed.negated, Not(self, evaluate=False), + Not(self.reversed, evaluate=False)) + if any(rel in conj_assumps for rel in neg_rels): + return False + + # evaluation using multipledispatching + ret = self.function.eval(self.arguments, assumptions) + if ret is not None: + return ret + + # simplify the args and try again + args = tuple(a.simplify() for a in self.arguments) + return self.function.eval(args, assumptions) + + def __bool__(self): + ret = ask(self) + if ret is None: + raise TypeError("Cannot determine truth value of %s" % self) + return ret diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/relation/equality.py b/.venv/lib/python3.12/site-packages/sympy/assumptions/relation/equality.py new file mode 100644 index 0000000000000000000000000000000000000000..d467cea2da706de2cbbc9875f93c7f8e324a9088 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/assumptions/relation/equality.py @@ -0,0 +1,302 @@ +""" +Module for mathematical equality [1] and inequalities [2]. + +The purpose of this module is to provide the instances which represent the +binary predicates in order to combine the relationals into logical inference +system. Objects such as ``Q.eq``, ``Q.lt`` should remain internal to +assumptions module, and user must use the classes such as :obj:`~.Eq()`, +:obj:`~.Lt()` instead to construct the relational expressions. + +References +========== + +.. [1] https://en.wikipedia.org/wiki/Equality_(mathematics) +.. [2] https://en.wikipedia.org/wiki/Inequality_(mathematics) +""" +from sympy.assumptions import Q +from sympy.core.relational import is_eq, is_neq, is_gt, is_ge, is_lt, is_le + +from .binrel import BinaryRelation + +__all__ = ['EqualityPredicate', 'UnequalityPredicate', 'StrictGreaterThanPredicate', + 'GreaterThanPredicate', 'StrictLessThanPredicate', 'LessThanPredicate'] + + +class EqualityPredicate(BinaryRelation): + """ + Binary predicate for $=$. + + The purpose of this class is to provide the instance which represent + the equality predicate in order to allow the logical inference. + This class must remain internal to assumptions module and user must + use :obj:`~.Eq()` instead to construct the equality expression. + + Evaluating this predicate to ``True`` or ``False`` is done by + :func:`~.core.relational.is_eq` + + Examples + ======== + + >>> from sympy import ask, Q + >>> Q.eq(0, 0) + Q.eq(0, 0) + >>> ask(_) + True + + See Also + ======== + + sympy.core.relational.Eq + + """ + is_reflexive = True + is_symmetric = True + + name = 'eq' + handler = None # Do not allow dispatching by this predicate + + @property + def negated(self): + return Q.ne + + def eval(self, args, assumptions=True): + if assumptions == True: + # default assumptions for is_eq is None + assumptions = None + return is_eq(*args, assumptions) + + +class UnequalityPredicate(BinaryRelation): + r""" + Binary predicate for $\neq$. + + The purpose of this class is to provide the instance which represent + the inequation predicate in order to allow the logical inference. + This class must remain internal to assumptions module and user must + use :obj:`~.Ne()` instead to construct the inequation expression. + + Evaluating this predicate to ``True`` or ``False`` is done by + :func:`~.core.relational.is_neq` + + Examples + ======== + + >>> from sympy import ask, Q + >>> Q.ne(0, 0) + Q.ne(0, 0) + >>> ask(_) + False + + See Also + ======== + + sympy.core.relational.Ne + + """ + is_reflexive = False + is_symmetric = True + + name = 'ne' + handler = None + + @property + def negated(self): + return Q.eq + + def eval(self, args, assumptions=True): + if assumptions == True: + # default assumptions for is_neq is None + assumptions = None + return is_neq(*args, assumptions) + + +class StrictGreaterThanPredicate(BinaryRelation): + """ + Binary predicate for $>$. + + The purpose of this class is to provide the instance which represent + the ">" predicate in order to allow the logical inference. + This class must remain internal to assumptions module and user must + use :obj:`~.Gt()` instead to construct the equality expression. + + Evaluating this predicate to ``True`` or ``False`` is done by + :func:`~.core.relational.is_gt` + + Examples + ======== + + >>> from sympy import ask, Q + >>> Q.gt(0, 0) + Q.gt(0, 0) + >>> ask(_) + False + + See Also + ======== + + sympy.core.relational.Gt + + """ + is_reflexive = False + is_symmetric = False + + name = 'gt' + handler = None + + @property + def reversed(self): + return Q.lt + + @property + def negated(self): + return Q.le + + def eval(self, args, assumptions=True): + if assumptions == True: + # default assumptions for is_gt is None + assumptions = None + return is_gt(*args, assumptions) + + +class GreaterThanPredicate(BinaryRelation): + """ + Binary predicate for $>=$. + + The purpose of this class is to provide the instance which represent + the ">=" predicate in order to allow the logical inference. + This class must remain internal to assumptions module and user must + use :obj:`~.Ge()` instead to construct the equality expression. + + Evaluating this predicate to ``True`` or ``False`` is done by + :func:`~.core.relational.is_ge` + + Examples + ======== + + >>> from sympy import ask, Q + >>> Q.ge(0, 0) + Q.ge(0, 0) + >>> ask(_) + True + + See Also + ======== + + sympy.core.relational.Ge + + """ + is_reflexive = True + is_symmetric = False + + name = 'ge' + handler = None + + @property + def reversed(self): + return Q.le + + @property + def negated(self): + return Q.lt + + def eval(self, args, assumptions=True): + if assumptions == True: + # default assumptions for is_ge is None + assumptions = None + return is_ge(*args, assumptions) + + +class StrictLessThanPredicate(BinaryRelation): + """ + Binary predicate for $<$. + + The purpose of this class is to provide the instance which represent + the "<" predicate in order to allow the logical inference. + This class must remain internal to assumptions module and user must + use :obj:`~.Lt()` instead to construct the equality expression. + + Evaluating this predicate to ``True`` or ``False`` is done by + :func:`~.core.relational.is_lt` + + Examples + ======== + + >>> from sympy import ask, Q + >>> Q.lt(0, 0) + Q.lt(0, 0) + >>> ask(_) + False + + See Also + ======== + + sympy.core.relational.Lt + + """ + is_reflexive = False + is_symmetric = False + + name = 'lt' + handler = None + + @property + def reversed(self): + return Q.gt + + @property + def negated(self): + return Q.ge + + def eval(self, args, assumptions=True): + if assumptions == True: + # default assumptions for is_lt is None + assumptions = None + return is_lt(*args, assumptions) + + +class LessThanPredicate(BinaryRelation): + """ + Binary predicate for $<=$. + + The purpose of this class is to provide the instance which represent + the "<=" predicate in order to allow the logical inference. + This class must remain internal to assumptions module and user must + use :obj:`~.Le()` instead to construct the equality expression. + + Evaluating this predicate to ``True`` or ``False`` is done by + :func:`~.core.relational.is_le` + + Examples + ======== + + >>> from sympy import ask, Q + >>> Q.le(0, 0) + Q.le(0, 0) + >>> ask(_) + True + + See Also + ======== + + sympy.core.relational.Le + + """ + is_reflexive = True + is_symmetric = False + + name = 'le' + handler = None + + @property + def reversed(self): + return Q.ge + + @property + def negated(self): + return Q.gt + + def eval(self, args, assumptions=True): + if assumptions == True: + # default assumptions for is_le is None + assumptions = None + return is_le(*args, assumptions) diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/satask.py b/.venv/lib/python3.12/site-packages/sympy/assumptions/satask.py new file mode 100644 index 0000000000000000000000000000000000000000..ffc13f6d3bc3fb7f573c8d5d0564b780440c1a8c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/assumptions/satask.py @@ -0,0 +1,369 @@ +""" +Module to evaluate the proposition with assumptions using SAT algorithm. +""" + +from sympy.core.singleton import S +from sympy.core.symbol import Symbol +from sympy.core.kind import NumberKind, UndefinedKind +from sympy.assumptions.ask_generated import get_all_known_matrix_facts, get_all_known_number_facts +from sympy.assumptions.assume import global_assumptions, AppliedPredicate +from sympy.assumptions.sathandlers import class_fact_registry +from sympy.core import oo +from sympy.logic.inference import satisfiable +from sympy.assumptions.cnf import CNF, EncodedCNF +from sympy.matrices.kind import MatrixKind + + +def satask(proposition, assumptions=True, context=global_assumptions, + use_known_facts=True, iterations=oo): + """ + Function to evaluate the proposition with assumptions using SAT algorithm. + + This function extracts every fact relevant to the expressions composing + proposition and assumptions. For example, if a predicate containing + ``Abs(x)`` is proposed, then ``Q.zero(Abs(x)) | Q.positive(Abs(x))`` + will be found and passed to SAT solver because ``Q.nonnegative`` is + registered as a fact for ``Abs``. + + Proposition is evaluated to ``True`` or ``False`` if the truth value can be + determined. If not, ``None`` is returned. + + Parameters + ========== + + proposition : Any boolean expression. + Proposition which will be evaluated to boolean value. + + assumptions : Any boolean expression, optional. + Local assumptions to evaluate the *proposition*. + + context : AssumptionsContext, optional. + Default assumptions to evaluate the *proposition*. By default, + this is ``sympy.assumptions.global_assumptions`` variable. + + use_known_facts : bool, optional. + If ``True``, facts from ``sympy.assumptions.ask_generated`` + module are passed to SAT solver as well. + + iterations : int, optional. + Number of times that relevant facts are recursively extracted. + Default is infinite times until no new fact is found. + + Returns + ======= + + ``True``, ``False``, or ``None`` + + Examples + ======== + + >>> from sympy import Abs, Q + >>> from sympy.assumptions.satask import satask + >>> from sympy.abc import x + >>> satask(Q.zero(Abs(x)), Q.zero(x)) + True + + """ + props = CNF.from_prop(proposition) + _props = CNF.from_prop(~proposition) + + assumptions = CNF.from_prop(assumptions) + + context_cnf = CNF() + if context: + context_cnf = context_cnf.extend(context) + + sat = get_all_relevant_facts(props, assumptions, context_cnf, + use_known_facts=use_known_facts, iterations=iterations) + sat.add_from_cnf(assumptions) + if context: + sat.add_from_cnf(context_cnf) + + return check_satisfiability(props, _props, sat) + + +def check_satisfiability(prop, _prop, factbase): + sat_true = factbase.copy() + sat_false = factbase.copy() + sat_true.add_from_cnf(prop) + sat_false.add_from_cnf(_prop) + can_be_true = satisfiable(sat_true) + can_be_false = satisfiable(sat_false) + + if can_be_true and can_be_false: + return None + + if can_be_true and not can_be_false: + return True + + if not can_be_true and can_be_false: + return False + + if not can_be_true and not can_be_false: + # TODO: Run additional checks to see which combination of the + # assumptions, global_assumptions, and relevant_facts are + # inconsistent. + raise ValueError("Inconsistent assumptions") + + +def extract_predargs(proposition, assumptions=None, context=None): + """ + Extract every expression in the argument of predicates from *proposition*, + *assumptions* and *context*. + + Parameters + ========== + + proposition : sympy.assumptions.cnf.CNF + + assumptions : sympy.assumptions.cnf.CNF, optional. + + context : sympy.assumptions.cnf.CNF, optional. + CNF generated from assumptions context. + + Examples + ======== + + >>> from sympy import Q, Abs + >>> from sympy.assumptions.cnf import CNF + >>> from sympy.assumptions.satask import extract_predargs + >>> from sympy.abc import x, y + >>> props = CNF.from_prop(Q.zero(Abs(x*y))) + >>> assump = CNF.from_prop(Q.zero(x) & Q.zero(y)) + >>> extract_predargs(props, assump) + {x, y, Abs(x*y)} + + """ + req_keys = find_symbols(proposition) + keys = proposition.all_predicates() + # XXX: We need this since True/False are not Basic + lkeys = set() + if assumptions: + lkeys |= assumptions.all_predicates() + if context: + lkeys |= context.all_predicates() + + lkeys = lkeys - {S.true, S.false} + tmp_keys = None + while tmp_keys != set(): + tmp = set() + for l in lkeys: + syms = find_symbols(l) + if (syms & req_keys) != set(): + tmp |= syms + tmp_keys = tmp - req_keys + req_keys |= tmp_keys + keys |= {l for l in lkeys if find_symbols(l) & req_keys != set()} + + exprs = set() + for key in keys: + if isinstance(key, AppliedPredicate): + exprs |= set(key.arguments) + else: + exprs.add(key) + return exprs + +def find_symbols(pred): + """ + Find every :obj:`~.Symbol` in *pred*. + + Parameters + ========== + + pred : sympy.assumptions.cnf.CNF, or any Expr. + + """ + if isinstance(pred, CNF): + symbols = set() + for a in pred.all_predicates(): + symbols |= find_symbols(a) + return symbols + return pred.atoms(Symbol) + + +def get_relevant_clsfacts(exprs, relevant_facts=None): + """ + Extract relevant facts from the items in *exprs*. Facts are defined in + ``assumptions.sathandlers`` module. + + This function is recursively called by ``get_all_relevant_facts()``. + + Parameters + ========== + + exprs : set + Expressions whose relevant facts are searched. + + relevant_facts : sympy.assumptions.cnf.CNF, optional. + Pre-discovered relevant facts. + + Returns + ======= + + exprs : set + Candidates for next relevant fact searching. + + relevant_facts : sympy.assumptions.cnf.CNF + Updated relevant facts. + + Examples + ======== + + Here, we will see how facts relevant to ``Abs(x*y)`` are recursively + extracted. On the first run, set containing the expression is passed + without pre-discovered relevant facts. The result is a set containing + candidates for next run, and ``CNF()`` instance containing facts + which are relevant to ``Abs`` and its argument. + + >>> from sympy import Abs + >>> from sympy.assumptions.satask import get_relevant_clsfacts + >>> from sympy.abc import x, y + >>> exprs = {Abs(x*y)} + >>> exprs, facts = get_relevant_clsfacts(exprs) + >>> exprs + {x*y} + >>> facts.clauses #doctest: +SKIP + {frozenset({Literal(Q.odd(Abs(x*y)), False), Literal(Q.odd(x*y), True)}), + frozenset({Literal(Q.zero(Abs(x*y)), False), Literal(Q.zero(x*y), True)}), + frozenset({Literal(Q.even(Abs(x*y)), False), Literal(Q.even(x*y), True)}), + frozenset({Literal(Q.zero(Abs(x*y)), True), Literal(Q.zero(x*y), False)}), + frozenset({Literal(Q.even(Abs(x*y)), False), + Literal(Q.odd(Abs(x*y)), False), + Literal(Q.odd(x*y), True)}), + frozenset({Literal(Q.even(Abs(x*y)), False), + Literal(Q.even(x*y), True), + Literal(Q.odd(Abs(x*y)), False)}), + frozenset({Literal(Q.positive(Abs(x*y)), False), + Literal(Q.zero(Abs(x*y)), False)})} + + We pass the first run's results to the second run, and get the expressions + for next run and updated facts. + + >>> exprs, facts = get_relevant_clsfacts(exprs, relevant_facts=facts) + >>> exprs + {x, y} + + On final run, no more candidate is returned thus we know that all + relevant facts are successfully retrieved. + + >>> exprs, facts = get_relevant_clsfacts(exprs, relevant_facts=facts) + >>> exprs + set() + + """ + if not relevant_facts: + relevant_facts = CNF() + + newexprs = set() + for expr in exprs: + for fact in class_fact_registry(expr): + newfact = CNF.to_CNF(fact) + relevant_facts = relevant_facts._and(newfact) + for key in newfact.all_predicates(): + if isinstance(key, AppliedPredicate): + newexprs |= set(key.arguments) + + return newexprs - exprs, relevant_facts + + +def get_all_relevant_facts(proposition, assumptions, context, + use_known_facts=True, iterations=oo): + """ + Extract all relevant facts from *proposition* and *assumptions*. + + This function extracts the facts by recursively calling + ``get_relevant_clsfacts()``. Extracted facts are converted to + ``EncodedCNF`` and returned. + + Parameters + ========== + + proposition : sympy.assumptions.cnf.CNF + CNF generated from proposition expression. + + assumptions : sympy.assumptions.cnf.CNF + CNF generated from assumption expression. + + context : sympy.assumptions.cnf.CNF + CNF generated from assumptions context. + + use_known_facts : bool, optional. + If ``True``, facts from ``sympy.assumptions.ask_generated`` + module are encoded as well. + + iterations : int, optional. + Number of times that relevant facts are recursively extracted. + Default is infinite times until no new fact is found. + + Returns + ======= + + sympy.assumptions.cnf.EncodedCNF + + Examples + ======== + + >>> from sympy import Q + >>> from sympy.assumptions.cnf import CNF + >>> from sympy.assumptions.satask import get_all_relevant_facts + >>> from sympy.abc import x, y + >>> props = CNF.from_prop(Q.nonzero(x*y)) + >>> assump = CNF.from_prop(Q.nonzero(x)) + >>> context = CNF.from_prop(Q.nonzero(y)) + >>> get_all_relevant_facts(props, assump, context) #doctest: +SKIP + + + """ + # The relevant facts might introduce new keys, e.g., Q.zero(x*y) will + # introduce the keys Q.zero(x) and Q.zero(y), so we need to run it until + # we stop getting new things. Hopefully this strategy won't lead to an + # infinite loop in the future. + i = 0 + relevant_facts = CNF() + all_exprs = set() + while True: + if i == 0: + exprs = extract_predargs(proposition, assumptions, context) + all_exprs |= exprs + exprs, relevant_facts = get_relevant_clsfacts(exprs, relevant_facts) + i += 1 + if i >= iterations: + break + if not exprs: + break + + if use_known_facts: + known_facts_CNF = CNF() + + if any(expr.kind == MatrixKind(NumberKind) for expr in all_exprs): + known_facts_CNF.add_clauses(get_all_known_matrix_facts()) + # check for undefinedKind since kind system isn't fully implemented + if any(((expr.kind == NumberKind) or (expr.kind == UndefinedKind)) for expr in all_exprs): + known_facts_CNF.add_clauses(get_all_known_number_facts()) + + kf_encoded = EncodedCNF() + kf_encoded.from_cnf(known_facts_CNF) + + def translate_literal(lit, delta): + if lit > 0: + return lit + delta + else: + return lit - delta + + def translate_data(data, delta): + return [{translate_literal(i, delta) for i in clause} for clause in data] + data = [] + symbols = [] + n_lit = len(kf_encoded.symbols) + for i, expr in enumerate(all_exprs): + symbols += [pred(expr) for pred in kf_encoded.symbols] + data += translate_data(kf_encoded.data, i * n_lit) + + encoding = dict(list(zip(symbols, range(1, len(symbols)+1)))) + ctx = EncodedCNF(data, encoding) + else: + ctx = EncodedCNF() + + ctx.add_from_cnf(relevant_facts) + + return ctx diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/sathandlers.py b/.venv/lib/python3.12/site-packages/sympy/assumptions/sathandlers.py new file mode 100644 index 0000000000000000000000000000000000000000..a11199eb0e547187ab280c18196c0259c178e004 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/assumptions/sathandlers.py @@ -0,0 +1,322 @@ +from collections import defaultdict + +from sympy.assumptions.ask import Q +from sympy.core import (Add, Mul, Pow, Number, NumberSymbol, Symbol) +from sympy.core.numbers import ImaginaryUnit +from sympy.functions.elementary.complexes import Abs +from sympy.logic.boolalg import (Equivalent, And, Or, Implies) +from sympy.matrices.expressions import MatMul + +# APIs here may be subject to change + + +### Helper functions ### + +def allargs(symbol, fact, expr): + """ + Apply all arguments of the expression to the fact structure. + + Parameters + ========== + + symbol : Symbol + A placeholder symbol. + + fact : Boolean + Resulting ``Boolean`` expression. + + expr : Expr + + Examples + ======== + + >>> from sympy import Q + >>> from sympy.assumptions.sathandlers import allargs + >>> from sympy.abc import x, y + >>> allargs(x, Q.negative(x) | Q.positive(x), x*y) + (Q.negative(x) | Q.positive(x)) & (Q.negative(y) | Q.positive(y)) + + """ + return And(*[fact.subs(symbol, arg) for arg in expr.args]) + + +def anyarg(symbol, fact, expr): + """ + Apply any argument of the expression to the fact structure. + + Parameters + ========== + + symbol : Symbol + A placeholder symbol. + + fact : Boolean + Resulting ``Boolean`` expression. + + expr : Expr + + Examples + ======== + + >>> from sympy import Q + >>> from sympy.assumptions.sathandlers import anyarg + >>> from sympy.abc import x, y + >>> anyarg(x, Q.negative(x) & Q.positive(x), x*y) + (Q.negative(x) & Q.positive(x)) | (Q.negative(y) & Q.positive(y)) + + """ + return Or(*[fact.subs(symbol, arg) for arg in expr.args]) + + +def exactlyonearg(symbol, fact, expr): + """ + Apply exactly one argument of the expression to the fact structure. + + Parameters + ========== + + symbol : Symbol + A placeholder symbol. + + fact : Boolean + Resulting ``Boolean`` expression. + + expr : Expr + + Examples + ======== + + >>> from sympy import Q + >>> from sympy.assumptions.sathandlers import exactlyonearg + >>> from sympy.abc import x, y + >>> exactlyonearg(x, Q.positive(x), x*y) + (Q.positive(x) & ~Q.positive(y)) | (Q.positive(y) & ~Q.positive(x)) + + """ + pred_args = [fact.subs(symbol, arg) for arg in expr.args] + res = Or(*[And(pred_args[i], *[~lit for lit in pred_args[:i] + + pred_args[i+1:]]) for i in range(len(pred_args))]) + return res + + +### Fact registry ### + +class ClassFactRegistry: + """ + Register handlers against classes. + + Explanation + =========== + + ``register`` method registers the handler function for a class. Here, + handler function should return a single fact. ``multiregister`` method + registers the handler function for multiple classes. Here, handler function + should return a container of multiple facts. + + ``registry(expr)`` returns a set of facts for *expr*. + + Examples + ======== + + Here, we register the facts for ``Abs``. + + >>> from sympy import Abs, Equivalent, Q + >>> from sympy.assumptions.sathandlers import ClassFactRegistry + >>> reg = ClassFactRegistry() + >>> @reg.register(Abs) + ... def f1(expr): + ... return Q.nonnegative(expr) + >>> @reg.register(Abs) + ... def f2(expr): + ... arg = expr.args[0] + ... return Equivalent(~Q.zero(arg), ~Q.zero(expr)) + + Calling the registry with expression returns the defined facts for the + expression. + + >>> from sympy.abc import x + >>> reg(Abs(x)) + {Q.nonnegative(Abs(x)), Equivalent(~Q.zero(x), ~Q.zero(Abs(x)))} + + Multiple facts can be registered at once by ``multiregister`` method. + + >>> reg2 = ClassFactRegistry() + >>> @reg2.multiregister(Abs) + ... def _(expr): + ... arg = expr.args[0] + ... return [Q.even(arg) >> Q.even(expr), Q.odd(arg) >> Q.odd(expr)] + >>> reg2(Abs(x)) + {Implies(Q.even(x), Q.even(Abs(x))), Implies(Q.odd(x), Q.odd(Abs(x)))} + + """ + def __init__(self): + self.singlefacts = defaultdict(frozenset) + self.multifacts = defaultdict(frozenset) + + def register(self, cls): + def _(func): + self.singlefacts[cls] |= {func} + return func + return _ + + def multiregister(self, *classes): + def _(func): + for cls in classes: + self.multifacts[cls] |= {func} + return func + return _ + + def __getitem__(self, key): + ret1 = self.singlefacts[key] + for k in self.singlefacts: + if issubclass(key, k): + ret1 |= self.singlefacts[k] + + ret2 = self.multifacts[key] + for k in self.multifacts: + if issubclass(key, k): + ret2 |= self.multifacts[k] + + return ret1, ret2 + + def __call__(self, expr): + ret = set() + + handlers1, handlers2 = self[type(expr)] + + ret.update(h(expr) for h in handlers1) + for h in handlers2: + ret.update(h(expr)) + return ret + +class_fact_registry = ClassFactRegistry() + + + +### Class fact registration ### + +x = Symbol('x') + +## Abs ## + +@class_fact_registry.multiregister(Abs) +def _(expr): + arg = expr.args[0] + return [Q.nonnegative(expr), + Equivalent(~Q.zero(arg), ~Q.zero(expr)), + Q.even(arg) >> Q.even(expr), + Q.odd(arg) >> Q.odd(expr), + Q.integer(arg) >> Q.integer(expr), + ] + + +### Add ## + +@class_fact_registry.multiregister(Add) +def _(expr): + return [allargs(x, Q.positive(x), expr) >> Q.positive(expr), + allargs(x, Q.negative(x), expr) >> Q.negative(expr), + allargs(x, Q.real(x), expr) >> Q.real(expr), + allargs(x, Q.rational(x), expr) >> Q.rational(expr), + allargs(x, Q.integer(x), expr) >> Q.integer(expr), + exactlyonearg(x, ~Q.integer(x), expr) >> ~Q.integer(expr), + ] + +@class_fact_registry.register(Add) +def _(expr): + allargs_real = allargs(x, Q.real(x), expr) + onearg_irrational = exactlyonearg(x, Q.irrational(x), expr) + return Implies(allargs_real, Implies(onearg_irrational, Q.irrational(expr))) + + +### Mul ### + +@class_fact_registry.multiregister(Mul) +def _(expr): + return [Equivalent(Q.zero(expr), anyarg(x, Q.zero(x), expr)), + allargs(x, Q.positive(x), expr) >> Q.positive(expr), + allargs(x, Q.real(x), expr) >> Q.real(expr), + allargs(x, Q.rational(x), expr) >> Q.rational(expr), + allargs(x, Q.integer(x), expr) >> Q.integer(expr), + exactlyonearg(x, ~Q.rational(x), expr) >> ~Q.integer(expr), + allargs(x, Q.commutative(x), expr) >> Q.commutative(expr), + ] + +@class_fact_registry.register(Mul) +def _(expr): + # Implicitly assumes Mul has more than one arg + # Would be allargs(x, Q.prime(x) | Q.composite(x)) except 1 is composite + # More advanced prime assumptions will require inequalities, as 1 provides + # a corner case. + allargs_prime = allargs(x, Q.prime(x), expr) + return Implies(allargs_prime, ~Q.prime(expr)) + +@class_fact_registry.register(Mul) +def _(expr): + # General Case: Odd number of imaginary args implies mul is imaginary(To be implemented) + allargs_imag_or_real = allargs(x, Q.imaginary(x) | Q.real(x), expr) + onearg_imaginary = exactlyonearg(x, Q.imaginary(x), expr) + return Implies(allargs_imag_or_real, Implies(onearg_imaginary, Q.imaginary(expr))) + +@class_fact_registry.register(Mul) +def _(expr): + allargs_real = allargs(x, Q.real(x), expr) + onearg_irrational = exactlyonearg(x, Q.irrational(x), expr) + return Implies(allargs_real, Implies(onearg_irrational, Q.irrational(expr))) + +@class_fact_registry.register(Mul) +def _(expr): + # Including the integer qualification means we don't need to add any facts + # for odd, since the assumptions already know that every integer is + # exactly one of even or odd. + allargs_integer = allargs(x, Q.integer(x), expr) + anyarg_even = anyarg(x, Q.even(x), expr) + return Implies(allargs_integer, Equivalent(anyarg_even, Q.even(expr))) + + +### MatMul ### + +@class_fact_registry.register(MatMul) +def _(expr): + allargs_square = allargs(x, Q.square(x), expr) + allargs_invertible = allargs(x, Q.invertible(x), expr) + return Implies(allargs_square, Equivalent(Q.invertible(expr), allargs_invertible)) + + +### Pow ### + +@class_fact_registry.multiregister(Pow) +def _(expr): + base, exp = expr.base, expr.exp + return [ + (Q.real(base) & Q.even(exp) & Q.nonnegative(exp)) >> Q.nonnegative(expr), + (Q.nonnegative(base) & Q.odd(exp) & Q.nonnegative(exp)) >> Q.nonnegative(expr), + (Q.nonpositive(base) & Q.odd(exp) & Q.nonnegative(exp)) >> Q.nonpositive(expr), + Equivalent(Q.zero(expr), Q.zero(base) & Q.positive(exp)) + ] + + +### Numbers ### + +_old_assump_getters = { + Q.positive: lambda o: o.is_positive, + Q.zero: lambda o: o.is_zero, + Q.negative: lambda o: o.is_negative, + Q.rational: lambda o: o.is_rational, + Q.irrational: lambda o: o.is_irrational, + Q.even: lambda o: o.is_even, + Q.odd: lambda o: o.is_odd, + Q.imaginary: lambda o: o.is_imaginary, + Q.prime: lambda o: o.is_prime, + Q.composite: lambda o: o.is_composite, +} + +@class_fact_registry.multiregister(Number, NumberSymbol, ImaginaryUnit) +def _(expr): + ret = [] + for p, getter in _old_assump_getters.items(): + pred = p(expr) + prop = getter(expr) + if prop is not None: + ret.append(Equivalent(pred, prop)) + return ret diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/__init__.py b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f8bbd6aa0fb9a91dc62af8265b8888751657b67 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/__pycache__/test_assumptions_2.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/__pycache__/test_assumptions_2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..619e70792f13f2c134084c166fb0e2a3410ea245 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/__pycache__/test_assumptions_2.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/__pycache__/test_context.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/__pycache__/test_context.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be9a9361e9609a96fcd9623afd02717f774c9fb7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/__pycache__/test_context.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/__pycache__/test_matrices.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/__pycache__/test_matrices.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..adcd32939c60e73aab295cf109f5f4fb7b069ef5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/__pycache__/test_matrices.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/__pycache__/test_query.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/__pycache__/test_query.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dcf3d522240d1f4cbc6094c781685c40db9fa4c4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/__pycache__/test_query.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:414791f6d2132332a7bfbb12d67403aebdff572535bbbea5253aa7bb74bb07aa +size 298892 diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/__pycache__/test_refine.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/__pycache__/test_refine.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ce2146a634390d9a8216f706b55a420e64fc034 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/__pycache__/test_refine.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/__pycache__/test_rel_queries.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/__pycache__/test_rel_queries.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5cfed981987c989224103d48065c09418a20bd9e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/__pycache__/test_rel_queries.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/__pycache__/test_satask.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/__pycache__/test_satask.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8731bc7ddde4596b71eb92d459cec507cfbae508 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/__pycache__/test_satask.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/__pycache__/test_sathandlers.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/__pycache__/test_sathandlers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3fc4afa8b492dc3f57a14bb7333ec0298abbfe0e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/__pycache__/test_sathandlers.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/__pycache__/test_wrapper.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/__pycache__/test_wrapper.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3041291134dc25de89f1cae47bd536a03daa71bf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/__pycache__/test_wrapper.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/test_assumptions_2.py b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/test_assumptions_2.py new file mode 100644 index 0000000000000000000000000000000000000000..493fe4a7ed70301754ad2cfe181c5acf30433768 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/test_assumptions_2.py @@ -0,0 +1,35 @@ +""" +rename this to test_assumptions.py when the old assumptions system is deleted +""" +from sympy.abc import x, y +from sympy.assumptions.assume import global_assumptions +from sympy.assumptions.ask import Q +from sympy.printing import pretty + + +def test_equal(): + """Test for equality""" + assert Q.positive(x) == Q.positive(x) + assert Q.positive(x) != ~Q.positive(x) + assert ~Q.positive(x) == ~Q.positive(x) + + +def test_pretty(): + assert pretty(Q.positive(x)) == "Q.positive(x)" + assert pretty( + {Q.positive, Q.integer}) == "{Q.integer, Q.positive}" + + +def test_global(): + """Test for global assumptions""" + global_assumptions.add(x > 0) + assert (x > 0) in global_assumptions + global_assumptions.remove(x > 0) + assert not (x > 0) in global_assumptions + # same with multiple of assumptions + global_assumptions.add(x > 0, y > 0) + assert (x > 0) in global_assumptions + assert (y > 0) in global_assumptions + global_assumptions.clear() + assert not (x > 0) in global_assumptions + assert not (y > 0) in global_assumptions diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/test_context.py b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/test_context.py new file mode 100644 index 0000000000000000000000000000000000000000..be162f1c69492218ff90ea69492925d7779567a4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/test_context.py @@ -0,0 +1,39 @@ +from sympy.assumptions import ask, Q +from sympy.assumptions.assume import assuming, global_assumptions +from sympy.abc import x, y + +def test_assuming(): + with assuming(Q.integer(x)): + assert ask(Q.integer(x)) + assert not ask(Q.integer(x)) + +def test_assuming_nested(): + assert not ask(Q.integer(x)) + assert not ask(Q.integer(y)) + with assuming(Q.integer(x)): + assert ask(Q.integer(x)) + assert not ask(Q.integer(y)) + with assuming(Q.integer(y)): + assert ask(Q.integer(x)) + assert ask(Q.integer(y)) + assert ask(Q.integer(x)) + assert not ask(Q.integer(y)) + assert not ask(Q.integer(x)) + assert not ask(Q.integer(y)) + +def test_finally(): + try: + with assuming(Q.integer(x)): + 1/0 + except ZeroDivisionError: + pass + assert not ask(Q.integer(x)) + +def test_remove_safe(): + global_assumptions.add(Q.integer(x)) + with assuming(): + assert ask(Q.integer(x)) + global_assumptions.remove(Q.integer(x)) + assert not ask(Q.integer(x)) + assert ask(Q.integer(x)) + global_assumptions.clear() # for the benefit of other tests diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/test_matrices.py b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/test_matrices.py new file mode 100644 index 0000000000000000000000000000000000000000..8bfa990f080eebe4d6dd5bfdd733ce1a19adf329 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/test_matrices.py @@ -0,0 +1,283 @@ +from sympy.assumptions.ask import (Q, ask) +from sympy.core.symbol import Symbol +from sympy.matrices.expressions.diagonal import (DiagMatrix, DiagonalMatrix) +from sympy.matrices.dense import Matrix +from sympy.matrices.expressions import (MatrixSymbol, Identity, ZeroMatrix, + OneMatrix, Trace, MatrixSlice, Determinant, BlockMatrix, BlockDiagMatrix) +from sympy.matrices.expressions.factorizations import LofLU +from sympy.testing.pytest import XFAIL + +X = MatrixSymbol('X', 2, 2) +Y = MatrixSymbol('Y', 2, 3) +Z = MatrixSymbol('Z', 2, 2) +A1x1 = MatrixSymbol('A1x1', 1, 1) +B1x1 = MatrixSymbol('B1x1', 1, 1) +C0x0 = MatrixSymbol('C0x0', 0, 0) +V1 = MatrixSymbol('V1', 2, 1) +V2 = MatrixSymbol('V2', 2, 1) + +def test_square(): + assert ask(Q.square(X)) + assert not ask(Q.square(Y)) + assert ask(Q.square(Y*Y.T)) + +def test_invertible(): + assert ask(Q.invertible(X), Q.invertible(X)) + assert ask(Q.invertible(Y)) is False + assert ask(Q.invertible(X*Y), Q.invertible(X)) is False + assert ask(Q.invertible(X*Z), Q.invertible(X)) is None + assert ask(Q.invertible(X*Z), Q.invertible(X) & Q.invertible(Z)) is True + assert ask(Q.invertible(X.T)) is None + assert ask(Q.invertible(X.T), Q.invertible(X)) is True + assert ask(Q.invertible(X.I)) is True + assert ask(Q.invertible(Identity(3))) is True + assert ask(Q.invertible(ZeroMatrix(3, 3))) is False + assert ask(Q.invertible(OneMatrix(1, 1))) is True + assert ask(Q.invertible(OneMatrix(3, 3))) is False + assert ask(Q.invertible(X), Q.fullrank(X) & Q.square(X)) + +def test_singular(): + assert ask(Q.singular(X)) is None + assert ask(Q.singular(X), Q.invertible(X)) is False + assert ask(Q.singular(X), ~Q.invertible(X)) is True + +@XFAIL +def test_invertible_fullrank(): + assert ask(Q.invertible(X), Q.fullrank(X)) is True + + +def test_invertible_BlockMatrix(): + assert ask(Q.invertible(BlockMatrix([Identity(3)]))) == True + assert ask(Q.invertible(BlockMatrix([ZeroMatrix(3, 3)]))) == False + + X = Matrix([[1, 2, 3], [3, 5, 4]]) + Y = Matrix([[4, 2, 7], [2, 3, 5]]) + # non-invertible A block + assert ask(Q.invertible(BlockMatrix([ + [Matrix.ones(3, 3), Y.T], + [X, Matrix.eye(2)], + ]))) == True + # non-invertible B block + assert ask(Q.invertible(BlockMatrix([ + [Y.T, Matrix.ones(3, 3)], + [Matrix.eye(2), X], + ]))) == True + # non-invertible C block + assert ask(Q.invertible(BlockMatrix([ + [X, Matrix.eye(2)], + [Matrix.ones(3, 3), Y.T], + ]))) == True + # non-invertible D block + assert ask(Q.invertible(BlockMatrix([ + [Matrix.eye(2), X], + [Y.T, Matrix.ones(3, 3)], + ]))) == True + + +def test_invertible_BlockDiagMatrix(): + assert ask(Q.invertible(BlockDiagMatrix(Identity(3), Identity(5)))) == True + assert ask(Q.invertible(BlockDiagMatrix(ZeroMatrix(3, 3), Identity(5)))) == False + assert ask(Q.invertible(BlockDiagMatrix(Identity(3), OneMatrix(5, 5)))) == False + + +def test_symmetric(): + assert ask(Q.symmetric(X), Q.symmetric(X)) + assert ask(Q.symmetric(X*Z), Q.symmetric(X)) is None + assert ask(Q.symmetric(X*Z), Q.symmetric(X) & Q.symmetric(Z)) is True + assert ask(Q.symmetric(X + Z), Q.symmetric(X) & Q.symmetric(Z)) is True + assert ask(Q.symmetric(Y)) is False + assert ask(Q.symmetric(Y*Y.T)) is True + assert ask(Q.symmetric(Y.T*X*Y)) is None + assert ask(Q.symmetric(Y.T*X*Y), Q.symmetric(X)) is True + assert ask(Q.symmetric(X**10), Q.symmetric(X)) is True + assert ask(Q.symmetric(A1x1)) is True + assert ask(Q.symmetric(A1x1 + B1x1)) is True + assert ask(Q.symmetric(A1x1 * B1x1)) is True + assert ask(Q.symmetric(V1.T*V1)) is True + assert ask(Q.symmetric(V1.T*(V1 + V2))) is True + assert ask(Q.symmetric(V1.T*(V1 + V2) + A1x1)) is True + assert ask(Q.symmetric(MatrixSlice(Y, (0, 1), (1, 2)))) is True + assert ask(Q.symmetric(Identity(3))) is True + assert ask(Q.symmetric(ZeroMatrix(3, 3))) is True + assert ask(Q.symmetric(OneMatrix(3, 3))) is True + +def _test_orthogonal_unitary(predicate): + assert ask(predicate(X), predicate(X)) + assert ask(predicate(X.T), predicate(X)) is True + assert ask(predicate(X.I), predicate(X)) is True + assert ask(predicate(X**2), predicate(X)) + assert ask(predicate(Y)) is False + assert ask(predicate(X)) is None + assert ask(predicate(X), ~Q.invertible(X)) is False + assert ask(predicate(X*Z*X), predicate(X) & predicate(Z)) is True + assert ask(predicate(Identity(3))) is True + assert ask(predicate(ZeroMatrix(3, 3))) is False + assert ask(Q.invertible(X), predicate(X)) + assert not ask(predicate(X + Z), predicate(X) & predicate(Z)) + +def test_orthogonal(): + _test_orthogonal_unitary(Q.orthogonal) + +def test_unitary(): + _test_orthogonal_unitary(Q.unitary) + assert ask(Q.unitary(X), Q.orthogonal(X)) + +def test_fullrank(): + assert ask(Q.fullrank(X), Q.fullrank(X)) + assert ask(Q.fullrank(X**2), Q.fullrank(X)) + assert ask(Q.fullrank(X.T), Q.fullrank(X)) is True + assert ask(Q.fullrank(X)) is None + assert ask(Q.fullrank(Y)) is None + assert ask(Q.fullrank(X*Z), Q.fullrank(X) & Q.fullrank(Z)) is True + assert ask(Q.fullrank(Identity(3))) is True + assert ask(Q.fullrank(ZeroMatrix(3, 3))) is False + assert ask(Q.fullrank(OneMatrix(1, 1))) is True + assert ask(Q.fullrank(OneMatrix(3, 3))) is False + assert ask(Q.invertible(X), ~Q.fullrank(X)) == False + + +def test_positive_definite(): + assert ask(Q.positive_definite(X), Q.positive_definite(X)) + assert ask(Q.positive_definite(X.T), Q.positive_definite(X)) is True + assert ask(Q.positive_definite(X.I), Q.positive_definite(X)) is True + assert ask(Q.positive_definite(Y)) is False + assert ask(Q.positive_definite(X)) is None + assert ask(Q.positive_definite(X**3), Q.positive_definite(X)) + assert ask(Q.positive_definite(X*Z*X), + Q.positive_definite(X) & Q.positive_definite(Z)) is True + assert ask(Q.positive_definite(X), Q.orthogonal(X)) + assert ask(Q.positive_definite(Y.T*X*Y), + Q.positive_definite(X) & Q.fullrank(Y)) is True + assert not ask(Q.positive_definite(Y.T*X*Y), Q.positive_definite(X)) + assert ask(Q.positive_definite(Identity(3))) is True + assert ask(Q.positive_definite(ZeroMatrix(3, 3))) is False + assert ask(Q.positive_definite(OneMatrix(1, 1))) is True + assert ask(Q.positive_definite(OneMatrix(3, 3))) is False + assert ask(Q.positive_definite(X + Z), Q.positive_definite(X) & + Q.positive_definite(Z)) is True + assert not ask(Q.positive_definite(-X), Q.positive_definite(X)) + assert ask(Q.positive(X[1, 1]), Q.positive_definite(X)) + +def test_triangular(): + assert ask(Q.upper_triangular(X + Z.T + Identity(2)), Q.upper_triangular(X) & + Q.lower_triangular(Z)) is True + assert ask(Q.upper_triangular(X*Z.T), Q.upper_triangular(X) & + Q.lower_triangular(Z)) is True + assert ask(Q.lower_triangular(Identity(3))) is True + assert ask(Q.lower_triangular(ZeroMatrix(3, 3))) is True + assert ask(Q.upper_triangular(ZeroMatrix(3, 3))) is True + assert ask(Q.lower_triangular(OneMatrix(1, 1))) is True + assert ask(Q.upper_triangular(OneMatrix(1, 1))) is True + assert ask(Q.lower_triangular(OneMatrix(3, 3))) is False + assert ask(Q.upper_triangular(OneMatrix(3, 3))) is False + assert ask(Q.triangular(X), Q.unit_triangular(X)) + assert ask(Q.upper_triangular(X**3), Q.upper_triangular(X)) + assert ask(Q.lower_triangular(X**3), Q.lower_triangular(X)) + + +def test_diagonal(): + assert ask(Q.diagonal(X + Z.T + Identity(2)), Q.diagonal(X) & + Q.diagonal(Z)) is True + assert ask(Q.diagonal(ZeroMatrix(3, 3))) + assert ask(Q.diagonal(OneMatrix(1, 1))) is True + assert ask(Q.diagonal(OneMatrix(3, 3))) is False + assert ask(Q.lower_triangular(X) & Q.upper_triangular(X), Q.diagonal(X)) + assert ask(Q.diagonal(X), Q.lower_triangular(X) & Q.upper_triangular(X)) + assert ask(Q.symmetric(X), Q.diagonal(X)) + assert ask(Q.triangular(X), Q.diagonal(X)) + assert ask(Q.diagonal(C0x0)) + assert ask(Q.diagonal(A1x1)) + assert ask(Q.diagonal(A1x1 + B1x1)) + assert ask(Q.diagonal(A1x1*B1x1)) + assert ask(Q.diagonal(V1.T*V2)) + assert ask(Q.diagonal(V1.T*(X + Z)*V1)) + assert ask(Q.diagonal(MatrixSlice(Y, (0, 1), (1, 2)))) is True + assert ask(Q.diagonal(V1.T*(V1 + V2))) is True + assert ask(Q.diagonal(X**3), Q.diagonal(X)) + assert ask(Q.diagonal(Identity(3))) + assert ask(Q.diagonal(DiagMatrix(V1))) + assert ask(Q.diagonal(DiagonalMatrix(X))) + + +def test_non_atoms(): + assert ask(Q.real(Trace(X)), Q.positive(Trace(X))) + +@XFAIL +def test_non_trivial_implies(): + X = MatrixSymbol('X', 3, 3) + Y = MatrixSymbol('Y', 3, 3) + assert ask(Q.lower_triangular(X+Y), Q.lower_triangular(X) & + Q.lower_triangular(Y)) is True + assert ask(Q.triangular(X), Q.lower_triangular(X)) is True + assert ask(Q.triangular(X+Y), Q.lower_triangular(X) & + Q.lower_triangular(Y)) is True + +def test_MatrixSlice(): + X = MatrixSymbol('X', 4, 4) + B = MatrixSlice(X, (1, 3), (1, 3)) + C = MatrixSlice(X, (0, 3), (1, 3)) + assert ask(Q.symmetric(B), Q.symmetric(X)) + assert ask(Q.invertible(B), Q.invertible(X)) + assert ask(Q.diagonal(B), Q.diagonal(X)) + assert ask(Q.orthogonal(B), Q.orthogonal(X)) + assert ask(Q.upper_triangular(B), Q.upper_triangular(X)) + + assert not ask(Q.symmetric(C), Q.symmetric(X)) + assert not ask(Q.invertible(C), Q.invertible(X)) + assert not ask(Q.diagonal(C), Q.diagonal(X)) + assert not ask(Q.orthogonal(C), Q.orthogonal(X)) + assert not ask(Q.upper_triangular(C), Q.upper_triangular(X)) + +def test_det_trace_positive(): + X = MatrixSymbol('X', 4, 4) + assert ask(Q.positive(Trace(X)), Q.positive_definite(X)) + assert ask(Q.positive(Determinant(X)), Q.positive_definite(X)) + +def test_field_assumptions(): + X = MatrixSymbol('X', 4, 4) + Y = MatrixSymbol('Y', 4, 4) + assert ask(Q.real_elements(X), Q.real_elements(X)) + assert not ask(Q.integer_elements(X), Q.real_elements(X)) + assert ask(Q.complex_elements(X), Q.real_elements(X)) + assert ask(Q.complex_elements(X**2), Q.real_elements(X)) + assert ask(Q.real_elements(X**2), Q.integer_elements(X)) + assert ask(Q.real_elements(X+Y), Q.real_elements(X)) is None + assert ask(Q.real_elements(X+Y), Q.real_elements(X) & Q.real_elements(Y)) + from sympy.matrices.expressions.hadamard import HadamardProduct + assert ask(Q.real_elements(HadamardProduct(X, Y)), + Q.real_elements(X) & Q.real_elements(Y)) + assert ask(Q.complex_elements(X+Y), Q.real_elements(X) & Q.complex_elements(Y)) + + assert ask(Q.real_elements(X.T), Q.real_elements(X)) + assert ask(Q.real_elements(X.I), Q.real_elements(X) & Q.invertible(X)) + assert ask(Q.real_elements(Trace(X)), Q.real_elements(X)) + assert ask(Q.integer_elements(Determinant(X)), Q.integer_elements(X)) + assert not ask(Q.integer_elements(X.I), Q.integer_elements(X)) + alpha = Symbol('alpha') + assert ask(Q.real_elements(alpha*X), Q.real_elements(X) & Q.real(alpha)) + assert ask(Q.real_elements(LofLU(X)), Q.real_elements(X)) + e = Symbol('e', integer=True, negative=True) + assert ask(Q.real_elements(X**e), Q.real_elements(X) & Q.invertible(X)) + assert ask(Q.real_elements(X**e), Q.real_elements(X)) is None + +def test_matrix_element_sets(): + X = MatrixSymbol('X', 4, 4) + assert ask(Q.real(X[1, 2]), Q.real_elements(X)) + assert ask(Q.integer(X[1, 2]), Q.integer_elements(X)) + assert ask(Q.complex(X[1, 2]), Q.complex_elements(X)) + assert ask(Q.integer_elements(Identity(3))) + assert ask(Q.integer_elements(ZeroMatrix(3, 3))) + assert ask(Q.integer_elements(OneMatrix(3, 3))) + from sympy.matrices.expressions.fourier import DFT + assert ask(Q.complex_elements(DFT(3))) + + +def test_matrix_element_sets_slices_blocks(): + X = MatrixSymbol('X', 4, 4) + assert ask(Q.integer_elements(X[:, 3]), Q.integer_elements(X)) + assert ask(Q.integer_elements(BlockMatrix([[X], [X]])), + Q.integer_elements(X)) + +def test_matrix_element_sets_determinant_trace(): + assert ask(Q.integer(Determinant(X)), Q.integer_elements(X)) + assert ask(Q.integer(Trace(X)), Q.integer_elements(X)) diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/test_query.py b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/test_query.py new file mode 100644 index 0000000000000000000000000000000000000000..e1ae1f1e482e5c9d19e3dcce3f37ad46b6821817 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/test_query.py @@ -0,0 +1,2541 @@ +from sympy.abc import t, w, x, y, z, n, k, m, p, i +from sympy.assumptions import (ask, AssumptionsContext, Q, register_handler, + remove_handler) +from sympy.assumptions.assume import assuming, global_assumptions, Predicate +from sympy.assumptions.cnf import CNF, Literal +from sympy.assumptions.facts import (single_fact_lookup, + get_known_facts, generate_known_facts_dict, get_known_facts_keys) +from sympy.assumptions.handlers import AskHandler +from sympy.assumptions.ask_generated import (get_all_known_facts, + get_known_facts_dict) +from sympy.core.add import Add +from sympy.core.numbers import (I, Integer, Rational, oo, zoo, pi) +from sympy.core.singleton import S +from sympy.core.power import Pow +from sympy.core.symbol import Str, symbols, Symbol +from sympy.functions.combinatorial.factorials import factorial +from sympy.functions.elementary.complexes import (Abs, im, re, sign) +from sympy.functions.elementary.exponential import (exp, log) +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import ( + acos, acot, asin, atan, cos, cot, sin, tan) +from sympy.logic.boolalg import Equivalent, Implies, Xor, And, to_cnf +from sympy.matrices import Matrix, SparseMatrix +from sympy.testing.pytest import (XFAIL, slow, raises, warns_deprecated_sympy, + _both_exp_pow) +import math + + +def test_int_1(): + z = 1 + assert ask(Q.commutative(z)) is True + assert ask(Q.integer(z)) is True + assert ask(Q.rational(z)) is True + assert ask(Q.real(z)) is True + assert ask(Q.complex(z)) is True + assert ask(Q.irrational(z)) is False + assert ask(Q.imaginary(z)) is False + assert ask(Q.positive(z)) is True + assert ask(Q.negative(z)) is False + assert ask(Q.even(z)) is False + assert ask(Q.odd(z)) is True + assert ask(Q.finite(z)) is True + assert ask(Q.prime(z)) is False + assert ask(Q.composite(z)) is False + assert ask(Q.hermitian(z)) is True + assert ask(Q.antihermitian(z)) is False + + +def test_int_11(): + z = 11 + assert ask(Q.commutative(z)) is True + assert ask(Q.integer(z)) is True + assert ask(Q.rational(z)) is True + assert ask(Q.real(z)) is True + assert ask(Q.complex(z)) is True + assert ask(Q.irrational(z)) is False + assert ask(Q.imaginary(z)) is False + assert ask(Q.positive(z)) is True + assert ask(Q.negative(z)) is False + assert ask(Q.even(z)) is False + assert ask(Q.odd(z)) is True + assert ask(Q.finite(z)) is True + assert ask(Q.prime(z)) is True + assert ask(Q.composite(z)) is False + assert ask(Q.hermitian(z)) is True + assert ask(Q.antihermitian(z)) is False + + +def test_int_12(): + z = 12 + assert ask(Q.commutative(z)) is True + assert ask(Q.integer(z)) is True + assert ask(Q.rational(z)) is True + assert ask(Q.real(z)) is True + assert ask(Q.complex(z)) is True + assert ask(Q.irrational(z)) is False + assert ask(Q.imaginary(z)) is False + assert ask(Q.positive(z)) is True + assert ask(Q.negative(z)) is False + assert ask(Q.even(z)) is True + assert ask(Q.odd(z)) is False + assert ask(Q.finite(z)) is True + assert ask(Q.prime(z)) is False + assert ask(Q.composite(z)) is True + assert ask(Q.hermitian(z)) is True + assert ask(Q.antihermitian(z)) is False + + +def test_float_1(): + z = 1.0 + assert ask(Q.commutative(z)) is True + assert ask(Q.integer(z)) is None + assert ask(Q.rational(z)) is None + assert ask(Q.real(z)) is True + assert ask(Q.complex(z)) is True + assert ask(Q.irrational(z)) is None + assert ask(Q.imaginary(z)) is False + assert ask(Q.positive(z)) is True + assert ask(Q.negative(z)) is False + assert ask(Q.even(z)) is None + assert ask(Q.odd(z)) is None + assert ask(Q.finite(z)) is True + assert ask(Q.prime(z)) is None + assert ask(Q.composite(z)) is None + assert ask(Q.hermitian(z)) is True + assert ask(Q.antihermitian(z)) is False + + z = 7.2123 + assert ask(Q.commutative(z)) is True + assert ask(Q.integer(z)) is False + assert ask(Q.rational(z)) is None + assert ask(Q.real(z)) is True + assert ask(Q.complex(z)) is True + assert ask(Q.irrational(z)) is None + assert ask(Q.imaginary(z)) is False + assert ask(Q.positive(z)) is True + assert ask(Q.negative(z)) is False + assert ask(Q.even(z)) is False + assert ask(Q.odd(z)) is False + assert ask(Q.finite(z)) is True + assert ask(Q.prime(z)) is False + assert ask(Q.composite(z)) is False + assert ask(Q.hermitian(z)) is True + assert ask(Q.antihermitian(z)) is False + + # test for issue #12168 + assert ask(Q.rational(math.pi)) is None + + +def test_zero_0(): + z = Integer(0) + assert ask(Q.nonzero(z)) is False + assert ask(Q.zero(z)) is True + assert ask(Q.commutative(z)) is True + assert ask(Q.integer(z)) is True + assert ask(Q.rational(z)) is True + assert ask(Q.real(z)) is True + assert ask(Q.complex(z)) is True + assert ask(Q.imaginary(z)) is False + assert ask(Q.positive(z)) is False + assert ask(Q.negative(z)) is False + assert ask(Q.even(z)) is True + assert ask(Q.odd(z)) is False + assert ask(Q.finite(z)) is True + assert ask(Q.prime(z)) is False + assert ask(Q.composite(z)) is False + assert ask(Q.hermitian(z)) is True + assert ask(Q.antihermitian(z)) is True + + +def test_negativeone(): + z = Integer(-1) + assert ask(Q.nonzero(z)) is True + assert ask(Q.zero(z)) is False + assert ask(Q.commutative(z)) is True + assert ask(Q.integer(z)) is True + assert ask(Q.rational(z)) is True + assert ask(Q.real(z)) is True + assert ask(Q.complex(z)) is True + assert ask(Q.irrational(z)) is False + assert ask(Q.imaginary(z)) is False + assert ask(Q.positive(z)) is False + assert ask(Q.negative(z)) is True + assert ask(Q.even(z)) is False + assert ask(Q.odd(z)) is True + assert ask(Q.finite(z)) is True + assert ask(Q.prime(z)) is False + assert ask(Q.composite(z)) is False + assert ask(Q.hermitian(z)) is True + assert ask(Q.antihermitian(z)) is False + + +def test_infinity(): + assert ask(Q.commutative(oo)) is True + assert ask(Q.integer(oo)) is False + assert ask(Q.rational(oo)) is False + assert ask(Q.algebraic(oo)) is False + assert ask(Q.real(oo)) is False + assert ask(Q.extended_real(oo)) is True + assert ask(Q.complex(oo)) is False + assert ask(Q.irrational(oo)) is False + assert ask(Q.imaginary(oo)) is False + assert ask(Q.positive(oo)) is False + assert ask(Q.extended_positive(oo)) is True + assert ask(Q.negative(oo)) is False + assert ask(Q.even(oo)) is False + assert ask(Q.odd(oo)) is False + assert ask(Q.finite(oo)) is False + assert ask(Q.infinite(oo)) is True + assert ask(Q.prime(oo)) is False + assert ask(Q.composite(oo)) is False + assert ask(Q.hermitian(oo)) is False + assert ask(Q.antihermitian(oo)) is False + assert ask(Q.positive_infinite(oo)) is True + assert ask(Q.negative_infinite(oo)) is False + + +def test_neg_infinity(): + mm = S.NegativeInfinity + assert ask(Q.commutative(mm)) is True + assert ask(Q.integer(mm)) is False + assert ask(Q.rational(mm)) is False + assert ask(Q.algebraic(mm)) is False + assert ask(Q.real(mm)) is False + assert ask(Q.extended_real(mm)) is True + assert ask(Q.complex(mm)) is False + assert ask(Q.irrational(mm)) is False + assert ask(Q.imaginary(mm)) is False + assert ask(Q.positive(mm)) is False + assert ask(Q.negative(mm)) is False + assert ask(Q.extended_negative(mm)) is True + assert ask(Q.even(mm)) is False + assert ask(Q.odd(mm)) is False + assert ask(Q.finite(mm)) is False + assert ask(Q.infinite(oo)) is True + assert ask(Q.prime(mm)) is False + assert ask(Q.composite(mm)) is False + assert ask(Q.hermitian(mm)) is False + assert ask(Q.antihermitian(mm)) is False + assert ask(Q.positive_infinite(-oo)) is False + assert ask(Q.negative_infinite(-oo)) is True + + +def test_complex_infinity(): + assert ask(Q.commutative(zoo)) is True + assert ask(Q.integer(zoo)) is False + assert ask(Q.rational(zoo)) is False + assert ask(Q.algebraic(zoo)) is False + assert ask(Q.real(zoo)) is False + assert ask(Q.extended_real(zoo)) is False + assert ask(Q.complex(zoo)) is False + assert ask(Q.irrational(zoo)) is False + assert ask(Q.imaginary(zoo)) is False + assert ask(Q.positive(zoo)) is False + assert ask(Q.negative(zoo)) is False + assert ask(Q.zero(zoo)) is False + assert ask(Q.nonzero(zoo)) is False + assert ask(Q.even(zoo)) is False + assert ask(Q.odd(zoo)) is False + assert ask(Q.finite(zoo)) is False + assert ask(Q.infinite(zoo)) is True + assert ask(Q.prime(zoo)) is False + assert ask(Q.composite(zoo)) is False + assert ask(Q.hermitian(zoo)) is False + assert ask(Q.antihermitian(zoo)) is False + assert ask(Q.positive_infinite(zoo)) is False + assert ask(Q.negative_infinite(zoo)) is False + + +def test_nan(): + nan = S.NaN + assert ask(Q.commutative(nan)) is True + assert ask(Q.integer(nan)) is None + assert ask(Q.rational(nan)) is None + assert ask(Q.algebraic(nan)) is None + assert ask(Q.real(nan)) is None + assert ask(Q.extended_real(nan)) is None + assert ask(Q.complex(nan)) is None + assert ask(Q.irrational(nan)) is None + assert ask(Q.imaginary(nan)) is None + assert ask(Q.positive(nan)) is None + assert ask(Q.nonzero(nan)) is None + assert ask(Q.zero(nan)) is None + assert ask(Q.even(nan)) is None + assert ask(Q.odd(nan)) is None + assert ask(Q.finite(nan)) is None + assert ask(Q.infinite(nan)) is None + assert ask(Q.prime(nan)) is None + assert ask(Q.composite(nan)) is None + assert ask(Q.hermitian(nan)) is None + assert ask(Q.antihermitian(nan)) is None + + +def test_Rational_number(): + r = Rational(3, 4) + assert ask(Q.commutative(r)) is True + assert ask(Q.integer(r)) is False + assert ask(Q.rational(r)) is True + assert ask(Q.real(r)) is True + assert ask(Q.complex(r)) is True + assert ask(Q.irrational(r)) is False + assert ask(Q.imaginary(r)) is False + assert ask(Q.positive(r)) is True + assert ask(Q.negative(r)) is False + assert ask(Q.even(r)) is False + assert ask(Q.odd(r)) is False + assert ask(Q.finite(r)) is True + assert ask(Q.prime(r)) is False + assert ask(Q.composite(r)) is False + assert ask(Q.hermitian(r)) is True + assert ask(Q.antihermitian(r)) is False + + r = Rational(1, 4) + assert ask(Q.positive(r)) is True + assert ask(Q.negative(r)) is False + + r = Rational(5, 4) + assert ask(Q.negative(r)) is False + assert ask(Q.positive(r)) is True + + r = Rational(5, 3) + assert ask(Q.positive(r)) is True + assert ask(Q.negative(r)) is False + + r = Rational(-3, 4) + assert ask(Q.positive(r)) is False + assert ask(Q.negative(r)) is True + + r = Rational(-1, 4) + assert ask(Q.positive(r)) is False + assert ask(Q.negative(r)) is True + + r = Rational(-5, 4) + assert ask(Q.negative(r)) is True + assert ask(Q.positive(r)) is False + + r = Rational(-5, 3) + assert ask(Q.positive(r)) is False + assert ask(Q.negative(r)) is True + + +def test_sqrt_2(): + z = sqrt(2) + assert ask(Q.commutative(z)) is True + assert ask(Q.integer(z)) is False + assert ask(Q.rational(z)) is False + assert ask(Q.real(z)) is True + assert ask(Q.complex(z)) is True + assert ask(Q.irrational(z)) is True + assert ask(Q.imaginary(z)) is False + assert ask(Q.positive(z)) is True + assert ask(Q.negative(z)) is False + assert ask(Q.even(z)) is False + assert ask(Q.odd(z)) is False + assert ask(Q.finite(z)) is True + assert ask(Q.prime(z)) is False + assert ask(Q.composite(z)) is False + assert ask(Q.hermitian(z)) is True + assert ask(Q.antihermitian(z)) is False + + +def test_pi(): + z = S.Pi + assert ask(Q.commutative(z)) is True + assert ask(Q.integer(z)) is False + assert ask(Q.rational(z)) is False + assert ask(Q.algebraic(z)) is False + assert ask(Q.real(z)) is True + assert ask(Q.complex(z)) is True + assert ask(Q.irrational(z)) is True + assert ask(Q.imaginary(z)) is False + assert ask(Q.positive(z)) is True + assert ask(Q.negative(z)) is False + assert ask(Q.even(z)) is False + assert ask(Q.odd(z)) is False + assert ask(Q.finite(z)) is True + assert ask(Q.prime(z)) is False + assert ask(Q.composite(z)) is False + assert ask(Q.hermitian(z)) is True + assert ask(Q.antihermitian(z)) is False + + z = S.Pi + 1 + assert ask(Q.commutative(z)) is True + assert ask(Q.integer(z)) is False + assert ask(Q.rational(z)) is False + assert ask(Q.algebraic(z)) is False + assert ask(Q.real(z)) is True + assert ask(Q.complex(z)) is True + assert ask(Q.irrational(z)) is True + assert ask(Q.imaginary(z)) is False + assert ask(Q.positive(z)) is True + assert ask(Q.negative(z)) is False + assert ask(Q.even(z)) is False + assert ask(Q.odd(z)) is False + assert ask(Q.finite(z)) is True + assert ask(Q.prime(z)) is False + assert ask(Q.composite(z)) is False + assert ask(Q.hermitian(z)) is True + assert ask(Q.antihermitian(z)) is False + + z = 2*S.Pi + assert ask(Q.commutative(z)) is True + assert ask(Q.integer(z)) is False + assert ask(Q.rational(z)) is False + assert ask(Q.algebraic(z)) is False + assert ask(Q.real(z)) is True + assert ask(Q.complex(z)) is True + assert ask(Q.irrational(z)) is True + assert ask(Q.imaginary(z)) is False + assert ask(Q.positive(z)) is True + assert ask(Q.negative(z)) is False + assert ask(Q.even(z)) is False + assert ask(Q.odd(z)) is False + assert ask(Q.finite(z)) is True + assert ask(Q.prime(z)) is False + assert ask(Q.composite(z)) is False + assert ask(Q.hermitian(z)) is True + assert ask(Q.antihermitian(z)) is False + + z = S.Pi ** 2 + assert ask(Q.commutative(z)) is True + assert ask(Q.integer(z)) is False + assert ask(Q.rational(z)) is False + assert ask(Q.algebraic(z)) is False + assert ask(Q.real(z)) is True + assert ask(Q.complex(z)) is True + assert ask(Q.irrational(z)) is True + assert ask(Q.imaginary(z)) is False + assert ask(Q.positive(z)) is True + assert ask(Q.negative(z)) is False + assert ask(Q.even(z)) is False + assert ask(Q.odd(z)) is False + assert ask(Q.finite(z)) is True + assert ask(Q.prime(z)) is False + assert ask(Q.composite(z)) is False + assert ask(Q.hermitian(z)) is True + assert ask(Q.antihermitian(z)) is False + + z = (1 + S.Pi) ** 2 + assert ask(Q.commutative(z)) is True + assert ask(Q.integer(z)) is False + assert ask(Q.rational(z)) is False + assert ask(Q.algebraic(z)) is None + assert ask(Q.real(z)) is True + assert ask(Q.complex(z)) is True + assert ask(Q.irrational(z)) is True + assert ask(Q.imaginary(z)) is False + assert ask(Q.positive(z)) is True + assert ask(Q.negative(z)) is False + assert ask(Q.even(z)) is False + assert ask(Q.odd(z)) is False + assert ask(Q.finite(z)) is True + assert ask(Q.prime(z)) is False + assert ask(Q.composite(z)) is False + assert ask(Q.hermitian(z)) is True + assert ask(Q.antihermitian(z)) is False + + +def test_E(): + z = S.Exp1 + assert ask(Q.commutative(z)) is True + assert ask(Q.integer(z)) is False + assert ask(Q.rational(z)) is False + assert ask(Q.algebraic(z)) is False + assert ask(Q.real(z)) is True + assert ask(Q.complex(z)) is True + assert ask(Q.irrational(z)) is True + assert ask(Q.imaginary(z)) is False + assert ask(Q.positive(z)) is True + assert ask(Q.negative(z)) is False + assert ask(Q.even(z)) is False + assert ask(Q.odd(z)) is False + assert ask(Q.finite(z)) is True + assert ask(Q.prime(z)) is False + assert ask(Q.composite(z)) is False + assert ask(Q.hermitian(z)) is True + assert ask(Q.antihermitian(z)) is False + + +def test_GoldenRatio(): + z = S.GoldenRatio + assert ask(Q.commutative(z)) is True + assert ask(Q.integer(z)) is False + assert ask(Q.rational(z)) is False + assert ask(Q.algebraic(z)) is True + assert ask(Q.real(z)) is True + assert ask(Q.complex(z)) is True + assert ask(Q.irrational(z)) is True + assert ask(Q.imaginary(z)) is False + assert ask(Q.positive(z)) is True + assert ask(Q.negative(z)) is False + assert ask(Q.even(z)) is False + assert ask(Q.odd(z)) is False + assert ask(Q.finite(z)) is True + assert ask(Q.prime(z)) is False + assert ask(Q.composite(z)) is False + assert ask(Q.hermitian(z)) is True + assert ask(Q.antihermitian(z)) is False + + +def test_TribonacciConstant(): + z = S.TribonacciConstant + assert ask(Q.commutative(z)) is True + assert ask(Q.integer(z)) is False + assert ask(Q.rational(z)) is False + assert ask(Q.algebraic(z)) is True + assert ask(Q.real(z)) is True + assert ask(Q.complex(z)) is True + assert ask(Q.irrational(z)) is True + assert ask(Q.imaginary(z)) is False + assert ask(Q.positive(z)) is True + assert ask(Q.negative(z)) is False + assert ask(Q.even(z)) is False + assert ask(Q.odd(z)) is False + assert ask(Q.finite(z)) is True + assert ask(Q.prime(z)) is False + assert ask(Q.composite(z)) is False + assert ask(Q.hermitian(z)) is True + assert ask(Q.antihermitian(z)) is False + + +def test_I(): + z = I + assert ask(Q.commutative(z)) is True + assert ask(Q.integer(z)) is False + assert ask(Q.rational(z)) is False + assert ask(Q.algebraic(z)) is True + assert ask(Q.real(z)) is False + assert ask(Q.complex(z)) is True + assert ask(Q.irrational(z)) is False + assert ask(Q.imaginary(z)) is True + assert ask(Q.positive(z)) is False + assert ask(Q.negative(z)) is False + assert ask(Q.even(z)) is False + assert ask(Q.odd(z)) is False + assert ask(Q.finite(z)) is True + assert ask(Q.prime(z)) is False + assert ask(Q.composite(z)) is False + assert ask(Q.hermitian(z)) is False + assert ask(Q.antihermitian(z)) is True + + z = 1 + I + assert ask(Q.commutative(z)) is True + assert ask(Q.integer(z)) is False + assert ask(Q.rational(z)) is False + assert ask(Q.algebraic(z)) is True + assert ask(Q.real(z)) is False + assert ask(Q.complex(z)) is True + assert ask(Q.irrational(z)) is False + assert ask(Q.imaginary(z)) is False + assert ask(Q.positive(z)) is False + assert ask(Q.negative(z)) is False + assert ask(Q.even(z)) is False + assert ask(Q.odd(z)) is False + assert ask(Q.finite(z)) is True + assert ask(Q.prime(z)) is False + assert ask(Q.composite(z)) is False + assert ask(Q.hermitian(z)) is False + assert ask(Q.antihermitian(z)) is False + + z = I*(1 + I) + assert ask(Q.commutative(z)) is True + assert ask(Q.integer(z)) is False + assert ask(Q.rational(z)) is False + assert ask(Q.algebraic(z)) is True + assert ask(Q.real(z)) is False + assert ask(Q.complex(z)) is True + assert ask(Q.irrational(z)) is False + assert ask(Q.imaginary(z)) is False + assert ask(Q.positive(z)) is False + assert ask(Q.negative(z)) is False + assert ask(Q.even(z)) is False + assert ask(Q.odd(z)) is False + assert ask(Q.finite(z)) is True + assert ask(Q.prime(z)) is False + assert ask(Q.composite(z)) is False + assert ask(Q.hermitian(z)) is False + assert ask(Q.antihermitian(z)) is False + + z = I**(I) + assert ask(Q.imaginary(z)) is False + assert ask(Q.real(z)) is True + + z = (-I)**(I) + assert ask(Q.imaginary(z)) is False + assert ask(Q.real(z)) is True + + z = (3*I)**(I) + assert ask(Q.imaginary(z)) is False + assert ask(Q.real(z)) is False + + z = (1)**(I) + assert ask(Q.imaginary(z)) is False + assert ask(Q.real(z)) is True + + z = (-1)**(I) + assert ask(Q.imaginary(z)) is False + assert ask(Q.real(z)) is True + + z = (1+I)**(I) + assert ask(Q.imaginary(z)) is False + assert ask(Q.real(z)) is False + + z = (I)**(I+3) + assert ask(Q.imaginary(z)) is True + assert ask(Q.real(z)) is False + + z = (I)**(I+2) + assert ask(Q.imaginary(z)) is False + assert ask(Q.real(z)) is True + + z = (I)**(2) + assert ask(Q.imaginary(z)) is False + assert ask(Q.real(z)) is True + + z = (I)**(3) + assert ask(Q.imaginary(z)) is True + assert ask(Q.real(z)) is False + + z = (3)**(I) + assert ask(Q.imaginary(z)) is False + assert ask(Q.real(z)) is False + + z = (I)**(0) + assert ask(Q.imaginary(z)) is False + assert ask(Q.real(z)) is True + +def test_bounded(): + x, y, z = symbols('x,y,z') + a = x + y + x, y = a.args + assert ask(Q.finite(a), Q.positive_infinite(y)) is None + assert ask(Q.finite(x)) is None + assert ask(Q.finite(x), Q.finite(x)) is True + assert ask(Q.finite(x), Q.finite(y)) is None + assert ask(Q.finite(x), Q.complex(x)) is True + assert ask(Q.finite(x), Q.extended_real(x)) is None + + assert ask(Q.finite(x + 1)) is None + assert ask(Q.finite(x + 1), Q.finite(x)) is True + a = x + y + x, y = a.args + # B + B + assert ask(Q.finite(a), Q.finite(x) & Q.finite(y)) is True + assert ask(Q.finite(a), Q.positive(x) & Q.finite(y)) is True + assert ask(Q.finite(a), Q.finite(x) & Q.positive(y)) is True + assert ask(Q.finite(a), Q.positive(x) & Q.positive(y)) is True + assert ask(Q.finite(a), Q.positive(x) & Q.finite(y) + & ~Q.positive(y)) is True + assert ask(Q.finite(a), Q.finite(x) & ~Q.positive(x) + & Q.positive(y)) is True + assert ask(Q.finite(a), Q.finite(x) & Q.finite(y) & ~Q.positive(x) + & ~Q.positive(y)) is True + # B + U + assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y)) is False + assert ask(Q.finite(a), Q.positive(x) & ~Q.finite(y)) is False + assert ask(Q.finite(a), Q.finite(x) + & Q.positive_infinite(y)) is False + assert ask(Q.finite(a), Q.positive(x) + & Q.positive_infinite(y)) is False + assert ask(Q.finite(a), Q.positive(x) & ~Q.finite(y) + & ~Q.positive(y)) is False + assert ask(Q.finite(a), Q.finite(x) & ~Q.positive(x) + & Q.positive_infinite(y)) is False + assert ask(Q.finite(a), Q.finite(x) & ~Q.positive(x) & ~Q.finite(y) + & ~Q.positive(y)) is False + # B + ? + assert ask(Q.finite(a), Q.finite(x)) is None + assert ask(Q.finite(a), Q.positive(x)) is None + assert ask(Q.finite(a), Q.finite(x) + & Q.extended_positive(y)) is None + assert ask(Q.finite(a), Q.positive(x) + & Q.extended_positive(y)) is None + assert ask(Q.finite(a), Q.positive(x) & ~Q.positive(y)) is None + assert ask(Q.finite(a), Q.finite(x) & ~Q.positive(x) + & Q.extended_positive(y)) is None + assert ask(Q.finite(a), Q.finite(x) & ~Q.positive(x) + & ~Q.positive(y)) is None + # U + U + assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y)) is None + assert ask(Q.finite(a), Q.positive_infinite(x) + & ~Q.finite(y)) is None + assert ask(Q.finite(a), ~Q.finite(x) + & Q.positive_infinite(y)) is None + assert ask(Q.finite(a), Q.positive_infinite(x) + & Q.positive_infinite(y)) is False + assert ask(Q.finite(a), Q.positive_infinite(x) & ~Q.finite(y) + & ~Q.extended_positive(y)) is None + assert ask(Q.finite(a), ~Q.finite(x) & ~Q.extended_positive(x) + & Q.positive_infinite(y)) is None + assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y) + & ~Q.extended_positive(x) & ~Q.extended_positive(y)) is False + # U + ? + assert ask(Q.finite(a), ~Q.finite(y)) is None + assert ask(Q.finite(a), Q.extended_positive(x) + & ~Q.finite(y)) is None + assert ask(Q.finite(a), Q.positive_infinite(y)) is None + assert ask(Q.finite(a), Q.extended_positive(x) + & Q.positive_infinite(y)) is False + assert ask(Q.finite(a), Q.extended_positive(x) + & ~Q.finite(y) & ~Q.extended_positive(y)) is None + assert ask(Q.finite(a), ~Q.extended_positive(x) + & Q.positive_infinite(y)) is None + assert ask(Q.finite(a), ~Q.extended_positive(x) & ~Q.finite(y) + & ~Q.extended_positive(y)) is False + # ? + ? + assert ask(Q.finite(a)) is None + assert ask(Q.finite(a), Q.extended_positive(x)) is None + assert ask(Q.finite(a), Q.extended_positive(y)) is None + assert ask(Q.finite(a), Q.extended_positive(x) + & Q.extended_positive(y)) is None + assert ask(Q.finite(a), Q.extended_positive(x) + & ~Q.extended_positive(y)) is None + assert ask(Q.finite(a), ~Q.extended_positive(x) + & Q.extended_positive(y)) is None + assert ask(Q.finite(a), ~Q.extended_positive(x) + & ~Q.extended_positive(y)) is None + + x, y, z = symbols('x,y,z') + a = x + y + z + x, y, z = a.args + assert ask(Q.finite(a), Q.negative(x) & Q.negative(y) + & Q.negative(z)) is True + assert ask(Q.finite(a), Q.negative(x) & Q.negative(y) + & Q.finite(z)) is True + assert ask(Q.finite(a), Q.negative(x) & Q.negative(y) + & Q.positive(z)) is True + assert ask(Q.finite(a), Q.negative(x) & Q.negative(y) + & Q.negative_infinite(z)) is False + assert ask(Q.finite(a), Q.negative(x) & Q.negative(y) + & ~Q.finite(z)) is False + assert ask(Q.finite(a), Q.negative(x) & Q.negative(y) + & Q.positive_infinite(z)) is False + assert ask(Q.finite(a), Q.negative(x) & Q.negative(y) + & Q.extended_negative(z)) is None + assert ask(Q.finite(a), Q.negative(x) & Q.negative(y)) is None + assert ask(Q.finite(a), Q.negative(x) & Q.negative(y) + & Q.extended_positive(z)) is None + assert ask(Q.finite(a), Q.negative(x) & Q.finite(y) + & Q.finite(z)) is True + assert ask(Q.finite(a), Q.negative(x) & Q.finite(y) + & Q.positive(z)) is True + assert ask(Q.finite(a), Q.negative(x) & Q.finite(y) + & Q.negative_infinite(z)) is False + assert ask(Q.finite(a), Q.negative(x) & Q.finite(y) + & ~Q.finite(z)) is False + assert ask(Q.finite(a), Q.negative(x) & Q.finite(y) + & Q.positive_infinite(z)) is False + assert ask(Q.finite(a), Q.negative(x) & Q.finite(y) + & Q.extended_negative(z)) is None + assert ask(Q.finite(a), Q.negative(x) & Q.finite(y)) is None + assert ask(Q.finite(a), Q.negative(x) & Q.finite(y) + & Q.extended_positive(z)) is None + assert ask(Q.finite(a), Q.negative(x) & Q.positive(y) + & Q.positive(z)) is True + assert ask(Q.finite(a), Q.negative(x) & Q.positive(y) + & Q.negative_infinite(z)) is False + assert ask(Q.finite(a), Q.negative(x) & Q.positive(y) + & ~Q.finite(z)) is False + assert ask(Q.finite(a), Q.negative(x) & Q.positive(y) + & Q.positive_infinite(z)) is False + assert ask(Q.finite(a), Q.negative(x) & Q.positive(y) + & Q.extended_negative(z)) is None + assert ask(Q.finite(a), Q.negative(x) & Q.extended_positive(y) + & Q.finite(y)) is None + assert ask(Q.finite(a), Q.negative(x) & Q.positive(y) + & Q.extended_positive(z)) is None + assert ask(Q.finite(a), Q.negative(x) & Q.negative_infinite(y) + & Q.negative_infinite(z)) is False + assert ask(Q.finite(a), Q.negative(x) & Q.negative_infinite(y) + & ~Q.finite(z)) is None + assert ask(Q.finite(a), Q.negative(x) & Q.negative_infinite(y) + & Q.positive_infinite(z)) is None + assert ask(Q.finite(a), Q.negative(x) & Q.negative_infinite(y) + & Q.extended_negative(z)) is False + assert ask(Q.finite(a), Q.negative(x) + & Q.negative_infinite(y)) is None + assert ask(Q.finite(a), Q.negative(x) & Q.negative_infinite(y) + & Q.extended_positive(z)) is None + assert ask(Q.finite(a), Q.negative(x) & ~Q.finite(y) + & ~Q.finite(z)) is None + assert ask(Q.finite(a), Q.negative(x) & ~Q.finite(y) + & Q.positive_infinite(z)) is None + assert ask(Q.finite(a), Q.negative(x) & ~Q.finite(y) + & Q.extended_negative(z)) is None + assert ask(Q.finite(a), Q.negative(x) & ~Q.finite(y)) is None + assert ask(Q.finite(a), Q.negative(x) & ~Q.finite(y) + & Q.extended_positive(z)) is None + assert ask(Q.finite(a), Q.negative(x) & Q.positive_infinite(y) + & Q.positive_infinite(z)) is False + assert ask(Q.finite(a), Q.negative(x) & Q.positive_infinite(y) + & Q.negative_infinite(z)) is None + assert ask(Q.finite(a), Q.negative(x) & + Q.positive_infinite(y)) is None + assert ask(Q.finite(a), Q.negative(x) & Q.positive_infinite(y) + & Q.extended_positive(z)) is False + assert ask(Q.finite(a), Q.negative(x) & Q.extended_negative(y) + & Q.extended_negative(z)) is None + assert ask(Q.finite(a), Q.negative(x) + & Q.extended_negative(y)) is None + assert ask(Q.finite(a), Q.negative(x) & Q.extended_negative(y) + & Q.extended_positive(z)) is None + assert ask(Q.finite(a), Q.negative(x)) is None + assert ask(Q.finite(a), Q.negative(x) + & Q.extended_positive(z)) is None + assert ask(Q.finite(a), Q.negative(x) & Q.extended_positive(y) + & Q.extended_positive(z)) is None + assert ask(Q.finite(a), Q.finite(x) & Q.finite(y) + & Q.finite(z)) is True + assert ask(Q.finite(a), Q.finite(x) & Q.finite(y) + & Q.positive(z)) is True + assert ask(Q.finite(a), Q.finite(x) & Q.finite(y) + & Q.negative_infinite(z)) is False + assert ask(Q.finite(a), Q.finite(x) & Q.finite(y) + & ~Q.finite(z)) is False + assert ask(Q.finite(a), Q.finite(x) & Q.finite(y) + & Q.positive_infinite(z)) is False + assert ask(Q.finite(a), Q.finite(x) & Q.finite(y) + & Q.extended_negative(z)) is None + assert ask(Q.finite(a), Q.finite(x) & Q.finite(y)) is None + assert ask(Q.finite(a), Q.finite(x) & Q.finite(y) + & Q.extended_positive(z)) is None + assert ask(Q.finite(a), Q.finite(x) & Q.positive(y) + & Q.positive(z)) is True + assert ask(Q.finite(a), Q.finite(x) & Q.positive(y) + & Q.negative_infinite(z)) is False + assert ask(Q.finite(a), Q.finite(x) & Q.positive(y) + & ~Q.finite(z)) is False + assert ask(Q.finite(a), Q.finite(x) & Q.positive(y) + & Q.positive_infinite(z)) is False + assert ask(Q.finite(a), Q.finite(x) & Q.positive(y) + & Q.extended_negative(z)) is None + assert ask(Q.finite(a), Q.finite(x) & Q.positive(y)) is None + assert ask(Q.finite(a), Q.finite(x) & Q.positive(y) + & Q.extended_positive(z)) is None + assert ask(Q.finite(a), Q.finite(x) & Q.negative_infinite(y) + & Q.negative_infinite(z)) is False + assert ask(Q.finite(a), Q.finite(x) & Q.negative_infinite(y) + & ~Q.finite(z)) is None + assert ask(Q.finite(a), Q.finite(x) & Q.negative_infinite(y) + & Q.positive_infinite(z)) is None + assert ask(Q.finite(a), Q.finite(x) & Q.negative_infinite(y) + & Q.extended_negative(z)) is False + assert ask(Q.finite(a), Q.finite(x) + & Q.negative_infinite(y)) is None + assert ask(Q.finite(a), Q.finite(x) & Q.negative_infinite(y) + & Q.extended_positive(z)) is None + assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y) + & ~Q.finite(z)) is None + assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y) + & Q.positive_infinite(z)) is None + assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y) + & Q.extended_negative(z)) is None + assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y)) is None + assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y) + & Q.extended_positive(z)) is None + assert ask(Q.finite(a), Q.finite(x) & Q.positive_infinite(y) + & Q.positive_infinite(z)) is False + assert ask(Q.finite(a), Q.finite(x) & Q.positive_infinite(y) + & Q.extended_negative(z)) is None + assert ask(Q.finite(a), Q.finite(x) + & Q.positive_infinite(y)) is None + assert ask(Q.finite(a), Q.finite(x) & Q.positive_infinite(y) + & Q.extended_positive(z)) is False + assert ask(Q.finite(a), Q.finite(x) & Q.extended_negative(y) + & Q.extended_negative(z)) is None + assert ask(Q.finite(a), Q.finite(x) + & Q.extended_negative(y)) is None + assert ask(Q.finite(a), Q.finite(x) & Q.extended_negative(y) + & Q.extended_positive(z)) is None + assert ask(Q.finite(a), Q.finite(x)) is None + assert ask(Q.finite(a), Q.finite(x) + & Q.extended_positive(z)) is None + assert ask(Q.finite(a), Q.finite(x) & Q.extended_positive(y) + & Q.extended_positive(z)) is None + assert ask(Q.finite(a), Q.positive(x) & Q.positive(y) + & Q.positive(z)) is True + assert ask(Q.finite(a), Q.positive(x) & Q.positive(y) + & Q.negative_infinite(z)) is False + assert ask(Q.finite(a), Q.positive(x) & Q.positive(y) + & ~Q.finite(z)) is False + assert ask(Q.finite(a), Q.positive(x) & Q.positive(y) + & Q.positive_infinite(z)) is False + assert ask(Q.finite(a), Q.positive(x) & Q.positive(y) + & Q.extended_negative(z)) is None + assert ask(Q.finite(a), Q.positive(x) & Q.positive(y)) is None + assert ask(Q.finite(a), Q.positive(x) & Q.positive(y) + & Q.extended_positive(z)) is None + assert ask(Q.finite(a), Q.positive(x) & Q.negative_infinite(y) + & Q.negative_infinite(z)) is False + assert ask(Q.finite(a), Q.positive(x) & Q.negative_infinite(y) + & ~Q.finite(z)) is None + assert ask(Q.finite(a), Q.positive(x) & Q.negative_infinite(y) + & Q.positive_infinite(z)) is None + assert ask(Q.finite(a), Q.positive(x) & Q.negative_infinite(y) + & Q.extended_negative(z)) is False + assert ask(Q.finite(a), Q.positive(x) + & Q.negative_infinite(y)) is None + assert ask(Q.finite(a), Q.positive(x) & Q.negative_infinite(y) + & Q.extended_positive(z)) is None + assert ask(Q.finite(a), Q.positive(x) & ~Q.finite(y) + & ~Q.finite(z)) is None + assert ask(Q.finite(a), Q.positive(x) & ~Q.finite(y) + & Q.positive_infinite(z)) is None + assert ask(Q.finite(a), Q.positive(x) & ~Q.finite(y) + & Q.extended_negative(z)) is None + assert ask(Q.finite(a), Q.positive(x) & ~Q.finite(y)) is None + assert ask(Q.finite(a), Q.positive(x) & ~Q.finite(y) + & Q.extended_positive(z)) is None + assert ask(Q.finite(a), Q.positive(x) & Q.positive_infinite(y) + & Q.positive_infinite(z)) is False + assert ask(Q.finite(a), Q.positive(x) & Q.positive_infinite(y) + & Q.extended_negative(z)) is None + assert ask(Q.finite(a), Q.positive(x) + & Q.positive_infinite(y)) is None + assert ask(Q.finite(a), Q.positive(x) & Q.positive_infinite(y) + & Q.extended_positive(z)) is False + assert ask(Q.finite(a), Q.positive(x) & Q.extended_negative(y) + & Q.extended_negative(z)) is None + assert ask(Q.finite(a), Q.positive(x) + & Q.extended_negative(y)) is None + assert ask(Q.finite(a), Q.positive(x) & Q.extended_negative(y) + & Q.extended_positive(z)) is None + assert ask(Q.finite(a), Q.positive(x)) is None + assert ask(Q.finite(a), Q.positive(x) + & Q.extended_positive(z)) is None + assert ask(Q.finite(a), Q.positive(x) & Q.extended_positive(y) + & Q.extended_positive(z)) is None + assert ask(Q.finite(a), Q.negative_infinite(x) + & Q.negative_infinite(y) & Q.negative_infinite(z)) is False + assert ask(Q.finite(a), Q.negative_infinite(x) + & Q.negative_infinite(y) & ~Q.finite(z)) is None + assert ask(Q.finite(a), Q.negative_infinite(x) + & Q.negative_infinite(y)& Q.positive_infinite(z)) is None + assert ask(Q.finite(a), Q.negative_infinite(x) + & Q.negative_infinite(y) & Q.extended_negative(z)) is False + assert ask(Q.finite(a), Q.negative_infinite(x) + & Q.negative_infinite(y)) is None + assert ask(Q.finite(a), Q.negative_infinite(x) + & Q.negative_infinite(y) & Q.extended_positive(z)) is None + assert ask(Q.finite(a), Q.negative_infinite(x) + & ~Q.finite(y) & ~Q.finite(z)) is None + assert ask(Q.finite(a), Q.negative_infinite(x) + & ~Q.finite(y) & Q.positive_infinite(z)) is None + assert ask(Q.finite(a), Q.negative_infinite(x) + & ~Q.finite(y) & Q.extended_negative(z)) is None + assert ask(Q.finite(a), Q.negative_infinite(x) + & ~Q.finite(y)) is None + assert ask(Q.finite(a), Q.negative_infinite(x) + & ~Q.finite(y) & Q.extended_positive(z)) is None + assert ask(Q.finite(a), Q.negative_infinite(x) + & Q.positive_infinite(y) & Q.positive_infinite(z)) is None + assert ask(Q.finite(a), Q.negative_infinite(x) + & Q.positive_infinite(y) & Q.extended_negative(z)) is None + assert ask(Q.finite(a), Q.negative_infinite(x) + & Q.positive_infinite(y)) is None + assert ask(Q.finite(a), Q.negative_infinite(x) + & Q.positive_infinite(y) & Q.extended_positive(z)) is None + assert ask(Q.finite(a), Q.negative_infinite(x) + & Q.extended_negative(y) & Q.extended_negative(z)) is False + assert ask(Q.finite(a), Q.negative_infinite(x) + & Q.extended_negative(y)) is None + assert ask(Q.finite(a), Q.negative_infinite(x) + & Q.extended_negative(y) & Q.extended_positive(z)) is None + assert ask(Q.finite(a), Q.negative_infinite(x)) is None + assert ask(Q.finite(a), Q.negative_infinite(x) + & Q.extended_positive(z)) is None + assert ask(Q.finite(a), Q.negative_infinite(x) + & Q.extended_positive(y) & Q.extended_positive(z)) is None + assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y) + & ~Q.finite(z)) is None + assert ask(Q.finite(a), ~Q.finite(x) & Q.positive_infinite(z) + & ~Q.finite(z)) is None + assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y) + & Q.extended_negative(z)) is None + assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y)) is None + assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y) + & Q.extended_positive(z)) is None + assert ask(Q.finite(a), ~Q.finite(x) & Q.positive_infinite(y) + & Q.positive_infinite(z)) is None + assert ask(Q.finite(a), ~Q.finite(x) & Q.positive_infinite(y) + & Q.extended_negative(z)) is None + assert ask(Q.finite(a), ~Q.finite(x) + & Q.positive_infinite(y)) is None + assert ask(Q.finite(a), ~Q.finite(x) & Q.positive_infinite(y) + & Q.extended_positive(z)) is None + assert ask(Q.finite(a), ~Q.finite(x) & Q.extended_negative(y) + & Q.extended_negative(z)) is None + assert ask(Q.finite(a), ~Q.finite(x) + & Q.extended_negative(y)) is None + assert ask(Q.finite(a), ~Q.finite(x) & Q.extended_negative(y) + & Q.extended_positive(z)) is None + assert ask(Q.finite(a), ~Q.finite(x)) is None + assert ask(Q.finite(a), ~Q.finite(x) + & Q.extended_positive(z)) is None + assert ask(Q.finite(a), ~Q.finite(x) & Q.extended_positive(y) + & Q.extended_positive(z)) is None + assert ask(Q.finite(a), Q.positive_infinite(x) + & Q.positive_infinite(y) & Q.positive_infinite(z)) is False + assert ask(Q.finite(a), Q.positive_infinite(x) + & Q.positive_infinite(y) & Q.extended_negative(z)) is None + assert ask(Q.finite(a), Q.positive_infinite(x) + & Q.positive_infinite(y)) is None + assert ask(Q.finite(a), Q.positive_infinite(x) + & Q.positive_infinite(y) & Q.extended_positive(z)) is False + assert ask(Q.finite(a), Q.positive_infinite(x) + & Q.extended_negative(y) & Q.extended_negative(z)) is None + assert ask(Q.finite(a), Q.positive_infinite(x) + & Q.extended_negative(y)) is None + assert ask(Q.finite(a), Q.positive_infinite(x) + & Q.extended_negative(y) & Q.extended_positive(z)) is None + assert ask(Q.finite(a), Q.positive_infinite(x)) is None + assert ask(Q.finite(a), Q.positive_infinite(x) + & Q.extended_positive(z)) is None + assert ask(Q.finite(a), Q.positive_infinite(x) + & Q.extended_positive(y) & Q.extended_positive(z)) is False + assert ask(Q.finite(a), Q.extended_negative(x) + & Q.extended_negative(y) & Q.extended_negative(z)) is None + assert ask(Q.finite(a), Q.extended_negative(x) + & Q.extended_negative(y)) is None + assert ask(Q.finite(a), Q.extended_negative(x) + & Q.extended_negative(y) & Q.extended_positive(z)) is None + assert ask(Q.finite(a), Q.extended_negative(x)) is None + assert ask(Q.finite(a), Q.extended_negative(x) + & Q.extended_positive(z)) is None + assert ask(Q.finite(a), Q.extended_negative(x) + & Q.extended_positive(y) & Q.extended_positive(z)) is None + assert ask(Q.finite(a)) is None + assert ask(Q.finite(a), Q.extended_positive(z)) is None + assert ask(Q.finite(a), Q.extended_positive(y) + & Q.extended_positive(z)) is None + assert ask(Q.finite(a), Q.extended_positive(x) + & Q.extended_positive(y) & Q.extended_positive(z)) is None + + assert ask(Q.finite(2*x)) is None + assert ask(Q.finite(2*x), Q.finite(x)) is True + + x, y, z = symbols('x,y,z') + a = x*y + x, y = a.args + assert ask(Q.finite(a), Q.finite(x) & Q.finite(y)) is True + assert ask(Q.finite(a), Q.finite(x) & ~Q.zero(x) & ~Q.finite(y)) is False + assert ask(Q.finite(a), Q.finite(x)) is None + assert ask(Q.finite(a), ~Q.finite(x) & Q.finite(y) &~Q.zero(y)) is False + assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y)) is False + assert ask(Q.finite(a), ~Q.finite(x)) is None + assert ask(Q.finite(a), Q.finite(y)) is None + assert ask(Q.finite(a), ~Q.finite(y)) is None + assert ask(Q.finite(a)) is None + a = x*y*z + x, y, z = a.args + assert ask(Q.finite(a), Q.finite(x) & Q.finite(y) + & Q.finite(z)) is True + assert ask(Q.finite(a), Q.finite(x) & ~Q.zero(x) & Q.finite(y) + & ~Q.zero(y) & ~Q.finite(z)) is False + assert ask(Q.finite(a), Q.finite(x) & Q.finite(y)) is None + assert ask(Q.finite(a), Q.finite(x) & ~Q.zero(x) & ~Q.finite(y) + & Q.finite(z) & ~Q.zero(z)) is False + assert ask(Q.finite(a), Q.finite(x) & ~Q.zero(x) & ~Q.finite(y) + & ~Q.finite(z)) is False + assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y)) is None + assert ask(Q.finite(a), Q.finite(x) & Q.finite(z)) is None + assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(z)) is None + assert ask(Q.finite(a), Q.finite(x)) is None + assert ask(Q.finite(a), ~Q.finite(x) & Q.finite(y) & ~Q.zero(y) + & Q.finite(z) & ~Q.zero(z)) is False + assert ask(Q.finite(a), ~Q.finite(x) & ~Q.zero(x) & Q.finite(y) + & ~Q.zero(y) & ~Q.finite(z)) is False + assert ask(Q.finite(a), ~Q.finite(x) & Q.finite(y)) is None + assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y) + & Q.finite(z) & ~Q.zero(z)) is False + assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y) + & ~Q.finite(z)) is False + assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y)) is None + assert ask(Q.finite(a), ~Q.finite(x) & Q.finite(z)) is None + assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(z)) is None + assert ask(Q.finite(a), ~Q.finite(x)) is None + assert ask(Q.finite(a), Q.finite(y) & Q.finite(z)) is None + assert ask(Q.finite(a), Q.finite(y) & ~Q.finite(z)) is None + assert ask(Q.finite(a), Q.finite(y)) is None + assert ask(Q.finite(a), ~Q.finite(y) & Q.finite(z)) is None + assert ask(Q.finite(a), ~Q.finite(y) & ~Q.finite(z)) is None + assert ask(Q.finite(a), ~Q.finite(y)) is None + assert ask(Q.finite(a), Q.finite(z)) is None + assert ask(Q.finite(a), ~Q.finite(z)) is None + assert ask(Q.finite(a), ~Q.finite(z) & Q.extended_nonzero(x) + & Q.extended_nonzero(y) & Q.extended_nonzero(z)) is None + assert ask(Q.finite(a), Q.extended_nonzero(x) & ~Q.finite(y) + & Q.extended_nonzero(y) & ~Q.finite(z) + & Q.extended_nonzero(z)) is False + + x, y, z = symbols('x,y,z') + assert ask(Q.finite(x**2)) is None + assert ask(Q.finite(2**x)) is None + assert ask(Q.finite(2**x), Q.finite(x)) is True + assert ask(Q.finite(x**x)) is None + assert ask(Q.finite(S.Half ** x)) is None + assert ask(Q.finite(S.Half ** x), Q.extended_positive(x)) is True + assert ask(Q.finite(S.Half ** x), Q.extended_negative(x)) is None + assert ask(Q.finite(2**x), Q.extended_negative(x)) is True + assert ask(Q.finite(sqrt(x))) is None + assert ask(Q.finite(2**x), ~Q.finite(x)) is False + assert ask(Q.finite(x**2), ~Q.finite(x)) is False + + # https://github.com/sympy/sympy/issues/27707 + assert ask(Q.finite(x**y), Q.real(x) & Q.real(y)) is None + assert ask(Q.finite(x**y), Q.real(x) & Q.negative(y)) is None + assert ask(Q.finite(x**y), Q.zero(x) & Q.negative(y)) is False + assert ask(Q.finite(x**y), Q.real(x) & Q.positive(y)) is True + assert ask(Q.finite(x**y), Q.nonzero(x) & Q.real(y)) is True + assert ask(Q.finite(x**y), Q.nonzero(x) & Q.negative(y)) is True + assert ask(Q.finite(x**y), Q.zero(x) & Q.positive(y)) is True + + # sign function + assert ask(Q.finite(sign(x))) is True + assert ask(Q.finite(sign(x)), ~Q.finite(x)) is True + + # exponential functions + assert ask(Q.finite(log(x))) is None + assert ask(Q.finite(log(x)), Q.finite(x)) is None + assert ask(Q.finite(log(x)), ~Q.zero(x)) is True + assert ask(Q.finite(log(x)), Q.infinite(x)) is False + assert ask(Q.finite(log(x)), Q.zero(x)) is False + assert ask(Q.finite(exp(x))) is None + assert ask(Q.finite(exp(x)), Q.finite(x)) is True + assert ask(Q.finite(exp(2))) is True + + # trigonometric functions + assert ask(Q.finite(sin(x))) is True + assert ask(Q.finite(sin(x)), ~Q.finite(x)) is True + assert ask(Q.finite(cos(x))) is True + assert ask(Q.finite(cos(x)), ~Q.finite(x)) is True + assert ask(Q.finite(2*sin(x))) is True + assert ask(Q.finite(sin(x)**2)) is True + assert ask(Q.finite(cos(x)**2)) is True + assert ask(Q.finite(cos(x) + sin(x))) is True + + +def test_unbounded(): + assert ask(Q.infinite(I * oo)) is True + assert ask(Q.infinite(1 + I*oo)) is True + assert ask(Q.infinite(3 * (I * oo))) is True + assert ask(Q.infinite(-I * oo)) is True + assert ask(Q.infinite(1 + zoo)) is True + assert ask(Q.infinite(I * zoo)) is True + assert ask(Q.infinite(x / y), Q.infinite(x) & Q.finite(y) & ~Q.zero(y)) is True + assert ask(Q.infinite(I * oo - I * oo)) is None + assert ask(Q.infinite(x * I * oo)) is None + assert ask(Q.infinite(1 / x), Q.finite(x) & ~Q.zero(x)) is False + assert ask(Q.infinite(1 / (I * oo))) is False + + +def test_issue_27441(): + # https://github.com/sympy/sympy/issues/27441 + assert ask(Q.composite(y), Q.integer(y) & Q.positive(y) & ~Q.prime(y)) is None + + +def test_issue_27447(): + x,y,z = symbols('x y z') + a = x*y + assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y)) is None + assert ask(Q.finite(a), ~Q.finite(x) & Q.finite(y)) is None + + a = x*y*z + assert ask(Q.finite(a), Q.finite(x) & Q.finite(y) + & ~Q.finite(z)) is None + assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y) + & Q.finite(z) ) is None + assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y) + & ~Q.finite(z)) is None + assert ask(Q.finite(a), ~Q.finite(x) & Q.finite(y) + & Q.finite(z)) is None + assert ask(Q.finite(a), ~Q.finite(x) & Q.finite(y) + & ~Q.finite(z)) is None + assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y) + & Q.finite(z)) is None + + +@XFAIL +def test_issue_27662_xfail(): + assert ask(Q.finite(x*y), ~Q.finite(x) + & Q.zero(y)) is None + + +@XFAIL +def test_bounded_xfail(): + """We need to support relations in ask for this to work""" + assert ask(Q.finite(sin(x)**x)) is True + assert ask(Q.finite(cos(x)**x)) is True + + +def test_commutative(): + """By default objects are Q.commutative that is why it returns True + for both key=True and key=False""" + assert ask(Q.commutative(x)) is True + assert ask(Q.commutative(x), ~Q.commutative(x)) is False + assert ask(Q.commutative(x), Q.complex(x)) is True + assert ask(Q.commutative(x), Q.imaginary(x)) is True + assert ask(Q.commutative(x), Q.real(x)) is True + assert ask(Q.commutative(x), Q.positive(x)) is True + assert ask(Q.commutative(x), ~Q.commutative(y)) is True + + assert ask(Q.commutative(2*x)) is True + assert ask(Q.commutative(2*x), ~Q.commutative(x)) is False + + assert ask(Q.commutative(x + 1)) is True + assert ask(Q.commutative(x + 1), ~Q.commutative(x)) is False + + assert ask(Q.commutative(x**2)) is True + assert ask(Q.commutative(x**2), ~Q.commutative(x)) is False + + assert ask(Q.commutative(log(x))) is True + + +@_both_exp_pow +def test_complex(): + assert ask(Q.complex(x)) is None + assert ask(Q.complex(x), Q.complex(x)) is True + assert ask(Q.complex(x), Q.complex(y)) is None + assert ask(Q.complex(x), ~Q.complex(x)) is False + assert ask(Q.complex(x), Q.real(x)) is True + assert ask(Q.complex(x), ~Q.real(x)) is None + assert ask(Q.complex(x), Q.rational(x)) is True + assert ask(Q.complex(x), Q.irrational(x)) is True + assert ask(Q.complex(x), Q.positive(x)) is True + assert ask(Q.complex(x), Q.imaginary(x)) is True + assert ask(Q.complex(x), Q.algebraic(x)) is True + + # a+b + assert ask(Q.complex(x + 1), Q.complex(x)) is True + assert ask(Q.complex(x + 1), Q.real(x)) is True + assert ask(Q.complex(x + 1), Q.rational(x)) is True + assert ask(Q.complex(x + 1), Q.irrational(x)) is True + assert ask(Q.complex(x + 1), Q.imaginary(x)) is True + assert ask(Q.complex(x + 1), Q.integer(x)) is True + assert ask(Q.complex(x + 1), Q.even(x)) is True + assert ask(Q.complex(x + 1), Q.odd(x)) is True + assert ask(Q.complex(x + y), Q.complex(x) & Q.complex(y)) is True + assert ask(Q.complex(x + y), Q.real(x) & Q.imaginary(y)) is True + + # a*x +b + assert ask(Q.complex(2*x + 1), Q.complex(x)) is True + assert ask(Q.complex(2*x + 1), Q.real(x)) is True + assert ask(Q.complex(2*x + 1), Q.positive(x)) is True + assert ask(Q.complex(2*x + 1), Q.rational(x)) is True + assert ask(Q.complex(2*x + 1), Q.irrational(x)) is True + assert ask(Q.complex(2*x + 1), Q.imaginary(x)) is True + assert ask(Q.complex(2*x + 1), Q.integer(x)) is True + assert ask(Q.complex(2*x + 1), Q.even(x)) is True + assert ask(Q.complex(2*x + 1), Q.odd(x)) is True + + # x**2 + assert ask(Q.complex(x**2), Q.complex(x)) is True + assert ask(Q.complex(x**2), Q.real(x)) is True + assert ask(Q.complex(x**2), Q.positive(x)) is True + assert ask(Q.complex(x**2), Q.rational(x)) is True + assert ask(Q.complex(x**2), Q.irrational(x)) is True + assert ask(Q.complex(x**2), Q.imaginary(x)) is True + assert ask(Q.complex(x**2), Q.integer(x)) is True + assert ask(Q.complex(x**2), Q.even(x)) is True + assert ask(Q.complex(x**2), Q.odd(x)) is True + + # 2**x + assert ask(Q.complex(2**x), Q.complex(x)) is True + assert ask(Q.complex(2**x), Q.real(x)) is True + assert ask(Q.complex(2**x), Q.positive(x)) is True + assert ask(Q.complex(2**x), Q.rational(x)) is True + assert ask(Q.complex(2**x), Q.irrational(x)) is True + assert ask(Q.complex(2**x), Q.imaginary(x)) is True + assert ask(Q.complex(2**x), Q.integer(x)) is True + assert ask(Q.complex(2**x), Q.even(x)) is True + assert ask(Q.complex(2**x), Q.odd(x)) is True + assert ask(Q.complex(x**y), Q.complex(x) & Q.complex(y)) is True + + # trigonometric expressions + assert ask(Q.complex(sin(x))) is True + assert ask(Q.complex(sin(2*x + 1))) is True + assert ask(Q.complex(cos(x))) is True + assert ask(Q.complex(cos(2*x + 1))) is True + + # exponential + assert ask(Q.complex(exp(x))) is True + assert ask(Q.complex(exp(x))) is True + + # Q.complexes + assert ask(Q.complex(Abs(x))) is True + assert ask(Q.complex(re(x))) is True + assert ask(Q.complex(im(x))) is True + + +def test_even_query(): + assert ask(Q.even(x)) is None + assert ask(Q.even(x), Q.integer(x)) is None + assert ask(Q.even(x), ~Q.integer(x)) is False + assert ask(Q.even(x), Q.rational(x)) is None + assert ask(Q.even(x), Q.positive(x)) is None + + assert ask(Q.even(2*x)) is None + assert ask(Q.even(2*x), Q.integer(x)) is True + assert ask(Q.even(2*x), Q.even(x)) is True + assert ask(Q.even(2*x), Q.irrational(x)) is False + assert ask(Q.even(2*x), Q.odd(x)) is True + assert ask(Q.even(2*x), ~Q.integer(x)) is None + assert ask(Q.even(3*x), Q.integer(x)) is None + assert ask(Q.even(3*x), Q.even(x)) is True + assert ask(Q.even(3*x), Q.odd(x)) is False + + assert ask(Q.even(x + 1), Q.odd(x)) is True + assert ask(Q.even(x + 1), Q.even(x)) is False + assert ask(Q.even(x + 2), Q.odd(x)) is False + assert ask(Q.even(x + 2), Q.even(x)) is True + assert ask(Q.even(7 - x), Q.odd(x)) is True + assert ask(Q.even(7 + x), Q.odd(x)) is True + assert ask(Q.even(x + y), Q.odd(x) & Q.odd(y)) is True + assert ask(Q.even(x + y), Q.odd(x) & Q.even(y)) is False + assert ask(Q.even(x + y), Q.even(x) & Q.even(y)) is True + + assert ask(Q.even(2*x + 1), Q.integer(x)) is False + assert ask(Q.even(2*x*y), Q.rational(x) & Q.rational(x)) is None + assert ask(Q.even(2*x*y), Q.irrational(x) & Q.irrational(x)) is None + + assert ask(Q.even(x + y + z), Q.odd(x) & Q.odd(y) & Q.even(z)) is True + assert ask(Q.even(x + y + z + t), + Q.odd(x) & Q.odd(y) & Q.even(z) & Q.integer(t)) is None + + assert ask(Q.even(Abs(x)), Q.even(x)) is True + assert ask(Q.even(Abs(x)), ~Q.even(x)) is None + assert ask(Q.even(re(x)), Q.even(x)) is True + assert ask(Q.even(re(x)), ~Q.even(x)) is None + assert ask(Q.even(im(x)), Q.even(x)) is True + assert ask(Q.even(im(x)), Q.real(x)) is True + + assert ask(Q.even((-1)**n), Q.integer(n)) is False + + assert ask(Q.even(k**2), Q.even(k)) is True + assert ask(Q.even(n**2), Q.odd(n)) is False + assert ask(Q.even(2**k), Q.even(k)) is None + assert ask(Q.even(x**2)) is None + + assert ask(Q.even(k**m), Q.even(k) & Q.integer(m) & ~Q.negative(m)) is None + assert ask(Q.even(n**m), Q.odd(n) & Q.integer(m) & ~Q.negative(m)) is False + + assert ask(Q.even(k**p), Q.even(k) & Q.integer(p) & Q.positive(p)) is True + assert ask(Q.even(n**p), Q.odd(n) & Q.integer(p) & Q.positive(p)) is False + + assert ask(Q.even(m**k), Q.even(k) & Q.integer(m) & ~Q.negative(m)) is None + assert ask(Q.even(p**k), Q.even(k) & Q.integer(p) & Q.positive(p)) is None + + assert ask(Q.even(m**n), Q.odd(n) & Q.integer(m) & ~Q.negative(m)) is None + assert ask(Q.even(p**n), Q.odd(n) & Q.integer(p) & Q.positive(p)) is None + + assert ask(Q.even(k**x), Q.even(k)) is None + assert ask(Q.even(n**x), Q.odd(n)) is None + + assert ask(Q.even(x*y), Q.integer(x) & Q.integer(y)) is None + assert ask(Q.even(x*x), Q.integer(x)) is None + assert ask(Q.even(x*(x + y)), Q.integer(x) & Q.odd(y)) is True + assert ask(Q.even(x*(x + y)), Q.integer(x) & Q.even(y)) is None + + +@XFAIL +def test_evenness_in_ternary_integer_product_with_odd(): + # Tests that oddness inference is independent of term ordering. + # Term ordering at the point of testing depends on SymPy's symbol order, so + # we try to force a different order by modifying symbol names. + assert ask(Q.even(x*y*(y + z)), Q.integer(x) & Q.integer(y) & Q.odd(z)) is True + assert ask(Q.even(y*x*(x + z)), Q.integer(x) & Q.integer(y) & Q.odd(z)) is True + + +def test_evenness_in_ternary_integer_product_with_even(): + assert ask(Q.even(x*y*(y + z)), Q.integer(x) & Q.integer(y) & Q.even(z)) is None + + +def test_extended_real(): + assert ask(Q.extended_real(x), Q.positive_infinite(x)) is True + assert ask(Q.extended_real(x), Q.positive(x)) is True + assert ask(Q.extended_real(x), Q.zero(x)) is True + assert ask(Q.extended_real(x), Q.negative(x)) is True + assert ask(Q.extended_real(x), Q.negative_infinite(x)) is True + + assert ask(Q.extended_real(-x), Q.positive(x)) is True + assert ask(Q.extended_real(-x), Q.negative(x)) is True + + assert ask(Q.extended_real(x + S.Infinity), Q.real(x)) is True + + assert ask(Q.extended_real(x), Q.infinite(x)) is None + + +@_both_exp_pow +def test_rational(): + assert ask(Q.rational(x), Q.integer(x)) is True + assert ask(Q.rational(x), Q.irrational(x)) is False + assert ask(Q.rational(x), Q.real(x)) is None + assert ask(Q.rational(x), Q.positive(x)) is None + assert ask(Q.rational(x), Q.negative(x)) is None + assert ask(Q.rational(x), Q.nonzero(x)) is None + assert ask(Q.rational(x), ~Q.algebraic(x)) is False + + assert ask(Q.rational(2*x), Q.rational(x)) is True + assert ask(Q.rational(2*x), Q.integer(x)) is True + assert ask(Q.rational(2*x), Q.even(x)) is True + assert ask(Q.rational(2*x), Q.odd(x)) is True + assert ask(Q.rational(2*x), Q.irrational(x)) is False + + assert ask(Q.rational(x/2), Q.rational(x)) is True + assert ask(Q.rational(x/2), Q.integer(x)) is True + assert ask(Q.rational(x/2), Q.even(x)) is True + assert ask(Q.rational(x/2), Q.odd(x)) is True + assert ask(Q.rational(x/2), Q.irrational(x)) is False + + assert ask(Q.rational(1/x), Q.rational(x) & Q.nonzero(x)) is True + assert ask(Q.rational(1/x), Q.integer(x) & Q.nonzero(x)) is True + assert ask(Q.rational(1/x), Q.even(x) & Q.nonzero(x)) is True + assert ask(Q.rational(1/x), Q.odd(x)) is True + assert ask(Q.rational(1/x), Q.irrational(x)) is False + + assert ask(Q.rational(2/x), Q.rational(x) & Q.nonzero(x)) is True + assert ask(Q.rational(2/x), Q.integer(x) & Q.nonzero(x)) is True + assert ask(Q.rational(2/x), Q.even(x) & Q.nonzero(x)) is True + assert ask(Q.rational(2/x), Q.odd(x)) is True + assert ask(Q.rational(2/x), Q.irrational(x)) is False + + assert ask(Q.rational(x), ~Q.algebraic(x)) is False + + # with multiple symbols + assert ask(Q.rational(x*y), Q.irrational(x) & Q.irrational(y)) is None + assert ask(Q.rational(y/x), Q.rational(x) & Q.rational(y) & Q.nonzero(x)) is True + assert ask(Q.rational(y/x), Q.integer(x) & Q.rational(y) & Q.nonzero(x)) is True + assert ask(Q.rational(y/x), Q.even(x) & Q.rational(y) & Q.nonzero(x)) is True + assert ask(Q.rational(y/x), Q.odd(x) & Q.rational(y)) is True + assert ask(Q.rational(y/x), Q.irrational(x) & Q.rational(y) & Q.nonzero(y)) is False + + for f in [exp, sin, tan, asin, atan, cos]: + assert ask(Q.rational(f(7))) is False + assert ask(Q.rational(f(7, evaluate=False))) is False + assert ask(Q.rational(f(0, evaluate=False))) is True + assert ask(Q.rational(f(x)), Q.rational(x)) is None + assert ask(Q.rational(f(x)), Q.rational(x) & Q.nonzero(x)) is False + + for g in [log, acos]: + assert ask(Q.rational(g(7))) is False + assert ask(Q.rational(g(7, evaluate=False))) is False + assert ask(Q.rational(g(1, evaluate=False))) is True + assert ask(Q.rational(g(x)), Q.rational(x)) is None + assert ask(Q.rational(g(x)), Q.rational(x) & Q.nonzero(x - 1)) is False + + for h in [cot, acot]: + assert ask(Q.rational(h(7))) is False + assert ask(Q.rational(h(7, evaluate=False))) is False + assert ask(Q.rational(h(x)), Q.rational(x)) is False + + # https://github.com/sympy/sympy/issues/27442 + assert ask(Q.rational(x**y),Q.irrational(x) & Q.rational(y)) is None + assert ask(Q.rational(x**y),Q.integer(x) & Q.prime(x) & Q.rational(y)) is None + assert ask(Q.rational(x**y),Q.integer(x) & Q.integer(y)) is None + assert ask(Q.rational(x**y),Q.integer(x) & Q.eq(x,0) & Q.integer(y)) is None + assert ask(Q.rational(x**y),Q.eq(x,1) & Q.rational(y)) is None + assert ask(Q.rational(x**y),Q.eq(x,-1) & Q.rational(y)) is None + assert ask(Q.rational(x**y), Q.prime(x) & Q.rational(y)) is None + assert ask(Q.rational(x**y), ~Q.rational(x) & Q.integer(y) ) is None + assert ask(Q.rational(Pow(-1, x, evaluate=False), Q.rational(x))) is None + assert ask(Q.rational(x**y), Q.integer(y) & ~Q. algebraic(x)) is None + assert ask(Q.rational(x**y), Q.integer(y) & ~Q. algebraic(x) & ~Q.zero(x)) is None + assert ask(Q.rational(x**y), Q.integer(y) & ~Q.algebraic(x) & Q.complex(x) & ~Q.real(x)) is None + assert ask(Q.rational(x**y), Q.integer(y) & ~Q.algebraic(x) & Q.complex(x)) is None + + +def test_hermitian(): + assert ask(Q.hermitian(x)) is None + assert ask(Q.hermitian(x), Q.antihermitian(x)) is None + assert ask(Q.hermitian(x), Q.imaginary(x)) is False + assert ask(Q.hermitian(x), Q.prime(x)) is True + assert ask(Q.hermitian(x), Q.real(x)) is True + assert ask(Q.hermitian(x), Q.zero(x)) is True + + assert ask(Q.hermitian(x + 1), Q.antihermitian(x)) is None + assert ask(Q.hermitian(x + 1), Q.complex(x)) is None + assert ask(Q.hermitian(x + 1), Q.hermitian(x)) is True + assert ask(Q.hermitian(x + 1), Q.imaginary(x)) is False + assert ask(Q.hermitian(x + 1), Q.real(x)) is True + assert ask(Q.hermitian(x + I), Q.antihermitian(x)) is None + assert ask(Q.hermitian(x + I), Q.complex(x)) is None + assert ask(Q.hermitian(x + I), Q.hermitian(x)) is False + assert ask(Q.hermitian(x + I), Q.imaginary(x)) is None + assert ask(Q.hermitian(x + I), Q.real(x)) is False + assert ask( + Q.hermitian(x + y), Q.antihermitian(x) & Q.antihermitian(y)) is None + assert ask(Q.hermitian(x + y), Q.antihermitian(x) & Q.complex(y)) is None + assert ask( + Q.hermitian(x + y), Q.antihermitian(x) & Q.hermitian(y)) is None + assert ask(Q.hermitian(x + y), Q.antihermitian(x) & Q.imaginary(y)) is None + assert ask(Q.hermitian(x + y), Q.antihermitian(x) & Q.real(y)) is None + assert ask(Q.hermitian(x + y), Q.hermitian(x) & Q.complex(y)) is None + assert ask(Q.hermitian(x + y), Q.hermitian(x) & Q.hermitian(y)) is True + assert ask(Q.hermitian(x + y), Q.hermitian(x) & Q.imaginary(y)) is False + assert ask(Q.hermitian(x + y), Q.hermitian(x) & Q.real(y)) is True + assert ask(Q.hermitian(x + y), Q.imaginary(x) & Q.complex(y)) is None + assert ask(Q.hermitian(x + y), Q.imaginary(x) & Q.imaginary(y)) is None + assert ask(Q.hermitian(x + y), Q.imaginary(x) & Q.real(y)) is False + assert ask(Q.hermitian(x + y), Q.real(x) & Q.complex(y)) is None + assert ask(Q.hermitian(x + y), Q.real(x) & Q.real(y)) is True + + assert ask(Q.hermitian(I*x), Q.antihermitian(x)) is True + assert ask(Q.hermitian(I*x), Q.complex(x)) is None + assert ask(Q.hermitian(I*x), Q.hermitian(x)) is False + assert ask(Q.hermitian(I*x), Q.imaginary(x)) is True + assert ask(Q.hermitian(I*x), Q.real(x)) is False + assert ask(Q.hermitian(x*y), Q.hermitian(x) & Q.real(y)) is True + + assert ask( + Q.hermitian(x + y + z), Q.real(x) & Q.real(y) & Q.real(z)) is True + assert ask(Q.hermitian(x + y + z), + Q.real(x) & Q.real(y) & Q.imaginary(z)) is False + assert ask(Q.hermitian(x + y + z), + Q.real(x) & Q.imaginary(y) & Q.imaginary(z)) is None + assert ask(Q.hermitian(x + y + z), + Q.imaginary(x) & Q.imaginary(y) & Q.imaginary(z)) is None + + assert ask(Q.antihermitian(x)) is None + assert ask(Q.antihermitian(x), Q.real(x)) is False + assert ask(Q.antihermitian(x), Q.prime(x)) is False + + assert ask(Q.antihermitian(x + 1), Q.antihermitian(x)) is False + assert ask(Q.antihermitian(x + 1), Q.complex(x)) is None + assert ask(Q.antihermitian(x + 1), Q.hermitian(x)) is None + assert ask(Q.antihermitian(x + 1), Q.imaginary(x)) is False + assert ask(Q.antihermitian(x + 1), Q.real(x)) is None + assert ask(Q.antihermitian(x + I), Q.antihermitian(x)) is True + assert ask(Q.antihermitian(x + I), Q.complex(x)) is None + assert ask(Q.antihermitian(x + I), Q.hermitian(x)) is None + assert ask(Q.antihermitian(x + I), Q.imaginary(x)) is True + assert ask(Q.antihermitian(x + I), Q.real(x)) is False + assert ask(Q.antihermitian(x), Q.zero(x)) is True + + assert ask( + Q.antihermitian(x + y), Q.antihermitian(x) & Q.antihermitian(y) + ) is True + assert ask( + Q.antihermitian(x + y), Q.antihermitian(x) & Q.complex(y)) is None + assert ask( + Q.antihermitian(x + y), Q.antihermitian(x) & Q.hermitian(y)) is None + assert ask( + Q.antihermitian(x + y), Q.antihermitian(x) & Q.imaginary(y)) is True + assert ask(Q.antihermitian(x + y), Q.antihermitian(x) & Q.real(y) + ) is False + assert ask(Q.antihermitian(x + y), Q.hermitian(x) & Q.complex(y)) is None + assert ask(Q.antihermitian(x + y), Q.hermitian(x) & Q.hermitian(y) + ) is None + assert ask( + Q.antihermitian(x + y), Q.hermitian(x) & Q.imaginary(y)) is None + assert ask(Q.antihermitian(x + y), Q.hermitian(x) & Q.real(y)) is None + assert ask(Q.antihermitian(x + y), Q.imaginary(x) & Q.complex(y)) is None + assert ask(Q.antihermitian(x + y), Q.imaginary(x) & Q.imaginary(y)) is True + assert ask(Q.antihermitian(x + y), Q.imaginary(x) & Q.real(y)) is False + assert ask(Q.antihermitian(x + y), Q.real(x) & Q.complex(y)) is None + assert ask(Q.antihermitian(x + y), Q.real(x) & Q.real(y)) is None + + assert ask(Q.antihermitian(I*x), Q.real(x)) is True + assert ask(Q.antihermitian(I*x), Q.antihermitian(x)) is False + assert ask(Q.antihermitian(I*x), Q.complex(x)) is None + assert ask(Q.antihermitian(x*y), Q.antihermitian(x) & Q.real(y)) is True + + assert ask(Q.antihermitian(x + y + z), + Q.real(x) & Q.real(y) & Q.real(z)) is None + assert ask(Q.antihermitian(x + y + z), + Q.real(x) & Q.real(y) & Q.imaginary(z)) is None + assert ask(Q.antihermitian(x + y + z), + Q.real(x) & Q.imaginary(y) & Q.imaginary(z)) is False + assert ask(Q.antihermitian(x + y + z), + Q.imaginary(x) & Q.imaginary(y) & Q.imaginary(z)) is True + + +@_both_exp_pow +def test_imaginary(): + assert ask(Q.imaginary(x)) is None + assert ask(Q.imaginary(x), Q.real(x)) is False + assert ask(Q.imaginary(x), Q.prime(x)) is False + + assert ask(Q.imaginary(x + 1), Q.real(x)) is False + assert ask(Q.imaginary(x + 1), Q.imaginary(x)) is False + assert ask(Q.imaginary(x + I), Q.real(x)) is False + assert ask(Q.imaginary(x + I), Q.imaginary(x)) is True + assert ask(Q.imaginary(x + y), Q.imaginary(x) & Q.imaginary(y)) is True + assert ask(Q.imaginary(x + y), Q.real(x) & Q.real(y)) is False + assert ask(Q.imaginary(x + y), Q.imaginary(x) & Q.real(y)) is False + assert ask(Q.imaginary(x + y), Q.complex(x) & Q.real(y)) is None + assert ask( + Q.imaginary(x + y + z), Q.real(x) & Q.real(y) & Q.real(z)) is False + assert ask(Q.imaginary(x + y + z), + Q.real(x) & Q.real(y) & Q.imaginary(z)) is None + assert ask(Q.imaginary(x + y + z), + Q.real(x) & Q.imaginary(y) & Q.imaginary(z)) is False + + assert ask(Q.imaginary(I*x), Q.real(x)) is True + assert ask(Q.imaginary(I*x), Q.imaginary(x)) is False + assert ask(Q.imaginary(I*x), Q.complex(x)) is None + assert ask(Q.imaginary(x*y), Q.imaginary(x) & Q.real(y)) is True + assert ask(Q.imaginary(x*y), Q.real(x) & Q.real(y)) is False + + assert ask(Q.imaginary(I**x), Q.negative(x)) is None + assert ask(Q.imaginary(I**x), Q.positive(x)) is None + assert ask(Q.imaginary(I**x), Q.even(x)) is False + assert ask(Q.imaginary(I**x), Q.odd(x)) is True + assert ask(Q.imaginary(I**x), Q.imaginary(x)) is False + assert ask(Q.imaginary((2*I)**x), Q.imaginary(x)) is False + assert ask(Q.imaginary(x**0), Q.imaginary(x)) is False + assert ask(Q.imaginary(x**y), Q.imaginary(x) & Q.imaginary(y)) is None + assert ask(Q.imaginary(x**y), Q.imaginary(x) & Q.real(y)) is None + assert ask(Q.imaginary(x**y), Q.real(x) & Q.imaginary(y)) is None + assert ask(Q.imaginary(x**y), Q.real(x) & Q.real(y)) is None + assert ask(Q.imaginary(x**y), Q.imaginary(x) & Q.integer(y)) is None + assert ask(Q.imaginary(x**y), Q.imaginary(y) & Q.integer(x)) is None + assert ask(Q.imaginary(x**y), Q.imaginary(x) & Q.odd(y)) is True + assert ask(Q.imaginary(x**y), Q.imaginary(x) & Q.rational(y)) is None + assert ask(Q.imaginary(x**y), Q.imaginary(x) & Q.even(y)) is False + + assert ask(Q.imaginary(x**y), Q.real(x) & Q.integer(y)) is False + assert ask(Q.imaginary(x**y), Q.positive(x) & Q.real(y)) is False + assert ask(Q.imaginary(x**y), Q.negative(x) & Q.real(y)) is None + assert ask(Q.imaginary(x**y), Q.negative(x) & Q.real(y) & ~Q.rational(y)) is False + assert ask(Q.imaginary(x**y), Q.integer(x) & Q.imaginary(y)) is None + assert ask(Q.imaginary(x**y), Q.negative(x) & Q.rational(y) & Q.integer(2*y)) is True + assert ask(Q.imaginary(x**y), Q.negative(x) & Q.rational(y) & ~Q.integer(2*y)) is False + assert ask(Q.imaginary(x**y), Q.negative(x) & Q.rational(y)) is None + assert ask(Q.imaginary(x**y), Q.real(x) & Q.rational(y) & ~Q.integer(2*y)) is False + assert ask(Q.imaginary(x**y), Q.real(x) & Q.rational(y) & Q.integer(2*y)) is None + + # logarithm + assert ask(Q.imaginary(log(I))) is True + assert ask(Q.imaginary(log(2*I))) is False + assert ask(Q.imaginary(log(I + 1))) is False + assert ask(Q.imaginary(log(x)), Q.complex(x)) is None + assert ask(Q.imaginary(log(x)), Q.imaginary(x)) is None + assert ask(Q.imaginary(log(x)), Q.positive(x)) is False + assert ask(Q.imaginary(log(exp(x))), Q.complex(x)) is None + assert ask(Q.imaginary(log(exp(x))), Q.imaginary(x)) is None # zoo/I/a+I*b + assert ask(Q.imaginary(log(exp(I)))) is True + + # exponential + assert ask(Q.imaginary(exp(x)**x), Q.imaginary(x)) is False + eq = Pow(exp(pi*I*x, evaluate=False), x, evaluate=False) + assert ask(Q.imaginary(eq), Q.even(x)) is False + eq = Pow(exp(pi*I*x/2, evaluate=False), x, evaluate=False) + assert ask(Q.imaginary(eq), Q.odd(x)) is True + assert ask(Q.imaginary(exp(3*I*pi*x)**x), Q.integer(x)) is False + assert ask(Q.imaginary(exp(2*pi*I, evaluate=False))) is False + assert ask(Q.imaginary(exp(pi*I/2, evaluate=False))) is True + + # issue 7886 + assert ask(Q.imaginary(Pow(x, Rational(1, 4))), Q.real(x) & Q.negative(x)) is False + + +def test_integer(): + assert ask(Q.integer(x)) is None + assert ask(Q.integer(x), Q.integer(x)) is True + assert ask(Q.integer(x), ~Q.integer(x)) is False + assert ask(Q.integer(x), ~Q.real(x)) is False + assert ask(Q.integer(x), ~Q.positive(x)) is None + assert ask(Q.integer(x), Q.even(x) | Q.odd(x)) is True + + assert ask(Q.integer(2*x), Q.integer(x)) is True + assert ask(Q.integer(2*x), Q.even(x)) is True + assert ask(Q.integer(2*x), Q.prime(x)) is True + assert ask(Q.integer(2*x), Q.rational(x)) is None + assert ask(Q.integer(2*x), Q.real(x)) is None + assert ask(Q.integer(sqrt(2)*x), Q.integer(x)) is False + assert ask(Q.integer(sqrt(2)*x), Q.irrational(x)) is None + + assert ask(Q.integer(x/2), Q.odd(x)) is False + assert ask(Q.integer(x/2), Q.even(x)) is True + assert ask(Q.integer(x/3), Q.odd(x)) is None + assert ask(Q.integer(x/3), Q.even(x)) is None + + # https://github.com/sympy/sympy/issues/7286 + assert ask(Q.integer(Abs(x)),Q.integer(x)) is True + assert ask(Q.integer(Abs(-x)),Q.integer(x)) is True + assert ask(Q.integer(Abs(x)), ~Q.integer(x)) is None + assert ask(Q.integer(Abs(x)),Q.complex(x)) is None + assert ask(Q.integer(Abs(x+I*y)),Q.real(x) & Q.real(y)) is None + + # https://github.com/sympy/sympy/issues/27739 + assert ask(Q.integer(x/y), Q.integer(x) & Q.integer(y)) is None + assert ask(Q.integer(1/x), Q.integer(x)) is None + assert ask(Q.integer(x**y), Q.integer(x) & Q.integer(y)) is None + assert ask(Q.integer(sqrt(5))) is False + assert ask(Q.integer(x**y), Q.nonzero(x) & Q.zero(y)) is True + assert ask(Q.integer(x**y), Q.integer(x) & Q.integer(y) & Q.positive(y)) is True + assert ask(Q.integer(-1**x), Q.integer(x)) is True + assert ask(Q.integer(x**y), Q.integer(x) & Q.integer(y) & Q.positive(y)) is True + assert ask(Q.integer(x**y), Q.zero(x) & Q.integer(y) & Q.positive(y)) is True + assert ask(Q.integer(pi**x), Q.zero(x)) is True + assert ask(Q.integer(x**y), Q.imaginary(x) & Q.zero(y)) is True + + +def test_negative(): + assert ask(Q.negative(x), Q.negative(x)) is True + assert ask(Q.negative(x), Q.positive(x)) is False + assert ask(Q.negative(x), ~Q.real(x)) is False + assert ask(Q.negative(x), Q.prime(x)) is False + assert ask(Q.negative(x), ~Q.prime(x)) is None + + assert ask(Q.negative(-x), Q.positive(x)) is True + assert ask(Q.negative(-x), ~Q.positive(x)) is None + assert ask(Q.negative(-x), Q.negative(x)) is False + assert ask(Q.negative(-x), Q.positive(x)) is True + + assert ask(Q.negative(x - 1), Q.negative(x)) is True + assert ask(Q.negative(x + y)) is None + assert ask(Q.negative(x + y), Q.negative(x)) is None + assert ask(Q.negative(x + y), Q.negative(x) & Q.negative(y)) is True + assert ask(Q.negative(x + y), Q.negative(x) & Q.nonpositive(y)) is True + assert ask(Q.negative(2 + I)) is False + # although this could be False, it is representative of expressions + # that don't evaluate to a zero with precision + assert ask(Q.negative(cos(I)**2 + sin(I)**2 - 1)) is None + assert ask(Q.negative(-I + I*(cos(2)**2 + sin(2)**2))) is None + + assert ask(Q.negative(x**2)) is None + assert ask(Q.negative(x**2), Q.real(x)) is False + assert ask(Q.negative(x**1.4), Q.real(x)) is None + + assert ask(Q.negative(x**I), Q.positive(x)) is None + + assert ask(Q.negative(x*y)) is None + assert ask(Q.negative(x*y), Q.positive(x) & Q.positive(y)) is False + assert ask(Q.negative(x*y), Q.positive(x) & Q.negative(y)) is True + assert ask(Q.negative(x*y), Q.complex(x) & Q.complex(y)) is None + + assert ask(Q.negative(x**y)) is None + assert ask(Q.negative(x**y), Q.negative(x) & Q.even(y)) is False + assert ask(Q.negative(x**y), Q.negative(x) & Q.odd(y)) is True + assert ask(Q.negative(x**y), Q.positive(x) & Q.integer(y)) is False + + assert ask(Q.negative(Abs(x))) is False + + +def test_nonzero(): + assert ask(Q.nonzero(x)) is None + assert ask(Q.nonzero(x), Q.real(x)) is None + assert ask(Q.nonzero(x), Q.positive(x)) is True + assert ask(Q.nonzero(x), Q.negative(x)) is True + assert ask(Q.nonzero(x), Q.negative(x) | Q.positive(x)) is True + + assert ask(Q.nonzero(x + y)) is None + assert ask(Q.nonzero(x + y), Q.positive(x) & Q.positive(y)) is True + assert ask(Q.nonzero(x + y), Q.positive(x) & Q.negative(y)) is None + assert ask(Q.nonzero(x + y), Q.negative(x) & Q.negative(y)) is True + + assert ask(Q.nonzero(2*x)) is None + assert ask(Q.nonzero(2*x), Q.positive(x)) is True + assert ask(Q.nonzero(2*x), Q.negative(x)) is True + assert ask(Q.nonzero(x*y), Q.nonzero(x)) is None + assert ask(Q.nonzero(x*y), Q.nonzero(x) & Q.nonzero(y)) is True + + assert ask(Q.nonzero(x**y), Q.nonzero(x)) is True + + assert ask(Q.nonzero(Abs(x))) is None + assert ask(Q.nonzero(Abs(x)), Q.nonzero(x)) is True + + assert ask(Q.nonzero(log(exp(2*I)))) is False + # although this could be False, it is representative of expressions + # that don't evaluate to a zero with precision + assert ask(Q.nonzero(cos(1)**2 + sin(1)**2 - 1)) is None + + +def test_zero(): + assert ask(Q.zero(x)) is None + assert ask(Q.zero(x), Q.real(x)) is None + assert ask(Q.zero(x), Q.positive(x)) is False + assert ask(Q.zero(x), Q.negative(x)) is False + assert ask(Q.zero(x), Q.negative(x) | Q.positive(x)) is False + + assert ask(Q.zero(x), Q.nonnegative(x) & Q.nonpositive(x)) is True + + assert ask(Q.zero(x + y)) is None + assert ask(Q.zero(x + y), Q.positive(x) & Q.positive(y)) is False + assert ask(Q.zero(x + y), Q.positive(x) & Q.negative(y)) is None + assert ask(Q.zero(x + y), Q.negative(x) & Q.negative(y)) is False + + assert ask(Q.zero(2*x)) is None + assert ask(Q.zero(2*x), Q.positive(x)) is False + assert ask(Q.zero(2*x), Q.negative(x)) is False + assert ask(Q.zero(x*y), Q.nonzero(x)) is None + + assert ask(Q.zero(Abs(x))) is None + assert ask(Q.zero(Abs(x)), Q.zero(x)) is True + + assert ask(Q.integer(x), Q.zero(x)) is True + assert ask(Q.even(x), Q.zero(x)) is True + assert ask(Q.odd(x), Q.zero(x)) is False + assert ask(Q.zero(x), Q.even(x)) is None + assert ask(Q.zero(x), Q.odd(x)) is False + assert ask(Q.zero(x) | Q.zero(y), Q.zero(x*y)) is True + + +def test_odd_query(): + assert ask(Q.odd(x)) is None + assert ask(Q.odd(x), Q.odd(x)) is True + assert ask(Q.odd(x), Q.integer(x)) is None + assert ask(Q.odd(x), ~Q.integer(x)) is False + assert ask(Q.odd(x), Q.rational(x)) is None + assert ask(Q.odd(x), Q.positive(x)) is None + + assert ask(Q.odd(-x), Q.odd(x)) is True + + assert ask(Q.odd(2*x)) is None + assert ask(Q.odd(2*x), Q.integer(x)) is False + assert ask(Q.odd(2*x), Q.odd(x)) is False + assert ask(Q.odd(2*x), Q.irrational(x)) is False + assert ask(Q.odd(2*x), ~Q.integer(x)) is None + assert ask(Q.odd(3*x), Q.integer(x)) is None + + assert ask(Q.odd(x/3), Q.odd(x)) is None + assert ask(Q.odd(x/3), Q.even(x)) is None + + assert ask(Q.odd(x + 1), Q.even(x)) is True + assert ask(Q.odd(x + 2), Q.even(x)) is False + assert ask(Q.odd(x + 2), Q.odd(x)) is True + assert ask(Q.odd(3 - x), Q.odd(x)) is False + assert ask(Q.odd(3 - x), Q.even(x)) is True + assert ask(Q.odd(3 + x), Q.odd(x)) is False + assert ask(Q.odd(3 + x), Q.even(x)) is True + assert ask(Q.odd(x + y), Q.odd(x) & Q.odd(y)) is False + assert ask(Q.odd(x + y), Q.odd(x) & Q.even(y)) is True + assert ask(Q.odd(x - y), Q.even(x) & Q.odd(y)) is True + assert ask(Q.odd(x - y), Q.odd(x) & Q.odd(y)) is False + + assert ask(Q.odd(x + y + z), Q.odd(x) & Q.odd(y) & Q.even(z)) is False + assert ask(Q.odd(x + y + z + t), + Q.odd(x) & Q.odd(y) & Q.even(z) & Q.integer(t)) is None + + assert ask(Q.odd(2*x + 1), Q.integer(x)) is True + assert ask(Q.odd(2*x + y), Q.integer(x) & Q.odd(y)) is True + assert ask(Q.odd(2*x + y), Q.integer(x) & Q.even(y)) is False + assert ask(Q.odd(2*x + y), Q.integer(x) & Q.integer(y)) is None + assert ask(Q.odd(x*y), Q.odd(x) & Q.even(y)) is False + assert ask(Q.odd(x*y), Q.odd(x) & Q.odd(y)) is True + assert ask(Q.odd(2*x*y), Q.rational(x) & Q.rational(x)) is None + assert ask(Q.odd(2*x*y), Q.irrational(x) & Q.irrational(x)) is None + + assert ask(Q.odd(Abs(x)), Q.odd(x)) is True + + assert ask(Q.odd((-1)**n), Q.integer(n)) is True + + assert ask(Q.odd(k**2), Q.even(k)) is False + assert ask(Q.odd(n**2), Q.odd(n)) is True + assert ask(Q.odd(3**k), Q.even(k)) is None + + assert ask(Q.odd(k**m), Q.even(k) & Q.integer(m) & ~Q.negative(m)) is None + assert ask(Q.odd(n**m), Q.odd(n) & Q.integer(m) & ~Q.negative(m)) is True + + assert ask(Q.odd(k**p), Q.even(k) & Q.integer(p) & Q.positive(p)) is False + assert ask(Q.odd(n**p), Q.odd(n) & Q.integer(p) & Q.positive(p)) is True + + assert ask(Q.odd(m**k), Q.even(k) & Q.integer(m) & ~Q.negative(m)) is None + assert ask(Q.odd(p**k), Q.even(k) & Q.integer(p) & Q.positive(p)) is None + + assert ask(Q.odd(m**n), Q.odd(n) & Q.integer(m) & ~Q.negative(m)) is None + assert ask(Q.odd(p**n), Q.odd(n) & Q.integer(p) & Q.positive(p)) is None + + assert ask(Q.odd(k**x), Q.even(k)) is None + assert ask(Q.odd(n**x), Q.odd(n)) is None + + assert ask(Q.odd(x*y), Q.integer(x) & Q.integer(y)) is None + assert ask(Q.odd(x*x), Q.integer(x)) is None + assert ask(Q.odd(x*(x + y)), Q.integer(x) & Q.odd(y)) is False + assert ask(Q.odd(x*(x + y)), Q.integer(x) & Q.even(y)) is None + + +@XFAIL +def test_oddness_in_ternary_integer_product_with_odd(): + # Tests that oddness inference is independent of term ordering. + # Term ordering at the point of testing depends on SymPy's symbol order, so + # we try to force a different order by modifying symbol names. + assert ask(Q.odd(x*y*(y + z)), Q.integer(x) & Q.integer(y) & Q.odd(z)) is False + assert ask(Q.odd(y*x*(x + z)), Q.integer(x) & Q.integer(y) & Q.odd(z)) is False + + +def test_oddness_in_ternary_integer_product_with_even(): + assert ask(Q.odd(x*y*(y + z)), Q.integer(x) & Q.integer(y) & Q.even(z)) is None + + +def test_prime(): + assert ask(Q.prime(x), Q.prime(x)) is True + assert ask(Q.prime(x), ~Q.prime(x)) is False + assert ask(Q.prime(x), Q.integer(x)) is None + assert ask(Q.prime(x), ~Q.integer(x)) is False + + assert ask(Q.prime(2*x), Q.integer(x)) is None + assert ask(Q.prime(x*y)) is None + assert ask(Q.prime(x*y), Q.prime(x)) is None + assert ask(Q.prime(x*y), Q.integer(x) & Q.integer(y)) is None + assert ask(Q.prime(4*x), Q.integer(x)) is False + assert ask(Q.prime(4*x)) is None + + assert ask(Q.prime(x**2), Q.integer(x)) is False + assert ask(Q.prime(x**2), Q.prime(x)) is False + + # https://github.com/sympy/sympy/issues/27446 + assert ask(Q.prime(4**x), Q.integer(x)) is False + assert ask(Q.prime(p**x), Q.prime(p) & Q.integer(x) & Q.ne(x, 1)) is False + assert ask(Q.prime(n**x), Q.integer(x) & Q.composite(n)) is False + assert ask(Q.prime(x**y), Q.integer(x) & Q.integer(y)) is None + assert ask(Q.prime(2**x), Q.integer(x)) is None + assert ask(Q.prime(p**x), Q.prime(p) & Q.integer(x)) is None + + # Ideally, these should return True since the base is prime and the exponent is one, + # but currently, they return None. + assert ask(Q.prime(x**y), Q.prime(x) & Q.eq(y,1)) is None + assert ask(Q.prime(x**y), Q.prime(x) & Q.integer(y) & Q.gt(y,0) & Q.lt(y,2)) is None + + assert ask(Q.prime(Pow(x,1, evaluate=False)), Q.prime(x)) is True + + +@_both_exp_pow +def test_positive(): + assert ask(Q.positive(cos(I) ** 2 + sin(I) ** 2 - 1)) is None + assert ask(Q.positive(x), Q.positive(x)) is True + assert ask(Q.positive(x), Q.negative(x)) is False + assert ask(Q.positive(x), Q.nonzero(x)) is None + + assert ask(Q.positive(-x), Q.positive(x)) is False + assert ask(Q.positive(-x), Q.negative(x)) is True + + assert ask(Q.positive(x + y), Q.positive(x) & Q.positive(y)) is True + assert ask(Q.positive(x + y), Q.positive(x) & Q.nonnegative(y)) is True + assert ask(Q.positive(x + y), Q.positive(x) & Q.negative(y)) is None + assert ask(Q.positive(x + y), Q.positive(x) & Q.imaginary(y)) is False + + assert ask(Q.positive(2*x), Q.positive(x)) is True + assumptions = Q.positive(x) & Q.negative(y) & Q.negative(z) & Q.positive(w) + assert ask(Q.positive(x*y*z)) is None + assert ask(Q.positive(x*y*z), assumptions) is True + assert ask(Q.positive(-x*y*z), assumptions) is False + + assert ask(Q.positive(x**I), Q.positive(x)) is None + + assert ask(Q.positive(x**2), Q.positive(x)) is True + assert ask(Q.positive(x**2), Q.negative(x)) is True + assert ask(Q.positive(x**3), Q.negative(x)) is False + assert ask(Q.positive(1/(1 + x**2)), Q.real(x)) is True + assert ask(Q.positive(2**I)) is False + assert ask(Q.positive(2 + I)) is False + # although this could be False, it is representative of expressions + # that don't evaluate to a zero with precision + assert ask(Q.positive(cos(I)**2 + sin(I)**2 - 1)) is None + assert ask(Q.positive(-I + I*(cos(2)**2 + sin(2)**2))) is None + + #exponential + assert ask(Q.positive(exp(x)), Q.real(x)) is True + assert ask(~Q.negative(exp(x)), Q.real(x)) is True + assert ask(Q.positive(x + exp(x)), Q.real(x)) is None + assert ask(Q.positive(exp(x)), Q.imaginary(x)) is None + assert ask(Q.positive(exp(2*pi*I, evaluate=False)), Q.imaginary(x)) is True + assert ask(Q.negative(exp(pi*I, evaluate=False)), Q.imaginary(x)) is True + assert ask(Q.positive(exp(x*pi*I)), Q.even(x)) is True + assert ask(Q.positive(exp(x*pi*I)), Q.odd(x)) is False + assert ask(Q.positive(exp(x*pi*I)), Q.real(x)) is None + + # logarithm + assert ask(Q.positive(log(x)), Q.imaginary(x)) is False + assert ask(Q.positive(log(x)), Q.negative(x)) is False + assert ask(Q.positive(log(x)), Q.positive(x)) is None + assert ask(Q.positive(log(x + 2)), Q.positive(x)) is True + + # factorial + assert ask(Q.positive(factorial(x)), Q.integer(x) & Q.positive(x)) + assert ask(Q.positive(factorial(x)), Q.integer(x)) is None + + #absolute value + assert ask(Q.positive(Abs(x))) is None # Abs(0) = 0 + assert ask(Q.positive(Abs(x)), Q.positive(x)) is True + + +def test_nonpositive(): + assert ask(Q.nonpositive(-1)) + assert ask(Q.nonpositive(0)) + assert ask(Q.nonpositive(1)) is False + assert ask(~Q.positive(x), Q.nonpositive(x)) + assert ask(Q.nonpositive(x), Q.positive(x)) is False + assert ask(Q.nonpositive(sqrt(-1))) is False + assert ask(Q.nonpositive(x), Q.imaginary(x)) is False + + +def test_nonnegative(): + assert ask(Q.nonnegative(-1)) is False + assert ask(Q.nonnegative(0)) + assert ask(Q.nonnegative(1)) + assert ask(~Q.negative(x), Q.nonnegative(x)) + assert ask(Q.nonnegative(x), Q.negative(x)) is False + assert ask(Q.nonnegative(sqrt(-1))) is False + assert ask(Q.nonnegative(x), Q.imaginary(x)) is False + +def test_real_basic(): + assert ask(Q.real(x)) is None + assert ask(Q.real(x), Q.real(x)) is True + assert ask(Q.real(x), Q.nonzero(x)) is True + assert ask(Q.real(x), Q.positive(x)) is True + assert ask(Q.real(x), Q.negative(x)) is True + assert ask(Q.real(x), Q.integer(x)) is True + assert ask(Q.real(x), Q.even(x)) is True + assert ask(Q.real(x), Q.prime(x)) is True + + assert ask(Q.real(x/sqrt(2)), Q.real(x)) is True + assert ask(Q.real(x/sqrt(-2)), Q.real(x)) is False + + assert ask(Q.real(x + 1), Q.real(x)) is True + assert ask(Q.real(x + I), Q.real(x)) is False + assert ask(Q.real(x + I), Q.complex(x)) is None + + assert ask(Q.real(2*x), Q.real(x)) is True + assert ask(Q.real(I*x), Q.real(x)) is False + assert ask(Q.real(I*x), Q.imaginary(x)) is True + assert ask(Q.real(I*x), Q.complex(x)) is None + + +def test_real_pow(): + assert ask(Q.real(x**2), Q.real(x)) is True + assert ask(Q.real(sqrt(x)), Q.negative(x)) is False + assert ask(Q.real(x**y), Q.real(x) & Q.integer(y)) is None + assert ask(Q.real(x**y), Q.real(x) & Q.real(y)) is None + assert ask(Q.real(x**y), Q.positive(x) & Q.real(y)) is True + assert ask(Q.real(x**y), Q.imaginary(x) & Q.imaginary(y)) is None # I**I or (2*I)**I + assert ask(Q.real(x**y), Q.imaginary(x) & Q.real(y)) is None # I**1 or I**0 + assert ask(Q.real(x**y), Q.real(x) & Q.imaginary(y)) is None # could be exp(2*pi*I) or 2**I + assert ask(Q.real(x**0), Q.imaginary(x)) is True + assert ask(Q.real(x**y), Q.positive(x) & Q.real(y)) is True + assert ask(Q.real(x**y), Q.real(x) & Q.rational(y)) is None + assert ask(Q.real(x**y), Q.imaginary(x) & Q.integer(y)) is None + assert ask(Q.real(x**y), Q.imaginary(x) & Q.odd(y)) is False + assert ask(Q.real(x**y), Q.imaginary(x) & Q.even(y)) is True + assert ask(Q.real(x**(y/z)), Q.real(x) & Q.real(y/z) & Q.rational(y/z) & Q.even(z) & Q.positive(x)) is True + assert ask(Q.real(x**(y/z)), Q.real(x) & Q.rational(y/z) & Q.even(z) & Q.negative(x)) is None + assert ask(Q.real(x**(y/z)), Q.real(x) & Q.integer(y/z)) is None + assert ask(Q.real(x**(y/z)), Q.real(x) & Q.real(y/z) & Q.positive(x)) is True + assert ask(Q.real(x**(y/z)), Q.real(x) & Q.real(y/z) & Q.negative(x)) is None + assert ask(Q.real((-I)**i), Q.imaginary(i)) is True + assert ask(Q.real(I**i), Q.imaginary(i)) is True + assert ask(Q.real(i**i), Q.imaginary(i)) is None # i might be 2*I + assert ask(Q.real(x**i), Q.imaginary(i)) is None # x could be 0 + assert ask(Q.real(x**(I*pi/log(x))), Q.real(x)) is True + + # https://github.com/sympy/sympy/issues/27485 + assert ask(Q.real(n**p), Q.negative(n) & Q.positive(p)) is None + + # https://github.com/sympy/sympy/issues/16530 + assert ask(Q.real(1/Abs(x))) is None + assert ask(Q.real(x**y), Q.zero(x) & Q.real(y)) is None + assert ask(Q.real(x**y), Q.zero(x) & Q.positive(y)) is True + + +@_both_exp_pow +def test_real_functions(): + # trigonometric functions + assert ask(Q.real(sin(x))) is None + assert ask(Q.real(cos(x))) is None + assert ask(Q.real(sin(x)), Q.real(x)) is True + assert ask(Q.real(cos(x)), Q.real(x)) is True + + # exponential function + assert ask(Q.real(exp(x))) is None + assert ask(Q.real(exp(x)), Q.real(x)) is True + assert ask(Q.real(x + exp(x)), Q.real(x)) is True + assert ask(Q.real(exp(2*pi*I, evaluate=False))) is True + assert ask(Q.real(exp(pi*I, evaluate=False))) is True + assert ask(Q.real(exp(pi*I/2, evaluate=False))) is False + + # logarithm + assert ask(Q.real(log(I))) is False + assert ask(Q.real(log(2*I))) is False + assert ask(Q.real(log(I + 1))) is False + assert ask(Q.real(log(x)), Q.complex(x)) is None + assert ask(Q.real(log(x)), Q.imaginary(x)) is False + assert ask(Q.real(log(exp(x))), Q.imaginary(x)) is None # exp(2*pi*I) is 1, log(exp(pi*I)) is pi*I (disregarding periodicity) + assert ask(Q.real(log(exp(x))), Q.complex(x)) is None + eq = Pow(exp(2*pi*I*x, evaluate=False), x, evaluate=False) + assert ask(Q.real(eq), Q.integer(x)) is True + assert ask(Q.real(exp(x)**x), Q.imaginary(x)) is True + assert ask(Q.real(exp(x)**x), Q.complex(x)) is None + + # Q.complexes + assert ask(Q.real(re(x))) is True + assert ask(Q.real(im(x))) is True + + +def test_matrix(): + + # hermitian + assert ask(Q.hermitian(Matrix([[2, 2 + I, 4], [2 - I, 3, I], [4, -I, 1]]))) == True + assert ask(Q.hermitian(Matrix([[2, 2 + I, 4], [2 + I, 3, I], [4, -I, 1]]))) == False + z = symbols('z', complex=True) + assert ask(Q.hermitian(Matrix([[2, 2 + I, z], [2 - I, 3, I], [4, -I, 1]]))) == None + assert ask(Q.hermitian(SparseMatrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11))))) == True + assert ask(Q.hermitian(SparseMatrix(((25, 15, -5), (15, I, 0), (-5, 0, 11))))) == False + assert ask(Q.hermitian(SparseMatrix(((25, 15, -5), (15, z, 0), (-5, 0, 11))))) == None + + # antihermitian + A = Matrix([[0, -2 - I, 0], [2 - I, 0, -I], [0, -I, 0]]) + B = Matrix([[-I, 2 + I, 0], [-2 + I, 0, 2 + I], [0, -2 + I, -I]]) + assert ask(Q.antihermitian(A)) is True + assert ask(Q.antihermitian(B)) is True + assert ask(Q.antihermitian(A**2)) is False + C = (B**3) + C.simplify() + assert ask(Q.antihermitian(C)) is True + _A = Matrix([[0, -2 - I, 0], [z, 0, -I], [0, -I, 0]]) + assert ask(Q.antihermitian(_A)) is None + + +@_both_exp_pow +def test_algebraic(): + assert ask(Q.algebraic(x)) is None + + assert ask(Q.algebraic(I)) is True + assert ask(Q.algebraic(2*I)) is True + assert ask(Q.algebraic(I/3)) is True + + assert ask(Q.algebraic(sqrt(7))) is True + assert ask(Q.algebraic(2*sqrt(7))) is True + assert ask(Q.algebraic(sqrt(7)/3)) is True + + assert ask(Q.algebraic(I*sqrt(3))) is True + assert ask(Q.algebraic(sqrt(1 + I*sqrt(3)))) is True + + assert ask(Q.algebraic(1 + I*sqrt(3)**Rational(17, 31))) is True + assert ask(Q.algebraic(1 + I*sqrt(3)**(17/pi))) is None + + for f in [exp, sin, tan, asin, atan, cos]: + assert ask(Q.algebraic(f(7))) is False + assert ask(Q.algebraic(f(7, evaluate=False))) is False + assert ask(Q.algebraic(f(0, evaluate=False))) is True + assert ask(Q.algebraic(f(x)), Q.algebraic(x)) is None + assert ask(Q.algebraic(f(x)), Q.algebraic(x) & Q.nonzero(x)) is False + + for g in [log, acos]: + assert ask(Q.algebraic(g(7))) is False + assert ask(Q.algebraic(g(7, evaluate=False))) is False + assert ask(Q.algebraic(g(1, evaluate=False))) is True + assert ask(Q.algebraic(g(x)), Q.algebraic(x)) is None + assert ask(Q.algebraic(g(x)), Q.algebraic(x) & Q.nonzero(x - 1)) is False + + for h in [cot, acot]: + assert ask(Q.algebraic(h(7))) is False + assert ask(Q.algebraic(h(7, evaluate=False))) is False + assert ask(Q.algebraic(h(x)), Q.algebraic(x)) is False + + assert ask(Q.algebraic(sqrt(sin(7)))) is None + assert ask(Q.algebraic(sqrt(y + I*sqrt(7)))) is None + + assert ask(Q.algebraic(2.47)) is True + + assert ask(Q.algebraic(x), Q.transcendental(x)) is False + assert ask(Q.transcendental(x), Q.algebraic(x)) is False + + #https://github.com/sympy/sympy/issues/27445 + assert ask(Q.algebraic(Pow(1, x, evaluate=False)), Q.algebraic(x)) is None + assert ask(Q.algebraic(Pow(x, y))) is None + assert ask(Q.algebraic(Pow(1, x, evaluate=False))) is None + assert ask(Q.algebraic(x**(pi*I))) is None + assert ask(Q.algebraic(pi**n),Q.integer(n) & Q.positive(n)) is False + assert ask(Q.algebraic(x**y),Q.algebraic(x) & Q.rational(y)) is True + + +def test_global(): + """Test ask with global assumptions""" + assert ask(Q.integer(x)) is None + global_assumptions.add(Q.integer(x)) + assert ask(Q.integer(x)) is True + global_assumptions.clear() + assert ask(Q.integer(x)) is None + + +def test_custom_context(): + """Test ask with custom assumptions context""" + assert ask(Q.integer(x)) is None + local_context = AssumptionsContext() + local_context.add(Q.integer(x)) + assert ask(Q.integer(x), context=local_context) is True + assert ask(Q.integer(x)) is None + + +def test_functions_in_assumptions(): + assert ask(Q.negative(x), Q.real(x) >> Q.positive(x)) is False + assert ask(Q.negative(x), Equivalent(Q.real(x), Q.positive(x))) is False + assert ask(Q.negative(x), Xor(Q.real(x), Q.negative(x))) is False + + +def test_composite_ask(): + assert ask(Q.negative(x) & Q.integer(x), + assumptions=Q.real(x) >> Q.positive(x)) is False + + +def test_composite_proposition(): + assert ask(True) is True + assert ask(False) is False + assert ask(~Q.negative(x), Q.positive(x)) is True + assert ask(~Q.real(x), Q.commutative(x)) is None + assert ask(Q.negative(x) & Q.integer(x), Q.positive(x)) is False + assert ask(Q.negative(x) & Q.integer(x)) is None + assert ask(Q.real(x) | Q.integer(x), Q.positive(x)) is True + assert ask(Q.real(x) | Q.integer(x)) is None + assert ask(Q.real(x) >> Q.positive(x), Q.negative(x)) is False + assert ask(Implies( + Q.real(x), Q.positive(x), evaluate=False), Q.negative(x)) is False + assert ask(Implies(Q.real(x), Q.positive(x), evaluate=False)) is None + assert ask(Equivalent(Q.integer(x), Q.even(x)), Q.even(x)) is True + assert ask(Equivalent(Q.integer(x), Q.even(x))) is None + assert ask(Equivalent(Q.positive(x), Q.integer(x)), Q.integer(x)) is None + assert ask(Q.real(x) | Q.integer(x), Q.real(x) | Q.integer(x)) is True + +def test_tautology(): + assert ask(Q.real(x) | ~Q.real(x)) is True + assert ask(Q.real(x) & ~Q.real(x)) is False + +def test_composite_assumptions(): + assert ask(Q.real(x), Q.real(x) & Q.real(y)) is True + assert ask(Q.positive(x), Q.positive(x) | Q.positive(y)) is None + assert ask(Q.positive(x), Q.real(x) >> Q.positive(y)) is None + assert ask(Q.real(x), ~(Q.real(x) >> Q.real(y))) is True + +def test_key_extensibility(): + """test that you can add keys to the ask system at runtime""" + # make sure the key is not defined + raises(AttributeError, lambda: ask(Q.my_key(x))) + + # Old handler system + class MyAskHandler(AskHandler): + @staticmethod + def Symbol(expr, assumptions): + return True + try: + with warns_deprecated_sympy(): + register_handler('my_key', MyAskHandler) + with warns_deprecated_sympy(): + assert ask(Q.my_key(x)) is True + with warns_deprecated_sympy(): + assert ask(Q.my_key(x + 1)) is None + finally: + # We have to disable the stacklevel testing here because this raises + # the warning twice from two different places + with warns_deprecated_sympy(): + remove_handler('my_key', MyAskHandler) + del Q.my_key + raises(AttributeError, lambda: ask(Q.my_key(x))) + + # New handler system + class MyPredicate(Predicate): + pass + try: + Q.my_key = MyPredicate() + @Q.my_key.register(Symbol) + def _(expr, assumptions): + return True + assert ask(Q.my_key(x)) is True + assert ask(Q.my_key(x+1)) is None + finally: + del Q.my_key + raises(AttributeError, lambda: ask(Q.my_key(x))) + + +def test_type_extensibility(): + """test that new types can be added to the ask system at runtime + """ + from sympy.core import Basic + + class MyType(Basic): + pass + + @Q.prime.register(MyType) + def _(expr, assumptions): + return True + + assert ask(Q.prime(MyType())) is True + + +def test_single_fact_lookup(): + known_facts = And(Implies(Q.integer, Q.rational), + Implies(Q.rational, Q.real), + Implies(Q.real, Q.complex)) + known_facts_keys = {Q.integer, Q.rational, Q.real, Q.complex} + + known_facts_cnf = to_cnf(known_facts) + mapping = single_fact_lookup(known_facts_keys, known_facts_cnf) + + assert mapping[Q.rational] == {Q.real, Q.rational, Q.complex} + + +def test_generate_known_facts_dict(): + known_facts = And(Implies(Q.integer(x), Q.rational(x)), + Implies(Q.rational(x), Q.real(x)), + Implies(Q.real(x), Q.complex(x))) + known_facts_keys = {Q.integer(x), Q.rational(x), Q.real(x), Q.complex(x)} + + assert generate_known_facts_dict(known_facts_keys, known_facts) == \ + {Q.complex: ({Q.complex}, set()), + Q.integer: ({Q.complex, Q.integer, Q.rational, Q.real}, set()), + Q.rational: ({Q.complex, Q.rational, Q.real}, set()), + Q.real: ({Q.complex, Q.real}, set())} + + +@slow +def test_known_facts_consistent(): + """"Test that ask_generated.py is up-to-date""" + x = Symbol('x') + fact = get_known_facts(x) + # test cnf clauses of fact between unary predicates + cnf = CNF.to_CNF(fact) + clauses = set() + clauses.update(frozenset(Literal(lit.arg.function, lit.is_Not) for lit in sorted(cl, key=str)) for cl in cnf.clauses) + assert get_all_known_facts() == clauses + # test dictionary of fact between unary predicates + keys = [pred(x) for pred in get_known_facts_keys()] + mapping = generate_known_facts_dict(keys, fact) + assert get_known_facts_dict() == mapping + + +def test_Add_queries(): + assert ask(Q.prime(12345678901234567890 + (cos(1)**2 + sin(1)**2))) is True + assert ask(Q.even(Add(S(2), S(2), evaluate=False))) is True + assert ask(Q.prime(Add(S(2), S(2), evaluate=False))) is False + assert ask(Q.integer(Add(S(2), S(2), evaluate=False))) is True + + +def test_positive_assuming(): + with assuming(Q.positive(x + 1)): + assert not ask(Q.positive(x)) + + +def test_issue_5421(): + raises(TypeError, lambda: ask(pi/log(x), Q.real)) + + +def test_issue_3906(): + raises(TypeError, lambda: ask(Q.positive)) + + +def test_issue_5833(): + assert ask(Q.positive(log(x)**2), Q.positive(x)) is None + assert ask(~Q.negative(log(x)**2), Q.positive(x)) is True + + +def test_issue_6732(): + raises(ValueError, lambda: ask(Q.positive(x), Q.positive(x) & Q.negative(x))) + raises(ValueError, lambda: ask(Q.negative(x), Q.positive(x) & Q.negative(x))) + + +def test_issue_7246(): + assert ask(Q.positive(atan(p)), Q.positive(p)) is True + assert ask(Q.positive(atan(p)), Q.negative(p)) is False + assert ask(Q.positive(atan(p)), Q.zero(p)) is False + assert ask(Q.positive(atan(x))) is None + + assert ask(Q.positive(asin(p)), Q.positive(p)) is None + assert ask(Q.positive(asin(p)), Q.zero(p)) is None + assert ask(Q.positive(asin(Rational(1, 7)))) is True + assert ask(Q.positive(asin(x)), Q.positive(x) & Q.nonpositive(x - 1)) is True + assert ask(Q.positive(asin(x)), Q.negative(x) & Q.nonnegative(x + 1)) is False + + assert ask(Q.positive(acos(p)), Q.positive(p)) is None + assert ask(Q.positive(acos(Rational(1, 7)))) is True + assert ask(Q.positive(acos(x)), Q.nonnegative(x + 1) & Q.nonpositive(x - 1)) is True + assert ask(Q.positive(acos(x)), Q.nonnegative(x - 1)) is None + + assert ask(Q.positive(acot(x)), Q.positive(x)) is True + assert ask(Q.positive(acot(x)), Q.real(x)) is True + assert ask(Q.positive(acot(x)), Q.imaginary(x)) is False + assert ask(Q.positive(acot(x))) is None + + +@XFAIL +def test_issue_7246_failing(): + #Move this test to test_issue_7246 once + #the new assumptions module is improved. + assert ask(Q.positive(acos(x)), Q.zero(x)) is True + + +def test_check_old_assumption(): + x = symbols('x', real=True) + assert ask(Q.real(x)) is True + assert ask(Q.imaginary(x)) is False + assert ask(Q.complex(x)) is True + + x = symbols('x', imaginary=True) + assert ask(Q.real(x)) is False + assert ask(Q.imaginary(x)) is True + assert ask(Q.complex(x)) is True + + x = symbols('x', complex=True) + assert ask(Q.real(x)) is None + assert ask(Q.complex(x)) is True + + x = symbols('x', positive=True) + assert ask(Q.positive(x)) is True + assert ask(Q.negative(x)) is False + assert ask(Q.real(x)) is True + + x = symbols('x', commutative=False) + assert ask(Q.commutative(x)) is False + + x = symbols('x', negative=True) + assert ask(Q.positive(x)) is False + assert ask(Q.negative(x)) is True + + x = symbols('x', nonnegative=True) + assert ask(Q.negative(x)) is False + assert ask(Q.positive(x)) is None + assert ask(Q.zero(x)) is None + + x = symbols('x', finite=True) + assert ask(Q.finite(x)) is True + + x = symbols('x', prime=True) + assert ask(Q.prime(x)) is True + assert ask(Q.composite(x)) is False + + x = symbols('x', composite=True) + assert ask(Q.prime(x)) is False + assert ask(Q.composite(x)) is True + + x = symbols('x', even=True) + assert ask(Q.even(x)) is True + assert ask(Q.odd(x)) is False + + x = symbols('x', odd=True) + assert ask(Q.even(x)) is False + assert ask(Q.odd(x)) is True + + x = symbols('x', nonzero=True) + assert ask(Q.nonzero(x)) is True + assert ask(Q.zero(x)) is False + + x = symbols('x', zero=True) + assert ask(Q.zero(x)) is True + + x = symbols('x', integer=True) + assert ask(Q.integer(x)) is True + + x = symbols('x', rational=True) + assert ask(Q.rational(x)) is True + assert ask(Q.irrational(x)) is False + + x = symbols('x', irrational=True) + assert ask(Q.irrational(x)) is True + assert ask(Q.rational(x)) is False + + +def test_issue_9636(): + assert ask(Q.integer(1.0)) is None + assert ask(Q.prime(3.0)) is None + assert ask(Q.composite(4.0)) is None + assert ask(Q.even(2.0)) is None + assert ask(Q.odd(3.0)) is None + + +def test_autosimp_used_to_fail(): + # See issue #9807 + assert ask(Q.imaginary(0**I)) is None + assert ask(Q.imaginary(0**(-I))) is None + assert ask(Q.real(0**I)) is None + assert ask(Q.real(0**(-I))) is None + + +def test_custom_AskHandler(): + from sympy.logic.boolalg import conjuncts + + # Old handler system + class MersenneHandler(AskHandler): + @staticmethod + def Integer(expr, assumptions): + if ask(Q.integer(log(expr + 1, 2))): + return True + @staticmethod + def Symbol(expr, assumptions): + if expr in conjuncts(assumptions): + return True + try: + with warns_deprecated_sympy(): + register_handler('mersenne', MersenneHandler) + n = Symbol('n', integer=True) + with warns_deprecated_sympy(): + assert ask(Q.mersenne(7)) + with warns_deprecated_sympy(): + assert ask(Q.mersenne(n), Q.mersenne(n)) + finally: + del Q.mersenne + + # New handler system + class MersennePredicate(Predicate): + pass + try: + Q.mersenne = MersennePredicate() + @Q.mersenne.register(Integer) + def _(expr, assumptions): + if ask(Q.integer(log(expr + 1, 2))): + return True + @Q.mersenne.register(Symbol) + def _(expr, assumptions): + if expr in conjuncts(assumptions): + return True + assert ask(Q.mersenne(7)) + assert ask(Q.mersenne(n), Q.mersenne(n)) + finally: + del Q.mersenne + + +def test_polyadic_predicate(): + + class SexyPredicate(Predicate): + pass + try: + Q.sexyprime = SexyPredicate() + + @Q.sexyprime.register(Integer, Integer) + def _(int1, int2, assumptions): + args = sorted([int1, int2]) + if not all(ask(Q.prime(a), assumptions) for a in args): + return False + return args[1] - args[0] == 6 + + @Q.sexyprime.register(Integer, Integer, Integer) + def _(int1, int2, int3, assumptions): + args = sorted([int1, int2, int3]) + if not all(ask(Q.prime(a), assumptions) for a in args): + return False + return args[2] - args[1] == 6 and args[1] - args[0] == 6 + + assert ask(Q.sexyprime(5, 11)) + assert ask(Q.sexyprime(7, 13, 19)) + finally: + del Q.sexyprime + + +def test_Predicate_handler_is_unique(): + + # Undefined predicate does not have a handler + assert Predicate('mypredicate').handler is None + + # Handler of defined predicate is unique to the class + class MyPredicate(Predicate): + pass + mp1 = MyPredicate(Str('mp1')) + mp2 = MyPredicate(Str('mp2')) + assert mp1.handler is mp2.handler + + +def test_relational(): + assert ask(Q.eq(x, 0), Q.zero(x)) + assert not ask(Q.eq(x, 0), Q.nonzero(x)) + assert not ask(Q.ne(x, 0), Q.zero(x)) + assert ask(Q.ne(x, 0), Q.nonzero(x)) + + +def test_issue_25221(): + assert ask(Q.transcendental(x), Q.algebraic(x) | Q.positive(y,y)) is None + assert ask(Q.transcendental(x), Q.algebraic(x) | (0 > y)) is None + assert ask(Q.transcendental(x), Q.algebraic(x) | Q.gt(0,y)) is None + + +def test_issue_27440(): + nan = S.NaN + assert ask(Q.negative(nan)) is None diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/test_refine.py b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/test_refine.py new file mode 100644 index 0000000000000000000000000000000000000000..81533a88b232cd5c3cfb9be17d09dad404d679dc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/test_refine.py @@ -0,0 +1,227 @@ +from sympy.assumptions.ask import Q +from sympy.assumptions.refine import refine +from sympy.core.expr import Expr +from sympy.core.numbers import (I, Rational, nan, pi) +from sympy.core.singleton import S +from sympy.core.symbol import Symbol +from sympy.functions.elementary.complexes import (Abs, arg, im, re, sign) +from sympy.functions.elementary.exponential import exp +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import (atan, atan2) +from sympy.abc import w, x, y, z +from sympy.core.relational import Eq, Ne +from sympy.functions.elementary.piecewise import Piecewise +from sympy.matrices.expressions.matexpr import MatrixSymbol + + +def test_Abs(): + assert refine(Abs(x), Q.positive(x)) == x + assert refine(1 + Abs(x), Q.positive(x)) == 1 + x + assert refine(Abs(x), Q.negative(x)) == -x + assert refine(1 + Abs(x), Q.negative(x)) == 1 - x + + assert refine(Abs(x**2)) != x**2 + assert refine(Abs(x**2), Q.real(x)) == x**2 + + +def test_pow1(): + assert refine((-1)**x, Q.even(x)) == 1 + assert refine((-1)**x, Q.odd(x)) == -1 + assert refine((-2)**x, Q.even(x)) == 2**x + + # nested powers + assert refine(sqrt(x**2)) != Abs(x) + assert refine(sqrt(x**2), Q.complex(x)) != Abs(x) + assert refine(sqrt(x**2), Q.real(x)) == Abs(x) + assert refine(sqrt(x**2), Q.positive(x)) == x + assert refine((x**3)**Rational(1, 3)) != x + + assert refine((x**3)**Rational(1, 3), Q.real(x)) != x + assert refine((x**3)**Rational(1, 3), Q.positive(x)) == x + + assert refine(sqrt(1/x), Q.real(x)) != 1/sqrt(x) + assert refine(sqrt(1/x), Q.positive(x)) == 1/sqrt(x) + + # powers of (-1) + assert refine((-1)**(x + y), Q.even(x)) == (-1)**y + assert refine((-1)**(x + y + z), Q.odd(x) & Q.odd(z)) == (-1)**y + assert refine((-1)**(x + y + 1), Q.odd(x)) == (-1)**y + assert refine((-1)**(x + y + 2), Q.odd(x)) == (-1)**(y + 1) + assert refine((-1)**(x + 3)) == (-1)**(x + 1) + + # continuation + assert refine((-1)**((-1)**x/2 - S.Half), Q.integer(x)) == (-1)**x + assert refine((-1)**((-1)**x/2 + S.Half), Q.integer(x)) == (-1)**(x + 1) + assert refine((-1)**((-1)**x/2 + 5*S.Half), Q.integer(x)) == (-1)**(x + 1) + + +def test_pow2(): + assert refine((-1)**((-1)**x/2 - 7*S.Half), Q.integer(x)) == (-1)**(x + 1) + assert refine((-1)**((-1)**x/2 - 9*S.Half), Q.integer(x)) == (-1)**x + + # powers of Abs + assert refine(Abs(x)**2, Q.real(x)) == x**2 + assert refine(Abs(x)**3, Q.real(x)) == Abs(x)**3 + assert refine(Abs(x)**2) == Abs(x)**2 + + +def test_exp(): + x = Symbol('x', integer=True) + assert refine(exp(pi*I*2*x)) == 1 + assert refine(exp(pi*I*2*(x + S.Half))) == -1 + assert refine(exp(pi*I*2*(x + Rational(1, 4)))) == I + assert refine(exp(pi*I*2*(x + Rational(3, 4)))) == -I + + +def test_Piecewise(): + assert refine(Piecewise((1, x < 0), (3, True)), (x < 0)) == 1 + assert refine(Piecewise((1, x < 0), (3, True)), ~(x < 0)) == 3 + assert refine(Piecewise((1, x < 0), (3, True)), (y < 0)) == \ + Piecewise((1, x < 0), (3, True)) + assert refine(Piecewise((1, x > 0), (3, True)), (x > 0)) == 1 + assert refine(Piecewise((1, x > 0), (3, True)), ~(x > 0)) == 3 + assert refine(Piecewise((1, x > 0), (3, True)), (y > 0)) == \ + Piecewise((1, x > 0), (3, True)) + assert refine(Piecewise((1, x <= 0), (3, True)), (x <= 0)) == 1 + assert refine(Piecewise((1, x <= 0), (3, True)), ~(x <= 0)) == 3 + assert refine(Piecewise((1, x <= 0), (3, True)), (y <= 0)) == \ + Piecewise((1, x <= 0), (3, True)) + assert refine(Piecewise((1, x >= 0), (3, True)), (x >= 0)) == 1 + assert refine(Piecewise((1, x >= 0), (3, True)), ~(x >= 0)) == 3 + assert refine(Piecewise((1, x >= 0), (3, True)), (y >= 0)) == \ + Piecewise((1, x >= 0), (3, True)) + assert refine(Piecewise((1, Eq(x, 0)), (3, True)), (Eq(x, 0)))\ + == 1 + assert refine(Piecewise((1, Eq(x, 0)), (3, True)), (Eq(0, x)))\ + == 1 + assert refine(Piecewise((1, Eq(x, 0)), (3, True)), ~(Eq(x, 0)))\ + == 3 + assert refine(Piecewise((1, Eq(x, 0)), (3, True)), ~(Eq(0, x)))\ + == 3 + assert refine(Piecewise((1, Eq(x, 0)), (3, True)), (Eq(y, 0)))\ + == Piecewise((1, Eq(x, 0)), (3, True)) + assert refine(Piecewise((1, Ne(x, 0)), (3, True)), (Ne(x, 0)))\ + == 1 + assert refine(Piecewise((1, Ne(x, 0)), (3, True)), ~(Ne(x, 0)))\ + == 3 + assert refine(Piecewise((1, Ne(x, 0)), (3, True)), (Ne(y, 0)))\ + == Piecewise((1, Ne(x, 0)), (3, True)) + + +def test_atan2(): + assert refine(atan2(y, x), Q.real(y) & Q.positive(x)) == atan(y/x) + assert refine(atan2(y, x), Q.negative(y) & Q.positive(x)) == atan(y/x) + assert refine(atan2(y, x), Q.negative(y) & Q.negative(x)) == atan(y/x) - pi + assert refine(atan2(y, x), Q.positive(y) & Q.negative(x)) == atan(y/x) + pi + assert refine(atan2(y, x), Q.zero(y) & Q.negative(x)) == pi + assert refine(atan2(y, x), Q.positive(y) & Q.zero(x)) == pi/2 + assert refine(atan2(y, x), Q.negative(y) & Q.zero(x)) == -pi/2 + assert refine(atan2(y, x), Q.zero(y) & Q.zero(x)) is nan + + +def test_re(): + assert refine(re(x), Q.real(x)) == x + assert refine(re(x), Q.imaginary(x)) is S.Zero + assert refine(re(x+y), Q.real(x) & Q.real(y)) == x + y + assert refine(re(x+y), Q.real(x) & Q.imaginary(y)) == x + assert refine(re(x*y), Q.real(x) & Q.real(y)) == x * y + assert refine(re(x*y), Q.real(x) & Q.imaginary(y)) == 0 + assert refine(re(x*y*z), Q.real(x) & Q.real(y) & Q.real(z)) == x * y * z + + +def test_im(): + assert refine(im(x), Q.imaginary(x)) == -I*x + assert refine(im(x), Q.real(x)) is S.Zero + assert refine(im(x+y), Q.imaginary(x) & Q.imaginary(y)) == -I*x - I*y + assert refine(im(x+y), Q.real(x) & Q.imaginary(y)) == -I*y + assert refine(im(x*y), Q.imaginary(x) & Q.real(y)) == -I*x*y + assert refine(im(x*y), Q.imaginary(x) & Q.imaginary(y)) == 0 + assert refine(im(1/x), Q.imaginary(x)) == -I/x + assert refine(im(x*y*z), Q.imaginary(x) & Q.imaginary(y) + & Q.imaginary(z)) == -I*x*y*z + + +def test_complex(): + assert refine(re(1/(x + I*y)), Q.real(x) & Q.real(y)) == \ + x/(x**2 + y**2) + assert refine(im(1/(x + I*y)), Q.real(x) & Q.real(y)) == \ + -y/(x**2 + y**2) + assert refine(re((w + I*x) * (y + I*z)), Q.real(w) & Q.real(x) & Q.real(y) + & Q.real(z)) == w*y - x*z + assert refine(im((w + I*x) * (y + I*z)), Q.real(w) & Q.real(x) & Q.real(y) + & Q.real(z)) == w*z + x*y + + +def test_sign(): + x = Symbol('x', real = True) + assert refine(sign(x), Q.positive(x)) == 1 + assert refine(sign(x), Q.negative(x)) == -1 + assert refine(sign(x), Q.zero(x)) == 0 + assert refine(sign(x), True) == sign(x) + assert refine(sign(Abs(x)), Q.nonzero(x)) == 1 + + x = Symbol('x', imaginary=True) + assert refine(sign(x), Q.positive(im(x))) == S.ImaginaryUnit + assert refine(sign(x), Q.negative(im(x))) == -S.ImaginaryUnit + assert refine(sign(x), True) == sign(x) + + x = Symbol('x', complex=True) + assert refine(sign(x), Q.zero(x)) == 0 + +def test_arg(): + x = Symbol('x', complex = True) + assert refine(arg(x), Q.positive(x)) == 0 + assert refine(arg(x), Q.negative(x)) == pi + +def test_func_args(): + class MyClass(Expr): + # A class with nontrivial .func + + def __init__(self, *args): + self.my_member = "" + + @property + def func(self): + def my_func(*args): + obj = MyClass(*args) + obj.my_member = self.my_member + return obj + return my_func + + x = MyClass() + x.my_member = "A very important value" + assert x.my_member == refine(x).my_member + +def test_issue_refine_9384(): + assert refine(Piecewise((1, x < 0), (0, True)), Q.positive(x)) == 0 + assert refine(Piecewise((1, x < 0), (0, True)), Q.negative(x)) == 1 + assert refine(Piecewise((1, x > 0), (0, True)), Q.positive(x)) == 1 + assert refine(Piecewise((1, x > 0), (0, True)), Q.negative(x)) == 0 + + +def test_eval_refine(): + class MockExpr(Expr): + def _eval_refine(self, assumptions): + return True + + mock_obj = MockExpr() + assert refine(mock_obj) + +def test_refine_issue_12724(): + expr1 = refine(Abs(x * y), Q.positive(x)) + expr2 = refine(Abs(x * y * z), Q.positive(x)) + assert expr1 == x * Abs(y) + assert expr2 == x * Abs(y * z) + y1 = Symbol('y1', real = True) + expr3 = refine(Abs(x * y1**2 * z), Q.positive(x)) + assert expr3 == x * y1**2 * Abs(z) + + +def test_matrixelement(): + x = MatrixSymbol('x', 3, 3) + i = Symbol('i', positive = True) + j = Symbol('j', positive = True) + assert refine(x[0, 1], Q.symmetric(x)) == x[0, 1] + assert refine(x[1, 0], Q.symmetric(x)) == x[0, 1] + assert refine(x[i, j], Q.symmetric(x)) == x[j, i] + assert refine(x[j, i], Q.symmetric(x)) == x[j, i] diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/test_rel_queries.py b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/test_rel_queries.py new file mode 100644 index 0000000000000000000000000000000000000000..46fe3a35dc1adb23668e88d5794fe1c0ab22f33a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/test_rel_queries.py @@ -0,0 +1,172 @@ +from sympy.assumptions.lra_satask import lra_satask +from sympy.logic.algorithms.lra_theory import UnhandledInput +from sympy.assumptions.ask import Q, ask + +from sympy.core import symbols, Symbol +from sympy.matrices.expressions.matexpr import MatrixSymbol +from sympy.core.numbers import I + +from sympy.testing.pytest import raises, XFAIL +x, y, z = symbols("x y z", real=True) + +def test_lra_satask(): + im = Symbol('im', imaginary=True) + + # test preprocessing of unequalities is working correctly + assert lra_satask(Q.eq(x, 1), ~Q.ne(x, 0)) is False + assert lra_satask(Q.eq(x, 0), ~Q.ne(x, 0)) is True + assert lra_satask(~Q.ne(x, 0), Q.eq(x, 0)) is True + assert lra_satask(~Q.eq(x, 0), Q.eq(x, 0)) is False + assert lra_satask(Q.ne(x, 0), Q.eq(x, 0)) is False + + # basic tests + assert lra_satask(Q.ne(x, x)) is False + assert lra_satask(Q.eq(x, x)) is True + assert lra_satask(Q.gt(x, 0), Q.gt(x, 1)) is True + + # check that True/False are handled + assert lra_satask(Q.gt(x, 0), True) is None + assert raises(ValueError, lambda: lra_satask(Q.gt(x, 0), False)) + + # check imaginary numbers are correctly handled + # (im * I).is_real returns True so this is an edge case + raises(UnhandledInput, lambda: lra_satask(Q.gt(im * I, 0), Q.gt(im * I, 0))) + + # check matrix inputs + X = MatrixSymbol("X", 2, 2) + raises(UnhandledInput, lambda: lra_satask(Q.lt(X, 2) & Q.gt(X, 3))) + + +def test_old_assumptions(): + # test unhandled old assumptions + w = symbols("w") + raises(UnhandledInput, lambda: lra_satask(Q.lt(w, 2) & Q.gt(w, 3))) + w = symbols("w", rational=False, real=True) + raises(UnhandledInput, lambda: lra_satask(Q.lt(w, 2) & Q.gt(w, 3))) + w = symbols("w", odd=True, real=True) + raises(UnhandledInput, lambda: lra_satask(Q.lt(w, 2) & Q.gt(w, 3))) + w = symbols("w", even=True, real=True) + raises(UnhandledInput, lambda: lra_satask(Q.lt(w, 2) & Q.gt(w, 3))) + w = symbols("w", prime=True, real=True) + raises(UnhandledInput, lambda: lra_satask(Q.lt(w, 2) & Q.gt(w, 3))) + w = symbols("w", composite=True, real=True) + raises(UnhandledInput, lambda: lra_satask(Q.lt(w, 2) & Q.gt(w, 3))) + w = symbols("w", integer=True, real=True) + raises(UnhandledInput, lambda: lra_satask(Q.lt(w, 2) & Q.gt(w, 3))) + w = symbols("w", integer=False, real=True) + raises(UnhandledInput, lambda: lra_satask(Q.lt(w, 2) & Q.gt(w, 3))) + + # test handled + w = symbols("w", positive=True, real=True) + assert lra_satask(Q.le(w, 0)) is False + assert lra_satask(Q.gt(w, 0)) is True + w = symbols("w", negative=True, real=True) + assert lra_satask(Q.lt(w, 0)) is True + assert lra_satask(Q.ge(w, 0)) is False + w = symbols("w", zero=True, real=True) + assert lra_satask(Q.eq(w, 0)) is True + assert lra_satask(Q.ne(w, 0)) is False + w = symbols("w", nonzero=True, real=True) + assert lra_satask(Q.ne(w, 0)) is True + assert lra_satask(Q.eq(w, 1)) is None + w = symbols("w", nonpositive=True, real=True) + assert lra_satask(Q.le(w, 0)) is True + assert lra_satask(Q.gt(w, 0)) is False + w = symbols("w", nonnegative=True, real=True) + assert lra_satask(Q.ge(w, 0)) is True + assert lra_satask(Q.lt(w, 0)) is False + + +def test_rel_queries(): + assert ask(Q.lt(x, 2) & Q.gt(x, 3)) is False + assert ask(Q.positive(x - z), (x > y) & (y > z)) is True + assert ask(x + y > 2, (x < 0) & (y <0)) is False + assert ask(x > z, (x > y) & (y > z)) is True + + +def test_unhandled_queries(): + X = MatrixSymbol("X", 2, 2) + assert ask(Q.lt(X, 2) & Q.gt(X, 3)) is None + + +def test_all_pred(): + # test usable pred + assert lra_satask(Q.extended_positive(x), (x > 2)) is True + assert lra_satask(Q.positive_infinite(x)) is False + assert lra_satask(Q.negative_infinite(x)) is False + + # test disallowed pred + raises(UnhandledInput, lambda: lra_satask((x > 0), (x > 2) & Q.prime(x))) + raises(UnhandledInput, lambda: lra_satask((x > 0), (x > 2) & Q.composite(x))) + raises(UnhandledInput, lambda: lra_satask((x > 0), (x > 2) & Q.odd(x))) + raises(UnhandledInput, lambda: lra_satask((x > 0), (x > 2) & Q.even(x))) + raises(UnhandledInput, lambda: lra_satask((x > 0), (x > 2) & Q.integer(x))) + + +def test_number_line_properties(): + # From: + # https://en.wikipedia.org/wiki/Inequality_(mathematics)#Properties_on_the_number_line + + a, b, c = symbols("a b c", real=True) + + # Transitivity + # If a <= b and b <= c, then a <= c. + assert ask(a <= c, (a <= b) & (b <= c)) is True + # If a <= b and b < c, then a < c. + assert ask(a < c, (a <= b) & (b < c)) is True + # If a < b and b <= c, then a < c. + assert ask(a < c, (a < b) & (b <= c)) is True + + # Addition and subtraction + # If a <= b, then a + c <= b + c and a - c <= b - c. + assert ask(a + c <= b + c, a <= b) is True + assert ask(a - c <= b - c, a <= b) is True + + +@XFAIL +def test_failing_number_line_properties(): + # From: + # https://en.wikipedia.org/wiki/Inequality_(mathematics)#Properties_on_the_number_line + + a, b, c = symbols("a b c", real=True) + + # Multiplication and division + # If a <= b and c > 0, then ac <= bc and a/c <= b/c. (True for non-zero c) + assert ask(a*c <= b*c, (a <= b) & (c > 0) & ~ Q.zero(c)) is True + assert ask(a/c <= b/c, (a <= b) & (c > 0) & ~ Q.zero(c)) is True + # If a <= b and c < 0, then ac >= bc and a/c >= b/c. (True for non-zero c) + assert ask(a*c >= b*c, (a <= b) & (c < 0) & ~ Q.zero(c)) is True + assert ask(a/c >= b/c, (a <= b) & (c < 0) & ~ Q.zero(c)) is True + + # Additive inverse + # If a <= b, then -a >= -b. + assert ask(-a >= -b, a <= b) is True + + # Multiplicative inverse + # For a, b that are both negative or both positive: + # If a <= b, then 1/a >= 1/b . + assert ask(1/a >= 1/b, (a <= b) & Q.positive(x) & Q.positive(b)) is True + assert ask(1/a >= 1/b, (a <= b) & Q.negative(x) & Q.negative(b)) is True + + +def test_equality(): + # test symmetry and reflexivity + assert ask(Q.eq(x, x)) is True + assert ask(Q.eq(y, x), Q.eq(x, y)) is True + assert ask(Q.eq(y, x), ~Q.eq(z, z) | Q.eq(x, y)) is True + + # test transitivity + assert ask(Q.eq(x,z), Q.eq(x,y) & Q.eq(y,z)) is True + + +@XFAIL +def test_equality_failing(): + # Note that implementing the substitution property of equality + # most likely requires a redesign of the new assumptions. + # See issue #25485 for why this is the case and general ideas + # about how things could be redesigned. + + # test substitution property + assert ask(Q.prime(x), Q.eq(x, y) & Q.prime(y)) is True + assert ask(Q.real(x), Q.eq(x, y) & Q.real(y)) is True + assert ask(Q.imaginary(x), Q.eq(x, y) & Q.imaginary(y)) is True diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/test_satask.py b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/test_satask.py new file mode 100644 index 0000000000000000000000000000000000000000..5831b69e3e6bf2b1a906d1140967510c2ea8b630 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/test_satask.py @@ -0,0 +1,378 @@ +from sympy.assumptions.ask import Q +from sympy.assumptions.assume import assuming +from sympy.core.numbers import (I, pi) +from sympy.core.relational import (Eq, Gt) +from sympy.core.singleton import S +from sympy.core.symbol import symbols +from sympy.functions.elementary.complexes import Abs +from sympy.logic.boolalg import Implies +from sympy.matrices.expressions.matexpr import MatrixSymbol +from sympy.assumptions.cnf import CNF, Literal +from sympy.assumptions.satask import (satask, extract_predargs, + get_relevant_clsfacts) + +from sympy.testing.pytest import raises, XFAIL + + +x, y, z = symbols('x y z') + + +def test_satask(): + # No relevant facts + assert satask(Q.real(x), Q.real(x)) is True + assert satask(Q.real(x), ~Q.real(x)) is False + assert satask(Q.real(x)) is None + + assert satask(Q.real(x), Q.positive(x)) is True + assert satask(Q.positive(x), Q.real(x)) is None + assert satask(Q.real(x), ~Q.positive(x)) is None + assert satask(Q.positive(x), ~Q.real(x)) is False + + raises(ValueError, lambda: satask(Q.real(x), Q.real(x) & ~Q.real(x))) + + with assuming(Q.positive(x)): + assert satask(Q.real(x)) is True + assert satask(~Q.positive(x)) is False + raises(ValueError, lambda: satask(Q.real(x), ~Q.positive(x))) + + assert satask(Q.zero(x), Q.nonzero(x)) is False + assert satask(Q.positive(x), Q.zero(x)) is False + assert satask(Q.real(x), Q.zero(x)) is True + assert satask(Q.zero(x), Q.zero(x*y)) is None + assert satask(Q.zero(x*y), Q.zero(x)) + + +def test_zero(): + """ + Everything in this test doesn't work with the ask handlers, and most + things would be very difficult or impossible to make work under that + model. + + """ + assert satask(Q.zero(x) | Q.zero(y), Q.zero(x*y)) is True + assert satask(Q.zero(x*y), Q.zero(x) | Q.zero(y)) is True + + assert satask(Implies(Q.zero(x), Q.zero(x*y))) is True + + # This one in particular requires computing the fixed-point of the + # relevant facts, because going from Q.nonzero(x*y) -> ~Q.zero(x*y) and + # Q.zero(x*y) -> Equivalent(Q.zero(x*y), Q.zero(x) | Q.zero(y)) takes two + # steps. + assert satask(Q.zero(x) | Q.zero(y), Q.nonzero(x*y)) is False + + assert satask(Q.zero(x), Q.zero(x**2)) is True + + +def test_zero_positive(): + assert satask(Q.zero(x + y), Q.positive(x) & Q.positive(y)) is False + assert satask(Q.positive(x) & Q.positive(y), Q.zero(x + y)) is False + assert satask(Q.nonzero(x + y), Q.positive(x) & Q.positive(y)) is True + assert satask(Q.positive(x) & Q.positive(y), Q.nonzero(x + y)) is None + + # This one requires several levels of forward chaining + assert satask(Q.zero(x*(x + y)), Q.positive(x) & Q.positive(y)) is False + + assert satask(Q.positive(pi*x*y + 1), Q.positive(x) & Q.positive(y)) is True + assert satask(Q.positive(pi*x*y - 5), Q.positive(x) & Q.positive(y)) is None + + +def test_zero_pow(): + assert satask(Q.zero(x**y), Q.zero(x) & Q.positive(y)) is True + assert satask(Q.zero(x**y), Q.nonzero(x) & Q.zero(y)) is False + + assert satask(Q.zero(x), Q.zero(x**y)) is True + + assert satask(Q.zero(x**y), Q.zero(x)) is None + + +@XFAIL +# Requires correct Q.square calculation first +def test_invertible(): + A = MatrixSymbol('A', 5, 5) + B = MatrixSymbol('B', 5, 5) + assert satask(Q.invertible(A*B), Q.invertible(A) & Q.invertible(B)) is True + assert satask(Q.invertible(A), Q.invertible(A*B)) is True + assert satask(Q.invertible(A) & Q.invertible(B), Q.invertible(A*B)) is True + + +def test_prime(): + assert satask(Q.prime(5)) is True + assert satask(Q.prime(6)) is False + assert satask(Q.prime(-5)) is False + + assert satask(Q.prime(x*y), Q.integer(x) & Q.integer(y)) is None + assert satask(Q.prime(x*y), Q.prime(x) & Q.prime(y)) is False + + +def test_old_assump(): + assert satask(Q.positive(1)) is True + assert satask(Q.positive(-1)) is False + assert satask(Q.positive(0)) is False + assert satask(Q.positive(I)) is False + assert satask(Q.positive(pi)) is True + + assert satask(Q.negative(1)) is False + assert satask(Q.negative(-1)) is True + assert satask(Q.negative(0)) is False + assert satask(Q.negative(I)) is False + assert satask(Q.negative(pi)) is False + + assert satask(Q.zero(1)) is False + assert satask(Q.zero(-1)) is False + assert satask(Q.zero(0)) is True + assert satask(Q.zero(I)) is False + assert satask(Q.zero(pi)) is False + + assert satask(Q.nonzero(1)) is True + assert satask(Q.nonzero(-1)) is True + assert satask(Q.nonzero(0)) is False + assert satask(Q.nonzero(I)) is False + assert satask(Q.nonzero(pi)) is True + + assert satask(Q.nonpositive(1)) is False + assert satask(Q.nonpositive(-1)) is True + assert satask(Q.nonpositive(0)) is True + assert satask(Q.nonpositive(I)) is False + assert satask(Q.nonpositive(pi)) is False + + assert satask(Q.nonnegative(1)) is True + assert satask(Q.nonnegative(-1)) is False + assert satask(Q.nonnegative(0)) is True + assert satask(Q.nonnegative(I)) is False + assert satask(Q.nonnegative(pi)) is True + + +def test_rational_irrational(): + assert satask(Q.irrational(2)) is False + assert satask(Q.rational(2)) is True + assert satask(Q.irrational(pi)) is True + assert satask(Q.rational(pi)) is False + assert satask(Q.irrational(I)) is False + assert satask(Q.rational(I)) is False + + assert satask(Q.irrational(x*y*z), Q.irrational(x) & Q.irrational(y) & + Q.rational(z)) is None + assert satask(Q.irrational(x*y*z), Q.irrational(x) & Q.rational(y) & + Q.rational(z)) is True + assert satask(Q.irrational(pi*x*y), Q.rational(x) & Q.rational(y)) is True + + assert satask(Q.irrational(x + y + z), Q.irrational(x) & Q.irrational(y) & + Q.rational(z)) is None + assert satask(Q.irrational(x + y + z), Q.irrational(x) & Q.rational(y) & + Q.rational(z)) is True + assert satask(Q.irrational(pi + x + y), Q.rational(x) & Q.rational(y)) is True + + assert satask(Q.irrational(x*y*z), Q.rational(x) & Q.rational(y) & + Q.rational(z)) is False + assert satask(Q.rational(x*y*z), Q.rational(x) & Q.rational(y) & + Q.rational(z)) is True + + assert satask(Q.irrational(x + y + z), Q.rational(x) & Q.rational(y) & + Q.rational(z)) is False + assert satask(Q.rational(x + y + z), Q.rational(x) & Q.rational(y) & + Q.rational(z)) is True + + +def test_even_satask(): + assert satask(Q.even(2)) is True + assert satask(Q.even(3)) is False + + assert satask(Q.even(x*y), Q.even(x) & Q.odd(y)) is True + assert satask(Q.even(x*y), Q.even(x) & Q.integer(y)) is True + assert satask(Q.even(x*y), Q.even(x) & Q.even(y)) is True + assert satask(Q.even(x*y), Q.odd(x) & Q.odd(y)) is False + assert satask(Q.even(x*y), Q.even(x)) is None + assert satask(Q.even(x*y), Q.odd(x) & Q.integer(y)) is None + assert satask(Q.even(x*y), Q.odd(x) & Q.odd(y)) is False + + assert satask(Q.even(abs(x)), Q.even(x)) is True + assert satask(Q.even(abs(x)), Q.odd(x)) is False + assert satask(Q.even(x), Q.even(abs(x))) is None # x could be complex + + +def test_odd_satask(): + assert satask(Q.odd(2)) is False + assert satask(Q.odd(3)) is True + + assert satask(Q.odd(x*y), Q.even(x) & Q.odd(y)) is False + assert satask(Q.odd(x*y), Q.even(x) & Q.integer(y)) is False + assert satask(Q.odd(x*y), Q.even(x) & Q.even(y)) is False + assert satask(Q.odd(x*y), Q.odd(x) & Q.odd(y)) is True + assert satask(Q.odd(x*y), Q.even(x)) is None + assert satask(Q.odd(x*y), Q.odd(x) & Q.integer(y)) is None + assert satask(Q.odd(x*y), Q.odd(x) & Q.odd(y)) is True + + assert satask(Q.odd(abs(x)), Q.even(x)) is False + assert satask(Q.odd(abs(x)), Q.odd(x)) is True + assert satask(Q.odd(x), Q.odd(abs(x))) is None # x could be complex + + +def test_integer(): + assert satask(Q.integer(1)) is True + assert satask(Q.integer(S.Half)) is False + + assert satask(Q.integer(x + y), Q.integer(x) & Q.integer(y)) is True + assert satask(Q.integer(x + y), Q.integer(x)) is None + + assert satask(Q.integer(x + y), Q.integer(x) & ~Q.integer(y)) is False + assert satask(Q.integer(x + y + z), Q.integer(x) & Q.integer(y) & + ~Q.integer(z)) is False + assert satask(Q.integer(x + y + z), Q.integer(x) & ~Q.integer(y) & + ~Q.integer(z)) is None + assert satask(Q.integer(x + y + z), Q.integer(x) & ~Q.integer(y)) is None + assert satask(Q.integer(x + y), Q.integer(x) & Q.irrational(y)) is False + + assert satask(Q.integer(x*y), Q.integer(x) & Q.integer(y)) is True + assert satask(Q.integer(x*y), Q.integer(x)) is None + + assert satask(Q.integer(x*y), Q.integer(x) & ~Q.integer(y)) is None + assert satask(Q.integer(x*y), Q.integer(x) & ~Q.rational(y)) is False + assert satask(Q.integer(x*y*z), Q.integer(x) & Q.integer(y) & + ~Q.rational(z)) is False + assert satask(Q.integer(x*y*z), Q.integer(x) & ~Q.rational(y) & + ~Q.rational(z)) is None + assert satask(Q.integer(x*y*z), Q.integer(x) & ~Q.rational(y)) is None + assert satask(Q.integer(x*y), Q.integer(x) & Q.irrational(y)) is False + + +def test_abs(): + assert satask(Q.nonnegative(abs(x))) is True + assert satask(Q.positive(abs(x)), ~Q.zero(x)) is True + assert satask(Q.zero(x), ~Q.zero(abs(x))) is False + assert satask(Q.zero(x), Q.zero(abs(x))) is True + assert satask(Q.nonzero(x), ~Q.zero(abs(x))) is None # x could be complex + assert satask(Q.zero(abs(x)), Q.zero(x)) is True + + +def test_imaginary(): + assert satask(Q.imaginary(2*I)) is True + assert satask(Q.imaginary(x*y), Q.imaginary(x)) is None + assert satask(Q.imaginary(x*y), Q.imaginary(x) & Q.real(y)) is True + assert satask(Q.imaginary(x), Q.real(x)) is False + assert satask(Q.imaginary(1)) is False + assert satask(Q.imaginary(x*y), Q.real(x) & Q.real(y)) is False + assert satask(Q.imaginary(x + y), Q.real(x) & Q.real(y)) is False + + +def test_real(): + assert satask(Q.real(x*y), Q.real(x) & Q.real(y)) is True + assert satask(Q.real(x + y), Q.real(x) & Q.real(y)) is True + assert satask(Q.real(x*y*z), Q.real(x) & Q.real(y) & Q.real(z)) is True + assert satask(Q.real(x*y*z), Q.real(x) & Q.real(y)) is None + assert satask(Q.real(x*y*z), Q.real(x) & Q.real(y) & Q.imaginary(z)) is False + assert satask(Q.real(x + y + z), Q.real(x) & Q.real(y) & Q.real(z)) is True + assert satask(Q.real(x + y + z), Q.real(x) & Q.real(y)) is None + + +def test_pos_neg(): + assert satask(~Q.positive(x), Q.negative(x)) is True + assert satask(~Q.negative(x), Q.positive(x)) is True + assert satask(Q.positive(x + y), Q.positive(x) & Q.positive(y)) is True + assert satask(Q.negative(x + y), Q.negative(x) & Q.negative(y)) is True + assert satask(Q.positive(x + y), Q.negative(x) & Q.negative(y)) is False + assert satask(Q.negative(x + y), Q.positive(x) & Q.positive(y)) is False + + +def test_pow_pos_neg(): + assert satask(Q.nonnegative(x**2), Q.positive(x)) is True + assert satask(Q.nonpositive(x**2), Q.positive(x)) is False + assert satask(Q.positive(x**2), Q.positive(x)) is True + assert satask(Q.negative(x**2), Q.positive(x)) is False + assert satask(Q.real(x**2), Q.positive(x)) is True + + assert satask(Q.nonnegative(x**2), Q.negative(x)) is True + assert satask(Q.nonpositive(x**2), Q.negative(x)) is False + assert satask(Q.positive(x**2), Q.negative(x)) is True + assert satask(Q.negative(x**2), Q.negative(x)) is False + assert satask(Q.real(x**2), Q.negative(x)) is True + + assert satask(Q.nonnegative(x**2), Q.nonnegative(x)) is True + assert satask(Q.nonpositive(x**2), Q.nonnegative(x)) is None + assert satask(Q.positive(x**2), Q.nonnegative(x)) is None + assert satask(Q.negative(x**2), Q.nonnegative(x)) is False + assert satask(Q.real(x**2), Q.nonnegative(x)) is True + + assert satask(Q.nonnegative(x**2), Q.nonpositive(x)) is True + assert satask(Q.nonpositive(x**2), Q.nonpositive(x)) is None + assert satask(Q.positive(x**2), Q.nonpositive(x)) is None + assert satask(Q.negative(x**2), Q.nonpositive(x)) is False + assert satask(Q.real(x**2), Q.nonpositive(x)) is True + + assert satask(Q.nonnegative(x**3), Q.positive(x)) is True + assert satask(Q.nonpositive(x**3), Q.positive(x)) is False + assert satask(Q.positive(x**3), Q.positive(x)) is True + assert satask(Q.negative(x**3), Q.positive(x)) is False + assert satask(Q.real(x**3), Q.positive(x)) is True + + assert satask(Q.nonnegative(x**3), Q.negative(x)) is False + assert satask(Q.nonpositive(x**3), Q.negative(x)) is True + assert satask(Q.positive(x**3), Q.negative(x)) is False + assert satask(Q.negative(x**3), Q.negative(x)) is True + assert satask(Q.real(x**3), Q.negative(x)) is True + + assert satask(Q.nonnegative(x**3), Q.nonnegative(x)) is True + assert satask(Q.nonpositive(x**3), Q.nonnegative(x)) is None + assert satask(Q.positive(x**3), Q.nonnegative(x)) is None + assert satask(Q.negative(x**3), Q.nonnegative(x)) is False + assert satask(Q.real(x**3), Q.nonnegative(x)) is True + + assert satask(Q.nonnegative(x**3), Q.nonpositive(x)) is None + assert satask(Q.nonpositive(x**3), Q.nonpositive(x)) is True + assert satask(Q.positive(x**3), Q.nonpositive(x)) is False + assert satask(Q.negative(x**3), Q.nonpositive(x)) is None + assert satask(Q.real(x**3), Q.nonpositive(x)) is True + + # If x is zero, x**negative is not real. + assert satask(Q.nonnegative(x**-2), Q.nonpositive(x)) is None + assert satask(Q.nonpositive(x**-2), Q.nonpositive(x)) is None + assert satask(Q.positive(x**-2), Q.nonpositive(x)) is None + assert satask(Q.negative(x**-2), Q.nonpositive(x)) is None + assert satask(Q.real(x**-2), Q.nonpositive(x)) is None + + # We could deduce things for negative powers if x is nonzero, but it + # isn't implemented yet. + + +def test_prime_composite(): + assert satask(Q.prime(x), Q.composite(x)) is False + assert satask(Q.composite(x), Q.prime(x)) is False + assert satask(Q.composite(x), ~Q.prime(x)) is None + assert satask(Q.prime(x), ~Q.composite(x)) is None + # since 1 is neither prime nor composite the following should hold + assert satask(Q.prime(x), Q.integer(x) & Q.positive(x) & ~Q.composite(x)) is None + assert satask(Q.prime(2)) is True + assert satask(Q.prime(4)) is False + assert satask(Q.prime(1)) is False + assert satask(Q.composite(1)) is False + + +def test_extract_predargs(): + props = CNF.from_prop(Q.zero(Abs(x*y)) & Q.zero(x*y)) + assump = CNF.from_prop(Q.zero(x)) + context = CNF.from_prop(Q.zero(y)) + assert extract_predargs(props) == {Abs(x*y), x*y} + assert extract_predargs(props, assump) == {Abs(x*y), x*y, x} + assert extract_predargs(props, assump, context) == {Abs(x*y), x*y, x, y} + + props = CNF.from_prop(Eq(x, y)) + assump = CNF.from_prop(Gt(y, z)) + assert extract_predargs(props, assump) == {x, y, z} + + +def test_get_relevant_clsfacts(): + exprs = {Abs(x*y)} + exprs, facts = get_relevant_clsfacts(exprs) + assert exprs == {x*y} + assert facts.clauses == \ + {frozenset({Literal(Q.odd(Abs(x*y)), False), Literal(Q.odd(x*y), True)}), + frozenset({Literal(Q.zero(Abs(x*y)), False), Literal(Q.zero(x*y), True)}), + frozenset({Literal(Q.even(Abs(x*y)), False), Literal(Q.even(x*y), True)}), + frozenset({Literal(Q.zero(Abs(x*y)), True), Literal(Q.zero(x*y), False)}), + frozenset({Literal(Q.even(Abs(x*y)), False), + Literal(Q.odd(Abs(x*y)), False), + Literal(Q.odd(x*y), True)}), + frozenset({Literal(Q.even(Abs(x*y)), False), + Literal(Q.even(x*y), True), + Literal(Q.odd(Abs(x*y)), False)}), + frozenset({Literal(Q.positive(Abs(x*y)), False), + Literal(Q.zero(Abs(x*y)), False)})} diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/test_sathandlers.py b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/test_sathandlers.py new file mode 100644 index 0000000000000000000000000000000000000000..9d568ad8efe6ba7cf7f5eb03879ad6764c16e729 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/test_sathandlers.py @@ -0,0 +1,50 @@ +from sympy.assumptions.ask import Q +from sympy.core.basic import Basic +from sympy.core.expr import Expr +from sympy.core.mul import Mul +from sympy.core.symbol import symbols +from sympy.logic.boolalg import (And, Or) + +from sympy.assumptions.sathandlers import (ClassFactRegistry, allargs, + anyarg, exactlyonearg,) + +x, y, z = symbols('x y z') + + +def test_class_handler_registry(): + my_handler_registry = ClassFactRegistry() + + # The predicate doesn't matter here, so just pass + @my_handler_registry.register(Mul) + def fact1(expr): + pass + @my_handler_registry.multiregister(Expr) + def fact2(expr): + pass + + assert my_handler_registry[Basic] == (frozenset(), frozenset()) + assert my_handler_registry[Expr] == (frozenset(), frozenset({fact2})) + assert my_handler_registry[Mul] == (frozenset({fact1}), frozenset({fact2})) + + +def test_allargs(): + assert allargs(x, Q.zero(x), x*y) == And(Q.zero(x), Q.zero(y)) + assert allargs(x, Q.positive(x) | Q.negative(x), x*y) == And(Q.positive(x) | Q.negative(x), Q.positive(y) | Q.negative(y)) + + +def test_anyarg(): + assert anyarg(x, Q.zero(x), x*y) == Or(Q.zero(x), Q.zero(y)) + assert anyarg(x, Q.positive(x) & Q.negative(x), x*y) == \ + Or(Q.positive(x) & Q.negative(x), Q.positive(y) & Q.negative(y)) + + +def test_exactlyonearg(): + assert exactlyonearg(x, Q.zero(x), x*y) == \ + Or(Q.zero(x) & ~Q.zero(y), Q.zero(y) & ~Q.zero(x)) + assert exactlyonearg(x, Q.zero(x), x*y*z) == \ + Or(Q.zero(x) & ~Q.zero(y) & ~Q.zero(z), Q.zero(y) + & ~Q.zero(x) & ~Q.zero(z), Q.zero(z) & ~Q.zero(x) & ~Q.zero(y)) + assert exactlyonearg(x, Q.positive(x) | Q.negative(x), x*y) == \ + Or((Q.positive(x) | Q.negative(x)) & + ~(Q.positive(y) | Q.negative(y)), (Q.positive(y) | Q.negative(y)) & + ~(Q.positive(x) | Q.negative(x))) diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/test_wrapper.py b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/test_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..af9afd5d51fb1341e0b08149dc842b78a39c329b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/assumptions/tests/test_wrapper.py @@ -0,0 +1,39 @@ +from sympy.assumptions.ask import Q +from sympy.assumptions.wrapper import (AssumptionsWrapper, is_infinite, + is_extended_real) +from sympy.core.symbol import Symbol +from sympy.core.assumptions import _assume_defined + + +def test_all_predicates(): + for fact in _assume_defined: + method_name = f'_eval_is_{fact}' + assert hasattr(AssumptionsWrapper, method_name) + + +def test_AssumptionsWrapper(): + x = Symbol('x', positive=True) + y = Symbol('y') + assert AssumptionsWrapper(x).is_positive + assert AssumptionsWrapper(y).is_positive is None + assert AssumptionsWrapper(y, Q.positive(y)).is_positive + + +def test_is_infinite(): + x = Symbol('x', infinite=True) + y = Symbol('y', infinite=False) + z = Symbol('z') + assert is_infinite(x) + assert not is_infinite(y) + assert is_infinite(z) is None + assert is_infinite(z, Q.infinite(z)) + + +def test_is_extended_real(): + x = Symbol('x', extended_real=True) + y = Symbol('y', extended_real=False) + z = Symbol('z') + assert is_extended_real(x) + assert not is_extended_real(y) + assert is_extended_real(z) is None + assert is_extended_real(z, Q.extended_real(z)) diff --git a/.venv/lib/python3.12/site-packages/sympy/assumptions/wrapper.py b/.venv/lib/python3.12/site-packages/sympy/assumptions/wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..cb06e9de770ed41a2b3d6fe63381ad1cb59acacc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/assumptions/wrapper.py @@ -0,0 +1,164 @@ +""" +Functions and wrapper object to call assumption property and predicate +query with same syntax. + +In SymPy, there are two assumption systems. Old assumption system is +defined in sympy/core/assumptions, and it can be accessed by attribute +such as ``x.is_even``. New assumption system is defined in +sympy/assumptions, and it can be accessed by predicates such as +``Q.even(x)``. + +Old assumption is fast, while new assumptions can freely take local facts. +In general, old assumption is used in evaluation method and new assumption +is used in refinement method. + +In most cases, both evaluation and refinement follow the same process, and +the only difference is which assumption system is used. This module provides +``is_[...]()`` functions and ``AssumptionsWrapper()`` class which allows +using two systems with same syntax so that parallel code implementation can be +avoided. + +Examples +======== + +For multiple use, use ``AssumptionsWrapper()``. + +>>> from sympy import Q, Symbol +>>> from sympy.assumptions.wrapper import AssumptionsWrapper +>>> x = Symbol('x') +>>> _x = AssumptionsWrapper(x, Q.even(x)) +>>> _x.is_integer +True +>>> _x.is_odd +False + +For single use, use ``is_[...]()`` functions. + +>>> from sympy.assumptions.wrapper import is_infinite +>>> a = Symbol('a') +>>> print(is_infinite(a)) +None +>>> is_infinite(a, Q.finite(a)) +False + +""" + +from sympy.assumptions import ask, Q +from sympy.core.basic import Basic +from sympy.core.sympify import _sympify + + +def make_eval_method(fact): + def getit(self): + pred = getattr(Q, fact) + ret = ask(pred(self.expr), self.assumptions) + return ret + return getit + + +# we subclass Basic to use the fact deduction and caching +class AssumptionsWrapper(Basic): + """ + Wrapper over ``Basic`` instances to call predicate query by + ``.is_[...]`` property + + Parameters + ========== + + expr : Basic + + assumptions : Boolean, optional + + Examples + ======== + + >>> from sympy import Q, Symbol + >>> from sympy.assumptions.wrapper import AssumptionsWrapper + >>> x = Symbol('x', even=True) + >>> AssumptionsWrapper(x).is_integer + True + >>> y = Symbol('y') + >>> AssumptionsWrapper(y, Q.even(y)).is_integer + True + + With ``AssumptionsWrapper``, both evaluation and refinement can be supported + by single implementation. + + >>> from sympy import Function + >>> class MyAbs(Function): + ... @classmethod + ... def eval(cls, x, assumptions=True): + ... _x = AssumptionsWrapper(x, assumptions) + ... if _x.is_nonnegative: + ... return x + ... if _x.is_negative: + ... return -x + ... def _eval_refine(self, assumptions): + ... return MyAbs.eval(self.args[0], assumptions) + >>> MyAbs(x) + MyAbs(x) + >>> MyAbs(x).refine(Q.positive(x)) + x + >>> MyAbs(Symbol('y', negative=True)) + -y + + """ + def __new__(cls, expr, assumptions=None): + if assumptions is None: + return expr + obj = super().__new__(cls, expr, _sympify(assumptions)) + obj.expr = expr + obj.assumptions = assumptions + return obj + + _eval_is_algebraic = make_eval_method("algebraic") + _eval_is_antihermitian = make_eval_method("antihermitian") + _eval_is_commutative = make_eval_method("commutative") + _eval_is_complex = make_eval_method("complex") + _eval_is_composite = make_eval_method("composite") + _eval_is_even = make_eval_method("even") + _eval_is_extended_negative = make_eval_method("extended_negative") + _eval_is_extended_nonnegative = make_eval_method("extended_nonnegative") + _eval_is_extended_nonpositive = make_eval_method("extended_nonpositive") + _eval_is_extended_nonzero = make_eval_method("extended_nonzero") + _eval_is_extended_positive = make_eval_method("extended_positive") + _eval_is_extended_real = make_eval_method("extended_real") + _eval_is_finite = make_eval_method("finite") + _eval_is_hermitian = make_eval_method("hermitian") + _eval_is_imaginary = make_eval_method("imaginary") + _eval_is_infinite = make_eval_method("infinite") + _eval_is_integer = make_eval_method("integer") + _eval_is_irrational = make_eval_method("irrational") + _eval_is_negative = make_eval_method("negative") + _eval_is_noninteger = make_eval_method("noninteger") + _eval_is_nonnegative = make_eval_method("nonnegative") + _eval_is_nonpositive = make_eval_method("nonpositive") + _eval_is_nonzero = make_eval_method("nonzero") + _eval_is_odd = make_eval_method("odd") + _eval_is_polar = make_eval_method("polar") + _eval_is_positive = make_eval_method("positive") + _eval_is_prime = make_eval_method("prime") + _eval_is_rational = make_eval_method("rational") + _eval_is_real = make_eval_method("real") + _eval_is_transcendental = make_eval_method("transcendental") + _eval_is_zero = make_eval_method("zero") + + +# one shot functions which are faster than AssumptionsWrapper + +def is_infinite(obj, assumptions=None): + if assumptions is None: + return obj.is_infinite + return ask(Q.infinite(obj), assumptions) + + +def is_extended_real(obj, assumptions=None): + if assumptions is None: + return obj.is_extended_real + return ask(Q.extended_real(obj), assumptions) + + +def is_extended_nonnegative(obj, assumptions=None): + if assumptions is None: + return obj.is_extended_nonnegative + return ask(Q.extended_nonnegative(obj), assumptions) diff --git a/.venv/lib/python3.12/site-packages/sympy/benchmarks/__init__.py b/.venv/lib/python3.12/site-packages/sympy/benchmarks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/sympy/benchmarks/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/benchmarks/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..478c1459143b32d4c31c008e207196fb596dafd6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/benchmarks/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/benchmarks/__pycache__/bench_discrete_log.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/benchmarks/__pycache__/bench_discrete_log.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..575f39b4b90bc24a3c7a6d8dc43c83f2efb52303 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/benchmarks/__pycache__/bench_discrete_log.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/benchmarks/__pycache__/bench_meijerint.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/benchmarks/__pycache__/bench_meijerint.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a78d09290ffd94e937a30c54936eaf722f534b4c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/benchmarks/__pycache__/bench_meijerint.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/benchmarks/__pycache__/bench_symbench.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/benchmarks/__pycache__/bench_symbench.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ecf51df06724b24f93c5af7c611036647984226 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/benchmarks/__pycache__/bench_symbench.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/benchmarks/bench_discrete_log.py b/.venv/lib/python3.12/site-packages/sympy/benchmarks/bench_discrete_log.py new file mode 100644 index 0000000000000000000000000000000000000000..76b273909e415318a7d3bace00ffff2a0bc53762 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/benchmarks/bench_discrete_log.py @@ -0,0 +1,83 @@ +import sys +from time import time +from sympy.ntheory.residue_ntheory import (discrete_log, + _discrete_log_trial_mul, _discrete_log_shanks_steps, + _discrete_log_pollard_rho, _discrete_log_pohlig_hellman) + + +# Cyclic group (Z/pZ)* with p prime, order p - 1 and generator g +data_set_1 = [ + # p, p - 1, g + [191, 190, 19], + [46639, 46638, 6], + [14789363, 14789362, 2], + [4254225211, 4254225210, 2], + [432751500361, 432751500360, 7], + [158505390797053, 158505390797052, 2], + [6575202655312007, 6575202655312006, 5], + [8430573471995353769, 8430573471995353768, 3], + [3938471339744997827267, 3938471339744997827266, 2], + [875260951364705563393093, 875260951364705563393092, 5], + ] + + +# Cyclic sub-groups of (Z/nZ)* with prime order p and generator g +# (n, p are primes and n = 2 * p + 1) +data_set_2 = [ + # n, p, g + [227, 113, 3], + [2447, 1223, 2], + [24527, 12263, 2], + [245639, 122819, 2], + [2456747, 1228373, 3], + [24567899, 12283949, 3], + [245679023, 122839511, 2], + [2456791307, 1228395653, 3], + [24567913439, 12283956719, 2], + [245679135407, 122839567703, 2], + [2456791354763, 1228395677381, 3], + [24567913550903, 12283956775451, 2], + [245679135509519, 122839567754759, 2], + ] + + +# Cyclic sub-groups of (Z/nZ)* with smooth order o and generator g +data_set_3 = [ + # n, o, g + [2**118, 2**116, 3], + ] + + +def bench_discrete_log(data_set, algo=None): + if algo is None: + f = discrete_log + elif algo == 'trial': + f = _discrete_log_trial_mul + elif algo == 'shanks': + f = _discrete_log_shanks_steps + elif algo == 'rho': + f = _discrete_log_pollard_rho + elif algo == 'ph': + f = _discrete_log_pohlig_hellman + else: + raise ValueError("Argument 'algo' should be one" + " of ('trial', 'shanks', 'rho' or 'ph')") + + for i, data in enumerate(data_set): + for j, (n, p, g) in enumerate(data): + t = time() + l = f(n, pow(g, p - 1, n), g, p) + t = time() - t + print('[%02d-%03d] %15.10f' % (i, j, t)) + assert l == p - 1 + + +if __name__ == '__main__': + algo = sys.argv[1] \ + if len(sys.argv) > 1 else None + data_set = [ + data_set_1, + data_set_2, + data_set_3, + ] + bench_discrete_log(data_set, algo) diff --git a/.venv/lib/python3.12/site-packages/sympy/benchmarks/bench_meijerint.py b/.venv/lib/python3.12/site-packages/sympy/benchmarks/bench_meijerint.py new file mode 100644 index 0000000000000000000000000000000000000000..d648c3e02463d5a7ee1dcbe3b22af5cc22fef43d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/benchmarks/bench_meijerint.py @@ -0,0 +1,261 @@ +# conceal the implicit import from the code quality tester +from sympy.core.numbers import (oo, pi) +from sympy.core.symbol import (Symbol, symbols) +from sympy.functions.elementary.exponential import exp +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.special.bessel import besseli +from sympy.functions.special.gamma_functions import gamma +from sympy.integrals.integrals import integrate +from sympy.integrals.transforms import (mellin_transform, + inverse_fourier_transform, inverse_mellin_transform, + laplace_transform, inverse_laplace_transform, fourier_transform) + +LT = laplace_transform +FT = fourier_transform +MT = mellin_transform +IFT = inverse_fourier_transform +ILT = inverse_laplace_transform +IMT = inverse_mellin_transform + +from sympy.abc import x, y +nu, beta, rho = symbols('nu beta rho') + +apos, bpos, cpos, dpos, posk, p = symbols('a b c d k p', positive=True) +k = Symbol('k', real=True) +negk = Symbol('k', negative=True) + +mu1, mu2 = symbols('mu1 mu2', real=True, nonzero=True, finite=True) +sigma1, sigma2 = symbols('sigma1 sigma2', real=True, nonzero=True, + finite=True, positive=True) +rate = Symbol('lambda', positive=True) + + +def normal(x, mu, sigma): + return 1/sqrt(2*pi*sigma**2)*exp(-(x - mu)**2/2/sigma**2) + + +def exponential(x, rate): + return rate*exp(-rate*x) +alpha, beta = symbols('alpha beta', positive=True) +betadist = x**(alpha - 1)*(1 + x)**(-alpha - beta)*gamma(alpha + beta) \ + /gamma(alpha)/gamma(beta) +kint = Symbol('k', integer=True, positive=True) +chi = 2**(1 - kint/2)*x**(kint - 1)*exp(-x**2/2)/gamma(kint/2) +chisquared = 2**(-k/2)/gamma(k/2)*x**(k/2 - 1)*exp(-x/2) +dagum = apos*p/x*(x/bpos)**(apos*p)/(1 + x**apos/bpos**apos)**(p + 1) +d1, d2 = symbols('d1 d2', positive=True) +f = sqrt(((d1*x)**d1 * d2**d2)/(d1*x + d2)**(d1 + d2))/x \ + /gamma(d1/2)/gamma(d2/2)*gamma((d1 + d2)/2) +nupos, sigmapos = symbols('nu sigma', positive=True) +rice = x/sigmapos**2*exp(-(x**2 + nupos**2)/2/sigmapos**2)*besseli(0, x* + nupos/sigmapos**2) +mu = Symbol('mu', real=True) +laplace = exp(-abs(x - mu)/bpos)/2/bpos + +u = Symbol('u', polar=True) +tpos = Symbol('t', positive=True) + + +def E(expr): + integrate(expr*exponential(x, rate)*normal(y, mu1, sigma1), + (x, 0, oo), (y, -oo, oo), meijerg=True) + integrate(expr*exponential(x, rate)*normal(y, mu1, sigma1), + (y, -oo, oo), (x, 0, oo), meijerg=True) + +bench = [ + 'MT(x**nu*Heaviside(x - 1), x, s)', + 'MT(x**nu*Heaviside(1 - x), x, s)', + 'MT((1-x)**(beta - 1)*Heaviside(1-x), x, s)', + 'MT((x-1)**(beta - 1)*Heaviside(x-1), x, s)', + 'MT((1+x)**(-rho), x, s)', + 'MT(abs(1-x)**(-rho), x, s)', + 'MT((1-x)**(beta-1)*Heaviside(1-x) + a*(x-1)**(beta-1)*Heaviside(x-1), x, s)', + 'MT((x**a-b**a)/(x-b), x, s)', + 'MT((x**a-bpos**a)/(x-bpos), x, s)', + 'MT(exp(-x), x, s)', + 'MT(exp(-1/x), x, s)', + 'MT(log(x)**4*Heaviside(1-x), x, s)', + 'MT(log(x)**3*Heaviside(x-1), x, s)', + 'MT(log(x + 1), x, s)', + 'MT(log(1/x + 1), x, s)', + 'MT(log(abs(1 - x)), x, s)', + 'MT(log(abs(1 - 1/x)), x, s)', + 'MT(log(x)/(x+1), x, s)', + 'MT(log(x)**2/(x+1), x, s)', + 'MT(log(x)/(x+1)**2, x, s)', + 'MT(erf(sqrt(x)), x, s)', + + 'MT(besselj(a, 2*sqrt(x)), x, s)', + 'MT(sin(sqrt(x))*besselj(a, sqrt(x)), x, s)', + 'MT(cos(sqrt(x))*besselj(a, sqrt(x)), x, s)', + 'MT(besselj(a, sqrt(x))**2, x, s)', + 'MT(besselj(a, sqrt(x))*besselj(-a, sqrt(x)), x, s)', + 'MT(besselj(a - 1, sqrt(x))*besselj(a, sqrt(x)), x, s)', + 'MT(besselj(a, sqrt(x))*besselj(b, sqrt(x)), x, s)', + 'MT(besselj(a, sqrt(x))**2 + besselj(-a, sqrt(x))**2, x, s)', + 'MT(bessely(a, 2*sqrt(x)), x, s)', + 'MT(sin(sqrt(x))*bessely(a, sqrt(x)), x, s)', + 'MT(cos(sqrt(x))*bessely(a, sqrt(x)), x, s)', + 'MT(besselj(a, sqrt(x))*bessely(a, sqrt(x)), x, s)', + 'MT(besselj(a, sqrt(x))*bessely(b, sqrt(x)), x, s)', + 'MT(bessely(a, sqrt(x))**2, x, s)', + + 'MT(besselk(a, 2*sqrt(x)), x, s)', + 'MT(besselj(a, 2*sqrt(2*sqrt(x)))*besselk(a, 2*sqrt(2*sqrt(x))), x, s)', + 'MT(besseli(a, sqrt(x))*besselk(a, sqrt(x)), x, s)', + 'MT(besseli(b, sqrt(x))*besselk(a, sqrt(x)), x, s)', + 'MT(exp(-x/2)*besselk(a, x/2), x, s)', + + # later: ILT, IMT + + 'LT((t-apos)**bpos*exp(-cpos*(t-apos))*Heaviside(t-apos), t, s)', + 'LT(t**apos, t, s)', + 'LT(Heaviside(t), t, s)', + 'LT(Heaviside(t - apos), t, s)', + 'LT(1 - exp(-apos*t), t, s)', + 'LT((exp(2*t)-1)*exp(-bpos - t)*Heaviside(t)/2, t, s, noconds=True)', + 'LT(exp(t), t, s)', + 'LT(exp(2*t), t, s)', + 'LT(exp(apos*t), t, s)', + 'LT(log(t/apos), t, s)', + 'LT(erf(t), t, s)', + 'LT(sin(apos*t), t, s)', + 'LT(cos(apos*t), t, s)', + 'LT(exp(-apos*t)*sin(bpos*t), t, s)', + 'LT(exp(-apos*t)*cos(bpos*t), t, s)', + 'LT(besselj(0, t), t, s, noconds=True)', + 'LT(besselj(1, t), t, s, noconds=True)', + + 'FT(Heaviside(1 - abs(2*apos*x)), x, k)', + 'FT(Heaviside(1-abs(apos*x))*(1-abs(apos*x)), x, k)', + 'FT(exp(-apos*x)*Heaviside(x), x, k)', + 'IFT(1/(apos + 2*pi*I*x), x, posk, noconds=False)', + 'IFT(1/(apos + 2*pi*I*x), x, -posk, noconds=False)', + 'IFT(1/(apos + 2*pi*I*x), x, negk)', + 'FT(x*exp(-apos*x)*Heaviside(x), x, k)', + 'FT(exp(-apos*x)*sin(bpos*x)*Heaviside(x), x, k)', + 'FT(exp(-apos*x**2), x, k)', + 'IFT(sqrt(pi/apos)*exp(-(pi*k)**2/apos), k, x)', + 'FT(exp(-apos*abs(x)), x, k)', + + 'integrate(normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True)', + 'integrate(x*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True)', + 'integrate(x**2*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True)', + 'integrate(x**3*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True)', + 'integrate(normal(x, mu1, sigma1)*normal(y, mu2, sigma2),' + ' (x, -oo, oo), (y, -oo, oo), meijerg=True)', + 'integrate(x*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),' + ' (x, -oo, oo), (y, -oo, oo), meijerg=True)', + 'integrate(y*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),' + ' (x, -oo, oo), (y, -oo, oo), meijerg=True)', + 'integrate(x*y*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),' + ' (x, -oo, oo), (y, -oo, oo), meijerg=True)', + 'integrate((x+y+1)*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),' + ' (x, -oo, oo), (y, -oo, oo), meijerg=True)', + 'integrate((x+y-1)*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),' + ' (x, -oo, oo), (y, -oo, oo), meijerg=True)', + 'integrate(x**2*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),' + ' (x, -oo, oo), (y, -oo, oo), meijerg=True)', + 'integrate(y**2*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),' + ' (x, -oo, oo), (y, -oo, oo), meijerg=True)', + 'integrate(exponential(x, rate), (x, 0, oo), meijerg=True)', + 'integrate(x*exponential(x, rate), (x, 0, oo), meijerg=True)', + 'integrate(x**2*exponential(x, rate), (x, 0, oo), meijerg=True)', + 'E(1)', + 'E(x*y)', + 'E(x*y**2)', + 'E((x+y+1)**2)', + 'E(x+y+1)', + 'E((x+y-1)**2)', + 'integrate(betadist, (x, 0, oo), meijerg=True)', + 'integrate(x*betadist, (x, 0, oo), meijerg=True)', + 'integrate(x**2*betadist, (x, 0, oo), meijerg=True)', + 'integrate(chi, (x, 0, oo), meijerg=True)', + 'integrate(x*chi, (x, 0, oo), meijerg=True)', + 'integrate(x**2*chi, (x, 0, oo), meijerg=True)', + 'integrate(chisquared, (x, 0, oo), meijerg=True)', + 'integrate(x*chisquared, (x, 0, oo), meijerg=True)', + 'integrate(x**2*chisquared, (x, 0, oo), meijerg=True)', + 'integrate(((x-k)/sqrt(2*k))**3*chisquared, (x, 0, oo), meijerg=True)', + 'integrate(dagum, (x, 0, oo), meijerg=True)', + 'integrate(x*dagum, (x, 0, oo), meijerg=True)', + 'integrate(x**2*dagum, (x, 0, oo), meijerg=True)', + 'integrate(f, (x, 0, oo), meijerg=True)', + 'integrate(x*f, (x, 0, oo), meijerg=True)', + 'integrate(x**2*f, (x, 0, oo), meijerg=True)', + 'integrate(rice, (x, 0, oo), meijerg=True)', + 'integrate(laplace, (x, -oo, oo), meijerg=True)', + 'integrate(x*laplace, (x, -oo, oo), meijerg=True)', + 'integrate(x**2*laplace, (x, -oo, oo), meijerg=True)', + 'integrate(log(x) * x**(k-1) * exp(-x) / gamma(k), (x, 0, oo))', + + 'integrate(sin(z*x)*(x**2-1)**(-(y+S(1)/2)), (x, 1, oo), meijerg=True)', + 'integrate(besselj(0,x)*besselj(1,x)*exp(-x**2), (x, 0, oo), meijerg=True)', + 'integrate(besselj(0,x)*besselj(1,x)*besselk(0,x), (x, 0, oo), meijerg=True)', + 'integrate(besselj(0,x)*besselj(1,x)*exp(-x**2), (x, 0, oo), meijerg=True)', + 'integrate(besselj(a,x)*besselj(b,x)/x, (x,0,oo), meijerg=True)', + + 'hyperexpand(meijerg((-s - a/2 + 1, -s + a/2 + 1), (-a/2 - S(1)/2, -s + a/2 + S(3)/2), (a/2, -a/2), (-a/2 - S(1)/2, -s + a/2 + S(3)/2), 1))', + "gammasimp(S('2**(2*s)*(-pi*gamma(-a + 1)*gamma(a + 1)*gamma(-a - s + 1)*gamma(-a + s - 1/2)*gamma(a - s + 3/2)*gamma(a + s + 1)/(a*(a + s)) - gamma(-a - 1/2)*gamma(-a + 1)*gamma(a + 1)*gamma(a + 3/2)*gamma(-s + 3/2)*gamma(s - 1/2)*gamma(-a + s + 1)*gamma(a - s + 1)/(a*(-a + s)))*gamma(-2*s + 1)*gamma(s + 1)/(pi*s*gamma(-a - 1/2)*gamma(a + 3/2)*gamma(-s + 1)*gamma(-s + 3/2)*gamma(s - 1/2)*gamma(-a - s + 1)*gamma(-a + s - 1/2)*gamma(a - s + 1)*gamma(a - s + 3/2))'))", + + 'mellin_transform(E1(x), x, s)', + 'inverse_mellin_transform(gamma(s)/s, s, x, (0, oo))', + 'mellin_transform(expint(a, x), x, s)', + 'mellin_transform(Si(x), x, s)', + 'inverse_mellin_transform(-2**s*sqrt(pi)*gamma((s + 1)/2)/(2*s*gamma(-s/2 + 1)), s, x, (-1, 0))', + 'mellin_transform(Ci(sqrt(x)), x, s)', + 'inverse_mellin_transform(-4**s*sqrt(pi)*gamma(s)/(2*s*gamma(-s + S(1)/2)),s, u, (0, 1))', + 'laplace_transform(Ci(x), x, s)', + 'laplace_transform(expint(a, x), x, s)', + 'laplace_transform(expint(1, x), x, s)', + 'laplace_transform(expint(2, x), x, s)', + 'inverse_laplace_transform(-log(1 + s**2)/2/s, s, u)', + 'inverse_laplace_transform(log(s + 1)/s, s, x)', + 'inverse_laplace_transform((s - log(s + 1))/s**2, s, x)', + 'laplace_transform(Chi(x), x, s)', + 'laplace_transform(Shi(x), x, s)', + + 'integrate(exp(-z*x)/x, (x, 1, oo), meijerg=True, conds="none")', + 'integrate(exp(-z*x)/x**2, (x, 1, oo), meijerg=True, conds="none")', + 'integrate(exp(-z*x)/x**3, (x, 1, oo), meijerg=True,conds="none")', + 'integrate(-cos(x)/x, (x, tpos, oo), meijerg=True)', + 'integrate(-sin(x)/x, (x, tpos, oo), meijerg=True)', + 'integrate(sin(x)/x, (x, 0, z), meijerg=True)', + 'integrate(sinh(x)/x, (x, 0, z), meijerg=True)', + 'integrate(exp(-x)/x, x, meijerg=True)', + 'integrate(exp(-x)/x**2, x, meijerg=True)', + 'integrate(cos(u)/u, u, meijerg=True)', + 'integrate(cosh(u)/u, u, meijerg=True)', + 'integrate(expint(1, x), x, meijerg=True)', + 'integrate(expint(2, x), x, meijerg=True)', + 'integrate(Si(x), x, meijerg=True)', + 'integrate(Ci(u), u, meijerg=True)', + 'integrate(Shi(x), x, meijerg=True)', + 'integrate(Chi(u), u, meijerg=True)', + 'integrate(Si(x)*exp(-x), (x, 0, oo), meijerg=True)', + 'integrate(expint(1, x)*sin(x), (x, 0, oo), meijerg=True)' +] + +from time import time +from sympy.core.cache import clear_cache +import sys + +timings = [] + +if __name__ == '__main__': + for n, string in enumerate(bench): + clear_cache() + _t = time() + exec(string) + _t = time() - _t + timings += [(_t, string)] + sys.stdout.write('.') + sys.stdout.flush() + if n % (len(bench) // 10) == 0: + sys.stdout.write('%s' % (10*n // len(bench))) + print() + + timings.sort(key=lambda x: -x[0]) + + for ti, string in timings: + print('%.2fs %s' % (ti, string)) diff --git a/.venv/lib/python3.12/site-packages/sympy/benchmarks/bench_symbench.py b/.venv/lib/python3.12/site-packages/sympy/benchmarks/bench_symbench.py new file mode 100644 index 0000000000000000000000000000000000000000..8ea700b44b677107f5345196a8895e8ed5a9d56d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/benchmarks/bench_symbench.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python +from sympy.core.random import random +from sympy.core.numbers import (I, Integer, pi) +from sympy.core.symbol import Symbol +from sympy.core.sympify import sympify +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import sin +from sympy.polys.polytools import factor +from sympy.simplify.simplify import simplify +from sympy.abc import x, y, z +from timeit import default_timer as clock + + +def bench_R1(): + "real(f(f(f(f(f(f(f(f(f(f(i/2)))))))))))" + def f(z): + return sqrt(Integer(1)/3)*z**2 + I/3 + f(f(f(f(f(f(f(f(f(f(I/2)))))))))).as_real_imag()[0] + + +def bench_R2(): + "Hermite polynomial hermite(15, y)" + def hermite(n, y): + if n == 1: + return 2*y + if n == 0: + return 1 + return (2*y*hermite(n - 1, y) - 2*(n - 1)*hermite(n - 2, y)).expand() + + hermite(15, y) + + +def bench_R3(): + "a = [bool(f==f) for _ in range(10)]" + f = x + y + z + [bool(f == f) for _ in range(10)] + + +def bench_R4(): + # we don't have Tuples + pass + + +def bench_R5(): + "blowup(L, 8); L=uniq(L)" + def blowup(L, n): + for i in range(n): + L.append( (L[i] + L[i + 1]) * L[i + 2] ) + + def uniq(x): + v = set(x) + return v + L = [x, y, z] + blowup(L, 8) + L = uniq(L) + + +def bench_R6(): + "sum(simplify((x+sin(i))/x+(x-sin(i))/x) for i in range(100))" + sum(simplify((x + sin(i))/x + (x - sin(i))/x) for i in range(100)) + + +def bench_R7(): + "[f.subs(x, random()) for _ in range(10**4)]" + f = x**24 + 34*x**12 + 45*x**3 + 9*x**18 + 34*x**10 + 32*x**21 + [f.subs(x, random()) for _ in range(10**4)] + + +def bench_R8(): + "right(x^2,0,5,10^4)" + def right(f, a, b, n): + a = sympify(a) + b = sympify(b) + n = sympify(n) + x = f.atoms(Symbol).pop() + Deltax = (b - a)/n + c = a + est = 0 + for i in range(n): + c += Deltax + est += f.subs(x, c) + return est*Deltax + + right(x**2, 0, 5, 10**4) + + +def _bench_R9(): + "factor(x^20 - pi^5*y^20)" + factor(x**20 - pi**5*y**20) + + +def bench_R10(): + "v = [-pi,-pi+1/10..,pi]" + def srange(min, max, step): + v = [min] + while (max - v[-1]).evalf() > 0: + v.append(v[-1] + step) + return v[:-1] + srange(-pi, pi, sympify(1)/10) + + +def bench_R11(): + "a = [random() + random()*I for w in [0..1000]]" + [random() + random()*I for w in range(1000)] + + +def bench_S1(): + "e=(x+y+z+1)**7;f=e*(e+1);f.expand()" + e = (x + y + z + 1)**7 + f = e*(e + 1) + f.expand() + + +if __name__ == '__main__': + benchmarks = [ + bench_R1, + bench_R2, + bench_R3, + bench_R5, + bench_R6, + bench_R7, + bench_R8, + #_bench_R9, + bench_R10, + bench_R11, + #bench_S1, + ] + + report = [] + for b in benchmarks: + t = clock() + b() + t = clock() - t + print("%s%65s: %f" % (b.__name__, b.__doc__, t)) diff --git a/.venv/lib/python3.12/site-packages/sympy/calculus/__init__.py b/.venv/lib/python3.12/site-packages/sympy/calculus/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..865c0556769e35ca7e8a09a4c208a1cfbd17369c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/calculus/__init__.py @@ -0,0 +1,25 @@ +"""Calculus-related methods.""" + +from .euler import euler_equations +from .singularities import (singularities, is_increasing, + is_strictly_increasing, is_decreasing, + is_strictly_decreasing, is_monotonic) +from .finite_diff import finite_diff_weights, apply_finite_diff, differentiate_finite +from .util import (periodicity, not_empty_in, is_convex, + stationary_points, minimum, maximum) +from .accumulationbounds import AccumBounds + +__all__ = [ +'euler_equations', + +'singularities', 'is_increasing', +'is_strictly_increasing', 'is_decreasing', +'is_strictly_decreasing', 'is_monotonic', + +'finite_diff_weights', 'apply_finite_diff', 'differentiate_finite', + +'periodicity', 'not_empty_in', 'is_convex', 'stationary_points', +'minimum', 'maximum', + +'AccumBounds' +] diff --git a/.venv/lib/python3.12/site-packages/sympy/calculus/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/calculus/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d3f99eedc8006b17253989511d9be1d32e954e20 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/calculus/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/calculus/__pycache__/accumulationbounds.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/calculus/__pycache__/accumulationbounds.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..227a80f97663ad6022228c63aef6b195a1b04239 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/calculus/__pycache__/accumulationbounds.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/calculus/__pycache__/euler.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/calculus/__pycache__/euler.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..130ac008462a099102ecb90ecb1bb6fef78ea557 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/calculus/__pycache__/euler.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/calculus/__pycache__/finite_diff.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/calculus/__pycache__/finite_diff.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc49f447ee1126cbdf366e20c00aebcec477a228 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/calculus/__pycache__/finite_diff.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/calculus/__pycache__/singularities.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/calculus/__pycache__/singularities.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef980813bedd8a5d626148969a9c75a739ce97eb Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/calculus/__pycache__/singularities.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/calculus/__pycache__/util.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/calculus/__pycache__/util.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6bd4edb03b49aef19bb7b36feec812b52e25b29 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/calculus/__pycache__/util.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/calculus/accumulationbounds.py b/.venv/lib/python3.12/site-packages/sympy/calculus/accumulationbounds.py new file mode 100644 index 0000000000000000000000000000000000000000..8a2b0e634da1028c25399c8b03884865d981a56e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/calculus/accumulationbounds.py @@ -0,0 +1,804 @@ +from sympy.core import Add, Mul, Pow, S +from sympy.core.basic import Basic +from sympy.core.expr import Expr +from sympy.core.numbers import _sympifyit, oo, zoo +from sympy.core.relational import is_le, is_lt, is_ge, is_gt +from sympy.core.sympify import _sympify +from sympy.functions.elementary.miscellaneous import Min, Max +from sympy.logic.boolalg import And +from sympy.multipledispatch import dispatch +from sympy.series.order import Order +from sympy.sets.sets import FiniteSet + + +class AccumulationBounds(Expr): + r"""An accumulation bounds. + + # Note AccumulationBounds has an alias: AccumBounds + + AccumulationBounds represent an interval `[a, b]`, which is always closed + at the ends. Here `a` and `b` can be any value from extended real numbers. + + The intended meaning of AccummulationBounds is to give an approximate + location of the accumulation points of a real function at a limit point. + + Let `a` and `b` be reals such that `a \le b`. + + `\left\langle a, b\right\rangle = \{x \in \mathbb{R} \mid a \le x \le b\}` + + `\left\langle -\infty, b\right\rangle = \{x \in \mathbb{R} \mid x \le b\} \cup \{-\infty, \infty\}` + + `\left\langle a, \infty \right\rangle = \{x \in \mathbb{R} \mid a \le x\} \cup \{-\infty, \infty\}` + + `\left\langle -\infty, \infty \right\rangle = \mathbb{R} \cup \{-\infty, \infty\}` + + ``oo`` and ``-oo`` are added to the second and third definition respectively, + since if either ``-oo`` or ``oo`` is an argument, then the other one should + be included (though not as an end point). This is forced, since we have, + for example, ``1/AccumBounds(0, 1) = AccumBounds(1, oo)``, and the limit at + `0` is not one-sided. As `x` tends to `0-`, then `1/x \rightarrow -\infty`, so `-\infty` + should be interpreted as belonging to ``AccumBounds(1, oo)`` though it need + not appear explicitly. + + In many cases it suffices to know that the limit set is bounded. + However, in some other cases more exact information could be useful. + For example, all accumulation values of `\cos(x) + 1` are non-negative. + (``AccumBounds(-1, 1) + 1 = AccumBounds(0, 2)``) + + A AccumulationBounds object is defined to be real AccumulationBounds, + if its end points are finite reals. + + Let `X`, `Y` be real AccumulationBounds, then their sum, difference, + product are defined to be the following sets: + + `X + Y = \{ x+y \mid x \in X \cap y \in Y\}` + + `X - Y = \{ x-y \mid x \in X \cap y \in Y\}` + + `X \times Y = \{ x \times y \mid x \in X \cap y \in Y\}` + + When an AccumBounds is raised to a negative power, if 0 is contained + between the bounds then an infinite range is returned, otherwise if an + endpoint is 0 then a semi-infinite range with consistent sign will be returned. + + AccumBounds in expressions behave a lot like Intervals but the + semantics are not necessarily the same. Division (or exponentiation + to a negative integer power) could be handled with *intervals* by + returning a union of the results obtained after splitting the + bounds between negatives and positives, but that is not done with + AccumBounds. In addition, bounds are assumed to be independent of + each other; if the same bound is used in more than one place in an + expression, the result may not be the supremum or infimum of the + expression (see below). Finally, when a boundary is ``1``, + exponentiation to the power of ``oo`` yields ``oo``, neither + ``1`` nor ``nan``. + + Examples + ======== + + >>> from sympy import AccumBounds, sin, exp, log, pi, E, S, oo + >>> from sympy.abc import x + + >>> AccumBounds(0, 1) + AccumBounds(1, 2) + AccumBounds(1, 3) + + >>> AccumBounds(0, 1) - AccumBounds(0, 2) + AccumBounds(-2, 1) + + >>> AccumBounds(-2, 3)*AccumBounds(-1, 1) + AccumBounds(-3, 3) + + >>> AccumBounds(1, 2)*AccumBounds(3, 5) + AccumBounds(3, 10) + + The exponentiation of AccumulationBounds is defined + as follows: + + If 0 does not belong to `X` or `n > 0` then + + `X^n = \{ x^n \mid x \in X\}` + + >>> AccumBounds(1, 4)**(S(1)/2) + AccumBounds(1, 2) + + otherwise, an infinite or semi-infinite result is obtained: + + >>> 1/AccumBounds(-1, 1) + AccumBounds(-oo, oo) + >>> 1/AccumBounds(0, 2) + AccumBounds(1/2, oo) + >>> 1/AccumBounds(-oo, 0) + AccumBounds(-oo, 0) + + A boundary of 1 will always generate all nonnegatives: + + >>> AccumBounds(1, 2)**oo + AccumBounds(0, oo) + >>> AccumBounds(0, 1)**oo + AccumBounds(0, oo) + + If the exponent is itself an AccumulationBounds or is not an + integer then unevaluated results will be returned unless the base + values are positive: + + >>> AccumBounds(2, 3)**AccumBounds(-1, 2) + AccumBounds(1/3, 9) + >>> AccumBounds(-2, 3)**AccumBounds(-1, 2) + AccumBounds(-2, 3)**AccumBounds(-1, 2) + + >>> AccumBounds(-2, -1)**(S(1)/2) + sqrt(AccumBounds(-2, -1)) + + Note: `\left\langle a, b\right\rangle^2` is not same as `\left\langle a, b\right\rangle \times \left\langle a, b\right\rangle` + + >>> AccumBounds(-1, 1)**2 + AccumBounds(0, 1) + + >>> AccumBounds(1, 3) < 4 + True + + >>> AccumBounds(1, 3) < -1 + False + + Some elementary functions can also take AccumulationBounds as input. + A function `f` evaluated for some real AccumulationBounds `\left\langle a, b \right\rangle` + is defined as `f(\left\langle a, b\right\rangle) = \{ f(x) \mid a \le x \le b \}` + + >>> sin(AccumBounds(pi/6, pi/3)) + AccumBounds(1/2, sqrt(3)/2) + + >>> exp(AccumBounds(0, 1)) + AccumBounds(1, E) + + >>> log(AccumBounds(1, E)) + AccumBounds(0, 1) + + Some symbol in an expression can be substituted for a AccumulationBounds + object. But it does not necessarily evaluate the AccumulationBounds for + that expression. + + The same expression can be evaluated to different values depending upon + the form it is used for substitution since each instance of an + AccumulationBounds is considered independent. For example: + + >>> (x**2 + 2*x + 1).subs(x, AccumBounds(-1, 1)) + AccumBounds(-1, 4) + + >>> ((x + 1)**2).subs(x, AccumBounds(-1, 1)) + AccumBounds(0, 4) + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Interval_arithmetic + + .. [2] https://fab.cba.mit.edu/classes/S62.12/docs/Hickey_interval.pdf + + Notes + ===== + + Do not use ``AccumulationBounds`` for floating point interval arithmetic + calculations, use ``mpmath.iv`` instead. + """ + + is_extended_real = True + is_number = False + + def __new__(cls, min, max) -> Expr: # type: ignore + + min = _sympify(min) + max = _sympify(max) + + # Only allow real intervals (use symbols with 'is_extended_real=True'). + if not min.is_extended_real or not max.is_extended_real: + raise ValueError("Only real AccumulationBounds are supported") + + if max == min: + return max + + # Make sure that the created AccumBounds object will be valid. + if max.is_number and min.is_number: + bad = max.is_comparable and min.is_comparable and max < min + else: + bad = (max - min).is_extended_negative + if bad: + raise ValueError( + "Lower limit should be smaller than upper limit") + + return Basic.__new__(cls, min, max) + + # setting the operation priority + _op_priority = 11.0 + + def _eval_is_real(self): + if self.min.is_real and self.max.is_real: + return True + + @property + def min(self): + """ + Returns the minimum possible value attained by AccumulationBounds + object. + + Examples + ======== + + >>> from sympy import AccumBounds + >>> AccumBounds(1, 3).min + 1 + + """ + return self.args[0] + + @property + def max(self): + """ + Returns the maximum possible value attained by AccumulationBounds + object. + + Examples + ======== + + >>> from sympy import AccumBounds + >>> AccumBounds(1, 3).max + 3 + + """ + return self.args[1] + + @property + def delta(self): + """ + Returns the difference of maximum possible value attained by + AccumulationBounds object and minimum possible value attained + by AccumulationBounds object. + + Examples + ======== + + >>> from sympy import AccumBounds + >>> AccumBounds(1, 3).delta + 2 + + """ + return self.max - self.min + + @property + def mid(self): + """ + Returns the mean of maximum possible value attained by + AccumulationBounds object and minimum possible value + attained by AccumulationBounds object. + + Examples + ======== + + >>> from sympy import AccumBounds + >>> AccumBounds(1, 3).mid + 2 + + """ + return (self.min + self.max) / 2 + + @_sympifyit('other', NotImplemented) + def _eval_power(self, other): + return self.__pow__(other) + + @_sympifyit('other', NotImplemented) + def __add__(self, other): + if isinstance(other, Expr): + if isinstance(other, AccumBounds): + return AccumBounds( + Add(self.min, other.min), + Add(self.max, other.max)) + if other is S.Infinity and self.min is S.NegativeInfinity or \ + other is S.NegativeInfinity and self.max is S.Infinity: + return AccumBounds(-oo, oo) + elif other.is_extended_real: + if self.min is S.NegativeInfinity and self.max is S.Infinity: + return AccumBounds(-oo, oo) + elif self.min is S.NegativeInfinity: + return AccumBounds(-oo, self.max + other) + elif self.max is S.Infinity: + return AccumBounds(self.min + other, oo) + else: + return AccumBounds(Add(self.min, other), Add(self.max, other)) + return Add(self, other, evaluate=False) + return NotImplemented + + __radd__ = __add__ + + def __neg__(self): + return AccumBounds(-self.max, -self.min) + + @_sympifyit('other', NotImplemented) + def __sub__(self, other): + if isinstance(other, Expr): + if isinstance(other, AccumBounds): + return AccumBounds( + Add(self.min, -other.max), + Add(self.max, -other.min)) + if other is S.NegativeInfinity and self.min is S.NegativeInfinity or \ + other is S.Infinity and self.max is S.Infinity: + return AccumBounds(-oo, oo) + elif other.is_extended_real: + if self.min is S.NegativeInfinity and self.max is S.Infinity: + return AccumBounds(-oo, oo) + elif self.min is S.NegativeInfinity: + return AccumBounds(-oo, self.max - other) + elif self.max is S.Infinity: + return AccumBounds(self.min - other, oo) + else: + return AccumBounds( + Add(self.min, -other), + Add(self.max, -other)) + return Add(self, -other, evaluate=False) + return NotImplemented + + @_sympifyit('other', NotImplemented) + def __rsub__(self, other): + return self.__neg__() + other + + @_sympifyit('other', NotImplemented) + def __mul__(self, other): + if self.args == (-oo, oo): + return self + if isinstance(other, Expr): + if isinstance(other, AccumBounds): + if other.args == (-oo, oo): + return other + v = set() + for a in self.args: + vi = other*a + v.update(vi.args or (vi,)) + return AccumBounds(Min(*v), Max(*v)) + if other is S.Infinity: + if self.min.is_zero: + return AccumBounds(0, oo) + if self.max.is_zero: + return AccumBounds(-oo, 0) + if other is S.NegativeInfinity: + if self.min.is_zero: + return AccumBounds(-oo, 0) + if self.max.is_zero: + return AccumBounds(0, oo) + if other.is_extended_real: + if other.is_zero: + if self.max is S.Infinity: + return AccumBounds(0, oo) + if self.min is S.NegativeInfinity: + return AccumBounds(-oo, 0) + return S.Zero + if other.is_extended_positive: + return AccumBounds( + Mul(self.min, other), + Mul(self.max, other)) + elif other.is_extended_negative: + return AccumBounds( + Mul(self.max, other), + Mul(self.min, other)) + if isinstance(other, Order): + return other + return Mul(self, other, evaluate=False) + return NotImplemented + + __rmul__ = __mul__ + + @_sympifyit('other', NotImplemented) + def __truediv__(self, other): + if isinstance(other, Expr): + if isinstance(other, AccumBounds): + if other.min.is_positive or other.max.is_negative: + return self * AccumBounds(1/other.max, 1/other.min) + + if (self.min.is_extended_nonpositive and self.max.is_extended_nonnegative and + other.min.is_extended_nonpositive and other.max.is_extended_nonnegative): + if self.min.is_zero and other.min.is_zero: + return AccumBounds(0, oo) + if self.max.is_zero and other.min.is_zero: + return AccumBounds(-oo, 0) + return AccumBounds(-oo, oo) + + if self.max.is_extended_negative: + if other.min.is_extended_negative: + if other.max.is_zero: + return AccumBounds(self.max / other.min, oo) + if other.max.is_extended_positive: + # if we were dealing with intervals we would return + # Union(Interval(-oo, self.max/other.max), + # Interval(self.max/other.min, oo)) + return AccumBounds(-oo, oo) + + if other.min.is_zero and other.max.is_extended_positive: + return AccumBounds(-oo, self.max / other.max) + + if self.min.is_extended_positive: + if other.min.is_extended_negative: + if other.max.is_zero: + return AccumBounds(-oo, self.min / other.min) + if other.max.is_extended_positive: + # if we were dealing with intervals we would return + # Union(Interval(-oo, self.min/other.min), + # Interval(self.min/other.max, oo)) + return AccumBounds(-oo, oo) + + if other.min.is_zero and other.max.is_extended_positive: + return AccumBounds(self.min / other.max, oo) + + elif other.is_extended_real: + if other in (S.Infinity, S.NegativeInfinity): + if self == AccumBounds(-oo, oo): + return AccumBounds(-oo, oo) + if self.max is S.Infinity: + return AccumBounds(Min(0, other), Max(0, other)) + if self.min is S.NegativeInfinity: + return AccumBounds(Min(0, -other), Max(0, -other)) + if other.is_extended_positive: + return AccumBounds(self.min / other, self.max / other) + elif other.is_extended_negative: + return AccumBounds(self.max / other, self.min / other) + if (1 / other) is S.ComplexInfinity: + return Mul(self, 1 / other, evaluate=False) + else: + return Mul(self, 1 / other) + + return NotImplemented + + @_sympifyit('other', NotImplemented) + def __rtruediv__(self, other): + if isinstance(other, Expr): + if other.is_extended_real: + if other.is_zero: + return S.Zero + if (self.min.is_extended_nonpositive and self.max.is_extended_nonnegative): + if self.min.is_zero: + if other.is_extended_positive: + return AccumBounds(Mul(other, 1 / self.max), oo) + if other.is_extended_negative: + return AccumBounds(-oo, Mul(other, 1 / self.max)) + if self.max.is_zero: + if other.is_extended_positive: + return AccumBounds(-oo, Mul(other, 1 / self.min)) + if other.is_extended_negative: + return AccumBounds(Mul(other, 1 / self.min), oo) + return AccumBounds(-oo, oo) + else: + return AccumBounds(Min(other / self.min, other / self.max), + Max(other / self.min, other / self.max)) + return Mul(other, 1 / self, evaluate=False) + else: + return NotImplemented + + @_sympifyit('other', NotImplemented) + def __pow__(self, other): + if isinstance(other, Expr): + if other is S.Infinity: + if self.min.is_extended_nonnegative: + if self.max < 1: + return S.Zero + if self.min > 1: + return S.Infinity + return AccumBounds(0, oo) + elif self.max.is_extended_negative: + if self.min > -1: + return S.Zero + if self.max < -1: + return zoo + return S.NaN + else: + if self.min > -1: + if self.max < 1: + return S.Zero + return AccumBounds(0, oo) + return AccumBounds(-oo, oo) + + if other is S.NegativeInfinity: + return (1/self)**oo + + # generically true + if (self.max - self.min).is_nonnegative: + # well defined + if self.min.is_nonnegative: + # no 0 to worry about + if other.is_nonnegative: + # no infinity to worry about + return self.func(self.min**other, self.max**other) + + if other.is_zero: + return S.One # x**0 = 1 + + if other.is_Integer or other.is_integer: + if self.min.is_extended_positive: + return AccumBounds( + Min(self.min**other, self.max**other), + Max(self.min**other, self.max**other)) + elif self.max.is_extended_negative: + return AccumBounds( + Min(self.max**other, self.min**other), + Max(self.max**other, self.min**other)) + + if other % 2 == 0: + if other.is_extended_negative: + if self.min.is_zero: + return AccumBounds(self.max**other, oo) + if self.max.is_zero: + return AccumBounds(self.min**other, oo) + return (1/self)**(-other) + return AccumBounds( + S.Zero, Max(self.min**other, self.max**other)) + elif other % 2 == 1: + if other.is_extended_negative: + if self.min.is_zero: + return AccumBounds(self.max**other, oo) + if self.max.is_zero: + return AccumBounds(-oo, self.min**other) + return (1/self)**(-other) + return AccumBounds(self.min**other, self.max**other) + + # non-integer exponent + # 0**neg or neg**frac yields complex + if (other.is_number or other.is_rational) and ( + self.min.is_extended_nonnegative or ( + other.is_extended_nonnegative and + self.min.is_extended_nonnegative)): + num, den = other.as_numer_denom() + if num is S.One: + return AccumBounds(*[i**(1/den) for i in self.args]) + + elif den is not S.One: # e.g. if other is not Float + return (self**num)**(1/den) # ok for non-negative base + + if isinstance(other, AccumBounds): + if (self.min.is_extended_positive or + self.min.is_extended_nonnegative and + other.min.is_extended_nonnegative): + p = [self**i for i in other.args] + if not any(i.is_Pow for i in p): + a = [j for i in p for j in i.args or (i,)] + try: + return self.func(min(a), max(a)) + except TypeError: # can't sort + pass + + return Pow(self, other, evaluate=False) + + return NotImplemented + + @_sympifyit('other', NotImplemented) + def __rpow__(self, other): + if other.is_real and other.is_extended_nonnegative and ( + self.max - self.min).is_extended_positive: + if other is S.One: + return S.One + if other.is_extended_positive: + a, b = [other**i for i in self.args] + if min(a, b) != a: + a, b = b, a + return self.func(a, b) + if other.is_zero: + if self.min.is_zero: + return self.func(0, 1) + if self.min.is_extended_positive: + return S.Zero + + return Pow(other, self, evaluate=False) + + def __abs__(self): + if self.max.is_extended_negative: + return self.__neg__() + elif self.min.is_extended_negative: + return AccumBounds(S.Zero, Max(abs(self.min), self.max)) + else: + return self + + + def __contains__(self, other): + """ + Returns ``True`` if other is contained in self, where other + belongs to extended real numbers, ``False`` if not contained, + otherwise TypeError is raised. + + Examples + ======== + + >>> from sympy import AccumBounds, oo + >>> 1 in AccumBounds(-1, 3) + True + + -oo and oo go together as limits (in AccumulationBounds). + + >>> -oo in AccumBounds(1, oo) + True + + >>> oo in AccumBounds(-oo, 0) + True + + """ + other = _sympify(other) + + if other in (S.Infinity, S.NegativeInfinity): + if self.min is S.NegativeInfinity or self.max is S.Infinity: + return True + return False + + rv = And(self.min <= other, self.max >= other) + if rv not in (True, False): + raise TypeError("input failed to evaluate") + return rv + + def intersection(self, other): + """ + Returns the intersection of 'self' and 'other'. + Here other can be an instance of :py:class:`~.FiniteSet` or AccumulationBounds. + + Parameters + ========== + + other : AccumulationBounds + Another AccumulationBounds object with which the intersection + has to be computed. + + Returns + ======= + + AccumulationBounds + Intersection of ``self`` and ``other``. + + Examples + ======== + + >>> from sympy import AccumBounds, FiniteSet + >>> AccumBounds(1, 3).intersection(AccumBounds(2, 4)) + AccumBounds(2, 3) + + >>> AccumBounds(1, 3).intersection(AccumBounds(4, 6)) + EmptySet + + >>> AccumBounds(1, 4).intersection(FiniteSet(1, 2, 5)) + {1, 2} + + """ + if not isinstance(other, (AccumBounds, FiniteSet)): + raise TypeError( + "Input must be AccumulationBounds or FiniteSet object") + + if isinstance(other, FiniteSet): + fin_set = S.EmptySet + for i in other: + if i in self: + fin_set = fin_set + FiniteSet(i) + return fin_set + + if self.max < other.min or self.min > other.max: + return S.EmptySet + + if self.min <= other.min: + if self.max <= other.max: + return AccumBounds(other.min, self.max) + if self.max > other.max: + return other + + if other.min <= self.min: + if other.max < self.max: + return AccumBounds(self.min, other.max) + if other.max > self.max: + return self + + def union(self, other): + # TODO : Devise a better method for Union of AccumBounds + # this method is not actually correct and + # can be made better + if not isinstance(other, AccumBounds): + raise TypeError( + "Input must be AccumulationBounds or FiniteSet object") + + if self.min <= other.min and self.max >= other.min: + return AccumBounds(self.min, Max(self.max, other.max)) + + if other.min <= self.min and other.max >= self.min: + return AccumBounds(other.min, Max(self.max, other.max)) + + +@dispatch(AccumulationBounds, AccumulationBounds) # type: ignore # noqa:F811 +def _eval_is_le(lhs, rhs): # noqa:F811 + if is_le(lhs.max, rhs.min): + return True + if is_gt(lhs.min, rhs.max): + return False + + +@dispatch(AccumulationBounds, Basic) # type: ignore # noqa:F811 +def _eval_is_le(lhs, rhs): # noqa: F811 + + """ + Returns ``True `` if range of values attained by ``lhs`` AccumulationBounds + object is greater than the range of values attained by ``rhs``, + where ``rhs`` may be any value of type AccumulationBounds object or + extended real number value, ``False`` if ``rhs`` satisfies + the same property, else an unevaluated :py:class:`~.Relational`. + + Examples + ======== + + >>> from sympy import AccumBounds, oo + >>> AccumBounds(1, 3) > AccumBounds(4, oo) + False + >>> AccumBounds(1, 4) > AccumBounds(3, 4) + AccumBounds(1, 4) > AccumBounds(3, 4) + >>> AccumBounds(1, oo) > -1 + True + + """ + if not rhs.is_extended_real: + raise TypeError( + "Invalid comparison of %s %s" % + (type(rhs), rhs)) + elif rhs.is_comparable: + if is_le(lhs.max, rhs): + return True + if is_gt(lhs.min, rhs): + return False + + +@dispatch(AccumulationBounds, AccumulationBounds) +def _eval_is_ge(lhs, rhs): # noqa:F811 + if is_ge(lhs.min, rhs.max): + return True + if is_lt(lhs.max, rhs.min): + return False + + +@dispatch(AccumulationBounds, Expr) # type:ignore +def _eval_is_ge(lhs, rhs): # noqa: F811 + """ + Returns ``True`` if range of values attained by ``lhs`` AccumulationBounds + object is less that the range of values attained by ``rhs``, where + other may be any value of type AccumulationBounds object or extended + real number value, ``False`` if ``rhs`` satisfies the same + property, else an unevaluated :py:class:`~.Relational`. + + Examples + ======== + + >>> from sympy import AccumBounds, oo + >>> AccumBounds(1, 3) >= AccumBounds(4, oo) + False + >>> AccumBounds(1, 4) >= AccumBounds(3, 4) + AccumBounds(1, 4) >= AccumBounds(3, 4) + >>> AccumBounds(1, oo) >= 1 + True + """ + + if not rhs.is_extended_real: + raise TypeError( + "Invalid comparison of %s %s" % + (type(rhs), rhs)) + elif rhs.is_comparable: + if is_ge(lhs.min, rhs): + return True + if is_lt(lhs.max, rhs): + return False + + +@dispatch(Expr, AccumulationBounds) # type:ignore +def _eval_is_ge(lhs, rhs): # noqa:F811 + if not lhs.is_extended_real: + raise TypeError( + "Invalid comparison of %s %s" % + (type(lhs), lhs)) + elif lhs.is_comparable: + if is_le(rhs.max, lhs): + return True + if is_gt(rhs.min, lhs): + return False + + +@dispatch(AccumulationBounds, AccumulationBounds) # type:ignore +def _eval_is_ge(lhs, rhs): # noqa:F811 + if is_ge(lhs.min, rhs.max): + return True + if is_lt(lhs.max, rhs.min): + return False + +# setting an alias for AccumulationBounds +AccumBounds = AccumulationBounds diff --git a/.venv/lib/python3.12/site-packages/sympy/calculus/euler.py b/.venv/lib/python3.12/site-packages/sympy/calculus/euler.py new file mode 100644 index 0000000000000000000000000000000000000000..817acf76091dfba2dba40487ca7735e307c0fc15 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/calculus/euler.py @@ -0,0 +1,108 @@ +""" +This module implements a method to find +Euler-Lagrange Equations for given Lagrangian. +""" +from itertools import combinations_with_replacement +from sympy.core.function import (Derivative, Function, diff) +from sympy.core.relational import Eq +from sympy.core.singleton import S +from sympy.core.symbol import Symbol +from sympy.core.sympify import sympify +from sympy.utilities.iterables import iterable + + +def euler_equations(L, funcs=(), vars=()): + r""" + Find the Euler-Lagrange equations [1]_ for a given Lagrangian. + + Parameters + ========== + + L : Expr + The Lagrangian that should be a function of the functions listed + in the second argument and their derivatives. + + For example, in the case of two functions $f(x,y)$, $g(x,y)$ and + two independent variables $x$, $y$ the Lagrangian has the form: + + .. math:: L\left(f(x,y),g(x,y),\frac{\partial f(x,y)}{\partial x}, + \frac{\partial f(x,y)}{\partial y}, + \frac{\partial g(x,y)}{\partial x}, + \frac{\partial g(x,y)}{\partial y},x,y\right) + + In many cases it is not necessary to provide anything, except the + Lagrangian, it will be auto-detected (and an error raised if this + cannot be done). + + funcs : Function or an iterable of Functions + The functions that the Lagrangian depends on. The Euler equations + are differential equations for each of these functions. + + vars : Symbol or an iterable of Symbols + The Symbols that are the independent variables of the functions. + + Returns + ======= + + eqns : list of Eq + The list of differential equations, one for each function. + + Examples + ======== + + >>> from sympy import euler_equations, Symbol, Function + >>> x = Function('x') + >>> t = Symbol('t') + >>> L = (x(t).diff(t))**2/2 - x(t)**2/2 + >>> euler_equations(L, x(t), t) + [Eq(-x(t) - Derivative(x(t), (t, 2)), 0)] + >>> u = Function('u') + >>> x = Symbol('x') + >>> L = (u(t, x).diff(t))**2/2 - (u(t, x).diff(x))**2/2 + >>> euler_equations(L, u(t, x), [t, x]) + [Eq(-Derivative(u(t, x), (t, 2)) + Derivative(u(t, x), (x, 2)), 0)] + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Euler%E2%80%93Lagrange_equation + + """ + + funcs = tuple(funcs) if iterable(funcs) else (funcs,) + + if not funcs: + funcs = tuple(L.atoms(Function)) + else: + for f in funcs: + if not isinstance(f, Function): + raise TypeError('Function expected, got: %s' % f) + + vars = tuple(vars) if iterable(vars) else (vars,) + + if not vars: + vars = funcs[0].args + else: + vars = tuple(sympify(var) for var in vars) + + if not all(isinstance(v, Symbol) for v in vars): + raise TypeError('Variables are not symbols, got %s' % vars) + + for f in funcs: + if not vars == f.args: + raise ValueError("Variables %s do not match args: %s" % (vars, f)) + + order = max([len(d.variables) for d in L.atoms(Derivative) + if d.expr in funcs] + [0]) + + eqns = [] + for f in funcs: + eq = diff(L, f) + for i in range(1, order + 1): + for p in combinations_with_replacement(vars, i): + eq = eq + S.NegativeOne**i*diff(L, diff(f, *p), *p) + new_eq = Eq(eq, 0) + if isinstance(new_eq, Eq): + eqns.append(new_eq) + + return eqns diff --git a/.venv/lib/python3.12/site-packages/sympy/calculus/finite_diff.py b/.venv/lib/python3.12/site-packages/sympy/calculus/finite_diff.py new file mode 100644 index 0000000000000000000000000000000000000000..17eece149aadad236cefeb350e1ef4a383c84f01 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/calculus/finite_diff.py @@ -0,0 +1,476 @@ +""" +Finite difference weights +========================= + +This module implements an algorithm for efficient generation of finite +difference weights for ordinary differentials of functions for +derivatives from 0 (interpolation) up to arbitrary order. + +The core algorithm is provided in the finite difference weight generating +function (``finite_diff_weights``), and two convenience functions are provided +for: + +- estimating a derivative (or interpolate) directly from a series of points + is also provided (``apply_finite_diff``). +- differentiating by using finite difference approximations + (``differentiate_finite``). + +""" + +from sympy.core.function import Derivative +from sympy.core.singleton import S +from sympy.core.function import Subs +from sympy.core.traversal import preorder_traversal +from sympy.utilities.exceptions import sympy_deprecation_warning +from sympy.utilities.iterables import iterable + + + +def finite_diff_weights(order, x_list, x0=S.One): + """ + Calculates the finite difference weights for an arbitrarily spaced + one-dimensional grid (``x_list``) for derivatives at ``x0`` of order + 0, 1, ..., up to ``order`` using a recursive formula. Order of accuracy + is at least ``len(x_list) - order``, if ``x_list`` is defined correctly. + + Parameters + ========== + + order: int + Up to what derivative order weights should be calculated. + 0 corresponds to interpolation. + x_list: sequence + Sequence of (unique) values for the independent variable. + It is useful (but not necessary) to order ``x_list`` from + nearest to furthest from ``x0``; see examples below. + x0: Number or Symbol + Root or value of the independent variable for which the finite + difference weights should be generated. Default is ``S.One``. + + Returns + ======= + + list + A list of sublists, each corresponding to coefficients for + increasing derivative order, and each containing lists of + coefficients for increasing subsets of x_list. + + Examples + ======== + + >>> from sympy import finite_diff_weights, S + >>> res = finite_diff_weights(1, [-S(1)/2, S(1)/2, S(3)/2, S(5)/2], 0) + >>> res + [[[1, 0, 0, 0], + [1/2, 1/2, 0, 0], + [3/8, 3/4, -1/8, 0], + [5/16, 15/16, -5/16, 1/16]], + [[0, 0, 0, 0], + [-1, 1, 0, 0], + [-1, 1, 0, 0], + [-23/24, 7/8, 1/8, -1/24]]] + >>> res[0][-1] # FD weights for 0th derivative, using full x_list + [5/16, 15/16, -5/16, 1/16] + >>> res[1][-1] # FD weights for 1st derivative + [-23/24, 7/8, 1/8, -1/24] + >>> res[1][-2] # FD weights for 1st derivative, using x_list[:-1] + [-1, 1, 0, 0] + >>> res[1][-1][0] # FD weight for 1st deriv. for x_list[0] + -23/24 + >>> res[1][-1][1] # FD weight for 1st deriv. for x_list[1], etc. + 7/8 + + Each sublist contains the most accurate formula at the end. + Note, that in the above example ``res[1][1]`` is the same as ``res[1][2]``. + Since res[1][2] has an order of accuracy of + ``len(x_list[:3]) - order = 3 - 1 = 2``, the same is true for ``res[1][1]``! + + >>> res = finite_diff_weights(1, [S(0), S(1), -S(1), S(2), -S(2)], 0)[1] + >>> res + [[0, 0, 0, 0, 0], + [-1, 1, 0, 0, 0], + [0, 1/2, -1/2, 0, 0], + [-1/2, 1, -1/3, -1/6, 0], + [0, 2/3, -2/3, -1/12, 1/12]] + >>> res[0] # no approximation possible, using x_list[0] only + [0, 0, 0, 0, 0] + >>> res[1] # classic forward step approximation + [-1, 1, 0, 0, 0] + >>> res[2] # classic centered approximation + [0, 1/2, -1/2, 0, 0] + >>> res[3:] # higher order approximations + [[-1/2, 1, -1/3, -1/6, 0], [0, 2/3, -2/3, -1/12, 1/12]] + + Let us compare this to a differently defined ``x_list``. Pay attention to + ``foo[i][k]`` corresponding to the gridpoint defined by ``x_list[k]``. + + >>> foo = finite_diff_weights(1, [-S(2), -S(1), S(0), S(1), S(2)], 0)[1] + >>> foo + [[0, 0, 0, 0, 0], + [-1, 1, 0, 0, 0], + [1/2, -2, 3/2, 0, 0], + [1/6, -1, 1/2, 1/3, 0], + [1/12, -2/3, 0, 2/3, -1/12]] + >>> foo[1] # not the same and of lower accuracy as res[1]! + [-1, 1, 0, 0, 0] + >>> foo[2] # classic double backward step approximation + [1/2, -2, 3/2, 0, 0] + >>> foo[4] # the same as res[4] + [1/12, -2/3, 0, 2/3, -1/12] + + Note that, unless you plan on using approximations based on subsets of + ``x_list``, the order of gridpoints does not matter. + + The capability to generate weights at arbitrary points can be + used e.g. to minimize Runge's phenomenon by using Chebyshev nodes: + + >>> from sympy import cos, symbols, pi, simplify + >>> N, (h, x) = 4, symbols('h x') + >>> x_list = [x+h*cos(i*pi/(N)) for i in range(N,-1,-1)] # chebyshev nodes + >>> print(x_list) + [-h + x, -sqrt(2)*h/2 + x, x, sqrt(2)*h/2 + x, h + x] + >>> mycoeffs = finite_diff_weights(1, x_list, 0)[1][4] + >>> [simplify(c) for c in mycoeffs] #doctest: +NORMALIZE_WHITESPACE + [(h**3/2 + h**2*x - 3*h*x**2 - 4*x**3)/h**4, + (-sqrt(2)*h**3 - 4*h**2*x + 3*sqrt(2)*h*x**2 + 8*x**3)/h**4, + (6*h**2*x - 8*x**3)/h**4, + (sqrt(2)*h**3 - 4*h**2*x - 3*sqrt(2)*h*x**2 + 8*x**3)/h**4, + (-h**3/2 + h**2*x + 3*h*x**2 - 4*x**3)/h**4] + + Notes + ===== + + If weights for a finite difference approximation of 3rd order + derivative is wanted, weights for 0th, 1st and 2nd order are + calculated "for free", so are formulae using subsets of ``x_list``. + This is something one can take advantage of to save computational cost. + Be aware that one should define ``x_list`` from nearest to furthest from + ``x0``. If not, subsets of ``x_list`` will yield poorer approximations, + which might not grand an order of accuracy of ``len(x_list) - order``. + + See also + ======== + + sympy.calculus.finite_diff.apply_finite_diff + + References + ========== + + .. [1] Generation of Finite Difference Formulas on Arbitrarily Spaced + Grids, Bengt Fornberg; Mathematics of computation; 51; 184; + (1988); 699-706; doi:10.1090/S0025-5718-1988-0935077-0 + + """ + # The notation below closely corresponds to the one used in the paper. + order = S(order) + if not order.is_number: + raise ValueError("Cannot handle symbolic order.") + if order < 0: + raise ValueError("Negative derivative order illegal.") + if int(order) != order: + raise ValueError("Non-integer order illegal") + M = order + N = len(x_list) - 1 + delta = [[[0 for nu in range(N+1)] for n in range(N+1)] for + m in range(M+1)] + delta[0][0][0] = S.One + c1 = S.One + for n in range(1, N+1): + c2 = S.One + for nu in range(n): + c3 = x_list[n] - x_list[nu] + c2 = c2 * c3 + if n <= M: + delta[n][n-1][nu] = 0 + for m in range(min(n, M)+1): + delta[m][n][nu] = (x_list[n]-x0)*delta[m][n-1][nu] -\ + m*delta[m-1][n-1][nu] + delta[m][n][nu] /= c3 + for m in range(min(n, M)+1): + delta[m][n][n] = c1/c2*(m*delta[m-1][n-1][n-1] - + (x_list[n-1]-x0)*delta[m][n-1][n-1]) + c1 = c2 + return delta + + +def apply_finite_diff(order, x_list, y_list, x0=S.Zero): + """ + Calculates the finite difference approximation of + the derivative of requested order at ``x0`` from points + provided in ``x_list`` and ``y_list``. + + Parameters + ========== + + order: int + order of derivative to approximate. 0 corresponds to interpolation. + x_list: sequence + Sequence of (unique) values for the independent variable. + y_list: sequence + The function value at corresponding values for the independent + variable in x_list. + x0: Number or Symbol + At what value of the independent variable the derivative should be + evaluated. Defaults to 0. + + Returns + ======= + + sympy.core.add.Add or sympy.core.numbers.Number + The finite difference expression approximating the requested + derivative order at ``x0``. + + Examples + ======== + + >>> from sympy import apply_finite_diff + >>> cube = lambda arg: (1.0*arg)**3 + >>> xlist = range(-3,3+1) + >>> apply_finite_diff(2, xlist, map(cube, xlist), 2) - 12 # doctest: +SKIP + -3.55271367880050e-15 + + we see that the example above only contain rounding errors. + apply_finite_diff can also be used on more abstract objects: + + >>> from sympy import IndexedBase, Idx + >>> x, y = map(IndexedBase, 'xy') + >>> i = Idx('i') + >>> x_list, y_list = zip(*[(x[i+j], y[i+j]) for j in range(-1,2)]) + >>> apply_finite_diff(1, x_list, y_list, x[i]) + ((x[i + 1] - x[i])/(-x[i - 1] + x[i]) - 1)*y[i]/(x[i + 1] - x[i]) - + (x[i + 1] - x[i])*y[i - 1]/((x[i + 1] - x[i - 1])*(-x[i - 1] + x[i])) + + (-x[i - 1] + x[i])*y[i + 1]/((x[i + 1] - x[i - 1])*(x[i + 1] - x[i])) + + Notes + ===== + + Order = 0 corresponds to interpolation. + Only supply so many points you think makes sense + to around x0 when extracting the derivative (the function + need to be well behaved within that region). Also beware + of Runge's phenomenon. + + See also + ======== + + sympy.calculus.finite_diff.finite_diff_weights + + References + ========== + + Fortran 90 implementation with Python interface for numerics: finitediff_ + + .. _finitediff: https://github.com/bjodah/finitediff + + """ + + # In the original paper the following holds for the notation: + # M = order + # N = len(x_list) - 1 + + N = len(x_list) - 1 + if len(x_list) != len(y_list): + raise ValueError("x_list and y_list not equal in length.") + + delta = finite_diff_weights(order, x_list, x0) + + derivative = 0 + for nu in range(len(x_list)): + derivative += delta[order][N][nu]*y_list[nu] + return derivative + + +def _as_finite_diff(derivative, points=1, x0=None, wrt=None): + """ + Returns an approximation of a derivative of a function in + the form of a finite difference formula. The expression is a + weighted sum of the function at a number of discrete values of + (one of) the independent variable(s). + + Parameters + ========== + + derivative: a Derivative instance + + points: sequence or coefficient, optional + If sequence: discrete values (length >= order+1) of the + independent variable used for generating the finite + difference weights. + If it is a coefficient, it will be used as the step-size + for generating an equidistant sequence of length order+1 + centered around ``x0``. default: 1 (step-size 1) + + x0: number or Symbol, optional + the value of the independent variable (``wrt``) at which the + derivative is to be approximated. Default: same as ``wrt``. + + wrt: Symbol, optional + "with respect to" the variable for which the (partial) + derivative is to be approximated for. If not provided it + is required that the Derivative is ordinary. Default: ``None``. + + Examples + ======== + + >>> from sympy import symbols, Function, exp, sqrt, Symbol + >>> from sympy.calculus.finite_diff import _as_finite_diff + >>> x, h = symbols('x h') + >>> f = Function('f') + >>> _as_finite_diff(f(x).diff(x)) + -f(x - 1/2) + f(x + 1/2) + + The default step size and number of points are 1 and ``order + 1`` + respectively. We can change the step size by passing a symbol + as a parameter: + + >>> _as_finite_diff(f(x).diff(x), h) + -f(-h/2 + x)/h + f(h/2 + x)/h + + We can also specify the discretized values to be used in a sequence: + + >>> _as_finite_diff(f(x).diff(x), [x, x+h, x+2*h]) + -3*f(x)/(2*h) + 2*f(h + x)/h - f(2*h + x)/(2*h) + + The algorithm is not restricted to use equidistant spacing, nor + do we need to make the approximation around ``x0``, but we can get + an expression estimating the derivative at an offset: + + >>> e, sq2 = exp(1), sqrt(2) + >>> xl = [x-h, x+h, x+e*h] + >>> _as_finite_diff(f(x).diff(x, 1), xl, x+h*sq2) + 2*h*((h + sqrt(2)*h)/(2*h) - (-sqrt(2)*h + h)/(2*h))*f(E*h + x)/((-h + E*h)*(h + E*h)) + + (-(-sqrt(2)*h + h)/(2*h) - (-sqrt(2)*h + E*h)/(2*h))*f(-h + x)/(h + E*h) + + (-(h + sqrt(2)*h)/(2*h) + (-sqrt(2)*h + E*h)/(2*h))*f(h + x)/(-h + E*h) + + Partial derivatives are also supported: + + >>> y = Symbol('y') + >>> d2fdxdy=f(x,y).diff(x,y) + >>> _as_finite_diff(d2fdxdy, wrt=x) + -Derivative(f(x - 1/2, y), y) + Derivative(f(x + 1/2, y), y) + + See also + ======== + + sympy.calculus.finite_diff.apply_finite_diff + sympy.calculus.finite_diff.finite_diff_weights + + """ + if derivative.is_Derivative: + pass + elif derivative.is_Atom: + return derivative + else: + return derivative.fromiter( + [_as_finite_diff(ar, points, x0, wrt) for ar + in derivative.args], **derivative.assumptions0) + + if wrt is None: + old = None + for v in derivative.variables: + if old is v: + continue + derivative = _as_finite_diff(derivative, points, x0, v) + old = v + return derivative + + order = derivative.variables.count(wrt) + + if x0 is None: + x0 = wrt + + if not iterable(points): + if getattr(points, 'is_Function', False) and wrt in points.args: + points = points.subs(wrt, x0) + # points is simply the step-size, let's make it a + # equidistant sequence centered around x0 + if order % 2 == 0: + # even order => odd number of points, grid point included + points = [x0 + points*i for i + in range(-order//2, order//2 + 1)] + else: + # odd order => even number of points, half-way wrt grid point + points = [x0 + points*S(i)/2 for i + in range(-order, order + 1, 2)] + others = [wrt, 0] + for v in set(derivative.variables): + if v == wrt: + continue + others += [v, derivative.variables.count(v)] + if len(points) < order+1: + raise ValueError("Too few points for order %d" % order) + return apply_finite_diff(order, points, [ + Derivative(derivative.expr.subs({wrt: x}), *others) for + x in points], x0) + + +def differentiate_finite(expr, *symbols, + points=1, x0=None, wrt=None, evaluate=False): + r""" Differentiate expr and replace Derivatives with finite differences. + + Parameters + ========== + + expr : expression + \*symbols : differentiate with respect to symbols + points: sequence, coefficient or undefined function, optional + see ``Derivative.as_finite_difference`` + x0: number or Symbol, optional + see ``Derivative.as_finite_difference`` + wrt: Symbol, optional + see ``Derivative.as_finite_difference`` + + Examples + ======== + + >>> from sympy import sin, Function, differentiate_finite + >>> from sympy.abc import x, y, h + >>> f, g = Function('f'), Function('g') + >>> differentiate_finite(f(x)*g(x), x, points=[x-h, x+h]) + -f(-h + x)*g(-h + x)/(2*h) + f(h + x)*g(h + x)/(2*h) + + ``differentiate_finite`` works on any expression, including the expressions + with embedded derivatives: + + >>> differentiate_finite(f(x) + sin(x), x, 2) + -2*f(x) + f(x - 1) + f(x + 1) - 2*sin(x) + sin(x - 1) + sin(x + 1) + >>> differentiate_finite(f(x, y), x, y) + f(x - 1/2, y - 1/2) - f(x - 1/2, y + 1/2) - f(x + 1/2, y - 1/2) + f(x + 1/2, y + 1/2) + >>> differentiate_finite(f(x)*g(x).diff(x), x) + (-g(x) + g(x + 1))*f(x + 1/2) - (g(x) - g(x - 1))*f(x - 1/2) + + To make finite difference with non-constant discretization step use + undefined functions: + + >>> dx = Function('dx') + >>> differentiate_finite(f(x)*g(x).diff(x), points=dx(x)) + -(-g(x - dx(x)/2 - dx(x - dx(x)/2)/2)/dx(x - dx(x)/2) + + g(x - dx(x)/2 + dx(x - dx(x)/2)/2)/dx(x - dx(x)/2))*f(x - dx(x)/2)/dx(x) + + (-g(x + dx(x)/2 - dx(x + dx(x)/2)/2)/dx(x + dx(x)/2) + + g(x + dx(x)/2 + dx(x + dx(x)/2)/2)/dx(x + dx(x)/2))*f(x + dx(x)/2)/dx(x) + + """ + if any(term.is_Derivative for term in list(preorder_traversal(expr))): + evaluate = False + + Dexpr = expr.diff(*symbols, evaluate=evaluate) + if evaluate: + sympy_deprecation_warning(""" + The evaluate flag to differentiate_finite() is deprecated. + + evaluate=True expands the intermediate derivatives before computing + differences, but this usually not what you want, as it does not + satisfy the product rule. + """, + deprecated_since_version="1.5", + active_deprecations_target="deprecated-differentiate_finite-evaluate", + ) + return Dexpr.replace( + lambda arg: arg.is_Derivative, + lambda arg: arg.as_finite_difference(points=points, x0=x0, wrt=wrt)) + else: + DFexpr = Dexpr.as_finite_difference(points=points, x0=x0, wrt=wrt) + return DFexpr.replace( + lambda arg: isinstance(arg, Subs), + lambda arg: arg.expr.as_finite_difference( + points=points, x0=arg.point[0], wrt=arg.variables[0])) diff --git a/.venv/lib/python3.12/site-packages/sympy/calculus/singularities.py b/.venv/lib/python3.12/site-packages/sympy/calculus/singularities.py new file mode 100644 index 0000000000000000000000000000000000000000..5adafc59efaf0bff44707f6b5e3f074be6bc1f32 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/calculus/singularities.py @@ -0,0 +1,406 @@ +""" +Singularities +============= + +This module implements algorithms for finding singularities for a function +and identifying types of functions. + +The differential calculus methods in this module include methods to identify +the following function types in the given ``Interval``: +- Increasing +- Strictly Increasing +- Decreasing +- Strictly Decreasing +- Monotonic + +""" + +from sympy.core.power import Pow +from sympy.core.singleton import S +from sympy.core.symbol import Symbol +from sympy.core.sympify import sympify +from sympy.functions.elementary.exponential import log +from sympy.functions.elementary.trigonometric import sec, csc, cot, tan, cos +from sympy.functions.elementary.hyperbolic import ( + sech, csch, coth, tanh, cosh, asech, acsch, atanh, acoth) +from sympy.utilities.misc import filldedent + + +def singularities(expression, symbol, domain=None): + """ + Find singularities of a given function. + + Parameters + ========== + + expression : Expr + The target function in which singularities need to be found. + symbol : Symbol + The symbol over the values of which the singularity in + expression in being searched for. + + Returns + ======= + + Set + A set of values for ``symbol`` for which ``expression`` has a + singularity. An ``EmptySet`` is returned if ``expression`` has no + singularities for any given value of ``Symbol``. + + Raises + ====== + + NotImplementedError + Methods for determining the singularities of this function have + not been developed. + + Notes + ===== + + This function does not find non-isolated singularities + nor does it find branch points of the expression. + + Currently supported functions are: + - univariate continuous (real or complex) functions + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Mathematical_singularity + + Examples + ======== + + >>> from sympy import singularities, Symbol, log + >>> x = Symbol('x', real=True) + >>> y = Symbol('y', real=False) + >>> singularities(x**2 + x + 1, x) + EmptySet + >>> singularities(1/(x + 1), x) + {-1} + >>> singularities(1/(y**2 + 1), y) + {-I, I} + >>> singularities(1/(y**3 + 1), y) + {-1, 1/2 - sqrt(3)*I/2, 1/2 + sqrt(3)*I/2} + >>> singularities(log(x), x) + {0} + + """ + from sympy.solvers.solveset import solveset + + if domain is None: + domain = S.Reals if symbol.is_real else S.Complexes + try: + sings = S.EmptySet + e = expression.rewrite([sec, csc, cot, tan], cos) + e = e.rewrite([sech, csch, coth, tanh], cosh) + for i in e.atoms(Pow): + if i.exp.is_infinite: + raise NotImplementedError + if i.exp.is_negative: + # XXX: exponent of varying sign not handled + sings += solveset(i.base, symbol, domain) + for i in expression.atoms(log, asech, acsch): + sings += solveset(i.args[0], symbol, domain) + for i in expression.atoms(atanh, acoth): + sings += solveset(i.args[0] - 1, symbol, domain) + sings += solveset(i.args[0] + 1, symbol, domain) + return sings + except NotImplementedError: + raise NotImplementedError(filldedent(''' + Methods for determining the singularities + of this function have not been developed.''')) + + +########################################################################### +# DIFFERENTIAL CALCULUS METHODS # +########################################################################### + + +def monotonicity_helper(expression, predicate, interval=S.Reals, symbol=None): + """ + Helper function for functions checking function monotonicity. + + Parameters + ========== + + expression : Expr + The target function which is being checked + predicate : function + The property being tested for. The function takes in an integer + and returns a boolean. The integer input is the derivative and + the boolean result should be true if the property is being held, + and false otherwise. + interval : Set, optional + The range of values in which we are testing, defaults to all reals. + symbol : Symbol, optional + The symbol present in expression which gets varied over the given range. + + It returns a boolean indicating whether the interval in which + the function's derivative satisfies given predicate is a superset + of the given interval. + + Returns + ======= + + Boolean + True if ``predicate`` is true for all the derivatives when ``symbol`` + is varied in ``range``, False otherwise. + + """ + from sympy.solvers.solveset import solveset + + expression = sympify(expression) + free = expression.free_symbols + + if symbol is None: + if len(free) > 1: + raise NotImplementedError( + 'The function has not yet been implemented' + ' for all multivariate expressions.' + ) + + variable = symbol or (free.pop() if free else Symbol('x')) + derivative = expression.diff(variable) + predicate_interval = solveset(predicate(derivative), variable, S.Reals) + return interval.is_subset(predicate_interval) + + +def is_increasing(expression, interval=S.Reals, symbol=None): + """ + Return whether the function is increasing in the given interval. + + Parameters + ========== + + expression : Expr + The target function which is being checked. + interval : Set, optional + The range of values in which we are testing (defaults to set of + all real numbers). + symbol : Symbol, optional + The symbol present in expression which gets varied over the given range. + + Returns + ======= + + Boolean + True if ``expression`` is increasing (either strictly increasing or + constant) in the given ``interval``, False otherwise. + + Examples + ======== + + >>> from sympy import is_increasing + >>> from sympy.abc import x, y + >>> from sympy import S, Interval, oo + >>> is_increasing(x**3 - 3*x**2 + 4*x, S.Reals) + True + >>> is_increasing(-x**2, Interval(-oo, 0)) + True + >>> is_increasing(-x**2, Interval(0, oo)) + False + >>> is_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval(-2, 3)) + False + >>> is_increasing(x**2 + y, Interval(1, 2), x) + True + + """ + return monotonicity_helper(expression, lambda x: x >= 0, interval, symbol) + + +def is_strictly_increasing(expression, interval=S.Reals, symbol=None): + """ + Return whether the function is strictly increasing in the given interval. + + Parameters + ========== + + expression : Expr + The target function which is being checked. + interval : Set, optional + The range of values in which we are testing (defaults to set of + all real numbers). + symbol : Symbol, optional + The symbol present in expression which gets varied over the given range. + + Returns + ======= + + Boolean + True if ``expression`` is strictly increasing in the given ``interval``, + False otherwise. + + Examples + ======== + + >>> from sympy import is_strictly_increasing + >>> from sympy.abc import x, y + >>> from sympy import Interval, oo + >>> is_strictly_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval.Ropen(-oo, -2)) + True + >>> is_strictly_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval.Lopen(3, oo)) + True + >>> is_strictly_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval.open(-2, 3)) + False + >>> is_strictly_increasing(-x**2, Interval(0, oo)) + False + >>> is_strictly_increasing(-x**2 + y, Interval(-oo, 0), x) + False + + """ + return monotonicity_helper(expression, lambda x: x > 0, interval, symbol) + + +def is_decreasing(expression, interval=S.Reals, symbol=None): + """ + Return whether the function is decreasing in the given interval. + + Parameters + ========== + + expression : Expr + The target function which is being checked. + interval : Set, optional + The range of values in which we are testing (defaults to set of + all real numbers). + symbol : Symbol, optional + The symbol present in expression which gets varied over the given range. + + Returns + ======= + + Boolean + True if ``expression`` is decreasing (either strictly decreasing or + constant) in the given ``interval``, False otherwise. + + Examples + ======== + + >>> from sympy import is_decreasing + >>> from sympy.abc import x, y + >>> from sympy import S, Interval, oo + >>> is_decreasing(1/(x**2 - 3*x), Interval.open(S(3)/2, 3)) + True + >>> is_decreasing(1/(x**2 - 3*x), Interval.open(1.5, 3)) + True + >>> is_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo)) + True + >>> is_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, S(3)/2)) + False + >>> is_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, 1.5)) + False + >>> is_decreasing(-x**2, Interval(-oo, 0)) + False + >>> is_decreasing(-x**2 + y, Interval(-oo, 0), x) + False + + """ + return monotonicity_helper(expression, lambda x: x <= 0, interval, symbol) + + +def is_strictly_decreasing(expression, interval=S.Reals, symbol=None): + """ + Return whether the function is strictly decreasing in the given interval. + + Parameters + ========== + + expression : Expr + The target function which is being checked. + interval : Set, optional + The range of values in which we are testing (defaults to set of + all real numbers). + symbol : Symbol, optional + The symbol present in expression which gets varied over the given range. + + Returns + ======= + + Boolean + True if ``expression`` is strictly decreasing in the given ``interval``, + False otherwise. + + Examples + ======== + + >>> from sympy import is_strictly_decreasing + >>> from sympy.abc import x, y + >>> from sympy import S, Interval, oo + >>> is_strictly_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo)) + True + >>> is_strictly_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, S(3)/2)) + False + >>> is_strictly_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, 1.5)) + False + >>> is_strictly_decreasing(-x**2, Interval(-oo, 0)) + False + >>> is_strictly_decreasing(-x**2 + y, Interval(-oo, 0), x) + False + + """ + return monotonicity_helper(expression, lambda x: x < 0, interval, symbol) + + +def is_monotonic(expression, interval=S.Reals, symbol=None): + """ + Return whether the function is monotonic in the given interval. + + Parameters + ========== + + expression : Expr + The target function which is being checked. + interval : Set, optional + The range of values in which we are testing (defaults to set of + all real numbers). + symbol : Symbol, optional + The symbol present in expression which gets varied over the given range. + + Returns + ======= + + Boolean + True if ``expression`` is monotonic in the given ``interval``, + False otherwise. + + Raises + ====== + + NotImplementedError + Monotonicity check has not been implemented for the queried function. + + Examples + ======== + + >>> from sympy import is_monotonic + >>> from sympy.abc import x, y + >>> from sympy import S, Interval, oo + >>> is_monotonic(1/(x**2 - 3*x), Interval.open(S(3)/2, 3)) + True + >>> is_monotonic(1/(x**2 - 3*x), Interval.open(1.5, 3)) + True + >>> is_monotonic(1/(x**2 - 3*x), Interval.Lopen(3, oo)) + True + >>> is_monotonic(x**3 - 3*x**2 + 4*x, S.Reals) + True + >>> is_monotonic(-x**2, S.Reals) + False + >>> is_monotonic(x**2 + y + 1, Interval(1, 2), x) + True + + """ + from sympy.solvers.solveset import solveset + + expression = sympify(expression) + + free = expression.free_symbols + if symbol is None and len(free) > 1: + raise NotImplementedError( + 'is_monotonic has not yet been implemented' + ' for all multivariate expressions.' + ) + + variable = symbol or (free.pop() if free else Symbol('x')) + turning_points = solveset(expression.diff(variable), variable, interval) + return interval.intersection(turning_points) is S.EmptySet diff --git a/.venv/lib/python3.12/site-packages/sympy/calculus/tests/__init__.py b/.venv/lib/python3.12/site-packages/sympy/calculus/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/sympy/calculus/tests/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/calculus/tests/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b81166c90ca1d0ca5e4bf6dcca795cd70f495f0e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/calculus/tests/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/calculus/tests/__pycache__/test_accumulationbounds.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/calculus/tests/__pycache__/test_accumulationbounds.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b08834edb64f4f1c6a06794151cf942fc764783 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/calculus/tests/__pycache__/test_accumulationbounds.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/calculus/tests/__pycache__/test_euler.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/calculus/tests/__pycache__/test_euler.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cfcc563bbf5f3bc57cd2af0ea108e5e5efab0809 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/calculus/tests/__pycache__/test_euler.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/calculus/tests/__pycache__/test_finite_diff.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/calculus/tests/__pycache__/test_finite_diff.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aea7f535f0811d4a8c9a77d424019e70692832c0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/calculus/tests/__pycache__/test_finite_diff.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/calculus/tests/__pycache__/test_singularities.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/calculus/tests/__pycache__/test_singularities.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..77b7d5c83f3cb9772b563a9cf0755a4512f9b712 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/calculus/tests/__pycache__/test_singularities.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/calculus/tests/__pycache__/test_util.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/calculus/tests/__pycache__/test_util.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..035770365074e14c56b5d6cad177dd9a8c6fd8e2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/calculus/tests/__pycache__/test_util.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/calculus/tests/test_accumulationbounds.py b/.venv/lib/python3.12/site-packages/sympy/calculus/tests/test_accumulationbounds.py new file mode 100644 index 0000000000000000000000000000000000000000..bcc47c66327fe21ddca3a6b73ca5914e0441b38e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/calculus/tests/test_accumulationbounds.py @@ -0,0 +1,336 @@ +from sympy.core.numbers import (E, Rational, oo, pi, zoo) +from sympy.core.singleton import S +from sympy.core.symbol import Symbol +from sympy.functions.elementary.exponential import (exp, log) +from sympy.functions.elementary.miscellaneous import (Max, Min, sqrt) +from sympy.functions.elementary.trigonometric import (cos, sin, tan) +from sympy.calculus.accumulationbounds import AccumBounds +from sympy.core import Add, Mul, Pow +from sympy.core.expr import unchanged +from sympy.testing.pytest import raises, XFAIL +from sympy.abc import x + +a = Symbol('a', real=True) +B = AccumBounds + + +def test_AccumBounds(): + assert B(1, 2).args == (1, 2) + assert B(1, 2).delta is S.One + assert B(1, 2).mid == Rational(3, 2) + assert B(1, 3).is_real == True + + assert B(1, 1) is S.One + + assert B(1, 2) + 1 == B(2, 3) + assert 1 + B(1, 2) == B(2, 3) + assert B(1, 2) + B(2, 3) == B(3, 5) + + assert -B(1, 2) == B(-2, -1) + + assert B(1, 2) - 1 == B(0, 1) + assert 1 - B(1, 2) == B(-1, 0) + assert B(2, 3) - B(1, 2) == B(0, 2) + + assert x + B(1, 2) == Add(B(1, 2), x) + assert a + B(1, 2) == B(1 + a, 2 + a) + assert B(1, 2) - x == Add(B(1, 2), -x) + + assert B(-oo, 1) + oo == B(-oo, oo) + assert B(1, oo) + oo is oo + assert B(1, oo) - oo == B(-oo, oo) + assert (-oo - B(-1, oo)) is -oo + assert B(-oo, 1) - oo is -oo + + assert B(1, oo) - oo == B(-oo, oo) + assert B(-oo, 1) - (-oo) == B(-oo, oo) + assert (oo - B(1, oo)) == B(-oo, oo) + assert (-oo - B(1, oo)) is -oo + + assert B(1, 2)/2 == B(S.Half, 1) + assert 2/B(2, 3) == B(Rational(2, 3), 1) + assert 1/B(-1, 1) == B(-oo, oo) + + assert abs(B(1, 2)) == B(1, 2) + assert abs(B(-2, -1)) == B(1, 2) + assert abs(B(-2, 1)) == B(0, 2) + assert abs(B(-1, 2)) == B(0, 2) + c = Symbol('c') + raises(ValueError, lambda: B(0, c)) + raises(ValueError, lambda: B(1, -1)) + r = Symbol('r', real=True) + raises(ValueError, lambda: B(r, r - 1)) + + +def test_AccumBounds_mul(): + assert B(1, 2)*2 == B(2, 4) + assert 2*B(1, 2) == B(2, 4) + assert B(1, 2)*B(2, 3) == B(2, 6) + assert B(0, 2)*B(2, oo) == B(0, oo) + l, r = B(-oo, oo), B(-a, a) + assert l*r == B(-oo, oo) + assert r*l == B(-oo, oo) + l, r = B(1, oo), B(-3, -2) + assert l*r == B(-oo, -2) + assert r*l == B(-oo, -2) + assert B(1, 2)*0 == 0 + assert B(1, oo)*0 == B(0, oo) + assert B(-oo, 1)*0 == B(-oo, 0) + assert B(-oo, oo)*0 == B(-oo, oo) + + assert B(1, 2)*x == Mul(B(1, 2), x, evaluate=False) + + assert B(0, 2)*oo == B(0, oo) + assert B(-2, 0)*oo == B(-oo, 0) + assert B(0, 2)*(-oo) == B(-oo, 0) + assert B(-2, 0)*(-oo) == B(0, oo) + assert B(-1, 1)*oo == B(-oo, oo) + assert B(-1, 1)*(-oo) == B(-oo, oo) + assert B(-oo, oo)*oo == B(-oo, oo) + + +def test_AccumBounds_div(): + assert B(-1, 3)/B(3, 4) == B(Rational(-1, 3), 1) + assert B(-2, 4)/B(-3, 4) == B(-oo, oo) + assert B(-3, -2)/B(-4, 0) == B(S.Half, oo) + + # these two tests can have a better answer + # after Union of B is improved + assert B(-3, -2)/B(-2, 1) == B(-oo, oo) + assert B(2, 3)/B(-2, 2) == B(-oo, oo) + + assert B(-3, -2)/B(0, 4) == B(-oo, Rational(-1, 2)) + assert B(2, 4)/B(-3, 0) == B(-oo, Rational(-2, 3)) + assert B(2, 4)/B(0, 3) == B(Rational(2, 3), oo) + + assert B(0, 1)/B(0, 1) == B(0, oo) + assert B(-1, 0)/B(0, 1) == B(-oo, 0) + assert B(-1, 2)/B(-2, 2) == B(-oo, oo) + + assert 1/B(-1, 2) == B(-oo, oo) + assert 1/B(0, 2) == B(S.Half, oo) + assert (-1)/B(0, 2) == B(-oo, Rational(-1, 2)) + assert 1/B(-oo, 0) == B(-oo, 0) + assert 1/B(-1, 0) == B(-oo, -1) + assert (-2)/B(-oo, 0) == B(0, oo) + assert 1/B(-oo, -1) == B(-1, 0) + + assert B(1, 2)/a == Mul(B(1, 2), 1/a, evaluate=False) + + assert B(1, 2)/0 == B(1, 2)*zoo + assert B(1, oo)/oo == B(0, oo) + assert B(1, oo)/(-oo) == B(-oo, 0) + assert B(-oo, -1)/oo == B(-oo, 0) + assert B(-oo, -1)/(-oo) == B(0, oo) + assert B(-oo, oo)/oo == B(-oo, oo) + assert B(-oo, oo)/(-oo) == B(-oo, oo) + assert B(-1, oo)/oo == B(0, oo) + assert B(-1, oo)/(-oo) == B(-oo, 0) + assert B(-oo, 1)/oo == B(-oo, 0) + assert B(-oo, 1)/(-oo) == B(0, oo) + + +def test_issue_18795(): + r = Symbol('r', real=True) + a = B(-1,1) + c = B(7, oo) + b = B(-oo, oo) + assert c - tan(r) == B(7-tan(r), oo) + assert b + tan(r) == B(-oo, oo) + assert (a + r)/a == B(-oo, oo)*B(r - 1, r + 1) + assert (b + a)/a == B(-oo, oo) + + +def test_AccumBounds_func(): + assert (x**2 + 2*x + 1).subs(x, B(-1, 1)) == B(-1, 4) + assert exp(B(0, 1)) == B(1, E) + assert exp(B(-oo, oo)) == B(0, oo) + assert log(B(3, 6)) == B(log(3), log(6)) + + +@XFAIL +def test_AccumBounds_powf(): + nn = Symbol('nn', nonnegative=True) + assert B(1 + nn, 2 + nn)**B(1, 2) == B(1 + nn, (2 + nn)**2) + i = Symbol('i', integer=True, negative=True) + assert B(1, 2)**i == B(2**i, 1) + + +def test_AccumBounds_pow(): + assert B(0, 2)**2 == B(0, 4) + assert B(-1, 1)**2 == B(0, 1) + assert B(1, 2)**2 == B(1, 4) + assert B(-1, 2)**3 == B(-1, 8) + assert B(-1, 1)**0 == 1 + + assert B(1, 2)**Rational(5, 2) == B(1, 4*sqrt(2)) + assert B(0, 2)**S.Half == B(0, sqrt(2)) + + neg = Symbol('neg', negative=True) + assert unchanged(Pow, B(neg, 1), S.Half) + nn = Symbol('nn', nonnegative=True) + assert B(nn, nn + 1)**S.Half == B(sqrt(nn), sqrt(nn + 1)) + assert B(nn, nn + 1)**nn == B(nn**nn, (nn + 1)**nn) + assert unchanged(Pow, B(nn, nn + 1), x) + i = Symbol('i', integer=True) + assert B(1, 2)**i == B(Min(1, 2**i), Max(1, 2**i)) + i = Symbol('i', integer=True, nonnegative=True) + assert B(1, 2)**i == B(1, 2**i) + assert B(0, 1)**i == B(0**i, 1) + + assert B(1, 5)**(-2) == B(Rational(1, 25), 1) + assert B(-1, 3)**(-2) == B(0, oo) + assert B(0, 2)**(-3) == B(Rational(1, 8), oo) + assert B(-2, 0)**(-3) == B(-oo, -Rational(1, 8)) + assert B(0, 2)**(-2) == B(Rational(1, 4), oo) + assert B(-1, 2)**(-3) == B(-oo, oo) + assert B(-3, -2)**(-3) == B(Rational(-1, 8), Rational(-1, 27)) + assert B(-3, -2)**(-2) == B(Rational(1, 9), Rational(1, 4)) + assert B(0, oo)**S.Half == B(0, oo) + assert B(-oo, 0)**(-2) == B(0, oo) + assert B(-2, 0)**(-2) == B(Rational(1, 4), oo) + + assert B(Rational(1, 3), S.Half)**oo is S.Zero + assert B(0, S.Half)**oo is S.Zero + assert B(S.Half, 1)**oo == B(0, oo) + assert B(0, 1)**oo == B(0, oo) + assert B(2, 3)**oo is oo + assert B(1, 2)**oo == B(0, oo) + assert B(S.Half, 3)**oo == B(0, oo) + assert B(Rational(-1, 3), Rational(-1, 4))**oo is S.Zero + assert B(-1, Rational(-1, 2))**oo is S.NaN + assert B(-3, -2)**oo is zoo + assert B(-2, -1)**oo is S.NaN + assert B(-2, Rational(-1, 2))**oo is S.NaN + assert B(Rational(-1, 2), S.Half)**oo is S.Zero + assert B(Rational(-1, 2), 1)**oo == B(0, oo) + assert B(Rational(-2, 3), 2)**oo == B(0, oo) + assert B(-1, 1)**oo == B(-oo, oo) + assert B(-1, S.Half)**oo == B(-oo, oo) + assert B(-1, 2)**oo == B(-oo, oo) + assert B(-2, S.Half)**oo == B(-oo, oo) + + assert B(1, 2)**x == Pow(B(1, 2), x, evaluate=False) + + assert B(2, 3)**(-oo) is S.Zero + assert B(0, 2)**(-oo) == B(0, oo) + assert B(-1, 2)**(-oo) == B(-oo, oo) + + assert (tan(x)**sin(2*x)).subs(x, B(0, pi/2)) == \ + Pow(B(-oo, oo), B(0, 1)) + + +def test_AccumBounds_exponent(): + # base is 0 + z = 0**B(a, a + S.Half) + assert z.subs(a, 0) == B(0, 1) + assert z.subs(a, 1) == 0 + p = z.subs(a, -1) + assert p.is_Pow and p.args == (0, B(-1, -S.Half)) + # base > 0 + # when base is 1 the type of bounds does not matter + assert 1**B(a, a + 1) == 1 + # otherwise we need to know if 0 is in the bounds + assert S.Half**B(-2, 2) == B(S(1)/4, 4) + assert 2**B(-2, 2) == B(S(1)/4, 4) + + # +eps may introduce +oo + # if there is a negative integer exponent + assert B(0, 1)**B(S(1)/2, 1) == B(0, 1) + assert B(0, 1)**B(0, 1) == B(0, 1) + + # positive bases have positive bounds + assert B(2, 3)**B(-3, -2) == B(S(1)/27, S(1)/4) + assert B(2, 3)**B(-3, 2) == B(S(1)/27, 9) + + # bounds generating imaginary parts unevaluated + assert unchanged(Pow, B(-1, 1), B(1, 2)) + assert B(0, S(1)/2)**B(1, oo) == B(0, S(1)/2) + assert B(0, 1)**B(1, oo) == B(0, oo) + assert B(0, 2)**B(1, oo) == B(0, oo) + assert B(0, oo)**B(1, oo) == B(0, oo) + assert B(S(1)/2, 1)**B(1, oo) == B(0, oo) + assert B(S(1)/2, 1)**B(-oo, -1) == B(0, oo) + assert B(S(1)/2, 1)**B(-oo, oo) == B(0, oo) + assert B(S(1)/2, 2)**B(1, oo) == B(0, oo) + assert B(S(1)/2, 2)**B(-oo, -1) == B(0, oo) + assert B(S(1)/2, 2)**B(-oo, oo) == B(0, oo) + assert B(S(1)/2, oo)**B(1, oo) == B(0, oo) + assert B(S(1)/2, oo)**B(-oo, -1) == B(0, oo) + assert B(S(1)/2, oo)**B(-oo, oo) == B(0, oo) + assert B(1, 2)**B(1, oo) == B(0, oo) + assert B(1, 2)**B(-oo, -1) == B(0, oo) + assert B(1, 2)**B(-oo, oo) == B(0, oo) + assert B(1, oo)**B(1, oo) == B(0, oo) + assert B(1, oo)**B(-oo, -1) == B(0, oo) + assert B(1, oo)**B(-oo, oo) == B(0, oo) + assert B(2, oo)**B(1, oo) == B(2, oo) + assert B(2, oo)**B(-oo, -1) == B(0, S(1)/2) + assert B(2, oo)**B(-oo, oo) == B(0, oo) + + +def test_comparison_AccumBounds(): + assert (B(1, 3) < 4) == S.true + assert (B(1, 3) < -1) == S.false + assert (B(1, 3) < 2).rel_op == '<' + assert (B(1, 3) <= 2).rel_op == '<=' + + assert (B(1, 3) > 4) == S.false + assert (B(1, 3) > -1) == S.true + assert (B(1, 3) > 2).rel_op == '>' + assert (B(1, 3) >= 2).rel_op == '>=' + + assert (B(1, 3) < B(4, 6)) == S.true + assert (B(1, 3) < B(2, 4)).rel_op == '<' + assert (B(1, 3) < B(-2, 0)) == S.false + + assert (B(1, 3) <= B(4, 6)) == S.true + assert (B(1, 3) <= B(-2, 0)) == S.false + + assert (B(1, 3) > B(4, 6)) == S.false + assert (B(1, 3) > B(-2, 0)) == S.true + + assert (B(1, 3) >= B(4, 6)) == S.false + assert (B(1, 3) >= B(-2, 0)) == S.true + + # issue 13499 + assert (cos(x) > 0).subs(x, oo) == (B(-1, 1) > 0) + + c = Symbol('c') + raises(TypeError, lambda: (B(0, 1) < c)) + raises(TypeError, lambda: (B(0, 1) <= c)) + raises(TypeError, lambda: (B(0, 1) > c)) + raises(TypeError, lambda: (B(0, 1) >= c)) + + +def test_contains_AccumBounds(): + assert (1 in B(1, 2)) == S.true + raises(TypeError, lambda: a in B(1, 2)) + assert 0 in B(-1, 0) + raises(TypeError, lambda: + (cos(1)**2 + sin(1)**2 - 1) in B(-1, 0)) + assert (-oo in B(1, oo)) == S.true + assert (oo in B(-oo, 0)) == S.true + + # issue 13159 + assert Mul(0, B(-1, 1)) == Mul(B(-1, 1), 0) == 0 + import itertools + for perm in itertools.permutations([0, B(-1, 1), x]): + assert Mul(*perm) == 0 + + +def test_intersection_AccumBounds(): + assert B(0, 3).intersection(B(1, 2)) == B(1, 2) + assert B(0, 3).intersection(B(1, 4)) == B(1, 3) + assert B(0, 3).intersection(B(-1, 2)) == B(0, 2) + assert B(0, 3).intersection(B(-1, 4)) == B(0, 3) + assert B(0, 1).intersection(B(2, 3)) == S.EmptySet + raises(TypeError, lambda: B(0, 3).intersection(1)) + + +def test_union_AccumBounds(): + assert B(0, 3).union(B(1, 2)) == B(0, 3) + assert B(0, 3).union(B(1, 4)) == B(0, 4) + assert B(0, 3).union(B(-1, 2)) == B(-1, 3) + assert B(0, 3).union(B(-1, 4)) == B(-1, 4) + raises(TypeError, lambda: B(0, 3).union(1)) diff --git a/.venv/lib/python3.12/site-packages/sympy/calculus/tests/test_euler.py b/.venv/lib/python3.12/site-packages/sympy/calculus/tests/test_euler.py new file mode 100644 index 0000000000000000000000000000000000000000..56371c8c787d9459d1390e18c306fddde94d2745 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/calculus/tests/test_euler.py @@ -0,0 +1,74 @@ +from sympy.core.function import (Derivative as D, Function) +from sympy.core.relational import Eq +from sympy.core.symbol import (Symbol, symbols) +from sympy.functions.elementary.trigonometric import (cos, sin) +from sympy.testing.pytest import raises +from sympy.calculus.euler import euler_equations as euler + + +def test_euler_interface(): + x = Function('x') + y = Symbol('y') + t = Symbol('t') + raises(TypeError, lambda: euler()) + raises(TypeError, lambda: euler(D(x(t), t)*y(t), [x(t), y])) + raises(ValueError, lambda: euler(D(x(t), t)*x(y), [x(t), x(y)])) + raises(TypeError, lambda: euler(D(x(t), t)**2, x(0))) + raises(TypeError, lambda: euler(D(x(t), t)*y(t), [t])) + assert euler(D(x(t), t)**2/2, {x(t)}) == [Eq(-D(x(t), t, t), 0)] + assert euler(D(x(t), t)**2/2, x(t), {t}) == [Eq(-D(x(t), t, t), 0)] + + +def test_euler_pendulum(): + x = Function('x') + t = Symbol('t') + L = D(x(t), t)**2/2 + cos(x(t)) + assert euler(L, x(t), t) == [Eq(-sin(x(t)) - D(x(t), t, t), 0)] + + +def test_euler_henonheiles(): + x = Function('x') + y = Function('y') + t = Symbol('t') + L = sum(D(z(t), t)**2/2 - z(t)**2/2 for z in [x, y]) + L += -x(t)**2*y(t) + y(t)**3/3 + assert euler(L, [x(t), y(t)], t) == [Eq(-2*x(t)*y(t) - x(t) - + D(x(t), t, t), 0), + Eq(-x(t)**2 + y(t)**2 - + y(t) - D(y(t), t, t), 0)] + + +def test_euler_sineg(): + psi = Function('psi') + t = Symbol('t') + x = Symbol('x') + L = D(psi(t, x), t)**2/2 - D(psi(t, x), x)**2/2 + cos(psi(t, x)) + assert euler(L, psi(t, x), [t, x]) == [Eq(-sin(psi(t, x)) - + D(psi(t, x), t, t) + + D(psi(t, x), x, x), 0)] + + +def test_euler_high_order(): + # an example from hep-th/0309038 + m = Symbol('m') + k = Symbol('k') + x = Function('x') + y = Function('y') + t = Symbol('t') + L = (m*D(x(t), t)**2/2 + m*D(y(t), t)**2/2 - + k*D(x(t), t)*D(y(t), t, t) + k*D(y(t), t)*D(x(t), t, t)) + assert euler(L, [x(t), y(t)]) == [Eq(2*k*D(y(t), t, t, t) - + m*D(x(t), t, t), 0), + Eq(-2*k*D(x(t), t, t, t) - + m*D(y(t), t, t), 0)] + + w = Symbol('w') + L = D(x(t, w), t, w)**2/2 + assert euler(L) == [Eq(D(x(t, w), t, t, w, w), 0)] + +def test_issue_18653(): + x, y, z = symbols("x y z") + f, g, h = symbols("f g h", cls=Function, args=(x, y)) + f, g, h = f(), g(), h() + expr2 = f.diff(x)*h.diff(z) + assert euler(expr2, (f,), (x, y)) == [] diff --git a/.venv/lib/python3.12/site-packages/sympy/calculus/tests/test_finite_diff.py b/.venv/lib/python3.12/site-packages/sympy/calculus/tests/test_finite_diff.py new file mode 100644 index 0000000000000000000000000000000000000000..e9ecfbdd61b15f516c54bd6d716ba1f264ee2ca0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/calculus/tests/test_finite_diff.py @@ -0,0 +1,164 @@ +from itertools import product + +from sympy.core.function import (Function, diff) +from sympy.core.numbers import Rational +from sympy.core.singleton import S +from sympy.core.symbol import symbols +from sympy.functions.elementary.exponential import exp +from sympy.calculus.finite_diff import ( + apply_finite_diff, differentiate_finite, finite_diff_weights, + _as_finite_diff +) +from sympy.testing.pytest import raises, warns_deprecated_sympy + + +def test_apply_finite_diff(): + x, h = symbols('x h') + f = Function('f') + assert (apply_finite_diff(1, [x-h, x+h], [f(x-h), f(x+h)], x) - + (f(x+h)-f(x-h))/(2*h)).simplify() == 0 + + assert (apply_finite_diff(1, [5, 6, 7], [f(5), f(6), f(7)], 5) - + (Rational(-3, 2)*f(5) + 2*f(6) - S.Half*f(7))).simplify() == 0 + raises(ValueError, lambda: apply_finite_diff(1, [x, h], [f(x)])) + + +def test_finite_diff_weights(): + + d = finite_diff_weights(1, [5, 6, 7], 5) + assert d[1][2] == [Rational(-3, 2), 2, Rational(-1, 2)] + + # Table 1, p. 702 in doi:10.1090/S0025-5718-1988-0935077-0 + # -------------------------------------------------------- + xl = [0, 1, -1, 2, -2, 3, -3, 4, -4] + + # d holds all coefficients + d = finite_diff_weights(4, xl, S.Zero) + + # Zeroeth derivative + for i in range(5): + assert d[0][i] == [S.One] + [S.Zero]*8 + + # First derivative + assert d[1][0] == [S.Zero]*9 + assert d[1][2] == [S.Zero, S.Half, Rational(-1, 2)] + [S.Zero]*6 + assert d[1][4] == [S.Zero, Rational(2, 3), Rational(-2, 3), Rational(-1, 12), Rational(1, 12)] + [S.Zero]*4 + assert d[1][6] == [S.Zero, Rational(3, 4), Rational(-3, 4), Rational(-3, 20), Rational(3, 20), + Rational(1, 60), Rational(-1, 60)] + [S.Zero]*2 + assert d[1][8] == [S.Zero, Rational(4, 5), Rational(-4, 5), Rational(-1, 5), Rational(1, 5), + Rational(4, 105), Rational(-4, 105), Rational(-1, 280), Rational(1, 280)] + + # Second derivative + for i in range(2): + assert d[2][i] == [S.Zero]*9 + assert d[2][2] == [-S(2), S.One, S.One] + [S.Zero]*6 + assert d[2][4] == [Rational(-5, 2), Rational(4, 3), Rational(4, 3), Rational(-1, 12), Rational(-1, 12)] + [S.Zero]*4 + assert d[2][6] == [Rational(-49, 18), Rational(3, 2), Rational(3, 2), Rational(-3, 20), Rational(-3, 20), + Rational(1, 90), Rational(1, 90)] + [S.Zero]*2 + assert d[2][8] == [Rational(-205, 72), Rational(8, 5), Rational(8, 5), Rational(-1, 5), Rational(-1, 5), + Rational(8, 315), Rational(8, 315), Rational(-1, 560), Rational(-1, 560)] + + # Third derivative + for i in range(3): + assert d[3][i] == [S.Zero]*9 + assert d[3][4] == [S.Zero, -S.One, S.One, S.Half, Rational(-1, 2)] + [S.Zero]*4 + assert d[3][6] == [S.Zero, Rational(-13, 8), Rational(13, 8), S.One, -S.One, + Rational(-1, 8), Rational(1, 8)] + [S.Zero]*2 + assert d[3][8] == [S.Zero, Rational(-61, 30), Rational(61, 30), Rational(169, 120), Rational(-169, 120), + Rational(-3, 10), Rational(3, 10), Rational(7, 240), Rational(-7, 240)] + + # Fourth derivative + for i in range(4): + assert d[4][i] == [S.Zero]*9 + assert d[4][4] == [S(6), -S(4), -S(4), S.One, S.One] + [S.Zero]*4 + assert d[4][6] == [Rational(28, 3), Rational(-13, 2), Rational(-13, 2), S(2), S(2), + Rational(-1, 6), Rational(-1, 6)] + [S.Zero]*2 + assert d[4][8] == [Rational(91, 8), Rational(-122, 15), Rational(-122, 15), Rational(169, 60), Rational(169, 60), + Rational(-2, 5), Rational(-2, 5), Rational(7, 240), Rational(7, 240)] + + # Table 2, p. 703 in doi:10.1090/S0025-5718-1988-0935077-0 + # -------------------------------------------------------- + xl = [[j/S(2) for j in list(range(-i*2+1, 0, 2))+list(range(1, i*2+1, 2))] + for i in range(1, 5)] + + # d holds all coefficients + d = [finite_diff_weights({0: 1, 1: 2, 2: 4, 3: 4}[i], xl[i], 0) for + i in range(4)] + + # Zeroth derivative + assert d[0][0][1] == [S.Half, S.Half] + assert d[1][0][3] == [Rational(-1, 16), Rational(9, 16), Rational(9, 16), Rational(-1, 16)] + assert d[2][0][5] == [Rational(3, 256), Rational(-25, 256), Rational(75, 128), Rational(75, 128), + Rational(-25, 256), Rational(3, 256)] + assert d[3][0][7] == [Rational(-5, 2048), Rational(49, 2048), Rational(-245, 2048), Rational(1225, 2048), + Rational(1225, 2048), Rational(-245, 2048), Rational(49, 2048), Rational(-5, 2048)] + + # First derivative + assert d[0][1][1] == [-S.One, S.One] + assert d[1][1][3] == [Rational(1, 24), Rational(-9, 8), Rational(9, 8), Rational(-1, 24)] + assert d[2][1][5] == [Rational(-3, 640), Rational(25, 384), Rational(-75, 64), + Rational(75, 64), Rational(-25, 384), Rational(3, 640)] + assert d[3][1][7] == [Rational(5, 7168), Rational(-49, 5120), + Rational(245, 3072), Rational(-1225, 1024), + Rational(1225, 1024), Rational(-245, 3072), + Rational(49, 5120), Rational(-5, 7168)] + + # Reasonably the rest of the table is also correct... (testing of that + # deemed excessive at the moment) + raises(ValueError, lambda: finite_diff_weights(-1, [1, 2])) + raises(ValueError, lambda: finite_diff_weights(1.2, [1, 2])) + x = symbols('x') + raises(ValueError, lambda: finite_diff_weights(x, [1, 2])) + + +def test_as_finite_diff(): + x = symbols('x') + f = Function('f') + dx = Function('dx') + + _as_finite_diff(f(x).diff(x), [x-2, x-1, x, x+1, x+2]) + + # Use of undefined functions in ``points`` + df_true = -f(x+dx(x)/2-dx(x+dx(x)/2)/2) / dx(x+dx(x)/2) \ + + f(x+dx(x)/2+dx(x+dx(x)/2)/2) / dx(x+dx(x)/2) + df_test = diff(f(x), x).as_finite_difference(points=dx(x), x0=x+dx(x)/2) + assert (df_test - df_true).simplify() == 0 + + +def test_differentiate_finite(): + x, y, h = symbols('x y h') + f = Function('f') + with warns_deprecated_sympy(): + res0 = differentiate_finite(f(x, y) + exp(42), x, y, evaluate=True) + xm, xp, ym, yp = [v + sign*S.Half for v, sign in product([x, y], [-1, 1])] + ref0 = f(xm, ym) + f(xp, yp) - f(xm, yp) - f(xp, ym) + assert (res0 - ref0).simplify() == 0 + + g = Function('g') + with warns_deprecated_sympy(): + res1 = differentiate_finite(f(x)*g(x) + 42, x, evaluate=True) + ref1 = (-f(x - S.Half) + f(x + S.Half))*g(x) + \ + (-g(x - S.Half) + g(x + S.Half))*f(x) + assert (res1 - ref1).simplify() == 0 + + res2 = differentiate_finite(f(x) + x**3 + 42, x, points=[x-1, x+1]) + ref2 = (f(x + 1) + (x + 1)**3 - f(x - 1) - (x - 1)**3)/2 + assert (res2 - ref2).simplify() == 0 + raises(TypeError, lambda: differentiate_finite(f(x)*g(x), x, + pints=[x-1, x+1])) + + res3 = differentiate_finite(f(x)*g(x).diff(x), x) + ref3 = (-g(x) + g(x + 1))*f(x + S.Half) - (g(x) - g(x - 1))*f(x - S.Half) + assert res3 == ref3 + + res4 = differentiate_finite(f(x)*g(x).diff(x).diff(x), x) + ref4 = -((g(x - Rational(3, 2)) - 2*g(x - S.Half) + g(x + S.Half))*f(x - S.Half)) \ + + (g(x - S.Half) - 2*g(x + S.Half) + g(x + Rational(3, 2)))*f(x + S.Half) + assert res4 == ref4 + + res5_expr = f(x).diff(x)*g(x).diff(x) + res5 = differentiate_finite(res5_expr, points=[x-h, x, x+h]) + ref5 = (-2*f(x)/h + f(-h + x)/(2*h) + 3*f(h + x)/(2*h))*(-2*g(x)/h + g(-h + x)/(2*h) \ + + 3*g(h + x)/(2*h))/(2*h) - (2*f(x)/h - 3*f(-h + x)/(2*h) - \ + f(h + x)/(2*h))*(2*g(x)/h - 3*g(-h + x)/(2*h) - g(h + x)/(2*h))/(2*h) + assert res5 == ref5 diff --git a/.venv/lib/python3.12/site-packages/sympy/calculus/tests/test_singularities.py b/.venv/lib/python3.12/site-packages/sympy/calculus/tests/test_singularities.py new file mode 100644 index 0000000000000000000000000000000000000000..19a042332326658021ce12a38f4e058f55903869 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/calculus/tests/test_singularities.py @@ -0,0 +1,122 @@ +from sympy.core.numbers import (I, Rational, pi, oo) +from sympy.core.singleton import S +from sympy.core.symbol import Symbol, Dummy +from sympy.core.function import Lambda +from sympy.functions.elementary.exponential import (exp, log) +from sympy.functions.elementary.trigonometric import sec, csc +from sympy.functions.elementary.hyperbolic import (coth, sech, + atanh, asech, acoth, acsch) +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.calculus.singularities import ( + singularities, + is_increasing, + is_strictly_increasing, + is_decreasing, + is_strictly_decreasing, + is_monotonic +) +from sympy.sets import Interval, FiniteSet, Union, ImageSet +from sympy.testing.pytest import raises +from sympy.abc import x, y + + +def test_singularities(): + x = Symbol('x') + assert singularities(x**2, x) == S.EmptySet + assert singularities(x/(x**2 + 3*x + 2), x) == FiniteSet(-2, -1) + assert singularities(1/(x**2 + 1), x) == FiniteSet(I, -I) + assert singularities(x/(x**3 + 1), x) == \ + FiniteSet(-1, (1 - sqrt(3) * I) / 2, (1 + sqrt(3) * I) / 2) + assert singularities(1/(y**2 + 2*I*y + 1), y) == \ + FiniteSet(-I + sqrt(2)*I, -I - sqrt(2)*I) + _n = Dummy('n') + assert singularities(sech(x), x).dummy_eq(Union( + ImageSet(Lambda(_n, 2*_n*I*pi + I*pi/2), S.Integers), + ImageSet(Lambda(_n, 2*_n*I*pi + 3*I*pi/2), S.Integers))) + assert singularities(coth(x), x).dummy_eq(Union( + ImageSet(Lambda(_n, 2*_n*I*pi + I*pi), S.Integers), + ImageSet(Lambda(_n, 2*_n*I*pi), S.Integers))) + assert singularities(atanh(x), x) == FiniteSet(-1, 1) + assert singularities(acoth(x), x) == FiniteSet(-1, 1) + assert singularities(asech(x), x) == FiniteSet(0) + assert singularities(acsch(x), x) == FiniteSet(0) + + x = Symbol('x', real=True) + assert singularities(1/(x**2 + 1), x) == S.EmptySet + assert singularities(exp(1/x), x, S.Reals) == FiniteSet(0) + assert singularities(exp(1/x), x, Interval(1, 2)) == S.EmptySet + assert singularities(log((x - 2)**2), x, Interval(1, 3)) == FiniteSet(2) + raises(NotImplementedError, lambda: singularities(x**-oo, x)) + assert singularities(sec(x), x, Interval(0, 3*pi)) == FiniteSet( + pi/2, 3*pi/2, 5*pi/2) + assert singularities(csc(x), x, Interval(0, 3*pi)) == FiniteSet( + 0, pi, 2*pi, 3*pi) + + +def test_is_increasing(): + """Test whether is_increasing returns correct value.""" + a = Symbol('a', negative=True) + + assert is_increasing(x**3 - 3*x**2 + 4*x, S.Reals) + assert is_increasing(-x**2, Interval(-oo, 0)) + assert not is_increasing(-x**2, Interval(0, oo)) + assert not is_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval(-2, 3)) + assert is_increasing(x**2 + y, Interval(1, oo), x) + assert is_increasing(-x**2*a, Interval(1, oo), x) + assert is_increasing(1) + + assert is_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval(-2, 3)) is False + + +def test_is_strictly_increasing(): + """Test whether is_strictly_increasing returns correct value.""" + assert is_strictly_increasing( + 4*x**3 - 6*x**2 - 72*x + 30, Interval.Ropen(-oo, -2)) + assert is_strictly_increasing( + 4*x**3 - 6*x**2 - 72*x + 30, Interval.Lopen(3, oo)) + assert not is_strictly_increasing( + 4*x**3 - 6*x**2 - 72*x + 30, Interval.open(-2, 3)) + assert not is_strictly_increasing(-x**2, Interval(0, oo)) + assert not is_strictly_decreasing(1) + + assert is_strictly_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval.open(-2, 3)) is False + + +def test_is_decreasing(): + """Test whether is_decreasing returns correct value.""" + b = Symbol('b', positive=True) + + assert is_decreasing(1/(x**2 - 3*x), Interval.open(Rational(3,2), 3)) + assert is_decreasing(1/(x**2 - 3*x), Interval.open(1.5, 3)) + assert is_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo)) + assert not is_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, Rational(3, 2))) + assert not is_decreasing(-x**2, Interval(-oo, 0)) + assert not is_decreasing(-x**2*b, Interval(-oo, 0), x) + + +def test_is_strictly_decreasing(): + """Test whether is_strictly_decreasing returns correct value.""" + assert is_strictly_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo)) + assert not is_strictly_decreasing( + 1/(x**2 - 3*x), Interval.Ropen(-oo, Rational(3, 2))) + assert not is_strictly_decreasing(-x**2, Interval(-oo, 0)) + assert not is_strictly_decreasing(1) + assert is_strictly_decreasing(1/(x**2 - 3*x), Interval.open(Rational(3,2), 3)) + assert is_strictly_decreasing(1/(x**2 - 3*x), Interval.open(1.5, 3)) + + +def test_is_monotonic(): + """Test whether is_monotonic returns correct value.""" + assert is_monotonic(1/(x**2 - 3*x), Interval.open(Rational(3,2), 3)) + assert is_monotonic(1/(x**2 - 3*x), Interval.open(1.5, 3)) + assert is_monotonic(1/(x**2 - 3*x), Interval.Lopen(3, oo)) + assert is_monotonic(x**3 - 3*x**2 + 4*x, S.Reals) + assert not is_monotonic(-x**2, S.Reals) + assert is_monotonic(x**2 + y + 1, Interval(1, 2), x) + raises(NotImplementedError, lambda: is_monotonic(x**2 + y + 1)) + + +def test_issue_23401(): + x = Symbol('x') + expr = (x + 1)/(-1.0e-3*x**2 + 0.1*x + 0.1) + assert is_increasing(expr, Interval(1,2), x) diff --git a/.venv/lib/python3.12/site-packages/sympy/calculus/tests/test_util.py b/.venv/lib/python3.12/site-packages/sympy/calculus/tests/test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..c18b7a79fd54fdb2638cc746d43ab26753fc72a9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/calculus/tests/test_util.py @@ -0,0 +1,392 @@ +from sympy.core.function import Lambda +from sympy.core.numbers import (E, I, Rational, oo, pi) +from sympy.core.relational import Eq +from sympy.core.singleton import S +from sympy.core.symbol import (Dummy, Symbol) +from sympy.functions.elementary.complexes import (Abs, re) +from sympy.functions.elementary.exponential import (exp, log) +from sympy.functions.elementary.integers import frac +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.piecewise import Piecewise +from sympy.functions.elementary.trigonometric import ( + cos, cot, csc, sec, sin, tan, asin, acos, atan, acot, asec, acsc) +from sympy.functions.elementary.hyperbolic import (sinh, cosh, tanh, coth, + sech, csch, asinh, acosh, atanh, acoth, asech, acsch) +from sympy.functions.special.gamma_functions import gamma +from sympy.functions.special.error_functions import expint +from sympy.matrices.expressions.matexpr import MatrixSymbol +from sympy.simplify.simplify import simplify +from sympy.calculus.util import (function_range, continuous_domain, not_empty_in, + periodicity, lcim, is_convex, + stationary_points, minimum, maximum) +from sympy.sets.sets import (Interval, FiniteSet, Complement, Union) +from sympy.sets.fancysets import ImageSet +from sympy.sets.conditionset import ConditionSet +from sympy.testing.pytest import XFAIL, raises, _both_exp_pow, slow +from sympy.abc import x, y + +a = Symbol('a', real=True) + +def test_function_range(): + assert function_range(sin(x), x, Interval(-pi/2, pi/2) + ) == Interval(-1, 1) + assert function_range(sin(x), x, Interval(0, pi) + ) == Interval(0, 1) + assert function_range(tan(x), x, Interval(0, pi) + ) == Interval(-oo, oo) + assert function_range(tan(x), x, Interval(pi/2, pi) + ) == Interval(-oo, 0) + assert function_range((x + 3)/(x - 2), x, Interval(-5, 5) + ) == Union(Interval(-oo, Rational(2, 7)), Interval(Rational(8, 3), oo)) + assert function_range(1/(x**2), x, Interval(-1, 1) + ) == Interval(1, oo) + assert function_range(exp(x), x, Interval(-1, 1) + ) == Interval(exp(-1), exp(1)) + assert function_range(log(x) - x, x, S.Reals + ) == Interval(-oo, -1) + assert function_range(sqrt(3*x - 1), x, Interval(0, 2) + ) == Interval(0, sqrt(5)) + assert function_range(x*(x - 1) - (x**2 - x), x, S.Reals + ) == FiniteSet(0) + assert function_range(x*(x - 1) - (x**2 - x) + y, x, S.Reals + ) == FiniteSet(y) + assert function_range(sin(x), x, Union(Interval(-5, -3), FiniteSet(4)) + ) == Union(Interval(-sin(3), 1), FiniteSet(sin(4))) + assert function_range(cos(x), x, Interval(-oo, -4) + ) == Interval(-1, 1) + assert function_range(cos(x), x, S.EmptySet) == S.EmptySet + assert function_range(x/sqrt(x**2+1), x, S.Reals) == Interval.open(-1,1) + raises(NotImplementedError, lambda : function_range( + exp(x)*(sin(x) - cos(x))/2 - x, x, S.Reals)) + raises(NotImplementedError, lambda : function_range( + sin(x) + x, x, S.Reals)) # issue 13273 + raises(NotImplementedError, lambda : function_range( + log(x), x, S.Integers)) + raises(NotImplementedError, lambda : function_range( + sin(x)/2, x, S.Naturals)) + + +@slow +def test_function_range1(): + assert function_range(tan(x)**2 + tan(3*x)**2 + 1, x, S.Reals) == Interval(1,oo) + + +def test_continuous_domain(): + assert continuous_domain(sin(x), x, Interval(0, 2*pi)) == Interval(0, 2*pi) + assert continuous_domain(tan(x), x, Interval(0, 2*pi)) == \ + Union(Interval(0, pi/2, False, True), Interval(pi/2, pi*Rational(3, 2), True, True), + Interval(pi*Rational(3, 2), 2*pi, True, False)) + assert continuous_domain(cot(x), x, Interval(0, 2*pi)) == Union( + Interval.open(0, pi), Interval.open(pi, 2*pi)) + assert continuous_domain((x - 1)/((x - 1)**2), x, S.Reals) == \ + Union(Interval(-oo, 1, True, True), Interval(1, oo, True, True)) + assert continuous_domain(log(x) + log(4*x - 1), x, S.Reals) == \ + Interval(Rational(1, 4), oo, True, True) + assert continuous_domain(1/sqrt(x - 3), x, S.Reals) == Interval(3, oo, True, True) + assert continuous_domain(1/x - 2, x, S.Reals) == \ + Union(Interval.open(-oo, 0), Interval.open(0, oo)) + assert continuous_domain(1/(x**2 - 4) + 2, x, S.Reals) == \ + Union(Interval.open(-oo, -2), Interval.open(-2, 2), Interval.open(2, oo)) + assert continuous_domain((x+1)**pi, x, S.Reals) == Interval(-1, oo) + assert continuous_domain((x+1)**(pi/2), x, S.Reals) == Interval(-1, oo) + assert continuous_domain(x**x, x, S.Reals) == Interval(0, oo) + assert continuous_domain((x+1)**log(x**2), x, S.Reals) == Union( + Interval.Ropen(-1, 0), Interval.open(0, oo)) + domain = continuous_domain(log(tan(x)**2 + 1), x, S.Reals) + assert not domain.contains(3*pi/2) + assert domain.contains(5) + d = Symbol('d', even=True, zero=False) + assert continuous_domain(x**(1/d), x, S.Reals) == Interval(0, oo) + n = Dummy('n') + assert continuous_domain(1/sin(x), x, S.Reals).dummy_eq(Complement( + S.Reals, Union(ImageSet(Lambda(n, 2*n*pi + pi), S.Integers), + ImageSet(Lambda(n, 2*n*pi), S.Integers)))) + assert continuous_domain(sin(x) + cos(x), x, S.Reals) == S.Reals + assert continuous_domain(asin(x), x, S.Reals) == Interval(-1, 1) # issue #21786 + assert continuous_domain(1/acos(log(x)), x, S.Reals) == Interval.Ropen(exp(-1), E) + assert continuous_domain(sinh(x)+cosh(x), x, S.Reals) == S.Reals + assert continuous_domain(tanh(x)+sech(x), x, S.Reals) == S.Reals + assert continuous_domain(atan(x)+asinh(x), x, S.Reals) == S.Reals + assert continuous_domain(acosh(x), x, S.Reals) == Interval(1, oo) + assert continuous_domain(atanh(x), x, S.Reals) == Interval.open(-1, 1) + assert continuous_domain(atanh(x)+acosh(x), x, S.Reals) == S.EmptySet + assert continuous_domain(asech(x), x, S.Reals) == Interval.Lopen(0, 1) + assert continuous_domain(acoth(x), x, S.Reals) == Union( + Interval.open(-oo, -1), Interval.open(1, oo)) + assert continuous_domain(asec(x), x, S.Reals) == Union( + Interval(-oo, -1), Interval(1, oo)) + assert continuous_domain(acsc(x), x, S.Reals) == Union( + Interval(-oo, -1), Interval(1, oo)) + for f in (coth, acsch, csch): + assert continuous_domain(f(x), x, S.Reals) == Union( + Interval.open(-oo, 0), Interval.open(0, oo)) + assert continuous_domain(acot(x), x, S.Reals).contains(0) == False + assert continuous_domain(1/(exp(x) - x), x, S.Reals) == Complement( + S.Reals, ConditionSet(x, Eq(-x + exp(x), 0), S.Reals)) + assert continuous_domain(frac(x**2), x, Interval(-2,-1)) == Union( + Interval.open(-2, -sqrt(3)), Interval.open(-sqrt(2), -1), + Interval.open(-sqrt(3), -sqrt(2))) + assert continuous_domain(frac(x), x, S.Reals) == Complement( + S.Reals, S.Integers) + raises(NotImplementedError, lambda : continuous_domain( + 1/(x**2+1), x, S.Complexes)) + raises(NotImplementedError, lambda : continuous_domain( + gamma(x), x, Interval(-5,0))) + assert continuous_domain(x + gamma(pi), x, S.Reals) == S.Reals + + +@XFAIL +def test_continuous_domain_acot(): + acot_cont = Piecewise((pi+acot(x), x<0), (acot(x), True)) + assert continuous_domain(acot_cont, x, S.Reals) == S.Reals + +@XFAIL +def test_continuous_domain_gamma(): + assert continuous_domain(gamma(x), x, S.Reals).contains(-1) == False + +@XFAIL +def test_continuous_domain_neg_power(): + assert continuous_domain((x-2)**(1-x), x, S.Reals) == Interval.open(2, oo) + + +def test_not_empty_in(): + assert not_empty_in(FiniteSet(x, 2*x).intersect(Interval(1, 2, True, False)), x) == \ + Interval(S.Half, 2, True, False) + assert not_empty_in(FiniteSet(x, x**2).intersect(Interval(1, 2)), x) == \ + Union(Interval(-sqrt(2), -1), Interval(1, 2)) + assert not_empty_in(FiniteSet(x**2 + x, x).intersect(Interval(2, 4)), x) == \ + Union(Interval(-sqrt(17)/2 - S.Half, -2), + Interval(1, Rational(-1, 2) + sqrt(17)/2), Interval(2, 4)) + assert not_empty_in(FiniteSet(x/(x - 1)).intersect(S.Reals), x) == \ + Complement(S.Reals, FiniteSet(1)) + assert not_empty_in(FiniteSet(a/(a - 1)).intersect(S.Reals), a) == \ + Complement(S.Reals, FiniteSet(1)) + assert not_empty_in(FiniteSet((x**2 - 3*x + 2)/(x - 1)).intersect(S.Reals), x) == \ + Complement(S.Reals, FiniteSet(1)) + assert not_empty_in(FiniteSet(3, 4, x/(x - 1)).intersect(Interval(2, 3)), x) == \ + Interval(-oo, oo) + assert not_empty_in(FiniteSet(4, x/(x - 1)).intersect(Interval(2, 3)), x) == \ + Interval(S(3)/2, 2) + assert not_empty_in(FiniteSet(x/(x**2 - 1)).intersect(S.Reals), x) == \ + Complement(S.Reals, FiniteSet(-1, 1)) + assert not_empty_in(FiniteSet(x, x**2).intersect(Union(Interval(1, 3, True, True), + Interval(4, 5))), x) == \ + Union(Interval(-sqrt(5), -2), Interval(-sqrt(3), -1, True, True), + Interval(1, 3, True, True), Interval(4, 5)) + assert not_empty_in(FiniteSet(1).intersect(Interval(3, 4)), x) == S.EmptySet + assert not_empty_in(FiniteSet(x**2/(x + 2)).intersect(Interval(1, oo)), x) == \ + Union(Interval(-2, -1, True, False), Interval(2, oo)) + raises(ValueError, lambda: not_empty_in(x)) + raises(ValueError, lambda: not_empty_in(Interval(0, 1), x)) + raises(NotImplementedError, + lambda: not_empty_in(FiniteSet(x).intersect(S.Reals), x, a)) + + +@_both_exp_pow +def test_periodicity(): + assert periodicity(sin(2*x), x) == pi + assert periodicity((-2)*tan(4*x), x) == pi/4 + assert periodicity(sin(x)**2, x) == 2*pi + assert periodicity(3**tan(3*x), x) == pi/3 + assert periodicity(tan(x)*cos(x), x) == 2*pi + assert periodicity(sin(x)**(tan(x)), x) == 2*pi + assert periodicity(tan(x)*sec(x), x) == 2*pi + assert periodicity(sin(2*x)*cos(2*x) - y, x) == pi/2 + assert periodicity(tan(x) + cot(x), x) == pi + assert periodicity(sin(x) - cos(2*x), x) == 2*pi + assert periodicity(sin(x) - 1, x) == 2*pi + assert periodicity(sin(4*x) + sin(x)*cos(x), x) == pi + assert periodicity(exp(sin(x)), x) == 2*pi + assert periodicity(log(cot(2*x)) - sin(cos(2*x)), x) == pi + assert periodicity(sin(2*x)*exp(tan(x) - csc(2*x)), x) == pi + assert periodicity(cos(sec(x) - csc(2*x)), x) == 2*pi + assert periodicity(tan(sin(2*x)), x) == pi + assert periodicity(2*tan(x)**2, x) == pi + assert periodicity(sin(x%4), x) == 4 + assert periodicity(sin(x)%4, x) == 2*pi + assert periodicity(tan((3*x-2)%4), x) == Rational(4, 3) + assert periodicity((sqrt(2)*(x+1)+x) % 3, x) == 3 / (sqrt(2)+1) + assert periodicity((x**2+1) % x, x) is None + assert periodicity(sin(re(x)), x) == 2*pi + assert periodicity(sin(x)**2 + cos(x)**2, x) is S.Zero + assert periodicity(tan(x), y) is S.Zero + assert periodicity(sin(x) + I*cos(x), x) == 2*pi + assert periodicity(x - sin(2*y), y) == pi + + assert periodicity(exp(x), x) is None + assert periodicity(exp(I*x), x) == 2*pi + assert periodicity(exp(I*a), a) == 2*pi + assert periodicity(exp(a), a) is None + assert periodicity(exp(log(sin(a) + I*cos(2*a)), evaluate=False), a) == 2*pi + assert periodicity(exp(log(sin(2*a) + I*cos(a)), evaluate=False), a) == 2*pi + assert periodicity(exp(sin(a)), a) == 2*pi + assert periodicity(exp(2*I*a), a) == pi + assert periodicity(exp(a + I*sin(a)), a) is None + assert periodicity(exp(cos(a/2) + sin(a)), a) == 4*pi + assert periodicity(log(x), x) is None + assert periodicity(exp(x)**sin(x), x) is None + assert periodicity(sin(x)**y, y) is None + + assert periodicity(Abs(sin(Abs(sin(x)))), x) == pi + assert all(periodicity(Abs(f(x)), x) == pi for f in ( + cos, sin, sec, csc, tan, cot)) + assert periodicity(Abs(sin(tan(x))), x) == pi + assert periodicity(Abs(sin(sin(x) + tan(x))), x) == 2*pi + assert periodicity(sin(x) > S.Half, x) == 2*pi + + assert periodicity(x > 2, x) is None + assert periodicity(x**3 - x**2 + 1, x) is None + assert periodicity(Abs(x), x) is None + assert periodicity(Abs(x**2 - 1), x) is None + + assert periodicity((x**2 + 4)%2, x) is None + assert periodicity((E**x)%3, x) is None + + assert periodicity(sin(expint(1, x))/expint(1, x), x) is None + # returning `None` for any Piecewise + p = Piecewise((0, x < -1), (x**2, x <= 1), (log(x), True)) + assert periodicity(p, x) is None + + m = MatrixSymbol('m', 3, 3) + raises(NotImplementedError, lambda: periodicity(sin(m), m)) + raises(NotImplementedError, lambda: periodicity(sin(m[0, 0]), m)) + raises(NotImplementedError, lambda: periodicity(sin(m), m[0, 0])) + raises(NotImplementedError, lambda: periodicity(sin(m[0, 0]), m[0, 0])) + + +def test_periodicity_check(): + assert periodicity(tan(x), x, check=True) == pi + assert periodicity(sin(x) + cos(x), x, check=True) == 2*pi + assert periodicity(sec(x), x) == 2*pi + assert periodicity(sin(x*y), x) == 2*pi/abs(y) + assert periodicity(Abs(sec(sec(x))), x) == pi + + +def test_lcim(): + assert lcim([S.Half, S(2), S(3)]) == 6 + assert lcim([pi/2, pi/4, pi]) == pi + assert lcim([2*pi, pi/2]) == 2*pi + assert lcim([S.One, 2*pi]) is None + assert lcim([S(2) + 2*E, E/3 + Rational(1, 3), S.One + E]) == S(2) + 2*E + + +def test_is_convex(): + assert is_convex(1/x, x, domain=Interval.open(0, oo)) == True + assert is_convex(1/x, x, domain=Interval(-oo, 0)) == False + assert is_convex(x**2, x, domain=Interval(0, oo)) == True + assert is_convex(1/x**3, x, domain=Interval.Lopen(0, oo)) == True + assert is_convex(-1/x**3, x, domain=Interval.Ropen(-oo, 0)) == True + assert is_convex(log(x) ,x) == False + assert is_convex(x**2+y**2, x, y) == True + assert is_convex(cos(x) + cos(y), x) == False + assert is_convex(8*x**2 - 2*y**2, x, y) == False + + +def test_stationary_points(): + assert stationary_points(sin(x), x, Interval(-pi/2, pi/2) + ) == {-pi/2, pi/2} + assert stationary_points(sin(x), x, Interval.Ropen(0, pi/4) + ) is S.EmptySet + assert stationary_points(tan(x), x, + ) is S.EmptySet + assert stationary_points(sin(x)*cos(x), x, Interval(0, pi) + ) == {pi/4, pi*Rational(3, 4)} + assert stationary_points(sec(x), x, Interval(0, pi) + ) == {0, pi} + assert stationary_points((x+3)*(x-2), x + ) == FiniteSet(Rational(-1, 2)) + assert stationary_points((x + 3)/(x - 2), x, Interval(-5, 5) + ) is S.EmptySet + assert stationary_points((x**2+3)/(x-2), x + ) == {2 - sqrt(7), 2 + sqrt(7)} + assert stationary_points((x**2+3)/(x-2), x, Interval(0, 5) + ) == {2 + sqrt(7)} + assert stationary_points(x**4 + x**3 - 5*x**2, x, S.Reals + ) == FiniteSet(-2, 0, Rational(5, 4)) + assert stationary_points(exp(x), x + ) is S.EmptySet + assert stationary_points(log(x) - x, x, S.Reals + ) == {1} + assert stationary_points(cos(x), x, Union(Interval(0, 5), Interval(-6, -3)) + ) == {0, -pi, pi} + assert stationary_points(y, x, S.Reals + ) == S.Reals + assert stationary_points(y, x, S.EmptySet) == S.EmptySet + + +def test_maximum(): + assert maximum(sin(x), x) is S.One + assert maximum(sin(x), x, Interval(0, 1)) == sin(1) + assert maximum(tan(x), x) is oo + assert maximum(tan(x), x, Interval(-pi/4, pi/4)) is S.One + assert maximum(sin(x)*cos(x), x, S.Reals) == S.Half + assert simplify(maximum(sin(x)*cos(x), x, Interval(pi*Rational(3, 8), pi*Rational(5, 8))) + ) == sqrt(2)/4 + assert maximum((x+3)*(x-2), x) is oo + assert maximum((x+3)*(x-2), x, Interval(-5, 0)) == S(14) + assert maximum((x+3)/(x-2), x, Interval(-5, 0)) == Rational(2, 7) + assert simplify(maximum(-x**4-x**3+x**2+10, x) + ) == 41*sqrt(41)/512 + Rational(5419, 512) + assert maximum(exp(x), x, Interval(-oo, 2)) == exp(2) + assert maximum(log(x) - x, x, S.Reals) is S.NegativeOne + assert maximum(cos(x), x, Union(Interval(0, 5), Interval(-6, -3)) + ) is S.One + assert maximum(cos(x)-sin(x), x, S.Reals) == sqrt(2) + assert maximum(y, x, S.Reals) == y + assert maximum(abs(a**3 + a), a, Interval(0, 2)) == 10 + assert maximum(abs(60*a**3 + 24*a), a, Interval(0, 2)) == 528 + assert maximum(abs(12*a*(5*a**2 + 2)), a, Interval(0, 2)) == 528 + assert maximum(x/sqrt(x**2+1), x, S.Reals) == 1 + + raises(ValueError, lambda : maximum(sin(x), x, S.EmptySet)) + raises(ValueError, lambda : maximum(log(cos(x)), x, S.EmptySet)) + raises(ValueError, lambda : maximum(1/(x**2 + y**2 + 1), x, S.EmptySet)) + raises(ValueError, lambda : maximum(sin(x), sin(x))) + raises(ValueError, lambda : maximum(sin(x), x*y, S.EmptySet)) + raises(ValueError, lambda : maximum(sin(x), S.One)) + + +def test_minimum(): + assert minimum(sin(x), x) is S.NegativeOne + assert minimum(sin(x), x, Interval(1, 4)) == sin(4) + assert minimum(tan(x), x) is -oo + assert minimum(tan(x), x, Interval(-pi/4, pi/4)) is S.NegativeOne + assert minimum(sin(x)*cos(x), x, S.Reals) == Rational(-1, 2) + assert simplify(minimum(sin(x)*cos(x), x, Interval(pi*Rational(3, 8), pi*Rational(5, 8))) + ) == -sqrt(2)/4 + assert minimum((x+3)*(x-2), x) == Rational(-25, 4) + assert minimum((x+3)/(x-2), x, Interval(-5, 0)) == Rational(-3, 2) + assert minimum(x**4-x**3+x**2+10, x) == S(10) + assert minimum(exp(x), x, Interval(-2, oo)) == exp(-2) + assert minimum(log(x) - x, x, S.Reals) is -oo + assert minimum(cos(x), x, Union(Interval(0, 5), Interval(-6, -3)) + ) is S.NegativeOne + assert minimum(cos(x)-sin(x), x, S.Reals) == -sqrt(2) + assert minimum(y, x, S.Reals) == y + assert minimum(x/sqrt(x**2+1), x, S.Reals) == -1 + + raises(ValueError, lambda : minimum(sin(x), x, S.EmptySet)) + raises(ValueError, lambda : minimum(log(cos(x)), x, S.EmptySet)) + raises(ValueError, lambda : minimum(1/(x**2 + y**2 + 1), x, S.EmptySet)) + raises(ValueError, lambda : minimum(sin(x), sin(x))) + raises(ValueError, lambda : minimum(sin(x), x*y, S.EmptySet)) + raises(ValueError, lambda : minimum(sin(x), S.One)) + + +def test_issue_19869(): + assert (maximum(sqrt(3)*(x - 1)/(3*sqrt(x**2 + 1)), x) + ) == sqrt(3)/3 + + +def test_issue_16469(): + f = abs(a) + assert function_range(f, a, S.Reals) == Interval(0, oo, False, True) + + +@_both_exp_pow +def test_issue_18747(): + assert periodicity(exp(pi*I*(x/4 + S.Half/2)), x) == 8 + + +def test_issue_25942(): + assert (acos(x) > pi/3).as_set() == Interval.Ropen(-1, S(1)/2) diff --git a/.venv/lib/python3.12/site-packages/sympy/calculus/util.py b/.venv/lib/python3.12/site-packages/sympy/calculus/util.py new file mode 100644 index 0000000000000000000000000000000000000000..dac316358873de2418dd8ab56445823f07a37b1b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/calculus/util.py @@ -0,0 +1,895 @@ +from .accumulationbounds import AccumBounds, AccumulationBounds # noqa: F401 +from .singularities import singularities +from sympy.core import Pow, S +from sympy.core.function import diff, expand_mul, Function +from sympy.core.kind import NumberKind +from sympy.core.mod import Mod +from sympy.core.numbers import equal_valued +from sympy.core.relational import Relational +from sympy.core.symbol import Symbol, Dummy +from sympy.core.sympify import _sympify +from sympy.functions.elementary.complexes import Abs, im, re +from sympy.functions.elementary.exponential import exp, log +from sympy.functions.elementary.integers import frac +from sympy.functions.elementary.piecewise import Piecewise +from sympy.functions.elementary.trigonometric import ( + TrigonometricFunction, sin, cos, tan, cot, csc, sec, + asin, acos, acot, atan, asec, acsc) +from sympy.functions.elementary.hyperbolic import (sinh, cosh, tanh, coth, + sech, csch, asinh, acosh, atanh, acoth, asech, acsch) +from sympy.polys.polytools import degree, lcm_list +from sympy.sets.sets import (Interval, Intersection, FiniteSet, Union, + Complement) +from sympy.sets.fancysets import ImageSet +from sympy.sets.conditionset import ConditionSet +from sympy.utilities import filldedent +from sympy.utilities.iterables import iterable +from sympy.matrices.dense import hessian + + +def continuous_domain(f, symbol, domain): + """ + Returns the domain on which the function expression f is continuous. + + This function is limited by the ability to determine the various + singularities and discontinuities of the given function. + The result is either given as a union of intervals or constructed using + other set operations. + + Parameters + ========== + + f : :py:class:`~.Expr` + The concerned function. + symbol : :py:class:`~.Symbol` + The variable for which the intervals are to be determined. + domain : :py:class:`~.Interval` + The domain over which the continuity of the symbol has to be checked. + + Examples + ======== + + >>> from sympy import Interval, Symbol, S, tan, log, pi, sqrt + >>> from sympy.calculus.util import continuous_domain + >>> x = Symbol('x') + >>> continuous_domain(1/x, x, S.Reals) + Union(Interval.open(-oo, 0), Interval.open(0, oo)) + >>> continuous_domain(tan(x), x, Interval(0, pi)) + Union(Interval.Ropen(0, pi/2), Interval.Lopen(pi/2, pi)) + >>> continuous_domain(sqrt(x - 2), x, Interval(-5, 5)) + Interval(2, 5) + >>> continuous_domain(log(2*x - 1), x, S.Reals) + Interval.open(1/2, oo) + + Returns + ======= + + :py:class:`~.Interval` + Union of all intervals where the function is continuous. + + Raises + ====== + + NotImplementedError + If the method to determine continuity of such a function + has not yet been developed. + + """ + from sympy.solvers.inequalities import solve_univariate_inequality + + if not domain.is_subset(S.Reals): + raise NotImplementedError(filldedent(''' + Domain must be a subset of S.Reals. + ''')) + implemented = [Pow, exp, log, Abs, frac, + sin, cos, tan, cot, sec, csc, + asin, acos, atan, acot, asec, acsc, + sinh, cosh, tanh, coth, sech, csch, + asinh, acosh, atanh, acoth, asech, acsch] + used = [fct.func for fct in f.atoms(Function) if fct.has(symbol)] + if any(func not in implemented for func in used): + raise NotImplementedError(filldedent(''' + Unable to determine the domain of the given function. + ''')) + + x = Symbol('x') + constraints = { + log: (x > 0,), + asin: (x >= -1, x <= 1), + acos: (x >= -1, x <= 1), + acosh: (x >= 1,), + atanh: (x > -1, x < 1), + asech: (x > 0, x <= 1) + } + constraints_union = { + asec: (x <= -1, x >= 1), + acsc: (x <= -1, x >= 1), + acoth: (x < -1, x > 1) + } + + cont_domain = domain + for atom in f.atoms(Pow): + den = atom.exp.as_numer_denom()[1] + if atom.exp.is_rational and den.is_odd: + pass # 0**negative handled by singularities() + else: + constraint = solve_univariate_inequality(atom.base >= 0, + symbol).as_set() + cont_domain = Intersection(constraint, cont_domain) + + for atom in f.atoms(Function): + if atom.func in constraints: + for c in constraints[atom.func]: + constraint_relational = c.subs(x, atom.args[0]) + constraint_set = solve_univariate_inequality( + constraint_relational, symbol).as_set() + cont_domain = Intersection(constraint_set, cont_domain) + elif atom.func in constraints_union: + constraint_set = S.EmptySet + for c in constraints_union[atom.func]: + constraint_relational = c.subs(x, atom.args[0]) + constraint_set += solve_univariate_inequality( + constraint_relational, symbol).as_set() + cont_domain = Intersection(constraint_set, cont_domain) + # XXX: the discontinuities below could be factored out in + # a new "discontinuities()". + elif atom.func == acot: + from sympy.solvers.solveset import solveset_real + # Sympy's acot() has a step discontinuity at 0. Since it's + # neither an essential singularity nor a pole, singularities() + # will not report it. But it's still relevant for determining + # the continuity of the function f. + cont_domain -= solveset_real(atom.args[0], symbol) + # Note that the above may introduce spurious discontinuities, e.g. + # for abs(acot(x)) at 0. + elif atom.func == frac: + from sympy.solvers.solveset import solveset_real + r = function_range(atom.args[0], symbol, domain) + r = Intersection(r, S.Integers) + if r.is_finite_set: + discont = S.EmptySet + for n in r: + discont += solveset_real(atom.args[0]-n, symbol) + else: + discont = ConditionSet( + symbol, S.Integers.contains(atom.args[0]), cont_domain) + cont_domain -= discont + + return cont_domain - singularities(f, symbol, domain) + + +def function_range(f, symbol, domain): + """ + Finds the range of a function in a given domain. + This method is limited by the ability to determine the singularities and + determine limits. + + Parameters + ========== + + f : :py:class:`~.Expr` + The concerned function. + symbol : :py:class:`~.Symbol` + The variable for which the range of function is to be determined. + domain : :py:class:`~.Interval` + The domain under which the range of the function has to be found. + + Examples + ======== + + >>> from sympy import Interval, Symbol, S, exp, log, pi, sqrt, sin, tan + >>> from sympy.calculus.util import function_range + >>> x = Symbol('x') + >>> function_range(sin(x), x, Interval(0, 2*pi)) + Interval(-1, 1) + >>> function_range(tan(x), x, Interval(-pi/2, pi/2)) + Interval(-oo, oo) + >>> function_range(1/x, x, S.Reals) + Union(Interval.open(-oo, 0), Interval.open(0, oo)) + >>> function_range(exp(x), x, S.Reals) + Interval.open(0, oo) + >>> function_range(log(x), x, S.Reals) + Interval(-oo, oo) + >>> function_range(sqrt(x), x, Interval(-5, 9)) + Interval(0, 3) + + Returns + ======= + + :py:class:`~.Interval` + Union of all ranges for all intervals under domain where function is + continuous. + + Raises + ====== + + NotImplementedError + If any of the intervals, in the given domain, for which function + is continuous are not finite or real, + OR if the critical points of the function on the domain cannot be found. + """ + + if domain is S.EmptySet: + return S.EmptySet + + period = periodicity(f, symbol) + if period == S.Zero: + # the expression is constant wrt symbol + return FiniteSet(f.expand()) + + from sympy.series.limits import limit + from sympy.solvers.solveset import solveset + + if period is not None: + if isinstance(domain, Interval): + if (domain.inf - domain.sup).is_infinite: + domain = Interval(0, period) + elif isinstance(domain, Union): + for sub_dom in domain.args: + if isinstance(sub_dom, Interval) and \ + ((sub_dom.inf - sub_dom.sup).is_infinite): + domain = Interval(0, period) + + intervals = continuous_domain(f, symbol, domain) + range_int = S.EmptySet + if isinstance(intervals,(Interval, FiniteSet)): + interval_iter = (intervals,) + elif isinstance(intervals, Union): + interval_iter = intervals.args + else: + raise NotImplementedError("Unable to find range for the given domain.") + + for interval in interval_iter: + if isinstance(interval, FiniteSet): + for singleton in interval: + if singleton in domain: + range_int += FiniteSet(f.subs(symbol, singleton)) + elif isinstance(interval, Interval): + vals = S.EmptySet + critical_values = S.EmptySet + bounds = ((interval.left_open, interval.inf, '+'), + (interval.right_open, interval.sup, '-')) + + for is_open, limit_point, direction in bounds: + if is_open: + critical_values += FiniteSet(limit(f, symbol, limit_point, direction)) + vals += critical_values + else: + vals += FiniteSet(f.subs(symbol, limit_point)) + + critical_points = solveset(f.diff(symbol), symbol, interval) + + if not iterable(critical_points): + raise NotImplementedError( + 'Unable to find critical points for {}'.format(f)) + if isinstance(critical_points, ImageSet): + raise NotImplementedError( + 'Infinite number of critical points for {}'.format(f)) + + for critical_point in critical_points: + vals += FiniteSet(f.subs(symbol, critical_point)) + + left_open, right_open = False, False + + if critical_values is not S.EmptySet: + if critical_values.inf == vals.inf: + left_open = True + + if critical_values.sup == vals.sup: + right_open = True + + range_int += Interval(vals.inf, vals.sup, left_open, right_open) + else: + raise NotImplementedError("Unable to find range for the given domain.") + + return range_int + + +def not_empty_in(finset_intersection, *syms): + """ + Finds the domain of the functions in ``finset_intersection`` in which the + ``finite_set`` is not-empty. + + Parameters + ========== + + finset_intersection : Intersection of FiniteSet + The unevaluated intersection of FiniteSet containing + real-valued functions with Union of Sets + syms : Tuple of symbols + Symbol for which domain is to be found + + Raises + ====== + + NotImplementedError + The algorithms to find the non-emptiness of the given FiniteSet are + not yet implemented. + ValueError + The input is not valid. + RuntimeError + It is a bug, please report it to the github issue tracker + (https://github.com/sympy/sympy/issues). + + Examples + ======== + + >>> from sympy import FiniteSet, Interval, not_empty_in, oo + >>> from sympy.abc import x + >>> not_empty_in(FiniteSet(x/2).intersect(Interval(0, 1)), x) + Interval(0, 2) + >>> not_empty_in(FiniteSet(x, x**2).intersect(Interval(1, 2)), x) + Union(Interval(1, 2), Interval(-sqrt(2), -1)) + >>> not_empty_in(FiniteSet(x**2/(x + 2)).intersect(Interval(1, oo)), x) + Union(Interval.Lopen(-2, -1), Interval(2, oo)) + """ + + # TODO: handle piecewise defined functions + # TODO: handle transcendental functions + # TODO: handle multivariate functions + if len(syms) == 0: + raise ValueError("One or more symbols must be given in syms.") + + if finset_intersection is S.EmptySet: + return S.EmptySet + + if isinstance(finset_intersection, Union): + elm_in_sets = finset_intersection.args[0] + return Union(not_empty_in(finset_intersection.args[1], *syms), + elm_in_sets) + + if isinstance(finset_intersection, FiniteSet): + finite_set = finset_intersection + _sets = S.Reals + else: + finite_set = finset_intersection.args[1] + _sets = finset_intersection.args[0] + + if not isinstance(finite_set, FiniteSet): + raise ValueError('A FiniteSet must be given, not %s: %s' % + (type(finite_set), finite_set)) + + if len(syms) == 1: + symb = syms[0] + else: + raise NotImplementedError('more than one variables %s not handled' % + (syms,)) + + def elm_domain(expr, intrvl): + """ Finds the domain of an expression in any given interval """ + from sympy.solvers.solveset import solveset + + _start = intrvl.start + _end = intrvl.end + _singularities = solveset(expr.as_numer_denom()[1], symb, + domain=S.Reals) + + if intrvl.right_open: + if _end is S.Infinity: + _domain1 = S.Reals + else: + _domain1 = solveset(expr < _end, symb, domain=S.Reals) + else: + _domain1 = solveset(expr <= _end, symb, domain=S.Reals) + + if intrvl.left_open: + if _start is S.NegativeInfinity: + _domain2 = S.Reals + else: + _domain2 = solveset(expr > _start, symb, domain=S.Reals) + else: + _domain2 = solveset(expr >= _start, symb, domain=S.Reals) + + # domain in the interval + expr_with_sing = Intersection(_domain1, _domain2) + expr_domain = Complement(expr_with_sing, _singularities) + return expr_domain + + if isinstance(_sets, Interval): + return Union(*[elm_domain(element, _sets) for element in finite_set]) + + if isinstance(_sets, Union): + _domain = S.EmptySet + for intrvl in _sets.args: + _domain_element = Union(*[elm_domain(element, intrvl) + for element in finite_set]) + _domain = Union(_domain, _domain_element) + return _domain + + +def periodicity(f, symbol, check=False): + """ + Tests the given function for periodicity in the given symbol. + + Parameters + ========== + + f : :py:class:`~.Expr` + The concerned function. + symbol : :py:class:`~.Symbol` + The variable for which the period is to be determined. + check : bool, optional + The flag to verify whether the value being returned is a period or not. + + Returns + ======= + + period + The period of the function is returned. + ``None`` is returned when the function is aperiodic or has a complex period. + The value of $0$ is returned as the period of a constant function. + + Raises + ====== + + NotImplementedError + The value of the period computed cannot be verified. + + + Notes + ===== + + Currently, we do not support functions with a complex period. + The period of functions having complex periodic values such + as ``exp``, ``sinh`` is evaluated to ``None``. + + The value returned might not be the "fundamental" period of the given + function i.e. it may not be the smallest periodic value of the function. + + The verification of the period through the ``check`` flag is not reliable + due to internal simplification of the given expression. Hence, it is set + to ``False`` by default. + + Examples + ======== + >>> from sympy import periodicity, Symbol, sin, cos, tan, exp + >>> x = Symbol('x') + >>> f = sin(x) + sin(2*x) + sin(3*x) + >>> periodicity(f, x) + 2*pi + >>> periodicity(sin(x)*cos(x), x) + pi + >>> periodicity(exp(tan(2*x) - 1), x) + pi/2 + >>> periodicity(sin(4*x)**cos(2*x), x) + pi + >>> periodicity(exp(x), x) + """ + if symbol.kind is not NumberKind: + raise NotImplementedError("Cannot use symbol of kind %s" % symbol.kind) + temp = Dummy('x', real=True) + f = f.subs(symbol, temp) + symbol = temp + + def _check(orig_f, period): + '''Return the checked period or raise an error.''' + new_f = orig_f.subs(symbol, symbol + period) + if new_f.equals(orig_f): + return period + else: + raise NotImplementedError(filldedent(''' + The period of the given function cannot be verified. + When `%s` was replaced with `%s + %s` in `%s`, the result + was `%s` which was not recognized as being the same as + the original function. + So either the period was wrong or the two forms were + not recognized as being equal. + Set check=False to obtain the value.''' % + (symbol, symbol, period, orig_f, new_f))) + + orig_f = f + period = None + + if isinstance(f, Relational): + f = f.lhs - f.rhs + + f = f.simplify() + + if symbol not in f.free_symbols: + return S.Zero + + if isinstance(f, TrigonometricFunction): + try: + period = f.period(symbol) + except NotImplementedError: + pass + + if isinstance(f, Abs): + arg = f.args[0] + if isinstance(arg, (sec, csc, cos)): + # all but tan and cot might have a + # a period that is half as large + # so recast as sin + arg = sin(arg.args[0]) + period = periodicity(arg, symbol) + if period is not None and isinstance(arg, sin): + # the argument of Abs was a trigonometric other than + # cot or tan; test to see if the half-period + # is valid. Abs(arg) has behaviour equivalent to + # orig_f, so use that for test: + orig_f = Abs(arg) + try: + return _check(orig_f, period/2) + except NotImplementedError as err: + if check: + raise NotImplementedError(err) + # else let new orig_f and period be + # checked below + + if isinstance(f, exp) or (f.is_Pow and f.base == S.Exp1): + f = Pow(S.Exp1, expand_mul(f.exp)) + if im(f) != 0: + period_real = periodicity(re(f), symbol) + period_imag = periodicity(im(f), symbol) + if period_real is not None and period_imag is not None: + period = lcim([period_real, period_imag]) + + if f.is_Pow and f.base != S.Exp1: + base, expo = f.args + base_has_sym = base.has(symbol) + expo_has_sym = expo.has(symbol) + + if base_has_sym and not expo_has_sym: + period = periodicity(base, symbol) + + elif expo_has_sym and not base_has_sym: + period = periodicity(expo, symbol) + + else: + period = _periodicity(f.args, symbol) + + elif f.is_Mul: + coeff, g = f.as_independent(symbol, as_Add=False) + if isinstance(g, TrigonometricFunction) or not equal_valued(coeff, 1): + period = periodicity(g, symbol) + else: + period = _periodicity(g.args, symbol) + + elif f.is_Add: + k, g = f.as_independent(symbol) + if k is not S.Zero: + return periodicity(g, symbol) + + period = _periodicity(g.args, symbol) + + elif isinstance(f, Mod): + a, n = f.args + + if a == symbol: + period = n + elif isinstance(a, TrigonometricFunction): + period = periodicity(a, symbol) + #check if 'f' is linear in 'symbol' + elif (a.is_polynomial(symbol) and degree(a, symbol) == 1 and + symbol not in n.free_symbols): + period = Abs(n / a.diff(symbol)) + + elif isinstance(f, Piecewise): + pass # not handling Piecewise yet as the return type is not favorable + + elif period is None: + from sympy.solvers.decompogen import compogen, decompogen + g_s = decompogen(f, symbol) + num_of_gs = len(g_s) + if num_of_gs > 1: + for index, g in enumerate(reversed(g_s)): + start_index = num_of_gs - 1 - index + g = compogen(g_s[start_index:], symbol) + if g not in (orig_f, f): # Fix for issue 12620 + period = periodicity(g, symbol) + if period is not None: + break + + if period is not None: + if check: + return _check(orig_f, period) + return period + + return None + + +def _periodicity(args, symbol): + """ + Helper for `periodicity` to find the period of a list of simpler + functions. + It uses the `lcim` method to find the least common period of + all the functions. + + Parameters + ========== + + args : Tuple of :py:class:`~.Symbol` + All the symbols present in a function. + + symbol : :py:class:`~.Symbol` + The symbol over which the function is to be evaluated. + + Returns + ======= + + period + The least common period of the function for all the symbols + of the function. + ``None`` if for at least one of the symbols the function is aperiodic. + + """ + periods = [] + for f in args: + period = periodicity(f, symbol) + if period is None: + return None + + if period is not S.Zero: + periods.append(period) + + if len(periods) > 1: + return lcim(periods) + + if periods: + return periods[0] + + +def lcim(numbers): + """Returns the least common integral multiple of a list of numbers. + + The numbers can be rational or irrational or a mixture of both. + `None` is returned for incommensurable numbers. + + Parameters + ========== + + numbers : list + Numbers (rational and/or irrational) for which lcim is to be found. + + Returns + ======= + + number + lcim if it exists, otherwise ``None`` for incommensurable numbers. + + Examples + ======== + + >>> from sympy.calculus.util import lcim + >>> from sympy import S, pi + >>> lcim([S(1)/2, S(3)/4, S(5)/6]) + 15/2 + >>> lcim([2*pi, 3*pi, pi, pi/2]) + 6*pi + >>> lcim([S(1), 2*pi]) + """ + result = None + if all(num.is_irrational for num in numbers): + factorized_nums = [num.factor() for num in numbers] + factors_num = [num.as_coeff_Mul() for num in factorized_nums] + term = factors_num[0][1] + if all(factor == term for coeff, factor in factors_num): + common_term = term + coeffs = [coeff for coeff, factor in factors_num] + result = lcm_list(coeffs) * common_term + + elif all(num.is_rational for num in numbers): + result = lcm_list(numbers) + + else: + pass + + return result + +def is_convex(f, *syms, domain=S.Reals): + r"""Determines the convexity of the function passed in the argument. + + Parameters + ========== + + f : :py:class:`~.Expr` + The concerned function. + syms : Tuple of :py:class:`~.Symbol` + The variables with respect to which the convexity is to be determined. + domain : :py:class:`~.Interval`, optional + The domain over which the convexity of the function has to be checked. + If unspecified, S.Reals will be the default domain. + + Returns + ======= + + bool + The method returns ``True`` if the function is convex otherwise it + returns ``False``. + + Raises + ====== + + NotImplementedError + The check for the convexity of multivariate functions is not implemented yet. + + Notes + ===== + + To determine concavity of a function pass `-f` as the concerned function. + To determine logarithmic convexity of a function pass `\log(f)` as + concerned function. + To determine logarithmic concavity of a function pass `-\log(f)` as + concerned function. + + Currently, convexity check of multivariate functions is not handled. + + Examples + ======== + + >>> from sympy import is_convex, symbols, exp, oo, Interval + >>> x = symbols('x') + >>> is_convex(exp(x), x) + True + >>> is_convex(x**3, x, domain = Interval(-1, oo)) + False + >>> is_convex(1/x**2, x, domain=Interval.open(0, oo)) + True + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Convex_function + .. [2] http://www.ifp.illinois.edu/~angelia/L3_convfunc.pdf + .. [3] https://en.wikipedia.org/wiki/Logarithmically_convex_function + .. [4] https://en.wikipedia.org/wiki/Logarithmically_concave_function + .. [5] https://en.wikipedia.org/wiki/Concave_function + + """ + if len(syms) > 1 : + return hessian(f, syms).is_positive_semidefinite + from sympy.solvers.inequalities import solve_univariate_inequality + f = _sympify(f) + var = syms[0] + if any(s in domain for s in singularities(f, var)): + return False + condition = f.diff(var, 2) < 0 + if solve_univariate_inequality(condition, var, False, domain): + return False + return True + + +def stationary_points(f, symbol, domain=S.Reals): + """ + Returns the stationary points of a function (where derivative of the + function is 0) in the given domain. + + Parameters + ========== + + f : :py:class:`~.Expr` + The concerned function. + symbol : :py:class:`~.Symbol` + The variable for which the stationary points are to be determined. + domain : :py:class:`~.Interval` + The domain over which the stationary points have to be checked. + If unspecified, ``S.Reals`` will be the default domain. + + Returns + ======= + + Set + A set of stationary points for the function. If there are no + stationary point, an :py:class:`~.EmptySet` is returned. + + Examples + ======== + + >>> from sympy import Interval, Symbol, S, sin, pi, pprint, stationary_points + >>> x = Symbol('x') + + >>> stationary_points(1/x, x, S.Reals) + EmptySet + + >>> pprint(stationary_points(sin(x), x), use_unicode=False) + pi 3*pi + {2*n*pi + -- | n in Integers} U {2*n*pi + ---- | n in Integers} + 2 2 + + >>> stationary_points(sin(x),x, Interval(0, 4*pi)) + {pi/2, 3*pi/2, 5*pi/2, 7*pi/2} + + """ + from sympy.solvers.solveset import solveset + + if domain is S.EmptySet: + return S.EmptySet + + domain = continuous_domain(f, symbol, domain) + set = solveset(diff(f, symbol), symbol, domain) + + return set + + +def maximum(f, symbol, domain=S.Reals): + """ + Returns the maximum value of a function in the given domain. + + Parameters + ========== + + f : :py:class:`~.Expr` + The concerned function. + symbol : :py:class:`~.Symbol` + The variable for maximum value needs to be determined. + domain : :py:class:`~.Interval` + The domain over which the maximum have to be checked. + If unspecified, then the global maximum is returned. + + Returns + ======= + + number + Maximum value of the function in given domain. + + Examples + ======== + + >>> from sympy import Interval, Symbol, S, sin, cos, pi, maximum + >>> x = Symbol('x') + + >>> f = -x**2 + 2*x + 5 + >>> maximum(f, x, S.Reals) + 6 + + >>> maximum(sin(x), x, Interval(-pi, pi/4)) + sqrt(2)/2 + + >>> maximum(sin(x)*cos(x), x) + 1/2 + + """ + if isinstance(symbol, Symbol): + if domain is S.EmptySet: + raise ValueError("Maximum value not defined for empty domain.") + + return function_range(f, symbol, domain).sup + else: + raise ValueError("%s is not a valid symbol." % symbol) + + +def minimum(f, symbol, domain=S.Reals): + """ + Returns the minimum value of a function in the given domain. + + Parameters + ========== + + f : :py:class:`~.Expr` + The concerned function. + symbol : :py:class:`~.Symbol` + The variable for minimum value needs to be determined. + domain : :py:class:`~.Interval` + The domain over which the minimum have to be checked. + If unspecified, then the global minimum is returned. + + Returns + ======= + + number + Minimum value of the function in the given domain. + + Examples + ======== + + >>> from sympy import Interval, Symbol, S, sin, cos, minimum + >>> x = Symbol('x') + + >>> f = x**2 + 2*x + 5 + >>> minimum(f, x, S.Reals) + 4 + + >>> minimum(sin(x), x, Interval(2, 3)) + sin(3) + + >>> minimum(sin(x)*cos(x), x) + -1/2 + + """ + if isinstance(symbol, Symbol): + if domain is S.EmptySet: + raise ValueError("Minimum value not defined for empty domain.") + + return function_range(f, symbol, domain).inf + else: + raise ValueError("%s is not a valid symbol." % symbol) diff --git a/.venv/lib/python3.12/site-packages/sympy/categories/__init__.py b/.venv/lib/python3.12/site-packages/sympy/categories/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4c5007308a1b232e57f9ed164276862df0c5f265 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/categories/__init__.py @@ -0,0 +1,33 @@ +""" +Category Theory module. + +Provides some of the fundamental category-theory-related classes, +including categories, morphisms, diagrams. Functors are not +implemented yet. + +The general reference work this module tries to follow is + + [JoyOfCats] J. Adamek, H. Herrlich. G. E. Strecker: Abstract and + Concrete Categories. The Joy of Cats. + +The latest version of this book should be available for free download +from + + katmat.math.uni-bremen.de/acc/acc.pdf + +""" + +from .baseclasses import (Object, Morphism, IdentityMorphism, + NamedMorphism, CompositeMorphism, Category, + Diagram) + +from .diagram_drawing import (DiagramGrid, XypicDiagramDrawer, + xypic_draw_diagram, preview_diagram) + +__all__ = [ + 'Object', 'Morphism', 'IdentityMorphism', 'NamedMorphism', + 'CompositeMorphism', 'Category', 'Diagram', + + 'DiagramGrid', 'XypicDiagramDrawer', 'xypic_draw_diagram', + 'preview_diagram', +] diff --git a/.venv/lib/python3.12/site-packages/sympy/categories/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/categories/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71034e0e25c832757e72eff5de28bbf428051dc4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/categories/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/categories/__pycache__/baseclasses.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/categories/__pycache__/baseclasses.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5a4b720105c9fc567b7005f8a0ecedb500454d86 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/categories/__pycache__/baseclasses.cpython-312.pyc differ
+

+ + + +

+ +
+ +[notebooks](https://github.com/roboflow/notebooks) | [inference](https://github.com/roboflow/inference) | [autodistill](https://github.com/autodistill/autodistill) | [maestro](https://github.com/roboflow/multimodal-maestro) + +
+ +[![version](https://badge.fury.io/py/supervision.svg)](https://badge.fury.io/py/supervision) [![downloads](https://img.shields.io/pypi/dm/supervision)](https://pypistats.org/packages/supervision) [![license](https://img.shields.io/pypi/l/supervision)](LICENSE.md) [![python-version](https://img.shields.io/pypi/pyversions/supervision)](https://badge.fury.io/py/supervision) [![codecov](https://codecov.io/gh/roboflow/supervision/graph/badge.svg?token=HMNJ5FVZ36)](https://codecov.io/gh/roboflow/supervision) + +[![Snyk Security](https://img.shields.io/badge/Snyk-Security-4C4A73?logo=snyk)](https://security.snyk.io/package/pip/supervision) [![colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/roboflow/supervision/blob/main/demo.ipynb) [![gradio](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue)](https://huggingface.co/spaces/Roboflow/Annotators) [![discord](https://img.shields.io/discord/1159501506232451173?logo=discord&label=discord&labelColor=fff&color=5865f2&link=https%3A%2F%2Fdiscord.gg%2FGbfgXGJ8Bk)](https://discord.gg/GbfgXGJ8Bk) + +
+ roboflow%2Fsupervision | Trendshift +
+ +